@studiometa/trafic-agent 0.1.21 → 0.1.22
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/dist/cli.js +3 -3
- package/dist/index.js +1 -1
- package/dist/setup/ddev.d.ts.map +1 -1
- package/dist/setup/migrations/0008__traefik_entrypoint_middleware.d.ts +21 -0
- package/dist/setup/migrations/0008__traefik_entrypoint_middleware.d.ts.map +1 -0
- package/dist/setup/migrations/index.d.ts.map +1 -1
- package/dist/{setup-BOYzFvil.js → setup-BB7Laws8.js} +105 -18
- package/dist/setup-BB7Laws8.js.map +1 -0
- package/dist/utils/config.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/setup-BOYzFvil.js.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { _ as validateConfig, c as info, d as success, f as warn, h as loadConfig, i as runPendingMigrations, l as isRoot, n as setup, p as startIdleScheduler, r as listMigrations, s as exec, t as audit, u as step } from "./setup-
|
|
2
|
+
import { _ as validateConfig, c as info, d as success, f as warn, h as loadConfig, i as runPendingMigrations, l as isRoot, n as setup, p as startIdleScheduler, r as listMigrations, s as exec, t as audit, u as step } from "./setup-BB7Laws8.js";
|
|
3
3
|
import { o as closeDb, t as startServer } from "./server-D6zlodZz.js";
|
|
4
4
|
import { readFileSync } from "node:fs";
|
|
5
5
|
import { execSync, spawnSync } from "node:child_process";
|
|
@@ -106,7 +106,7 @@ function runUpgrade(dryRun = false, reExecArgs) {
|
|
|
106
106
|
}
|
|
107
107
|
const alreadyReExeced = process.env["TRAFIC_UPGRADE_REEXEC"] === "1";
|
|
108
108
|
step("Check for updates");
|
|
109
|
-
const current = "0.1.
|
|
109
|
+
const current = "0.1.22";
|
|
110
110
|
info(`Current version: ${current}`);
|
|
111
111
|
const latest = fetchLatestVersion();
|
|
112
112
|
if (!latest) warn("Could not reach npm registry — skipping version check");
|
|
@@ -183,7 +183,7 @@ function printHelp() {
|
|
|
183
183
|
console.log(HELP.trim());
|
|
184
184
|
}
|
|
185
185
|
function printVersion() {
|
|
186
|
-
console.log("0.1.
|
|
186
|
+
console.log("0.1.22");
|
|
187
187
|
}
|
|
188
188
|
async function runStart(values) {
|
|
189
189
|
const config = loadConfig(values.config);
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { _ as validateConfig, a as printAuditResults, g as parseDuration, h as loadConfig, m as stopIdleProjects, n as setup, o as runAudit, p as startIdleScheduler, t as audit } from "./setup-
|
|
1
|
+
import { _ as validateConfig, a as printAuditResults, g as parseDuration, h as loadConfig, m as stopIdleProjects, n as setup, o as runAudit, p as startIdleScheduler, t as audit } from "./setup-BB7Laws8.js";
|
|
2
2
|
import { C as checkAuth, D as parseBearerToken, E as parseBasicAuth, S as watchProjectList, T as matchIp, _ as getProjectInfo, a as cleanOldLogs, b as startProject, c as getDb, d as initDb, f as logAccess, g as getProjectFromHostname, h as buildHostnameIndex, i as shouldNeverStop, l as getIdleProjects, m as updateProjectAccess, n as getIdleTimeoutMs, o as closeDb, p as setProjectStatus, r as loadProjectConfig, s as getAccessLogs, t as startServer, u as getProject, v as listProjects, w as matchHostname, x as stopProject, y as loadProjectList } from "./server-D6zlodZz.js";
|
|
3
3
|
export { audit, buildHostnameIndex, checkAuth, cleanOldLogs, closeDb, getAccessLogs, getDb, getIdleProjects, getIdleTimeoutMs, getProject, getProjectFromHostname, getProjectInfo, initDb, listProjects, loadConfig, loadProjectConfig, loadProjectList, logAccess, matchHostname, matchIp, parseBasicAuth, parseBearerToken, parseDuration, printAuditResults, runAudit, setProjectStatus, setup, shouldNeverStop, startIdleScheduler, startProject, startServer, stopIdleProjects, stopProject, updateProjectAccess, validateConfig, watchProjectList };
|
package/dist/setup/ddev.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ddev.d.ts","sourceRoot":"","sources":["../../src/setup/ddev.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,wBAAgB,iBAAiB,IAAI,IAAI,CAOxC;AAED;;;GAGG;AACH,wBAAgB,cAAc,IAAI,IAAI,CAWrC;AAED;;GAEG;AACH,wBAAgB,WAAW,IAAI,IAAI,CA2BlC;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAsB/D;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAsChD;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAc3C;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,IAAI,
|
|
1
|
+
{"version":3,"file":"ddev.d.ts","sourceRoot":"","sources":["../../src/setup/ddev.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,wBAAgB,iBAAiB,IAAI,IAAI,CAOxC;AAED;;;GAGG;AACH,wBAAgB,cAAc,IAAI,IAAI,CAWrC;AAED;;GAEG;AACH,wBAAgB,WAAW,IAAI,IAAI,CA2BlC;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAsB/D;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAsChD;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAc3C;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,IAAI,CAkEvC"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Migration } from "../types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Migration 0008: Switch Traefik from catch-all router to entry point middleware.
|
|
4
|
+
*
|
|
5
|
+
* The previous approach used a low-priority catch-all router (priority=1) with
|
|
6
|
+
* trafic-auth middleware in dynamic.yaml. This failed because DDEV's project-specific
|
|
7
|
+
* routers always win — they have higher priority and no trafic-auth middleware.
|
|
8
|
+
*
|
|
9
|
+
* The correct approach (from the previous trafic v1 with DDEV 1.24) is to attach
|
|
10
|
+
* the middleware at the entry point level via a static_config.*.yaml file that DDEV
|
|
11
|
+
* merges into .static_config.yaml on every start. This ensures every request on
|
|
12
|
+
* http-80 and http-443 passes through auth regardless of which router handles it.
|
|
13
|
+
*
|
|
14
|
+
* Changes:
|
|
15
|
+
* - Write static_config.trafic.yaml: attaches trafic-auth@file + trafic-errors@file
|
|
16
|
+
* to the http-80 and http-443 entry points
|
|
17
|
+
* - Write trafic.yaml to custom-global-config/ (survives DDEV 1.25+ config purge)
|
|
18
|
+
* - Remove the old dynamic.yaml catch-all router
|
|
19
|
+
*/
|
|
20
|
+
export declare const migration0008TraefikEntrypointMiddleware: Migration;
|
|
21
|
+
//# sourceMappingURL=0008__traefik_entrypoint_middleware.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"0008__traefik_entrypoint_middleware.d.ts","sourceRoot":"","sources":["../../../src/setup/migrations/0008__traefik_entrypoint_middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,wCAAwC,EAAE,SAkEtD,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/setup/migrations/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/setup/migrations/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAUjF,iDAAiD;AACjD,eAAO,MAAM,qBAAqB,iCAAiC,CAAC;AAEpE,+CAA+C;AAC/C,eAAO,MAAM,cAAc,EAAE,SAAS,EASrC,CAAC;AAMF;;;GAGG;AACH,wBAAgB,kBAAkB,IAAI,cAAc,CAqBnD;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI,CAG9D;AAMD;;GAEG;AACH,wBAAgB,cAAc,IAAI,kBAAkB,EAAE,CAMrD;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,UAAQ,GAAG,IAAI,CAyBzD;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,IAAI,IAAI,CAU/C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { _ as getProjectInfo, i as shouldNeverStop, l as getIdleProjects, n as getIdleTimeoutMs, p as setProjectStatus, r as loadProjectConfig, x as stopProject, y as loadProjectList } from "./server-D6zlodZz.js";
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { parse } from "smol-toml";
|
|
4
4
|
import { execSync } from "node:child_process";
|
|
5
5
|
var DEFAULT_CONFIG_PATHS = [
|
|
@@ -57,6 +57,21 @@ function loadConfig(configPath) {
|
|
|
57
57
|
auth
|
|
58
58
|
};
|
|
59
59
|
}
|
|
60
|
+
/**
|
|
61
|
+
* Parse basic_auth entries from TOML.
|
|
62
|
+
* Accepts either plain strings ("user:pass") or objects ({username, password}).
|
|
63
|
+
*/
|
|
64
|
+
function parseBasicAuthEntries(raw) {
|
|
65
|
+
if (!Array.isArray(raw)) return null;
|
|
66
|
+
return raw.map((entry) => {
|
|
67
|
+
if (typeof entry === "string") return entry;
|
|
68
|
+
if (typeof entry === "object" && entry !== null) {
|
|
69
|
+
const { username, password } = entry;
|
|
70
|
+
return `${username}:${password}`;
|
|
71
|
+
}
|
|
72
|
+
return String(entry);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
60
75
|
function mergeAuthConfig(raw) {
|
|
61
76
|
if (!raw) return DEFAULT_CONFIG.auth;
|
|
62
77
|
const rules = raw.rules ?? [];
|
|
@@ -64,7 +79,7 @@ function mergeAuthConfig(raw) {
|
|
|
64
79
|
defaultPolicy: raw.default_policy ?? DEFAULT_CONFIG.auth.defaultPolicy,
|
|
65
80
|
allowedIps: raw.allowed_ips ?? DEFAULT_CONFIG.auth.allowedIps,
|
|
66
81
|
tokens: raw.tokens ?? DEFAULT_CONFIG.auth.tokens,
|
|
67
|
-
basicAuth: raw.basic_auth ?? DEFAULT_CONFIG.auth.basicAuth,
|
|
82
|
+
basicAuth: parseBasicAuthEntries(raw.basic_auth) ?? DEFAULT_CONFIG.auth.basicAuth,
|
|
68
83
|
rules: rules.map((r) => ({
|
|
69
84
|
match: r.match,
|
|
70
85
|
policy: r.policy,
|
|
@@ -384,10 +399,10 @@ function getDockerGatewayIp() {
|
|
|
384
399
|
*/
|
|
385
400
|
function configureTraefik() {
|
|
386
401
|
step("Configure Traefik for forward auth");
|
|
387
|
-
exec("mkdir -p /home/ddev/.ddev/traefik", { silent: true });
|
|
402
|
+
exec("mkdir -p /home/ddev/.ddev/traefik/custom-global-config", { silent: true });
|
|
388
403
|
exec("chown -R ddev:ddev /home/ddev/.ddev", { silent: true });
|
|
389
404
|
const gatewayIp = getDockerGatewayIp();
|
|
390
|
-
|
|
405
|
+
const dynamicConfig = `# Trafic: Forward auth middleware definition
|
|
391
406
|
http:
|
|
392
407
|
middlewares:
|
|
393
408
|
trafic-auth:
|
|
@@ -409,21 +424,24 @@ http:
|
|
|
409
424
|
loadBalancer:
|
|
410
425
|
servers:
|
|
411
426
|
- url: "http://${gatewayIp}:9876"
|
|
412
|
-
|
|
427
|
+
`;
|
|
428
|
+
writeFileSync("/home/ddev/.ddev/traefik/trafic.yaml", dynamicConfig);
|
|
413
429
|
exec("chown ddev:ddev /home/ddev/.ddev/traefik/trafic.yaml", { silent: true });
|
|
414
|
-
writeFileSync("/home/ddev/.ddev/traefik/
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
430
|
+
writeFileSync("/home/ddev/.ddev/traefik/custom-global-config/trafic.yaml", dynamicConfig);
|
|
431
|
+
exec("chown ddev:ddev /home/ddev/.ddev/traefik/custom-global-config/trafic.yaml", { silent: true });
|
|
432
|
+
writeFileSync("/home/ddev/.ddev/traefik/static_config.trafic.yaml", `entryPoints:
|
|
433
|
+
http-80:
|
|
434
|
+
http:
|
|
435
|
+
middlewares:
|
|
436
|
+
- trafic-auth@file
|
|
437
|
+
- trafic-errors@file
|
|
438
|
+
http-443:
|
|
439
|
+
http:
|
|
421
440
|
middlewares:
|
|
422
|
-
- trafic-auth
|
|
423
|
-
- trafic-errors
|
|
424
|
-
service: api@internal
|
|
441
|
+
- trafic-auth@file
|
|
442
|
+
- trafic-errors@file
|
|
425
443
|
`);
|
|
426
|
-
exec("chown ddev:ddev /home/ddev/.ddev/traefik/
|
|
444
|
+
exec("chown ddev:ddev /home/ddev/.ddev/traefik/static_config.trafic.yaml", { silent: true });
|
|
427
445
|
success("Traefik configured with Trafic middleware");
|
|
428
446
|
}
|
|
429
447
|
/**
|
|
@@ -1049,6 +1067,74 @@ const migration0007UfwDockerTraficPort = {
|
|
|
1049
1067
|
exec("ufw allow from 172.16.0.0/12 to any port 9876 comment 'trafic-agent from Docker'", { silent: true });
|
|
1050
1068
|
}
|
|
1051
1069
|
};
|
|
1070
|
+
/**
|
|
1071
|
+
* Migration 0008: Switch Traefik from catch-all router to entry point middleware.
|
|
1072
|
+
*
|
|
1073
|
+
* The previous approach used a low-priority catch-all router (priority=1) with
|
|
1074
|
+
* trafic-auth middleware in dynamic.yaml. This failed because DDEV's project-specific
|
|
1075
|
+
* routers always win — they have higher priority and no trafic-auth middleware.
|
|
1076
|
+
*
|
|
1077
|
+
* The correct approach (from the previous trafic v1 with DDEV 1.24) is to attach
|
|
1078
|
+
* the middleware at the entry point level via a static_config.*.yaml file that DDEV
|
|
1079
|
+
* merges into .static_config.yaml on every start. This ensures every request on
|
|
1080
|
+
* http-80 and http-443 passes through auth regardless of which router handles it.
|
|
1081
|
+
*
|
|
1082
|
+
* Changes:
|
|
1083
|
+
* - Write static_config.trafic.yaml: attaches trafic-auth@file + trafic-errors@file
|
|
1084
|
+
* to the http-80 and http-443 entry points
|
|
1085
|
+
* - Write trafic.yaml to custom-global-config/ (survives DDEV 1.25+ config purge)
|
|
1086
|
+
* - Remove the old dynamic.yaml catch-all router
|
|
1087
|
+
*/
|
|
1088
|
+
const migration0008TraefikEntrypointMiddleware = {
|
|
1089
|
+
id: "0008__traefik_entrypoint_middleware",
|
|
1090
|
+
description: "Switch Traefik auth from catch-all router to entry point middleware",
|
|
1091
|
+
run() {
|
|
1092
|
+
const gatewayIp = getDockerGatewayIp();
|
|
1093
|
+
const dynamicConfig = `# Trafic: Forward auth middleware definition
|
|
1094
|
+
http:
|
|
1095
|
+
middlewares:
|
|
1096
|
+
trafic-auth:
|
|
1097
|
+
forwardAuth:
|
|
1098
|
+
address: "http://${gatewayIp}:9876/__auth__"
|
|
1099
|
+
authResponseHeaders:
|
|
1100
|
+
- "X-Trafic-Project"
|
|
1101
|
+
|
|
1102
|
+
trafic-errors:
|
|
1103
|
+
errors:
|
|
1104
|
+
status:
|
|
1105
|
+
- "502"
|
|
1106
|
+
- "503"
|
|
1107
|
+
service: trafic-service
|
|
1108
|
+
query: "/"
|
|
1109
|
+
|
|
1110
|
+
services:
|
|
1111
|
+
trafic-service:
|
|
1112
|
+
loadBalancer:
|
|
1113
|
+
servers:
|
|
1114
|
+
- url: "http://${gatewayIp}:9876"
|
|
1115
|
+
`;
|
|
1116
|
+
exec("mkdir -p /home/ddev/.ddev/traefik/custom-global-config", { silent: true });
|
|
1117
|
+
writeFileSync("/home/ddev/.ddev/traefik/trafic.yaml", dynamicConfig);
|
|
1118
|
+
writeFileSync("/home/ddev/.ddev/traefik/custom-global-config/trafic.yaml", dynamicConfig);
|
|
1119
|
+
exec("chown -R ddev:ddev /home/ddev/.ddev/traefik", { silent: true });
|
|
1120
|
+
writeFileSync("/home/ddev/.ddev/traefik/static_config.trafic.yaml", `entryPoints:
|
|
1121
|
+
http-80:
|
|
1122
|
+
http:
|
|
1123
|
+
middlewares:
|
|
1124
|
+
- trafic-auth@file
|
|
1125
|
+
- trafic-errors@file
|
|
1126
|
+
http-443:
|
|
1127
|
+
http:
|
|
1128
|
+
middlewares:
|
|
1129
|
+
- trafic-auth@file
|
|
1130
|
+
- trafic-errors@file
|
|
1131
|
+
`);
|
|
1132
|
+
exec("chown ddev:ddev /home/ddev/.ddev/traefik/static_config.trafic.yaml", { silent: true });
|
|
1133
|
+
const oldDynamicYaml = "/home/ddev/.ddev/traefik/dynamic.yaml";
|
|
1134
|
+
if (existsSync(oldDynamicYaml)) rmSync(oldDynamicYaml);
|
|
1135
|
+
exec("su - ddev -c 'DDEV_NONINTERACTIVE=true ddev poweroff && ddev start --all'", { silent: false });
|
|
1136
|
+
}
|
|
1137
|
+
};
|
|
1052
1138
|
/** Path to the persisted migration state file */
|
|
1053
1139
|
const MIGRATIONS_STATE_FILE = "/etc/trafic/.migrations.json";
|
|
1054
1140
|
/** Ordered registry of all known migrations */
|
|
@@ -1059,7 +1145,8 @@ const ALL_MIGRATIONS = [
|
|
|
1059
1145
|
migration0004DdevHostnameSudoers,
|
|
1060
1146
|
migration0005TraefikGatewayIp,
|
|
1061
1147
|
migration0006TraefikGatewayIpFix,
|
|
1062
|
-
migration0007UfwDockerTraficPort
|
|
1148
|
+
migration0007UfwDockerTraficPort,
|
|
1149
|
+
migration0008TraefikEntrypointMiddleware
|
|
1063
1150
|
];
|
|
1064
1151
|
/**
|
|
1065
1152
|
* Load the current migration state from disk.
|
|
@@ -1196,4 +1283,4 @@ async function audit() {
|
|
|
1196
1283
|
}
|
|
1197
1284
|
export { validateConfig as _, printAuditResults as a, info as c, success as d, warn as f, parseDuration as g, loadConfig as h, runPendingMigrations as i, isRoot as l, stopIdleProjects as m, setup as n, runAudit as o, startIdleScheduler as p, listMigrations as r, exec as s, audit as t, step as u };
|
|
1198
1285
|
|
|
1199
|
-
//# sourceMappingURL=setup-
|
|
1286
|
+
//# sourceMappingURL=setup-BB7Laws8.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"setup-BB7Laws8.js","names":[],"sources":["../src/utils/config.ts","../src/tasks/stop-idle.ts","../src/setup/steps.ts","../src/setup/user.ts","../src/setup/docker.ts","../src/setup/ddev.ts","../src/setup/agent.ts","../src/setup/hardening.ts","../src/setup/audit.ts","../src/setup/migrations/0001__ddev_apt_repo.ts","../src/setup/migrations/0002__mkcert_ddev_user.ts","../src/setup/migrations/0003__ddev_router_bind_all_interfaces.ts","../src/setup/migrations/0004__ddev_hostname_sudoers.ts","../src/setup/migrations/0005__traefik_gateway_ip.ts","../src/setup/migrations/0006__traefik_gateway_ip_fix.ts","../src/setup/migrations/0007__ufw_docker_trafic_port.ts","../src/setup/migrations/0008__traefik_entrypoint_middleware.ts","../src/setup/migrations/index.ts","../src/setup/index.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"node:fs\";\nimport { parse } from \"smol-toml\";\nimport type { AgentConfig, AuthConfig, AuthRule } from \"../types.js\";\n\nconst DEFAULT_CONFIG_PATHS = [\n \"/etc/trafic/config.toml\",\n \"./config.toml\",\n \"./trafic.toml\",\n];\n\nconst DEFAULT_CONFIG: AgentConfig = {\n tld: \"\",\n port: 9876,\n dbPath: \"/var/lib/trafic/db.sqlite\",\n projectListPath: \"/home/ddev/.ddev/project_list.yaml\",\n projectsDir: \"/home/ddev/www\",\n idleTimeout: \"30m\",\n idleCheckInterval: \"5m\",\n auth: {\n defaultPolicy: \"basic\",\n allowedIps: [],\n tokens: [],\n basicAuth: [],\n rules: [],\n },\n};\n\n/**\n * Parse a duration string (e.g., \"30m\", \"1h\", \"2h30m\") to milliseconds\n */\nexport function parseDuration(duration: string): number {\n const regex = /(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?/;\n const match = duration.match(regex);\n if (!match) return 0;\n\n const hours = parseInt(match[1] ?? \"0\", 10);\n const minutes = parseInt(match[2] ?? \"0\", 10);\n const seconds = parseInt(match[3] ?? \"0\", 10);\n\n return (hours * 3600 + minutes * 60 + seconds) * 1000;\n}\n\n/**\n * Load configuration from TOML file\n */\nexport function loadConfig(configPath?: string): AgentConfig {\n // Find config file\n let path = configPath;\n if (!path) {\n path = DEFAULT_CONFIG_PATHS.find((p) => existsSync(p));\n }\n\n if (!path || !existsSync(path)) {\n console.warn(\"No config file found, using defaults\");\n return DEFAULT_CONFIG;\n }\n\n const content = readFileSync(path, \"utf-8\");\n const parsed = parse(content) as Record<string, unknown>;\n\n // Merge with defaults\n const auth = mergeAuthConfig(parsed.auth as Record<string, unknown>);\n\n return {\n tld: (parsed.tld as string) ?? DEFAULT_CONFIG.tld,\n port: (parsed.port as number) ?? DEFAULT_CONFIG.port,\n dbPath: (parsed.db_path as string) ?? DEFAULT_CONFIG.dbPath,\n projectListPath:\n (parsed.project_list_path as string) ?? DEFAULT_CONFIG.projectListPath,\n projectsDir: (parsed.projects_dir as string) ?? DEFAULT_CONFIG.projectsDir,\n idleTimeout:\n (parsed.idle_timeout as string) ?? DEFAULT_CONFIG.idleTimeout,\n idleCheckInterval:\n (parsed.idle_check_interval as string) ??\n DEFAULT_CONFIG.idleCheckInterval,\n auth,\n };\n}\n\n/**\n * Parse basic_auth entries from TOML.\n * Accepts either plain strings (\"user:pass\") or objects ({username, password}).\n */\nfunction parseBasicAuthEntries(raw: unknown): string[] | null {\n if (!Array.isArray(raw)) return null;\n return raw.map((entry) => {\n if (typeof entry === \"string\") return entry;\n if (typeof entry === \"object\" && entry !== null) {\n const { username, password } = entry as Record<string, unknown>;\n return `${username}:${password}`;\n }\n return String(entry);\n });\n}\n\nfunction mergeAuthConfig(raw?: Record<string, unknown>): AuthConfig {\n if (!raw) return DEFAULT_CONFIG.auth;\n\n const rules = (raw.rules as Array<Record<string, unknown>>) ?? [];\n\n return {\n defaultPolicy:\n (raw.default_policy as AuthConfig[\"defaultPolicy\"]) ??\n DEFAULT_CONFIG.auth.defaultPolicy,\n allowedIps:\n (raw.allowed_ips as string[]) ?? DEFAULT_CONFIG.auth.allowedIps,\n tokens: (raw.tokens as string[]) ?? DEFAULT_CONFIG.auth.tokens,\n basicAuth: parseBasicAuthEntries(raw.basic_auth) ?? DEFAULT_CONFIG.auth.basicAuth,\n rules: rules.map(\n (r): AuthRule => ({\n match: r.match as string,\n policy: r.policy as AuthRule[\"policy\"],\n tokens: r.tokens as string[] | undefined,\n allowedIps: r.allowed_ips as string[] | undefined,\n }),\n ),\n };\n}\n\n/**\n * Validate configuration\n */\nexport function validateConfig(config: AgentConfig): string[] {\n const errors: string[] = [];\n\n if (!config.tld) {\n errors.push(\"tld is required\");\n }\n\n if (config.port < 1 || config.port > 65535) {\n errors.push(\"port must be between 1 and 65535\");\n }\n\n if (\n config.auth.defaultPolicy !== \"allow\" &&\n config.auth.defaultPolicy !== \"deny\" &&\n config.auth.defaultPolicy !== \"basic\" &&\n config.auth.defaultPolicy !== \"token\"\n ) {\n errors.push('auth.default_policy must be \"allow\", \"deny\", \"basic\", or \"token\"');\n }\n\n return errors;\n}\n","import { getIdleProjects, setProjectStatus } from \"../utils/db.js\";\nimport { stopProject, getProjectInfo, loadProjectList } from \"../utils/ddev.js\";\nimport { parseDuration } from \"../utils/config.js\";\nimport { loadProjectConfig, shouldNeverStop, getIdleTimeoutMs } from \"../utils/project-config.js\";\nimport type { AgentConfig } from \"../types.js\";\n\n/**\n * Stop idle projects that haven't been accessed recently\n * Respects per-project idle_timeout settings from .ddev/config.trafic.yaml\n */\nexport function stopIdleProjects(config: AgentConfig): void {\n const globalThresholdMs = parseDuration(config.idleTimeout);\n\n // Get all projects to check their individual configs\n const projects = loadProjectList(config.projectListPath);\n\n // Get projects idle according to global threshold\n const idleProjects = getIdleProjects(globalThresholdMs);\n\n for (const project of idleProjects) {\n const projectDir = projects.get(project.name);\n\n // Load per-project config if available\n if (projectDir) {\n const projectConfig = loadProjectConfig(projectDir);\n\n // Skip if project is configured to never stop\n if (shouldNeverStop(projectConfig)) {\n continue;\n }\n\n // Check project-specific idle timeout\n const projectThresholdMs = getIdleTimeoutMs(projectConfig);\n if (projectThresholdMs !== undefined) {\n const idleDuration = Date.now() - project.lastAccess;\n if (idleDuration < projectThresholdMs) {\n // Not idle according to project-specific timeout\n continue;\n }\n }\n }\n\n // Double-check project is actually running via DDEV\n const info = getProjectInfo(project.name);\n if (info?.status !== \"running\") {\n // Already stopped, just update our record\n setProjectStatus(project.name, \"stopped\");\n continue;\n }\n\n console.log(`Stopping idle project: ${project.name}`);\n const success = stopProject(project.name);\n\n if (success) {\n setProjectStatus(project.name, \"stopped\");\n console.log(`Stopped: ${project.name}`);\n } else {\n console.error(`Failed to stop: ${project.name}`);\n }\n }\n}\n\n/**\n * Start the idle check scheduler\n */\nexport function startIdleScheduler(config: AgentConfig): NodeJS.Timeout {\n const intervalMs = parseDuration(config.idleCheckInterval);\n\n console.log(\n `Idle scheduler started: checking every ${config.idleCheckInterval}, timeout ${config.idleTimeout}`,\n );\n\n // Run immediately on start\n stopIdleProjects(config);\n\n // Then run on interval\n return setInterval(() => {\n stopIdleProjects(config);\n }, intervalMs);\n}\n","import { execSync } from \"node:child_process\";\nimport { writeFileSync as fsWriteFile } from \"node:fs\";\n\nlet stepNumber = 0;\nlet dryRun = false;\n\n/**\n * Set dry-run mode\n */\nexport function setDryRun(value: boolean): void {\n dryRun = value;\n}\n\n/**\n * Reset step counter\n */\nexport function resetSteps(): void {\n stepNumber = 0;\n}\n\n/**\n * Log a step\n */\nexport function step(message: string): void {\n stepNumber++;\n console.log(`\\n\\x1b[36m[${stepNumber}]\\x1b[0m ${message}`);\n}\n\n/**\n * Log success\n */\nexport function success(message: string): void {\n console.log(` \\x1b[32m✓\\x1b[0m ${message}`);\n}\n\n/**\n * Log warning\n */\nexport function warn(message: string): void {\n console.log(` \\x1b[33m⚠\\x1b[0m ${message}`);\n}\n\n/**\n * Log error\n */\nexport function error(message: string): void {\n console.log(` \\x1b[31m✗\\x1b[0m ${message}`);\n}\n\n/**\n * Log info\n */\nexport function info(message: string): void {\n console.log(` ${message}`);\n}\n\n/**\n * Execute a command (or show in dry-run mode)\n */\nexport function exec(command: string, options?: { silent?: boolean }): string {\n if (dryRun) {\n if (!options?.silent) {\n console.log(` \\x1b[90m$ ${command}\\x1b[0m`);\n }\n return \"\";\n }\n\n try {\n return execSync(command, {\n encoding: \"utf-8\",\n stdio: options?.silent ? \"pipe\" : \"inherit\",\n });\n } catch (err) {\n const e = err as { status?: number; stderr?: string };\n throw new Error(`Command failed: ${command}\\n${e.stderr ?? \"\"}`);\n }\n}\n\n/**\n * Execute a command and return output (silent)\n */\nexport function execSilent(command: string): string {\n if (dryRun) {\n return \"\";\n }\n\n try {\n return execSync(command, {\n encoding: \"utf-8\",\n stdio: \"pipe\",\n }).trim();\n } catch {\n return \"\";\n }\n}\n\n/**\n * Check if a command exists\n */\nexport function commandExists(command: string): boolean {\n try {\n execSync(`which ${command}`, { stdio: \"pipe\" });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if running as root\n */\nexport function isRoot(): boolean {\n return process.getuid?.() === 0;\n}\n\n/**\n * Write a file (or show in dry-run mode)\n */\nexport function writeFile(path: string, content: string): void {\n if (dryRun) {\n console.log(` \\x1b[90mWrite ${path}:\\x1b[0m`);\n const lines = content.split(\"\\n\").slice(0, 5);\n for (const line of lines) {\n console.log(` \\x1b[90m ${line}\\x1b[0m`);\n }\n if (content.split(\"\\n\").length > 5) {\n console.log(` \\x1b[90m ...\\x1b[0m`);\n }\n return;\n }\n\n fsWriteFile(path, content);\n}\n","import { writeFileSync } from \"node:fs\";\nimport { step, success, info, exec, execSilent, warn } from \"./steps.js\";\n\n/**\n * Write /etc/sudoers.d/trafic-ddev allowing the ddev user to run\n * ddev-hostname without a password. Idempotent — safe to call multiple times.\n */\nexport function configureDdevSudoers(): void {\n const sudoersContent = `# Trafic: allow ddev user to run ddev-hostname without a password.\n# ddev-hostname manages /etc/hosts and always calls sudo internally.\nddev ALL=(ALL) NOPASSWD: /usr/bin/ddev-hostname\n`;\n writeFileSync(\"/etc/sudoers.d/trafic-ddev\", sudoersContent);\n exec(\"chmod 440 /etc/sudoers.d/trafic-ddev\", { silent: true });\n success(\"Configured passwordless sudo for ddev-hostname\");\n}\n\n/**\n * Create the ddev user with proper permissions\n */\nexport function createDdevUser(): void {\n step(\"Create ddev user\");\n\n // Check if user exists\n const userExists = execSilent(\"id -u ddev 2>/dev/null\");\n if (userExists) {\n info(\"User 'ddev' already exists\");\n } else {\n exec(\"useradd -m -s /bin/bash ddev\");\n success(\"Created user 'ddev'\");\n }\n\n // Add to docker group (will be created by Docker install)\n exec(\"usermod -aG docker ddev 2>/dev/null || true\", { silent: true });\n\n // Create www directory\n exec(\"mkdir -p /home/ddev/www\");\n exec(\"chown ddev:ddev /home/ddev/www\");\n exec(\"chmod 750 /home/ddev/www\");\n success(\"Created /home/ddev/www\");\n\n // Create .ssh directory if needed\n exec(\"mkdir -p /home/ddev/.ssh\");\n exec(\"chmod 700 /home/ddev/.ssh\");\n exec(\"chown ddev:ddev /home/ddev/.ssh\");\n\n // Allow ddev user to run ddev-hostname without a password.\n // ddev-hostname manages /etc/hosts entries and always calls sudo internally,\n // even when DDEV_NONINTERACTIVE=true. Without this rule, any ddev command\n // that touches hostname resolution (start, restart, poweroff + start) will\n // fail with \"sudo: a terminal is required to read the password\".\n configureDdevSudoers();\n success(\"User ddev configured\");\n}\n\n/**\n * Setup authorized_keys for ddev user\n */\nexport function setupAuthorizedKeys(publicKey?: string): void {\n if (!publicKey) {\n warn(\"No SSH public key provided, skipping authorized_keys setup\");\n return;\n }\n\n step(\"Setup SSH authorized_keys\");\n\n const authKeysPath = \"/home/ddev/.ssh/authorized_keys\";\n exec(`touch ${authKeysPath}`);\n exec(`chmod 600 ${authKeysPath}`);\n exec(`chown ddev:ddev ${authKeysPath}`);\n\n // Check if key already exists\n const existing = execSilent(`cat ${authKeysPath}`);\n if (existing.includes(publicKey.trim())) {\n info(\"SSH key already authorized\");\n } else {\n exec(`echo '${publicKey}' >> ${authKeysPath}`);\n success(\"Added SSH public key\");\n }\n}\n","import { writeFileSync, existsSync, readFileSync } from \"node:fs\";\nimport { step, success, info, exec, commandExists, warn } from \"./steps.js\";\n\n/**\n * Install Docker using the official script\n */\nexport function installDocker(): void {\n step(\"Install Docker\");\n\n if (commandExists(\"docker\")) {\n const version = exec(\"docker --version\", { silent: true });\n info(`Docker already installed: ${version?.trim() ?? \"unknown version\"}`);\n return;\n }\n\n // Install Docker using official script\n info(\"Downloading and running Docker install script...\");\n exec(\"curl -fsSL https://get.docker.com -o /tmp/get-docker.sh\");\n exec(\"sh /tmp/get-docker.sh\", { silent: true });\n exec(\"rm /tmp/get-docker.sh\");\n\n // Enable and start Docker\n exec(\"systemctl enable docker\", { silent: true });\n exec(\"systemctl start docker\", { silent: true });\n\n success(\"Docker installed and started\");\n\n // Add ddev user to docker group\n exec(\"usermod -aG docker ddev\", { silent: true });\n success(\"Added ddev user to docker group\");\n}\n\n/**\n * Configure Docker for production use\n */\nexport function configureDocker(): void {\n step(\"Configure Docker\");\n\n // Create daemon.json with production settings\n const daemonConfig = {\n \"log-driver\": \"json-file\",\n \"log-opts\": {\n \"max-size\": \"10m\",\n \"max-file\": \"3\",\n },\n \"storage-driver\": \"overlay2\",\n \"live-restore\": true,\n };\n\n exec(\"mkdir -p /etc/docker\");\n\n const configPath = \"/etc/docker/daemon.json\";\n\n // Check if config already exists\n if (existsSync(configPath)) {\n try {\n const existing = JSON.parse(readFileSync(configPath, \"utf-8\"));\n // Merge with existing config\n const merged = { ...existing, ...daemonConfig };\n writeFileSync(configPath, JSON.stringify(merged, null, 2));\n info(\"Merged with existing Docker config\");\n } catch {\n warn(\"Could not parse existing Docker config, skipping\");\n return;\n }\n } else {\n writeFileSync(configPath, JSON.stringify(daemonConfig, null, 2));\n }\n\n // Reload Docker to apply config\n exec(\"systemctl reload docker || systemctl restart docker\");\n success(\"Docker configured with production settings\");\n}\n\n/**\n * Setup Docker system prune cron job\n */\nexport function setupDockerPrune(): void {\n step(\"Setup Docker cleanup cron\");\n\n const cronContent = `# Trafic: Clean up Docker resources weekly\n0 3 * * 0 root docker system prune -af --volumes 2>&1 | logger -t docker-prune\n`;\n\n writeFileSync(\"/etc/cron.d/trafic-docker-prune\", cronContent);\n exec(\"chmod 644 /etc/cron.d/trafic-docker-prune\");\n\n success(\"Docker prune scheduled weekly at 3am on Sundays\");\n}\n","import { writeFileSync } from \"node:fs\";\nimport { step, success, info, exec, commandExists } from \"./steps.js\";\n\n/**\n * Install system dependencies required by Trafic\n */\nexport function installSystemDeps(): void {\n step(\"Install system dependencies\");\n\n exec(\"apt-get update -qq\", { silent: true });\n exec(\"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y jq curl rsync\", { silent: true });\n\n success(\"System dependencies installed: jq, curl, rsync\");\n}\n\n/**\n * Add the official DDEV apt repository and GPG key.\n * Idempotent: safe to call even if the repository is already configured.\n */\nexport function addDdevAptRepo(): void {\n exec(\"install -m 0755 -d /etc/apt/keyrings\", { silent: true });\n exec(\n \"curl -fsSL https://pkg.ddev.com/apt/gpg.key | gpg --dearmor | tee /etc/apt/keyrings/ddev.gpg > /dev/null\",\n { silent: true },\n );\n exec(\"chmod a+r /etc/apt/keyrings/ddev.gpg\", { silent: true });\n exec(\n \"echo \\\"deb [signed-by=/etc/apt/keyrings/ddev.gpg] https://pkg.ddev.com/apt/ * *\\\" | tee /etc/apt/sources.list.d/ddev.list > /dev/null\",\n { silent: true },\n );\n}\n\n/**\n * Install DDEV\n */\nexport function installDdev(): void {\n step(\"Install DDEV\");\n\n if (commandExists(\"ddev\")) {\n const version = exec(\"ddev --version 2>/dev/null | head -1\", { silent: true });\n info(`DDEV already installed: ${version?.trim() ?? \"unknown version\"}`);\n return;\n }\n\n // Install DDEV via the official apt repository\n // See https://docs.ddev.com/en/stable/users/install/ddev-installation/#debianubuntu\n info(\"Adding DDEV apt repository...\");\n addDdevAptRepo();\n\n info(\"Installing DDEV...\");\n exec(\"apt-get update -qq\", { silent: true });\n exec(\"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y ddev\", { silent: true });\n\n // Initialize mkcert certificate authority for the ddev user.\n // mkcert installs the CA into the home directory of the current user.\n // Since setup runs as root, we must point HOME to the ddev user's home\n // so the CA is trusted by DDEV when it runs as that user.\n exec(\"HOME=/home/ddev mkcert -install\", { silent: true });\n exec(\"chown -R ddev:ddev /home/ddev/.local/share/mkcert\", { silent: true });\n\n const version = exec(\"ddev --version 2>/dev/null | head -1\", { silent: true });\n success(`DDEV installed: ${version?.trim() ?? \"unknown version\"}`);\n}\n\n/**\n * Configure DDEV global settings for production\n *\n * Note on DNS and /etc/hosts:\n * When using a custom TLD (not ddev.site), DDEV may try to edit /etc/hosts\n * if it can't resolve project hostnames via DNS. To avoid this:\n * 1. Configure DNS so *.{tld} resolves to the server's IP (recommended)\n * 2. Or install dnsmasq for local wildcard DNS resolution\n *\n * With proper DNS, DDEV won't need sudo for hostname management.\n */\nexport function configureDdev(tld: string, email?: string): void {\n step(\"Configure DDEV\");\n\n // Run as ddev user\n const ddevCmd = (cmd: string) => `su - ddev -c '${cmd}'`;\n\n // Configure all global settings in a single call\n exec(\n ddevCmd(\n `ddev config global --project-tld=${tld} --router-http-port=80 --router-https-port=443 --router-bind-all-interfaces=true --use-letsencrypt=${email ? \"true\" : \"false\"} ${email ? `--letsencrypt-email=${email}` : \"\"} --instrumentation-opt-in=false`,\n ),\n { silent: true },\n );\n\n success(`DDEV configured with TLD: ${tld}`);\n info(`Ensure DNS is configured: *.${tld} → server IP`);\n\n if (email) {\n success(`Let's Encrypt enabled with email: ${email}`);\n }\n\n success(\"DDEV global settings configured\");\n}\n\n/**\n * Install dnsmasq for local DNS resolution (optional)\n * This allows the server itself to resolve *.{tld} hostnames\n * without needing to edit /etc/hosts for each project\n */\nexport function installDnsmasq(tld: string): void {\n step(\"Install dnsmasq for local DNS\");\n\n exec(\"apt-get update && apt-get install -y dnsmasq\", { silent: true });\n\n // Get server's public IP\n const serverIp = exec(\n \"curl -4 -s ifconfig.me || hostname -I | awk '{print $1}'\",\n { silent: true },\n )?.trim() || \"127.0.0.1\";\n\n // Configure dnsmasq to resolve *.{tld} to server IP\n const dnsmasqConfig = `# Trafic: Local DNS for DDEV projects\n# Resolve all *.${tld} to this server\naddress=/${tld}/${serverIp}\n\n# Don't read /etc/resolv.conf\nno-resolv\n\n# Use upstream DNS for everything else\nserver=1.1.1.1\nserver=8.8.8.8\n\n# Listen on localhost only\nlisten-address=127.0.0.1\nbind-interfaces\n`;\n\n writeFileSync(\"/etc/dnsmasq.d/trafic.conf\", dnsmasqConfig);\n\n // Configure system to use local dnsmasq\n exec(\"systemctl restart dnsmasq\");\n exec(\"systemctl enable dnsmasq\");\n\n // Update resolv.conf to use local DNS first\n info(\"Configure /etc/resolv.conf to use 127.0.0.1 as primary DNS\");\n\n success(`dnsmasq configured: *.${tld} → ${serverIp}`);\n}\n\n/**\n * Get the Docker gateway IP reachable from inside DDEV containers on Linux.\n * DDEV runs containers on the `ddev_default` network — we inspect that first.\n * Falls back to the default `bridge` network, then to 172.17.0.1.\n * `host.docker.internal` is not available on Linux without extra configuration.\n */\nexport function getDockerGatewayIp(): string {\n // Prefer the ddev_default network gateway — that's the network ddev-router is on\n const ddevIp = exec(\n \"docker network inspect ddev_default --format '{{range .IPAM.Config}}{{.Gateway}}{{end}}' 2>/dev/null\",\n { silent: true },\n )?.trim();\n if (ddevIp) return ddevIp;\n\n // Fall back to the default bridge network\n const bridgeIp = exec(\n \"docker network inspect bridge --format '{{range .IPAM.Config}}{{.Gateway}}{{end}}' 2>/dev/null\",\n { silent: true },\n )?.trim();\n return bridgeIp || \"172.17.0.1\";\n}\n\n/**\n * Configure Traefik for forward auth\n */\nexport function configureTraefik(): void {\n step(\"Configure Traefik for forward auth\");\n\n // Create custom Traefik config directories\n exec(\"mkdir -p /home/ddev/.ddev/traefik/custom-global-config\", { silent: true });\n exec(\"chown -R ddev:ddev /home/ddev/.ddev\", { silent: true });\n\n // Use the Docker bridge gateway IP instead of host.docker.internal —\n // the latter is not available on Linux without extra Docker configuration.\n const gatewayIp = getDockerGatewayIp();\n\n // Dynamic configuration: defines the trafic-auth and trafic-errors middlewares\n // and the trafic-service backend pointing at the agent.\n // Written to:\n // - custom-global-config/ — picked up by DDEV 1.25+ (survives config dir purge on restart)\n // - traefik root — also watched by older DDEV versions\n const dynamicConfig = `# Trafic: Forward auth middleware definition\nhttp:\n middlewares:\n trafic-auth:\n forwardAuth:\n address: \"http://${gatewayIp}:9876/__auth__\"\n authResponseHeaders:\n - \"X-Trafic-Project\"\n\n trafic-errors:\n errors:\n status:\n - \"502\"\n - \"503\"\n service: trafic-service\n query: \"/\"\n\n services:\n trafic-service:\n loadBalancer:\n servers:\n - url: \"http://${gatewayIp}:9876\"\n`;\n\n writeFileSync(\"/home/ddev/.ddev/traefik/trafic.yaml\", dynamicConfig);\n exec(\"chown ddev:ddev /home/ddev/.ddev/traefik/trafic.yaml\", { silent: true });\n writeFileSync(\"/home/ddev/.ddev/traefik/custom-global-config/trafic.yaml\", dynamicConfig);\n exec(\"chown ddev:ddev /home/ddev/.ddev/traefik/custom-global-config/trafic.yaml\", { silent: true });\n\n // Static configuration: attaches trafic-auth and trafic-errors to the\n // http-80 and http-443 entry points so every request goes through auth —\n // regardless of which project router handles it.\n // DDEV merges all static_config.*.yaml files into .static_config.yaml on start.\n const staticConfig = `entryPoints:\n http-80:\n http:\n middlewares:\n - trafic-auth@file\n - trafic-errors@file\n http-443:\n http:\n middlewares:\n - trafic-auth@file\n - trafic-errors@file\n`;\n\n writeFileSync(\"/home/ddev/.ddev/traefik/static_config.trafic.yaml\", staticConfig);\n exec(\"chown ddev:ddev /home/ddev/.ddev/traefik/static_config.trafic.yaml\", { silent: true });\n\n success(\"Traefik configured with Trafic middleware\");\n}\n","import { step, success, info, exec, commandExists } from \"./steps.js\";\nimport { writeFileSync, existsSync } from \"node:fs\";\n\n/**\n * Install Node.js using fnm\n */\nexport function installNode(): void {\n step(\"Install Node.js\");\n\n // Check if Node is already installed\n if (commandExists(\"node\")) {\n const version = exec(\"node --version\", { silent: true });\n info(`Node.js already installed: ${version?.trim()}`);\n return;\n }\n\n // Install fnm (Fast Node Manager)\n exec(\n 'curl -fsSL https://fnm.vercel.app/install | bash -s -- --install-dir \"/opt/fnm\" --skip-shell',\n );\n\n // Add fnm to system path\n const profileContent = `# Trafic: fnm (Node.js version manager)\nexport FNM_DIR=\"/opt/fnm\"\nexport PATH=\"/opt/fnm:$PATH\"\neval \"$(fnm env)\"\n`;\n\n writeFileSync(\"/etc/profile.d/fnm.sh\", profileContent);\n exec(\"chmod 644 /etc/profile.d/fnm.sh\");\n\n // Install Node.js 24\n exec(\"export FNM_DIR=/opt/fnm && /opt/fnm/fnm install 24\");\n exec(\"export FNM_DIR=/opt/fnm && /opt/fnm/fnm default 24\");\n\n // Create symlinks for system-wide access\n exec(\n \"ln -sf /opt/fnm/aliases/default/bin/node /usr/local/bin/node || true\",\n );\n exec(\"ln -sf /opt/fnm/aliases/default/bin/npm /usr/local/bin/npm || true\");\n exec(\"ln -sf /opt/fnm/aliases/default/bin/npx /usr/local/bin/npx || true\");\n\n success(\"Node.js 24 installed via fnm\");\n}\n\n/**\n * Install the Trafic agent\n */\nexport function installAgent(): void {\n step(\"Install Trafic agent\");\n\n // Install the agent globally\n exec(\"npm install -g @studiometa/trafic-agent\");\n\n success(\"Trafic agent installed\");\n}\n\n/**\n * Create the agent configuration\n */\nexport function createAgentConfig(tld: string, _email?: string): void {\n step(\"Create agent configuration\");\n\n // Create directories\n exec(\"mkdir -p /etc/trafic\");\n exec(\"mkdir -p /var/lib/trafic\");\n exec(\"chown ddev:ddev /var/lib/trafic\");\n\n const configPath = \"/etc/trafic/config.toml\";\n\n if (existsSync(configPath)) {\n info(\"Configuration already exists at /etc/trafic/config.toml — skipping\");\n info(\"Edit this file to configure authentication\");\n return;\n }\n\n const config = `# Trafic agent configuration\n# Generated by trafic setup\n\n# Required: TLD for DDEV projects\ntld = \"${tld}\"\n\n# Agent HTTP server port\nport = 9876\n\n# Database and paths\ndb_path = \"/var/lib/trafic/db.sqlite\"\nproject_list_path = \"/home/ddev/.ddev/project_list.yaml\"\nprojects_dir = \"/home/ddev/www\"\n\n# Scale-to-zero settings\nidle_timeout = \"4h\"\nidle_check_interval = \"5m\"\n\n# Authentication\n[auth]\ndefault_policy = \"basic\"\nallowed_ips = []\ntokens = []\nbasic_auth = []\nrules = []\n`;\n\n writeFileSync(configPath, config);\n exec(\"chmod 640 /etc/trafic/config.toml\");\n exec(\"chown root:ddev /etc/trafic/config.toml\");\n\n success(\"Configuration created at /etc/trafic/config.toml\");\n info(\"Edit this file to configure authentication\");\n}\n\n/**\n * Create systemd service for the agent\n */\nexport function createSystemdService(): void {\n step(\"Create systemd service\");\n\n // Find the trafic-agent binary path\n const agentPath = exec(\"which trafic-agent\", { silent: true })?.trim() || \"/usr/bin/trafic-agent\";\n\n const serviceContent = `[Unit]\nDescription=Trafic Agent - DDEV preview environment manager\nAfter=network.target docker.service\nRequires=docker.service\n\n[Service]\nType=simple\nUser=ddev\nGroup=ddev\nExecStart=${agentPath} start --config /etc/trafic/config.toml\nRestart=always\nRestartSec=5\nStandardOutput=journal\nStandardError=journal\nSyslogIdentifier=trafic-agent\n\n# Environment\nEnvironment=NODE_ENV=production\n# Skip ddev-hostname /etc/hosts management — on a server, hostnames resolve\n# to the public IP (not localhost), which would trigger ddev-hostname on every\n# ddev start. DDEV_NONINTERACTIVE=true skips that entirely.\nEnvironment=DDEV_NONINTERACTIVE=true\n\n# Security hardening\nNoNewPrivileges=true\nProtectSystem=strict\nProtectHome=read-only\nReadWritePaths=/var/lib/trafic /home/ddev/.ddev\nPrivateTmp=true\n\n[Install]\nWantedBy=multi-user.target\n`;\n\n writeFileSync(\"/etc/systemd/system/trafic-agent.service\", serviceContent);\n exec(\"chmod 644 /etc/systemd/system/trafic-agent.service\");\n\n // Reload systemd and enable service\n exec(\"systemctl daemon-reload\");\n exec(\"systemctl enable trafic-agent\");\n exec(\"systemctl start trafic-agent\");\n\n success(\"Trafic agent service started\");\n info(\"View logs: journalctl -u trafic-agent -f\");\n}\n","import { step, success, info, exec, warn, commandExists } from \"./steps.js\";\nimport { writeFileSync, existsSync } from \"node:fs\";\n\n/**\n * Configure SSH hardening\n */\nexport function hardenSsh(allowedUsers: string[] = [\"ddev\"]): void {\n step(\"Harden SSH configuration\");\n\n const sshConfig = `# Trafic SSH hardening\n# Generated by trafic setup\n\n# Allow root login via SSH key only (no password) — required for server management\nPermitRootLogin prohibit-password\n\n# Disable password authentication (keys only)\nPasswordAuthentication no\nPubkeyAuthentication yes\n\n# Limit authentication attempts\nMaxAuthTries 3\n\n# Idle timeout (5 minutes)\nClientAliveInterval 300\nClientAliveCountMax 2\n\n# Allowed users (root kept for emergency access)\nAllowUsers root ${allowedUsers.join(\" \")}\n\n# Disable X11 forwarding\nX11Forwarding no\n\n# Disable TCP forwarding\nAllowTcpForwarding no\n\n# Use strong algorithms only\nKexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256\nCiphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com\nMACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com\n`;\n\n writeFileSync(\"/etc/ssh/sshd_config.d/trafic.conf\", sshConfig);\n exec(\"chmod 644 /etc/ssh/sshd_config.d/trafic.conf\");\n\n // Test config before restarting\n const testResult = exec(\"sshd -t 2>&1 || echo 'error'\", { silent: true });\n if (testResult?.includes(\"error\")) {\n warn(\"SSH config test failed, reverting...\");\n exec(\"rm /etc/ssh/sshd_config.d/trafic.conf\");\n return;\n }\n\n exec(\"systemctl reload ssh || systemctl reload sshd\");\n success(\"SSH hardened: password auth disabled, root key-only login retained\");\n info(`Allowed users: root, ${allowedUsers.join(\", \")}`);\n}\n\n/**\n * Configure UFW firewall\n */\nexport function configureFirewall(): void {\n step(\"Configure firewall (UFW)\");\n\n // Install UFW if not present\n if (!commandExists(\"ufw\")) {\n exec(\"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y ufw\", { silent: true });\n }\n\n // Reset and configure\n exec(\"ufw --force reset\", { silent: true });\n exec(\"ufw default deny incoming\");\n exec(\"ufw default allow outgoing\");\n exec(\"ufw allow 22/tcp comment 'SSH'\");\n exec(\"ufw allow 80/tcp comment 'HTTP'\");\n exec(\"ufw allow 443/tcp comment 'HTTPS'\");\n // Allow trafic-agent port from Docker bridge subnets so ddev-router can\n // reach the forward-auth endpoint. Docker typically uses 172.16.0.0/12.\n exec(\"ufw allow from 172.16.0.0/12 to any port 9876 comment 'trafic-agent from Docker'\");\n\n // Enable firewall\n exec(\"ufw --force enable\");\n\n success(\"Firewall enabled: SSH (22), HTTP (80), HTTPS (443), trafic-agent (9876 from Docker) allowed\");\n}\n\n/**\n * Configure automatic security updates\n */\nexport function configureUnattendedUpgrades(): void {\n step(\"Configure automatic security updates\");\n\n // Install unattended-upgrades\n exec(\n \"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y unattended-upgrades apt-listchanges\",\n { silent: true },\n );\n\n // Configure for security updates only\n const upgradesConfig = `// Trafic: Automatic security updates\nUnattended-Upgrade::Allowed-Origins {\n \"\\${distro_id}:\\${distro_codename}\";\n \"\\${distro_id}:\\${distro_codename}-security\";\n \"\\${distro_id}ESMApps:\\${distro_codename}-apps-security\";\n \"\\${distro_id}ESM:\\${distro_codename}-infra-security\";\n};\n\n// Do not automatically reboot\nUnattended-Upgrade::Automatic-Reboot \"false\";\n\n// Remove unused dependencies\nUnattended-Upgrade::Remove-Unused-Dependencies \"true\";\n\n// Email notifications (optional)\n// Unattended-Upgrade::Mail \"root\";\n`;\n\n writeFileSync(\n \"/etc/apt/apt.conf.d/50unattended-upgrades\",\n upgradesConfig,\n );\n\n // Enable automatic updates\n const autoConfig = `APT::Periodic::Update-Package-Lists \"1\";\nAPT::Periodic::Download-Upgradeable-Packages \"1\";\nAPT::Periodic::AutocleanInterval \"7\";\nAPT::Periodic::Unattended-Upgrade \"1\";\n`;\n\n writeFileSync(\"/etc/apt/apt.conf.d/20auto-upgrades\", autoConfig);\n\n // Enable the service\n exec(\"systemctl enable unattended-upgrades\");\n exec(\"systemctl start unattended-upgrades\");\n\n success(\"Automatic security updates enabled\");\n}\n\n/**\n * Configure Fail2ban\n */\nexport function configureFail2ban(): void {\n step(\"Configure Fail2ban\");\n\n // Install fail2ban\n if (!commandExists(\"fail2ban-client\")) {\n exec(\"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y fail2ban\", { silent: true });\n }\n\n // Configure jail\n const jailConfig = `# Trafic: Fail2ban configuration\n[DEFAULT]\nbantime = 3600\nfindtime = 600\nmaxretry = 5\nbackend = auto\n\n[sshd]\nenabled = true\nport = ssh\nfilter = sshd\nlogpath = /var/log/auth.log\nmaxretry = 3\nbantime = 7200\n`;\n\n writeFileSync(\"/etc/fail2ban/jail.local\", jailConfig);\n exec(\"chmod 644 /etc/fail2ban/jail.local\");\n\n // Restart fail2ban\n exec(\"systemctl enable fail2ban\");\n exec(\"systemctl restart fail2ban\");\n\n success(\"Fail2ban enabled: SSH brute force protection active\");\n}\n\n/**\n * Configure system limits\n */\nexport function configureSystemLimits(): void {\n step(\"Configure system limits\");\n\n const limitsConfig = `# Trafic: System limits for ddev user\nddev soft nofile 65536\nddev hard nofile 65536\nddev soft nproc 4096\nddev hard nproc 4096\n`;\n\n writeFileSync(\"/etc/security/limits.d/trafic.conf\", limitsConfig);\n exec(\"chmod 644 /etc/security/limits.d/trafic.conf\");\n\n success(\"System limits configured for ddev user\");\n}\n\n/**\n * Set proper file permissions\n */\nexport function configureFilePermissions(): void {\n step(\"Configure file permissions\");\n\n // Create directories\n exec(\"mkdir -p /etc/trafic\");\n exec(\"mkdir -p /var/lib/trafic\");\n exec(\"mkdir -p /var/backups/trafic\");\n\n // Set permissions\n exec(\"chmod 755 /etc/trafic\");\n exec(\"chmod 700 /var/lib/trafic\");\n exec(\"chmod 700 /var/backups/trafic\");\n exec(\"chown root:ddev /etc/trafic\");\n exec(\"chown ddev:ddev /var/lib/trafic\");\n exec(\"chown ddev:ddev /var/backups/trafic\");\n\n // Config file (if exists)\n if (existsSync(\"/etc/trafic/config.toml\")) {\n exec(\"chmod 640 /etc/trafic/config.toml\");\n exec(\"chown root:ddev /etc/trafic/config.toml\");\n }\n\n success(\"File permissions configured\");\n}\n\n/**\n * Run all hardening steps\n */\nexport function hardenServer(sshUsers: string[] = [\"ddev\"]): void {\n hardenSsh(sshUsers);\n configureFirewall();\n configureUnattendedUpgrades();\n configureFail2ban();\n configureSystemLimits();\n configureFilePermissions();\n}\n","import { execSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { AuditCheck } from \"./types.js\";\n\n/**\n * Run a command silently and return output\n */\nfunction execSilent(command: string): string {\n try {\n return execSync(command, { encoding: \"utf-8\", stdio: \"pipe\" }).trim();\n } catch {\n return \"\";\n }\n}\n\n/**\n * Check if a service is active\n */\nfunction isServiceActive(service: string): boolean {\n const status = execSilent(`systemctl is-active ${service}`);\n return status === \"active\";\n}\n\n/**\n * Audit SSH configuration\n */\nfunction auditSsh(): AuditCheck[] {\n const checks: AuditCheck[] = [];\n\n // Check root login\n const sshdConfig = existsSync(\"/etc/ssh/sshd_config\")\n ? readFileSync(\"/etc/ssh/sshd_config\", \"utf-8\")\n : \"\";\n const traficConfig = existsSync(\"/etc/ssh/sshd_config.d/trafic.conf\")\n ? readFileSync(\"/etc/ssh/sshd_config.d/trafic.conf\", \"utf-8\")\n : \"\";\n\n const config = sshdConfig + \"\\n\" + traficConfig;\n\n const rootLoginDisabled =\n config.includes(\"PermitRootLogin no\") ||\n config.includes(\"PermitRootLogin prohibit-password\");\n checks.push({\n name: \"SSH root login\",\n status: rootLoginDisabled ? \"pass\" : \"fail\",\n message: rootLoginDisabled\n ? \"Root login disabled\"\n : \"Root login may be enabled\",\n fix: \"Add 'PermitRootLogin no' to /etc/ssh/sshd_config.d/trafic.conf\",\n });\n\n const passwordAuthDisabled = config.includes(\"PasswordAuthentication no\");\n checks.push({\n name: \"SSH password auth\",\n status: passwordAuthDisabled ? \"pass\" : \"warn\",\n message: passwordAuthDisabled\n ? \"Password authentication disabled\"\n : \"Password authentication may be enabled\",\n fix: \"Add 'PasswordAuthentication no' to /etc/ssh/sshd_config.d/trafic.conf\",\n });\n\n return checks;\n}\n\n/**\n * Audit firewall configuration\n */\nfunction auditFirewall(): AuditCheck[] {\n const checks: AuditCheck[] = [];\n\n const ufwStatus = execSilent(\"ufw status\");\n const isActive = ufwStatus.includes(\"Status: active\");\n\n checks.push({\n name: \"Firewall (UFW)\",\n status: isActive ? \"pass\" : \"fail\",\n message: isActive ? \"UFW is active\" : \"UFW is not active\",\n fix: \"Run: ufw enable\",\n });\n\n if (isActive) {\n const allows22 = ufwStatus.includes(\"22/tcp\");\n const allows80 = ufwStatus.includes(\"80/tcp\");\n const allows443 = ufwStatus.includes(\"443/tcp\");\n\n if (allows22 && allows80 && allows443) {\n checks.push({\n name: \"Firewall ports\",\n status: \"pass\",\n message: \"Required ports (22, 80, 443) are open\",\n });\n } else {\n checks.push({\n name: \"Firewall ports\",\n status: \"warn\",\n message: \"Some required ports may be blocked\",\n fix: \"Run: ufw allow 22/tcp && ufw allow 80/tcp && ufw allow 443/tcp\",\n });\n }\n }\n\n return checks;\n}\n\n/**\n * Audit security services\n */\nfunction auditServices(): AuditCheck[] {\n const checks: AuditCheck[] = [];\n\n // Fail2ban\n const fail2banActive = isServiceActive(\"fail2ban\");\n checks.push({\n name: \"Fail2ban\",\n status: fail2banActive ? \"pass\" : \"warn\",\n message: fail2banActive ? \"Fail2ban is active\" : \"Fail2ban is not running\",\n fix: \"Run: apt install fail2ban && systemctl enable fail2ban --now\",\n });\n\n // Unattended upgrades\n const unattendedActive = isServiceActive(\"unattended-upgrades\");\n checks.push({\n name: \"Automatic updates\",\n status: unattendedActive ? \"pass\" : \"warn\",\n message: unattendedActive\n ? \"Unattended upgrades enabled\"\n : \"Automatic updates not configured\",\n fix: \"Run: apt install unattended-upgrades && dpkg-reconfigure unattended-upgrades\",\n });\n\n // Trafic agent\n const agentActive = isServiceActive(\"trafic-agent\");\n checks.push({\n name: \"Trafic agent\",\n status: agentActive ? \"pass\" : \"fail\",\n message: agentActive\n ? \"Trafic agent is running\"\n : \"Trafic agent is not running\",\n fix: \"Run: systemctl start trafic-agent\",\n });\n\n return checks;\n}\n\n/**\n * Audit Docker\n */\nfunction auditDocker(): AuditCheck[] {\n const checks: AuditCheck[] = [];\n\n // Docker running\n const dockerActive = isServiceActive(\"docker\");\n checks.push({\n name: \"Docker\",\n status: dockerActive ? \"pass\" : \"fail\",\n message: dockerActive ? \"Docker is running\" : \"Docker is not running\",\n fix: \"Run: systemctl start docker\",\n });\n\n // Dangling images\n const danglingImages = execSilent(\n \"docker images -f dangling=true -q | wc -l\",\n );\n const count = parseInt(danglingImages, 10) || 0;\n if (count > 0) {\n checks.push({\n name: \"Docker cleanup\",\n status: \"warn\",\n message: `${count} dangling Docker images`,\n fix: \"Run: docker system prune -f\",\n });\n }\n\n // Disk usage\n const diskUsage = execSilent(\"df -h / | awk 'NR==2{print $5}'\");\n const usagePercent = parseInt(diskUsage, 10) || 0;\n checks.push({\n name: \"Disk usage\",\n status: usagePercent > 90 ? \"fail\" : usagePercent > 80 ? \"warn\" : \"pass\",\n message: `Disk usage: ${diskUsage}`,\n fix: usagePercent > 80 ? \"Consider cleaning up old projects or Docker resources\" : undefined,\n });\n\n return checks;\n}\n\n/**\n * Audit file permissions\n */\nfunction auditPermissions(): AuditCheck[] {\n const checks: AuditCheck[] = [];\n\n // Config file\n if (existsSync(\"/etc/trafic/config.toml\")) {\n const stats = execSilent(\"stat -c '%a' /etc/trafic/config.toml\");\n const isSecure = stats === \"640\" || stats === \"600\";\n checks.push({\n name: \"Config permissions\",\n status: isSecure ? \"pass\" : \"warn\",\n message: isSecure\n ? \"Config file has secure permissions\"\n : `Config file permissions: ${stats} (should be 640)`,\n fix: \"Run: chmod 640 /etc/trafic/config.toml\",\n });\n }\n\n // Projects directory\n if (existsSync(\"/home/ddev/www\")) {\n const owner = execSilent(\"stat -c '%U:%G' /home/ddev/www\");\n const isCorrect = owner === \"ddev:ddev\";\n checks.push({\n name: \"Projects directory\",\n status: isCorrect ? \"pass\" : \"warn\",\n message: isCorrect\n ? \"Projects directory owned by ddev\"\n : `Projects directory owner: ${owner}`,\n fix: \"Run: chown ddev:ddev /home/ddev/www\",\n });\n }\n\n return checks;\n}\n\n/**\n * Run all audit checks\n */\nexport function runAudit(): AuditCheck[] {\n return [\n ...auditSsh(),\n ...auditFirewall(),\n ...auditServices(),\n ...auditDocker(),\n ...auditPermissions(),\n ];\n}\n\n/**\n * Print audit results\n */\nexport function printAuditResults(checks: AuditCheck[]): void {\n console.log(\"\\n\\x1b[1mSecurity Audit Results\\x1b[0m\\n\");\n\n for (const check of checks) {\n const icon =\n check.status === \"pass\"\n ? \"\\x1b[32m✓\\x1b[0m\"\n : check.status === \"warn\"\n ? \"\\x1b[33m⚠\\x1b[0m\"\n : \"\\x1b[31m✗\\x1b[0m\";\n\n console.log(`${icon} \\x1b[1m${check.name}\\x1b[0m: ${check.message}`);\n\n if (check.fix && check.status !== \"pass\") {\n console.log(` \\x1b[90m${check.fix}\\x1b[0m`);\n }\n }\n\n const passed = checks.filter((c) => c.status === \"pass\").length;\n const warnings = checks.filter((c) => c.status === \"warn\").length;\n const failed = checks.filter((c) => c.status === \"fail\").length;\n\n console.log(\n `\\n\\x1b[1mSummary:\\x1b[0m ${passed} passed, ${warnings} warnings, ${failed} failed`,\n );\n}\n","import { existsSync } from \"node:fs\";\nimport { exec } from \"../steps.js\";\nimport { addDdevAptRepo } from \"../ddev.js\";\nimport type { Migration } from \"../types.js\";\n\n/**\n * Migration 0001: Migrate DDEV from manual tarball to apt repository.\n *\n * Old installs downloaded a tarball from GitHub releases. This migration\n * removes the manually-installed binaries and reinstalls DDEV via the\n * official apt repository so future updates are handled by apt.\n *\n * Condition: skip if /etc/apt/sources.list.d/ddev.list already exists,\n * which means the apt repository is already configured.\n */\nexport const migration0001DdevAptRepo: Migration = {\n id: \"0001__ddev_apt_repo\",\n description: \"Migrate DDEV from manual tarball to apt repository\",\n\n run(): void {\n // Already using the apt repository — nothing to do\n if (existsSync(\"/etc/apt/sources.list.d/ddev.list\")) {\n return;\n }\n\n // 1. Remove manually-installed DDEV binaries\n exec(\"rm -f /usr/local/bin/ddev /usr/local/bin/ddev-hostname /usr/local/bin/mkcert\", {\n silent: true,\n });\n\n // 2. Add the official DDEV apt repository\n addDdevAptRepo();\n\n // 3. Install DDEV via apt\n exec(\"apt-get update -qq\", { silent: true });\n exec(\"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y ddev\", {\n silent: true,\n });\n\n // 4. Re-install mkcert CA (mkcert is now bundled with DDEV via apt)\n exec(\"mkcert -install\", { silent: true });\n },\n};\n","import { existsSync } from \"node:fs\";\nimport { exec } from \"../steps.js\";\nimport type { Migration } from \"../types.js\";\n\n/**\n * Migration 0002: Install mkcert CA in the ddev user trust store.\n *\n * Previously, `mkcert -install` was called as root without overriding HOME,\n * so the CA was stored under ~root/.local/share/mkcert. DDEV runs as the\n * `ddev` user and looks for the CA in its own home directory — so it never\n * found it, reporting mkcert as not installed.\n *\n * Fix: run `mkcert -install` with HOME=/home/ddev so the CA lands in the\n * ddev user trust store, then chown the directory to ddev:ddev.\n *\n * Condition: skip if /home/ddev/.local/share/mkcert already exists,\n * which means the CA is already installed for the ddev user.\n */\nexport const migration0002MkcertDdevUser: Migration = {\n id: \"0002__mkcert_ddev_user\",\n description: \"Install mkcert CA in the ddev user trust store\",\n\n run(): void {\n // Already installed for the ddev user — nothing to do\n if (existsSync(\"/home/ddev/.local/share/mkcert\")) {\n return;\n }\n\n exec(\"HOME=/home/ddev mkcert -install\", { silent: true });\n exec(\"chown -R ddev:ddev /home/ddev/.local/share/mkcert\", { silent: true });\n },\n};\n","import { exec } from \"../steps.js\";\nimport type { Migration } from \"../types.js\";\n\n/**\n * Migration 0003: Enable router_bind_all_interfaces in DDEV global config.\n *\n * The initial setup did not set --router-bind-all-interfaces=true, which\n * caused ddev-router to bind only on 127.0.0.1. External traffic (including\n * Cloudflare proxying) could not reach the router, resulting in 521 errors.\n *\n * This migration enables the flag and restarts the DDEV router so the change\n * takes effect immediately.\n *\n * Idempotent: ddev config global is safe to re-run with the same value.\n */\nexport const migration0003DdevRouterBindAllInterfaces: Migration = {\n id: \"0003__ddev_router_bind_all_interfaces\",\n description: \"Bind ddev-router on all interfaces (fix 521 for external traffic)\",\n\n run(): void {\n exec(\"su - ddev -c 'ddev config global --router-bind-all-interfaces=true'\", { silent: true });\n // Restart all running projects so the router picks up the new bind setting\n exec(\"su - ddev -c 'ddev poweroff'\", { silent: true });\n exec(\"su - ddev -c 'ddev start --all'\", { silent: true });\n },\n};\n","import { existsSync } from \"node:fs\";\nimport { configureDdevSudoers } from \"../user.js\";\nimport type { Migration } from \"../types.js\";\n\n/**\n * Migration 0004: Allow ddev user to run ddev-hostname without a password.\n *\n * ddev-hostname manages /etc/hosts entries and always calls sudo internally,\n * even when DDEV_NONINTERACTIVE=true. Without this sudoers rule, any ddev\n * command that touches hostname resolution (start, restart, poweroff + start)\n * fails with \"sudo: a terminal is required to read the password\".\n *\n * Condition: skip if /etc/sudoers.d/trafic-ddev already exists.\n */\nexport const migration0004DdevHostnameSudoers: Migration = {\n id: \"0004__ddev_hostname_sudoers\",\n description: \"Allow ddev user to run ddev-hostname without a password\",\n\n run(): void {\n if (existsSync(\"/etc/sudoers.d/trafic-ddev\")) {\n return;\n }\n\n configureDdevSudoers();\n },\n};\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { getDockerGatewayIp } from \"../ddev.js\";\nimport type { Migration } from \"../types.js\";\n\nconst TRAFIC_YAML = \"/home/ddev/.ddev/traefik/trafic.yaml\";\n\n/**\n * Migration 0005: Replace host.docker.internal with the Docker bridge gateway IP\n * in the Traefik forward-auth config.\n *\n * host.docker.internal is a Docker Desktop / macOS feature and is not available\n * on Linux without explicit configuration. The Traefik router container cannot\n * resolve it, so forward-auth requests silently fail and all traffic bypasses\n * authentication.\n *\n * Fix: replace all occurrences of host.docker.internal in trafic.yaml with the\n * actual Docker bridge gateway IP (typically 172.17.0.1 or 172.18.0.1).\n *\n * Condition: skip if trafic.yaml doesn't exist or already uses an IP address.\n */\nexport const migration0005TraefikGatewayIp: Migration = {\n id: \"0005__traefik_gateway_ip\",\n description: \"Replace host.docker.internal with Docker bridge gateway IP in Traefik config\",\n\n run(): void {\n if (!existsSync(TRAFIC_YAML)) {\n return;\n }\n\n const content = readFileSync(TRAFIC_YAML, \"utf-8\");\n const gatewayIp = getDockerGatewayIp();\n\n // Replace host.docker.internal (original broken value) or any previously\n // written IP that no longer matches the current gateway (e.g. if the\n // migration ran before ddev_default existed and wrote 172.17.0.1 instead).\n const updated = content\n .replaceAll(\"host.docker.internal\", gatewayIp)\n .replace(/http:\\/\\/\\d+\\.\\d+\\.\\d+\\.\\d+:9876/g, `http://${gatewayIp}:9876`);\n\n if (updated === content) {\n return;\n }\n\n writeFileSync(TRAFIC_YAML, updated, \"utf-8\");\n },\n};\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { getDockerGatewayIp } from \"../ddev.js\";\nimport type { Migration } from \"../types.js\";\n\nconst TRAFIC_YAML = \"/home/ddev/.ddev/traefik/trafic.yaml\";\n\n/**\n * Migration 0006: Fix the Docker gateway IP in trafic.yaml.\n *\n * Migration 0005 inspected the default `bridge` network (172.17.0.1) instead\n * of the `ddev_default` network (typically 172.18.0.1) that ddev-router\n * actually runs on. This migration rewrites trafic.yaml with the correct IP.\n *\n * Idempotent: re-reads the file and only writes if the IP has changed.\n */\nexport const migration0006TraefikGatewayIpFix: Migration = {\n id: \"0006__traefik_gateway_ip_fix\",\n description: \"Fix Docker gateway IP in Traefik config (use ddev_default network)\",\n\n run(): void {\n if (!existsSync(TRAFIC_YAML)) {\n return;\n }\n\n const content = readFileSync(TRAFIC_YAML, \"utf-8\");\n const gatewayIp = getDockerGatewayIp();\n\n const updated = content.replace(\n /http:\\/\\/[\\w.]+:9876/g,\n `http://${gatewayIp}:9876`,\n );\n\n if (updated === content) {\n return;\n }\n\n writeFileSync(TRAFIC_YAML, updated, \"utf-8\");\n },\n};\n","import { exec, execSilent } from \"../steps.js\";\nimport type { Migration } from \"../types.js\";\n\n/**\n * Migration 0007: Allow trafic-agent port 9876 from Docker bridge subnets in UFW.\n *\n * UFW does not automatically allow traffic from Docker bridge networks.\n * Without this rule, ddev-router cannot reach the trafic-agent forward-auth\n * endpoint (172.18.0.1:9876), causing all auth checks to time out and traffic\n * to pass through unauthenticated.\n *\n * Condition: skip if the rule already exists.\n */\nexport const migration0007UfwDockerTraficPort: Migration = {\n id: \"0007__ufw_docker_trafic_port\",\n description: \"Allow trafic-agent port 9876 from Docker bridge subnets in UFW\",\n\n run(): void {\n const existing = execSilent(\"ufw status | grep '9876'\");\n if (existing.includes(\"9876\")) {\n return;\n }\n\n exec(\"ufw allow from 172.16.0.0/12 to any port 9876 comment 'trafic-agent from Docker'\", {\n silent: true,\n });\n },\n};\n","import { writeFileSync, rmSync, existsSync } from \"node:fs\";\nimport { exec } from \"../steps.js\";\nimport { getDockerGatewayIp } from \"../ddev.js\";\nimport type { Migration } from \"../types.js\";\n\n/**\n * Migration 0008: Switch Traefik from catch-all router to entry point middleware.\n *\n * The previous approach used a low-priority catch-all router (priority=1) with\n * trafic-auth middleware in dynamic.yaml. This failed because DDEV's project-specific\n * routers always win — they have higher priority and no trafic-auth middleware.\n *\n * The correct approach (from the previous trafic v1 with DDEV 1.24) is to attach\n * the middleware at the entry point level via a static_config.*.yaml file that DDEV\n * merges into .static_config.yaml on every start. This ensures every request on\n * http-80 and http-443 passes through auth regardless of which router handles it.\n *\n * Changes:\n * - Write static_config.trafic.yaml: attaches trafic-auth@file + trafic-errors@file\n * to the http-80 and http-443 entry points\n * - Write trafic.yaml to custom-global-config/ (survives DDEV 1.25+ config purge)\n * - Remove the old dynamic.yaml catch-all router\n */\nexport const migration0008TraefikEntrypointMiddleware: Migration = {\n id: \"0008__traefik_entrypoint_middleware\",\n description:\n \"Switch Traefik auth from catch-all router to entry point middleware\",\n\n run(): void {\n const gatewayIp = getDockerGatewayIp();\n\n // Dynamic config: middleware + service definitions\n const dynamicConfig = `# Trafic: Forward auth middleware definition\nhttp:\n middlewares:\n trafic-auth:\n forwardAuth:\n address: \"http://${gatewayIp}:9876/__auth__\"\n authResponseHeaders:\n - \"X-Trafic-Project\"\n\n trafic-errors:\n errors:\n status:\n - \"502\"\n - \"503\"\n service: trafic-service\n query: \"/\"\n\n services:\n trafic-service:\n loadBalancer:\n servers:\n - url: \"http://${gatewayIp}:9876\"\n`;\n\n exec(\"mkdir -p /home/ddev/.ddev/traefik/custom-global-config\", { silent: true });\n writeFileSync(\"/home/ddev/.ddev/traefik/trafic.yaml\", dynamicConfig);\n writeFileSync(\"/home/ddev/.ddev/traefik/custom-global-config/trafic.yaml\", dynamicConfig);\n exec(\"chown -R ddev:ddev /home/ddev/.ddev/traefik\", { silent: true });\n\n // Static config: attach middleware to entry points\n const staticConfig = `entryPoints:\n http-80:\n http:\n middlewares:\n - trafic-auth@file\n - trafic-errors@file\n http-443:\n http:\n middlewares:\n - trafic-auth@file\n - trafic-errors@file\n`;\n\n writeFileSync(\"/home/ddev/.ddev/traefik/static_config.trafic.yaml\", staticConfig);\n exec(\"chown ddev:ddev /home/ddev/.ddev/traefik/static_config.trafic.yaml\", { silent: true });\n\n // Remove the old catch-all router config — it's superseded by entry point middleware\n const oldDynamicYaml = \"/home/ddev/.ddev/traefik/dynamic.yaml\";\n if (existsSync(oldDynamicYaml)) {\n rmSync(oldDynamicYaml);\n }\n\n // Restart DDEV router to apply the new static config\n exec(\"su - ddev -c 'DDEV_NONINTERACTIVE=true ddev poweroff && ddev start --all'\", {\n silent: false,\n });\n },\n};\n","import { existsSync, readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport type { Migration, MigrationState, MigrationListEntry } from \"../types.js\";\nimport { migration0001DdevAptRepo } from \"./0001__ddev_apt_repo.js\";\nimport { migration0002MkcertDdevUser } from \"./0002__mkcert_ddev_user.js\";\nimport { migration0003DdevRouterBindAllInterfaces } from \"./0003__ddev_router_bind_all_interfaces.js\";\nimport { migration0004DdevHostnameSudoers } from \"./0004__ddev_hostname_sudoers.js\";\nimport { migration0005TraefikGatewayIp } from \"./0005__traefik_gateway_ip.js\";\nimport { migration0006TraefikGatewayIpFix } from \"./0006__traefik_gateway_ip_fix.js\";\nimport { migration0007UfwDockerTraficPort } from \"./0007__ufw_docker_trafic_port.js\";\nimport { migration0008TraefikEntrypointMiddleware } from \"./0008__traefik_entrypoint_middleware.js\";\n\n/** Path to the persisted migration state file */\nexport const MIGRATIONS_STATE_FILE = \"/etc/trafic/.migrations.json\";\n\n/** Ordered registry of all known migrations */\nexport const ALL_MIGRATIONS: Migration[] = [\n migration0001DdevAptRepo,\n migration0002MkcertDdevUser,\n migration0003DdevRouterBindAllInterfaces,\n migration0004DdevHostnameSudoers,\n migration0005TraefikGatewayIp,\n migration0006TraefikGatewayIpFix,\n migration0007UfwDockerTraficPort,\n migration0008TraefikEntrypointMiddleware,\n];\n\n// ---------------------------------------------------------------------------\n// State helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Load the current migration state from disk.\n * Returns an empty state if the file does not exist yet.\n */\nexport function loadMigrationState(): MigrationState {\n if (!existsSync(MIGRATIONS_STATE_FILE)) {\n return { applied: [] };\n }\n\n try {\n const raw = readFileSync(MIGRATIONS_STATE_FILE, \"utf-8\");\n const parsed = JSON.parse(raw) as unknown;\n if (\n parsed !== null &&\n typeof parsed === \"object\" &&\n \"applied\" in parsed &&\n Array.isArray((parsed as { applied: unknown }).applied)\n ) {\n return parsed as MigrationState;\n }\n } catch {\n // Corrupted file — start fresh\n }\n\n return { applied: [] };\n}\n\n/**\n * Persist the migration state to disk.\n * Creates /etc/trafic/ if it does not exist.\n */\nexport function saveMigrationState(state: MigrationState): void {\n mkdirSync(\"/etc/trafic\", { recursive: true });\n writeFileSync(MIGRATIONS_STATE_FILE, JSON.stringify(state, null, 2) + \"\\n\", \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Return all migrations with their current status.\n */\nexport function listMigrations(): MigrationListEntry[] {\n const state = loadMigrationState();\n return ALL_MIGRATIONS.map((migration) => ({\n migration,\n status: state.applied.includes(migration.id) ? \"applied\" : \"pending\",\n }));\n}\n\n/**\n * Run all pending migrations and persist state after each one.\n *\n * When `dryRun` is true the runner prints what it would do without\n * executing anything or touching the state file.\n */\nexport function runPendingMigrations(dryRun = false): void {\n const state = loadMigrationState();\n const pending = ALL_MIGRATIONS.filter((m) => !state.applied.includes(m.id));\n\n if (pending.length === 0) {\n console.log(\" No pending migrations.\");\n return;\n }\n\n for (const migration of pending) {\n console.log(`\\n → \\x1b[1m${migration.id}\\x1b[0m ${migration.description}`);\n\n if (dryRun) {\n console.log(` \\x1b[90m(dry-run: skipped)\\x1b[0m`);\n continue;\n }\n\n migration.run();\n\n // Persist state immediately so a partial failure leaves a consistent state\n state.applied.push(migration.id);\n saveMigrationState(state);\n\n console.log(` \\x1b[32m✓ Applied\\x1b[0m`);\n }\n}\n\n/**\n * Mark all known migrations as applied without running them.\n *\n * Called at the end of a fresh `setup()` run: a brand-new server has\n * already been configured correctly, so migrations that fix older\n * installations are not needed.\n */\nexport function markAllMigrationsApplied(): void {\n const state = loadMigrationState();\n\n for (const migration of ALL_MIGRATIONS) {\n if (!state.applied.includes(migration.id)) {\n state.applied.push(migration.id);\n }\n }\n\n saveMigrationState(state);\n}\n","import type { SetupOptions } from \"./types.js\";\nimport { step, info, error, setDryRun, resetSteps, isRoot } from \"./steps.js\";\nimport { createDdevUser } from \"./user.js\";\nimport { installDocker, configureDocker, setupDockerPrune } from \"./docker.js\";\nimport { installSystemDeps, installDdev, configureDdev, configureTraefik } from \"./ddev.js\";\nimport { installNode, installAgent, createAgentConfig, createSystemdService } from \"./agent.js\";\nimport { hardenServer } from \"./hardening.js\";\nimport { runAudit, printAuditResults } from \"./audit.js\";\nimport { markAllMigrationsApplied } from \"./migrations/index.js\";\n\nexport * from \"./types.js\";\nexport * from \"./audit.js\";\n\n/**\n * Run the full server setup\n */\nexport async function setup(options: SetupOptions): Promise<void> {\n resetSteps();\n setDryRun(options.dryRun ?? false);\n\n console.log(\"\\n\\x1b[1m🚦 Trafic Server Setup\\x1b[0m\\n\");\n\n if (options.dryRun) {\n console.log(\"\\x1b[33m⚠ Dry-run mode: no changes will be made\\x1b[0m\\n\");\n }\n\n // Check root\n if (!isRoot() && !options.dryRun) {\n error(\"This command must be run as root\");\n console.log(\" Run: sudo trafic-agent setup ...\");\n process.exit(1);\n }\n\n info(`TLD: ${options.tld}`);\n if (options.email) {\n info(`Let's Encrypt email: ${options.email}`);\n }\n if (options.noHardening) {\n info(\"Hardening: disabled\");\n }\n\n try {\n // Step 1: Install system dependencies\n installSystemDeps();\n\n // Step 2: Create ddev user\n createDdevUser();\n\n // Step 3: Install Docker\n if (!options.noDocker) {\n installDocker();\n configureDocker();\n setupDockerPrune();\n } else {\n step(\"Install Docker\");\n info(\"Skipped (--no-docker)\");\n }\n\n // Step 4: Install DDEV\n if (!options.noDdev) {\n installDdev();\n configureDdev(options.tld, options.email);\n configureTraefik();\n } else {\n step(\"Install DDEV\");\n info(\"Skipped (--no-ddev)\");\n }\n\n // Step 5: Install Node.js\n installNode();\n\n // Step 6: Install and configure agent\n installAgent();\n createAgentConfig(options.tld, options.email);\n createSystemdService();\n\n // Step 7: Server hardening\n if (!options.noHardening) {\n const sshUsers = options.sshUsers ?? [\"ddev\"];\n hardenServer(sshUsers);\n } else {\n step(\"Server hardening\");\n info(\"Skipped (--no-hardening)\");\n }\n\n // Mark all migrations as applied — fresh servers are already up-to-date\n markAllMigrationsApplied();\n\n // Done\n console.log(\"\\n\\x1b[32m✓ Setup complete!\\x1b[0m\\n\");\n console.log(\"Next steps:\");\n console.log(` 1. Edit /etc/trafic/config.toml to configure authentication`);\n console.log(` 2. Add SSH public keys to /home/ddev/.ssh/authorized_keys`);\n console.log(` 3. Deploy your first project:`);\n console.log(` npx @studiometa/trafic-cli deploy --host=<this-server> --name=my-app`);\n console.log(`\\nYour projects will be available at https://<name>.${options.tld}`);\n } catch (err) {\n error(`Setup failed: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n}\n\n/**\n * Run security audit\n */\nexport async function audit(): Promise<void> {\n const checks = runAudit();\n printAuditResults(checks);\n\n const failed = checks.filter((c) => c.status === \"fail\").length;\n if (failed > 0) {\n process.exit(1);\n }\n}\n"],"mappings":";;;;AAIA,IAAM,uBAAuB;CAC3B;CACA;CACA;CACD;AAED,IAAM,iBAA8B;CAClC,KAAK;CACL,MAAM;CACN,QAAQ;CACR,iBAAiB;CACjB,aAAa;CACb,aAAa;CACb,mBAAmB;CACnB,MAAM;EACJ,eAAe;EACf,YAAY,EAAE;EACd,QAAQ,EAAE;EACV,WAAW,EAAE;EACb,OAAO,EAAE;EACV;CACF;;;;AAKD,SAAgB,cAAc,UAA0B;CAEtD,MAAM,QAAQ,SAAS,MADT,oCACqB;AACnC,KAAI,CAAC,MAAO,QAAO;CAEnB,MAAM,QAAQ,SAAS,MAAM,MAAM,KAAK,GAAG;CAC3C,MAAM,UAAU,SAAS,MAAM,MAAM,KAAK,GAAG;CAC7C,MAAM,UAAU,SAAS,MAAM,MAAM,KAAK,GAAG;AAE7C,SAAQ,QAAQ,OAAO,UAAU,KAAK,WAAW;;;;;AAMn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;;;;AAOnB,eAAsB,QAAuB;CAC3C,MAAM,SAAS,UAAU;AACzB,mBAAkB,OAAO;AAGzB,KADe,OAAO,QAAQ,MAAM,EAAE,WAAW,OAAO,CAAC,SAC5C,EACX,SAAQ,KAAK,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/utils/config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAwB,MAAM,aAAa,CAAC;AAyBrE;;GAEG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAUtD;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,WAAW,CAgC3D;
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/utils/config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAwB,MAAM,aAAa,CAAC;AAyBrE;;GAEG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAUtD;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,WAAW,CAgC3D;AA0CD;;GAEG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,EAAE,CAqB5D"}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"setup-BOYzFvil.js","names":[],"sources":["../src/utils/config.ts","../src/tasks/stop-idle.ts","../src/setup/steps.ts","../src/setup/user.ts","../src/setup/docker.ts","../src/setup/ddev.ts","../src/setup/agent.ts","../src/setup/hardening.ts","../src/setup/audit.ts","../src/setup/migrations/0001__ddev_apt_repo.ts","../src/setup/migrations/0002__mkcert_ddev_user.ts","../src/setup/migrations/0003__ddev_router_bind_all_interfaces.ts","../src/setup/migrations/0004__ddev_hostname_sudoers.ts","../src/setup/migrations/0005__traefik_gateway_ip.ts","../src/setup/migrations/0006__traefik_gateway_ip_fix.ts","../src/setup/migrations/0007__ufw_docker_trafic_port.ts","../src/setup/migrations/index.ts","../src/setup/index.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"node:fs\";\nimport { parse } from \"smol-toml\";\nimport type { AgentConfig, AuthConfig, AuthRule } from \"../types.js\";\n\nconst DEFAULT_CONFIG_PATHS = [\n \"/etc/trafic/config.toml\",\n \"./config.toml\",\n \"./trafic.toml\",\n];\n\nconst DEFAULT_CONFIG: AgentConfig = {\n tld: \"\",\n port: 9876,\n dbPath: \"/var/lib/trafic/db.sqlite\",\n projectListPath: \"/home/ddev/.ddev/project_list.yaml\",\n projectsDir: \"/home/ddev/www\",\n idleTimeout: \"30m\",\n idleCheckInterval: \"5m\",\n auth: {\n defaultPolicy: \"basic\",\n allowedIps: [],\n tokens: [],\n basicAuth: [],\n rules: [],\n },\n};\n\n/**\n * Parse a duration string (e.g., \"30m\", \"1h\", \"2h30m\") to milliseconds\n */\nexport function parseDuration(duration: string): number {\n const regex = /(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?/;\n const match = duration.match(regex);\n if (!match) return 0;\n\n const hours = parseInt(match[1] ?? \"0\", 10);\n const minutes = parseInt(match[2] ?? \"0\", 10);\n const seconds = parseInt(match[3] ?? \"0\", 10);\n\n return (hours * 3600 + minutes * 60 + seconds) * 1000;\n}\n\n/**\n * Load configuration from TOML file\n */\nexport function loadConfig(configPath?: string): AgentConfig {\n // Find config file\n let path = configPath;\n if (!path) {\n path = DEFAULT_CONFIG_PATHS.find((p) => existsSync(p));\n }\n\n if (!path || !existsSync(path)) {\n console.warn(\"No config file found, using defaults\");\n return DEFAULT_CONFIG;\n }\n\n const content = readFileSync(path, \"utf-8\");\n const parsed = parse(content) as Record<string, unknown>;\n\n // Merge with defaults\n const auth = mergeAuthConfig(parsed.auth as Record<string, unknown>);\n\n return {\n tld: (parsed.tld as string) ?? DEFAULT_CONFIG.tld,\n port: (parsed.port as number) ?? DEFAULT_CONFIG.port,\n dbPath: (parsed.db_path as string) ?? DEFAULT_CONFIG.dbPath,\n projectListPath:\n (parsed.project_list_path as string) ?? DEFAULT_CONFIG.projectListPath,\n projectsDir: (parsed.projects_dir as string) ?? DEFAULT_CONFIG.projectsDir,\n idleTimeout:\n (parsed.idle_timeout as string) ?? DEFAULT_CONFIG.idleTimeout,\n idleCheckInterval:\n (parsed.idle_check_interval as string) ??\n DEFAULT_CONFIG.idleCheckInterval,\n auth,\n };\n}\n\nfunction mergeAuthConfig(raw?: Record<string, unknown>): AuthConfig {\n if (!raw) return DEFAULT_CONFIG.auth;\n\n const rules = (raw.rules as Array<Record<string, unknown>>) ?? [];\n\n return {\n defaultPolicy:\n (raw.default_policy as AuthConfig[\"defaultPolicy\"]) ??\n DEFAULT_CONFIG.auth.defaultPolicy,\n allowedIps:\n (raw.allowed_ips as string[]) ?? DEFAULT_CONFIG.auth.allowedIps,\n tokens: (raw.tokens as string[]) ?? DEFAULT_CONFIG.auth.tokens,\n basicAuth: (raw.basic_auth as string[]) ?? DEFAULT_CONFIG.auth.basicAuth,\n rules: rules.map(\n (r): AuthRule => ({\n match: r.match as string,\n policy: r.policy as AuthRule[\"policy\"],\n tokens: r.tokens as string[] | undefined,\n allowedIps: r.allowed_ips as string[] | undefined,\n }),\n ),\n };\n}\n\n/**\n * Validate configuration\n */\nexport function validateConfig(config: AgentConfig): string[] {\n const errors: string[] = [];\n\n if (!config.tld) {\n errors.push(\"tld is required\");\n }\n\n if (config.port < 1 || config.port > 65535) {\n errors.push(\"port must be between 1 and 65535\");\n }\n\n if (\n config.auth.defaultPolicy !== \"allow\" &&\n config.auth.defaultPolicy !== \"deny\" &&\n config.auth.defaultPolicy !== \"basic\" &&\n config.auth.defaultPolicy !== \"token\"\n ) {\n errors.push('auth.default_policy must be \"allow\", \"deny\", \"basic\", or \"token\"');\n }\n\n return errors;\n}\n","import { getIdleProjects, setProjectStatus } from \"../utils/db.js\";\nimport { stopProject, getProjectInfo, loadProjectList } from \"../utils/ddev.js\";\nimport { parseDuration } from \"../utils/config.js\";\nimport { loadProjectConfig, shouldNeverStop, getIdleTimeoutMs } from \"../utils/project-config.js\";\nimport type { AgentConfig } from \"../types.js\";\n\n/**\n * Stop idle projects that haven't been accessed recently\n * Respects per-project idle_timeout settings from .ddev/config.trafic.yaml\n */\nexport function stopIdleProjects(config: AgentConfig): void {\n const globalThresholdMs = parseDuration(config.idleTimeout);\n\n // Get all projects to check their individual configs\n const projects = loadProjectList(config.projectListPath);\n\n // Get projects idle according to global threshold\n const idleProjects = getIdleProjects(globalThresholdMs);\n\n for (const project of idleProjects) {\n const projectDir = projects.get(project.name);\n\n // Load per-project config if available\n if (projectDir) {\n const projectConfig = loadProjectConfig(projectDir);\n\n // Skip if project is configured to never stop\n if (shouldNeverStop(projectConfig)) {\n continue;\n }\n\n // Check project-specific idle timeout\n const projectThresholdMs = getIdleTimeoutMs(projectConfig);\n if (projectThresholdMs !== undefined) {\n const idleDuration = Date.now() - project.lastAccess;\n if (idleDuration < projectThresholdMs) {\n // Not idle according to project-specific timeout\n continue;\n }\n }\n }\n\n // Double-check project is actually running via DDEV\n const info = getProjectInfo(project.name);\n if (info?.status !== \"running\") {\n // Already stopped, just update our record\n setProjectStatus(project.name, \"stopped\");\n continue;\n }\n\n console.log(`Stopping idle project: ${project.name}`);\n const success = stopProject(project.name);\n\n if (success) {\n setProjectStatus(project.name, \"stopped\");\n console.log(`Stopped: ${project.name}`);\n } else {\n console.error(`Failed to stop: ${project.name}`);\n }\n }\n}\n\n/**\n * Start the idle check scheduler\n */\nexport function startIdleScheduler(config: AgentConfig): NodeJS.Timeout {\n const intervalMs = parseDuration(config.idleCheckInterval);\n\n console.log(\n `Idle scheduler started: checking every ${config.idleCheckInterval}, timeout ${config.idleTimeout}`,\n );\n\n // Run immediately on start\n stopIdleProjects(config);\n\n // Then run on interval\n return setInterval(() => {\n stopIdleProjects(config);\n }, intervalMs);\n}\n","import { execSync } from \"node:child_process\";\nimport { writeFileSync as fsWriteFile } from \"node:fs\";\n\nlet stepNumber = 0;\nlet dryRun = false;\n\n/**\n * Set dry-run mode\n */\nexport function setDryRun(value: boolean): void {\n dryRun = value;\n}\n\n/**\n * Reset step counter\n */\nexport function resetSteps(): void {\n stepNumber = 0;\n}\n\n/**\n * Log a step\n */\nexport function step(message: string): void {\n stepNumber++;\n console.log(`\\n\\x1b[36m[${stepNumber}]\\x1b[0m ${message}`);\n}\n\n/**\n * Log success\n */\nexport function success(message: string): void {\n console.log(` \\x1b[32m✓\\x1b[0m ${message}`);\n}\n\n/**\n * Log warning\n */\nexport function warn(message: string): void {\n console.log(` \\x1b[33m⚠\\x1b[0m ${message}`);\n}\n\n/**\n * Log error\n */\nexport function error(message: string): void {\n console.log(` \\x1b[31m✗\\x1b[0m ${message}`);\n}\n\n/**\n * Log info\n */\nexport function info(message: string): void {\n console.log(` ${message}`);\n}\n\n/**\n * Execute a command (or show in dry-run mode)\n */\nexport function exec(command: string, options?: { silent?: boolean }): string {\n if (dryRun) {\n if (!options?.silent) {\n console.log(` \\x1b[90m$ ${command}\\x1b[0m`);\n }\n return \"\";\n }\n\n try {\n return execSync(command, {\n encoding: \"utf-8\",\n stdio: options?.silent ? \"pipe\" : \"inherit\",\n });\n } catch (err) {\n const e = err as { status?: number; stderr?: string };\n throw new Error(`Command failed: ${command}\\n${e.stderr ?? \"\"}`);\n }\n}\n\n/**\n * Execute a command and return output (silent)\n */\nexport function execSilent(command: string): string {\n if (dryRun) {\n return \"\";\n }\n\n try {\n return execSync(command, {\n encoding: \"utf-8\",\n stdio: \"pipe\",\n }).trim();\n } catch {\n return \"\";\n }\n}\n\n/**\n * Check if a command exists\n */\nexport function commandExists(command: string): boolean {\n try {\n execSync(`which ${command}`, { stdio: \"pipe\" });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if running as root\n */\nexport function isRoot(): boolean {\n return process.getuid?.() === 0;\n}\n\n/**\n * Write a file (or show in dry-run mode)\n */\nexport function writeFile(path: string, content: string): void {\n if (dryRun) {\n console.log(` \\x1b[90mWrite ${path}:\\x1b[0m`);\n const lines = content.split(\"\\n\").slice(0, 5);\n for (const line of lines) {\n console.log(` \\x1b[90m ${line}\\x1b[0m`);\n }\n if (content.split(\"\\n\").length > 5) {\n console.log(` \\x1b[90m ...\\x1b[0m`);\n }\n return;\n }\n\n fsWriteFile(path, content);\n}\n","import { writeFileSync } from \"node:fs\";\nimport { step, success, info, exec, execSilent, warn } from \"./steps.js\";\n\n/**\n * Write /etc/sudoers.d/trafic-ddev allowing the ddev user to run\n * ddev-hostname without a password. Idempotent — safe to call multiple times.\n */\nexport function configureDdevSudoers(): void {\n const sudoersContent = `# Trafic: allow ddev user to run ddev-hostname without a password.\n# ddev-hostname manages /etc/hosts and always calls sudo internally.\nddev ALL=(ALL) NOPASSWD: /usr/bin/ddev-hostname\n`;\n writeFileSync(\"/etc/sudoers.d/trafic-ddev\", sudoersContent);\n exec(\"chmod 440 /etc/sudoers.d/trafic-ddev\", { silent: true });\n success(\"Configured passwordless sudo for ddev-hostname\");\n}\n\n/**\n * Create the ddev user with proper permissions\n */\nexport function createDdevUser(): void {\n step(\"Create ddev user\");\n\n // Check if user exists\n const userExists = execSilent(\"id -u ddev 2>/dev/null\");\n if (userExists) {\n info(\"User 'ddev' already exists\");\n } else {\n exec(\"useradd -m -s /bin/bash ddev\");\n success(\"Created user 'ddev'\");\n }\n\n // Add to docker group (will be created by Docker install)\n exec(\"usermod -aG docker ddev 2>/dev/null || true\", { silent: true });\n\n // Create www directory\n exec(\"mkdir -p /home/ddev/www\");\n exec(\"chown ddev:ddev /home/ddev/www\");\n exec(\"chmod 750 /home/ddev/www\");\n success(\"Created /home/ddev/www\");\n\n // Create .ssh directory if needed\n exec(\"mkdir -p /home/ddev/.ssh\");\n exec(\"chmod 700 /home/ddev/.ssh\");\n exec(\"chown ddev:ddev /home/ddev/.ssh\");\n\n // Allow ddev user to run ddev-hostname without a password.\n // ddev-hostname manages /etc/hosts entries and always calls sudo internally,\n // even when DDEV_NONINTERACTIVE=true. Without this rule, any ddev command\n // that touches hostname resolution (start, restart, poweroff + start) will\n // fail with \"sudo: a terminal is required to read the password\".\n configureDdevSudoers();\n success(\"User ddev configured\");\n}\n\n/**\n * Setup authorized_keys for ddev user\n */\nexport function setupAuthorizedKeys(publicKey?: string): void {\n if (!publicKey) {\n warn(\"No SSH public key provided, skipping authorized_keys setup\");\n return;\n }\n\n step(\"Setup SSH authorized_keys\");\n\n const authKeysPath = \"/home/ddev/.ssh/authorized_keys\";\n exec(`touch ${authKeysPath}`);\n exec(`chmod 600 ${authKeysPath}`);\n exec(`chown ddev:ddev ${authKeysPath}`);\n\n // Check if key already exists\n const existing = execSilent(`cat ${authKeysPath}`);\n if (existing.includes(publicKey.trim())) {\n info(\"SSH key already authorized\");\n } else {\n exec(`echo '${publicKey}' >> ${authKeysPath}`);\n success(\"Added SSH public key\");\n }\n}\n","import { writeFileSync, existsSync, readFileSync } from \"node:fs\";\nimport { step, success, info, exec, commandExists, warn } from \"./steps.js\";\n\n/**\n * Install Docker using the official script\n */\nexport function installDocker(): void {\n step(\"Install Docker\");\n\n if (commandExists(\"docker\")) {\n const version = exec(\"docker --version\", { silent: true });\n info(`Docker already installed: ${version?.trim() ?? \"unknown version\"}`);\n return;\n }\n\n // Install Docker using official script\n info(\"Downloading and running Docker install script...\");\n exec(\"curl -fsSL https://get.docker.com -o /tmp/get-docker.sh\");\n exec(\"sh /tmp/get-docker.sh\", { silent: true });\n exec(\"rm /tmp/get-docker.sh\");\n\n // Enable and start Docker\n exec(\"systemctl enable docker\", { silent: true });\n exec(\"systemctl start docker\", { silent: true });\n\n success(\"Docker installed and started\");\n\n // Add ddev user to docker group\n exec(\"usermod -aG docker ddev\", { silent: true });\n success(\"Added ddev user to docker group\");\n}\n\n/**\n * Configure Docker for production use\n */\nexport function configureDocker(): void {\n step(\"Configure Docker\");\n\n // Create daemon.json with production settings\n const daemonConfig = {\n \"log-driver\": \"json-file\",\n \"log-opts\": {\n \"max-size\": \"10m\",\n \"max-file\": \"3\",\n },\n \"storage-driver\": \"overlay2\",\n \"live-restore\": true,\n };\n\n exec(\"mkdir -p /etc/docker\");\n\n const configPath = \"/etc/docker/daemon.json\";\n\n // Check if config already exists\n if (existsSync(configPath)) {\n try {\n const existing = JSON.parse(readFileSync(configPath, \"utf-8\"));\n // Merge with existing config\n const merged = { ...existing, ...daemonConfig };\n writeFileSync(configPath, JSON.stringify(merged, null, 2));\n info(\"Merged with existing Docker config\");\n } catch {\n warn(\"Could not parse existing Docker config, skipping\");\n return;\n }\n } else {\n writeFileSync(configPath, JSON.stringify(daemonConfig, null, 2));\n }\n\n // Reload Docker to apply config\n exec(\"systemctl reload docker || systemctl restart docker\");\n success(\"Docker configured with production settings\");\n}\n\n/**\n * Setup Docker system prune cron job\n */\nexport function setupDockerPrune(): void {\n step(\"Setup Docker cleanup cron\");\n\n const cronContent = `# Trafic: Clean up Docker resources weekly\n0 3 * * 0 root docker system prune -af --volumes 2>&1 | logger -t docker-prune\n`;\n\n writeFileSync(\"/etc/cron.d/trafic-docker-prune\", cronContent);\n exec(\"chmod 644 /etc/cron.d/trafic-docker-prune\");\n\n success(\"Docker prune scheduled weekly at 3am on Sundays\");\n}\n","import { writeFileSync } from \"node:fs\";\nimport { step, success, info, exec, commandExists } from \"./steps.js\";\n\n/**\n * Install system dependencies required by Trafic\n */\nexport function installSystemDeps(): void {\n step(\"Install system dependencies\");\n\n exec(\"apt-get update -qq\", { silent: true });\n exec(\"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y jq curl rsync\", { silent: true });\n\n success(\"System dependencies installed: jq, curl, rsync\");\n}\n\n/**\n * Add the official DDEV apt repository and GPG key.\n * Idempotent: safe to call even if the repository is already configured.\n */\nexport function addDdevAptRepo(): void {\n exec(\"install -m 0755 -d /etc/apt/keyrings\", { silent: true });\n exec(\n \"curl -fsSL https://pkg.ddev.com/apt/gpg.key | gpg --dearmor | tee /etc/apt/keyrings/ddev.gpg > /dev/null\",\n { silent: true },\n );\n exec(\"chmod a+r /etc/apt/keyrings/ddev.gpg\", { silent: true });\n exec(\n \"echo \\\"deb [signed-by=/etc/apt/keyrings/ddev.gpg] https://pkg.ddev.com/apt/ * *\\\" | tee /etc/apt/sources.list.d/ddev.list > /dev/null\",\n { silent: true },\n );\n}\n\n/**\n * Install DDEV\n */\nexport function installDdev(): void {\n step(\"Install DDEV\");\n\n if (commandExists(\"ddev\")) {\n const version = exec(\"ddev --version 2>/dev/null | head -1\", { silent: true });\n info(`DDEV already installed: ${version?.trim() ?? \"unknown version\"}`);\n return;\n }\n\n // Install DDEV via the official apt repository\n // See https://docs.ddev.com/en/stable/users/install/ddev-installation/#debianubuntu\n info(\"Adding DDEV apt repository...\");\n addDdevAptRepo();\n\n info(\"Installing DDEV...\");\n exec(\"apt-get update -qq\", { silent: true });\n exec(\"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y ddev\", { silent: true });\n\n // Initialize mkcert certificate authority for the ddev user.\n // mkcert installs the CA into the home directory of the current user.\n // Since setup runs as root, we must point HOME to the ddev user's home\n // so the CA is trusted by DDEV when it runs as that user.\n exec(\"HOME=/home/ddev mkcert -install\", { silent: true });\n exec(\"chown -R ddev:ddev /home/ddev/.local/share/mkcert\", { silent: true });\n\n const version = exec(\"ddev --version 2>/dev/null | head -1\", { silent: true });\n success(`DDEV installed: ${version?.trim() ?? \"unknown version\"}`);\n}\n\n/**\n * Configure DDEV global settings for production\n *\n * Note on DNS and /etc/hosts:\n * When using a custom TLD (not ddev.site), DDEV may try to edit /etc/hosts\n * if it can't resolve project hostnames via DNS. To avoid this:\n * 1. Configure DNS so *.{tld} resolves to the server's IP (recommended)\n * 2. Or install dnsmasq for local wildcard DNS resolution\n *\n * With proper DNS, DDEV won't need sudo for hostname management.\n */\nexport function configureDdev(tld: string, email?: string): void {\n step(\"Configure DDEV\");\n\n // Run as ddev user\n const ddevCmd = (cmd: string) => `su - ddev -c '${cmd}'`;\n\n // Configure all global settings in a single call\n exec(\n ddevCmd(\n `ddev config global --project-tld=${tld} --router-http-port=80 --router-https-port=443 --router-bind-all-interfaces=true --use-letsencrypt=${email ? \"true\" : \"false\"} ${email ? `--letsencrypt-email=${email}` : \"\"} --instrumentation-opt-in=false`,\n ),\n { silent: true },\n );\n\n success(`DDEV configured with TLD: ${tld}`);\n info(`Ensure DNS is configured: *.${tld} → server IP`);\n\n if (email) {\n success(`Let's Encrypt enabled with email: ${email}`);\n }\n\n success(\"DDEV global settings configured\");\n}\n\n/**\n * Install dnsmasq for local DNS resolution (optional)\n * This allows the server itself to resolve *.{tld} hostnames\n * without needing to edit /etc/hosts for each project\n */\nexport function installDnsmasq(tld: string): void {\n step(\"Install dnsmasq for local DNS\");\n\n exec(\"apt-get update && apt-get install -y dnsmasq\", { silent: true });\n\n // Get server's public IP\n const serverIp = exec(\n \"curl -4 -s ifconfig.me || hostname -I | awk '{print $1}'\",\n { silent: true },\n )?.trim() || \"127.0.0.1\";\n\n // Configure dnsmasq to resolve *.{tld} to server IP\n const dnsmasqConfig = `# Trafic: Local DNS for DDEV projects\n# Resolve all *.${tld} to this server\naddress=/${tld}/${serverIp}\n\n# Don't read /etc/resolv.conf\nno-resolv\n\n# Use upstream DNS for everything else\nserver=1.1.1.1\nserver=8.8.8.8\n\n# Listen on localhost only\nlisten-address=127.0.0.1\nbind-interfaces\n`;\n\n writeFileSync(\"/etc/dnsmasq.d/trafic.conf\", dnsmasqConfig);\n\n // Configure system to use local dnsmasq\n exec(\"systemctl restart dnsmasq\");\n exec(\"systemctl enable dnsmasq\");\n\n // Update resolv.conf to use local DNS first\n info(\"Configure /etc/resolv.conf to use 127.0.0.1 as primary DNS\");\n\n success(`dnsmasq configured: *.${tld} → ${serverIp}`);\n}\n\n/**\n * Get the Docker gateway IP reachable from inside DDEV containers on Linux.\n * DDEV runs containers on the `ddev_default` network — we inspect that first.\n * Falls back to the default `bridge` network, then to 172.17.0.1.\n * `host.docker.internal` is not available on Linux without extra configuration.\n */\nexport function getDockerGatewayIp(): string {\n // Prefer the ddev_default network gateway — that's the network ddev-router is on\n const ddevIp = exec(\n \"docker network inspect ddev_default --format '{{range .IPAM.Config}}{{.Gateway}}{{end}}' 2>/dev/null\",\n { silent: true },\n )?.trim();\n if (ddevIp) return ddevIp;\n\n // Fall back to the default bridge network\n const bridgeIp = exec(\n \"docker network inspect bridge --format '{{range .IPAM.Config}}{{.Gateway}}{{end}}' 2>/dev/null\",\n { silent: true },\n )?.trim();\n return bridgeIp || \"172.17.0.1\";\n}\n\n/**\n * Configure Traefik for forward auth\n */\nexport function configureTraefik(): void {\n step(\"Configure Traefik for forward auth\");\n\n // Create custom Traefik config directory\n exec(\"mkdir -p /home/ddev/.ddev/traefik\", { silent: true });\n exec(\"chown -R ddev:ddev /home/ddev/.ddev\", { silent: true });\n\n // Use the Docker bridge gateway IP instead of host.docker.internal —\n // the latter is not available on Linux without extra Docker configuration.\n const gatewayIp = getDockerGatewayIp();\n\n // Static configuration for Trafic middleware\n const staticConfig = `# Trafic: Forward auth middleware\nhttp:\n middlewares:\n trafic-auth:\n forwardAuth:\n address: \"http://${gatewayIp}:9876/__auth__\"\n authResponseHeaders:\n - \"X-Trafic-Project\"\n\n trafic-errors:\n errors:\n status:\n - \"502\"\n - \"503\"\n service: trafic-service\n query: \"/\"\n\n services:\n trafic-service:\n loadBalancer:\n servers:\n - url: \"http://${gatewayIp}:9876\"\n`;\n\n writeFileSync(\"/home/ddev/.ddev/traefik/trafic.yaml\", staticConfig);\n exec(\"chown ddev:ddev /home/ddev/.ddev/traefik/trafic.yaml\", { silent: true });\n\n // Create default router config that applies middleware to all projects\n const routerConfig = `# Trafic: Default router configuration\n# This file makes all DDEV projects use the Trafic auth middleware\nhttp:\n routers:\n trafic-catch-all:\n rule: \"HostRegexp(\\`.+\\`)\"\n priority: 1\n middlewares:\n - trafic-auth\n - trafic-errors\n service: api@internal\n`;\n\n writeFileSync(\"/home/ddev/.ddev/traefik/dynamic.yaml\", routerConfig);\n exec(\"chown ddev:ddev /home/ddev/.ddev/traefik/dynamic.yaml\", { silent: true });\n\n success(\"Traefik configured with Trafic middleware\");\n}\n","import { step, success, info, exec, commandExists } from \"./steps.js\";\nimport { writeFileSync, existsSync } from \"node:fs\";\n\n/**\n * Install Node.js using fnm\n */\nexport function installNode(): void {\n step(\"Install Node.js\");\n\n // Check if Node is already installed\n if (commandExists(\"node\")) {\n const version = exec(\"node --version\", { silent: true });\n info(`Node.js already installed: ${version?.trim()}`);\n return;\n }\n\n // Install fnm (Fast Node Manager)\n exec(\n 'curl -fsSL https://fnm.vercel.app/install | bash -s -- --install-dir \"/opt/fnm\" --skip-shell',\n );\n\n // Add fnm to system path\n const profileContent = `# Trafic: fnm (Node.js version manager)\nexport FNM_DIR=\"/opt/fnm\"\nexport PATH=\"/opt/fnm:$PATH\"\neval \"$(fnm env)\"\n`;\n\n writeFileSync(\"/etc/profile.d/fnm.sh\", profileContent);\n exec(\"chmod 644 /etc/profile.d/fnm.sh\");\n\n // Install Node.js 24\n exec(\"export FNM_DIR=/opt/fnm && /opt/fnm/fnm install 24\");\n exec(\"export FNM_DIR=/opt/fnm && /opt/fnm/fnm default 24\");\n\n // Create symlinks for system-wide access\n exec(\n \"ln -sf /opt/fnm/aliases/default/bin/node /usr/local/bin/node || true\",\n );\n exec(\"ln -sf /opt/fnm/aliases/default/bin/npm /usr/local/bin/npm || true\");\n exec(\"ln -sf /opt/fnm/aliases/default/bin/npx /usr/local/bin/npx || true\");\n\n success(\"Node.js 24 installed via fnm\");\n}\n\n/**\n * Install the Trafic agent\n */\nexport function installAgent(): void {\n step(\"Install Trafic agent\");\n\n // Install the agent globally\n exec(\"npm install -g @studiometa/trafic-agent\");\n\n success(\"Trafic agent installed\");\n}\n\n/**\n * Create the agent configuration\n */\nexport function createAgentConfig(tld: string, _email?: string): void {\n step(\"Create agent configuration\");\n\n // Create directories\n exec(\"mkdir -p /etc/trafic\");\n exec(\"mkdir -p /var/lib/trafic\");\n exec(\"chown ddev:ddev /var/lib/trafic\");\n\n const configPath = \"/etc/trafic/config.toml\";\n\n if (existsSync(configPath)) {\n info(\"Configuration already exists at /etc/trafic/config.toml — skipping\");\n info(\"Edit this file to configure authentication\");\n return;\n }\n\n const config = `# Trafic agent configuration\n# Generated by trafic setup\n\n# Required: TLD for DDEV projects\ntld = \"${tld}\"\n\n# Agent HTTP server port\nport = 9876\n\n# Database and paths\ndb_path = \"/var/lib/trafic/db.sqlite\"\nproject_list_path = \"/home/ddev/.ddev/project_list.yaml\"\nprojects_dir = \"/home/ddev/www\"\n\n# Scale-to-zero settings\nidle_timeout = \"4h\"\nidle_check_interval = \"5m\"\n\n# Authentication\n[auth]\ndefault_policy = \"basic\"\nallowed_ips = []\ntokens = []\nbasic_auth = []\nrules = []\n`;\n\n writeFileSync(configPath, config);\n exec(\"chmod 640 /etc/trafic/config.toml\");\n exec(\"chown root:ddev /etc/trafic/config.toml\");\n\n success(\"Configuration created at /etc/trafic/config.toml\");\n info(\"Edit this file to configure authentication\");\n}\n\n/**\n * Create systemd service for the agent\n */\nexport function createSystemdService(): void {\n step(\"Create systemd service\");\n\n // Find the trafic-agent binary path\n const agentPath = exec(\"which trafic-agent\", { silent: true })?.trim() || \"/usr/bin/trafic-agent\";\n\n const serviceContent = `[Unit]\nDescription=Trafic Agent - DDEV preview environment manager\nAfter=network.target docker.service\nRequires=docker.service\n\n[Service]\nType=simple\nUser=ddev\nGroup=ddev\nExecStart=${agentPath} start --config /etc/trafic/config.toml\nRestart=always\nRestartSec=5\nStandardOutput=journal\nStandardError=journal\nSyslogIdentifier=trafic-agent\n\n# Environment\nEnvironment=NODE_ENV=production\n# Skip ddev-hostname /etc/hosts management — on a server, hostnames resolve\n# to the public IP (not localhost), which would trigger ddev-hostname on every\n# ddev start. DDEV_NONINTERACTIVE=true skips that entirely.\nEnvironment=DDEV_NONINTERACTIVE=true\n\n# Security hardening\nNoNewPrivileges=true\nProtectSystem=strict\nProtectHome=read-only\nReadWritePaths=/var/lib/trafic /home/ddev/.ddev\nPrivateTmp=true\n\n[Install]\nWantedBy=multi-user.target\n`;\n\n writeFileSync(\"/etc/systemd/system/trafic-agent.service\", serviceContent);\n exec(\"chmod 644 /etc/systemd/system/trafic-agent.service\");\n\n // Reload systemd and enable service\n exec(\"systemctl daemon-reload\");\n exec(\"systemctl enable trafic-agent\");\n exec(\"systemctl start trafic-agent\");\n\n success(\"Trafic agent service started\");\n info(\"View logs: journalctl -u trafic-agent -f\");\n}\n","import { step, success, info, exec, warn, commandExists } from \"./steps.js\";\nimport { writeFileSync, existsSync } from \"node:fs\";\n\n/**\n * Configure SSH hardening\n */\nexport function hardenSsh(allowedUsers: string[] = [\"ddev\"]): void {\n step(\"Harden SSH configuration\");\n\n const sshConfig = `# Trafic SSH hardening\n# Generated by trafic setup\n\n# Allow root login via SSH key only (no password) — required for server management\nPermitRootLogin prohibit-password\n\n# Disable password authentication (keys only)\nPasswordAuthentication no\nPubkeyAuthentication yes\n\n# Limit authentication attempts\nMaxAuthTries 3\n\n# Idle timeout (5 minutes)\nClientAliveInterval 300\nClientAliveCountMax 2\n\n# Allowed users (root kept for emergency access)\nAllowUsers root ${allowedUsers.join(\" \")}\n\n# Disable X11 forwarding\nX11Forwarding no\n\n# Disable TCP forwarding\nAllowTcpForwarding no\n\n# Use strong algorithms only\nKexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256\nCiphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com\nMACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com\n`;\n\n writeFileSync(\"/etc/ssh/sshd_config.d/trafic.conf\", sshConfig);\n exec(\"chmod 644 /etc/ssh/sshd_config.d/trafic.conf\");\n\n // Test config before restarting\n const testResult = exec(\"sshd -t 2>&1 || echo 'error'\", { silent: true });\n if (testResult?.includes(\"error\")) {\n warn(\"SSH config test failed, reverting...\");\n exec(\"rm /etc/ssh/sshd_config.d/trafic.conf\");\n return;\n }\n\n exec(\"systemctl reload ssh || systemctl reload sshd\");\n success(\"SSH hardened: password auth disabled, root key-only login retained\");\n info(`Allowed users: root, ${allowedUsers.join(\", \")}`);\n}\n\n/**\n * Configure UFW firewall\n */\nexport function configureFirewall(): void {\n step(\"Configure firewall (UFW)\");\n\n // Install UFW if not present\n if (!commandExists(\"ufw\")) {\n exec(\"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y ufw\", { silent: true });\n }\n\n // Reset and configure\n exec(\"ufw --force reset\", { silent: true });\n exec(\"ufw default deny incoming\");\n exec(\"ufw default allow outgoing\");\n exec(\"ufw allow 22/tcp comment 'SSH'\");\n exec(\"ufw allow 80/tcp comment 'HTTP'\");\n exec(\"ufw allow 443/tcp comment 'HTTPS'\");\n // Allow trafic-agent port from Docker bridge subnets so ddev-router can\n // reach the forward-auth endpoint. Docker typically uses 172.16.0.0/12.\n exec(\"ufw allow from 172.16.0.0/12 to any port 9876 comment 'trafic-agent from Docker'\");\n\n // Enable firewall\n exec(\"ufw --force enable\");\n\n success(\"Firewall enabled: SSH (22), HTTP (80), HTTPS (443), trafic-agent (9876 from Docker) allowed\");\n}\n\n/**\n * Configure automatic security updates\n */\nexport function configureUnattendedUpgrades(): void {\n step(\"Configure automatic security updates\");\n\n // Install unattended-upgrades\n exec(\n \"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y unattended-upgrades apt-listchanges\",\n { silent: true },\n );\n\n // Configure for security updates only\n const upgradesConfig = `// Trafic: Automatic security updates\nUnattended-Upgrade::Allowed-Origins {\n \"\\${distro_id}:\\${distro_codename}\";\n \"\\${distro_id}:\\${distro_codename}-security\";\n \"\\${distro_id}ESMApps:\\${distro_codename}-apps-security\";\n \"\\${distro_id}ESM:\\${distro_codename}-infra-security\";\n};\n\n// Do not automatically reboot\nUnattended-Upgrade::Automatic-Reboot \"false\";\n\n// Remove unused dependencies\nUnattended-Upgrade::Remove-Unused-Dependencies \"true\";\n\n// Email notifications (optional)\n// Unattended-Upgrade::Mail \"root\";\n`;\n\n writeFileSync(\n \"/etc/apt/apt.conf.d/50unattended-upgrades\",\n upgradesConfig,\n );\n\n // Enable automatic updates\n const autoConfig = `APT::Periodic::Update-Package-Lists \"1\";\nAPT::Periodic::Download-Upgradeable-Packages \"1\";\nAPT::Periodic::AutocleanInterval \"7\";\nAPT::Periodic::Unattended-Upgrade \"1\";\n`;\n\n writeFileSync(\"/etc/apt/apt.conf.d/20auto-upgrades\", autoConfig);\n\n // Enable the service\n exec(\"systemctl enable unattended-upgrades\");\n exec(\"systemctl start unattended-upgrades\");\n\n success(\"Automatic security updates enabled\");\n}\n\n/**\n * Configure Fail2ban\n */\nexport function configureFail2ban(): void {\n step(\"Configure Fail2ban\");\n\n // Install fail2ban\n if (!commandExists(\"fail2ban-client\")) {\n exec(\"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y fail2ban\", { silent: true });\n }\n\n // Configure jail\n const jailConfig = `# Trafic: Fail2ban configuration\n[DEFAULT]\nbantime = 3600\nfindtime = 600\nmaxretry = 5\nbackend = auto\n\n[sshd]\nenabled = true\nport = ssh\nfilter = sshd\nlogpath = /var/log/auth.log\nmaxretry = 3\nbantime = 7200\n`;\n\n writeFileSync(\"/etc/fail2ban/jail.local\", jailConfig);\n exec(\"chmod 644 /etc/fail2ban/jail.local\");\n\n // Restart fail2ban\n exec(\"systemctl enable fail2ban\");\n exec(\"systemctl restart fail2ban\");\n\n success(\"Fail2ban enabled: SSH brute force protection active\");\n}\n\n/**\n * Configure system limits\n */\nexport function configureSystemLimits(): void {\n step(\"Configure system limits\");\n\n const limitsConfig = `# Trafic: System limits for ddev user\nddev soft nofile 65536\nddev hard nofile 65536\nddev soft nproc 4096\nddev hard nproc 4096\n`;\n\n writeFileSync(\"/etc/security/limits.d/trafic.conf\", limitsConfig);\n exec(\"chmod 644 /etc/security/limits.d/trafic.conf\");\n\n success(\"System limits configured for ddev user\");\n}\n\n/**\n * Set proper file permissions\n */\nexport function configureFilePermissions(): void {\n step(\"Configure file permissions\");\n\n // Create directories\n exec(\"mkdir -p /etc/trafic\");\n exec(\"mkdir -p /var/lib/trafic\");\n exec(\"mkdir -p /var/backups/trafic\");\n\n // Set permissions\n exec(\"chmod 755 /etc/trafic\");\n exec(\"chmod 700 /var/lib/trafic\");\n exec(\"chmod 700 /var/backups/trafic\");\n exec(\"chown root:ddev /etc/trafic\");\n exec(\"chown ddev:ddev /var/lib/trafic\");\n exec(\"chown ddev:ddev /var/backups/trafic\");\n\n // Config file (if exists)\n if (existsSync(\"/etc/trafic/config.toml\")) {\n exec(\"chmod 640 /etc/trafic/config.toml\");\n exec(\"chown root:ddev /etc/trafic/config.toml\");\n }\n\n success(\"File permissions configured\");\n}\n\n/**\n * Run all hardening steps\n */\nexport function hardenServer(sshUsers: string[] = [\"ddev\"]): void {\n hardenSsh(sshUsers);\n configureFirewall();\n configureUnattendedUpgrades();\n configureFail2ban();\n configureSystemLimits();\n configureFilePermissions();\n}\n","import { execSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { AuditCheck } from \"./types.js\";\n\n/**\n * Run a command silently and return output\n */\nfunction execSilent(command: string): string {\n try {\n return execSync(command, { encoding: \"utf-8\", stdio: \"pipe\" }).trim();\n } catch {\n return \"\";\n }\n}\n\n/**\n * Check if a service is active\n */\nfunction isServiceActive(service: string): boolean {\n const status = execSilent(`systemctl is-active ${service}`);\n return status === \"active\";\n}\n\n/**\n * Audit SSH configuration\n */\nfunction auditSsh(): AuditCheck[] {\n const checks: AuditCheck[] = [];\n\n // Check root login\n const sshdConfig = existsSync(\"/etc/ssh/sshd_config\")\n ? readFileSync(\"/etc/ssh/sshd_config\", \"utf-8\")\n : \"\";\n const traficConfig = existsSync(\"/etc/ssh/sshd_config.d/trafic.conf\")\n ? readFileSync(\"/etc/ssh/sshd_config.d/trafic.conf\", \"utf-8\")\n : \"\";\n\n const config = sshdConfig + \"\\n\" + traficConfig;\n\n const rootLoginDisabled =\n config.includes(\"PermitRootLogin no\") ||\n config.includes(\"PermitRootLogin prohibit-password\");\n checks.push({\n name: \"SSH root login\",\n status: rootLoginDisabled ? \"pass\" : \"fail\",\n message: rootLoginDisabled\n ? \"Root login disabled\"\n : \"Root login may be enabled\",\n fix: \"Add 'PermitRootLogin no' to /etc/ssh/sshd_config.d/trafic.conf\",\n });\n\n const passwordAuthDisabled = config.includes(\"PasswordAuthentication no\");\n checks.push({\n name: \"SSH password auth\",\n status: passwordAuthDisabled ? \"pass\" : \"warn\",\n message: passwordAuthDisabled\n ? \"Password authentication disabled\"\n : \"Password authentication may be enabled\",\n fix: \"Add 'PasswordAuthentication no' to /etc/ssh/sshd_config.d/trafic.conf\",\n });\n\n return checks;\n}\n\n/**\n * Audit firewall configuration\n */\nfunction auditFirewall(): AuditCheck[] {\n const checks: AuditCheck[] = [];\n\n const ufwStatus = execSilent(\"ufw status\");\n const isActive = ufwStatus.includes(\"Status: active\");\n\n checks.push({\n name: \"Firewall (UFW)\",\n status: isActive ? \"pass\" : \"fail\",\n message: isActive ? \"UFW is active\" : \"UFW is not active\",\n fix: \"Run: ufw enable\",\n });\n\n if (isActive) {\n const allows22 = ufwStatus.includes(\"22/tcp\");\n const allows80 = ufwStatus.includes(\"80/tcp\");\n const allows443 = ufwStatus.includes(\"443/tcp\");\n\n if (allows22 && allows80 && allows443) {\n checks.push({\n name: \"Firewall ports\",\n status: \"pass\",\n message: \"Required ports (22, 80, 443) are open\",\n });\n } else {\n checks.push({\n name: \"Firewall ports\",\n status: \"warn\",\n message: \"Some required ports may be blocked\",\n fix: \"Run: ufw allow 22/tcp && ufw allow 80/tcp && ufw allow 443/tcp\",\n });\n }\n }\n\n return checks;\n}\n\n/**\n * Audit security services\n */\nfunction auditServices(): AuditCheck[] {\n const checks: AuditCheck[] = [];\n\n // Fail2ban\n const fail2banActive = isServiceActive(\"fail2ban\");\n checks.push({\n name: \"Fail2ban\",\n status: fail2banActive ? \"pass\" : \"warn\",\n message: fail2banActive ? \"Fail2ban is active\" : \"Fail2ban is not running\",\n fix: \"Run: apt install fail2ban && systemctl enable fail2ban --now\",\n });\n\n // Unattended upgrades\n const unattendedActive = isServiceActive(\"unattended-upgrades\");\n checks.push({\n name: \"Automatic updates\",\n status: unattendedActive ? \"pass\" : \"warn\",\n message: unattendedActive\n ? \"Unattended upgrades enabled\"\n : \"Automatic updates not configured\",\n fix: \"Run: apt install unattended-upgrades && dpkg-reconfigure unattended-upgrades\",\n });\n\n // Trafic agent\n const agentActive = isServiceActive(\"trafic-agent\");\n checks.push({\n name: \"Trafic agent\",\n status: agentActive ? \"pass\" : \"fail\",\n message: agentActive\n ? \"Trafic agent is running\"\n : \"Trafic agent is not running\",\n fix: \"Run: systemctl start trafic-agent\",\n });\n\n return checks;\n}\n\n/**\n * Audit Docker\n */\nfunction auditDocker(): AuditCheck[] {\n const checks: AuditCheck[] = [];\n\n // Docker running\n const dockerActive = isServiceActive(\"docker\");\n checks.push({\n name: \"Docker\",\n status: dockerActive ? \"pass\" : \"fail\",\n message: dockerActive ? \"Docker is running\" : \"Docker is not running\",\n fix: \"Run: systemctl start docker\",\n });\n\n // Dangling images\n const danglingImages = execSilent(\n \"docker images -f dangling=true -q | wc -l\",\n );\n const count = parseInt(danglingImages, 10) || 0;\n if (count > 0) {\n checks.push({\n name: \"Docker cleanup\",\n status: \"warn\",\n message: `${count} dangling Docker images`,\n fix: \"Run: docker system prune -f\",\n });\n }\n\n // Disk usage\n const diskUsage = execSilent(\"df -h / | awk 'NR==2{print $5}'\");\n const usagePercent = parseInt(diskUsage, 10) || 0;\n checks.push({\n name: \"Disk usage\",\n status: usagePercent > 90 ? \"fail\" : usagePercent > 80 ? \"warn\" : \"pass\",\n message: `Disk usage: ${diskUsage}`,\n fix: usagePercent > 80 ? \"Consider cleaning up old projects or Docker resources\" : undefined,\n });\n\n return checks;\n}\n\n/**\n * Audit file permissions\n */\nfunction auditPermissions(): AuditCheck[] {\n const checks: AuditCheck[] = [];\n\n // Config file\n if (existsSync(\"/etc/trafic/config.toml\")) {\n const stats = execSilent(\"stat -c '%a' /etc/trafic/config.toml\");\n const isSecure = stats === \"640\" || stats === \"600\";\n checks.push({\n name: \"Config permissions\",\n status: isSecure ? \"pass\" : \"warn\",\n message: isSecure\n ? \"Config file has secure permissions\"\n : `Config file permissions: ${stats} (should be 640)`,\n fix: \"Run: chmod 640 /etc/trafic/config.toml\",\n });\n }\n\n // Projects directory\n if (existsSync(\"/home/ddev/www\")) {\n const owner = execSilent(\"stat -c '%U:%G' /home/ddev/www\");\n const isCorrect = owner === \"ddev:ddev\";\n checks.push({\n name: \"Projects directory\",\n status: isCorrect ? \"pass\" : \"warn\",\n message: isCorrect\n ? \"Projects directory owned by ddev\"\n : `Projects directory owner: ${owner}`,\n fix: \"Run: chown ddev:ddev /home/ddev/www\",\n });\n }\n\n return checks;\n}\n\n/**\n * Run all audit checks\n */\nexport function runAudit(): AuditCheck[] {\n return [\n ...auditSsh(),\n ...auditFirewall(),\n ...auditServices(),\n ...auditDocker(),\n ...auditPermissions(),\n ];\n}\n\n/**\n * Print audit results\n */\nexport function printAuditResults(checks: AuditCheck[]): void {\n console.log(\"\\n\\x1b[1mSecurity Audit Results\\x1b[0m\\n\");\n\n for (const check of checks) {\n const icon =\n check.status === \"pass\"\n ? \"\\x1b[32m✓\\x1b[0m\"\n : check.status === \"warn\"\n ? \"\\x1b[33m⚠\\x1b[0m\"\n : \"\\x1b[31m✗\\x1b[0m\";\n\n console.log(`${icon} \\x1b[1m${check.name}\\x1b[0m: ${check.message}`);\n\n if (check.fix && check.status !== \"pass\") {\n console.log(` \\x1b[90m${check.fix}\\x1b[0m`);\n }\n }\n\n const passed = checks.filter((c) => c.status === \"pass\").length;\n const warnings = checks.filter((c) => c.status === \"warn\").length;\n const failed = checks.filter((c) => c.status === \"fail\").length;\n\n console.log(\n `\\n\\x1b[1mSummary:\\x1b[0m ${passed} passed, ${warnings} warnings, ${failed} failed`,\n );\n}\n","import { existsSync } from \"node:fs\";\nimport { exec } from \"../steps.js\";\nimport { addDdevAptRepo } from \"../ddev.js\";\nimport type { Migration } from \"../types.js\";\n\n/**\n * Migration 0001: Migrate DDEV from manual tarball to apt repository.\n *\n * Old installs downloaded a tarball from GitHub releases. This migration\n * removes the manually-installed binaries and reinstalls DDEV via the\n * official apt repository so future updates are handled by apt.\n *\n * Condition: skip if /etc/apt/sources.list.d/ddev.list already exists,\n * which means the apt repository is already configured.\n */\nexport const migration0001DdevAptRepo: Migration = {\n id: \"0001__ddev_apt_repo\",\n description: \"Migrate DDEV from manual tarball to apt repository\",\n\n run(): void {\n // Already using the apt repository — nothing to do\n if (existsSync(\"/etc/apt/sources.list.d/ddev.list\")) {\n return;\n }\n\n // 1. Remove manually-installed DDEV binaries\n exec(\"rm -f /usr/local/bin/ddev /usr/local/bin/ddev-hostname /usr/local/bin/mkcert\", {\n silent: true,\n });\n\n // 2. Add the official DDEV apt repository\n addDdevAptRepo();\n\n // 3. Install DDEV via apt\n exec(\"apt-get update -qq\", { silent: true });\n exec(\"DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y ddev\", {\n silent: true,\n });\n\n // 4. Re-install mkcert CA (mkcert is now bundled with DDEV via apt)\n exec(\"mkcert -install\", { silent: true });\n },\n};\n","import { existsSync } from \"node:fs\";\nimport { exec } from \"../steps.js\";\nimport type { Migration } from \"../types.js\";\n\n/**\n * Migration 0002: Install mkcert CA in the ddev user trust store.\n *\n * Previously, `mkcert -install` was called as root without overriding HOME,\n * so the CA was stored under ~root/.local/share/mkcert. DDEV runs as the\n * `ddev` user and looks for the CA in its own home directory — so it never\n * found it, reporting mkcert as not installed.\n *\n * Fix: run `mkcert -install` with HOME=/home/ddev so the CA lands in the\n * ddev user trust store, then chown the directory to ddev:ddev.\n *\n * Condition: skip if /home/ddev/.local/share/mkcert already exists,\n * which means the CA is already installed for the ddev user.\n */\nexport const migration0002MkcertDdevUser: Migration = {\n id: \"0002__mkcert_ddev_user\",\n description: \"Install mkcert CA in the ddev user trust store\",\n\n run(): void {\n // Already installed for the ddev user — nothing to do\n if (existsSync(\"/home/ddev/.local/share/mkcert\")) {\n return;\n }\n\n exec(\"HOME=/home/ddev mkcert -install\", { silent: true });\n exec(\"chown -R ddev:ddev /home/ddev/.local/share/mkcert\", { silent: true });\n },\n};\n","import { exec } from \"../steps.js\";\nimport type { Migration } from \"../types.js\";\n\n/**\n * Migration 0003: Enable router_bind_all_interfaces in DDEV global config.\n *\n * The initial setup did not set --router-bind-all-interfaces=true, which\n * caused ddev-router to bind only on 127.0.0.1. External traffic (including\n * Cloudflare proxying) could not reach the router, resulting in 521 errors.\n *\n * This migration enables the flag and restarts the DDEV router so the change\n * takes effect immediately.\n *\n * Idempotent: ddev config global is safe to re-run with the same value.\n */\nexport const migration0003DdevRouterBindAllInterfaces: Migration = {\n id: \"0003__ddev_router_bind_all_interfaces\",\n description: \"Bind ddev-router on all interfaces (fix 521 for external traffic)\",\n\n run(): void {\n exec(\"su - ddev -c 'ddev config global --router-bind-all-interfaces=true'\", { silent: true });\n // Restart all running projects so the router picks up the new bind setting\n exec(\"su - ddev -c 'ddev poweroff'\", { silent: true });\n exec(\"su - ddev -c 'ddev start --all'\", { silent: true });\n },\n};\n","import { existsSync } from \"node:fs\";\nimport { configureDdevSudoers } from \"../user.js\";\nimport type { Migration } from \"../types.js\";\n\n/**\n * Migration 0004: Allow ddev user to run ddev-hostname without a password.\n *\n * ddev-hostname manages /etc/hosts entries and always calls sudo internally,\n * even when DDEV_NONINTERACTIVE=true. Without this sudoers rule, any ddev\n * command that touches hostname resolution (start, restart, poweroff + start)\n * fails with \"sudo: a terminal is required to read the password\".\n *\n * Condition: skip if /etc/sudoers.d/trafic-ddev already exists.\n */\nexport const migration0004DdevHostnameSudoers: Migration = {\n id: \"0004__ddev_hostname_sudoers\",\n description: \"Allow ddev user to run ddev-hostname without a password\",\n\n run(): void {\n if (existsSync(\"/etc/sudoers.d/trafic-ddev\")) {\n return;\n }\n\n configureDdevSudoers();\n },\n};\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { getDockerGatewayIp } from \"../ddev.js\";\nimport type { Migration } from \"../types.js\";\n\nconst TRAFIC_YAML = \"/home/ddev/.ddev/traefik/trafic.yaml\";\n\n/**\n * Migration 0005: Replace host.docker.internal with the Docker bridge gateway IP\n * in the Traefik forward-auth config.\n *\n * host.docker.internal is a Docker Desktop / macOS feature and is not available\n * on Linux without explicit configuration. The Traefik router container cannot\n * resolve it, so forward-auth requests silently fail and all traffic bypasses\n * authentication.\n *\n * Fix: replace all occurrences of host.docker.internal in trafic.yaml with the\n * actual Docker bridge gateway IP (typically 172.17.0.1 or 172.18.0.1).\n *\n * Condition: skip if trafic.yaml doesn't exist or already uses an IP address.\n */\nexport const migration0005TraefikGatewayIp: Migration = {\n id: \"0005__traefik_gateway_ip\",\n description: \"Replace host.docker.internal with Docker bridge gateway IP in Traefik config\",\n\n run(): void {\n if (!existsSync(TRAFIC_YAML)) {\n return;\n }\n\n const content = readFileSync(TRAFIC_YAML, \"utf-8\");\n const gatewayIp = getDockerGatewayIp();\n\n // Replace host.docker.internal (original broken value) or any previously\n // written IP that no longer matches the current gateway (e.g. if the\n // migration ran before ddev_default existed and wrote 172.17.0.1 instead).\n const updated = content\n .replaceAll(\"host.docker.internal\", gatewayIp)\n .replace(/http:\\/\\/\\d+\\.\\d+\\.\\d+\\.\\d+:9876/g, `http://${gatewayIp}:9876`);\n\n if (updated === content) {\n return;\n }\n\n writeFileSync(TRAFIC_YAML, updated, \"utf-8\");\n },\n};\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { getDockerGatewayIp } from \"../ddev.js\";\nimport type { Migration } from \"../types.js\";\n\nconst TRAFIC_YAML = \"/home/ddev/.ddev/traefik/trafic.yaml\";\n\n/**\n * Migration 0006: Fix the Docker gateway IP in trafic.yaml.\n *\n * Migration 0005 inspected the default `bridge` network (172.17.0.1) instead\n * of the `ddev_default` network (typically 172.18.0.1) that ddev-router\n * actually runs on. This migration rewrites trafic.yaml with the correct IP.\n *\n * Idempotent: re-reads the file and only writes if the IP has changed.\n */\nexport const migration0006TraefikGatewayIpFix: Migration = {\n id: \"0006__traefik_gateway_ip_fix\",\n description: \"Fix Docker gateway IP in Traefik config (use ddev_default network)\",\n\n run(): void {\n if (!existsSync(TRAFIC_YAML)) {\n return;\n }\n\n const content = readFileSync(TRAFIC_YAML, \"utf-8\");\n const gatewayIp = getDockerGatewayIp();\n\n const updated = content.replace(\n /http:\\/\\/[\\w.]+:9876/g,\n `http://${gatewayIp}:9876`,\n );\n\n if (updated === content) {\n return;\n }\n\n writeFileSync(TRAFIC_YAML, updated, \"utf-8\");\n },\n};\n","import { exec, execSilent } from \"../steps.js\";\nimport type { Migration } from \"../types.js\";\n\n/**\n * Migration 0007: Allow trafic-agent port 9876 from Docker bridge subnets in UFW.\n *\n * UFW does not automatically allow traffic from Docker bridge networks.\n * Without this rule, ddev-router cannot reach the trafic-agent forward-auth\n * endpoint (172.18.0.1:9876), causing all auth checks to time out and traffic\n * to pass through unauthenticated.\n *\n * Condition: skip if the rule already exists.\n */\nexport const migration0007UfwDockerTraficPort: Migration = {\n id: \"0007__ufw_docker_trafic_port\",\n description: \"Allow trafic-agent port 9876 from Docker bridge subnets in UFW\",\n\n run(): void {\n const existing = execSilent(\"ufw status | grep '9876'\");\n if (existing.includes(\"9876\")) {\n return;\n }\n\n exec(\"ufw allow from 172.16.0.0/12 to any port 9876 comment 'trafic-agent from Docker'\", {\n silent: true,\n });\n },\n};\n","import { existsSync, readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport type { Migration, MigrationState, MigrationListEntry } from \"../types.js\";\nimport { migration0001DdevAptRepo } from \"./0001__ddev_apt_repo.js\";\nimport { migration0002MkcertDdevUser } from \"./0002__mkcert_ddev_user.js\";\nimport { migration0003DdevRouterBindAllInterfaces } from \"./0003__ddev_router_bind_all_interfaces.js\";\nimport { migration0004DdevHostnameSudoers } from \"./0004__ddev_hostname_sudoers.js\";\nimport { migration0005TraefikGatewayIp } from \"./0005__traefik_gateway_ip.js\";\nimport { migration0006TraefikGatewayIpFix } from \"./0006__traefik_gateway_ip_fix.js\";\nimport { migration0007UfwDockerTraficPort } from \"./0007__ufw_docker_trafic_port.js\";\n\n/** Path to the persisted migration state file */\nexport const MIGRATIONS_STATE_FILE = \"/etc/trafic/.migrations.json\";\n\n/** Ordered registry of all known migrations */\nexport const ALL_MIGRATIONS: Migration[] = [\n migration0001DdevAptRepo,\n migration0002MkcertDdevUser,\n migration0003DdevRouterBindAllInterfaces,\n migration0004DdevHostnameSudoers,\n migration0005TraefikGatewayIp,\n migration0006TraefikGatewayIpFix,\n migration0007UfwDockerTraficPort,\n];\n\n// ---------------------------------------------------------------------------\n// State helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Load the current migration state from disk.\n * Returns an empty state if the file does not exist yet.\n */\nexport function loadMigrationState(): MigrationState {\n if (!existsSync(MIGRATIONS_STATE_FILE)) {\n return { applied: [] };\n }\n\n try {\n const raw = readFileSync(MIGRATIONS_STATE_FILE, \"utf-8\");\n const parsed = JSON.parse(raw) as unknown;\n if (\n parsed !== null &&\n typeof parsed === \"object\" &&\n \"applied\" in parsed &&\n Array.isArray((parsed as { applied: unknown }).applied)\n ) {\n return parsed as MigrationState;\n }\n } catch {\n // Corrupted file — start fresh\n }\n\n return { applied: [] };\n}\n\n/**\n * Persist the migration state to disk.\n * Creates /etc/trafic/ if it does not exist.\n */\nexport function saveMigrationState(state: MigrationState): void {\n mkdirSync(\"/etc/trafic\", { recursive: true });\n writeFileSync(MIGRATIONS_STATE_FILE, JSON.stringify(state, null, 2) + \"\\n\", \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Return all migrations with their current status.\n */\nexport function listMigrations(): MigrationListEntry[] {\n const state = loadMigrationState();\n return ALL_MIGRATIONS.map((migration) => ({\n migration,\n status: state.applied.includes(migration.id) ? \"applied\" : \"pending\",\n }));\n}\n\n/**\n * Run all pending migrations and persist state after each one.\n *\n * When `dryRun` is true the runner prints what it would do without\n * executing anything or touching the state file.\n */\nexport function runPendingMigrations(dryRun = false): void {\n const state = loadMigrationState();\n const pending = ALL_MIGRATIONS.filter((m) => !state.applied.includes(m.id));\n\n if (pending.length === 0) {\n console.log(\" No pending migrations.\");\n return;\n }\n\n for (const migration of pending) {\n console.log(`\\n → \\x1b[1m${migration.id}\\x1b[0m ${migration.description}`);\n\n if (dryRun) {\n console.log(` \\x1b[90m(dry-run: skipped)\\x1b[0m`);\n continue;\n }\n\n migration.run();\n\n // Persist state immediately so a partial failure leaves a consistent state\n state.applied.push(migration.id);\n saveMigrationState(state);\n\n console.log(` \\x1b[32m✓ Applied\\x1b[0m`);\n }\n}\n\n/**\n * Mark all known migrations as applied without running them.\n *\n * Called at the end of a fresh `setup()` run: a brand-new server has\n * already been configured correctly, so migrations that fix older\n * installations are not needed.\n */\nexport function markAllMigrationsApplied(): void {\n const state = loadMigrationState();\n\n for (const migration of ALL_MIGRATIONS) {\n if (!state.applied.includes(migration.id)) {\n state.applied.push(migration.id);\n }\n }\n\n saveMigrationState(state);\n}\n","import type { SetupOptions } from \"./types.js\";\nimport { step, info, error, setDryRun, resetSteps, isRoot } from \"./steps.js\";\nimport { createDdevUser } from \"./user.js\";\nimport { installDocker, configureDocker, setupDockerPrune } from \"./docker.js\";\nimport { installSystemDeps, installDdev, configureDdev, configureTraefik } from \"./ddev.js\";\nimport { installNode, installAgent, createAgentConfig, createSystemdService } from \"./agent.js\";\nimport { hardenServer } from \"./hardening.js\";\nimport { runAudit, printAuditResults } from \"./audit.js\";\nimport { markAllMigrationsApplied } from \"./migrations/index.js\";\n\nexport * from \"./types.js\";\nexport * from \"./audit.js\";\n\n/**\n * Run the full server setup\n */\nexport async function setup(options: SetupOptions): Promise<void> {\n resetSteps();\n setDryRun(options.dryRun ?? false);\n\n console.log(\"\\n\\x1b[1m🚦 Trafic Server Setup\\x1b[0m\\n\");\n\n if (options.dryRun) {\n console.log(\"\\x1b[33m⚠ Dry-run mode: no changes will be made\\x1b[0m\\n\");\n }\n\n // Check root\n if (!isRoot() && !options.dryRun) {\n error(\"This command must be run as root\");\n console.log(\" Run: sudo trafic-agent setup ...\");\n process.exit(1);\n }\n\n info(`TLD: ${options.tld}`);\n if (options.email) {\n info(`Let's Encrypt email: ${options.email}`);\n }\n if (options.noHardening) {\n info(\"Hardening: disabled\");\n }\n\n try {\n // Step 1: Install system dependencies\n installSystemDeps();\n\n // Step 2: Create ddev user\n createDdevUser();\n\n // Step 3: Install Docker\n if (!options.noDocker) {\n installDocker();\n configureDocker();\n setupDockerPrune();\n } else {\n step(\"Install Docker\");\n info(\"Skipped (--no-docker)\");\n }\n\n // Step 4: Install DDEV\n if (!options.noDdev) {\n installDdev();\n configureDdev(options.tld, options.email);\n configureTraefik();\n } else {\n step(\"Install DDEV\");\n info(\"Skipped (--no-ddev)\");\n }\n\n // Step 5: Install Node.js\n installNode();\n\n // Step 6: Install and configure agent\n installAgent();\n createAgentConfig(options.tld, options.email);\n createSystemdService();\n\n // Step 7: Server hardening\n if (!options.noHardening) {\n const sshUsers = options.sshUsers ?? [\"ddev\"];\n hardenServer(sshUsers);\n } else {\n step(\"Server hardening\");\n info(\"Skipped (--no-hardening)\");\n }\n\n // Mark all migrations as applied — fresh servers are already up-to-date\n markAllMigrationsApplied();\n\n // Done\n console.log(\"\\n\\x1b[32m✓ Setup complete!\\x1b[0m\\n\");\n console.log(\"Next steps:\");\n console.log(` 1. Edit /etc/trafic/config.toml to configure authentication`);\n console.log(` 2. Add SSH public keys to /home/ddev/.ssh/authorized_keys`);\n console.log(` 3. Deploy your first project:`);\n console.log(` npx @studiometa/trafic-cli deploy --host=<this-server> --name=my-app`);\n console.log(`\\nYour projects will be available at https://<name>.${options.tld}`);\n } catch (err) {\n error(`Setup failed: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n}\n\n/**\n * Run security audit\n */\nexport async function audit(): Promise<void> {\n const checks = runAudit();\n printAuditResults(checks);\n\n const failed = checks.filter((c) => c.status === \"fail\").length;\n if (failed > 0) {\n process.exit(1);\n }\n}\n"],"mappings":";;;;AAIA,IAAM,uBAAuB;CAC3B;CACA;CACA;CACD;AAED,IAAM,iBAA8B;CAClC,KAAK;CACL,MAAM;CACN,QAAQ;CACR,iBAAiB;CACjB,aAAa;CACb,aAAa;CACb,mBAAmB;CACnB,MAAM;EACJ,eAAe;EACf,YAAY,EAAE;EACd,QAAQ,EAAE;EACV,WAAW,EAAE;EACb,OAAO,EAAE;EACV;CACF;;;;AAKD,SAAgB,cAAc,UAA0B;CAEtD,MAAM,QAAQ,SAAS,MADT,oCACqB;AACnC,KAAI,CAAC,MAAO,QAAO;CAEnB,MAAM,QAAQ,SAAS,MAAM,MAAM,KAAK,GAAG;CAC3C,MAAM,UAAU,SAAS,MAAM,MAAM,KAAK,GAAG;CAC7C,MAAM,UAAU,SAAS,MAAM,MAAM,KAAK,GAAG;AAE7C,SAAQ,QAAQ,OAAO,UAAU,KAAK,WAAW;;;;;AAMnD,SAAgB,WAAW,YAAkC;CAE3D,IAAI,OAAO;AACX,KAAI,CAAC,KACH,QAAO,qBAAqB,MAAM,MAAM,WAAW,EAAE,CAAC;AAGxD,KAAI,CAAC,QAAQ,CAAC,WAAW,KAAK,EAAE;AAC9B,UAAQ,KAAK,uCAAuC;AACpD,SAAO;;CAIT,MAAM,SAAS,MADC,aAAa,MAAM,QAAQ,CACd;CAG7B,MAAM,OAAO,gBAAgB,OAAO,KAAgC;AAEpE,QAAO;EACL,KAAM,OAAO,OAAkB,eAAe;EAC9C,MAAO,OAAO,QAAmB,eAAe;EAChD,QAAS,OAAO,WAAsB,eAAe;EACrD,iBACG,OAAO,qBAAgC,eAAe;EACzD,aAAc,OAAO,gBAA2B,eAAe;EAC/D,aACG,OAAO,gBAA2B,eAAe;EACpD,mBACG,OAAO,uBACR,eAAe;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