@sixb/deploy-ssh 0.2.5 → 0.2.7

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 (64) hide show
  1. package/README.md +51 -42
  2. package/dist/check/index.d.ts +24 -0
  3. package/dist/check/index.d.ts.map +1 -0
  4. package/dist/check/judge.d.ts +23 -0
  5. package/dist/check/judge.d.ts.map +1 -0
  6. package/dist/index.js +599 -1102
  7. package/dist/index.js.map +10 -15
  8. package/dist/layout.d.ts +91 -18
  9. package/dist/layout.d.ts.map +1 -1
  10. package/dist/operations.d.ts +5 -2
  11. package/dist/operations.d.ts.map +1 -1
  12. package/dist/plan.d.ts +25 -0
  13. package/dist/plan.d.ts.map +1 -0
  14. package/dist/render.d.ts +20 -10
  15. package/dist/render.d.ts.map +1 -1
  16. package/dist/server/manifest.d.ts +15 -3
  17. package/dist/server/manifest.d.ts.map +1 -1
  18. package/dist/server/release-host.d.ts +4 -0
  19. package/dist/server/release-host.d.ts.map +1 -0
  20. package/dist/server/release.d.ts +46 -0
  21. package/dist/server/release.d.ts.map +1 -0
  22. package/dist/server/state.d.ts +2 -0
  23. package/dist/server/state.d.ts.map +1 -1
  24. package/dist/server/supervisor.d.ts +12 -4
  25. package/dist/server/supervisor.d.ts.map +1 -1
  26. package/dist/ssh-target.d.ts +3 -18
  27. package/dist/ssh-target.d.ts.map +1 -1
  28. package/dist/transport.d.ts.map +1 -1
  29. package/package.json +3 -3
  30. package/src/bootstrap.sh +93 -0
  31. package/src/check/index.ts +117 -0
  32. package/src/check/judge.ts +299 -0
  33. package/src/check/probe.sh +99 -0
  34. package/src/layout.ts +117 -34
  35. package/src/operations.ts +104 -61
  36. package/src/plan.ts +59 -0
  37. package/src/render.ts +128 -31
  38. package/src/server/cli.ts +26 -9
  39. package/src/server/manifest.ts +42 -4
  40. package/src/server/release-host.ts +81 -0
  41. package/src/server/release.ts +738 -0
  42. package/src/server/state.ts +3 -1
  43. package/src/server/supervisor.ts +127 -55
  44. package/src/sh.d.ts +4 -0
  45. package/src/ssh-target.ts +46 -227
  46. package/src/transport.ts +28 -12
  47. package/dist/access.d.ts +0 -11
  48. package/dist/access.d.ts.map +0 -1
  49. package/dist/check.d.ts +0 -31
  50. package/dist/check.d.ts.map +0 -1
  51. package/dist/ci.d.ts +0 -27
  52. package/dist/ci.d.ts.map +0 -1
  53. package/dist/keys.d.ts +0 -13
  54. package/dist/keys.d.ts.map +0 -1
  55. package/dist/scripts.d.ts +0 -38
  56. package/dist/scripts.d.ts.map +0 -1
  57. package/dist/setup.d.ts +0 -32
  58. package/dist/setup.d.ts.map +0 -1
  59. package/src/access.ts +0 -107
  60. package/src/check.ts +0 -231
  61. package/src/ci.ts +0 -88
  62. package/src/keys.ts +0 -57
  63. package/src/scripts.ts +0 -323
  64. package/src/setup.ts +0 -203
package/dist/index.js.map CHANGED
@@ -1,24 +1,19 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/ssh-target.ts", "../src/access.ts", "../src/keys.ts", "../src/shell.ts", "../src/check.ts", "../src/layout.ts", "../src/ci.ts", "../src/operations.ts", "../src/update-page.ts", "../src/render.ts", "../src/scripts.ts", "../src/server/logs.ts", "../src/transport.ts", "../src/setup.ts", "../src/ssh-config.ts"],
3
+ "sources": ["../src/ssh-target.ts", "../src/check/index.ts", "../src/shell.ts", "../src/check/judge.ts", "../src/layout.ts", "../src/operations.ts", "../src/plan.ts", "../src/server/logs.ts", "../src/transport.ts", "../src/ssh-config.ts"],
4
4
  "sourcesContent": [
5
- "import { isIPv6 } from \"node:net\"\nimport type {\n DeployAccess,\n DeployAccessKey,\n DeployCheck,\n DeployCheckContext,\n DeployCi,\n DeployCiCredential,\n DeployContext,\n DeployControlAction,\n DeployHttpServiceName,\n DeployListenAddress,\n DeployLogsOptions,\n DeployOperationContext,\n DeployRelease,\n DeployScript,\n DeploySetupContext,\n DeploySource,\n DeployStatus,\n DeployTarget,\n} from \"@sixb/core/deploy\"\nimport { addKey, listKeys, removeKeys, removeKeysWhere } from \"./access\"\nimport { checkDns, ENV_TOKEN_CHECK, runChecks } from \"./check\"\nimport { generateCiKey, knownHostsLines, readHostKeys, renderCiInstall } from \"./ci\"\nimport { ENV_TOKEN_FILE } from \"./layout\"\nimport {\n controlServices,\n deployRelease,\n readStatus,\n runDeployScript,\n streamLogs,\n} from \"./operations\"\nimport { ensureEnvToken, pickPublicKey, renderAdminScript } from \"./setup\"\nimport { shellQuote } from \"./shell\"\nimport { resolveSshConfig } from \"./ssh-config\"\nimport { RemoteScriptError, type RemoteShell, SshShell } from \"./transport\"\n\nexport interface SshTargetOptions {\n /** The server: a hostname, an IP address, or a `Host` alias from your SSH config. */\n readonly host: string\n /**\n * The Linux user the deployment runs as. Projects under one user can read each other's files,\n * so give a project its own user to wall it off from the others on the server. Defaults to\n * `\"sixb\"`.\n */\n readonly user?: string\n /**\n * Local ports for the HTTP services, which Caddy on the server forwards to. Set them when\n * projects share a server, so that each has its own. Defaults: app 3001, api 3002.\n */\n readonly ports?: Readonly<Partial<Record<DeployHttpServiceName, number>>>\n}\n\nconst OPTIONS = [\"host\", \"user\", \"ports\"] as const\n\nconst DEFAULT_USER = \"sixb\"\n\nconst DEFAULT_PORTS = {\n app: 3001,\n api: 3002,\n} as const satisfies Record<DeployHttpServiceName, number>\n\n/** Services listen on loopback only: Caddy on the same server is their one way in. */\nconst LISTEN_HOST = \"127.0.0.1\"\n\n/** A Linux account name `useradd` accepts. */\nconst USER_PATTERN = /^[a-z_][a-z0-9_-]{0,31}$/\n\n/** A server reached over SSH, where Caddy routes each domain to its service. */\nexport class SshTarget implements DeployTarget {\n readonly kind = \"ssh\"\n readonly host: string\n readonly user: string\n readonly location: string\n readonly #ports: Readonly<Record<DeployHttpServiceName, number>>\n\n constructor(options: SshTargetOptions) {\n if (typeof options !== \"object\" || options === null) {\n throw new Error(\n '[SshTarget] Pass options, such as `new SshTarget({ host: \"203.0.113.10\" })`.'\n )\n }\n for (const key of Object.keys(options)) {\n if (!(OPTIONS as readonly string[]).includes(key)) {\n throw new Error(`[SshTarget] Unknown option '${key}'. Available: ${OPTIONS.join(\", \")}.`)\n }\n }\n\n this.host = validateHost(options.host)\n this.user = validateUser(options.user ?? DEFAULT_USER)\n this.location = `${this.user}@${this.host}`\n this.#ports = { ...DEFAULT_PORTS, ...validatePorts(options.ports) }\n }\n\n listenAddress(service: DeployHttpServiceName): DeployListenAddress {\n return { host: LISTEN_HOST, port: this.#ports[service] }\n }\n\n deploy(release: DeployRelease, source: DeploySource, context: DeployContext): Promise<void> {\n return this.#connected((shell) => deployRelease(shell, this.user, release, source, context))\n }\n\n status(context: DeployOperationContext): Promise<DeployStatus> {\n return this.#connected((shell) => readStatus(shell, context.name))\n }\n\n logs(options: DeployLogsOptions, context: DeployOperationContext): Promise<void> {\n // Following in a terminal attaches it, so Ctrl-C stops the remote reader too.\n const terminal = options.follow && Boolean(process.stdin.isTTY && process.stdout.isTTY)\n return this.#connected((shell) => streamLogs(shell, context.name, { ...options, terminal }))\n }\n\n control(\n action: DeployControlAction,\n service: string | undefined,\n context: DeployOperationContext\n ): Promise<void> {\n return this.#connected((shell) => controlServices(shell, context.name, action, service))\n }\n\n run(script: DeployScript, context: DeployOperationContext): Promise<number> {\n return this.#connected((shell) => runDeployScript(shell, context.name, script))\n }\n\n async check(release: DeployRelease, context: DeployCheckContext): Promise<DeployCheck[]> {\n const { hostname } = await resolveSshConfig(this.location)\n const dns = checkDns(release, hostname)\n let server: DeployCheck[]\n try {\n server = await this.#connected(async (shell) => [\n { id: \"ssh\", label: \"SSH\", status: \"ok\" as const, detail: this.location },\n ...(await runChecks(shell, {\n name: context.name,\n projectPath: context.projectPath,\n ports: release.services.flatMap((service) =>\n service.http ? [{ service: service.name, port: service.http.port }] : []\n ),\n envFromSource: release.steps.env !== undefined,\n location: this.location,\n })),\n ])\n } catch (error) {\n server = [sshCheck(this.location, error)]\n }\n return [...server, ...(await dns)]\n }\n\n /**\n * Prepares the server as the admin login when the deploy user or the server is not set up\n * yet, then the project as the deploy user. Running it again changes nothing that is right.\n */\n async setup(release: DeployRelease, context: DeploySetupContext): Promise<void> {\n const before = await this.check(release, context)\n const serverFixes = before.filter(\n (check) =>\n (check.status === \"fixable\" &&\n check.id !== \"project.env\" &&\n check.id !== ENV_TOKEN_CHECK) ||\n (check.id === \"ssh\" && check.status !== \"ok\")\n )\n const unreachable = before.find((check) => check.id === \"ssh\" && check.status === \"manual\")\n if (unreachable) {\n throw new Error(`[SshTarget] ${unreachable.detail}`)\n }\n\n if (serverFixes.length > 0) {\n const admin = context.admin ?? \"root\"\n const { identityFiles } = await resolveSshConfig(this.location)\n const key = await pickPublicKey({ key: context.key, identityFiles })\n context.write(\n `Setting up ${this.host} as ${admin}, authorizing ${key.source} for ${this.user}.`\n )\n await runAsAdmin(\n `${admin}@${this.host}`,\n admin === \"root\",\n renderAdminScript({ user: this.user, publicKey: key.text, admin })\n )\n }\n\n context.write(`Preparing ${context.name} as ${this.user}.`)\n await this.#connected((shell) =>\n shell.run(\n [\n `project=\"$HOME\"/${shellQuote(`${context.name}/code/${context.projectPath}`)}`,\n 'mkdir -p \"$project\"',\n 'if [ -f \"$project/.env\" ]; then chmod 600 \"$project/.env\"; fi',\n `token=\"$HOME\"/${shellQuote(`${context.name}/${ENV_TOKEN_FILE}`)}`,\n 'if [ -f \"$token\" ]; then chmod 600 \"$token\"; fi',\n ].join(\"\\n\")\n )\n )\n\n const { createEnvToken } = context\n if (release.steps.env && createEnvToken) {\n const installed = await this.#connected((shell) =>\n ensureEnvToken(shell, context.name, createEnvToken)\n )\n if (installed) context.write(`Installed a read-only token for ${context.name}.`)\n }\n }\n\n readonly access: DeployAccess = {\n list: () => this.#connected(async (shell) => (await listKeys(shell)).map(withoutLine)),\n add: (key) => this.#connected((shell) => addKey(shell, key)).then(withoutLine),\n remove: (match) =>\n this.#connected(async (shell) => (await removeKeys(shell, match)).map(withoutLine)),\n }\n\n readonly ci: DeployCi = {\n create: (job, context) => this.#createCiKey(job, context.name),\n }\n\n /**\n * A key for one CI job, allowed to run commands and nothing else (no forwarding, no terminal),\n * with the server's host keys pinned so CI never trusts an address on first sight.\n */\n async #createCiKey(job: string, name: string): Promise<DeployCiCredential> {\n const ssh = await resolveSshConfig(this.location)\n if (ssh.proxyJump) {\n throw new Error(\n `[SshTarget] Your SSH config reaches ${this.host} through ${ssh.proxyJump}, and CI connects ` +\n \"directly. Set `host` to an address CI can reach.\"\n )\n }\n // One comment per job and deployment: it is how a later run finds the keys it replaces.\n const comment = `sixb-ci:${name}@${job}`\n const pair = await generateCiKey(comment)\n const { key, hostKeys } = await this.#connected(async (shell) => ({\n hostKeys: await readHostKeys(shell),\n key: await addKey(shell, pair.publicKey, \"restrict\"),\n }))\n\n return {\n description: `${key.fingerprint} for ${this.location}, restricted to running commands`,\n secrets: {\n SIXB_DEPLOY_SSH_KEY: pair.privateKey,\n SIXB_DEPLOY_KNOWN_HOSTS: knownHostsLines(hostKeys, ssh.hostname, ssh.port).join(\"\\n\"),\n },\n install: renderCiInstall({ host: this.host, hostname: ssh.hostname, port: ssh.port }),\n retireOthers: () =>\n this.#connected(async (shell) =>\n (\n await removeKeysWhere(\n shell,\n (other) => other.comment === comment && other.fingerprint !== key.fingerprint\n )\n ).map(withoutLine)\n ),\n revoke: () =>\n this.#connected(async (shell) => {\n await removeKeysWhere(shell, (other) => other.fingerprint === key.fingerprint)\n }),\n }\n }\n\n async #connected<T>(work: (shell: RemoteShell) => Promise<T>): Promise<T> {\n const shell = await SshShell.open(this.location)\n try {\n return await work(shell)\n } finally {\n await shell.close()\n }\n }\n}\n\nfunction validateHost(value: unknown): string {\n if (typeof value !== \"string\" || value.trim() === \"\") {\n throw new Error(\"[SshTarget] host must be the server's hostname or IP address.\")\n }\n const host = value.trim()\n if (host.includes(\"@\")) {\n throw new Error(\n `[SshTarget] host '${host}' includes a user. Set the host alone, and the user with \\`user\\`.`\n )\n }\n // `ssh` reads an argument that starts with `-` as an option, not a host.\n if (host.startsWith(\"-\") || /[\\s/\\\\]/.test(host)) {\n throw new Error(`[SshTarget] host '${host}' is not a hostname or IP address.`)\n }\n if (host.includes(\":\") && !isIPv6(host)) {\n throw new Error(\n `[SshTarget] host '${host}' includes a port. For an SSH port other than 22, add a Host ` +\n \"entry with that Port to your SSH config and use its name as the host.\"\n )\n }\n return host\n}\n\nfunction validateUser(value: unknown): string {\n if (value === \"root\") {\n throw new Error(\n \"[SshTarget] Deployments never run as root. Use a deploy user without sudo, such as the \" +\n 'default \"sixb\".'\n )\n }\n if (typeof value !== \"string\" || !USER_PATTERN.test(value)) {\n throw new Error(\n `[SshTarget] user ${JSON.stringify(value)} is not a Linux user name. Use lowercase ` +\n \"letters, digits, underscores, and hyphens, starting with a letter or underscore.\"\n )\n }\n return value\n}\n\nfunction validatePorts(value: unknown): Partial<Record<DeployHttpServiceName, number>> {\n if (value === undefined) return {}\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(\"[SshTarget] ports must be an object, such as `{ api: 3012 }`.\")\n }\n\n const ports: Partial<Record<DeployHttpServiceName, number>> = {}\n for (const [service, port] of Object.entries(value)) {\n if (!Object.hasOwn(DEFAULT_PORTS, service)) {\n throw new Error(`[SshTarget] ports.${service} is not an HTTP service. Available: api, app.`)\n }\n // A deploy user has no privileges, and ports below 1024 need them.\n if (!Number.isInteger(port) || port < 1024 || port > 65_535) {\n throw new Error(`[SshTarget] ports.${service} must be a port from 1024 to 65535.`)\n }\n ports[service as DeployHttpServiceName] = port\n }\n return ports\n}\n\n/** What a failed connection means for a deploy, and whether setup can fix it. */\nfunction sshCheck(location: string, error: unknown): DeployCheck {\n const message =\n (error instanceof Error ? error.message : String(error))\n .split(\"\\n\")[0]\n ?.replace(/^\\[SshTarget\\] /, \"\") ?? \"\"\n if (error instanceof RemoteScriptError && /refused your SSH key/.test(message)) {\n return {\n id: \"ssh\",\n label: \"SSH\",\n status: \"fixable\",\n detail: message,\n remedy: `Run \\`sixb deploy setup --admin <login>\\` with a login that has sudo: it creates the deploy user and authorizes your key. Or have someone with access run \\`sixb deploy access add\\` with your key.`,\n }\n }\n return {\n id: \"ssh\",\n label: \"SSH\",\n status: \"manual\",\n detail: message || `Cannot reach ${location}.`,\n }\n}\n\nfunction withoutLine({ type, fingerprint, comment, restricted }: DeployAccessKey): DeployAccessKey {\n return { type, fingerprint, comment, restricted }\n}\n\n/**\n * Runs the setup script as the admin login with the terminal attached, so sudo can ask for its\n * password and the person running setup sees each step.\n */\nasync function runAsAdmin(destination: string, root: boolean, script: string): Promise<void> {\n const command = `${root ? \"\" : \"sudo \"}bash -c ${shellQuote(script)}`\n // LogLevel=ERROR drops the \"Connection closed\" line a terminal session ends with, not errors.\n const ssh = [\"ssh\", \"-tt\", \"-o\", \"ConnectTimeout=15\", \"-o\", \"LogLevel=ERROR\"]\n const child = Bun.spawn([...ssh, destination, command], {\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\n })\n const exitCode = await child.exited\n if (exitCode !== 0) {\n throw new Error(\n `[SshTarget] Setting up the server as ${destination} failed (exit code ${exitCode}).`\n )\n }\n}\n",
6
- "import { createHash } from \"node:crypto\"\nimport type { DeployAccessKey } from \"@sixb/core/deploy\"\nimport { type AuthorizedKey, parseAuthorizedKey, parsePublicKey } from \"./keys\"\nimport { shellQuote } from \"./shell\"\nimport type { RemoteShell } from \"./transport\"\n\ninterface KeysFile {\n readonly lines: readonly string[]\n readonly keys: readonly AuthorizedKey[]\n readonly hash: string\n}\n\nexport async function listKeys(shell: RemoteShell): Promise<AuthorizedKey[]> {\n return [...(await readKeysFile(shell)).keys]\n}\n\n/** Authorizes a public key once, with `options` (such as `restrict`) in front of it. */\nexport async function addKey(\n shell: RemoteShell,\n text: string,\n options?: string\n): Promise<AuthorizedKey> {\n const parsed = parsePublicKey(text)\n const key = options ? (parseAuthorizedKey(`${options} ${parsed.line}`) ?? parsed) : parsed\n const file = await readKeysFile(shell)\n if (file.keys.some((candidate) => candidate.fingerprint === key.fingerprint)) return key\n await rewrite(shell, [...file.lines, key.line], file.hash)\n return key\n}\n\n/** Removes the keys whose fingerprint or comment is `match`. Never removes the last one. */\nexport async function removeKeys(shell: RemoteShell, match: string): Promise<DeployAccessKey[]> {\n const removed = await removeKeysWhere(\n shell,\n (key) => key.fingerprint === match || key.comment === match\n )\n if (removed.length === 0) {\n throw new Error(`[SshTarget] No authorized key has the fingerprint or comment '${match}'.`)\n }\n return removed\n}\n\n/** Removes the keys `matches` picks, if any. Never removes the last one. */\nexport async function removeKeysWhere(\n shell: RemoteShell,\n matches: (key: AuthorizedKey) => boolean\n): Promise<AuthorizedKey[]> {\n const file = await readKeysFile(shell)\n const removed = file.keys.filter(matches)\n if (removed.length === 0) return []\n if (removed.length === file.keys.length) {\n throw new Error(\n \"[SshTarget] That would remove every key, and nobody could reach the deployment. \" +\n \"Add another key first.\"\n )\n }\n const gone = new Set(removed.map((key) => key.line))\n await rewrite(\n shell,\n file.lines.filter((line) => !gone.has(line.trim())),\n file.hash\n )\n return removed\n}\n\nasync function readKeysFile(shell: RemoteShell): Promise<KeysFile> {\n const encoded: string[] = []\n await shell.run('(base64 < \"$HOME/.ssh/authorized_keys\" 2> /dev/null || true) | tr -d \"\\\\n\"', {\n onLine: (line, stream) => {\n if (stream === \"stdout\") encoded.push(line)\n },\n })\n const content = Buffer.from(encoded.join(\"\"), \"base64\").toString(\"utf8\")\n const lines = content.split(\"\\n\").filter((line, index, all) => line || index < all.length - 1)\n return {\n lines,\n keys: lines.flatMap((line) => parseAuthorizedKey(line) ?? []),\n hash: sha256(content),\n }\n}\n\n/**\n * Replaces `authorized_keys` through a rename, other lines untouched. Fails if the file changed\n * since it was read, so two people changing access at once cannot drop each other's key.\n */\nasync function rewrite(shell: RemoteShell, lines: readonly string[], readHash: string) {\n const content = `${lines.join(\"\\n\")}\\n`\n await shell.run(\n [\n \"set -euo pipefail\",\n 'keys=\"$HOME/.ssh/authorized_keys\"',\n 'mkdir -p -m 700 \"$HOME/.ssh\"',\n 'current=\"$( (cat \"$keys\" 2> /dev/null || true) | sha256sum | cut -d\" \" -f1)\"',\n `if [ \"$current\" != ${shellQuote(readHash)} ]; then`,\n ' echo \"authorized_keys changed while this ran; run the command again.\" >&2',\n \" exit 1\",\n \"fi\",\n `printf '%s' ${shellQuote(Buffer.from(content).toString(\"base64\"))} | base64 -d > \"$keys.new\"`,\n 'chmod 600 \"$keys.new\"',\n 'mv \"$keys.new\" \"$keys\"',\n ].join(\"\\n\")\n )\n}\n\nfunction sha256(content: string): string {\n return createHash(\"sha256\").update(content).digest(\"hex\")\n}\n",
7
- "import { createHash } from \"node:crypto\"\nimport type { DeployAccessKey } from \"@sixb/core/deploy\"\n\nconst KEY_TYPES = new Set([\n \"ssh-ed25519\",\n \"ssh-rsa\",\n \"ecdsa-sha2-nistp256\",\n \"ecdsa-sha2-nistp384\",\n \"ecdsa-sha2-nistp521\",\n \"sk-ssh-ed25519@openssh.com\",\n \"sk-ecdsa-sha2-nistp256@openssh.com\",\n])\n\nexport interface AuthorizedKey extends DeployAccessKey {\n /** The line as it appears in `authorized_keys`. */\n readonly line: string\n}\n\n/**\n * One `authorized_keys` line: optional options, then type, key, and comment. Returns `null` for\n * blank lines, comments, and anything that is not a public key.\n */\nexport function parseAuthorizedKey(line: string): AuthorizedKey | null {\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith(\"#\")) return null\n const words = trimmed.split(/\\s+/)\n const typeIndex = words.findIndex((word) => KEY_TYPES.has(word))\n if (typeIndex === -1) return null\n const type = words[typeIndex] ?? \"\"\n const encoded = words[typeIndex + 1] ?? \"\"\n\n const blob = Buffer.from(encoded, \"base64\")\n // The blob names its own type first; a key pasted under another type is not that key.\n const nameLength = blob.length >= 4 ? blob.readUInt32BE(0) : 0\n if (blob.subarray(4, 4 + nameLength).toString() !== type) return null\n\n const options = typeIndex > 0 ? words.slice(0, typeIndex).join(\" \") : \"\"\n return {\n type,\n fingerprint: `SHA256:${createHash(\"sha256\").update(blob).digest(\"base64\").replace(/=+$/, \"\")}`,\n comment: words.slice(typeIndex + 2).join(\" \"),\n restricted: /(^|,)restrict(,|$)/.test(options),\n line: trimmed,\n }\n}\n\n/** Parses a public key given as text, failing with what is wrong with it. */\nexport function parsePublicKey(text: string): AuthorizedKey {\n const key = parseAuthorizedKey(text)\n if (!key || key.line.includes(\"\\n\")) {\n throw new Error(\n \"[SshTarget] That is not an SSH public key. Pass the contents of a .pub file, such as \" +\n \"`ssh-ed25519 AAAA… you@laptop`.\"\n )\n }\n return key\n}\n",
5
+ "import { isIPv6 } from \"node:net\"\nimport type {\n DeployCheck,\n DeployCheckContext,\n DeployContext,\n DeployControlAction,\n DeployHttpServiceName,\n DeployListenAddress,\n DeployLogsOptions,\n DeployOperationContext,\n DeployRelease,\n DeployScript,\n DeploySource,\n DeployStatus,\n DeployTarget,\n} from \"@sixb/core/deploy\"\nimport { checkDns, checkHost } from \"./check\"\nimport { SLOT_PORTS } from \"./layout\"\nimport {\n controlServices,\n deployRelease,\n readStatus,\n runDeployScript,\n streamLogs,\n} from \"./operations\"\nimport { resolveSshConfig } from \"./ssh-config\"\nimport { type RemoteShell, SshShell } from \"./transport\"\n\nexport interface SshTargetOptions {\n /** The server: a hostname, an IP address, or a `Host` alias from your SSH config. */\n readonly host: string\n /** The account the deployment logs in and runs as, never `root`. Defaults to `\"sixb\"`. */\n readonly user?: string\n}\n\nconst DEFAULT_USER = \"sixb\"\n\n/** Options earlier versions took, and why they went. */\nconst REMOVED_OPTIONS: Readonly<Record<string, string>> = {\n ports: \"a server runs one deployment, on fixed ports\",\n standbyPorts: \"a server runs one deployment, on fixed ports\",\n}\n\n/** A Linux account name `useradd` accepts. */\nconst USER_PATTERN = /^[a-z_][a-z0-9_-]{0,31}$/\n\n/** Services listen on loopback only: Caddy on the same server is their one way in. */\nconst LISTEN_HOST = \"127.0.0.1\"\n\n/** A server reached over SSH, where Caddy routes each domain to its service. */\nexport class SshTarget implements DeployTarget {\n readonly kind = \"ssh\"\n readonly host: string\n /** The account the deployment logs in and runs as. */\n readonly user: string\n readonly location: string\n\n constructor(options: SshTargetOptions) {\n if (typeof options !== \"object\" || options === null) {\n throw new Error(\n '[SshTarget] Pass options, such as `new SshTarget({ host: \"203.0.113.10\" })`.'\n )\n }\n for (const key of Object.keys(options)) {\n const removed = REMOVED_OPTIONS[key]\n if (removed) throw new Error(`[SshTarget] Remove \\`${key}\\`: ${removed}.`)\n if (key !== \"host\" && key !== \"user\") {\n throw new Error(`[SshTarget] Unknown option '${key}'. Available: host, user.`)\n }\n }\n\n this.host = validateHost(options.host)\n this.user = validateUser(options.user ?? DEFAULT_USER)\n this.location = `${this.user}@${this.host}`\n }\n\n listenAddress(service: DeployHttpServiceName): DeployListenAddress {\n return { host: LISTEN_HOST, port: SLOT_PORTS.blue[service] }\n }\n\n deploy(release: DeployRelease, source: DeploySource, context: DeployContext): Promise<void> {\n return this.#connected((shell) => deployRelease(shell, release, source, context))\n }\n\n status(context: DeployOperationContext): Promise<DeployStatus> {\n return this.#connected((shell) => readStatus(shell, context.name))\n }\n\n logs(options: DeployLogsOptions, context: DeployOperationContext): Promise<void> {\n // Following in a terminal attaches it, so Ctrl-C stops the remote reader too.\n const terminal = options.follow && Boolean(process.stdin.isTTY && process.stdout.isTTY)\n return this.#connected((shell) => streamLogs(shell, context.name, { ...options, terminal }))\n }\n\n control(\n action: DeployControlAction,\n service: string | undefined,\n context: DeployOperationContext\n ): Promise<void> {\n return this.#connected((shell) => controlServices(shell, context.name, action, service))\n }\n\n run(script: DeployScript, context: DeployOperationContext): Promise<number> {\n return this.#connected((shell) => runDeployScript(shell, context.name, script))\n }\n\n async check(release: DeployRelease, context: DeployCheckContext): Promise<DeployCheck[]> {\n const { hostname } = await resolveSshConfig(this.location)\n const dns = checkDns(release, hostname)\n let server: DeployCheck[]\n try {\n server = await this.#connected(async (shell) => [\n { id: \"ssh\", label: \"SSH\", status: \"ok\" as const, detail: this.location },\n ...(await checkHost(shell, {\n name: context.name,\n projectPath: context.projectPath,\n ports: [...Object.values(SLOT_PORTS.blue), ...Object.values(SLOT_PORTS.green)],\n settings:\n release.steps.env === undefined\n ? \"env-file\"\n : context.envToken\n ? \"env-token\"\n : \"identity\",\n chromium: context.chromium,\n })),\n ])\n } catch (error) {\n server = [sshCheck(this.location, error)]\n }\n return [...server, ...(await dns)]\n }\n\n async #connected<T>(work: (shell: RemoteShell) => Promise<T>): Promise<T> {\n const shell = await SshShell.open(this.location)\n try {\n return await work(shell)\n } finally {\n await shell.close()\n }\n }\n}\n\nfunction validateUser(value: unknown): string {\n if (value === \"root\") {\n throw new Error(\"[SshTarget] Deployments never run as root. Use an account without sudo.\")\n }\n if (typeof value !== \"string\" || !USER_PATTERN.test(value)) {\n throw new Error(\n `[SshTarget] user ${JSON.stringify(value)} is not a Linux account name. Use lowercase ` +\n \"letters, digits, underscores and hyphens, starting with a letter or underscore.\"\n )\n }\n return value\n}\n\nfunction validateHost(value: unknown): string {\n if (typeof value !== \"string\" || value.trim() === \"\") {\n throw new Error(\"[SshTarget] host must be the server's hostname or IP address.\")\n }\n const host = value.trim()\n if (host.includes(\"@\")) {\n throw new Error(\n `[SshTarget] host '${host}' includes a user. Set the host alone, and the account with \\`user\\`.`\n )\n }\n // `ssh` reads an argument that starts with `-` as an option, not a host.\n if (host.startsWith(\"-\") || /[\\s/\\\\]/.test(host)) {\n throw new Error(`[SshTarget] host '${host}' is not a hostname or IP address.`)\n }\n if (host.includes(\":\") && !isIPv6(host)) {\n throw new Error(\n `[SshTarget] host '${host}' includes a port. For an SSH port other than 22, add a Host ` +\n \"entry with that Port to your SSH config and use its name as the host.\"\n )\n }\n return host\n}\n\n/** A failed connection, as the check that stops a deploy. */\nfunction sshCheck(location: string, error: unknown): DeployCheck {\n const [message = \"\"] = (error instanceof Error ? error.message : String(error)).split(\"\\n\")\n return {\n id: \"ssh\",\n label: \"SSH\",\n status: \"fail\",\n detail: message.replace(/^\\[SshTarget\\] /, \"\") || `Cannot reach ${location}.`,\n }\n}\n",
6
+ "/// <reference path=\"../sh.d.ts\" />\nimport { resolve4, resolve6 } from \"node:dns/promises\"\nimport { isIP } from \"node:net\"\nimport type { DeployCheck, DeployRelease } from \"@sixb/core/deploy\"\nimport { shellQuote } from \"../shell\"\nimport type { RemoteShell } from \"../transport\"\nimport { type JudgeInput, judge, parseFacts } from \"./judge\"\nimport probe from \"./probe.sh\" with { type: \"text\" }\n\nexport { HOST_REQUIREMENTS } from \"./judge\"\n\n/** Runs the read-only probe as the deploy account, and judges what it reports. */\nexport async function checkHost(\n shell: RemoteShell,\n input: JudgeInput & { readonly projectPath: string }\n): Promise<DeployCheck[]> {\n const lines: string[] = []\n await shell.run(renderProbe(input), {\n onLine: (line, stream) => {\n if (stream === \"stdout\") lines.push(line)\n },\n })\n return judge(parseFacts(lines), input)\n}\n\n/** The probe, with what it needs to know set above it. */\nexport function renderProbe(input: {\n readonly name: string\n readonly projectPath: string\n readonly ports: readonly number[]\n readonly chromium: boolean\n}): string {\n return [\n `SIXB_NAME=${shellQuote(input.name)}`,\n `SIXB_PROJECT=${shellQuote(input.projectPath)}`,\n `SIXB_PORTS=${shellQuote(input.ports.join(\" \"))}`,\n `SIXB_CHROMIUM=${input.chromium ? 1 : 0}`,\n probe,\n ].join(\"\\n\")\n}\n\n/**\n * Where each HTTP domain resolves, against the server's address. Reached over a tailnet or a\n * private network, the server's public address is unknown here, so the check only says where\n * each domain points.\n */\nexport async function checkDns(release: DeployRelease, hostname: string): Promise<DeployCheck[]> {\n const server = isIP(hostname) ? [hostname] : await lookup(hostname)\n const comparable = server.length > 0 && server.every((address) => !isPrivateAddress(address))\n return Promise.all(\n release.services.flatMap((service) => {\n const domain = service.http?.domain\n if (!domain) return []\n return [\n (async (): Promise<DeployCheck> => {\n const found = await lookup(domain)\n const id = `dns.${service.name}`\n const label = `${service.name} DNS`\n const detail = `${domain} → ${found.join(\", \")}`\n if (found.length === 0) {\n return {\n id,\n label,\n status: \"warning\",\n detail: `${domain} does not resolve`,\n remedy: `Point ${domain} at the server. Until then, Caddy cannot get it a certificate.`,\n }\n }\n if (!comparable || found.some((address) => server.includes(address))) {\n return { id, label, status: \"ok\", detail }\n }\n const target = server[0] ?? hostname\n return {\n id,\n label,\n status: \"warning\",\n detail,\n remedy: `Point ${domain} at ${target} with an ${isIP(target) === 6 ? \"AAAA\" : \"A\"} record. Until then, Caddy cannot get it a certificate.`,\n }\n })(),\n ]\n })\n )\n}\n\n/** Private, carrier-grade NAT (Tailscale's 100.64.0.0/10) and unique-local addresses. */\nexport function isPrivateAddress(address: string): boolean {\n if (isIP(address) === 6) return /^f[cd]/i.test(address) || address === \"::1\"\n const [a = 0, b = 0] = address.split(\".\").map(Number)\n return (\n a === 10 ||\n a === 127 ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) ||\n (a === 100 && b >= 64 && b <= 127)\n )\n}\n\nasync function lookup(hostname: string): Promise<string[]> {\n const [v4, v6] = await Promise.all([settle(resolve4(hostname)), settle(resolve6(hostname))])\n return [...v4, ...v6]\n}\n\n/** A lookup's answers, or none once it fails or takes over four seconds. */\nasync function settle(query: Promise<string[]>): Promise<string[]> {\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n query.catch(() => []),\n new Promise<string[]>((resolveTimeout) => {\n timer = setTimeout(() => resolveTimeout([]), 4_000)\n }),\n ])\n } finally {\n clearTimeout(timer)\n }\n}\n",
8
7
  "/** Quotes a value as one POSIX shell word. */\nexport function shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`\n}\n\n/** A shell command that writes `content` to `path`, whatever bytes it holds. */\nexport function writeFileCommand(path: string, content: string): string {\n const encoded = Buffer.from(content, \"utf8\").toString(\"base64\")\n return `printf '%s' ${shellQuote(encoded)} | base64 -d > ${shellQuote(path)}`\n}\n",
9
- "import { resolve4, resolve6 } from \"node:dns/promises\"\nimport { isIP } from \"node:net\"\nimport { posix } from \"node:path\"\nimport type { DeployCheck, DeployRelease } from \"@sixb/core/deploy\"\nimport { ENV_TOKEN_FILE } from \"./layout\"\nimport { shellQuote } from \"./shell\"\nimport type { RemoteShell } from \"./transport\"\n\nexport const CHECK_MARKER = \"__SIXB_CHECK__\"\n\n/** The tools a deploy runs on the server. */\nconst TOOLS = [\"git\", \"curl\", \"unzip\", \"tar\", \"flock\", \"sha256sum\", \"caddy\"]\n\nexport const ENV_TOKEN_CHECK = \"project.env-token\"\n\ntype Status = DeployCheck[\"status\"]\n\n/**\n * Checks the server as the deploy user, changing nothing. Each check prints one\n * `__SIXB_CHECK__ id status detail` line; labels and remedies are added on this side.\n */\nexport function renderCheckScript(input: {\n readonly name: string\n readonly projectPath: string\n readonly ports: readonly { readonly service: string; readonly port: number }[]\n /** A deploy writes `.env` from the project's source, so what it needs is the token instead. */\n readonly envFromSource?: boolean\n}): string {\n const project = posix.join(input.name, \"code\", input.projectPath)\n const envToken = posix.join(input.name, ENV_TOKEN_FILE)\n return [\n `emit() { printf '${CHECK_MARKER}\\\\t%s\\\\t%s\\\\t%s\\\\n' \"$1\" \"$2\" \"$(printf '%s' \"$3\" | tr '\\\\t\\\\n' ' ')\"; }`,\n `project=\"$HOME\"/${shellQuote(project)}`,\n `manifest=\"$HOME\"/${shellQuote(input.name)}/deploy/processes.json`,\n 'routes_dir=\"/etc/caddy/sixb.d/$USER\"',\n `snippet=\"$routes_dir\"/${shellQuote(`${input.name}.caddy`)}`,\n \"\",\n \"if command -v apt-get > /dev/null && command -v systemctl > /dev/null; then\",\n ' emit server.os ok \"$(. /etc/os-release 2>/dev/null; echo \"$PRETTY_NAME\")\"',\n \"else\",\n ' emit server.os manual \"$(uname -s) without apt and systemd\"',\n \"fi\",\n \"\",\n 'missing=\"\"',\n `for tool in ${TOOLS.join(\" \")}; do command -v \"$tool\" > /dev/null || missing=\"$missing $tool\"; done`,\n 'if [ -n \"$missing\" ]; then emit server.tools fixable \"missing:$missing\"',\n 'else emit server.tools ok \"Caddy $(caddy version 2>/dev/null | cut -d\" \" -f1), git, curl, unzip\"; fi',\n \"\",\n 'if [ -e \"/var/lib/systemd/linger/$USER\" ]; then emit server.linger ok \"on for $USER\"',\n 'else emit server.linger fixable \"off for $USER: services would stop when you log out\"; fi',\n \"\",\n \"if sudo -n -l /usr/bin/systemctl reload caddy > /dev/null 2>&1; then\",\n ' emit server.reload ok \"$USER may reload Caddy\"',\n \"else\",\n ' emit server.reload fixable \"$USER may not run sudo systemctl reload caddy\"',\n \"fi\",\n \"\",\n 'problems=\"\"',\n '[ -d \"$routes_dir\" ] && [ -w \"$routes_dir\" ] || problems=\"$problems; $routes_dir is missing or not writable\"',\n 'grep -qsF \"import $routes_dir/*.caddy\" \"/etc/caddy/sixb.d/$USER.caddy\" || problems=\"$problems; /etc/caddy/sixb.d/$USER.caddy does not import it\"',\n \"grep -qsF 'import /etc/caddy/sixb.d/*.caddy' /etc/caddy/Caddyfile || problems=\\\"$problems; /etc/caddy/Caddyfile does not import /etc/caddy/sixb.d/*.caddy\\\"\",\n 'if [ -z \"$problems\" ]; then emit server.routes ok \"$routes_dir\"',\n \"else emit server.routes fixable \\\"$(printf '%s' \\\"$problems\\\" | sed 's/^; //')\\\"; fi\",\n \"\",\n \"if ss -ltnH 2> /dev/null | grep -qE '(127\\\\.0\\\\.0\\\\.1|\\\\[::1\\\\]):2019 '; then\",\n ' emit server.admin-api warning \"Caddy\\'s admin API listens on localhost:2019, where any process on the server can change every route\"',\n \"else\",\n ' emit server.admin-api ok \"not on localhost:2019\"',\n \"fi\",\n \"\",\n ...(input.envFromSource\n ? [\n `token=\"$HOME\"/${shellQuote(envToken)}`,\n `if [ ! -s \"$token\" ]; then emit ${ENV_TOKEN_CHECK} fixable \"$token has no token\"`,\n `elif [ \"$(stat -c %a \"$token\")\" != 600 ]; then emit ${ENV_TOKEN_CHECK} fixable \"$token is readable by others (mode $(stat -c %a \"$token\"))\"`,\n `else emit ${ENV_TOKEN_CHECK} ok \"$token\"; fi`,\n ]\n : [\n 'if [ ! -f \"$project/.env\" ]; then emit project.env manual \"$project/.env does not exist\"',\n 'elif [ \"$(stat -c %a \"$project/.env\")\" != 600 ]; then emit project.env fixable \"$project/.env is readable by others (mode $(stat -c %a \"$project/.env\"))\"',\n 'else emit project.env ok \"$project/.env\"; fi',\n ]),\n \"\",\n ...input.ports.flatMap(({ service, port }) => [\n `if ss -ltnH \"sport = :${port}\" 2> /dev/null | grep -q .; then`,\n ` if grep -qs '\"--port\",' \"$manifest\" && grep -A1 -s '\"--port\",' \"$manifest\" | grep -q '\"${port}\"'; then`,\n ` emit project.port.${service} ok \"${port}, used by this deployment\"`,\n \" else\",\n ` emit project.port.${service} manual \"${port} is in use by another program\"`,\n \" fi\",\n `elif grep -ls '127.0.0.1:${port}\\\\b' /etc/caddy/sixb.d/*/*.caddy 2> /dev/null | grep -qv \"^$snippet$\"; then`,\n ` emit project.port.${service} manual \"${port} is routed to another deployment\"`,\n \"else\",\n ` emit project.port.${service} ok \"${port}\"`,\n \"fi\",\n ]),\n \"\",\n 'free_kb=\"$(df -Pk \"$HOME\" | awk \\'NR == 2 { print $4 + 0 }\\')\"',\n 'if [ \"$free_kb\" -lt 2097152 ]; then emit server.disk warning \"$((free_kb / 1024)) MB free\"',\n 'else emit server.disk ok \"$((free_kb / 1048576)) GB free\"; fi',\n ].join(\"\\n\")\n}\n\n/** Reads the check script's output into checks, with labels and remedies. */\nexport function parseCheckOutput(\n lines: readonly string[],\n context: { readonly location: string; readonly name: string }\n): DeployCheck[] {\n return lines.flatMap((line) => {\n const [marker, id, status, detail] = line.split(\"\\t\")\n if (marker !== CHECK_MARKER || !id || !isStatus(status)) return []\n return [describe(id, status, detail ?? \"\", context)]\n })\n}\n\n/** Where each HTTP domain resolves, against where the target is. */\nexport async function checkDns(release: DeployRelease, hostname: string): Promise<DeployCheck[]> {\n const expected = isIP(hostname) ? [hostname] : await lookup(hostname)\n return Promise.all(\n release.services.flatMap((service) => {\n const http = service.http\n if (!http) return []\n return [\n (async (): Promise<DeployCheck> => {\n const found = await lookup(http.domain)\n const id = `dns.${service.name}`\n const label = `${service.name} DNS`\n if (expected.length > 0 && found.some((address) => expected.includes(address))) {\n return { id, label, status: \"ok\", detail: `${http.domain} → ${found.join(\", \")}` }\n }\n const target = expected[0] ?? hostname\n return {\n id,\n label,\n status: \"warning\",\n detail:\n found.length > 0\n ? `${http.domain} → ${found.join(\", \")}`\n : `${http.domain} does not resolve`,\n remedy: `Point ${http.domain} at ${target} with an ${isIP(target) === 6 ? \"AAAA\" : \"A\"} record. Until then, Caddy cannot get it a certificate.`,\n }\n })(),\n ]\n })\n )\n}\n\n/** The checks that stop a deploy. */\nexport function blocksDeploy(check: DeployCheck): boolean {\n return check.status === \"fixable\" || check.status === \"manual\"\n}\n\nexport async function runChecks(\n shell: RemoteShell,\n input: Parameters<typeof renderCheckScript>[0] & { readonly location: string }\n): Promise<DeployCheck[]> {\n const lines: string[] = []\n await shell.run(renderCheckScript(input), {\n onLine: (line, stream) => {\n if (stream === \"stdout\") lines.push(line)\n },\n })\n return parseCheckOutput(lines, input)\n}\n\nconst LABELS: Readonly<Record<string, string>> = {\n \"server.os\": \"Server\",\n \"server.tools\": \"Server tools\",\n \"server.linger\": \"Services at boot\",\n \"server.reload\": \"Caddy reload\",\n \"server.routes\": \"Caddy routes\",\n \"server.admin-api\": \"Caddy admin API\",\n \"server.disk\": \"Disk space\",\n \"project.env\": \".env\",\n [ENV_TOKEN_CHECK]: \"Source token\",\n}\n\nfunction describe(\n id: string,\n status: Status,\n detail: string,\n context: { readonly location: string; readonly name: string }\n): DeployCheck {\n const label = LABELS[id] ?? (id.startsWith(\"project.port.\") ? `${id.slice(13)} port` : id)\n const check = { id, label, status, detail }\n if (status === \"ok\") return check\n if (status === \"fixable\") return { ...check, remedy: \"Run `sixb deploy setup`.\" }\n if (id === \"server.os\") return { ...check, remedy: \"Deploy to an Ubuntu or Debian server.\" }\n if (id === \"project.env\") {\n const path = detail.replace(/ does not exist$/, \"\")\n return {\n ...check,\n remedy: `Create it with the project's settings: \\`ssh ${context.location} 'install -m 600 /dev/null ${path}'\\`, then edit it.`,\n }\n }\n if (id.startsWith(\"project.port.\")) {\n return { ...check, remedy: \"Give this service another port in the target's `ports`.\" }\n }\n if (id === \"server.admin-api\") {\n return {\n ...check,\n remedy:\n \"Set `admin unix//var/lib/caddy/admin.sock` in the global options of /etc/caddy/Caddyfile.\",\n }\n }\n return check\n}\n\nfunction isStatus(value: string | undefined): value is Status {\n return value === \"ok\" || value === \"fixable\" || value === \"manual\" || value === \"warning\"\n}\n\nasync function lookup(hostname: string): Promise<string[]> {\n const [v4, v6] = await Promise.all([settle(resolve4(hostname)), settle(resolve6(hostname))])\n return [...v4, ...v6]\n}\n\n/** A lookup's answers, or none once it fails or takes over four seconds. */\nasync function settle(query: Promise<string[]>): Promise<string[]> {\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n query.catch(() => []),\n new Promise<string[]>((resolveTimeout) => {\n timer = setTimeout(() => resolveTimeout([]), 4_000)\n }),\n ])\n } finally {\n clearTimeout(timer)\n }\n}\n",
10
- "import { posix } from \"node:path\"\n\n/**\n * Where a deployment lives on its server. Everything but the Bun binaries and the Caddy route\n * sits in one directory in the deploy user's home, so projects under one user never share files.\n *\n * ~/<name>/code the deployed commit; the project is `code/<projectPath>`\n * ~/<name>/env-token the read-only token a deploy pulls `.env` with, if it has a source\n * ~/<name>/deploy lock, uploads, file list, release record, process manifest, ctl\n * ~/<name>/run supervisor state, control requests, and logs\n * ~/.sixb/bun/<v> Bun, shared by the user's projects that pin the same version\n */\nexport const ENV_TOKEN_FILE = \"env-token\"\n\nexport interface DeploymentLayout {\n readonly root: string\n readonly code: string\n readonly envToken: string\n readonly project: string\n readonly deployDir: string\n readonly incomingDir: string\n readonly lock: string\n readonly fileList: string\n readonly manifest: string\n readonly releaseRecord: string\n /** Runs the server half of this package with the project's Bun and manifest. */\n readonly ctl: string\n readonly runDir: string\n readonly logDir: string\n readonly bunDir: string\n readonly bun: string\n readonly unitName: string\n readonly unit: string\n readonly caddyDir: string\n readonly caddySnippet: string\n}\n\nexport function deploymentLayout(input: {\n readonly home: string\n readonly user: string\n readonly name: string\n readonly projectPath: string\n readonly bunVersion: string\n}): DeploymentLayout {\n const root = posix.join(input.home, input.name)\n const code = posix.join(root, \"code\")\n const deployDir = posix.join(root, \"deploy\")\n const runDir = posix.join(root, \"run\")\n const bunDir = posix.join(input.home, \".sixb\", \"bun\", input.bunVersion)\n const unitName = `sixb-${input.name}.service`\n const caddyDir = posix.join(\"/etc/caddy/sixb.d\", input.user)\n\n return {\n root,\n code,\n envToken: posix.join(root, ENV_TOKEN_FILE),\n project: posix.join(code, input.projectPath),\n deployDir,\n incomingDir: posix.join(deployDir, \"incoming\"),\n lock: posix.join(deployDir, \"lock\"),\n fileList: posix.join(deployDir, \"files.txt\"),\n manifest: posix.join(deployDir, \"processes.json\"),\n releaseRecord: posix.join(deployDir, \"release.json\"),\n ctl: posix.join(deployDir, \"ctl\"),\n runDir,\n logDir: posix.join(runDir, \"logs\"),\n bunDir,\n bun: posix.join(bunDir, \"bun\"),\n unitName,\n unit: posix.join(input.home, \".config\", \"systemd\", \"user\", unitName),\n caddyDir,\n caddySnippet: posix.join(caddyDir, `${input.name}.caddy`),\n }\n}\n",
11
- "import { mkdtemp, readFile, rm } from \"node:fs/promises\"\nimport { tmpdir } from \"node:os\"\nimport { join } from \"node:path\"\nimport type { RemoteShell } from \"./transport\"\n\n/**\n * A new key pair for a CI job. It is made in a directory that is removed before this returns, so\n * the private key exists only in memory here and, afterwards, in the CI system's secrets.\n */\nexport async function generateCiKey(\n comment: string\n): Promise<{ readonly privateKey: string; readonly publicKey: string }> {\n const dir = await mkdtemp(join(tmpdir(), \"sixb-ci-key-\"))\n try {\n const path = join(dir, \"key\")\n const child = Bun.spawn(\n [\"ssh-keygen\", \"-q\", \"-t\", \"ed25519\", \"-N\", \"\", \"-C\", comment, \"-f\", path],\n {\n stdin: \"ignore\",\n stdout: \"ignore\",\n stderr: \"pipe\",\n }\n )\n if ((await child.exited) !== 0) {\n const reason = (await new Response(child.stderr).text()).trim()\n throw new Error(`[SshTarget] ssh-keygen could not make a key for CI: ${reason}`)\n }\n return {\n privateKey: await readFile(path, \"utf8\"),\n publicKey: (await readFile(`${path}.pub`, \"utf8\")).trim(),\n }\n } finally {\n await rm(dir, { recursive: true, force: true })\n }\n}\n\n/**\n * The server's host keys, read over a connection SSH has already checked against your own\n * `known_hosts`. CI trusts these instead of whatever answers at the address the first time.\n */\nexport async function readHostKeys(shell: RemoteShell): Promise<string[]> {\n const keys: string[] = []\n await shell.run(\"cat /etc/ssh/ssh_host_*_key.pub\", {\n onLine: (line, stream) => {\n const [type, key] = line.trim().split(/\\s+/)\n if (stream === \"stdout\" && type && key) keys.push(`${type} ${key}`)\n },\n })\n if (keys.length === 0) throw new Error(\"[SshTarget] Could not read the server's SSH host keys.\")\n return keys\n}\n\n/** `known_hosts` lines for the host keys, under the name and port CI connects to. */\nexport function knownHostsLines(\n hostKeys: readonly string[],\n hostname: string,\n port: number\n): string[] {\n const name = port === 22 ? hostname : `[${hostname}]:${port}`\n return hostKeys.map((key) => `${name} ${key}`)\n}\n\n/**\n * Shell lines that install the key on the CI runner, reading `SIXB_DEPLOY_SSH_KEY` and\n * `SIXB_DEPLOY_KNOWN_HOSTS` from the environment. `host` is what `sixb.deploy.ts` names, which may\n * be an alias from your SSH config; the runner gets the same alias.\n */\nexport function renderCiInstall(input: {\n readonly host: string\n readonly hostname: string\n readonly port: number\n}): string[] {\n return [\n \"install -d -m 700 ~/.ssh\",\n \"install -m 600 /dev/null ~/.ssh/sixb_deploy\",\n `printf '%s\\\\n' \"$SIXB_DEPLOY_SSH_KEY\" > ~/.ssh/sixb_deploy`,\n `printf '%s\\\\n' \"$SIXB_DEPLOY_KNOWN_HOSTS\" > ~/.ssh/sixb_known_hosts`,\n \"cat >> ~/.ssh/config <<'__SIXB_SSH_CONFIG__'\",\n `Host ${input.host}`,\n ` HostName ${input.hostname}`,\n ` Port ${input.port}`,\n \" IdentityFile ~/.ssh/sixb_deploy\",\n \" IdentitiesOnly yes\",\n \" UserKnownHostsFile ~/.ssh/sixb_known_hosts\",\n \" StrictHostKeyChecking yes\",\n \"__SIXB_SSH_CONFIG__\",\n ]\n}\n",
12
- "import { randomUUID } from \"node:crypto\"\nimport type {\n DeployContext,\n DeployControlAction,\n DeployLogsOptions,\n DeployRelease,\n DeployScript,\n DeploySource,\n DeployStatus,\n} from \"@sixb/core/deploy\"\nimport { deploymentLayout } from \"./layout\"\nimport {\n renderDeployScript,\n renderPrepareScript,\n renderReceiveScript,\n STEP_MARKER,\n} from \"./scripts\"\nimport { stripTerminalControl } from \"./server/logs\"\nimport { shellQuote } from \"./shell\"\nimport { RemoteScriptError, type RemoteShell } from \"./transport\"\n\nconst NOT_DEPLOYED = \"__SIXB_NOT_DEPLOYED__\"\n\n/** Uploads the source, then runs the release on the server as one locked script. */\nexport async function deployRelease(\n shell: RemoteShell,\n user: string,\n release: DeployRelease,\n source: DeploySource,\n context: DeployContext\n): Promise<void> {\n const prepared = await capture(shell, renderPrepareScript(release.name, source.commit))\n const [home, incoming] = prepared\n if (!home || !incoming) {\n throw new Error(\"[SshTarget] The server did not report its home directory.\")\n }\n\n const layout = deploymentLayout({\n home,\n user,\n name: release.name,\n projectPath: source.projectPath,\n bunVersion: release.bunVersion,\n })\n const { labels, script } = renderDeployScript({\n release,\n layout,\n incoming,\n record: {\n commit: source.commit,\n ref: source.ref,\n deployedAt: new Date().toISOString(),\n deployedBy: context.deployedBy,\n },\n })\n context.report({ type: \"steps\", labels: [\"Upload source\", ...labels] })\n\n context.report({ type: \"step\", index: 0, status: \"running\" })\n for (const archive of source.archives) {\n await shell.run(renderReceiveScript(incoming, archive.path), { stdin: archive.open() })\n }\n context.report({ type: \"step\", index: 0, status: \"done\" })\n\n await runReportingSteps(shell, script, context)\n}\n\n/** Runs the deploy script, turning its step markers into progress and the rest into output. */\nasync function runReportingSteps(\n shell: RemoteShell,\n script: string,\n context: DeployContext\n): Promise<void> {\n const run = shell.run(script, {\n onLine: (line) => {\n const [marker, index, status] = line.split(\"\\t\")\n if (marker === STEP_MARKER && (status === \"start\" || status === \"done\")) {\n const step = Number(index) + 1\n context.report({\n type: \"step\",\n index: step,\n status: status === \"start\" ? \"running\" : \"done\",\n })\n } else {\n const output = stripTerminalControl(line)\n if (output.trim()) context.report({ type: \"output\", line: output })\n }\n },\n })\n try {\n await run\n } catch (error) {\n // The step's output already reached `report`; repeating it here would print it twice.\n if (error instanceof RemoteScriptError && error.exitCode !== 255) {\n throw new Error(`[SshTarget] The step exited with code ${error.exitCode}.`)\n }\n throw error\n }\n}\n\nexport async function readStatus(shell: RemoteShell, name: string): Promise<DeployStatus> {\n const lines = await capture(shell, ctlScript(name, [\"status\", \"--json\"], { allowMissing: true }))\n const report = lines.find((line) => line.startsWith(\"{\"))\n if (lines.includes(NOT_DEPLOYED) || !report) {\n return { release: null, running: false, processes: [] }\n }\n return JSON.parse(report) as DeployStatus\n}\n\nexport async function streamLogs(\n shell: RemoteShell,\n name: string,\n options: DeployLogsOptions & { readonly terminal?: boolean }\n): Promise<void> {\n const args = [\n \"logs\",\n ...(options.service ? [options.service] : []),\n \"--tail\",\n String(options.tail),\n ...(options.follow ? [\"--follow\"] : []),\n ]\n await shell.run(ctlScript(name, args), {\n ...(options.terminal ? { terminal: true } : { onLine: (line: string) => options.write(line) }),\n })\n}\n\nexport async function controlServices(\n shell: RemoteShell,\n name: string,\n action: DeployControlAction,\n service: string | undefined\n): Promise<void> {\n await shell.run(ctlScript(name, [action, ...(service ? [service] : [])]))\n}\n\n/**\n * Uploads the script, then runs it through `ctl run` in a terminal on the server: Ctrl-C reaches\n * the script there, and so does a dropped connection, as a hangup. Holding the deploy lock shared\n * for the whole run keeps a deploy from replacing the code it imports or migrating its storage;\n * runs share it with each other. Resolves with the script's exit code.\n */\nexport async function runDeployScript(\n shell: RemoteShell,\n name: string,\n script: DeployScript\n): Promise<number> {\n const root = `\"$HOME\"/${shellQuote(name)}`\n const staged = `${root}/deploy/runs/${randomUUID()}`\n await shell.run(\n [\n `if [ ! -x ${root}/deploy/ctl ]; then`,\n ` echo \"Nothing named ${name} is deployed on this server yet.\" >&2; exit 1`,\n \"fi\",\n \"umask 077\",\n `mkdir -p ${root}/deploy/runs`,\n // An upload whose run never started is left behind; a day later it goes.\n `find ${root}/deploy/runs -type f -mmin +1440 -delete 2> /dev/null || true`,\n `cat > ${staged}`,\n ].join(\"\\n\"),\n { stdin: new Blob([Uint8Array.from(script.source)]).stream() }\n )\n\n const run = [\n `cd ${root}`,\n `exec 9> ${root}/deploy/lock`,\n \"if ! flock -s -n 9; then\",\n ` echo \"Waiting for a deploy of ${name} to finish…\" >&2`,\n \"fi\",\n \"if ! flock -s -w 600 9; then\",\n ` echo \"A deploy of ${name} has held its lock for 10 minutes.\" >&2`,\n ` rm -f ${staged}`,\n \" exit 1\",\n \"fi\",\n `exec ${root}/deploy/ctl run ${staged} ${[script.path, ...script.args].map(shellQuote).join(\" \")}`,\n ].join(\"\\n\")\n try {\n await shell.run(run, { terminal: true })\n return 0\n } catch (error) {\n // 255 is OpenSSH's own failure; any other code is the script's.\n if (error instanceof RemoteScriptError && error.exitCode !== 255) return error.exitCode\n throw error\n }\n}\n\n/** Runs the deployment's `ctl` with arguments; fails plainly when nothing is deployed yet. */\nfunction ctlScript(\n name: string,\n args: readonly string[],\n options: { readonly allowMissing?: boolean } = {}\n): string {\n return [\n `ctl=\"$HOME\"/${shellQuote(name)}/deploy/ctl`,\n 'if [ ! -x \"$ctl\" ]; then',\n options.allowMissing\n ? ` echo ${NOT_DEPLOYED}; exit 0`\n : ` echo \"Nothing named ${name} is deployed on this server yet.\" >&2; exit 1`,\n \"fi\",\n `exec \"$ctl\" ${args.map(shellQuote).join(\" \")}`,\n ].join(\"\\n\")\n}\n\nasync function capture(shell: RemoteShell, script: string): Promise<string[]> {\n const lines: string[] = []\n await shell.run(script, {\n onLine: (line, stream) => {\n if (stream === \"stdout\") lines.push(line)\n },\n })\n return lines\n}\n",
13
- "/**\n * Shown by Caddy for a page request while the app cannot answer — during a deploy, or an\n * outage. It needs no assets or JavaScript and reloads itself every 10 seconds.\n */\nexport function renderUpdatePage(): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <meta http-equiv=\"refresh\" content=\"10\">\n <title>Updates in progress</title>\n <style>\n :root { color-scheme: light dark; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; background: #fff; color: #111; --muted: #666; --line: #e8e8e8; --surface: #fafafa; --track: #d6d6d6; }\n * { box-sizing: border-box; }\n body { margin: 0; min-height: 100vh; min-height: 100svh; display: grid; place-items: center; padding: 48px 28px; -webkit-font-smoothing: antialiased; }\n main { width: 100%; max-width: 480px; }\n .status { display: inline-flex; align-items: center; gap: 9px; margin-bottom: 28px; padding: 8px 11px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface); font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 10px; font-weight: 500; line-height: 1.4; letter-spacing: 0.1em; text-transform: uppercase; }\n .loader { width: 12px; height: 12px; flex: none; border: 1.5px solid var(--track); border-top-color: currentColor; border-radius: 50%; animation: spin 1s linear infinite; }\n h1 { margin: 0 0 16px; font-size: clamp(28px, 5vw, 36px); font-weight: 500; letter-spacing: -0.045em; line-height: 1.2; text-wrap: balance; }\n .description { margin: 0; max-width: 380px; color: var(--muted); font-size: 15px; line-height: 1.8; text-wrap: pretty; }\n .footer { display: flex; align-items: baseline; justify-content: space-between; flex-wrap: wrap; gap: 8px 20px; margin-top: 36px; padding-top: 20px; border-top: 1px solid var(--line); color: var(--muted); }\n .footer p { margin: 0; font-size: 12px; line-height: 1.6; }\n .footer .interval { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 10px; letter-spacing: 0.02em; }\n @keyframes spin { to { transform: rotate(360deg); } }\n @media (prefers-reduced-motion: reduce) { .loader { animation: none; } }\n @media (prefers-color-scheme: dark) {\n :root { background: #0a0a0a; color: #f5f5f5; --muted: #999; --line: #262626; --surface: #111; --track: #444; }\n }\n </style>\n</head>\n<body>\n <main>\n <div class=\"status\"><span class=\"loader\" aria-hidden=\"true\"></span>Site update</div>\n <h1>Updates in progress</h1>\n <p class=\"description\">We’re making a few updates. The site should be back soon. Thanks for your patience.</p>\n <div class=\"footer\">\n <p>This page will reconnect automatically.</p>\n <p class=\"interval\">Retrying every 10s</p>\n </div>\n </main>\n</body>\n</html>`\n}\n",
14
- "import type { DeployRelease } from \"@sixb/core/deploy\"\nimport type { DeploymentLayout } from \"./layout\"\nimport type { ProcessManifest } from \"./server/manifest\"\nimport { shellQuote } from \"./shell\"\nimport { renderUpdatePage } from \"./update-page\"\n\nconst GENERATED = \"Generated by sixb deploy. Changes are replaced on the next deploy.\"\n\n/** The supervisor's view of the release: absolute commands, full environments. */\nexport function renderProcessManifest(\n release: DeployRelease,\n layout: DeploymentLayout\n): ProcessManifest {\n const sixb = `${layout.project}/node_modules/.bin/sixb`\n return {\n version: 1,\n name: release.name,\n cwd: layout.project,\n runDir: layout.runDir,\n logDir: layout.logDir,\n releasePath: layout.releaseRecord,\n env: release.env,\n services: release.services.map((service) => ({\n name: service.name,\n processName: `${release.name}-${service.name}`,\n command: layout.bun,\n args:\n service.command.program === \"sixb\"\n ? [sixb, ...service.command.args]\n : [...service.command.args],\n env: service.env,\n instances: service.instances,\n killTimeoutMs: service.process.killTimeoutMs,\n restartDelayMs: service.process.restartDelayMs,\n ...(service.process.maxMemory ? { maxMemory: service.process.maxMemory } : {}),\n })),\n }\n}\n\n/** Pins the server half of this package to the project's Bun and manifest. */\nexport function renderCtl(layout: DeploymentLayout): string {\n return [\n \"#!/bin/sh\",\n `# ${GENERATED}`,\n `exec ${shellQuote(layout.bun)} ${shellQuote(`${layout.project}/node_modules/.bin/sixb-deploy-ssh`)} \"$@\" --manifest ${shellQuote(layout.manifest)}`,\n \"\",\n ].join(\"\\n\")\n}\n\n/**\n * The deployment's `systemd --user` unit. Linger starts the user's systemd at boot, so the\n * unit comes back after a reboot without anyone logged in.\n */\nexport function renderUnit(release: DeployRelease, layout: DeploymentLayout): string {\n // Long enough for the supervisor to stop every process with its own kill timeout.\n const stopSeconds =\n Math.ceil(\n Math.max(...release.services.map((service) => service.process.killTimeoutMs)) / 1000\n ) + 10\n return [\n `# ${GENERATED}`,\n \"[Unit]\",\n `Description=Sixb deployment ${release.name}`,\n \"\",\n \"[Service]\",\n \"Type=simple\",\n `WorkingDirectory=${systemdValue(layout.project)}`,\n `Environment=${systemdValue(`PATH=${layout.bunDir}:/usr/local/bin:/usr/bin:/bin`)}`,\n `ExecStart=${systemdValue(layout.ctl)} supervise`,\n \"Restart=always\",\n \"RestartSec=2\",\n \"KillSignal=SIGTERM\",\n `TimeoutStopSec=${stopSeconds}`,\n \"\",\n \"[Install]\",\n \"WantedBy=default.target\",\n \"\",\n ].join(\"\\n\")\n}\n\n/** One site per HTTP service, forwarded to the service's loopback port. */\nexport function renderCaddySnippet(release: DeployRelease): string {\n const sites = release.services.flatMap((service) => {\n if (!service.http) return []\n const pages = service.name === \"app\"\n return [\n [\n `${service.http.domain} {`,\n ...(service.name === \"api\" ? compressJson() : []),\n `\\treverse_proxy ${service.http.host}:${service.http.port}`,\n ...(pages ? updatePageOnProxyErrors() : []),\n \"}\",\n ].join(\"\\n\"),\n ]\n })\n return [`# ${GENERATED}`, \"\", sites.join(\"\\n\\n\"), \"\"].join(\"\\n\")\n}\n\n/**\n * The API never compresses its responses, and an object query page is easily a megabyte of\n * JSON that compresses about twentyfold. Only complete JSON answers are encoded: the\n * WebSocket upgrade and anything else streamed through the API stay as they are, since an\n * encoder buffers what it writes. A 206 keeps its byte range of the stored file intact, and the\n * app's assets are already precompressed.\n */\nfunction compressJson(): string[] {\n return [\n \"\\tencode {\",\n \"\\t\\tzstd\",\n \"\\t\\tgzip\",\n \"\\t\\tmatch {\",\n \"\\t\\t\\tstatus 200\",\n \"\\t\\t\\theader Content-Type application/json*\",\n \"\\t\\t}\",\n \"\\t}\",\n ]\n}\n\n/**\n * While the app is down — during a deploy, or an outage — a browser asking for a page\n * gets the update page instead of Caddy's bare error. Other requests keep the error.\n */\nfunction updatePageOnProxyErrors(): string[] {\n return [\n \"\\thandle_errors 502 503 504 {\",\n \"\\t\\t@page {\",\n \"\\t\\t\\tmethod GET\",\n \"\\t\\t\\theader Accept *text/html*\",\n \"\\t\\t}\",\n \"\\t\\thandle @page {\",\n '\\t\\t\\theader Content-Type \"text/html; charset=utf-8\"',\n '\\t\\t\\theader Cache-Control \"no-store\"',\n '\\t\\t\\theader Retry-After \"10\"',\n \"\\t\\t\\trespond 503 {\",\n \"\\t\\t\\t\\tbody <<HTML\",\n ...renderUpdatePage()\n .split(\"\\n\")\n .map((line) => `\\t\\t\\t\\t${line}`),\n \"\\t\\t\\t\\tHTML\",\n \"\\t\\t\\t}\",\n \"\\t\\t}\",\n \"\\t\\thandle {\",\n '\\t\\t\\trespond \"Service temporarily unavailable\" {err.status_code}',\n \"\\t\\t}\",\n \"\\t}\",\n ]\n}\n\nfunction systemdValue(value: string): string {\n return value.replace(/%/g, \"%%\").replace(/\\s/g, \"\\\\x20\")\n}\n",
15
- "import type { DeployCommand, DeployRecord, DeployRelease } from \"@sixb/core/deploy\"\nimport type { DeploymentLayout } from \"./layout\"\nimport { renderCaddySnippet, renderCtl, renderProcessManifest, renderUnit } from \"./render\"\nimport { shellQuote, writeFileCommand } from \"./shell\"\n\n/** A line the deploy script prints around each step; the target turns it into progress. */\nexport const STEP_MARKER = \"__SIXB_STEP__\"\n\n/** The server's home directory, and a fresh directory to upload the source into. */\nexport function renderPrepareScript(name: string, commit: string): string {\n return [\n `root=\"$HOME\"/${shellQuote(name)}`,\n 'mkdir -p \"$root/deploy/incoming\"',\n `incoming=\"$(mktemp -d \"$root/deploy/incoming/${commit.slice(0, 12)}.XXXXXX\")\"`,\n // `mktemp` makes it 0700, and GNU tar passes the mode of the upload's `.` on to `code/`, which\n // would lock out the admin, who reads the code through the deploy user's group.\n 'chmod 755 \"$incoming\"',\n `printf '%s\\\\n%s\\\\n' \"$HOME\" \"$incoming\"`,\n ].join(\"\\n\")\n}\n\n/** Extracts one uploaded archive from standard input. */\nexport function renderReceiveScript(incoming: string, path: string): string {\n const directory = path === \".\" ? incoming : `${incoming}/${path}`\n return `mkdir -p ${shellQuote(directory)} && tar -x -f - -C ${shellQuote(directory)}`\n}\n\nexport interface DeployScriptInput {\n readonly release: DeployRelease\n readonly layout: DeploymentLayout\n readonly incoming: string\n readonly record: DeployRecord\n}\n\nexport interface DeployScript {\n readonly labels: readonly string[]\n readonly script: string\n}\n\ninterface Step {\n readonly label: string\n readonly body: string\n}\n\n/**\n * Everything the server does once the source is uploaded, as one script that holds the\n * deployment's lock throughout. It runs with standard input closed: bash reads the whole `main`\n * function before running any of it, so no command can swallow the rest of the script.\n */\nexport function renderDeployScript(input: DeployScriptInput): DeployScript {\n const { release, layout } = input\n const api = release.services.find((service) => service.http?.readinessPath)\n const steps: Step[] = [\n { label: \"Apply files\", body: renderApplyFiles(layout, input.incoming) },\n { label: `Install Bun ${release.bunVersion}`, body: renderInstallBun(release.bunVersion) },\n { label: \"Install dependencies\", body: renderInstallDependencies() },\n ...(release.steps.env ? [envStep(release.steps.env, layout)] : []),\n ...release.steps.build.map((command) => runStep(command)),\n // Everything that can be rejected happens while the previous release still serves: services\n // are down only from here to \"Start services\".\n { label: \"Write services\", body: renderWriteServices(release, layout) },\n { label: \"Update routes\", body: renderUpdateRoutes(release, layout) },\n { label: \"Stop services\", body: renderStopServices() },\n ...release.steps.beforeStart.map((command) => runStep(command)),\n { label: \"Start services\", body: renderStartServices() },\n {\n label: \"Check services\",\n body: renderCheckServices(\n api?.http ? `http://${api.http.host}:${api.http.port}${api.http.readinessPath}` : null\n ),\n },\n {\n label: \"Record release\",\n body: writeFileCommand(layout.releaseRecord, `${JSON.stringify(input.record)}\\n`),\n },\n ]\n\n const script = [\n \"set -euo pipefail\",\n \"main() {\",\n renderEnvironment(release, layout),\n renderTakeLock(layout),\n ...steps.flatMap((step, index) => [\n `printf '\\\\n%s\\\\t%s\\\\t%s\\\\n' ${STEP_MARKER} ${index} start`,\n step.body,\n `printf '%s\\\\t%s\\\\t%s\\\\n' ${STEP_MARKER} ${index} done`,\n ]),\n \"}\",\n \"main </dev/null\",\n \"\",\n ].join(\"\\n\")\n\n return { labels: steps.map((step) => step.label), script }\n}\n\nfunction renderEnvironment(release: DeployRelease, layout: DeploymentLayout): string {\n const variables: Record<string, string> = {\n ROOT: layout.root,\n CODE: layout.code,\n PROJECT: layout.project,\n DEPLOY: layout.deployDir,\n BUN: layout.bun,\n BUN_DIR: layout.bunDir,\n BUN_VERSION: release.bunVersion,\n CTL: layout.ctl,\n UNIT: layout.unitName,\n UNIT_PATH: layout.unit,\n CADDY_DIR: layout.caddyDir,\n CADDY_SNIPPET: layout.caddySnippet,\n }\n return [\n ...Object.entries(variables).map(([name, value]) => `${name}=${shellQuote(value)}`),\n // The steps run with the release's environment; the project's `.env` fills in the rest.\n ...Object.entries(release.env).map(([name, value]) => `export ${name}=${shellQuote(value)}`),\n 'export PATH=\"$BUN_DIR:$PATH\"',\n // `systemctl --user` finds the user's systemd through this; SSH sessions usually set it.\n 'printenv XDG_RUNTIME_DIR > /dev/null || export XDG_RUNTIME_DIR=\"/run/user/$(id -u)\"',\n ].join(\"\\n\")\n}\n\nfunction renderTakeLock(layout: DeploymentLayout): string {\n return [\n `exec 9>${shellQuote(layout.lock)}`,\n \"if ! flock -n 9; then\",\n ' echo \"Waiting for another deploy or script run of this project to finish…\"',\n \"fi\",\n \"if ! flock -w 600 9; then\",\n ' echo \"Another deploy or script run of this project has held its lock for 10 minutes.\" >&2',\n \" exit 1\",\n \"fi\",\n ].join(\"\\n\")\n}\n\n/**\n * Makes `code/` match the commit the way `git reset --hard` would: committed files replace what is\n * there, files the previous deploy brought and this one does not are removed, and everything else\n * — `.env`, `.sixb/`, `node_modules/` — stays. A committed `.env` is never copied over the\n * server's.\n */\nexport function renderApplyFiles(layout: DeploymentLayout, incoming: string): string {\n return [\n `incoming=${shellQuote(incoming)}`,\n `files=${shellQuote(layout.fileList)}`,\n `code=${shellQuote(layout.code)}`,\n 'listed=\"$incoming.files\"',\n '(cd \"$incoming\" && find . \\\\( -type f -o -type l \\\\) ! -name .env | LC_ALL=C sort) > \"$listed\"',\n 'mkdir -p \"$code\"',\n 'if [ -f \"$files\" ]; then',\n ' LC_ALL=C comm -23 \"$files\" \"$listed\" | while IFS= read -r path; do',\n ' rm -f \"$code/$path\"',\n ' dir=\"$(dirname \"$code/$path\")\"',\n ' while [ \"$dir\" != \"$code\" ] && [ \"$dir\" != \"$code/.\" ] && rmdir \"$dir\" 2>/dev/null; do',\n ' dir=\"$(dirname \"$dir\")\"',\n \" done\",\n \" done\",\n \"fi\",\n `(cd \"$incoming\" && tar -c -f - --exclude=.env .) | (cd \"$code\" && tar -x -f -)`,\n 'mv \"$listed\" \"$files\"',\n 'rm -rf \"$incoming\"',\n // Uploads a deploy abandoned before it took the lock.\n 'find \"$(dirname \"$incoming\")\" -mindepth 1 -maxdepth 1 -mmin +1440 -exec rm -rf {} + 2>/dev/null || true',\n ].join(\"\\n\")\n}\n\n/** Downloads the pinned Bun once per user and version, checking it against the release's sums. */\nfunction renderInstallBun(version: string): string {\n const release = `https://github.com/oven-sh/bun/releases/download/bun-v${version}`\n return [\n 'if [ ! -x \"$BUN\" ]; then',\n ' case \"$(uname -m)\" in',\n \" x86_64 | amd64) arch=x64 ;;\",\n \" aarch64 | arm64) arch=aarch64 ;;\",\n ' *) echo \"Bun has no Linux build for $(uname -m).\" >&2; exit 1 ;;',\n \" esac\",\n // Bun's default x64 build needs AVX2; older CPUs take the baseline build.\n ' if [ \"$arch\" = x64 ] && ! grep -q avx2 /proc/cpuinfo; then arch=x64-baseline; fi',\n ' asset=\"bun-linux-$arch\"',\n ' download=\"$(mktemp -d)\"',\n ` curl -fsSL --retry 3 -o \"$download/$asset.zip\" ${shellQuote(release)}\"/$asset.zip\"`,\n ` curl -fsSL --retry 3 -o \"$download/SHASUMS256.txt\" ${shellQuote(release)}/SHASUMS256.txt`,\n ' (cd \"$download\" && grep \" $asset.zip\\\\$\" SHASUMS256.txt | sha256sum -c --quiet -)',\n ' unzip -q \"$download/$asset.zip\" -d \"$download\"',\n ' mkdir -p \"$BUN_DIR\"',\n ' mv \"$download/$asset/bun\" \"$BUN\"',\n ' rm -rf \"$download\"',\n \"fi\",\n // Dependency lifecycle scripts call `node`; with none installed, Bun runs them.\n 'command -v node > /dev/null || ln -s \"$BUN\" \"$BUN_DIR/node\"',\n '\"$BUN\" --version',\n ].join(\"\\n\")\n}\n\nfunction renderInstallDependencies(): string {\n return [\n 'cd \"$PROJECT\"',\n '\"$BUN\" install --frozen-lockfile',\n \"for bin in sixb sixb-deploy-ssh; do\",\n ' if [ ! -e \"$PROJECT/node_modules/.bin/$bin\" ]; then',\n ' package=\"@sixb/cli\"; [ \"$bin\" = sixb ] || package=\"@sixb/deploy-ssh\"',\n ' echo \"$package is not installed. Add it to the project dependencies.\" >&2',\n \" exit 1\",\n \" fi\",\n \"done\",\n ].join(\"\\n\")\n}\n\nfunction runStep(command: DeployCommand): Step {\n const program = command.program === \"sixb\" ? '\"$PROJECT/node_modules/.bin/sixb\"' : \"\"\n return {\n label: [command.program, ...command.args].join(\" \"),\n body: [\n 'cd \"$PROJECT\"',\n `\"$BUN\" ${program} ${command.args.map(shellQuote).join(\" \")}`.replace(/ {2,}/g, \" \"),\n ].join(\"\\n\"),\n }\n}\n\n/** Pulls `.env` with the token only this step reads, so no build or service ever holds it. */\nfunction envStep(command: DeployCommand, layout: DeploymentLayout): Step {\n const step = runStep(command)\n return { ...step, body: `${step.body} --token-file ${shellQuote(layout.envToken)}` }\n}\n\nfunction renderStopServices(): string {\n return [\n 'if systemctl --user is-active --quiet \"$UNIT\"; then',\n ' systemctl --user stop \"$UNIT\"',\n \"else\",\n \" echo 'Services were not running.'\",\n \"fi\",\n ].join(\"\\n\")\n}\n\nfunction renderWriteServices(release: DeployRelease, layout: DeploymentLayout): string {\n return [\n writeFileCommand(\n layout.manifest,\n `${JSON.stringify(renderProcessManifest(release, layout), null, 2)}\\n`\n ),\n writeFileCommand(layout.ctl, renderCtl(layout)),\n 'chmod 755 \"$CTL\"',\n 'mkdir -p \"$(dirname \"$UNIT_PATH\")\"',\n writeFileCommand(`${layout.unit}.new`, renderUnit(release, layout)),\n 'if cmp -s \"$UNIT_PATH.new\" \"$UNIT_PATH\"; then',\n ' rm -f \"$UNIT_PATH.new\"',\n \"else\",\n ' mv \"$UNIT_PATH.new\" \"$UNIT_PATH\"',\n \" systemctl --user daemon-reload\",\n ' systemctl --user enable \"$UNIT\"',\n \"fi\",\n ].join(\"\\n\")\n}\n\n/**\n * Installs the deployment's Caddy routes when they changed. Caddy has to accept the whole\n * configuration before it reloads; otherwise the previous routes come back and the deploy stops.\n */\nfunction renderUpdateRoutes(release: DeployRelease, layout: DeploymentLayout): string {\n return [\n `new=${shellQuote(`${layout.deployDir}/Caddyfile`)}`,\n writeFileCommand(`${layout.deployDir}/Caddyfile`, renderCaddySnippet(release)),\n 'if cmp -s \"$new\" \"$CADDY_SNIPPET\"; then',\n \" echo 'Routes unchanged.'\",\n \"else\",\n ' if [ ! -w \"$CADDY_DIR\" ]; then',\n ' echo \"$CADDY_DIR is missing or not writable, so this server is not set up for sixb deploy.\" >&2',\n \" exit 1\",\n \" fi\",\n ' previous=\"$DEPLOY/Caddyfile.previous\"',\n ' rm -f \"$previous\"',\n ' if [ -f \"$CADDY_SNIPPET\" ]; then cp \"$CADDY_SNIPPET\" \"$previous\"; fi',\n ' cp \"$new\" \"$CADDY_SNIPPET\"',\n ' if ! caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile > \"$DEPLOY/caddy-validate.log\" 2>&1; then',\n ' if [ -f \"$previous\" ]; then cp \"$previous\" \"$CADDY_SNIPPET\"; else rm -f \"$CADDY_SNIPPET\"; fi',\n ' tail -n 20 \"$DEPLOY/caddy-validate.log\" >&2',\n \" echo 'Caddy rejected the routes; the previous ones are back in place.' >&2\",\n \" exit 1\",\n \" fi\",\n \" sudo -n /usr/bin/systemctl reload caddy\",\n \"fi\",\n ].join(\"\\n\")\n}\n\nfunction renderStartServices(): string {\n return [\n 'systemctl --user restart \"$UNIT\"',\n 'systemctl --user is-active --quiet \"$UNIT\"',\n // Where \"Check services\" counts its quiet window from.\n \"started=$SECONDS\",\n ].join(\"\\n\")\n}\n\n/**\n * Done means healthy, not just started: the API answers its readiness route, and no process has\n * exited in its first seconds. Those seconds count from \"Start services\", so the time the API\n * takes to boot is part of them rather than added to them.\n */\nexport function renderCheckServices(readinessUrl: string | null): string {\n const waitForApi = readinessUrl\n ? [\n `ready_url=${shellQuote(readinessUrl)}`,\n \"ready=0\",\n \"for attempt in $(seq 1 90); do\",\n ` if \"$BUN\" -e 'const r = await fetch(process.argv[1]).catch(() => null); process.exit(r?.ok ? 0 : 1)' \"$ready_url\" 2>/dev/null; then`,\n \" ready=1\",\n \" break\",\n \" fi\",\n \" sleep 1\",\n \"done\",\n 'if [ \"$ready\" != 1 ]; then',\n ' echo \"The API did not answer $ready_url within 90 seconds. Its latest log lines:\" >&2',\n ' \"$CTL\" logs api --tail 30 >&2 || true',\n \" exit 1\",\n \"fi\",\n ]\n : []\n return [\n ...waitForApi,\n \"quiet=$((5 - (SECONDS - started)))\",\n 'if [ \"$quiet\" -gt 0 ]; then sleep \"$quiet\"; fi',\n '\"$CTL\" status --check',\n ].join(\"\\n\")\n}\n",
8
+ "import type { DeployCheck } from \"@sixb/core/deploy\"\n\n/** Where every remedy points: the list of what a server provides. */\nexport const HOST_REQUIREMENTS = \"https://docs.sixb.ai/deployment/host-requirements\"\nconst ENV_TOKEN_DOCS = \"https://docs.sixb.ai/deployment/environment-variables#deploy\"\n\n/** What the probe reported, by key. */\nexport type HostFacts = ReadonlyMap<string, string>\n\nexport interface JudgeInput {\n /** The deployment's `name`: its folder in the account's home. */\n readonly name: string\n /** The loopback ports the deployment's slots listen on. */\n readonly ports: readonly number[]\n /**\n * Where the server's settings come from: the project's source, read with the env token or with\n * the server's own identity, or the `.env` kept on the server.\n */\n readonly settings: \"env-token\" | \"identity\" | \"env-file\"\n /** The project prints with Chromium, so the server needs Chromium's libraries. */\n readonly chromium: boolean\n}\n\n/** The Debian package each tool the deploy uses comes in. */\nconst TOOL_PACKAGES: Readonly<Record<string, string>> = {\n curl: \"curl\",\n unzip: \"unzip\",\n tar: \"tar\",\n flock: \"util-linux\",\n setsid: \"util-linux\",\n sha256sum: \"coreutils\",\n stat: \"coreutils\",\n ss: \"iproute2\",\n}\n\n/** Caddy from its own apt repository, as its documentation installs it. */\nconst INSTALL_CADDY = [\n \"curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/gpg.key | gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg\",\n \"curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt > /etc/apt/sources.list.d/caddy-stable.list\",\n \"apt-get update && apt-get install -y caddy\",\n]\n\nconst MIN_CADDY = [2, 7] as const\nconst MIN_FREE_KB = 2 * 1024 * 1024\nconst ARCHITECTURES = new Set([\"x86_64\", \"amd64\", \"aarch64\", \"arm64\"])\n\n/** Reads the probe's `fact<TAB>key<TAB>value` lines. */\nexport function parseFacts(lines: readonly string[]): HostFacts {\n const facts = new Map<string, string>()\n for (const line of lines) {\n const [marker, key, ...value] = line.split(\"\\t\")\n if (marker === \"fact\" && key) facts.set(key, value.join(\"\\t\").trim())\n }\n return facts\n}\n\n/** What the facts mean for a deploy, one check per host requirement. */\nexport function judge(facts: HostFacts, input: JudgeInput): DeployCheck[] {\n // The fixes name the account and its home as the server reports them, and are pasted into a root\n // shell: anything that would need quoting gets no commands, only the remedy.\n const user = pasteable(facts.get(\"account.name\"))\n const home = pasteable(facts.get(\"account.home\"))\n const root = home && pasteable(input.name) ? `${home}/${input.name}` : null\n return [\n server(facts),\n account(facts),\n deployments(facts),\n linger(facts, user),\n caddy(facts, user),\n settings(facts, input.settings, root),\n ports(facts, input.ports),\n ...(input.chromium ? [chromium(facts)] : []),\n disk(facts),\n ]\n}\n\nfunction server(facts: HostFacts): DeployCheck {\n const name = facts.get(\"os.name\") || \"an unknown system\"\n const family = `${facts.get(\"os.id\") ?? \"\"} ${facts.get(\"os.like\") ?? \"\"}`\n const arch = facts.get(\"os.arch\") ?? \"\"\n const missing = facts.get(\"os.missing\") ?? \"\"\n const problems = [\n /\\b(debian|ubuntu)\\b/.test(family) ? \"\" : `${name} is not Ubuntu or Debian`,\n facts.get(\"os.systemd\") === \"yes\" ? \"\" : \"systemd is missing\",\n ARCHITECTURES.has(arch) ? \"\" : `Bun has no build for ${arch || \"this CPU\"}`,\n missing ? `missing ${missing.split(\" \").join(\", \")}` : \"\",\n ].filter(Boolean)\n const packages = [...new Set(missing.split(\" \").flatMap((tool) => TOOL_PACKAGES[tool] ?? []))]\n return problems.length === 0\n ? ok(\"server\", \"Server\", `${name}, ${arch}`)\n : fail(\"server\", \"Server\", problems.join(\"; \"), {\n commands: packages.length > 0 ? [`apt-get install -y ${packages.join(\" \")}`] : [],\n })\n}\n\n/** `root` is refused in `sixb.deploy.ts`, and again here, where SSH config could still map to it. */\nfunction account(facts: HostFacts): DeployCheck {\n const name = facts.get(\"account.name\") || \"an unknown account\"\n return facts.get(\"account.uid\") === \"0\"\n ? fail(\"account\", \"Account\", `${name} is root: deploy as an account without root access`)\n : ok(\"account\", \"Account\", name)\n}\n\nfunction deployments(facts: HostFacts): DeployCheck {\n const others = (facts.get(\"deployments.others\") ?? \"\").split(\" \").filter(Boolean)\n return others.length === 0\n ? ok(\"deployments\", \"Deployments\", \"none other on this server\")\n : fail(\n \"deployments\",\n \"Deployments\",\n `this server already runs ${others.join(\", \")}: a server runs one deployment`\n )\n}\n\nfunction linger(facts: HostFacts, user: string | null): DeployCheck {\n return facts.get(\"linger\") === \"yes\"\n ? ok(\"linger\", \"Services at boot\", \"lingering is on\")\n : fail(\"linger\", \"Services at boot\", \"lingering is off: the services would stop at logout\", {\n commands: user ? [`loginctl enable-linger ${user}`] : [],\n })\n}\n\nfunction caddy(facts: HostFacts, user: string | null): DeployCheck {\n const version = facts.get(\"caddy.version\") ?? \"\"\n const routes = facts.get(\"caddy.routes\") ?? \"the routes folder\"\n const problems = [\n !version\n ? \"Caddy is not installed\"\n : atLeast(version, MIN_CADDY)\n ? \"\"\n : `Caddy ${version} is older than ${MIN_CADDY.join(\".\")}`,\n facts.get(\"caddy.caddyfile-imports\") === \"yes\"\n ? \"\"\n : \"/etc/caddy/Caddyfile does not import /etc/caddy/sixb.d/*.caddy\",\n facts.get(\"caddy.routes-imported\") === \"yes\" ? \"\" : `nothing imports ${routes}`,\n facts.get(\"caddy.routes-writable\") === \"yes\" ? \"\" : `${routes} is missing or not writable`,\n facts.get(\"caddy.reload\") === \"yes\" ? \"\" : \"sudo systemctl reload caddy is not allowed\",\n ].filter(Boolean)\n if (problems.length === 0) return ok(\"caddy\", \"Caddy\", `${version}, routes in ${routes}`)\n\n const folder = `/etc/caddy/sixb.d/${user}`\n const configure = !user\n ? []\n : [\n ...(facts.get(\"caddy.caddyfile-imports\") === \"yes\"\n ? []\n : [\n // Safe to paste twice: a second import of the same files is an error Caddy won't reload.\n \"grep -qxF 'import /etc/caddy/sixb.d/*.caddy' /etc/caddy/Caddyfile || echo 'import /etc/caddy/sixb.d/*.caddy' >> /etc/caddy/Caddyfile\",\n ]),\n ...(facts.get(\"caddy.routes-imported\") === \"yes\"\n ? []\n : [\n \"install -d -m 0755 /etc/caddy/sixb.d\",\n `echo 'import ${folder}/*.caddy' > ${folder}.caddy`,\n ]),\n ...(facts.get(\"caddy.routes-writable\") === \"yes\"\n ? []\n : [`install -d -m 0755 -o ${user} -g ${user} ${folder}`]),\n ...(facts.get(\"caddy.reload\") === \"yes\"\n ? []\n : [\n `echo '${user} ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy' > /etc/sudoers.d/${user}`,\n `chmod 440 /etc/sudoers.d/${user}`,\n ]),\n ]\n const install = !version\n ? INSTALL_CADDY\n : atLeast(version, MIN_CADDY)\n ? []\n : [\"apt-get update && apt-get install -y --only-upgrade caddy\"]\n return fail(\"caddy\", \"Caddy\", problems.join(\"; \"), {\n commands: [\n ...install,\n ...configure,\n ...(configure.length > 0 ? [\"systemctl reload caddy\"] : []),\n ],\n })\n}\n\nfunction settings(\n facts: HostFacts,\n source: JudgeInput[\"settings\"],\n root: string | null\n): DeployCheck {\n const folder = root ?? \"~/<name>\"\n if (source === \"identity\") {\n return ok(\"settings\", \"Settings\", \"the source reads with the server's own identity\")\n }\n if (source === \"env-token\") {\n const token = fileFact(facts.get(\"file.env-token\"))\n if (!token || token.size === 0) {\n return fail(\"settings\", \"Settings\", \"no env token: the deploy can't pull .env\", {\n remedy: `Put a read-only token for the project's prod values at ${folder}/env-token, mode 600. See ${ENV_TOKEN_DOCS}.`,\n })\n }\n return privateMode(token.mode)\n ? ok(\"settings\", \"Settings\", \"env token in place\")\n : fail(\"settings\", \"Settings\", `the env token is readable by others (mode ${token.mode})`, {\n commands: root ? [`chmod 600 ${root}/env-token`] : [],\n })\n }\n // A deployment from before releases keeps its settings in its code folder.\n const shared = fileFact(facts.get(\"file.shared-env\"))\n const env = shared ?? fileFact(facts.get(\"file.legacy-env\"))\n if (!env) {\n return fail(\"settings\", \"Settings\", \"no .env on the server\", {\n remedy: `Create ${folder}/shared/.env, mode 600, with the project's settings.`,\n })\n }\n return privateMode(env.mode)\n ? ok(\"settings\", \"Settings\", \".env in place\")\n : fail(\"settings\", \"Settings\", `.env is readable by others (mode ${env.mode})`, {\n commands: shared && root ? [`chmod 600 ${root}/shared/.env`] : [],\n })\n}\n\nfunction ports(facts: HostFacts, wanted: readonly number[]): DeployCheck {\n const taken = wanted.filter((port) => facts.get(`port.${port}`) === \"other\")\n return taken.length === 0\n ? ok(\"ports\", \"Ports\", wanted.join(\", \"))\n : fail(\n \"ports\",\n \"Ports\",\n `${taken.join(\", \")} ${taken.length === 1 ? \"is\" : \"are\"} held by another program: a server runs one deployment`\n )\n}\n\nfunction chromium(facts: HostFacts): DeployCheck {\n const missing = facts.get(\"chromium.missing\") ?? \"\"\n const checked = facts.get(\"chromium.checked\") ?? \"system libraries\"\n return missing\n ? fail(\"chromium\", \"Chromium\", `missing ${missing.split(\" \").join(\", \")} (${checked})`, {\n remedy: \"Install them as root, such as with `npx playwright install-deps chromium`.\",\n })\n : ok(\"chromium\", \"Chromium\", \"its libraries are installed\")\n}\n\nfunction disk(facts: HostFacts): DeployCheck {\n const freeKb = Number(facts.get(\"disk.free-kb\") ?? 0)\n return freeKb >= MIN_FREE_KB\n ? ok(\"disk\", \"Disk space\", `${Math.floor(freeKb / 1048576)} GB free`)\n : {\n id: \"disk\",\n label: \"Disk space\",\n status: \"warning\",\n detail: `${Math.floor(freeKb / 1024)} MB free`,\n remedy: \"A release needs about 1 GB while it builds.\",\n }\n}\n\nfunction ok(id: string, label: string, detail: string): DeployCheck {\n return { id, label, status: \"ok\", detail }\n}\n\n/** A failed requirement, with what fixes it: commands to run as root, when there are some. */\nfunction fail(\n id: string,\n label: string,\n detail: string,\n fix: { readonly remedy?: string; readonly commands?: readonly string[] } = {}\n): DeployCheck {\n const commands = fix.commands ?? []\n return {\n id,\n label,\n status: \"fail\",\n detail,\n remedy: fix.remedy ?? `See ${HOST_REQUIREMENTS}.`,\n ...(commands.length > 0 ? { commands } : {}),\n }\n}\n\n/** A name or path that pastes into a shell as it is, or nothing when it would need quoting. */\nfunction pasteable(value: string | undefined): string | null {\n return value && /^[A-Za-z0-9._/-]+$/.test(value) ? value : null\n}\n\n/** Readable by its owner alone: no group or other bits, as 600 or 400. */\nfunction privateMode(mode: string): boolean {\n const bits = Number.parseInt(mode, 8)\n return Number.isInteger(bits) && (bits & 0o077) === 0\n}\n\n/** `mode size` from the probe, or nothing when the file is missing. */\nfunction fileFact(value: string | undefined): { mode: string; size: number } | null {\n if (!value || value === \"missing\") return null\n const [mode = \"\", size = \"0\"] = value.split(\" \")\n return { mode, size: Number(size) }\n}\n\nfunction atLeast(version: string, minimum: readonly number[]): boolean {\n const parts = version.split(\".\").map((part) => Number.parseInt(part, 10) || 0)\n for (const [index, wanted] of minimum.entries()) {\n const part = parts[index] ?? 0\n if (part !== wanted) return part > wanted\n }\n return true\n}\n",
9
+ "import { posix } from \"node:path\"\nimport type { DeployHttpServiceName } from \"@sixb/core/deploy\"\n\n/** The read-only token a deploy pulls `.env` with, for a project with a source. */\nexport const ENV_TOKEN_FILE = \"env-token\"\n\n/**\n * A deployment runs in one of two slots. A release starts in the idle one, beside the live one,\n * and takes traffic once it is healthy.\n */\nexport type DeploySlot = \"blue\" | \"green\"\n\nexport const SLOTS: readonly DeploySlot[] = [\"blue\", \"green\"]\n\n/** The loopback ports each slot's HTTP services listen on. Caddy forwards to the live slot's. */\nexport const SLOT_PORTS = {\n blue: { app: 3001, api: 3002 },\n green: { app: 3011, api: 3012 },\n} as const satisfies Record<DeploySlot, Record<DeployHttpServiceName, number>>\n\nexport function otherSlot(slot: DeploySlot): DeploySlot {\n return slot === \"blue\" ? \"green\" : \"blue\"\n}\n\n/**\n * Where a deployment lives on its server: one folder in the deploy account's home, plus Bun, the\n * slot service and the Caddy routes.\n *\n * ~/<name>/releases/<id> immutable releases: code, node_modules, .sixb/dist, .env\n * ~/<name>/current the live release\n * ~/<name>/code `current`, for scripts and older tools that look here\n * ~/<name>/shared/.env the `.env` kept on the server, for a project without a source\n * ~/<name>/env-token the token a deploy pulls `.env` with, for a project with one\n * ~/<name>/deploy/ lock, uploads, release record, live slot, slot launchers, ctl\n * ~/<name>/run/<slot>/ each slot's supervisor state, control requests and logs\n * ~/.sixb/bun/<version>/ Bun, shared by releases on the same version\n */\nexport interface DeploymentLayout {\n readonly name: string\n readonly home: string\n readonly root: string\n readonly releasesDir: string\n readonly currentLink: string\n readonly code: string\n readonly sharedEnv: string\n readonly envToken: string\n readonly deployDir: string\n readonly incomingDir: string\n readonly runsDir: string\n readonly lock: string\n readonly releaseRecord: string\n /** Names the live slot. */\n readonly liveSlotFile: string\n /** What `status`, `logs` and the other operations run: the live release's server half. */\n readonly ctl: string\n readonly unitDir: string\n /** The slot service's template, instantiated as `sixb-<name>@blue` and `sixb-<name>@green`. */\n readonly unitTemplate: string\n readonly caddyDir: string\n readonly caddySnippet: string\n}\n\nexport interface SlotLayout {\n readonly slot: DeploySlot\n readonly unit: string\n readonly manifest: string\n /** What the slot's service runs: its release's supervisor, with its Bun. */\n readonly launcher: string\n readonly runDir: string\n readonly logDir: string\n}\n\n/** A deployment from before slots: one service, one manifest. Adopted by its first slot deploy. */\nexport interface LegacyLayout {\n readonly unit: string\n readonly unitPath: string\n readonly manifest: string\n}\n\n/** Where a deployment lives: under the home of the account it runs as, whichever that is. */\nexport function deploymentLayout(input: {\n readonly home: string\n readonly user: string\n readonly name: string\n}) {\n const root = posix.join(input.home, input.name)\n const deployDir = posix.join(root, \"deploy\")\n const unitDir = posix.join(input.home, \".config\", \"systemd\", \"user\")\n // Each account writes routes only in its own folder, which the server's Caddyfile imports.\n const caddyDir = posix.join(\"/etc/caddy/sixb.d\", input.user)\n return {\n name: input.name,\n home: input.home,\n root,\n releasesDir: posix.join(root, \"releases\"),\n currentLink: posix.join(root, \"current\"),\n code: posix.join(root, \"code\"),\n sharedEnv: posix.join(root, \"shared\", \".env\"),\n envToken: posix.join(root, ENV_TOKEN_FILE),\n deployDir,\n incomingDir: posix.join(deployDir, \"incoming\"),\n runsDir: posix.join(deployDir, \"runs\"),\n lock: posix.join(deployDir, \"lock\"),\n releaseRecord: posix.join(deployDir, \"release.json\"),\n liveSlotFile: posix.join(deployDir, \"live-slot\"),\n ctl: posix.join(deployDir, \"ctl\"),\n unitDir,\n unitTemplate: posix.join(unitDir, `sixb-${input.name}@.service`),\n caddyDir,\n caddySnippet: posix.join(caddyDir, `${input.name}.caddy`),\n } satisfies DeploymentLayout\n}\n\nexport function slotLayout(layout: DeploymentLayout, slot: DeploySlot): SlotLayout {\n const runDir = posix.join(layout.root, \"run\", slot)\n return {\n slot,\n unit: `sixb-${layout.name}@${slot}.service`,\n manifest: posix.join(layout.deployDir, `${slot}.json`),\n launcher: posix.join(layout.deployDir, slot),\n runDir,\n logDir: posix.join(runDir, \"logs\"),\n }\n}\n\nexport function legacyLayout(layout: DeploymentLayout): LegacyLayout {\n const unit = `sixb-${layout.name}.service`\n return {\n unit,\n unitPath: posix.join(layout.unitDir, unit),\n manifest: posix.join(layout.deployDir, \"processes.json\"),\n }\n}\n\nexport interface ReleaseLayout {\n readonly id: string\n readonly root: string\n /** The project inside the release: its root, or a folder of a monorepo. */\n readonly project: string\n readonly bunDir: string\n readonly bun: string\n}\n\nexport function releaseLayout(\n layout: DeploymentLayout,\n input: { readonly id: string; readonly projectPath: string; readonly bunVersion: string }\n): ReleaseLayout {\n const root = posix.join(layout.releasesDir, input.id)\n const bunDir = posix.join(layout.home, \".sixb\", \"bun\", input.bunVersion)\n return {\n id: input.id,\n root,\n project: posix.join(root, input.projectPath),\n bunDir,\n bun: posix.join(bunDir, \"bun\"),\n }\n}\n",
10
+ "/// <reference path=\"./sh.d.ts\" />\nimport { randomUUID } from \"node:crypto\"\nimport type {\n DeployContext,\n DeployControlAction,\n DeployLogsOptions,\n DeployRelease,\n DeployScript,\n DeploySource,\n DeployStatus,\n} from \"@sixb/core/deploy\"\nimport bootstrap from \"./bootstrap.sh\" with { type: \"text\" }\nimport { deriveReleaseId, parseEvent, type ReleasePlan, releaseStepLabels } from \"./plan\"\nimport { stripTerminalControl } from \"./server/logs\"\nimport { shellQuote } from \"./shell\"\nimport { RemoteScriptError, type RemoteShell } from \"./transport\"\n\nconst NOT_DEPLOYED = \"__SIXB_NOT_DEPLOYED__\"\n\n/**\n * Uploads the source and the plan, starts the release on the server detached from this\n * connection, and follows its log until it ends. A dropped connection leaves the deploy running.\n */\nexport async function deployRelease(\n shell: RemoteShell,\n release: DeployRelease,\n source: DeploySource,\n context: DeployContext\n): Promise<void> {\n const record = {\n commit: source.commit,\n ref: source.ref,\n deployedAt: new Date().toISOString(),\n deployedBy: context.deployedBy,\n }\n const releaseId = deriveReleaseId(record)\n const [home, incoming] = await capture(\n shell,\n [\n `root=\"$HOME\"/${shellQuote(release.name)}`,\n 'mkdir -p \"$root/deploy/incoming\" \"$root/deploy/runs\"',\n // Run logs hold all the build and migration output: for the deploy account alone.\n 'chmod 700 \"$root/deploy/runs\"',\n `incoming=\"$(mktemp -d \"$root/deploy/incoming/${releaseId}.XXXXXX\")\"`,\n // `mktemp` makes it 0700, and tar passes the mode of the upload's `.` on to the release.\n 'chmod 755 \"$incoming\"',\n `printf '%s\\n%s\\n' \"$HOME\" \"$incoming\"`,\n ].join(\"\\n\")\n )\n if (!home || !incoming)\n throw new Error(\"[SshTarget] The server did not report its home directory.\")\n\n const labels = releaseStepLabels(release)\n context.report({ type: \"steps\", labels })\n context.report({ type: \"step\", index: 0, status: \"running\" })\n for (const archive of source.archives) {\n const directory = archive.path === \".\" ? incoming : `${incoming}/${archive.path}`\n await shell.run(\n `mkdir -p ${shellQuote(directory)} && tar -x -f - -C ${shellQuote(directory)}`,\n { stdin: archive.open() }\n )\n }\n const runs = `${home}/${release.name}/deploy/runs`\n const plan: ReleasePlan = {\n version: 1,\n release,\n record,\n releaseId,\n projectPath: source.projectPath,\n }\n const files = { plan: `${runs}/${releaseId}.json`, script: `${runs}/${releaseId}.sh` }\n await upload(shell, files.plan, JSON.stringify(plan))\n await upload(shell, files.script, bootstrap)\n context.report({ type: \"step\", index: 0, status: \"done\" })\n\n const log = `${runs}/${releaseId}.log`\n const args = [\n release.name,\n releaseId,\n source.projectPath,\n release.bunVersion,\n incoming,\n files.plan,\n ]\n const [pid] = await capture(\n shell,\n `setsid nohup bash ${[files.script, ...args].map(shellQuote).join(\" \")} > ${shellQuote(log)} 2>&1 < /dev/null & echo $!`\n )\n await follow(shell, { pid: pid ?? \"\", log, labels, context })\n}\n\n/** Reads the release's log as it grows, until the release ends, and reports its progress. */\nasync function follow(\n shell: RemoteShell,\n input: {\n readonly pid: string\n readonly log: string\n readonly labels: readonly string[]\n readonly context: DeployContext\n }\n): Promise<void> {\n const { context, labels } = input\n let exit: number | null = null\n let failure: string | null = null\n try {\n await shell.run(\n `tail -n +1 -F --pid=${shellQuote(input.pid)} ${shellQuote(input.log)} 2> /dev/null`,\n {\n onLine: (line, stream) => {\n if (stream !== \"stdout\") return\n const event = parseEvent(line)\n if (event && \"exit\" in event) {\n exit = event.exit\n } else if (event) {\n const index = labels.indexOf(event.step)\n if (index === -1) context.report({ type: \"output\", line: event.step })\n else context.report({ type: \"step\", index, status: event.status })\n } else {\n const output = stripTerminalControl(line)\n if (output.startsWith(\"[SshTarget] \")) failure = output\n if (output.trim()) context.report({ type: \"output\", line: output })\n }\n },\n }\n )\n } catch (error) {\n throw new Error(\n `[SshTarget] Lost the connection while following the deploy, which carries on on the server. \\`sixb deploy status\\` shows the release once it ends; its log is ${input.log}.`,\n { cause: error }\n )\n }\n if (exit === 0) return\n // The step's output already reached `report`; the error repeats only its conclusion.\n throw new Error(failure ?? `[SshTarget] The deploy ended with code ${exit ?? \"unknown\"}.`)\n}\n\nasync function upload(shell: RemoteShell, path: string, content: string): Promise<void> {\n await shell.run(`umask 077 && cat > ${shellQuote(path)}`, {\n stdin: new Blob([content]).stream(),\n })\n}\n\nexport async function readStatus(shell: RemoteShell, name: string): Promise<DeployStatus> {\n const lines = await capture(shell, ctlScript(name, [\"status\", \"--json\"], { allowMissing: true }))\n const report = lines.find((line) => line.startsWith(\"{\"))\n if (lines.includes(NOT_DEPLOYED) || !report) {\n return { release: null, running: false, processes: [] }\n }\n return JSON.parse(report) as DeployStatus\n}\n\nexport async function streamLogs(\n shell: RemoteShell,\n name: string,\n options: DeployLogsOptions & { readonly terminal?: boolean }\n): Promise<void> {\n const args = [\n \"logs\",\n ...(options.service ? [options.service] : []),\n \"--tail\",\n String(options.tail),\n ...(options.follow ? [\"--follow\"] : []),\n ]\n await shell.run(ctlScript(name, args), {\n ...(options.terminal ? { terminal: true } : { onLine: (line: string) => options.write(line) }),\n })\n}\n\nexport async function controlServices(\n shell: RemoteShell,\n name: string,\n action: DeployControlAction,\n service: string | undefined\n): Promise<void> {\n await shell.run(ctlScript(name, [action, ...(service ? [service] : [])]))\n}\n\n/**\n * Uploads the script, then runs it through `ctl run` in a terminal on the server: Ctrl-C reaches\n * the script there, and so does a dropped connection, as a hangup. Holding the deploy lock shared\n * for the whole run keeps a deploy from replacing the code it imports or migrating its storage;\n * runs share it with each other. Resolves with the script's exit code.\n */\nexport async function runDeployScript(\n shell: RemoteShell,\n name: string,\n script: DeployScript\n): Promise<number> {\n const root = `\"$HOME\"/${shellQuote(name)}`\n const staged = `${root}/deploy/runs/${randomUUID()}`\n await shell.run(\n [\n `if [ ! -x ${root}/deploy/ctl ]; then`,\n ` echo \"Nothing named ${name} is deployed on this server yet.\" >&2; exit 1`,\n \"fi\",\n \"umask 077\",\n `mkdir -p ${root}/deploy/runs`,\n // An upload whose run never started is left behind; a day later it goes.\n `find ${root}/deploy/runs -type f -mmin +1440 -delete 2> /dev/null || true`,\n `cat > ${staged}`,\n ].join(\"\\n\"),\n { stdin: new Blob([Uint8Array.from(script.source)]).stream() }\n )\n\n const run = [\n `cd ${root}`,\n `exec 9> ${root}/deploy/lock`,\n \"if ! flock -s -n 9; then\",\n ` echo \"Waiting for a deploy of ${name} to finish…\" >&2`,\n \"fi\",\n \"if ! flock -s -w 600 9; then\",\n ` echo \"A deploy of ${name} has held its lock for 10 minutes.\" >&2`,\n ` rm -f ${staged}`,\n \" exit 1\",\n \"fi\",\n `exec ${root}/deploy/ctl run ${staged} ${[script.path, ...script.args].map(shellQuote).join(\" \")}`,\n ].join(\"\\n\")\n try {\n await shell.run(run, { terminal: true })\n return 0\n } catch (error) {\n // 255 is OpenSSH's own failure; any other code is the script's.\n if (error instanceof RemoteScriptError && error.exitCode !== 255) return error.exitCode\n throw error\n }\n}\n\n/** Runs the deployment's `ctl` with arguments; fails plainly when nothing is deployed yet. */\nfunction ctlScript(\n name: string,\n args: readonly string[],\n options: { readonly allowMissing?: boolean } = {}\n): string {\n return [\n `ctl=\"$HOME\"/${shellQuote(name)}/deploy/ctl`,\n 'if [ ! -x \"$ctl\" ]; then',\n options.allowMissing\n ? ` echo ${NOT_DEPLOYED}; exit 0`\n : ` echo \"Nothing named ${name} is deployed on this server yet.\" >&2; exit 1`,\n \"fi\",\n `exec \"$ctl\" ${args.map(shellQuote).join(\" \")}`,\n ].join(\"\\n\")\n}\n\nasync function capture(shell: RemoteShell, script: string): Promise<string[]> {\n const lines: string[] = []\n await shell.run(script, {\n onLine: (line, stream) => {\n if (stream === \"stdout\") lines.push(line)\n },\n })\n return lines\n}\n",
11
+ "import type { DeployCommand, DeployRecord, DeployRelease } from \"@sixb/core/deploy\"\n\n/** What the laptop sends the server's runner: the release, and how it was asked for. */\nexport interface ReleasePlan {\n readonly version: 1\n readonly release: DeployRelease\n readonly record: DeployRecord\n readonly releaseId: string\n readonly projectPath: string\n}\n\n/** Starts every progress line, so the laptop tells events from a command's output (RFC 7464). */\nexport const EVENT_PREFIX = \"\\u001e\"\n\nexport type ReleaseEvent =\n | { readonly step: string; readonly status: \"running\" | \"done\" }\n | { readonly exit: number }\n\nexport function event(value: ReleaseEvent): string {\n return `${EVENT_PREFIX}${JSON.stringify(value)}`\n}\n\nexport function parseEvent(line: string): ReleaseEvent | null {\n if (!line.startsWith(EVENT_PREFIX)) return null\n try {\n return JSON.parse(line.slice(EVENT_PREFIX.length)) as ReleaseEvent\n } catch {\n return null\n }\n}\n\n/** The steps a deploy runs, in order: the upload, then what the server does. */\nexport function releaseStepLabels(release: DeployRelease): string[] {\n return [\n \"Upload source\",\n \"Prepare release\",\n `Install Bun ${release.bunVersion}`,\n \"Install dependencies\",\n ...(release.steps.env ? [commandLabel(release.steps.env)] : []),\n ...release.steps.build.map(commandLabel),\n ...release.steps.beforeStart.map(commandLabel),\n \"Start new release\",\n \"Check services\",\n \"Update routes\",\n \"Move singletons\",\n \"Retire previous release\",\n ]\n}\n\nexport function commandLabel(command: DeployCommand): string {\n return [command.program, ...command.args].join(\" \")\n}\n\n/** A release folder's name: when, to the millisecond, then which commit. */\nexport function deriveReleaseId(record: DeployRecord): string {\n const stamp = record.deployedAt.replace(/[-:.]/g, \"\").slice(0, 18)\n const sha = record.commit.slice(0, 12).replace(/[^a-zA-Z0-9_-]/g, \"\")\n return `${stamp}Z-${sha || \"release\"}`\n}\n",
16
12
  "import { createWriteStream, type WriteStream } from \"node:fs\"\nimport { mkdir, open, rename, stat } from \"node:fs/promises\"\nimport { dirname, resolve } from \"node:path\"\nimport type { ProcessManifest } from \"./manifest\"\nimport { isMissing } from \"./state\"\n\n/** A log past this size moves to `<name>.log.1`, replacing the previous one. */\nexport const MAX_LOG_BYTES = 20 * 1024 * 1024\n\n/** How much of a log `readRecentLogLines` reads from its end. */\nconst RECENT_BYTES = 256 * 1024\n\nexport interface LogLine {\n readonly path: string\n readonly line: string\n}\n\nexport function processLogPath(\n manifest: Pick<ProcessManifest, \"logDir\">,\n processName: string,\n instance: number\n): string {\n return resolve(manifest.logDir, `${processName}-${instance}.log`)\n}\n\nexport async function openProcessLog(path: string): Promise<WriteStream> {\n await mkdir(dirname(path), { recursive: true })\n return createWriteStream(path, { flags: \"a\" })\n}\n\n/** Moves a log aside once it passes {@link MAX_LOG_BYTES}. Returns whether it did. */\nexport async function rotateLogIfLarge(path: string): Promise<boolean> {\n if ((await fileSize(path)) <= MAX_LOG_BYTES) return false\n await rename(path, `${path}.1`)\n return true\n}\n\n/** The last `tail` lines across the given logs, in time order. */\nexport async function readRecentLogLines(\n paths: readonly string[],\n tail: number\n): Promise<LogLine[]> {\n const lines: LogLine[] = []\n for (const path of paths) {\n const recent = (await readEnd(path, RECENT_BYTES)).split(/\\r?\\n/).filter(Boolean).slice(-tail)\n lines.push(...recent.map((line) => ({ path, line })))\n }\n return sortLogLines(lines).slice(-tail)\n}\n\nexport async function followLogFiles(\n paths: readonly string[],\n onLine: (line: LogLine) => void,\n options: { readonly intervalMs?: number; readonly signal?: AbortSignal } = {}\n): Promise<void> {\n const positions = new Map<string, number>()\n for (const path of paths) positions.set(path, await fileSize(path))\n\n while (!options.signal?.aborted) {\n await new Promise<void>((resolveWait) => setTimeout(resolveWait, options.intervalMs ?? 500))\n\n for (const path of paths) {\n const previous = positions.get(path) ?? 0\n const current = await fileSize(path)\n // A smaller file was rotated: read the new one from its start.\n const from = current < previous ? 0 : previous\n positions.set(path, current)\n if (current === from) continue\n\n const chunk = await readRange(path, from, current)\n for (const line of chunk.split(/\\r?\\n/).filter(Boolean)) onLine({ path, line })\n }\n }\n}\n\n/**\n * Terminal control sequences: services draw their startup view with cursor movement, which reads\n * as noise once it is in a log.\n */\nconst TERMINAL_CONTROL = /\\x1B(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\x07\\x1B]*(?:\\x07|\\x1B\\\\)|[@-Z\\\\-_])/g\n\nexport function stripTerminalControl(line: string): string {\n return line.replace(TERMINAL_CONTROL, \"\")\n}\n\n/** `hh:mm:ss service stderr message`, or `null` for an empty line. */\nexport function renderProcessLogLine(\n item: LogLine,\n options: { readonly label: string; readonly labelWidth?: number }\n): string | null {\n const parsed = parseStoredLogLine(item.line)\n const message = formatLogMessage(stripTerminalControl(parsed.message))\n if (!message.trim()) return null\n\n const time = parsed.timestamp ? formatLogTime(parsed.timestamp) : \" \".repeat(8)\n const label = options.label.padEnd(options.labelWidth ?? options.label.length)\n const stream = parsed.stream === \"stderr\" ? \" stderr\" : \"\"\n return `${time} ${label}${stream} ${message}`\n}\n\nfunction sortLogLines(lines: readonly LogLine[]): LogLine[] {\n return lines\n .map((line, index) => ({ line, index, time: logTimestampMs(line.line) }))\n .sort((a, b) => a.time - b.time || a.index - b.index)\n .map((item) => item.line)\n}\n\nfunction parseStoredLogLine(line: string): {\n readonly timestamp?: Date\n readonly stream?: \"stdout\" | \"stderr\"\n readonly message: string\n} {\n const match = line.match(/^\\[([^\\]]+)](?: \\[(stdout|stderr)])?\\s?(.*)$/)\n if (!match) return { message: line }\n const timestamp = new Date(match[1] ?? \"\")\n return {\n ...(Number.isFinite(timestamp.getTime()) ? { timestamp } : {}),\n ...(match[2] === \"stdout\" || match[2] === \"stderr\" ? { stream: match[2] } : {}),\n message: match[3] ?? \"\",\n }\n}\n\nfunction formatLogMessage(message: string): string {\n const start = message.match(/^start\\s+\\S+#\\d+\\s+pid=(\\S+)$/)\n if (start) return `started pid=${start[1]}`\n\n const exit = message.match(/^exit code=(\\S+)\\s+signal=(\\S+)$/)\n if (exit) {\n const code = exit[1] === \"null\" ? \"\" : ` code=${exit[1]}`\n const signal = exit[2] === \"null\" ? \"\" : ` signal=${exit[2]}`\n return `exited${code}${signal}`\n }\n\n return message\n}\n\nfunction formatLogTime(value: Date): string {\n return [value.getHours(), value.getMinutes(), value.getSeconds()]\n .map((part) => String(part).padStart(2, \"0\"))\n .join(\":\")\n}\n\nfunction logTimestampMs(line: string): number {\n const time = Date.parse(line.match(/^\\[([^\\]]+)]/)?.[1] ?? \"\")\n return Number.isFinite(time) ? time : Number.MAX_SAFE_INTEGER\n}\n\nasync function readEnd(path: string, bytes: number): Promise<string> {\n const size = await fileSize(path)\n const text = await readRange(path, Math.max(0, size - bytes), size)\n // Drop a line cut in half by starting mid-file.\n return size > bytes ? text.slice(text.indexOf(\"\\n\") + 1) : text\n}\n\nasync function readRange(path: string, start: number, end: number): Promise<string> {\n if (end <= start) return \"\"\n let handle: Awaited<ReturnType<typeof open>>\n try {\n handle = await open(path, \"r\")\n } catch (error) {\n if (isMissing(error)) return \"\"\n throw error\n }\n try {\n const buffer = Buffer.alloc(end - start)\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, start)\n return buffer.subarray(0, bytesRead).toString(\"utf8\")\n } finally {\n await handle.close()\n }\n}\n\nasync function fileSize(path: string): Promise<number> {\n try {\n return (await stat(path)).size\n } catch (error) {\n if (isMissing(error)) return 0\n throw error\n }\n}\n",
17
- "import { mkdtemp, rm } from \"node:fs/promises\"\nimport { tmpdir } from \"node:os\"\nimport { join } from \"node:path\"\nimport { shellQuote } from \"./shell\"\n\nexport interface RunOptions {\n /** Streamed to the script's standard input. The script itself then travels as an argument. */\n readonly stdin?: ReadableStream<Uint8Array>\n /**\n * Every line the script prints, and which stream it came from. Read results from `stdout`\n * only: a login script or a failed redirection can write to `stderr` first.\n */\n readonly onLine?: (line: string, stream: \"stdout\" | \"stderr\") => void\n /** Attach the terminal, so the remote command stops when you press Ctrl-C. */\n readonly terminal?: boolean\n}\n\n/** Runs bash scripts on a deployment's server. */\nexport interface RemoteShell {\n /** Rejects with the script's last output lines when it exits non-zero. */\n run(script: string, options?: RunOptions): Promise<void>\n close(): Promise<void>\n}\n\nexport class RemoteScriptError extends Error {\n readonly exitCode: number\n\n constructor(message: string, exitCode: number) {\n super(message)\n this.name = \"RemoteScriptError\"\n this.exitCode = exitCode\n }\n}\n\nconst OUTPUT_TAIL = 20\n\n/**\n * One SSH connection, shared by every script a command runs through OpenSSH's connection\n * multiplexing. Never prompts: a password, passphrase, or unknown host key fails with a message\n * instead of hanging a deploy.\n */\nexport class SshShell implements RemoteShell {\n private constructor(\n private readonly destination: string,\n private readonly controlDir: string\n ) {}\n\n static async open(destination: string): Promise<SshShell> {\n // Kept short: a socket path longer than about 100 characters cannot be bound.\n const controlDir = await mkdtemp(join(tmpdir(), \"sixb-ssh-\"))\n const shell = new SshShell(destination, controlDir)\n try {\n await runProcess([\"ssh\", ...shell.options(), \"-M\", \"-N\", \"-f\", destination], {})\n } catch (error) {\n await rm(controlDir, { recursive: true, force: true })\n throw sshError(destination, error)\n }\n return shell\n }\n\n async run(script: string, options: RunOptions = {}): Promise<void> {\n const inline = options.stdin !== undefined || options.terminal === true\n const command = inline ? [\"bash\", \"-c\", shellQuote(script)] : [\"bash\", \"-s\"]\n try {\n await runProcess(\n [\n \"ssh\",\n ...this.options(),\n ...(options.terminal ? [\"-tt\"] : []),\n this.destination,\n command.join(\" \"),\n ],\n {\n ...options,\n ...(inline ? {} : { stdin: new Blob([script]).stream() }),\n }\n )\n } catch (error) {\n throw sshError(this.destination, error)\n }\n }\n\n async close(): Promise<void> {\n await runProcess([\"ssh\", ...this.options(), \"-O\", \"exit\", this.destination], {}).catch(() => {})\n await rm(this.controlDir, { recursive: true, force: true })\n }\n\n private options(): string[] {\n return [\n \"-o\",\n \"BatchMode=yes\",\n \"-o\",\n \"ConnectTimeout=15\",\n // Notices a dead connection during a long build instead of waiting forever.\n \"-o\",\n \"ServerAliveInterval=15\",\n \"-o\",\n \"ControlMaster=auto\",\n \"-o\",\n \"ControlPersist=60\",\n \"-o\",\n \"LogLevel=ERROR\",\n \"-S\",\n join(this.controlDir, \"control\"),\n ]\n }\n}\n\n/** Runs the scripts on this machine instead, with its own home. For tests. */\nexport class LocalShell implements RemoteShell {\n constructor(private readonly env: Readonly<Record<string, string>> = {}) {}\n\n async run(script: string, options: RunOptions = {}): Promise<void> {\n const inline = options.stdin !== undefined || options.terminal === true\n await runProcess(inline ? [\"bash\", \"-c\", script] : [\"bash\", \"-s\"], {\n ...options,\n ...(inline ? {} : { stdin: new Blob([script]).stream() }),\n env: this.env,\n })\n }\n\n async close(): Promise<void> {}\n}\n\nasync function runProcess(\n command: readonly string[],\n options: RunOptions & { readonly env?: Readonly<Record<string, string>> }\n): Promise<void> {\n if (options.terminal) {\n const child = Bun.spawn([...command], {\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\n env: { ...process.env, ...options.env },\n })\n const exitCode = await child.exited\n if (exitCode !== 0) throw new RemoteScriptError(`exited with code ${exitCode}`, exitCode)\n return\n }\n\n const child = Bun.spawn([...command], {\n stdin: options.stdin ? \"pipe\" : \"ignore\",\n stdout: \"pipe\",\n stderr: \"pipe\",\n env: { ...process.env, ...options.env },\n })\n const tail: string[] = []\n const onLine = (stream: \"stdout\" | \"stderr\") => (line: string) => {\n tail.push(line)\n if (tail.length > OUTPUT_TAIL) tail.shift()\n options.onLine?.(line, stream)\n }\n\n const [exitCode] = await Promise.all([\n child.exited,\n options.stdin && child.stdin ? pump(options.stdin, child.stdin) : undefined,\n readLines(child.stdout, onLine(\"stdout\")),\n readLines(child.stderr, onLine(\"stderr\")),\n ])\n if (exitCode !== 0) {\n throw new RemoteScriptError(\n tail.length > 0 ? tail.join(\"\\n\") : `exited with code ${exitCode}`,\n exitCode\n )\n }\n}\n\nasync function pump(source: ReadableStream<Uint8Array>, sink: Bun.FileSink): Promise<void> {\n const reader = source.getReader()\n try {\n for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {\n sink.write(chunk.value)\n await sink.flush()\n }\n } finally {\n await sink.end()\n }\n}\n\nasync function readLines(\n stream: ReadableStream<Uint8Array>,\n onLine: (line: string) => void\n): Promise<void> {\n const reader = stream.getReader()\n const decoder = new TextDecoder()\n let buffer = \"\"\n for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {\n buffer += decoder.decode(chunk.value, { stream: true })\n const lines = buffer.split(/\\r?\\n/)\n buffer = lines.pop() ?? \"\"\n for (const line of lines) onLine(line)\n }\n buffer += decoder.decode()\n if (buffer) onLine(buffer)\n}\n\n/** OpenSSH's own failures, which exit 255, reworded as what to do about them. */\nexport function sshError(destination: string, error: unknown): Error {\n if (!(error instanceof RemoteScriptError) || error.exitCode !== 255) {\n return error instanceof Error ? error : new Error(String(error))\n }\n const output = error.message\n const host = destination.split(\"@\").at(-1) ?? destination\n const reason = /REMOTE HOST IDENTIFICATION HAS CHANGED/.test(output)\n ? `${host} answered with a host key other than the one on record. If the server was rebuilt, remove the old key with \\`ssh-keygen -R ${host}\\` and connect once to accept the new one; for CI, run \\`sixb deploy ci\\` again. Otherwise, something else is answering at that address: do not deploy to it.`\n : /Host key verification failed/.test(output)\n ? `The host key for ${host} is not trusted yet. Connect once with \\`ssh ${destination}\\`, check the fingerprint, and accept it.`\n : /Permission denied/.test(output)\n ? `The server refused your SSH key for ${destination}. Load it into your SSH agent, or ask someone with access to authorize it.`\n : /Could not resolve hostname/.test(output)\n ? `${host} does not resolve. Check the target's host.`\n : /Connection refused|timed out|No route to host/.test(output)\n ? `Could not reach ${host} over SSH.`\n : `SSH to ${destination} failed.`\n return new RemoteScriptError(`[SshTarget] ${reason}\\n${output}`, error.exitCode)\n}\n",
18
- "import { access } from \"node:fs/promises\"\nimport { ENV_TOKEN_FILE } from \"./layout\"\nimport { shellQuote } from \"./shell\"\nimport { RemoteScriptError, type RemoteShell } from \"./transport\"\n\n/** The first line of the Caddyfile the Debian and Ubuntu packages install. */\nconst PACKAGED_CADDYFILE = \"The Caddyfile is an easy way to configure your Caddy web server.\"\n\n/**\n * Everything that needs root, run once per server and once per deploy user, safe to run again.\n * Afterwards the deploy user needs no sudo but reloading Caddy.\n *\n * Caddy's configuration is taken over only when it is still the one the package installed. A\n * server that already serves other sites keeps its configuration and gains one import line (the\n * old file is kept beside it), and its admin API stays where that configuration puts it.\n */\nexport function renderAdminScript(input: {\n readonly user: string\n readonly publicKey: string\n readonly admin: string\n}): string {\n const user = shellQuote(input.user)\n return [\n \"set -euo pipefail\",\n `deploy_user=${user}`,\n `public_key=${shellQuote(input.publicKey)}`,\n `admin_login=${shellQuote(input.admin)}`,\n 'step() { printf \"\\\\n== %s\\\\n\" \"$1\"; }',\n // Shows a command's output only when it fails, so a first setup is not pages of apt.\n 'quiet() { log=\"$(mktemp)\"; if \"$@\" > \"$log\" 2>&1; then rm -f \"$log\"; else status=$?; tail -n 20 \"$log\" >&2; rm -f \"$log\"; return \"$status\"; fi; }',\n \"\",\n 'step \"Server\"',\n \"if ! command -v apt-get > /dev/null || ! command -v systemctl > /dev/null; then\",\n ' echo \"sixb deploy needs an Ubuntu or Debian server with systemd.\" >&2',\n \" exit 1\",\n \"fi\",\n '. /etc/os-release && echo \"$PRETTY_NAME\"',\n \"\",\n 'step \"Packages\"',\n \"export DEBIAN_FRONTEND=noninteractive\",\n 'missing=\"\"',\n \"for package in git curl unzip ca-certificates gnupg; do\",\n // `ii` is installed; `dpkg -s` also succeeds for a removed package whose config it keeps.\n ' dpkg -l \"$package\" 2> /dev/null | grep -q \"^ii\" || missing=\"$missing $package\"',\n \"done\",\n 'if [ -n \"$missing\" ]; then',\n ' echo \"Installing$missing\"',\n \" quiet apt-get update\",\n \" quiet apt-get install -y $missing\",\n \"fi\",\n \"if ! command -v caddy > /dev/null; then\",\n ' echo \"Installing caddy\"',\n \" curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/gpg.key |\",\n \" gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg\",\n \" curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt > /etc/apt/sources.list.d/caddy-stable.list\",\n \" quiet apt-get update\",\n \" quiet apt-get install -y caddy\",\n \"fi\",\n \"echo \\\"git, curl, unzip, caddy $(caddy version | cut -d' ' -f1)\\\"\",\n \"\",\n 'step \"Deploy user $deploy_user\"',\n 'id \"$deploy_user\" > /dev/null 2>&1 || useradd --create-home --shell /bin/bash --user-group \"$deploy_user\"',\n 'home=\"$(getent passwd \"$deploy_user\" | cut -d: -f6)\"',\n 'chmod 750 \"$home\"',\n 'install -d -m 0700 -o \"$deploy_user\" -g \"$deploy_user\" \"$home/.ssh\"',\n 'touch \"$home/.ssh/authorized_keys\"',\n 'grep -qxF \"$public_key\" \"$home/.ssh/authorized_keys\" || echo \"$public_key\" >> \"$home/.ssh/authorized_keys\"',\n 'chown \"$deploy_user:$deploy_user\" \"$home/.ssh/authorized_keys\"',\n 'chmod 0600 \"$home/.ssh/authorized_keys\"',\n 'loginctl enable-linger \"$deploy_user\"',\n 'grep -qs XDG_RUNTIME_DIR \"$home/.profile\" ||',\n ' echo \\'export XDG_RUNTIME_DIR=\"/run/user/$(id -u)\"\\' >> \"$home/.profile\"',\n 'chown \"$deploy_user:$deploy_user\" \"$home/.profile\"',\n // The admin reads every project under this user without sudo; `.env` stays 0600.\n 'if [ \"$admin_login\" != root ]; then usermod -aG \"$deploy_user\" \"$admin_login\"; fi',\n 'echo \"$home, key-only, services start at boot\"',\n \"\",\n 'step \"Caddy reload\"',\n \"groupadd -f sixb-deploy\",\n 'usermod -aG sixb-deploy \"$deploy_user\"',\n 'sudoers=\"$(mktemp)\"',\n \"echo '%sixb-deploy ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy' > \\\"$sudoers\\\"\",\n 'visudo -cf \"$sudoers\" > /dev/null',\n 'install -m 0440 \"$sudoers\" /etc/sudoers.d/sixb',\n 'rm -f \"$sudoers\"',\n 'echo \"$deploy_user may run sudo systemctl reload caddy, and nothing else\"',\n \"\",\n 'step \"Caddy routes\"',\n \"caddyfile=/etc/caddy/Caddyfile\",\n \"backup=/etc/caddy/Caddyfile.before-sixb-deploy\",\n \"install -d -m 0755 /etc/caddy/sixb.d\",\n 'install -d -m 0755 -o \"$deploy_user\" -g \"$deploy_user\" \"/etc/caddy/sixb.d/$deploy_user\"',\n // Caddy allows one `*` per import pattern, so each deploy user's folder has an index file.\n 'printf \\'import /etc/caddy/sixb.d/%s/*.caddy\\\\n\\' \"$deploy_user\" > \"/etc/caddy/sixb.d/$deploy_user.caddy\"',\n \"restart_caddy=0\",\n `if [ ! -s \"$caddyfile\" ] || grep -qF ${shellQuote(PACKAGED_CADDYFILE)} \"$caddyfile\"; then`,\n ' if [ -f \"$caddyfile\" ]; then cp \"$caddyfile\" \"$backup\"; fi',\n \" cat > \\\"$caddyfile\\\" <<'__SIXB_CADDYFILE__'\",\n \"# Managed by sixb deploy. Each deploy user's routes live in /etc/caddy/sixb.d/<user>/.\",\n \"{\",\n \"\\t# Only root and Caddy may change the running configuration.\",\n \"\\tadmin unix//var/lib/caddy/admin.sock\",\n \"}\",\n \"\",\n \"import /etc/caddy/sixb.d/*.caddy\",\n \"__SIXB_CADDYFILE__\",\n // A restart, not a reload: the admin address itself moves.\n \" restart_caddy=1\",\n \"elif ! grep -qF 'import /etc/caddy/sixb.d/*.caddy' \\\"$caddyfile\\\"; then\",\n ' cp \"$caddyfile\" \"$backup\"',\n \" printf '\\\\n# Routes written by sixb deploy, one folder per deploy user.\\\\nimport /etc/caddy/sixb.d/*.caddy\\\\n' >> \\\"$caddyfile\\\"\",\n ' echo \"Kept this server\\'s Caddyfile and added one import; the previous one is $backup.\"',\n \"fi\",\n 'if ! caddy validate --config \"$caddyfile\" --adapter caddyfile > /tmp/sixb-caddy-validate.log 2>&1; then',\n \" tail -n 5 /tmp/sixb-caddy-validate.log >&2\",\n ' if [ -f \"$backup\" ]; then cp \"$backup\" \"$caddyfile\"; fi',\n ' echo \"Caddy rejected the configuration; the previous one is back in place.\" >&2',\n \" exit 1\",\n \"fi\",\n 'if [ \"$restart_caddy\" = 1 ]; then systemctl restart caddy; else systemctl reload caddy; fi',\n 'echo \"/etc/caddy/sixb.d/$deploy_user\"',\n \"\",\n 'step \"Checks\"',\n // Reported, not changed: editing sshd or the firewall is how people lock themselves out.\n \"sshd -T 2> /dev/null | grep -qx 'passwordauthentication yes' &&\",\n ' echo \"Warning: SSH accepts passwords. Set PasswordAuthentication no in /etc/ssh/sshd_config.\" || true',\n \"sshd -T 2> /dev/null | grep -qx 'permitrootlogin yes' &&\",\n ' echo \"Warning: root can log in with a password. Set PermitRootLogin prohibit-password.\" || true',\n \"if command -v ufw > /dev/null && ufw status 2> /dev/null | grep -q '^Status: active'; then\",\n \" for port in 80 443; do\",\n ' ufw status | grep -qE \"^$port(/tcp)?\\\\s+ALLOW\" ||',\n ' echo \"Warning: the firewall blocks port $port, which Caddy needs. Run: sudo ufw allow $port/tcp\"',\n \" done\",\n \"fi\",\n 'echo \"Done.\"',\n ].join(\"\\n\")\n}\n\n/**\n * The public key to authorize for deploys: the one given, else the first key SSH would offer to\n * the server that has a `.pub` beside it, else the first key in the SSH agent.\n */\nexport async function pickPublicKey(input: {\n readonly key?: string\n readonly identityFiles: readonly string[]\n}): Promise<{ readonly text: string; readonly source: string }> {\n if (input.key) {\n const path = input.key.endsWith(\".pub\") ? input.key : `${input.key}.pub`\n return { text: (await Bun.file(path).text()).trim(), source: path }\n }\n for (const identity of input.identityFiles) {\n const path = `${identity}.pub`\n if (\n await access(path).then(\n () => true,\n () => false\n )\n ) {\n return { text: (await Bun.file(path).text()).trim(), source: path }\n }\n }\n const agent = Bun.spawn([\"ssh-add\", \"-L\"], { stdout: \"pipe\", stderr: \"ignore\" })\n const first = (await new Response(agent.stdout).text()).split(\"\\n\").find((line) => line.trim())\n if ((await agent.exited) === 0 && first) return { text: first.trim(), source: \"your SSH agent\" }\n throw new Error(\n \"[SshTarget] No public key to authorize. Pass one with `--key ~/.ssh/id_ed25519.pub`.\"\n )\n}\n\n/**\n * Creates the deploy's token when the server doesn't have one. This asks the server rather than\n * going by the checks setup started with: on a fresh server those stop at SSH, before they reach\n * the token. Returns whether it installed one.\n */\nexport async function ensureEnvToken(\n shell: RemoteShell,\n name: string,\n createToken: () => Promise<string>\n): Promise<boolean> {\n const path = `\"$HOME\"/${shellQuote(`${name}/${ENV_TOKEN_FILE}`)}`\n\n const installed = await shell.run(`[ -s ${path} ]`).then(\n () => true,\n (error: unknown) => {\n if (error instanceof RemoteScriptError && error.exitCode === 1) return false\n throw error\n }\n )\n if (installed) return false\n\n // On standard input, because a script is an argument any process on the server can read.\n await shell.run(\n [\n \"set -e\",\n \"umask 077\",\n `mkdir -p \"$HOME\"/${shellQuote(name)}`,\n `cat > ${path}.new`,\n `mv ${path}.new ${path}`,\n ].join(\"\\n\"),\n { stdin: new Blob([`${await createToken()}\\n`]).stream() }\n )\n return true\n}\n",
13
+ "import { mkdtemp, rm } from \"node:fs/promises\"\nimport { tmpdir } from \"node:os\"\nimport { join } from \"node:path\"\nimport { shellQuote } from \"./shell\"\n\nexport interface RunOptions {\n /** Streamed to the script's standard input. The script itself then travels as an argument. */\n readonly stdin?: ReadableStream<Uint8Array>\n /**\n * Every line the script prints, and which stream it came from. Read results from `stdout`\n * only: a login script or a failed redirection can write to `stderr` first.\n */\n readonly onLine?: (line: string, stream: \"stdout\" | \"stderr\") => void\n /** Attach the terminal, so the remote command stops when you press Ctrl-C. */\n readonly terminal?: boolean\n}\n\n/** Runs bash scripts on a deployment's server. */\nexport interface RemoteShell {\n /** Rejects with the script's last output lines when it exits non-zero. */\n run(script: string, options?: RunOptions): Promise<void>\n close(): Promise<void>\n}\n\nexport class RemoteScriptError extends Error {\n readonly exitCode: number\n\n constructor(message: string, exitCode: number) {\n super(message)\n this.name = \"RemoteScriptError\"\n this.exitCode = exitCode\n }\n}\n\nconst OUTPUT_TAIL = 20\n\n/**\n * One SSH connection, shared by every script a command runs through OpenSSH's connection\n * multiplexing. Never prompts: a password, passphrase, or unknown host key fails with a message\n * instead of hanging a deploy.\n */\nexport class SshShell implements RemoteShell {\n private constructor(\n private readonly destination: string,\n private readonly controlDir: string\n ) {}\n\n static async open(destination: string): Promise<SshShell> {\n // Kept short: a socket path longer than about 100 characters cannot be bound.\n const controlDir = await mkdtemp(join(tmpdir(), \"sixb-ssh-\"))\n const shell = new SshShell(destination, controlDir)\n try {\n await runProcess([\"ssh\", ...shell.options(), \"-M\", \"-N\", \"-f\", destination], {})\n } catch (error) {\n await rm(controlDir, { recursive: true, force: true })\n throw sshError(destination, error)\n }\n return shell\n }\n\n async run(script: string, options: RunOptions = {}): Promise<void> {\n const inline = options.stdin !== undefined || options.terminal === true\n const command = inline ? [\"bash\", \"-c\", shellQuote(script)] : [\"bash\", \"-s\"]\n try {\n await runProcess(\n [\n \"ssh\",\n ...this.options(),\n ...(options.terminal ? [\"-tt\"] : []),\n this.destination,\n command.join(\" \"),\n ],\n {\n ...options,\n ...(inline ? {} : { stdin: new Blob([script]).stream() }),\n }\n )\n } catch (error) {\n throw sshError(this.destination, error)\n }\n }\n\n async close(): Promise<void> {\n await runProcess([\"ssh\", ...this.options(), \"-O\", \"exit\", this.destination], {}).catch(() => {})\n await rm(this.controlDir, { recursive: true, force: true })\n }\n\n private options(): string[] {\n return [\n \"-o\",\n \"BatchMode=yes\",\n \"-o\",\n \"ConnectTimeout=15\",\n // Notices a dead connection during a long build instead of waiting forever.\n \"-o\",\n \"ServerAliveInterval=15\",\n \"-o\",\n \"ControlMaster=auto\",\n \"-o\",\n \"ControlPersist=60\",\n \"-o\",\n \"LogLevel=ERROR\",\n \"-S\",\n join(this.controlDir, \"control\"),\n ]\n }\n}\n\n/** Runs the scripts on this machine instead, with its own home. For tests. */\nexport class LocalShell implements RemoteShell {\n constructor(private readonly env: Readonly<Record<string, string>> = {}) {}\n\n async run(script: string, options: RunOptions = {}): Promise<void> {\n const inline = options.stdin !== undefined || options.terminal === true\n await runProcess(inline ? [\"bash\", \"-c\", script] : [\"bash\", \"-s\"], {\n ...options,\n ...(inline ? {} : { stdin: new Blob([script]).stream() }),\n env: this.env,\n })\n }\n\n async close(): Promise<void> {}\n}\n\nasync function runProcess(\n command: readonly string[],\n options: RunOptions & { readonly env?: Readonly<Record<string, string>> }\n): Promise<void> {\n if (options.terminal) {\n const child = Bun.spawn([...command], {\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\n env: { ...process.env, ...options.env },\n })\n const exitCode = await child.exited\n if (exitCode !== 0) throw new RemoteScriptError(`exited with code ${exitCode}`, exitCode)\n return\n }\n\n const child = Bun.spawn([...command], {\n stdin: options.stdin ? \"pipe\" : \"ignore\",\n stdout: \"pipe\",\n stderr: \"pipe\",\n env: { ...process.env, ...options.env },\n })\n const tail: string[] = []\n const onLine = (stream: \"stdout\" | \"stderr\") => (line: string) => {\n tail.push(line)\n if (tail.length > OUTPUT_TAIL) tail.shift()\n options.onLine?.(line, stream)\n }\n\n const [exitCode] = await Promise.all([\n child.exited,\n options.stdin && child.stdin ? pump(options.stdin, child.stdin) : undefined,\n readLines(child.stdout, onLine(\"stdout\")),\n readLines(child.stderr, onLine(\"stderr\")),\n ])\n if (exitCode !== 0) {\n throw new RemoteScriptError(\n tail.length > 0 ? tail.join(\"\\n\") : `exited with code ${exitCode}`,\n exitCode\n )\n }\n}\n\nasync function pump(source: ReadableStream<Uint8Array>, sink: Bun.FileSink): Promise<void> {\n const reader = source.getReader()\n try {\n for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {\n sink.write(chunk.value)\n await sink.flush()\n }\n } finally {\n await sink.end()\n }\n}\n\nasync function readLines(\n stream: ReadableStream<Uint8Array>,\n onLine: (line: string) => void\n): Promise<void> {\n const reader = stream.getReader()\n const decoder = new TextDecoder()\n let buffer = \"\"\n for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {\n buffer += decoder.decode(chunk.value, { stream: true })\n const lines = buffer.split(/\\r?\\n/)\n buffer = lines.pop() ?? \"\"\n for (const line of lines) onLine(line)\n }\n buffer += decoder.decode()\n if (buffer) onLine(buffer)\n}\n\n/** OpenSSH's own failures, which exit 255, reworded as what to do about them. */\nexport function sshError(destination: string, error: unknown): Error {\n if (!(error instanceof RemoteScriptError) || error.exitCode !== 255) {\n return error instanceof Error ? error : new Error(String(error))\n }\n const output = error.message\n const host = destination.split(\"@\").at(-1) ?? destination\n return new RemoteScriptError(\n `[SshTarget] ${sshFailureReason(output, destination, host)}\\n${output}`,\n error.exitCode\n )\n}\n\nfunction sshFailureReason(output: string, destination: string, host: string): string {\n if (/Tailscale SSH requires an additional check/.test(output)) {\n return `Tailscale SSH wants you to sign in again before reaching ${destination}: open the link below, then try again.`\n }\n if (/tailnet policy does not permit/.test(output)) {\n return `The tailnet's SSH rules don't let you reach ${destination}. Ask a tailnet admin to allow it.`\n }\n if (/REMOTE HOST IDENTIFICATION HAS CHANGED/.test(output)) {\n return `${host} answered with a host key other than the one on record. If the server was rebuilt, remove the old key with \\`ssh-keygen -R ${host}\\` and connect once to accept the new one. Otherwise, something else is answering at that address: do not deploy to it.`\n }\n if (/Host key verification failed/.test(output)) {\n return `The host key for ${host} is not trusted yet. Connect once with \\`ssh ${destination}\\`, check the fingerprint, and accept it.`\n }\n if (/Permission denied/.test(output)) {\n return `The server refused your SSH key for ${destination}. Load it into your SSH agent, or ask someone with access to the server to allow it.`\n }\n if (/Could not resolve hostname/.test(output))\n return `${host} does not resolve. Check the target's host.`\n if (/Connection refused|timed out|No route to host/.test(output)) {\n return `Could not reach ${host} over SSH.`\n }\n return `SSH to ${destination} failed.`\n}\n",
19
14
  "import { homedir } from \"node:os\"\n\nexport interface ResolvedSshConfig {\n /** The real hostname or address behind the target's host, which may be an SSH config alias. */\n readonly hostname: string\n readonly port: number\n /** The host SSH jumps through first, when the config sets one. */\n readonly proxyJump?: string\n /** Identity files SSH would offer, in order, with `~` expanded. */\n readonly identityFiles: readonly string[]\n}\n\n/** What OpenSSH makes of a destination once its config applies, from `ssh -G`. */\nexport async function resolveSshConfig(destination: string): Promise<ResolvedSshConfig> {\n const child = Bun.spawn([\"ssh\", \"-G\", destination], { stdout: \"pipe\", stderr: \"pipe\" })\n const [exitCode, output] = await Promise.all([child.exited, new Response(child.stdout).text()])\n if (exitCode !== 0) throw new Error(`[SshTarget] ssh -G ${destination} failed.`)\n\n let hostname = destination.split(\"@\").at(-1) ?? destination\n let port = 22\n let proxyJump: string | undefined\n const identityFiles: string[] = []\n for (const line of output.split(\"\\n\")) {\n const [key, ...rest] = line.split(\" \")\n const value = rest.join(\" \")\n if (key === \"hostname\" && value) hostname = value\n if (key === \"port\" && Number(value) > 0) port = Number(value)\n // `ssh -G` prints `none` for a host reached directly.\n if ((key === \"proxyjump\" || key === \"proxycommand\") && value && value !== \"none\") {\n proxyJump = value\n }\n if (key === \"identityfile\" && value) identityFiles.push(value.replace(/^~(?=\\/)/, homedir()))\n }\n return { hostname, port, identityFiles, ...(proxyJump ? { proxyJump } : {}) }\n}\n"
20
15
  ],
21
- "mappings": ";;AAAA;;;ACAA,uBAAS;;;ACAT;AAGA,IAAM,YAAY,IAAI,IAAI;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAWM,SAAS,kBAAkB,CAAC,MAAoC;AAAA,EACrE,MAAM,UAAU,KAAK,KAAK;AAAA,EAC1B,IAAI,CAAC,WAAW,QAAQ,WAAW,GAAG;AA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