@sealant/mend 0.36.0-next.773 → 0.36.0-next.780

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.
Files changed (92) hide show
  1. package/dist/main.js +613 -84
  2. package/man/mend-accounts.1 +1 -1
  3. package/man/mend-adopt.1 +1 -1
  4. package/man/mend-attach.1 +1 -1
  5. package/man/mend-codex.1 +1 -1
  6. package/man/mend-completions.1 +1 -1
  7. package/man/mend-connect-pi.1 +1 -1
  8. package/man/mend-connect.1 +1 -1
  9. package/man/mend-continue.1 +1 -1
  10. package/man/mend-doctor.1 +1 -1
  11. package/man/mend-dotfiles-repo.1 +1 -1
  12. package/man/mend-dotfiles-sync.1 +1 -1
  13. package/man/mend-dotfiles.1 +1 -1
  14. package/man/mend-env-cluster.1 +1 -1
  15. package/man/mend-env-load.1 +1 -1
  16. package/man/mend-env-show.1 +1 -1
  17. package/man/mend-folder-create.1 +1 -1
  18. package/man/mend-folder-list.1 +1 -1
  19. package/man/mend-folder-push.1 +1 -1
  20. package/man/mend-folder-rm.1 +1 -1
  21. package/man/mend-git-author.1 +1 -1
  22. package/man/mend-help.1 +1 -1
  23. package/man/mend-invite.1 +1 -1
  24. package/man/mend-keys-init.1 +1 -1
  25. package/man/mend-keys-mode.1 +1 -1
  26. package/man/mend-keys-share.1 +1 -1
  27. package/man/mend-keys-show.1 +1 -1
  28. package/man/mend-land.1 +1 -1
  29. package/man/mend-login.1 +1 -1
  30. package/man/mend-logout.1 +1 -1
  31. package/man/mend-logs.1 +1 -1
  32. package/man/mend-man.1 +1 -1
  33. package/man/mend-members.1 +1 -1
  34. package/man/mend-memory-import.1 +1 -1
  35. package/man/mend-memory-rm.1 +1 -1
  36. package/man/mend-memory-show.1 +1 -1
  37. package/man/mend-memory.1 +1 -1
  38. package/man/mend-models.1 +1 -1
  39. package/man/mend-operator-exposure.1 +1 -1
  40. package/man/mend-operator-gate.1 +1 -1
  41. package/man/mend-operator-grant-owner.1 +1 -1
  42. package/man/mend-operator-org-create.1 +1 -1
  43. package/man/mend-operator-org-invite-owner.1 +1 -1
  44. package/man/mend-operator-org-list.1 +1 -1
  45. package/man/mend-operator-org-rename.1 +1 -1
  46. package/man/mend-operator-reset-link.1 +1 -1
  47. package/man/mend-pair.1 +3 -1
  48. package/man/mend-projects.1 +1 -1
  49. package/man/mend-pull.1 +1 -1
  50. package/man/mend-refresh.1 +1 -1
  51. package/man/mend-rejoin.1 +1 -1
  52. package/man/mend-resume.1 +1 -1
  53. package/man/mend-run.1 +1 -1
  54. package/man/mend-secrets-add.1 +1 -1
  55. package/man/mend-secrets-rm.1 +1 -1
  56. package/man/mend-secrets.1 +1 -1
  57. package/man/mend-server-logs.1 +1 -1
  58. package/man/mend-server-restart.1 +1 -1
  59. package/man/mend-server-setup.1 +19 -9
  60. package/man/mend-server-start.1 +1 -1
  61. package/man/mend-server-status.1 +1 -1
  62. package/man/mend-server-stop.1 +1 -1
  63. package/man/mend-server-upgrade.1 +1 -1
  64. package/man/mend-server.1 +1 -1
  65. package/man/mend-service-add.1 +1 -1
  66. package/man/mend-service-connect.1 +1 -1
  67. package/man/mend-service-init.1 +1 -1
  68. package/man/mend-service-list.1 +1 -1
  69. package/man/mend-service-logs.1 +1 -1
  70. package/man/mend-service-restart.1 +1 -1
  71. package/man/mend-service-run.1 +1 -1
  72. package/man/mend-service-stop.1 +1 -1
  73. package/man/mend-session-share.1 +1 -1
  74. package/man/mend-sessions.1 +1 -1
  75. package/man/mend-shell.1 +1 -1
  76. package/man/mend-skills-push.1 +1 -1
  77. package/man/mend-skills.1 +1 -1
  78. package/man/mend-snake.1 +1 -1
  79. package/man/mend-ssh-keys-remove.1 +1 -1
  80. package/man/mend-ssh-keys.1 +1 -1
  81. package/man/mend-ssh-setup.1 +1 -1
  82. package/man/mend-ssh.1 +1 -1
  83. package/man/mend-stop.1 +1 -1
  84. package/man/mend-ui.1 +1 -1
  85. package/man/mend-uninstall.1 +1 -1
  86. package/man/mend-version.1 +1 -1
  87. package/man/mend-wait.1 +1 -1
  88. package/man/mend-workspace-replace.1 +1 -1
  89. package/man/mend-worktrees-rm.1 +1 -1
  90. package/man/mend-worktrees.1 +1 -1
  91. package/man/mend.1 +1 -1
  92. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -863,7 +863,11 @@ var EDGE_CADDYFILE = [
863
863
  " }",
864
864
  " }",
865
865
  " }",
866
- "}"
866
+ "}",
867
+ "",
868
+ "# Sites beside Mend's own origin, one file each. `mend server setup --t3-gateway-origin <host>`",
869
+ "# mounts the t3code gateway's here (docs/adr/0012); none is there unless one was asked for.",
870
+ "import /etc/caddy/sites/*.caddy"
867
871
  ].join("\n") + "\n";
868
872
 
869
873
  // src/server-mirrors.ts
@@ -1292,6 +1296,8 @@ var POSTURE_COMPOSE_FILE = "compose.posture.yaml";
1292
1296
  var T3_GATEWAY_COMPOSE_FILE = "compose.t3.yaml";
1293
1297
  var T3_GATEWAY_CONTAINER_PORT = 3120;
1294
1298
  var DEFAULT_T3_GATEWAY_PORT = 3120;
1299
+ var T3_GATEWAY_CADDYFILE_NAME = "Caddyfile.t3";
1300
+ var T3_GATEWAY_CADDY_SITE = "/etc/caddy/sites/t3code-gateway.caddy";
1295
1301
  var DECLARABLE_ITEMS = [
1296
1302
  "core-private",
1297
1303
  "edge-tls",
@@ -1300,6 +1306,36 @@ var DECLARABLE_ITEMS = [
1300
1306
  ];
1301
1307
  var isDeclarableItem = (value) => DECLARABLE_ITEMS.some((item) => item === value);
1302
1308
  var publishedAddress = (address, port) => `${net2.isIP(address) === 6 ? `[${address}]` : address}:${port}`;
1309
+ var isLoopbackBindAddress = (address) => address === "::1" || address.startsWith("127.");
1310
+ var urlHostOf = (address) => address === "0.0.0.0" ? "127.0.0.1" : address === "::" ? "[::1]" : net2.isIP(address) === 6 ? `[${address}]` : address;
1311
+ var t3GatewayPlacement = (posture) => {
1312
+ const port = posture.t3GatewayPort;
1313
+ if (port === void 0) return void 0;
1314
+ const web = posture.bind ?? "127.0.0.1";
1315
+ const behindEdge = posture.edgeHost !== void 0 || posture.exposure === "public";
1316
+ const bind = behindEdge && !isLoopbackBindAddress(web) ? "127.0.0.1" : web;
1317
+ const probeUrl = `http://${urlHostOf(bind)}:${port}`;
1318
+ if (posture.edgeHost !== void 0 && posture.t3GatewayOrigin !== void 0) {
1319
+ return {
1320
+ bind,
1321
+ port,
1322
+ url: `https://${posture.t3GatewayOrigin}`,
1323
+ probeUrl,
1324
+ edgeHost: posture.t3GatewayOrigin
1325
+ };
1326
+ }
1327
+ if (isLoopbackBindAddress(bind)) return { bind, port, url: probeUrl, probeUrl };
1328
+ const named = (() => {
1329
+ try {
1330
+ return posture.appUrl === void 0 ? null : new URL(posture.appUrl).hostname;
1331
+ } catch {
1332
+ return null;
1333
+ }
1334
+ })();
1335
+ const host = named === null || named === "" ? urlHostOf(bind) : named;
1336
+ return { bind, port, url: `http://${host}:${port}`, probeUrl };
1337
+ };
1338
+ var t3GatewayBeyondMachine = (placement) => !isLoopbackBindAddress(placement.bind);
1303
1339
  var parseEdgeHost = (value) => {
1304
1340
  const host = value.trim().toLowerCase().replace(/\.$/, "");
1305
1341
  const labels = host.split(".");
@@ -1322,9 +1358,20 @@ var postureEnvironment = (posture) => {
1322
1358
  ...posture.declared === void 0 || posture.declared.length === 0 ? [] : [["MEND_EXPOSURE_DECLARED", posture.declared.join(",")]]
1323
1359
  ];
1324
1360
  };
1361
+ var t3GatewayEnvLines = (posture) => {
1362
+ const placement = t3GatewayPlacement(posture);
1363
+ if (placement === void 0) return [];
1364
+ return [
1365
+ `MEND_T3_GATEWAY_PORT=${placement.port}`,
1366
+ `MEND_T3_GATEWAY_BIND_HOST=${net2.isIP(placement.bind) === 6 ? `[${placement.bind}]` : placement.bind}`,
1367
+ `MEND_T3_GATEWAY_PUBLISHED=${publishedAddress(placement.bind, placement.port)}`,
1368
+ `MEND_T3_GATEWAY_URL=${placement.url}`,
1369
+ ...placement.edgeHost === void 0 ? [] : [`MEND_T3_GATEWAY_EDGE_HOST=${placement.edgeHost}`]
1370
+ ];
1371
+ };
1325
1372
  var postureEnvLines = (posture) => [
1326
1373
  ...posture.edgeHost === void 0 ? [] : [`MEND_EDGE_HOST=${posture.edgeHost}`],
1327
- ...posture.t3GatewayPort === void 0 ? [] : [`MEND_T3_GATEWAY_PORT=${posture.t3GatewayPort}`],
1374
+ ...t3GatewayEnvLines(posture),
1328
1375
  ...postureEnvironment(posture).map(([key, value]) => `${key}=${value}`)
1329
1376
  ];
1330
1377
  var renderPostureOverlay = (posture) => {
@@ -1347,25 +1394,66 @@ var renderPostureOverlay = (posture) => {
1347
1394
  var T3_GATEWAY_VOLUME = "mend-t3-gateway";
1348
1395
  var T3_GATEWAY_IMAGE_LABEL = "dev.sealant.mend.t3-gateway";
1349
1396
  var T3_GATEWAY_STATE_DIR = "/opt/mend-t3-gateway/state";
1397
+ var required = (key) => `\${${key}:?set ${key} in server.env}`;
1350
1398
  var renderT3GatewayOverlay = (posture) => {
1351
- if (posture.t3GatewayPort === void 0) return void 0;
1399
+ const placement = t3GatewayPlacement(posture);
1400
+ if (placement === void 0) return void 0;
1352
1401
  return [
1353
1402
  "# Written by mend server setup --t3-gateway: the t3code gateway (docs/adr/0012), its own",
1354
- "# listener beside Mend's, published on loopback only. Reaching it from elsewhere is an",
1355
- "# exposure the operator declares (docs/adr/0004). mend server setup --no-t3-gateway removes it.",
1403
+ "# listener beside Mend's, published on the address Mend's web port is published on. Every device",
1404
+ "# pairs through Mend. mend server setup --no-t3-gateway removes it.",
1356
1405
  "services:",
1357
1406
  " mend:",
1358
1407
  " environment:",
1359
1408
  ' MEND_T3_GATEWAY_ENABLED: "true"',
1409
+ " # What the exposure report, mend pair and mend doctor say about it.",
1410
+ ` MEND_T3_GATEWAY_PUBLISHED: ${required("MEND_T3_GATEWAY_PUBLISHED")}`,
1411
+ ` MEND_T3_GATEWAY_URL: ${required("MEND_T3_GATEWAY_URL")}`,
1360
1412
  " ports:",
1361
- ` - "127.0.0.1:\${MEND_T3_GATEWAY_PORT:?set MEND_T3_GATEWAY_PORT in server.env}:${T3_GATEWAY_CONTAINER_PORT}"`,
1413
+ ` - "${required("MEND_T3_GATEWAY_BIND_HOST")}:${required("MEND_T3_GATEWAY_PORT")}:${T3_GATEWAY_CONTAINER_PORT}"`,
1362
1414
  " volumes:",
1363
1415
  ` - ${T3_GATEWAY_VOLUME}:${T3_GATEWAY_STATE_DIR}`,
1416
+ ...placement.edgeHost === void 0 ? [] : [
1417
+ " # The edge serves the gateway on its own origin (--t3-gateway-origin): Caddy gets a",
1418
+ " # certificate for it once its DNS points here, and reaches the gateway on the edge network.",
1419
+ " edge:",
1420
+ " environment:",
1421
+ ` MEND_T3_GATEWAY_EDGE_HOST: ${required("MEND_T3_GATEWAY_EDGE_HOST")}`,
1422
+ " volumes:",
1423
+ ` - ./${T3_GATEWAY_CADDYFILE_NAME}:${T3_GATEWAY_CADDY_SITE}:ro`
1424
+ ],
1364
1425
  "volumes:",
1365
1426
  ` ${T3_GATEWAY_VOLUME}:`,
1366
1427
  ""
1367
1428
  ].join("\n");
1368
1429
  };
1430
+ var T3_GATEWAY_CADDYFILE = [
1431
+ "# Written by mend server setup --t3-gateway-origin: the t3code gateway (docs/adr/0012) on an",
1432
+ "# origin of its own. A t3code client always uses a server's root path, so it cannot share Mend's.",
1433
+ "{$MEND_T3_GATEWAY_EDGE_HOST} {",
1434
+ " encode zstd gzip",
1435
+ "",
1436
+ ` reverse_proxy mend:${T3_GATEWAY_CONTAINER_PORT} {`,
1437
+ " # The gateway's socket and its streams are long-lived: never buffer them.",
1438
+ " flush_interval -1",
1439
+ " }",
1440
+ "",
1441
+ " log {",
1442
+ " output stdout",
1443
+ " format filter {",
1444
+ " wrap json",
1445
+ " fields {",
1446
+ " request>uri query {",
1447
+ " replace wsTicket REDACTED",
1448
+ " replace token REDACTED",
1449
+ " }",
1450
+ " request>headers>Referer delete",
1451
+ " }",
1452
+ " }",
1453
+ " }",
1454
+ "}",
1455
+ ""
1456
+ ].join("\n");
1369
1457
  var composeOverlays = (posture) => [
1370
1458
  ...posture.edgeHost === void 0 ? [] : [EDGE_COMPOSE_FILE],
1371
1459
  ...renderPostureOverlay(posture) === void 0 ? [] : [POSTURE_COMPOSE_FILE],
@@ -1392,11 +1480,17 @@ var healthPosture = (body) => {
1392
1480
  exposure: typeof declared === "string" && isExposure(declared) && typeof open === "number" && typeof unobservable === "number" ? { declared, open, unobservable } : null
1393
1481
  };
1394
1482
  };
1483
+ var t3GatewayDeclaredLines = (posture) => {
1484
+ const placement = t3GatewayPlacement(posture);
1485
+ if (placement === void 0) return [];
1486
+ const published = publishedAddress(placement.bind, placement.port);
1487
+ return [
1488
+ placement.edgeHost !== void 0 ? `t3code gateway \xB7 on \xB7 served by the edge at ${placement.url} \xB7 its port published on ${published} only` : t3GatewayBeyondMachine(placement) ? `t3code gateway \xB7 on \xB7 published on ${published}, where Mend's web port is \xB7 T3 Code's Remote link takes ${placement.url}` : `t3code gateway \xB7 on \xB7 published on ${published} only \xB7 reached from this machine${posture.edgeHost === void 0 ? "" : "; mend server setup --t3-gateway-origin <host> serves it through the edge"}`
1489
+ ];
1490
+ };
1395
1491
  var declaredPostureLines = (posture) => [
1396
1492
  ...posture.edgeHost === void 0 ? [] : [`edge \xB7 ${posture.edgeHost} \xB7 ${EDGE_IMAGE} on 80 and 443 \xB7 Mend's own port on loopback`],
1397
- ...posture.t3GatewayPort === void 0 ? [] : [
1398
- `t3code gateway \xB7 on \xB7 127.0.0.1:${posture.t3GatewayPort} \xB7 loopback only \xB7 reaching it from elsewhere is an exposure you declare`
1399
- ],
1493
+ ...t3GatewayDeclaredLines(posture),
1400
1494
  `exposure \xB7 declared ${posture.exposure ?? "private"}${posture.exposure === void 0 ? " \xB7 the default, not set on this install" : ""}`,
1401
1495
  `tenancy \xB7 declared ${posture.tenancy ?? "single"}${posture.tenancy === void 0 ? " \xB7 the default, not set on this install" : ""}`,
1402
1496
  ...posture.sshBind === void 0 || posture.sshPort === void 0 ? [] : [
@@ -2333,7 +2427,8 @@ var COMMANDS = [
2333
2427
  summary: "pair a phone or a second machine",
2334
2428
  synopsis: ["[--url <base url>]"],
2335
2429
  description: [
2336
- "Prints a QR code, the code itself, and the URL this server is reached at. The pairing is for one device, once, and expires after 10 minutes."
2430
+ "Prints a QR code, the code itself, and the URL this server is reached at. The pairing is for one device, once, and expires after 10 minutes.",
2431
+ "With the server's T3 Code gateway on, it also prints the gateway's address: in T3 Code, add a Remote link with that address and the code, or paste the link it prints, which carries both. The same code pairs T3 Code or the Mend app, once. T3 Code's SSH mode is not for Mend: it starts T3 Code's own server on the other machine."
2337
2432
  ],
2338
2433
  options: [
2339
2434
  { flag: "--url <base url>", text: "the address the other device should use for this server" }
@@ -3298,16 +3393,16 @@ var COMMANDS = [
3298
3393
  summary: "install or change the local Mend server, guided",
3299
3394
  synopsis: [
3300
3395
  "",
3301
- "[--yes] [--context <name>] [--version <version|latest>] [--bind <ip>] [--ssh-bind <ip>] [--url <origin>] [--origin <origin>...] [--port <n>] [--ssh-port <n>] [--edge <host> | --no-edge] [--exposure <loopback|private|public>] [--tenancy <single|multi>] [--declare <item>...] [--undeclare <item>...] [--t3-gateway [--t3-gateway-port <n>] | --no-t3-gateway] [--npm-mirror | --no-npm-mirror] [--npm-mirror-max-size <size>] [--docker-mirror | --no-docker-mirror] [--docker-mirror-max-size <size>] [--docker-hub-username <name> --docker-hub-token-stdin --docker-hub-public-only | --no-docker-hub-login] [--docker-socket <path>] [--assets-dir <dir>] [--offline] [--allow-userns | --no-allow-userns]"
3396
+ "[--yes] [--context <name>] [--version <version|latest>] [--bind <ip>] [--ssh-bind <ip>] [--url <origin>] [--origin <origin>...] [--port <n>] [--ssh-port <n>] [--edge <host> | --no-edge] [--exposure <loopback|private|public>] [--tenancy <single|multi>] [--declare <item>...] [--undeclare <item>...] [--t3-gateway [--t3-gateway-port <n>] [--t3-gateway-origin <host> | --no-t3-gateway-origin] | --no-t3-gateway] [--npm-mirror | --no-npm-mirror] [--npm-mirror-max-size <size>] [--docker-mirror | --no-docker-mirror] [--docker-mirror-max-size <size>] [--docker-hub-username <name> --docker-hub-token-stdin --docker-hub-public-only | --no-docker-hub-login] [--docker-socket <path>] [--assets-dir <dir>] [--offline] [--allow-userns | --no-allow-userns]"
3302
3397
  ],
3303
3398
  description: [
3304
- "On a terminal with no flags, setup asks its questions in plain words, one at a time: how people reach this Mend (just this machine, your private network or Tailscale, or the public internet with HTTPS), whether VS Code Remote-SSH reaches it from other machines, the T3 Code gateway, the mirrors, and one organization or several. It looks before it asks and says what it observed: Tailscale's name and address and what Tailscale Serve forwards, where your domain resolves, and whether ports 80 and 443 are taken. It never asks for an address to bind: that follows from the answers. On an existing install it shows what is saved and lets you keep it, change one thing, or go through every question. It ends with what changes, in words, and the same command with flags; nothing applies until you say yes.",
3305
- "Flags are for scripts and CI, and teach what the questions do. Each changes only what it names; everything else is kept from the saved install, so mend server setup --t3-gateway turns the gateway on and nothing more. When there is an install, a run with flags says what it changes. With no terminal and no flags, a fresh install is refused rather than guessed: --yes takes the defaults. --context and --docker-socket choose the Docker engine and answer no question, so with only those (on a Mac with Docker Desktop and OrbStack, --context orbstack) setup still asks its questions. A fresh install without --context takes DOCKER_CONTEXT, as docker does; an existing one stays on the context its data is on.",
3399
+ "On a terminal with no flags, setup asks its questions in plain words, one at a time: on a fresh install with more than one Docker engine answering here (Docker Desktop beside OrbStack, colima, Rancher Desktop, a rootless Docker), which one Mend runs in, the current context in brackets; then how people reach this Mend (just this machine, your private network or Tailscale, or the public internet with HTTPS), whether VS Code Remote-SSH reaches it from other machines, the T3 Code gateway, the mirrors, and one organization or several. It looks before it asks and says what it observed: Tailscale's name and address and what Tailscale Serve forwards, where your domain resolves, and whether ports 80 and 443 are taken. It never asks for an address to bind: that follows from the answers. On an existing install it shows what is saved and lets you keep it, change one thing, or go through every question. It ends with what changes, in words, and the same command with flags; nothing applies until you say yes.",
3400
+ "Flags are for scripts and CI, and teach what the questions do. Each changes only what it names; everything else is kept from the saved install, so mend server setup --t3-gateway turns the gateway on and nothing more. When there is an install, a run with flags says what it changes. With no terminal and no flags, a fresh install is refused rather than guessed: --yes takes the defaults. --context and --docker-socket choose the Docker engine and answer only that question, so with only those (on a Mac with Docker Desktop and OrbStack, --context orbstack) setup still asks the rest. A fresh install without --context takes DOCKER_CONTEXT, as docker does, and with --yes or no terminal the current context, naming the others; an existing one stays on the context its data is on, and running Mend in another engine is a new install (mend uninstall --server, then mend server setup there).",
3306
3401
  "Before anything is pulled, setup checks that Mend's web and SSH ports are free where they are to be published, and says what holds one that is not: another Mend, with its version, or something else. On a terminal it offers the next free port; with flags it refuses and names --port or --ssh-port. After starting, it reads health until this install answers: its version, and the instance id the server reports, so another Mend on the same port is said as one, never taken for this one.",
3307
3402
  "Checks a local Unix-socket Docker context and the Compose plugin, downloads the compose and Postgres initialization assets for one Mend release, preserves existing data and secrets, and starts the server. Re-running repairs the same pinned version. A changed --version is refused; use mend server upgrade. Updating this CLI never updates an existing server pin.",
3308
3403
  "The default listens only on localhost at http://localhost:3105. Non-local access requires both --bind and --url. Every extra browser origin must be named with --origin; setup never guesses from the request Host header or network interfaces. A fresh install refuses a public --bind address: until the first account exists, registration is open to whoever reaches it first. On an existing install, setup says when Mend's port or workspace SSH is published on a public address while the exposure is not public. The questions offer only private addresses (a tailnet, a LAN or VPN, carrier-grade NAT space) for a private network.",
3309
3404
  "--edge <host> runs a TLS edge in front of Mend: Caddy on ports 80 and 443 of every interface, which obtains and renews a certificate for the host and proxies to Mend's web tier. Mend's own port stays on loopback and the browser origin is https://<host>. The edge's compose overlay and Caddyfile are written into the generation beside compose.yaml, so start, restart and upgrade run them every time. --no-edge takes it away again, and the edge's container with it. A fresh install cannot start with the edge: until the first account exists, registration is open to whoever reaches the origin first, so set up on localhost, create the account, then add the edge.",
3310
- "--t3-gateway turns on the t3code gateway (docs/adr/0012): t3code's desktop, mobile and web clients add it as an environment, pair with a code from mend pair, and see this Mend's projects and sessions. It runs in the Mend container, confined to a root and a uid of its own, on a listener of its own published on 127.0.0.1 only (port 3120, or --t3-gateway-port): reaching it from another machine is an exposure you put in front of it and declare. Setup refuses it on a Mend image that has no gateway, and says whether it answered. It is kept across reruns and upgrades; --no-t3-gateway turns it off, and its state stays in its own volume, mend-t3-gateway. Off, nothing of it runs.",
3405
+ "--t3-gateway turns on the t3code gateway (docs/adr/0012): t3code's desktop, mobile and web clients add it as an environment, pair with a code from mend pair, and see this Mend's projects and sessions. It runs in the Mend container, confined to a root and a uid of its own, on a listener of its own (port 3120, or --t3-gateway-port) published where Mend's web port is: on 127.0.0.1 for just this machine, on the tailnet or LAN address for a private network, so T3 Code reaches it as it reaches Mend, with no tunnel. Every device pairs through Mend wherever it is published. Behind the edge its port stays on 127.0.0.1, and --t3-gateway-origin <host> has the edge serve it on a host of its own, over HTTPS: a t3code client always uses a server's root path, so it cannot sit under Mend's origin. That host's DNS points where the edge's does; setup says where it resolves. Setup refuses it on a Mend image that has no gateway, and says whether it answered. It is kept across reruns and upgrades; --no-t3-gateway turns it off, and its state stays in its own volume, mend-t3-gateway. Off, nothing of it runs.",
3311
3406
  "--exposure declares how the instance is reached, and --tenancy whether one organization or many use it. Both are written into the generation and kept across reruns and upgrades. public needs the edge and an existing first account. With multi, or with public, the multi mode gate's settings follow: MEND_SOURCE_POLICY=tenant and MEND_CAPTURE_REQUIRE_SIZES=true, and public sets MEND_URL_BEARERS=refuse. The server still decides whether it starts, and mend server status shows what it reports.",
3312
3407
  "Two mirrors run beside Mend unless turned off: an npm mirror (nginx caching npmjs.org, capped at 10g by default, least recently used out) and a Docker mirror (a pull-through cache of Docker Hub, capped at 20g by default: over the cap its cache is cleared). Both leave 5g free on their disk: below that, nginx evicts and the Docker mirror pauses, and sessions pull from Docker Hub directly. Neither publishes a host port. Sessions install npm packages and pull Docker Hub images through them; a project's own npm settings win, and a mirror that is down sends sessions upstream instead. Both are kept across reruns and upgrades, and an upgrade adds them to an install from before them. The Docker mirror pulls anonymously unless given a Docker Hub login: --docker-hub-username with the access token piped on standard input, kept in server.env only. The mirror has no login of its own, so every session that reaches it can pull whatever that token can read: setup takes a login only with --docker-hub-public-only, your statement that the token's access permission is Public Repo Read-only. Mend cannot check a token's scope.",
3313
3408
  "Before its other questions and before it pulls the release, setup reads the Docker host's kernel, through the few megabytes of busybox every install needs anyway. Each workspace runs its own rootless Docker, which needs unprivileged user namespaces; Ubuntu 23.10 and later (24.04 LTS included) refuse them by default, and then no session can start. On a terminal setup asks to allow them: on a yes it writes the setting to /etc/sysctl.d/60-mend-rootless-docker.conf on the Docker host and applies it, through a short privileged container on the Docker socket it already uses, then reads the kernel again. That lifts the restriction for the whole host; the file says on its first lines that setup wrote it and what it replaced, so mend uninstall --all removes it and puts that back. On a no, or on a rootless daemon, it prints the command to run on the host, and repeats it as its last line. Without a terminal or with --yes, it says to re-run with --allow-userns, so that setup writes the file and mend uninstall can undo it; the command is the other way, and a file written by hand stays on uninstall. --allow-userns and --no-allow-userns answer for a script.",
@@ -3322,7 +3417,7 @@ var COMMANDS = [
3322
3417
  },
3323
3418
  {
3324
3419
  flag: "--context <name>",
3325
- text: "local Docker context to persist; the global context is unchanged. Answers no question. Default: DOCKER_CONTEXT on a fresh install, else the saved one"
3420
+ text: "local Docker context to persist; the global context is unchanged. Answers the engine question. Default: DOCKER_CONTEXT on a fresh install, else the saved one"
3326
3421
  },
3327
3422
  {
3328
3423
  flag: "--version <v>",
@@ -3350,13 +3445,21 @@ var COMMANDS = [
3350
3445
  { flag: "--no-edge", text: "take a saved edge away; the origin returns to http://localhost" },
3351
3446
  {
3352
3447
  flag: "--t3-gateway",
3353
- text: "run the t3code gateway, published on 127.0.0.1:3120 only; kept across reruns and upgrades"
3448
+ text: "run the t3code gateway on port 3120, published where Mend's web port is; kept across reruns and upgrades"
3354
3449
  },
3355
3450
  {
3356
3451
  flag: "--t3-gateway-port <n>",
3357
- text: "the gateway's port on 127.0.0.1; implies --t3-gateway"
3452
+ text: "the gateway's port; implies --t3-gateway"
3358
3453
  },
3359
3454
  { flag: "--no-t3-gateway", text: "turn the t3code gateway off; its state stays" },
3455
+ {
3456
+ flag: "--t3-gateway-origin <host>",
3457
+ text: "with the edge: serve the gateway over HTTPS on this host of its own; its DNS points where the edge's does. Implies --t3-gateway"
3458
+ },
3459
+ {
3460
+ flag: "--no-t3-gateway-origin",
3461
+ text: "the edge stops serving the gateway; it stays on, on 127.0.0.1"
3462
+ },
3360
3463
  {
3361
3464
  flag: "--exposure <v>",
3362
3465
  text: "declare loopback, private or public; kept across reruns and upgrades. public needs --edge and an existing first account"
@@ -3427,7 +3530,11 @@ var COMMANDS = [
3427
3530
  },
3428
3531
  {
3429
3532
  command: "mend server setup --t3-gateway",
3430
- text: "on an existing install: turn the T3 Code gateway on, and keep everything else"
3533
+ text: "on an existing install: turn the T3 Code gateway on where Mend's web port is published, and keep everything else"
3534
+ },
3535
+ {
3536
+ command: "mend server setup --t3-gateway-origin t3.mend.example.com",
3537
+ text: "behind the edge: serve the T3 Code gateway at https://t3.mend.example.com"
3431
3538
  },
3432
3539
  {
3433
3540
  command: "mend server setup --yes",
@@ -4563,6 +4670,31 @@ var exposureCheck = (exposure) => {
4563
4670
  fix: plainBeyondMachine ? "serve it over https: on the server's machine, mend server setup --edge <domain>, or mend server setup --url https://<origin> behind HTTPS you run" : gateOpen === 0 ? null : "mend operator exposure"
4564
4671
  };
4565
4672
  };
4673
+ var t3GatewayCheck = (gateway) => {
4674
+ if (gateway.url === null)
4675
+ return {
4676
+ label: "t3code gateway",
4677
+ state: "todo",
4678
+ detail: `on${gateway.published === null ? "" : ` \xB7 published on ${gateway.published}`} \xB7 the server does not say its address`,
4679
+ fix: "on the server's machine, mend server setup --t3-gateway"
4680
+ };
4681
+ let host = "";
4682
+ try {
4683
+ host = new URL(gateway.url).hostname;
4684
+ } catch {
4685
+ }
4686
+ const onMachine = host === "localhost" || host === "[::1]" || host.startsWith("127.");
4687
+ return {
4688
+ label: "t3code gateway",
4689
+ state: "ok",
4690
+ detail: [
4691
+ gateway.url,
4692
+ ...gateway.published === null ? [] : [`published on ${gateway.published}`],
4693
+ onMachine ? "reached on the server's machine only" : "T3 Code's Remote link takes it, with a code from mend pair"
4694
+ ].join(" \xB7 "),
4695
+ fix: null
4696
+ };
4697
+ };
4566
4698
  var userNamespacesCheck = (observed) => observed.allowed ? {
4567
4699
  label: "workspaces",
4568
4700
  state: "ok",
@@ -4796,6 +4928,8 @@ var runChecks = async (config, probes) => {
4796
4928
  checks.push(exposure === void 0 ? notChecked("exposure") : exposureCheck(exposure));
4797
4929
  const userNamespaces = machine === null || machine.value === null ? void 0 : machine.value.userNamespaces;
4798
4930
  if (userNamespaces !== void 0) checks.push(userNamespacesCheck(userNamespaces));
4931
+ const t3Gateway = machine === null || machine.value === null ? void 0 : machine.value.t3Gateway;
4932
+ if (t3Gateway !== void 0) checks.push(t3GatewayCheck(t3Gateway));
4799
4933
  if (probes.dockerStop !== void 0 && probes.onPath("docker")) {
4800
4934
  checks.push(dockerStopCheck(probes.dockerStop(local?.dockerContext ?? null)));
4801
4935
  }
@@ -5646,6 +5780,26 @@ var groupCode = (code) => {
5646
5780
  };
5647
5781
  var pairingLink = (url, code) => `mend://pair?u=${encodeURIComponent(url)}&c=${code}`;
5648
5782
  var chooseUrl = (urls, override) => override === null ? urls[0] ?? null : urls.includes(override) ? override : null;
5783
+ var t3PairingLink = (url, code) => `${url.replace(/\/+$/, "")}/pair#token=${code}`;
5784
+ var isLoopbackUrl2 = (url) => {
5785
+ try {
5786
+ const host = new URL(url).hostname;
5787
+ return host === "localhost" || host === "[::1]" || host.startsWith("127.");
5788
+ } catch {
5789
+ return false;
5790
+ }
5791
+ };
5792
+ var t3GatewayLines = (gateway, code) => {
5793
+ if (gateway === null) return [];
5794
+ if (gateway.url === null)
5795
+ return [
5796
+ ` t3 code the gateway is on${gateway.published === null ? "" : ` at ${gateway.published}`}; the server does not say its address (MEND_T3_GATEWAY_URL)`
5797
+ ];
5798
+ return [
5799
+ ` t3 code ${gateway.url}${isLoopbackUrl2(gateway.url) ? " \xB7 on the server's machine only" : ""}`,
5800
+ ` in T3 Code, add a Remote link with this address and the code, or paste ${t3PairingLink(gateway.url, code)}`
5801
+ ];
5802
+ };
5649
5803
  var minutesUntil = (expiresAt, now = Date.now()) => {
5650
5804
  const at = Date.parse(expiresAt);
5651
5805
  if (Number.isNaN(at)) return null;
@@ -5656,7 +5810,7 @@ var renderQr = async (text) => {
5656
5810
  const options = { type: "terminal", small: true };
5657
5811
  return (await toQrString(text, options)).trimEnd();
5658
5812
  };
5659
- var pairCommand = async (args, api2) => {
5813
+ var pairCommand = async (args, api2, t3Gateway = async () => null) => {
5660
5814
  const pairing = await api2("POST", "/me/devices/pairings");
5661
5815
  const override = takeFlagValue(args, "--url");
5662
5816
  if (args.includes("--url") && override === null) {
@@ -5675,6 +5829,7 @@ var pairCommand = async (args, api2) => {
5675
5829
  say2(
5676
5830
  ` ${dim2("expires")} ${minutes === null ? pairing.expiresAt : `in ${minutes} min`} ${dim2("\xB7 one device, once")}`
5677
5831
  );
5832
+ for (const line of t3GatewayLines(await t3Gateway(), pairing.code)) say2(line);
5678
5833
  say2("");
5679
5834
  say2(dim2(" scan it in the Mend app, or enter the url and the code there by hand"));
5680
5835
  say2(dim2(" the app is apps/mobile \u2014 build it yourself; it is not published yet"));
@@ -7077,7 +7232,8 @@ var optionalFileKeys = [
7077
7232
  "mirrors",
7078
7233
  "npmMirrorConf",
7079
7234
  "dockerMirrorGuard",
7080
- "t3Gateway"
7235
+ "t3Gateway",
7236
+ "t3Caddyfile"
7081
7237
  ];
7082
7238
  var fileNames = {
7083
7239
  identity: "identity.env",
@@ -7091,7 +7247,8 @@ var fileNames = {
7091
7247
  mirrors: "compose.mirrors.yaml",
7092
7248
  npmMirrorConf: "npm-mirror.conf",
7093
7249
  dockerMirrorGuard: "docker-mirror-guard.sh",
7094
- t3Gateway: "compose.t3.yaml"
7250
+ t3Gateway: "compose.t3.yaml",
7251
+ t3Caddyfile: "Caddyfile.t3"
7095
7252
  };
7096
7253
  var fileModes = {
7097
7254
  identity: 384,
@@ -7105,7 +7262,8 @@ var fileModes = {
7105
7262
  mirrors: 384,
7106
7263
  npmMirrorConf: 420,
7107
7264
  dockerMirrorGuard: 420,
7108
- t3Gateway: 384
7265
+ t3Gateway: 384,
7266
+ t3Caddyfile: 420
7109
7267
  };
7110
7268
  var allFiles = (files) => [...fileKeys, ...optionalFileKeys].map((key) => [key, files[key]]);
7111
7269
  var parseLockOwner = (raw) => {
@@ -7238,6 +7396,7 @@ var readActive = (paths) => {
7238
7396
  const npmMirrorConf = optional("npmMirrorConf");
7239
7397
  const dockerMirrorGuard = optional("dockerMirrorGuard");
7240
7398
  const t3Gateway = optional("t3Gateway");
7399
+ const t3Caddyfile = optional("t3Caddyfile");
7241
7400
  const files = {
7242
7401
  identity: fs14.readFileSync(path15.join(directory, fileNames.identity), "utf8"),
7243
7402
  config: fs14.readFileSync(path15.join(directory, fileNames.config), "utf8"),
@@ -7250,7 +7409,8 @@ var readActive = (paths) => {
7250
7409
  ...mirrors === void 0 ? {} : { mirrors },
7251
7410
  ...npmMirrorConf === void 0 ? {} : { npmMirrorConf },
7252
7411
  ...dockerMirrorGuard === void 0 ? {} : { dockerMirrorGuard },
7253
- ...t3Gateway === void 0 ? {} : { t3Gateway }
7412
+ ...t3Gateway === void 0 ? {} : { t3Gateway },
7413
+ ...t3Caddyfile === void 0 ? {} : { t3Caddyfile }
7254
7414
  };
7255
7415
  if (readIdentity(paths) !== files.identity) {
7256
7416
  throw new ServerStoreError(
@@ -7958,7 +8118,7 @@ var isPrivateNetworkAddress = (address) => {
7958
8118
  var isLoopbackName = (hostname8) => hostname8 === "localhost" || hostname8 === "[::1]" || isLoopbackAddress(hostname8);
7959
8119
  var sameSet = (left, right) => left.length === right.length && left.every((item) => right.includes(item));
7960
8120
  var sameMirrors = (left, right) => left.npm?.maxSize === right.npm?.maxSize && left.npm === null === (right.npm === null) && left.docker === null === (right.docker === null) && left.docker?.maxSize === right.docker?.maxSize && dockerMirrorLogin(left.docker) === dockerMirrorLogin(right.docker);
7961
- var sameSettings = (left, right) => left.bind === right.bind && left.sshBind === right.sshBind && left.appUrl === right.appUrl && sameSet(left.allowedOrigins, right.allowedOrigins) && left.appPort === right.appPort && left.sshPort === right.sshPort && left.edgeHost === right.edgeHost && left.exposure === right.exposure && left.tenancy === right.tenancy && sameSet(left.declared, right.declared) && left.t3GatewayPort === right.t3GatewayPort && sameMirrors(left.mirrors, right.mirrors);
8121
+ var sameSettings = (left, right) => left.bind === right.bind && left.sshBind === right.sshBind && left.appUrl === right.appUrl && sameSet(left.allowedOrigins, right.allowedOrigins) && left.appPort === right.appPort && left.sshPort === right.sshPort && left.edgeHost === right.edgeHost && left.exposure === right.exposure && left.tenancy === right.tenancy && sameSet(left.declared, right.declared) && left.t3GatewayPort === right.t3GatewayPort && left.t3GatewayOrigin === right.t3GatewayOrigin && sameMirrors(left.mirrors, right.mirrors);
7962
8122
  var flagsFor = (before, after) => {
7963
8123
  const flags = [];
7964
8124
  if (after.edgeHost !== before.edgeHost)
@@ -7986,10 +8146,14 @@ var flagsFor = (before, after) => {
7986
8146
  }
7987
8147
  if (after.t3GatewayPort !== before.t3GatewayPort) {
7988
8148
  if (after.t3GatewayPort === void 0) flags.push("--no-t3-gateway");
7989
- else if (before.t3GatewayPort === void 0 && after.t3GatewayPort === DEFAULT_T3_GATEWAY_PORT)
7990
- flags.push("--t3-gateway");
7991
- else flags.push("--t3-gateway-port", String(after.t3GatewayPort));
8149
+ else if (before.t3GatewayPort === void 0 && after.t3GatewayPort === DEFAULT_T3_GATEWAY_PORT) {
8150
+ if (after.t3GatewayOrigin === void 0) flags.push("--t3-gateway");
8151
+ } else flags.push("--t3-gateway-port", String(after.t3GatewayPort));
7992
8152
  }
8153
+ if (after.t3GatewayPort !== void 0 && after.t3GatewayOrigin !== before.t3GatewayOrigin)
8154
+ flags.push(
8155
+ ...after.t3GatewayOrigin === void 0 ? ["--no-t3-gateway-origin"] : ["--t3-gateway-origin", after.t3GatewayOrigin]
8156
+ );
7993
8157
  const npmBefore = before.mirrors.npm;
7994
8158
  const npmAfter = after.mirrors.npm;
7995
8159
  if (npmAfter === null && npmBefore !== null) flags.push("--no-npm-mirror");
@@ -8026,7 +8190,20 @@ var sshOf = (settings) => {
8026
8190
  const at = publishedAddress(sshAt(settings), settings.sshPort);
8027
8191
  return sshBeyondThisMachine(settings) ? `published on ${at}, beyond this machine` : `this machine only (${at})`;
8028
8192
  };
8029
- var t3Of = (settings) => settings.t3GatewayPort === void 0 ? "off" : `on, at 127.0.0.1:${settings.t3GatewayPort}`;
8193
+ var t3PlacementOf = (settings, port = settings.t3GatewayPort) => t3GatewayPlacement({
8194
+ bind: settings.bind,
8195
+ appUrl: settings.appUrl,
8196
+ ...settings.edgeHost === void 0 ? {} : { edgeHost: settings.edgeHost },
8197
+ ...settings.exposure === void 0 ? {} : { exposure: settings.exposure },
8198
+ ...port === void 0 ? {} : { t3GatewayPort: port },
8199
+ ...settings.t3GatewayOrigin === void 0 ? {} : { t3GatewayOrigin: settings.t3GatewayOrigin }
8200
+ });
8201
+ var t3Of = (settings) => {
8202
+ const placement = t3PlacementOf(settings);
8203
+ if (placement === void 0) return "off";
8204
+ const published = publishedAddress(placement.bind, placement.port);
8205
+ return placement.edgeHost !== void 0 ? `on, at ${placement.url} through the edge (its port on ${published})` : t3GatewayBeyondMachine(placement) ? `on, at ${placement.url} (published on ${published})` : `on, at ${placement.url}, this machine only`;
8206
+ };
8030
8207
  var tenancyOf = (settings) => settings.tenancy === "multi" ? "several organizations (multi)" : "one organization (single)";
8031
8208
  var mirrorsOf = (mirrors) => {
8032
8209
  const login2 = dockerMirrorLogin(mirrors.docker);
@@ -8162,6 +8339,39 @@ var typed = async (io, question, preferred, parse) => {
8162
8339
  io.write(` ${parsed.refused}`);
8163
8340
  }
8164
8341
  };
8342
+ var GUIDE_INTRO = "Mend server setup. A few questions; enter takes the answer in brackets.";
8343
+ var MEND_THERE = {
8344
+ running: "a Mend server runs here",
8345
+ volumes: "Mend volumes from an earlier install are here",
8346
+ none: "nothing of Mend's here yet"
8347
+ };
8348
+ var engineNote = (engine) => [
8349
+ engine.what,
8350
+ `socket ${engine.socket}`,
8351
+ ...engine.mend === null ? [] : [MEND_THERE[engine.mend]]
8352
+ ].join(" \xB7 ");
8353
+ var chooseDockerEngine = async (io, engines, preferred) => {
8354
+ const index = engines.findIndex((engine) => engine.context === preferred);
8355
+ io.write("");
8356
+ io.write(
8357
+ "Mend's server, its data and every session's workspace live in the Docker engine you choose, and stay there: another engine later means a new install."
8358
+ );
8359
+ try {
8360
+ return await choose(
8361
+ io,
8362
+ "Which Docker should Mend run in?",
8363
+ engines.map((engine) => ({
8364
+ label: `${engine.context}${engine.current ? " (the current context)" : ""}`,
8365
+ detail: engineNote(engine),
8366
+ value: engine.context
8367
+ })),
8368
+ index < 0 ? 0 : index
8369
+ );
8370
+ } catch (cause) {
8371
+ if (cause instanceof GuideStopped) return null;
8372
+ throw cause;
8373
+ }
8374
+ };
8165
8375
  var reachModeOf = (settings) => settings.edgeHost !== void 0 ? "public" : isLoopbackAddress(settings.bind) ? "machine" : "network";
8166
8376
  var without = (declared, item) => declared.filter((entry) => entry !== item);
8167
8377
  var withItem = (declared, item) => declared.includes(item) ? declared : [...declared, item];
@@ -8196,6 +8406,7 @@ var toThisMachine = (settings) => ({
8196
8406
  bind: isLoopbackAddress(settings.bind) ? settings.bind : LOOPBACK,
8197
8407
  sshBind: void 0,
8198
8408
  edgeHost: void 0,
8409
+ t3GatewayOrigin: void 0,
8199
8410
  appUrl: settings.edgeHost === void 0 && isLoopbackName(new URL(settings.appUrl).hostname) ? settings.appUrl : `http://localhost:${settings.appPort}`,
8200
8411
  exposure: "loopback",
8201
8412
  declared: without(settings.declared, "workspace-ssh")
@@ -8284,14 +8495,14 @@ var askNetwork = async (asked, settings) => {
8284
8495
  bind: picked.bind,
8285
8496
  sshBind: followsWeb || reachModeOf(settings) === "machine" ? void 0 : settings.sshBind ?? settings.bind,
8286
8497
  edgeHost: void 0,
8498
+ t3GatewayOrigin: void 0,
8287
8499
  appUrl,
8288
8500
  exposure: "private"
8289
8501
  });
8290
8502
  };
8291
- var noPrivateNetwork = (port) => [
8503
+ var NO_PRIVATE_NETWORK = [
8292
8504
  "This machine has no address on a private network: no tailnet, no LAN or VPN address. Mend can",
8293
8505
  "still be reached from other machines without publishing it to the internet:",
8294
- ` - keep it on this machine and reach it through a tunnel you run, such as ssh -L ${port}:127.0.0.1:${port} <this machine>;`,
8295
8506
  " - join this machine to a tailnet (tailscale up), then run mend server setup again;",
8296
8507
  " - or choose the public internet, with HTTPS: the edge serves it on your domain, behind the public exposure gate."
8297
8508
  ];
@@ -8483,7 +8694,7 @@ var askReach = async (asked, settings) => {
8483
8694
  const network = await askNetwork(asked, settings);
8484
8695
  if (network === null) {
8485
8696
  asked.io.write("");
8486
- for (const line of noPrivateNetwork(settings.appPort)) asked.io.write(line);
8697
+ for (const line of NO_PRIVATE_NETWORK) asked.io.write(line);
8487
8698
  asked.io.write(
8488
8699
  asked.fresh ? "Setup installs Mend on this machine now." : "How Mend is reached stays as it is."
8489
8700
  );
@@ -8510,9 +8721,18 @@ var DECLARATIONS = [
8510
8721
  },
8511
8722
  {
8512
8723
  item: "t3code-gateway",
8513
- text: (settings) => `port ${settings.t3GatewayPort ?? DEFAULT_T3_GATEWAY_PORT} answers nothing from another machine, or only through what you put in front of it`
8724
+ text: (settings) => {
8725
+ const placement = t3PlacementOf(settings);
8726
+ if (placement === void 0) return "";
8727
+ const published = publishedAddress(placement.bind, placement.port);
8728
+ return placement.edgeHost !== void 0 ? `${placement.url} serves the T3 Code gateway with a certificate that chains to a public root, and ${published} answers nothing from another machine` : `the T3 Code gateway on ${published} answers only the networks that should reach it`;
8729
+ }
8514
8730
  }
8515
8731
  ];
8732
+ var t3NeedsStatement = (settings) => {
8733
+ const placement = t3PlacementOf(settings);
8734
+ return placement !== void 0 && (placement.edgeHost !== void 0 || t3GatewayBeyondMachine(placement));
8735
+ };
8516
8736
  var askDeclarations = async (asked, settings) => {
8517
8737
  const { io } = asked;
8518
8738
  io.write("");
@@ -8521,7 +8741,7 @@ var askDeclarations = async (asked, settings) => {
8521
8741
  );
8522
8742
  let declared = settings.declared;
8523
8743
  for (const { item, text } of DECLARATIONS) {
8524
- if (item === "t3code-gateway" && settings.t3GatewayPort === void 0) continue;
8744
+ if (item === "t3code-gateway" && !t3NeedsStatement(settings)) continue;
8525
8745
  const checked = await yesNo(
8526
8746
  io,
8527
8747
  ` ${item}: ${text(settings)}. Checked?`,
@@ -8531,22 +8751,102 @@ var askDeclarations = async (asked, settings) => {
8531
8751
  }
8532
8752
  return { ...settings, declared: DECLARABLE_ITEMS.filter((item) => declared.includes(item)) };
8533
8753
  };
8534
- var askT3 = async (asked, settings) => {
8754
+ var askT3Origin = async (asked, settings) => {
8755
+ const edgeHost = settings.edgeHost;
8756
+ if (edgeHost === void 0) return { ...settings, t3GatewayOrigin: void 0 };
8757
+ const { io } = asked;
8535
8758
  const port = settings.t3GatewayPort ?? DEFAULT_T3_GATEWAY_PORT;
8536
- asked.io.write("");
8537
- asked.io.write(
8538
- `The T3 Code gateway lets t3code's desktop, mobile and web apps pair with this Mend (mend pair). It listens on 127.0.0.1:${port} only; from another machine, use a tunnel you run, such as ssh -L ${port}:127.0.0.1:${port} <this machine>, or tailscale serve.`
8759
+ const served = await choose(
8760
+ io,
8761
+ `T3 Code always uses a server's root path, so the edge cannot serve the gateway under ${edgeHost}. Serve it on a host of its own?`,
8762
+ [
8763
+ {
8764
+ label: "yes, on a host of its own",
8765
+ detail: `such as t3.${edgeHost}, whose DNS points here as ${edgeHost}'s does; Caddy gets its certificate`,
8766
+ value: true
8767
+ },
8768
+ {
8769
+ label: "no, not through the edge",
8770
+ detail: `it stays on 127.0.0.1:${port}: this machine, or a tailnet through Tailscale Serve`,
8771
+ value: false
8772
+ }
8773
+ ],
8774
+ settings.t3GatewayOrigin === void 0 ? 1 : 0
8539
8775
  );
8540
- const on = await yesNo(
8541
- asked.io,
8542
- "Turn on the T3 Code gateway?",
8543
- settings.t3GatewayPort !== void 0
8776
+ if (!served) return { ...settings, t3GatewayOrigin: void 0 };
8777
+ const host = await typed(
8778
+ io,
8779
+ "The gateway's host",
8780
+ settings.t3GatewayOrigin ?? `t3.${edgeHost}`,
8781
+ (input) => {
8782
+ const parsed = parseEdgeHost(input);
8783
+ if (parsed === null)
8784
+ return {
8785
+ refused: `"${input}" is not a DNS name a certificate can be issued for, such as t3.${edgeHost}.`
8786
+ };
8787
+ if (parsed === edgeHost)
8788
+ return { refused: `${edgeHost} is Mend's own origin; the gateway needs another host.` };
8789
+ return { value: parsed };
8790
+ }
8544
8791
  );
8545
- return on ? { ...settings, t3GatewayPort: port } : {
8546
- ...settings,
8547
- t3GatewayPort: void 0,
8548
- declared: without(settings.declared, "t3code-gateway")
8549
- };
8792
+ const [resolved, edge] = await Promise.all([
8793
+ asked.context.observe.lookupHost(host),
8794
+ asked.context.observe.lookupHost(edgeHost)
8795
+ ]);
8796
+ if (resolved === null || resolved.length === 0)
8797
+ io.write(
8798
+ `Observed: ${host} does not resolve from this machine. Caddy cannot get its certificate until its DNS points where ${edgeHost}'s does.`
8799
+ );
8800
+ else if (edge !== null && resolved.every((address) => edge.includes(address)))
8801
+ io.write(`Observed: ${host} resolves to ${resolved.join(", ")}, as ${edgeHost} does.`);
8802
+ else
8803
+ io.write(
8804
+ `Observed: ${host} resolves to ${resolved.join(", ")}, and ${edgeHost} to ${edge === null || edge.length === 0 ? "nothing" : edge.join(", ")}.`
8805
+ );
8806
+ return { ...settings, t3GatewayOrigin: host };
8807
+ };
8808
+ var askT3 = async (asked, settings) => {
8809
+ const port = settings.t3GatewayPort ?? DEFAULT_T3_GATEWAY_PORT;
8810
+ const { io } = asked;
8811
+ io.write("");
8812
+ io.write(
8813
+ "The T3 Code gateway lets T3 Code's desktop, mobile and web apps pair with this Mend: in T3 Code, add a Remote link with its address and a code from mend pair. T3 Code's SSH mode is not for Mend: it starts T3 Code's own server on this machine."
8814
+ );
8815
+ const placement = t3PlacementOf(settings, port);
8816
+ if (placement !== void 0 && settings.edgeHost !== void 0)
8817
+ io.write(
8818
+ `Behind the edge, its port stays on ${publishedAddress(placement.bind, placement.port)}, as Mend's own does; the edge can serve it on a host of its own${settings.t3GatewayOrigin === void 0 ? "" : `, as it does now at https://${settings.t3GatewayOrigin}`}.`
8819
+ );
8820
+ else if (placement !== void 0 && t3GatewayBeyondMachine(placement))
8821
+ io.write(
8822
+ `It is published where Mend's web port is, on ${publishedAddress(placement.bind, placement.port)}: T3 Code reaches it at ${placement.url}, with no tunnel.`
8823
+ );
8824
+ else if (placement !== void 0)
8825
+ io.write(
8826
+ `It is published where Mend's web port is, on ${publishedAddress(placement.bind, placement.port)}: T3 Code on this machine reaches it at ${placement.url}. Reached from your network, Mend's web port and the gateway are published there together.`
8827
+ );
8828
+ if (placement !== void 0 && !t3GatewayBeyondMachine(placement)) {
8829
+ const tailscale = await asked.tailscale();
8830
+ const gatewayRoute = tailscale?.serve.find((route) => route.loopbackPort === port);
8831
+ const webServed = tailscale?.serve.some((route) => route.loopbackPort === settings.appPort);
8832
+ if (tailscale?.running === true && gatewayRoute !== void 0)
8833
+ io.write(
8834
+ `Observed: Tailscale Serve forwards ${gatewayRoute.origin} to port ${port} here${gatewayRoute.funnel ? ", with Funnel on: public" : ""}. T3 Code on your tailnet uses it as its Remote link.`
8835
+ );
8836
+ else if (tailscale?.running === true && tailscale.dnsName !== null && webServed === true)
8837
+ io.write(
8838
+ `Observed: Tailscale Serve forwards to Mend's port here. The gateway is reached the same way once Serve forwards to it too: tailscale serve --bg --https=${port} http://127.0.0.1:${port}, and T3 Code's Remote link takes https://${tailscale.dnsName}:${port}.`
8839
+ );
8840
+ }
8841
+ const on = await yesNo(io, "Turn on the T3 Code gateway?", settings.t3GatewayPort !== void 0);
8842
+ if (!on)
8843
+ return {
8844
+ ...settings,
8845
+ t3GatewayPort: void 0,
8846
+ t3GatewayOrigin: void 0,
8847
+ declared: without(settings.declared, "t3code-gateway")
8848
+ };
8849
+ return askT3Origin(asked, { ...settings, t3GatewayPort: port });
8550
8850
  };
8551
8851
  var askSize = (asked, question, preferred) => typed(asked.io, question, preferred, (input) => {
8552
8852
  const size = parseMirrorSize(input);
@@ -8752,7 +9052,7 @@ var runGuide = async (io, context) => {
8752
9052
  try {
8753
9053
  let target;
8754
9054
  if (context.saved === null) {
8755
- io.write("Mend server setup. A few questions; enter takes the answer in brackets.");
9055
+ if (context.introduced !== true) io.write(GUIDE_INTRO);
8756
9056
  target = await walk2(asked, base);
8757
9057
  } else {
8758
9058
  io.write(`Currently: ${headlineOf(base)}.`);
@@ -8946,6 +9246,8 @@ var SETUP_FLAGS = /* @__PURE__ */ new Set([
8946
9246
  "--t3-gateway",
8947
9247
  "--t3-gateway-port",
8948
9248
  "--no-t3-gateway",
9249
+ "--t3-gateway-origin",
9250
+ "--no-t3-gateway-origin",
8949
9251
  "--undeclare",
8950
9252
  "--allow-userns",
8951
9253
  "--no-allow-userns",
@@ -8963,6 +9265,7 @@ var SWITCHES = /* @__PURE__ */ new Set([
8963
9265
  "--no-docker-hub-login",
8964
9266
  "--t3-gateway",
8965
9267
  "--no-t3-gateway",
9268
+ "--no-t3-gateway-origin",
8966
9269
  "--allow-userns",
8967
9270
  "--no-allow-userns",
8968
9271
  "--yes"
@@ -8993,15 +9296,16 @@ var parseDeclared = (values, flag) => {
8993
9296
  )
8994
9297
  ];
8995
9298
  };
8996
- var parseEdge = (value) => {
9299
+ var parseHostFlag = (value, flag) => {
8997
9300
  const host = parseEdgeHost(value);
8998
9301
  if (host === null) {
8999
9302
  throw setupError(
9000
- `--edge must be a DNS name a certificate can be issued for, such as mend.example.com, not "${value}". An IP address or a single label cannot carry a public certificate.`
9303
+ `${flag} must be a DNS name a certificate can be issued for, such as ${flag === "--edge" ? "mend.example.com" : "t3.mend.example.com"}, not "${value}". An IP address or a single label cannot carry a public certificate.`
9001
9304
  );
9002
9305
  }
9003
9306
  return host;
9004
9307
  };
9308
+ var parseEdge = (value) => parseHostFlag(value, "--edge");
9005
9309
  var parseSetupOptions = (args) => {
9006
9310
  const values = /* @__PURE__ */ new Map();
9007
9311
  for (let index = 0; index < args.length; index += 1) {
@@ -9091,6 +9395,12 @@ var parseSetupOptions = (args) => {
9091
9395
  if (values.has("--no-t3-gateway") && (values.has("--t3-gateway") || t3GatewayPort !== void 0)) {
9092
9396
  throw setupError("--no-t3-gateway contradicts --t3-gateway and --t3-gateway-port.");
9093
9397
  }
9398
+ const t3GatewayOrigin = flagValue2("--t3-gateway-origin");
9399
+ if (t3GatewayOrigin !== void 0 && (values.has("--no-t3-gateway") || values.has("--no-t3-gateway-origin"))) {
9400
+ throw setupError(
9401
+ `--t3-gateway-origin contradicts ${values.has("--no-t3-gateway") ? "--no-t3-gateway" : "--no-t3-gateway-origin"}.`
9402
+ );
9403
+ }
9094
9404
  return {
9095
9405
  context: flagValue2("--context"),
9096
9406
  version: version === void 0 ? void 0 : parseVersion(version),
@@ -9121,6 +9431,8 @@ var parseSetupOptions = (args) => {
9121
9431
  t3Gateway: values.has("--t3-gateway"),
9122
9432
  t3GatewayPort: t3GatewayPort === void 0 ? void 0 : parsePort(t3GatewayPort, "--t3-gateway-port"),
9123
9433
  noT3Gateway: values.has("--no-t3-gateway"),
9434
+ t3GatewayOrigin: t3GatewayOrigin === void 0 ? void 0 : parseHostFlag(t3GatewayOrigin, "--t3-gateway-origin"),
9435
+ noT3GatewayOrigin: values.has("--no-t3-gateway-origin"),
9124
9436
  allowUserns: pair("--allow-userns", "--no-allow-userns")
9125
9437
  };
9126
9438
  };
@@ -9308,7 +9620,7 @@ var validateExposure = (existing, options) => {
9308
9620
  const edgeHost = options.noEdge ? void 0 : options.edge ?? existing?.edgeHost;
9309
9621
  const exposure = options.exposure ?? existing?.exposure;
9310
9622
  const tenancy = options.tenancy ?? existing?.tenancy;
9311
- const t3GatewayPort = options.noT3Gateway ? void 0 : options.t3GatewayPort ?? existing?.t3GatewayPort ?? (options.t3Gateway ? DEFAULT_T3_GATEWAY_PORT : void 0);
9623
+ const t3GatewayPort = options.noT3Gateway ? void 0 : options.t3GatewayPort ?? existing?.t3GatewayPort ?? (options.t3Gateway || options.t3GatewayOrigin !== void 0 ? DEFAULT_T3_GATEWAY_PORT : void 0);
9312
9624
  if (t3GatewayPort !== void 0 && [appPort, sshPort].includes(t3GatewayPort)) {
9313
9625
  throw setupError(
9314
9626
  `--t3-gateway-port ${t3GatewayPort} is Mend's own --port or --ssh-port: the gateway needs a port of its own.`
@@ -9317,6 +9629,17 @@ var validateExposure = (existing, options) => {
9317
9629
  if (t3GatewayPort !== void 0 && edgeHost !== void 0 && [80, 443].includes(t3GatewayPort)) {
9318
9630
  throw setupError("With an edge, --t3-gateway-port must not be 80 or 443: the edge has them.");
9319
9631
  }
9632
+ const t3GatewayOrigin = options.noT3Gateway || options.noT3GatewayOrigin ? void 0 : options.t3GatewayOrigin ?? existing?.t3GatewayOrigin;
9633
+ if (t3GatewayOrigin !== void 0 && edgeHost === void 0) {
9634
+ throw setupError(
9635
+ options.t3GatewayOrigin === void 0 ? `The edge serves the t3code gateway at ${t3GatewayOrigin}; without the edge nothing does. Add --no-t3-gateway-origin to take it away with the edge.` : "--t3-gateway-origin needs the edge (--edge <host>): it is the edge that serves the gateway on its own origin. On a private network, the gateway is published where Mend's web port is, and needs no origin."
9636
+ );
9637
+ }
9638
+ if (t3GatewayOrigin !== void 0 && t3GatewayOrigin === edgeHost) {
9639
+ throw setupError(
9640
+ `--t3-gateway-origin ${t3GatewayOrigin} is Mend's own origin. A t3code client always uses a server's root path, so the gateway needs a host of its own, such as t3.${edgeHost}.`
9641
+ );
9642
+ }
9320
9643
  const saved = existing?.declared ?? [];
9321
9644
  const stated = options.declared === void 0 ? saved : options.declared.length === 0 ? [] : [.../* @__PURE__ */ new Set([...saved, ...options.declared])];
9322
9645
  const declared = stated.filter((item) => !options.undeclared.includes(item));
@@ -9340,7 +9663,8 @@ var validateExposure = (existing, options) => {
9340
9663
  ...exposure === void 0 ? {} : { exposure },
9341
9664
  ...tenancy === void 0 ? {} : { tenancy },
9342
9665
  ...declared.length === 0 ? {} : { declared },
9343
- ...t3GatewayPort === void 0 ? {} : { t3GatewayPort }
9666
+ ...t3GatewayPort === void 0 ? {} : { t3GatewayPort },
9667
+ ...t3GatewayOrigin === void 0 ? {} : { t3GatewayOrigin }
9344
9668
  };
9345
9669
  };
9346
9670
  var settingsOf = (config) => ({
@@ -9355,6 +9679,7 @@ var settingsOf = (config) => ({
9355
9679
  tenancy: config.tenancy,
9356
9680
  declared: config.declared ?? [],
9357
9681
  t3GatewayPort: config.t3GatewayPort,
9682
+ t3GatewayOrigin: config.t3GatewayOrigin,
9358
9683
  mirrors: config.mirrors
9359
9684
  });
9360
9685
  var resolveSetupSettings = (existing, flags) => {
@@ -9408,6 +9733,10 @@ var parseServerConfig = (raw) => {
9408
9733
  }
9409
9734
  const declared = Array.isArray(declaredField) ? declaredField.filter((item) => isDeclarableItem(String(item))) : [];
9410
9735
  const t3GatewayPort = fields.has("t3GatewayPort") ? requiredInteger(fields, "t3GatewayPort") : void 0;
9736
+ const t3GatewayOrigin = fields.has("t3GatewayOrigin") ? requiredString(fields, "t3GatewayOrigin") : void 0;
9737
+ if (t3GatewayOrigin !== void 0 && parseEdgeHost(t3GatewayOrigin) !== t3GatewayOrigin) {
9738
+ throw setupError("Server config is corrupt: t3GatewayOrigin must be a lowercase DNS name.");
9739
+ }
9411
9740
  const config = {
9412
9741
  schemaVersion: requiredInteger(fields, "schemaVersion"),
9413
9742
  assetContract: requiredString(fields, "assetContract"),
@@ -9431,7 +9760,8 @@ var parseServerConfig = (raw) => {
9431
9760
  ...tenancy === void 0 ? {} : { tenancy },
9432
9761
  ...declared.length === 0 ? {} : { declared },
9433
9762
  ...fields.has("mirrors") ? { mirrors: parseMirrorsField(fields.get("mirrors")) } : {},
9434
- ...t3GatewayPort === void 0 ? {} : { t3GatewayPort }
9763
+ ...t3GatewayPort === void 0 ? {} : { t3GatewayPort },
9764
+ ...t3GatewayOrigin === void 0 ? {} : { t3GatewayOrigin }
9435
9765
  };
9436
9766
  if (config.schemaVersion !== CONFIG_SCHEMA_VERSION || config.assetContract !== ASSET_CONTRACT && !LEGACY_ASSET_CONTRACTS.has(config.assetContract)) {
9437
9767
  throw setupError(
@@ -9473,8 +9803,13 @@ var parseServerConfig = (raw) => {
9473
9803
  t3Gateway: false,
9474
9804
  t3GatewayPort: config.t3GatewayPort,
9475
9805
  noT3Gateway: false,
9806
+ t3GatewayOrigin: config.t3GatewayOrigin,
9807
+ noT3GatewayOrigin: false,
9476
9808
  allowUserns: void 0
9477
9809
  });
9810
+ if (config.t3GatewayOrigin !== void 0 && config.t3GatewayPort === void 0) {
9811
+ throw setupError("Server config is corrupt: t3GatewayOrigin without t3GatewayPort.");
9812
+ }
9478
9813
  return config;
9479
9814
  };
9480
9815
  var envValue = (fields, key) => {
@@ -9572,6 +9907,7 @@ var parseContextRows = (raw) => {
9572
9907
  var localUnixEndpoint = (endpoint) => endpoint.startsWith("unix:///");
9573
9908
  var outputDetail = (output) => output.stderr.trim() || output.error || `exit ${output.status ?? "unknown"}`;
9574
9909
  var commandFailure = (label, output) => setupError(`${label}: ${outputDetail(output)}`);
9910
+ var preferredContext = (local) => local.find((row) => row.current) ?? local.find((row) => row.name === "orbstack") ?? local.find((row) => row.name === "desktop-linux") ?? local.find((row) => row.name === "default") ?? (local.length === 1 ? local[0] : void 0);
9575
9911
  var selectDockerContext = async (runtime, requested) => {
9576
9912
  if (requested !== void 0) {
9577
9913
  const inspect = await runtime.run("docker", [
@@ -9589,18 +9925,22 @@ var selectDockerContext = async (runtime, requested) => {
9589
9925
  `Docker context "${requested}" uses ${endpoint || "an unknown endpoint"}. Mend server setup supports local Unix-socket contexts only; remote SSH/TCP daemons would make the advertised health check report the wrong machine.`
9590
9926
  );
9591
9927
  }
9592
- return { name: requested, endpoint };
9928
+ return { name: requested, endpoint, others: [] };
9593
9929
  }
9594
9930
  const listed3 = await runtime.run("docker", ["context", "ls", "--format", "{{json .}}"]);
9595
9931
  if (listed3.status !== 0) throw commandFailure("Docker contexts are unavailable", listed3);
9596
9932
  const local = parseContextRows(listed3.stdout).filter((row) => localUnixEndpoint(row.endpoint));
9597
- const selected = local.find((row) => row.current) ?? local.find((row) => row.name === "orbstack") ?? local.find((row) => row.name === "desktop-linux") ?? local.find((row) => row.name === "default") ?? (local.length === 1 ? local[0] : void 0);
9933
+ const selected = preferredContext(local);
9598
9934
  if (selected === void 0) {
9599
9935
  throw setupError(
9600
9936
  local.length === 0 ? "No local Unix-socket Docker context was found. Start Docker Desktop, OrbStack, or a local Docker Engine, then retry." : `Several local Docker contexts are available (${local.map((row) => row.name).join(", ")}). Choose one with --context.`
9601
9937
  );
9602
9938
  }
9603
- return { name: selected.name, endpoint: selected.endpoint };
9939
+ return {
9940
+ name: selected.name,
9941
+ endpoint: selected.endpoint,
9942
+ others: local.filter((row) => row !== selected).map((row) => row.name)
9943
+ };
9604
9944
  };
9605
9945
  var compareApiVersions = (left, right) => {
9606
9946
  const parts = (value) => {
@@ -9967,7 +10307,7 @@ var validateOverlays = (config, files) => {
9967
10307
  }
9968
10308
  for (const line of postureEnvLines(config)) {
9969
10309
  const key = line.slice(0, line.indexOf("="));
9970
- if (key !== "MEND_EDGE_HOST" && key !== "MEND_T3_GATEWAY_PORT" && !(files.posture ?? "").includes(` ${key}: \${${key}`)) {
10310
+ if (key !== "MEND_EDGE_HOST" && !key.startsWith("MEND_T3_GATEWAY_") && !(files.posture ?? "").includes(` ${key}: \${${key}`)) {
9971
10311
  throw setupError(
9972
10312
  `Server generation is corrupt: compose.posture.yaml does not hand ${key} to Mend.`
9973
10313
  );
@@ -9978,9 +10318,13 @@ var validateOverlays = (config, files) => {
9978
10318
  "Server generation is corrupt: compose.t3.yaml does not match the persisted server config."
9979
10319
  );
9980
10320
  }
9981
- if (files.t3Gateway !== void 0 && (!files.t3Gateway.includes('MEND_T3_GATEWAY_ENABLED: "true"') || !files.t3Gateway.includes('"127.0.0.1:${MEND_T3_GATEWAY_PORT'))) {
10321
+ if (files.t3Gateway !== void 0 && (!files.t3Gateway.includes('MEND_T3_GATEWAY_ENABLED: "true"') || !(files.t3Gateway.includes('"${MEND_T3_GATEWAY_BIND_HOST') || files.t3Gateway.includes('"127.0.0.1:${MEND_T3_GATEWAY_PORT')))) {
10322
+ throw setupError("Server generation is corrupt: compose.t3.yaml is not the gateway overlay.");
10323
+ }
10324
+ const servedByEdge = t3GatewayPlacement(config)?.edgeHost !== void 0;
10325
+ if (servedByEdge !== (files.t3Caddyfile !== void 0) || servedByEdge && !(files.t3Gateway ?? "").includes(T3_GATEWAY_CADDY_SITE)) {
9982
10326
  throw setupError(
9983
- "Server generation is corrupt: compose.t3.yaml is not the gateway overlay on loopback."
10327
+ `Server generation is corrupt: ${T3_GATEWAY_CADDYFILE_NAME} does not match the persisted server config.`
9984
10328
  );
9985
10329
  }
9986
10330
  if (config.edgeHost === void 0 !== (files.edge === void 0) || config.edgeHost === void 0 !== (files.caddyfile === void 0)) {
@@ -10115,7 +10459,8 @@ var readServerInstallationFacts = async (configDir) => {
10115
10459
  ...generation.files.mirrors === void 0 ? [] : [{ name: MIRRORS_COMPOSE_FILE, content: generation.files.mirrors }],
10116
10460
  ...generation.files.npmMirrorConf === void 0 ? [] : [{ name: NPM_MIRROR_CONF_NAME, content: generation.files.npmMirrorConf }],
10117
10461
  ...generation.files.dockerMirrorGuard === void 0 ? [] : [{ name: DOCKER_MIRROR_GUARD_NAME, content: generation.files.dockerMirrorGuard }],
10118
- ...generation.files.t3Gateway === void 0 ? [] : [{ name: "compose.t3.yaml", content: generation.files.t3Gateway }]
10462
+ ...generation.files.t3Gateway === void 0 ? [] : [{ name: "compose.t3.yaml", content: generation.files.t3Gateway }],
10463
+ ...generation.files.t3Caddyfile === void 0 ? [] : [{ name: T3_GATEWAY_CADDYFILE_NAME, content: generation.files.t3Caddyfile }]
10119
10464
  ],
10120
10465
  envKeys: envKeyNames(generation.files.env)
10121
10466
  };
@@ -10129,6 +10474,7 @@ var generationFiles = (config, secrets, assets, identity = renderIdentity(secret
10129
10474
  const posture = renderPostureOverlay(config);
10130
10475
  const mirrors = renderMirrorsOverlay(config.mirrors);
10131
10476
  const t3Gateway = renderT3GatewayOverlay(config);
10477
+ const t3Caddyfile = t3GatewayPlacement(config)?.edgeHost === void 0 ? void 0 : T3_GATEWAY_CADDYFILE;
10132
10478
  return {
10133
10479
  identity,
10134
10480
  config: `${JSON.stringify(config, null, 2)}
@@ -10137,6 +10483,7 @@ var generationFiles = (config, secrets, assets, identity = renderIdentity(secret
10137
10483
  ...assets,
10138
10484
  ...posture === void 0 ? {} : { posture },
10139
10485
  ...t3Gateway === void 0 ? {} : { t3Gateway },
10486
+ ...t3Caddyfile === void 0 ? {} : { t3Caddyfile },
10140
10487
  ...config.edgeHost === void 0 ? {} : { edge: EDGE_COMPOSE_OVERLAY, caddyfile: EDGE_CADDYFILE },
10141
10488
  ...mirrors === void 0 ? {} : { mirrors },
10142
10489
  ...config.mirrors === void 0 || config.mirrors.npm === null ? {} : { npmMirrorConf: NPM_MIRROR_CONF },
@@ -10151,16 +10498,38 @@ var healthOrigin = (config) => {
10151
10498
  };
10152
10499
  var reachableLine = (config) => config.edgeHost === void 0 ? `Mend ${config.serverVersion} is reachable at ${config.appUrl}` : `Mend ${config.serverVersion} answers at ${healthOrigin(config)} on this machine \xB7 the edge is set up for ${config.appUrl}`;
10153
10500
  var T3_GATEWAY_OBSERVE_ATTEMPTS = 15;
10154
- var observeT3Gateway = async (runtime, port) => {
10155
- const url = `http://127.0.0.1:${port}/.well-known/t3/environment`;
10501
+ var t3GatewayOriginLine = async (runtime, config) => {
10502
+ const edgeHost = config.edgeHost;
10503
+ const host = edgeHost === void 0 ? void 0 : config.t3GatewayOrigin;
10504
+ if (edgeHost === void 0 || host === void 0 || runtime.lookupHost === void 0) return null;
10505
+ const [origin, edge] = await Promise.all([
10506
+ runtime.lookupHost(host),
10507
+ runtime.lookupHost(edgeHost)
10508
+ ]);
10509
+ if (origin === null || origin.length === 0)
10510
+ return `Observed: ${host} does not resolve from this machine. Caddy cannot get its certificate, and T3 Code cannot reach it, until its DNS points where ${edgeHost} does.`;
10511
+ const edgeAddresses = edge ?? [];
10512
+ return origin.every((address) => edgeAddresses.includes(address)) ? `Observed: ${host} resolves to ${origin.join(", ")}, as ${edgeHost} does.` : `Observed: ${host} resolves to ${origin.join(", ")}, and ${edgeHost} to ${edgeAddresses.length === 0 ? "nothing" : edgeAddresses.join(", ")}. Caddy gets a certificate for ${host} once it points where ${edgeHost} does.`;
10513
+ };
10514
+ var t3GatewayReachLine = (placement) => {
10515
+ const published = publishedAddress(placement.bind, placement.port);
10516
+ if (placement.edgeHost !== void 0)
10517
+ return `Its port is published on ${published} only; the edge serves it at ${placement.url} once ${placement.edgeHost} resolves to this machine and Caddy holds its certificate. In T3 Code, add a Remote link to ${placement.url} and pair with a code from mend pair.`;
10518
+ if (t3GatewayBeyondMachine(placement))
10519
+ return `It is published on ${published}, where Mend's web port is: T3 Code on a machine that reaches Mend reaches it too, with no tunnel. In T3 Code, add a Remote link to ${placement.url} and pair with a code from mend pair.`;
10520
+ return `It is published on ${published} only, as Mend's web port is. In T3 Code on this machine, add a Remote link to ${placement.url} and pair with a code from mend pair.`;
10521
+ };
10522
+ var observeT3Gateway = async (runtime, placement) => {
10523
+ const url = `${placement.probeUrl}/.well-known/t3/environment`;
10524
+ const at = new URL(placement.probeUrl).host;
10156
10525
  for (let attempt2 = 0; attempt2 < T3_GATEWAY_OBSERVE_ATTEMPTS; attempt2 += 1) {
10157
10526
  const response = await runtime.fetchText(url, 2e3);
10158
10527
  if (response.error === void 0 && response.status === 200) {
10159
- return `The t3code gateway answered at 127.0.0.1:${port}, observed from this machine; it is published there only. In t3code, add it as an environment at http://127.0.0.1:${port} and pair with a code from mend pair; reaching it from elsewhere is an exposure you put in front of it and declare (docs/adr/0004).`;
10528
+ return `The t3code gateway answered at ${at}, observed from this machine. ${t3GatewayReachLine(placement)}`;
10160
10529
  }
10161
10530
  if (attempt2 < T3_GATEWAY_OBSERVE_ATTEMPTS - 1) await runtime.sleep(2e3);
10162
10531
  }
10163
- return `The t3code gateway did not answer at 127.0.0.1:${port} from this machine within about a minute. Mend runs without it; mend server logs shows what it said, and mend server status looks again.`;
10532
+ return `The t3code gateway did not answer at ${at} from this machine within about a minute. Mend runs without it; mend server logs shows what it said, and mend server status looks again.`;
10164
10533
  };
10165
10534
  var instanceIdOf = (betterAuthSecret) => createHmac("sha256", betterAuthSecret).update("mend instance id").digest("hex").slice(0, 32);
10166
10535
  var readHealth = (response) => {
@@ -10674,6 +11043,130 @@ var guideObservations = (runtime) => ({
10674
11043
  portTaken: runtime.portTaken ?? (async () => false),
10675
11044
  portHolder: (address, port, what) => portHolder(runtime, address, port, what)
10676
11045
  });
11046
+ var ENGINE_PING_MS = 5e3;
11047
+ var socketOf = (endpoint) => {
11048
+ try {
11049
+ return decodeURIComponent(new URL(endpoint).pathname);
11050
+ } catch {
11051
+ return endpoint;
11052
+ }
11053
+ };
11054
+ var engineKind = (name, operatingSystem, rootless) => {
11055
+ if (operatingSystem === "OrbStack" || operatingSystem === "Docker Desktop")
11056
+ return operatingSystem;
11057
+ if (name === "colima" || name.startsWith("colima-")) return "colima";
11058
+ if (name.startsWith("rancher-desktop")) return "Rancher Desktop";
11059
+ return `${rootless ? "rootless " : ""}Docker Engine${operatingSystem === "" ? "" : ` on ${operatingSystem}`}`;
11060
+ };
11061
+ var namesFrom = (output) => output.status === 0 ? output.stdout.split("\n").map((line) => line.trim()).filter((line) => line !== "") : null;
11062
+ var mendIn = async (runtime, context) => {
11063
+ const [running, volumes] = await Promise.all([
11064
+ runtime.run(
11065
+ "docker",
11066
+ [
11067
+ "--context",
11068
+ context,
11069
+ "container",
11070
+ "ls",
11071
+ "--filter",
11072
+ `label=com.docker.compose.project=${MEND_DOCKER_NAMESPACE.project}`,
11073
+ "--format",
11074
+ "{{.Names}}"
11075
+ ],
11076
+ { timeoutMs: ENGINE_PING_MS }
11077
+ ),
11078
+ runtime.run(
11079
+ "docker",
11080
+ [
11081
+ "--context",
11082
+ context,
11083
+ "volume",
11084
+ "ls",
11085
+ "--filter",
11086
+ `label=${SERVER_VOLUME_OWNER_LABEL}`,
11087
+ "--format",
11088
+ "{{.Name}}"
11089
+ ],
11090
+ { timeoutMs: ENGINE_PING_MS }
11091
+ )
11092
+ ]);
11093
+ const containers = namesFrom(running);
11094
+ const owned = namesFrom(volumes);
11095
+ if (containers === null || owned === null) return null;
11096
+ return containers.length > 0 ? "running" : owned.length > 0 ? "volumes" : "none";
11097
+ };
11098
+ var observeDockerEngines = async (runtime) => {
11099
+ const listed3 = await runtime.run("docker", ["context", "ls", "--format", "{{json .}}"], {
11100
+ timeoutMs: ENGINE_PING_MS
11101
+ });
11102
+ if (listed3.status !== 0) return null;
11103
+ let rows2;
11104
+ try {
11105
+ rows2 = parseContextRows(listed3.stdout);
11106
+ } catch {
11107
+ return null;
11108
+ }
11109
+ const local = rows2.filter((row) => localUnixEndpoint(row.endpoint));
11110
+ const answers = await Promise.all(
11111
+ local.map(async (row) => {
11112
+ const info = await runtime.run(
11113
+ "docker",
11114
+ [
11115
+ "--context",
11116
+ row.name,
11117
+ "info",
11118
+ "--format",
11119
+ "{{.OperatingSystem}} {{json .SecurityOptions}}"
11120
+ ],
11121
+ { timeoutMs: ENGINE_PING_MS }
11122
+ );
11123
+ if (info.status !== 0 || info.stdout.trim() === "") return null;
11124
+ const [operatingSystem = "", security = ""] = info.stdout.trim().split(" ");
11125
+ return {
11126
+ context: row.name,
11127
+ what: engineKind(row.name, operatingSystem.trim(), security.includes("name=rootless")),
11128
+ socket: socketOf(row.endpoint),
11129
+ current: row.current,
11130
+ mend: await mendIn(runtime, row.name)
11131
+ };
11132
+ })
11133
+ );
11134
+ return {
11135
+ engines: answers.filter((engine) => engine !== null),
11136
+ silent: local.filter((_, index) => answers[index] === null),
11137
+ remote: rows2.filter((row) => !localUnixEndpoint(row.endpoint)),
11138
+ unasked: preferredContext(local)?.name
11139
+ };
11140
+ };
11141
+ var settleDockerEngine = async (runtime, io) => {
11142
+ const observed = await observeDockerEngines(runtime);
11143
+ if (observed === null) return [];
11144
+ for (const row of observed.remote)
11145
+ io.write(
11146
+ `Observed: Docker context ${row.name} is on another machine (${row.endpoint}); Mend runs in a Docker engine on this machine only.`
11147
+ );
11148
+ for (const row of observed.silent)
11149
+ io.write(
11150
+ `Observed: Docker context ${row.name} (socket ${socketOf(row.endpoint)}) did not answer; start it and run mend server setup again to choose it.`
11151
+ );
11152
+ const [only, ...others] = observed.engines;
11153
+ if (only === void 0) return [];
11154
+ if (others.length === 0) {
11155
+ io.write(
11156
+ `Docker: Mend runs in ${only.context} (${engineNote(only)}), the one Docker engine here that answers.`
11157
+ );
11158
+ return only.context === observed.unasked ? [] : ["--context", only.context];
11159
+ }
11160
+ const preferred = preferredContext(
11161
+ observed.engines.map((engine) => ({
11162
+ name: engine.context,
11163
+ endpoint: "",
11164
+ current: engine.current
11165
+ }))
11166
+ )?.name;
11167
+ const picked = await chooseDockerEngine(io, observed.engines, preferred);
11168
+ return picked === null ? null : ["--context", picked];
11169
+ };
10677
11170
  var guidedSetup = async (runtime, prompter, hostFlags2 = []) => {
10678
11171
  if (runtime.platform !== "linux" && runtime.platform !== "darwin") {
10679
11172
  throw setupError(`mend server setup supports Linux and macOS, not ${runtime.platform}.`);
@@ -10686,27 +11179,42 @@ var guidedSetup = async (runtime, prompter, hostFlags2 = []) => {
10686
11179
  if (read._tag === "error") return { _tag: "error", message: read.error.message };
10687
11180
  const existing = read.value;
10688
11181
  refuseLegacyContract(existing);
11182
+ const io = { write: runtime.writeLine, ask: prompter };
10689
11183
  const hostOptions = parseSetupOptions(hostFlags2);
11184
+ let given = hostFlags2;
11185
+ if (existing === null) {
11186
+ io.write(GUIDE_INTRO);
11187
+ if (requestedDockerContext(runtime, hostOptions, null).requested === void 0) {
11188
+ const engine = await settleDockerEngine(runtime, io);
11189
+ if (engine === null) {
11190
+ runtime.writeLine("Nothing changed.");
11191
+ return { _tag: "ok" };
11192
+ }
11193
+ given = [...engine, ...hostFlags2];
11194
+ }
11195
+ }
10690
11196
  const context = await selectDockerContext(
10691
11197
  runtime,
10692
- requestedDockerContext(runtime, hostOptions, existing).requested
11198
+ requestedDockerContext(runtime, parseSetupOptions(given), existing).requested
10693
11199
  );
10694
11200
  await checkDocker(runtime, context.name);
11201
+ if (existing !== null && hostOptions.context === void 0)
11202
+ io.write(
11203
+ `Docker: this install runs in context ${context.name} (socket ${socketOf(context.endpoint)}), where its data is, and stays there. Running Mend in another Docker engine is a new install: mend uninstall --server removes this one, its data included, then mend server setup there.`
11204
+ );
10695
11205
  const reminder = await settleHostUserNamespaces(
10696
11206
  { ...runtime, prompter },
10697
11207
  hostOptions,
10698
11208
  context.name
10699
11209
  );
10700
- const outcome = await runGuide(
10701
- { write: runtime.writeLine, ask: prompter },
10702
- {
10703
- saved: existing === null ? null : resolveSetupSettings(existing.config, []),
10704
- defaults: resolveSetupSettings(null, []),
10705
- observe: guideObservations(runtime),
10706
- resolve: (flags) => resolveSetupSettings(existing?.config ?? null, flags),
10707
- given: hostFlags2
10708
- }
10709
- );
11210
+ const outcome = await runGuide(io, {
11211
+ saved: existing === null ? null : resolveSetupSettings(existing.config, []),
11212
+ defaults: resolveSetupSettings(null, []),
11213
+ observe: guideObservations(runtime),
11214
+ resolve: (flags) => resolveSetupSettings(existing?.config ?? null, flags),
11215
+ given,
11216
+ introduced: existing === null
11217
+ });
10710
11218
  if (outcome._tag === "refused") return { _tag: "error", message: outcome.message };
10711
11219
  if (outcome._tag === "stopped") {
10712
11220
  runtime.writeLine("Nothing changed.");
@@ -10714,7 +11222,7 @@ var guidedSetup = async (runtime, prompter, hostFlags2 = []) => {
10714
11222
  }
10715
11223
  return underLock(
10716
11224
  runtime.configDir,
10717
- (store) => setupServer([...outcome.flags, ...hostFlags2], runtime, store, {
11225
+ (store) => setupServer([...outcome.flags, ...given], runtime, store, {
10718
11226
  askedAgainst: existing?.directory ?? null,
10719
11227
  userNamespaces: { reminder }
10720
11228
  }),
@@ -10767,9 +11275,13 @@ var setupServer = async (args, runtime, store, run2 = {}) => {
10767
11275
  runtime.writeLine(
10768
11276
  `Using Docker context "${selectedContext.name}" (${selectedContext.endpoint})${fromVariable ? ", from DOCKER_CONTEXT" : ""}`
10769
11277
  );
11278
+ if (existing === null && run2.askedAgainst === void 0 && selectedContext.others.length > 0)
11279
+ runtime.writeLine(
11280
+ `Other Docker contexts here: ${selectedContext.others.join(", ")}. To install in one of them instead: mend server setup --context <name>.`
11281
+ );
10770
11282
  if (existing !== null && options.context === void 0 && variable !== void 0 && variable !== existing.config.dockerContext) {
10771
11283
  runtime.writeLine(
10772
- `DOCKER_CONTEXT is "${variable}"; this install runs on Docker context "${existing.config.dockerContext}", where its data is, and stays there. --context moves it.`
11284
+ `DOCKER_CONTEXT is "${variable}"; this install runs on Docker context "${existing.config.dockerContext}", where its data is, and stays there. Running Mend in another Docker engine is a new install: mend uninstall --server removes this one, its data included, then mend server setup there.`
10773
11285
  );
10774
11286
  }
10775
11287
  await refuseTakenPorts(
@@ -10843,9 +11355,11 @@ var setupServer = async (args, runtime, store, run2 = {}) => {
10843
11355
  ...savedSecrets ?? createSecrets(runtime),
10844
11356
  ...dockerHubToken === void 0 ? {} : { dockerHubToken }
10845
11357
  };
10846
- if (config.t3GatewayPort !== void 0 && config.t3GatewayPort !== existing?.config.t3GatewayPort && config.dockerEndpoint.startsWith("unix://") && runtime.portTaken !== void 0 && await runtime.portTaken(config.t3GatewayPort)) {
11358
+ const t3Gateway = t3GatewayPlacement(config);
11359
+ const t3GatewayBefore = existing === null ? void 0 : t3GatewayPlacement(existing.config);
11360
+ if (t3Gateway !== void 0 && (t3Gateway.port !== t3GatewayBefore?.port || t3Gateway.bind !== t3GatewayBefore.bind) && config.dockerEndpoint.startsWith("unix://") && runtime.portTaken !== void 0 && await runtime.portTaken(t3Gateway.port, t3Gateway.bind)) {
10847
11361
  throw setupError(
10848
- `127.0.0.1:${config.t3GatewayPort} is already in use on this machine, so the t3code gateway cannot be published there and Mend would not start. Free it, or pick another with --t3-gateway-port <n>`
11362
+ `${publishedAddress(t3Gateway.bind, t3Gateway.port)} is already in use on this machine, so the t3code gateway cannot be published there and Mend would not start. Free it, or pick another with --t3-gateway-port <n>`
10849
11363
  );
10850
11364
  }
10851
11365
  const generation = persistSetup(store, config, secrets, assets);
@@ -10873,8 +11387,10 @@ var setupServer = async (args, runtime, store, run2 = {}) => {
10873
11387
  if (edgeStarted !== null) runtime.writeLine(edgeStarted);
10874
11388
  const sshPublication = await sshPublicationLine(runtime, config);
10875
11389
  if (sshPublication !== null) runtime.writeLine(sshPublication);
10876
- if (config.t3GatewayPort !== void 0) {
10877
- runtime.writeLine(await observeT3Gateway(runtime, config.t3GatewayPort));
11390
+ if (t3Gateway !== void 0) {
11391
+ runtime.writeLine(await observeT3Gateway(runtime, t3Gateway));
11392
+ const origin = await t3GatewayOriginLine(runtime, config);
11393
+ if (origin !== null) runtime.writeLine(origin);
10878
11394
  }
10879
11395
  if (existing?.config.t3GatewayPort !== void 0 && config.t3GatewayPort === void 0) {
10880
11396
  runtime.writeLine(
@@ -11603,13 +12119,15 @@ var serverStatus = async (runtime, installation) => {
11603
12119
  }
11604
12120
  for (const line of await mirrorStatusLines(runtime, installation, runningServices))
11605
12121
  runtime.writeLine(line);
11606
- if (config.t3GatewayPort !== void 0 && runningServices.includes("mend")) {
12122
+ const t3Gateway = t3GatewayPlacement(config);
12123
+ if (t3Gateway !== void 0 && runningServices.includes("mend")) {
11607
12124
  const gateway = await runtime.fetchText(
11608
- `http://127.0.0.1:${config.t3GatewayPort}/.well-known/t3/environment`,
12125
+ `${t3Gateway.probeUrl}/.well-known/t3/environment`,
11609
12126
  2e3
11610
12127
  );
12128
+ const at = new URL(t3Gateway.probeUrl).host;
11611
12129
  runtime.writeLine(
11612
- gateway.error === void 0 && gateway.status === 200 ? `t3code gateway \xB7 observed answering at 127.0.0.1:${config.t3GatewayPort} from this machine` : `t3code gateway \xB7 not observed at 127.0.0.1:${config.t3GatewayPort} from this machine \xB7 mend server logs shows what it said`
12130
+ gateway.error === void 0 && gateway.status === 200 ? `t3code gateway \xB7 observed answering at ${at} from this machine \xB7 T3 Code's Remote link takes ${t3Gateway.url}` : `t3code gateway \xB7 not observed at ${at} from this machine \xB7 mend server logs shows what it said`
11613
12131
  );
11614
12132
  }
11615
12133
  if (!runningServices.includes("mend")) {
@@ -18521,7 +19039,18 @@ var main = async () => {
18521
19039
  case "connect":
18522
19040
  return connectCommand(config, rest);
18523
19041
  case "pair":
18524
- return pairCommand(rest, boundApi(config));
19042
+ return pairCommand(rest, boundApi(config), async () => {
19043
+ try {
19044
+ const machine = await request(
19045
+ config,
19046
+ "GET",
19047
+ "/machine"
19048
+ );
19049
+ return machine.t3Gateway ?? null;
19050
+ } catch {
19051
+ return null;
19052
+ }
19053
+ });
18525
19054
  case "invite":
18526
19055
  return inviteCommand(boundApi(config), config.url, rest);
18527
19056
  case "members":