@sixb/deploy-ssh 0.2.6 → 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.
- package/README.md +51 -44
- package/dist/check/index.d.ts +24 -0
- package/dist/check/index.d.ts.map +1 -0
- package/dist/check/judge.d.ts +23 -0
- package/dist/check/judge.d.ts.map +1 -0
- package/dist/index.js +599 -1527
- package/dist/index.js.map +10 -16
- package/dist/layout.d.ts +87 -30
- package/dist/layout.d.ts.map +1 -1
- package/dist/operations.d.ts +5 -3
- package/dist/operations.d.ts.map +1 -1
- package/dist/plan.d.ts +25 -0
- package/dist/plan.d.ts.map +1 -0
- package/dist/render.d.ts +15 -11
- package/dist/render.d.ts.map +1 -1
- package/dist/server/manifest.d.ts +10 -4
- package/dist/server/manifest.d.ts.map +1 -1
- package/dist/server/release-host.d.ts +4 -0
- package/dist/server/release-host.d.ts.map +1 -0
- package/dist/server/release.d.ts +46 -0
- package/dist/server/release.d.ts.map +1 -0
- package/dist/server/state.d.ts +0 -4
- package/dist/server/state.d.ts.map +1 -1
- package/dist/server/supervisor.d.ts +8 -8
- package/dist/server/supervisor.d.ts.map +1 -1
- package/dist/ssh-target.d.ts +3 -24
- package/dist/ssh-target.d.ts.map +1 -1
- package/dist/transport.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/bootstrap.sh +93 -0
- package/src/check/index.ts +117 -0
- package/src/check/judge.ts +299 -0
- package/src/check/probe.sh +99 -0
- package/src/layout.ts +109 -61
- package/src/operations.ts +105 -65
- package/src/plan.ts +59 -0
- package/src/render.ts +54 -35
- package/src/server/cli.ts +16 -20
- package/src/server/manifest.ts +13 -6
- package/src/server/release-host.ts +81 -0
- package/src/server/release.ts +738 -0
- package/src/server/state.ts +1 -5
- package/src/server/supervisor.ts +45 -238
- package/src/sh.d.ts +4 -0
- package/src/ssh-target.ts +43 -285
- package/src/transport.ts +28 -12
- package/dist/access.d.ts +0 -11
- package/dist/access.d.ts.map +0 -1
- package/dist/check.d.ts +0 -31
- package/dist/check.d.ts.map +0 -1
- package/dist/ci.d.ts +0 -27
- package/dist/ci.d.ts.map +0 -1
- package/dist/keys.d.ts +0 -13
- package/dist/keys.d.ts.map +0 -1
- package/dist/scripts.d.ts +0 -48
- package/dist/scripts.d.ts.map +0 -1
- package/dist/setup.d.ts +0 -32
- package/dist/setup.d.ts.map +0 -1
- package/src/access.ts +0 -107
- package/src/check.ts +0 -257
- package/src/ci.ts +0 -88
- package/src/keys.ts +0 -57
- package/src/scripts.ts +0 -703
- package/src/setup.ts +0 -203
package/dist/index.js.map
CHANGED
|
@@ -1,25 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/ssh-target.ts", "../src/
|
|
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 * Second local port pair for blue-green cutovers while the active slot keeps serving. Defaults\n * to `ports` plus 10 (app 3011, api 3012).\n */\n readonly standbyPorts?: Readonly<Partial<Record<DeployHttpServiceName, number>>>\n}\n\nconst OPTIONS = [\"host\", \"user\", \"ports\", \"standbyPorts\"] 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 readonly #standbyPorts: 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 const primary = { ...DEFAULT_PORTS, ...validatePorts(options.ports, \"ports\") }\n const standbyDefaults: Record<DeployHttpServiceName, number> = {\n app: defaultStandbyPort(primary.app),\n api: defaultStandbyPort(primary.api),\n }\n const standby = { ...standbyDefaults, ...validatePorts(options.standbyPorts, \"standbyPorts\") }\n assertDistinctPorts(primary, standby)\n this.#ports = primary\n this.#standbyPorts = standby\n }\n\n listenAddress(service: DeployHttpServiceName): DeployListenAddress {\n return { host: LISTEN_HOST, port: this.#ports[service] }\n }\n\n standbyListenAddress(service: DeployHttpServiceName): DeployListenAddress {\n return { host: LISTEN_HOST, port: this.#standbyPorts[service] }\n }\n\n deploy(release: DeployRelease, source: DeploySource, context: DeployContext): Promise<void> {\n return this.#connected((shell) =>\n deployRelease(shell, this.user, release, source, context, {\n blue: this.#ports,\n green: this.#standbyPorts,\n })\n )\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 if (!service.http || (service.name !== \"api\" && service.name !== \"app\")) return []\n return [\n { service: service.name, port: this.#ports[service.name] },\n { service: `${service.name}-standby`, port: this.#standbyPorts[service.name] },\n ]\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 `root=\"$HOME\"/${shellQuote(context.name)}`,\n `project=\"$HOME\"/${shellQuote(`${context.name}/code/${context.projectPath}`)}`,\n 'mkdir -p \"$root/shared\"',\n 'if [ ! -L \"$root/code\" ]; then mkdir -p \"$project\"; fi',\n 'if [ -f \"$root/shared/.env\" ]; then chmod 600 \"$root/shared/.env\"; fi',\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 defaultStandbyPort(port: number): number {\n return port + 10 <= 65_535 ? port + 10 : port - 10\n}\n\nfunction assertDistinctPorts(\n primary: Readonly<Record<DeployHttpServiceName, number>>,\n standby: Readonly<Record<DeployHttpServiceName, number>>\n): void {\n const entries: readonly [string, number][] = [\n [\"ports.app\", primary.app],\n [\"ports.api\", primary.api],\n [\"standbyPorts.app\", standby.app],\n [\"standbyPorts.api\", standby.api],\n ]\n const seen = new Map<number, string>()\n for (const [label, port] of entries) {\n const previous = seen.get(port)\n if (previous) {\n throw new Error(\n `[SshTarget] ${label} (${port}) conflicts with ${previous}. Give each HTTP service and slot its own port.`\n )\n }\n seen.set(port, label)\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(\n value: unknown,\n field: \"ports\" | \"standbyPorts\"\n): Partial<Record<DeployHttpServiceName, number>> {\n if (value === undefined) return {}\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`[SshTarget] ${field} 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(\n `[SshTarget] ${field}.${service} is not an HTTP service. Available: api, app.`\n )\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] ${field}.${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
|
-
"
|
|
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 sharedEnv = posix.join(input.name, \"shared\", \".env\")\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 `shared_env=\"$HOME\"/${shellQuote(sharedEnv)}`,\n `manifest=\"$HOME\"/${shellQuote(input.name)}/deploy/processes.json`,\n `ports_file=\"$HOME\"/${shellQuote(input.name)}/deploy/ports.txt`,\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 // The routes keep WebSockets open through a reload with `stream_close_delay`, new in Caddy 2.7.\n \"if command -v caddy > /dev/null; then\",\n ' caddy_version=\"$(caddy version 2>/dev/null | cut -d\" \" -f1 | sed \"s/^v//\")\"',\n ' if [ \"$(printf \"%s\\\\n\" 2.7.0 \"$caddy_version\" | sort -V | head -n 1)\" = 2.7.0 ]; then emit server.caddy ok \"$caddy_version\"',\n ' else emit server.caddy manual \"$caddy_version is older than 2.7\"; fi',\n \"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 'env_file=\"$project/.env\"',\n 'if [ -f \"$shared_env\" ]; then env_file=\"$shared_env\"; fi',\n 'if [ ! -f \"$env_file\" ]; then emit project.env manual \"$env_file does not exist\"',\n 'elif [ \"$(stat -c %a \"$env_file\")\" != 600 ]; then emit project.env fixable \"$env_file is readable by others (mode $(stat -c %a \"$env_file\"))\"',\n 'else emit project.env ok \"$env_file\"; fi',\n ]),\n \"\",\n ...input.ports.flatMap(({ service, port }) => [\n `if ss -ltnH \"sport = :${port}\" 2> /dev/null | grep -q .; then`,\n ` if grep -qx '${port}' \"$ports_file\" 2> /dev/null || { 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 `elif grep -lxs '${port}' \"$HOME\"/*/deploy/ports.txt 2> /dev/null | grep -qv \"^$ports_file$\"; then`,\n ` emit project.port.${service} manual \"${port} is reserved by 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.caddy\": \"Caddy version\",\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 =\n LABELS[id] ?? (id.startsWith(\"project.port.\") ? `${id.slice(13).replace(/-/g, \" \")} 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 {\n ...check,\n remedy: \"Give this service another port in the target's `ports` or `standbyPorts`.\",\n }\n }\n if (id === \"server.caddy\") {\n return {\n ...check,\n remedy:\n \"Upgrade Caddy from its own apt repository: https://caddyserver.com/docs/install#debian-ubuntu-raspbian\",\n }\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 *
|
|
11
|
-
"
|
|
12
|
-
"import {
|
|
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",
|
|
13
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",
|
|
14
|
-
"import { type ChildProcess, spawn } from \"node:child_process\"\nimport type { WriteStream } from \"node:fs\"\nimport { mkdir, readdir, readFile, rm } from \"node:fs/promises\"\nimport { resolve } from \"node:path\"\nimport type { Readable } from \"node:stream\"\nimport type { DeploySlot } from \"../layout\"\nimport { openProcessLog, processLogPath, rotateLogIfLarge } from \"./logs\"\nimport {\n controlDir,\n isOverlapSafeService,\n loadProcessManifest,\n type ProcessManifest,\n type ProcessServiceManifest,\n responseDir,\n statePath,\n} from \"./manifest\"\nimport {\n isMissing,\n isPidRunning,\n type ProcessInstanceState,\n type ProcessInstanceStatus,\n type ProcessState,\n readProcessState,\n writeFileAtomically,\n writeProcessState,\n} from \"./state\"\n\nexport type SupervisorCommand = \"restart\" | \"start\" | \"stop\" | \"stage\" | \"activate\" | \"discard\"\n\nconst LINUX_CLOCK_TICKS_PER_SECOND = 100\n/** How often memory, CPU, and log sizes are checked. */\nconst SAMPLE_INTERVAL_MS = 5_000\nconst MAX_RESTART_DELAY_MS = 30_000\n/** How long old `api` and `workers` may drain in the background after a blue-green cutover. */\nconst RETIRING_KILL_TIMEOUT_MS = 300_000\n/** SIGINT comes this long before SIGKILL, so a draining role can still record its partial work. */\nexport const INTERRUPT_LEAD_MS = 10_000\n\n/** A retiring process gets the cutover's drain window, or its own kill timeout when longer. */\nexport function retiringKillTimeoutMs(killTimeoutMs: number): number {\n return Math.max(killTimeoutMs, RETIRING_KILL_TIMEOUT_MS)\n}\n\ninterface SupervisorRequest {\n readonly id: string\n readonly type: SupervisorCommand\n readonly service?: string\n readonly manifestPath?: string\n}\n\ninterface SupervisorResponse {\n readonly id: string\n readonly ok: boolean\n readonly message?: string\n}\n\ntype InstanceCohort = \"active\" | \"staged\" | \"retiring\"\n\ninterface ManagedInstance {\n readonly key: string\n readonly cwd: string\n readonly slot?: DeploySlot\n readonly service: ProcessServiceManifest\n readonly instance: number\n readonly child: ChildProcess\n readonly logPath: string\n cohort: InstanceCohort\n log: WriteStream\n startedAt: string\n stoppedAt?: string\n status: ProcessInstanceStatus\n restarts: number\n stopping: boolean\n exited: boolean\n /** Whether the child's output streams have ended. */\n closed: boolean\n cpuPercent?: number\n cpuSample?: CpuSample\n memoryBytes?: number\n restartTimer?: ReturnType<typeof setTimeout>\n cancelRetire?: () => void\n lastExitCode?: number | null\n lastSignal?: NodeJS.Signals | null\n lastError?: string\n}\n\ninterface CpuSample {\n readonly processSeconds: number\n readonly sampledAtMs: number\n}\n\n/**\n * Runs every process a deployment's manifest lists, restarting any that exit, and answers\n * control requests. One per deployment, started by the deployment's `systemd --user` unit.\n *\n * Requests arrive as files in `run/control` followed by `SIGUSR2`, so a caller needs nothing but\n * the file system and the supervisor's pid from `run/state.json`. The supervisor answers in\n * `run/responses`.\n */\nexport async function runSupervisor(manifestPath: string): Promise<void> {\n const supervisor = new Supervisor(manifestPath, await loadProcessManifest(manifestPath))\n await supervisor.run()\n}\n\n/** Asks the running supervisor to control services or cut over a staged release. */\nexport async function sendSupervisorCommand(\n manifest: ProcessManifest,\n type: SupervisorCommand,\n options: {\n readonly service?: string\n readonly manifestPath?: string\n readonly timeoutMs?: number\n } = {}\n): Promise<string> {\n const state = await readProcessState(statePath(manifest))\n if (!state || !isPidRunning(state.supervisorPid)) {\n throw new Error(\"[SshTarget] The deployment's supervisor is not running.\")\n }\n\n const id = `${Date.now()}-${process.pid}-${Math.random().toString(16).slice(2)}`\n await mkdir(controlDir(manifest), { recursive: true })\n await writeFileAtomically(\n resolve(controlDir(manifest), `${id}.json`),\n `${JSON.stringify({\n id,\n type,\n ...(options.service ? { service: options.service } : {}),\n ...(options.manifestPath ? { manifestPath: options.manifestPath } : {}),\n })}\\n`\n )\n process.kill(state.supervisorPid, \"SIGUSR2\")\n\n const response = await waitForResponse(\n resolve(responseDir(manifest), `${id}.json`),\n options.timeoutMs ?? 90_000\n )\n if (!response.ok) throw new Error(response.message ?? \"[SshTarget] The supervisor refused.\")\n return response.message ?? type\n}\n\nclass Supervisor {\n private manifest: ProcessManifest\n private candidate: ProcessManifest | null = null\n private readonly managed = new Map<string, ManagedInstance>()\n private readonly staged = new Map<string, ManagedInstance>()\n private readonly retiring = new Set<ManagedInstance>()\n private readonly restartCounts = new Map<string, number>()\n private readonly stagedRestartCounts = new Map<string, number>()\n private shuttingDown = false\n private sampleTimer: ReturnType<typeof setInterval> | null = null\n private resolveStopped: (() => void) | null = null\n private stateWrites: Promise<void> = Promise.resolve()\n\n constructor(\n private readonly manifestPath: string,\n manifest: ProcessManifest\n ) {\n this.manifest = manifest\n }\n\n async run(): Promise<void> {\n await mkdir(this.manifest.logDir, { recursive: true })\n await mkdir(controlDir(this.manifest), { recursive: true })\n await mkdir(responseDir(this.manifest), { recursive: true })\n process.once(\"SIGINT\", () => void this.shutdown())\n process.once(\"SIGTERM\", () => void this.shutdown())\n process.on(\"SIGUSR2\", () => void this.handleControlRequests())\n\n for (const desired of desiredInstances(this.manifest)) {\n await this.startInstance(this.manifest, desired.service, desired.instance, \"active\")\n }\n // Requests written while the supervisor was starting would otherwise wait for a signal.\n await this.handleControlRequests()\n this.sampleTimer = setInterval(() => void this.sample(), SAMPLE_INTERVAL_MS)\n\n await new Promise<void>((resolveStopped) => {\n this.resolveStopped = resolveStopped\n })\n }\n\n private async startInstance(\n manifest: ProcessManifest,\n service: ProcessServiceManifest,\n instance: number,\n cohort: \"active\" | \"staged\"\n ): Promise<void> {\n const key = instanceKey(service.processName, instance)\n const logPath = processLogPath(manifest, service.processName, instance)\n const log = await openProcessLog(logPath)\n // A restart already under way when shutdown began must not leave a process behind.\n if (this.shuttingDown) {\n log.end()\n return\n }\n const counts = cohort === \"active\" ? this.restartCounts : this.stagedRestartCounts\n const targetMap = cohort === \"active\" ? this.managed : this.staged\n const child = spawn(service.command, [...service.args], {\n cwd: manifest.cwd,\n env: { ...process.env, ...service.env },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n const managed: ManagedInstance = {\n key,\n cwd: manifest.cwd,\n ...(manifest.slot ? { slot: manifest.slot } : {}),\n service,\n instance,\n cohort,\n child,\n log,\n logPath,\n startedAt: new Date().toISOString(),\n status: \"running\",\n restarts: counts.get(key) ?? 0,\n stopping: false,\n exited: false,\n closed: false,\n }\n\n targetMap.set(key, managed)\n log.write(\n `[${managed.startedAt}] start ${service.processName}#${instance} pid=${child.pid ?? \"unknown\"}\\n`\n )\n this.pipeOutput(managed, child.stdout, \"stdout\")\n this.pipeOutput(managed, child.stderr, \"stderr\")\n child.on(\"error\", (error) => {\n managed.lastError = error.message\n managed.status = \"exited\"\n void this.writeState()\n })\n // Lifecycle follows `exit`: Bun does not always emit `close` for a child killed right after\n // it started. `close` only decides when the log may end; see `endLog`.\n child.once(\"close\", () => {\n managed.closed = true\n })\n child.on(\"exit\", (code, signal) => void this.handleExit(managed, code, signal))\n\n await this.writeState()\n }\n\n private async handleExit(\n managed: ManagedInstance,\n code: number | null,\n signal: NodeJS.Signals | null\n ): Promise<void> {\n managed.exited = true\n managed.lastExitCode = code\n managed.lastSignal = signal\n managed.stoppedAt = new Date().toISOString()\n managed.status = managed.stopping ? \"stopped\" : \"exited\"\n managed.log.write(\n `[${managed.stoppedAt}] exit code=${code ?? \"null\"} signal=${signal ?? \"null\"}\\n`\n )\n void endLog(managed)\n\n if (managed.cohort === \"retiring\") {\n this.retiring.delete(managed)\n await this.writeState()\n return\n }\n\n const cohort = managed.cohort\n const ownerMap = cohort === \"active\" ? this.managed : this.staged\n const counts = cohort === \"active\" ? this.restartCounts : this.stagedRestartCounts\n\n if (this.shuttingDown || managed.stopping) {\n if (ownerMap.get(managed.key) === managed) ownerMap.delete(managed.key)\n await this.writeState()\n return\n }\n\n // Back off a process that keeps exiting: each restart waits one delay longer, up to 30s.\n const restarts = (counts.get(managed.key) ?? 0) + 1\n counts.set(managed.key, restarts)\n managed.restarts = restarts\n const delay = Math.min(managed.service.restartDelayMs * restarts, MAX_RESTART_DELAY_MS)\n managed.restartTimer = setTimeout(() => {\n // Read where the instance belongs now: `activate` can make a waiting candidate active.\n const cohortNow = managed.cohort\n if (cohortNow === \"retiring\") return\n\n const ownerNow = cohortNow === \"active\" ? this.managed : this.staged\n if (ownerNow.get(managed.key) !== managed) return\n ownerNow.delete(managed.key)\n\n const currentManifest = cohortNow === \"active\" ? this.manifest : this.candidate\n if (!currentManifest || currentManifest.cwd !== managed.cwd) return\n void this.startInstance(currentManifest, managed.service, managed.instance, cohortNow)\n }, delay)\n await this.writeState()\n }\n\n private async stopManaged(\n managed: ManagedInstance,\n timeoutMs = managed.service.killTimeoutMs\n ): Promise<void> {\n if (managed.restartTimer) clearTimeout(managed.restartTimer)\n managed.cancelRetire?.()\n managed.cancelRetire = undefined\n managed.stopping = true\n\n const removeFromOwner = () => {\n if (this.managed.get(managed.key) === managed) this.managed.delete(managed.key)\n if (this.staged.get(managed.key) === managed) this.staged.delete(managed.key)\n this.retiring.delete(managed)\n }\n\n // Tracked here rather than read from `child.exitCode`, which Bun does not always set.\n if (managed.exited) {\n removeFromOwner()\n await this.writeState()\n return\n }\n\n managed.status = \"stopping\"\n await this.writeState()\n await new Promise<void>((resolveStop) => {\n // The child can exit during the state write above, and its `exit` has then already fired.\n // systemd signals every process in the unit at once, so a deploy's stop often lands here.\n if (managed.exited) {\n resolveStop()\n return\n }\n // Give draining roles 10s before SIGKILL to escalate via SIGINT and record partial work.\n const interruptTimer =\n timeoutMs > 15_000\n ? setTimeout(() => {\n if (!managed.exited) managed.child.kill(\"SIGINT\")\n }, timeoutMs - INTERRUPT_LEAD_MS)\n : undefined\n const killTimer = setTimeout(() => {\n if (!managed.exited) managed.child.kill(\"SIGKILL\")\n }, timeoutMs)\n // A child killed as it started may never report its exit; stopping must still finish.\n const giveUp = setTimeout(done, timeoutMs + 2_000)\n function done() {\n if (interruptTimer) clearTimeout(interruptTimer)\n clearTimeout(killTimer)\n clearTimeout(giveUp)\n resolveStop()\n }\n managed.child.once(\"exit\", done)\n managed.child.kill(\"SIGTERM\")\n })\n removeFromOwner()\n // The exit listener queues its state write asynchronously. Publish the final state before\n // the control request can acknowledge the stop, including when the exit event never arrives.\n await this.writeState()\n }\n\n private retireManaged(managed: ManagedInstance): void {\n if (managed.restartTimer) clearTimeout(managed.restartTimer)\n managed.cohort = \"retiring\"\n managed.stopping = true\n managed.status = \"stopping\"\n\n if (managed.exited) {\n this.retiring.delete(managed)\n return\n }\n\n this.retiring.add(managed)\n const timeoutMs = retiringKillTimeoutMs(managed.service.killTimeoutMs)\n const interruptTimer = setTimeout(\n () => {\n if (!managed.exited) managed.child.kill(\"SIGINT\")\n },\n Math.max(timeoutMs - INTERRUPT_LEAD_MS, 1_000)\n )\n const killTimer = setTimeout(() => {\n if (!managed.exited) managed.child.kill(\"SIGKILL\")\n }, timeoutMs)\n const giveUp = setTimeout(() => {\n cleanup()\n this.retiring.delete(managed)\n void this.writeState()\n }, timeoutMs + 2_000)\n\n const cleanup = () => {\n clearTimeout(interruptTimer)\n clearTimeout(killTimer)\n clearTimeout(giveUp)\n managed.cancelRetire = undefined\n }\n managed.cancelRetire = cleanup\n managed.child.once(\"exit\", cleanup)\n managed.child.kill(\"SIGTERM\")\n }\n\n private async handleControlRequests(): Promise<void> {\n let entries: string[]\n try {\n entries = await readdir(controlDir(this.manifest))\n } catch (error) {\n if (isMissing(error)) return\n throw error\n }\n\n for (const entry of entries.filter((name) => name.endsWith(\".json\"))) {\n const path = resolve(controlDir(this.manifest), entry)\n\n // The id is read first: a request this supervisor cannot run, such as a command newer than\n // it, still gets an answer, so its client fails at once instead of waiting out its timeout.\n let id: string | null = null\n try {\n const body: unknown = JSON.parse(await readFile(path, \"utf8\"))\n id = requestId(body)\n\n const request = parseRequest(body)\n await rm(path, { force: true })\n await this.writeResponse(request.id, true, await this.handleRequest(request))\n } catch (error) {\n await rm(path, { force: true })\n if (id) await this.writeResponse(id, false, errorMessage(error))\n }\n }\n }\n\n private async handleRequest(request: SupervisorRequest): Promise<string> {\n if (request.type === \"stage\") {\n if (!request.manifestPath) {\n throw new Error(\"[SshTarget] stage requires a candidate manifest path.\")\n }\n return this.stageCandidate(await loadProcessManifest(request.manifestPath))\n }\n if (request.type === \"discard\") {\n await this.discardStaged()\n return \"discarded candidate\"\n }\n if (request.type === \"activate\") {\n return this.activateCandidate()\n }\n\n const services = this.manifest.services.filter(\n (service) => !request.service || service.name === request.service\n )\n if (services.length === 0) {\n throw new Error(\n `[SshTarget] No service named '${request.service}'. ` +\n `Services: ${this.manifest.services.map((service) => service.name).join(\", \")}.`\n )\n }\n const names = new Set(services.map((service) => service.name))\n const running = [...this.managed.values()].filter((managed) => names.has(managed.service.name))\n\n if (request.type !== \"start\") {\n for (const managed of running) await this.stopManaged(managed)\n }\n if (request.type !== \"stop\") {\n for (const desired of desiredInstances(this.manifest)) {\n if (!names.has(desired.service.name) || this.managed.has(desired.key)) continue\n this.restartCounts.delete(desired.key)\n await this.startInstance(this.manifest, desired.service, desired.instance, \"active\")\n }\n }\n return `${request.type === \"stop\" ? \"stopped\" : `${request.type}ed`} ${[...names].join(\", \")}`\n }\n\n private async stageCandidate(candidate: ProcessManifest): Promise<string> {\n await this.discardStaged()\n\n // Ensure no retiring HTTP server still holds the candidate slot's loopback ports.\n const sameSlotHttp = [...this.retiring].filter(\n (managed) =>\n managed.service.kind === \"http\" &&\n (candidate.slot === undefined || managed.slot === candidate.slot)\n )\n if (sameSlotHttp.length > 0) {\n await Promise.all(sameSlotHttp.map((managed) => this.stopManaged(managed, 5_000)))\n }\n\n this.candidate = candidate\n this.stagedRestartCounts.clear()\n const started: string[] = []\n for (const desired of desiredInstances(candidate)) {\n if (!isOverlapSafeService(desired.service)) continue\n await this.startInstance(candidate, desired.service, desired.instance, \"staged\")\n if (!started.includes(desired.service.name)) started.push(desired.service.name)\n }\n await this.writeState()\n return `staged ${started.join(\", \") || \"candidate\"}`\n }\n\n private async discardStaged(): Promise<void> {\n const staged = [...this.staged.values()]\n this.candidate = null\n this.stagedRestartCounts.clear()\n if (staged.length > 0) {\n await Promise.all(staged.map((managed) => this.stopManaged(managed)))\n }\n await this.writeState()\n }\n\n private async activateCandidate(): Promise<string> {\n const nextManifest = this.candidate ?? (await loadProcessManifest(this.manifestPath))\n const activeInstances = [...this.managed.values()]\n const exclusiveOld = activeInstances.filter((managed) => !isOverlapSafeService(managed.service))\n const overlapOld = activeInstances.filter((managed) => isOverlapSafeService(managed.service))\n\n // Stop singletons and custom scripts before starting the new release's copies.\n if (exclusiveOld.length > 0) {\n await Promise.all(exclusiveOld.map((managed) => this.stopManaged(managed)))\n }\n\n // Drain old HTTP and worker instances in the background while green serves traffic.\n for (const managed of overlapOld) {\n this.managed.delete(managed.key)\n this.retireManaged(managed)\n }\n\n this.manifest = nextManifest\n this.candidate = null\n this.restartCounts.clear()\n for (const [key, count] of this.stagedRestartCounts) {\n this.restartCounts.set(key, count)\n }\n this.stagedRestartCounts.clear()\n\n for (const [key, staged] of this.staged) {\n staged.cohort = \"active\"\n this.managed.set(key, staged)\n }\n this.staged.clear()\n\n for (const desired of desiredInstances(nextManifest)) {\n if (this.managed.has(desired.key)) continue\n await this.startInstance(nextManifest, desired.service, desired.instance, \"active\")\n }\n\n await this.writeState()\n return `activated ${nextManifest.services.map((service) => service.name).join(\", \")}`\n }\n\n private async writeResponse(id: string, ok: boolean, message: string): Promise<void> {\n await mkdir(responseDir(this.manifest), { recursive: true })\n await writeFileAtomically(\n resolve(responseDir(this.manifest), `${id}.json`),\n `${JSON.stringify({ id, ok, message } satisfies SupervisorResponse)}\\n`\n )\n }\n\n private async sample(): Promise<void> {\n for (const managed of [...this.managed.values()]) {\n const pid = managed.child.pid\n if (!pid || managed.status !== \"running\") continue\n await this.rotateLog(managed)\n const cpuSample = await readLinuxCpuSample(pid)\n if (cpuSample) {\n managed.cpuPercent = cpuPercent(managed.cpuSample, cpuSample)\n managed.cpuSample = cpuSample\n }\n const memory = await readLinuxRssBytes(pid)\n if (!memory) continue\n managed.memoryBytes = memory\n\n const limit = managed.service.maxMemory ? parseMemoryLimit(managed.service.maxMemory) : null\n if (limit && memory > limit) {\n managed.lastError = `memory limit exceeded: ${formatBytes(memory)} > ${managed.service.maxMemory}`\n managed.log.write(`[${new Date().toISOString()}] ${managed.lastError}\\n`)\n await this.stopManaged(managed)\n this.restartCounts.set(managed.key, managed.restarts + 1)\n await this.startInstance(this.manifest, managed.service, managed.instance, \"active\")\n }\n }\n await this.writeState()\n }\n\n private async rotateLog(managed: ManagedInstance): Promise<void> {\n if (!(await rotateLogIfLarge(managed.logPath))) return\n const previous = managed.log\n managed.log = await openProcessLog(managed.logPath)\n previous.end()\n }\n\n private async shutdown(): Promise<void> {\n if (this.shuttingDown) return\n this.shuttingDown = true\n if (this.sampleTimer) clearInterval(this.sampleTimer)\n\n const all = [...this.managed.values(), ...this.staged.values(), ...this.retiring]\n await Promise.all(all.map((managed) => this.stopManaged(managed)))\n await this.writeState()\n this.resolveStopped?.()\n }\n\n /**\n * Queues a snapshot write. Writes run one at a time, each taking its snapshot when it starts,\n * and a failed one is reported rather than stopping the processes it describes.\n */\n private writeState(): Promise<void> {\n this.stateWrites = this.stateWrites\n .then(() => writeProcessState(statePath(this.manifest), this.snapshotState()))\n .catch((error) => console.error(`[SshTarget] Could not write state: ${errorMessage(error)}`))\n return this.stateWrites\n }\n\n private snapshotState(): ProcessState {\n const staged = this.candidate\n ? desiredInstances(this.candidate)\n .filter((desired) => isOverlapSafeService(desired.service))\n .map((desired) =>\n snapshotDesired(this.candidate!, desired, this.staged, this.stagedRestartCounts)\n )\n : undefined\n const retiringCwds = [...new Set([...this.retiring].map((managed) => managed.cwd))]\n\n return {\n version: 1,\n name: this.manifest.name,\n supervisorPid: process.pid,\n updatedAt: new Date().toISOString(),\n ...(this.manifest.slot ? { slot: this.manifest.slot } : {}),\n instances: desiredInstances(this.manifest).map((desired) =>\n snapshotDesired(this.manifest, desired, this.managed, this.restartCounts)\n ),\n ...(staged ? { staged } : {}),\n ...(retiringCwds.length > 0 ? { retiringCwds } : {}),\n }\n }\n\n private pipeOutput(\n managed: ManagedInstance,\n stream: Readable | null,\n streamName: \"stdout\" | \"stderr\"\n ): void {\n if (!stream) return\n let buffer = \"\"\n const write = (line: string) => {\n if (managed.log.writableEnded) return\n managed.log.write(`[${new Date().toISOString()}] [${streamName}] ${line}\\n`)\n }\n\n stream.setEncoding(\"utf8\")\n stream.on(\"data\", (chunk: string) => {\n buffer += chunk\n const lines = buffer.split(/\\r?\\n|\\r/)\n buffer = lines.pop() ?? \"\"\n for (const line of lines) write(line)\n })\n stream.on(\"end\", () => {\n if (buffer) write(buffer)\n buffer = \"\"\n })\n }\n}\n\nfunction desiredInstances(manifest: ProcessManifest): {\n readonly key: string\n readonly service: ProcessServiceManifest\n readonly instance: number\n}[] {\n return manifest.services.flatMap((service) =>\n Array.from({ length: service.instances }, (_, instance) => ({\n key: instanceKey(service.processName, instance),\n service,\n instance,\n }))\n )\n}\n\nfunction snapshotDesired(\n manifest: ProcessManifest,\n desired: {\n readonly key: string\n readonly service: ProcessServiceManifest\n readonly instance: number\n },\n instances: ReadonlyMap<string, ManagedInstance>,\n restarts: ReadonlyMap<string, number>\n): ProcessInstanceState {\n const managed = instances.get(desired.key)\n if (managed) return snapshot(managed)\n return {\n service: desired.service.name,\n processName: desired.service.processName,\n instance: desired.instance,\n status: \"stopped\",\n restarts: restarts.get(desired.key) ?? 0,\n logPath: processLogPath(manifest, desired.service.processName, desired.instance),\n }\n}\n\n/** Ends a log once the child's output has drained, or two seconds after it exited. */\nasync function endLog(managed: ManagedInstance): Promise<void> {\n for (let waited = 0; !managed.closed && waited < 2_000; waited += 50) {\n await new Promise<void>((resolveWait) => setTimeout(resolveWait, 50))\n }\n managed.log.end()\n}\n\nfunction snapshot(managed: ManagedInstance): ProcessInstanceState {\n return {\n service: managed.service.name,\n processName: managed.service.processName,\n instance: managed.instance,\n ...(managed.child.pid ? { pid: managed.child.pid } : {}),\n status: managed.status,\n startedAt: managed.startedAt,\n ...(managed.stoppedAt ? { stoppedAt: managed.stoppedAt } : {}),\n restarts: managed.restarts,\n ...(managed.cpuPercent === undefined ? {} : { cpuPercent: managed.cpuPercent }),\n ...(managed.memoryBytes ? { memoryBytes: managed.memoryBytes } : {}),\n ...(managed.lastExitCode === undefined ? {} : { lastExitCode: managed.lastExitCode }),\n ...(managed.lastSignal === undefined ? {} : { lastSignal: managed.lastSignal }),\n ...(managed.lastError ? { lastError: managed.lastError } : {}),\n logPath: managed.logPath,\n }\n}\n\nasync function waitForResponse(path: string, timeoutMs: number): Promise<SupervisorResponse> {\n const started = Date.now()\n while (Date.now() - started < timeoutMs) {\n try {\n const response = JSON.parse(await readFile(path, \"utf8\")) as SupervisorResponse\n await rm(path, { force: true })\n return response\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n await new Promise<void>((resolveWait) => setTimeout(resolveWait, 100))\n }\n throw new Error(\"[SshTarget] Timed out waiting for the supervisor to answer.\")\n}\n\nconst VALID_COMMANDS: readonly SupervisorCommand[] = [\n \"restart\",\n \"start\",\n \"stop\",\n \"stage\",\n \"activate\",\n \"discard\",\n]\n\nfunction requestId(value: unknown): string | null {\n const id = (value as { readonly id?: unknown } | null)?.id\n return typeof id === \"string\" ? id : null\n}\n\nfunction parseRequest(value: unknown): SupervisorRequest {\n const request = value as Partial<SupervisorRequest> | null\n if (!request || typeof request.id !== \"string\") {\n throw new Error(\"[SshTarget] Invalid supervisor request.\")\n }\n\n if (!VALID_COMMANDS.includes(request.type as SupervisorCommand)) {\n throw new Error(\n `[SshTarget] This supervisor does not know the \"${String(request.type)}\" command: it is ` +\n \"older than the deploy that sent it. Restarting the deployment starts the new one.\"\n )\n }\n return {\n id: request.id,\n type: request.type as SupervisorCommand,\n ...(typeof request.service === \"string\" ? { service: request.service } : {}),\n ...(typeof request.manifestPath === \"string\" ? { manifestPath: request.manifestPath } : {}),\n }\n}\n\nfunction instanceKey(processName: string, instance: number): string {\n return `${processName}:${instance}`\n}\n\nexport function parseMemoryLimit(value: string): number | null {\n const match = value.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*(b|k|kb|m|mb|g|gb)?$/i)\n if (!match) return null\n const unit = (match[2] ?? \"b\").toLowerCase()[0]\n const multiplier = unit === \"g\" ? 1024 ** 3 : unit === \"m\" ? 1024 ** 2 : unit === \"k\" ? 1024 : 1\n return Math.round(Number(match[1]) * multiplier)\n}\n\nasync function readLinuxRssBytes(pid: number): Promise<number | null> {\n try {\n const rssPages = Number((await readFile(`/proc/${pid}/statm`, \"utf8\")).trim().split(/\\s+/)[1])\n return Number.isFinite(rssPages) ? rssPages * 4096 : null\n } catch {\n return null\n }\n}\n\nasync function readLinuxCpuSample(pid: number): Promise<CpuSample | null> {\n try {\n const stat = await readFile(`/proc/${pid}/stat`, \"utf8\")\n const end = stat.lastIndexOf(\") \")\n if (end === -1) return null\n const fields = stat\n .slice(end + 2)\n .trim()\n .split(/\\s+/)\n const ticks = Number(fields[11]) + Number(fields[12])\n if (!Number.isFinite(ticks)) return null\n return { processSeconds: ticks / LINUX_CLOCK_TICKS_PER_SECOND, sampledAtMs: Date.now() }\n } catch {\n return null\n }\n}\n\nfunction cpuPercent(previous: CpuSample | undefined, current: CpuSample): number | undefined {\n if (!previous) return undefined\n const processSeconds = current.processSeconds - previous.processSeconds\n const wallSeconds = (current.sampledAtMs - previous.sampledAtMs) / 1000\n if (processSeconds < 0 || wallSeconds <= 0) return undefined\n return Math.max(0, Math.round((processSeconds / wallSeconds) * 1000) / 10)\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)}G`\n if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)}M`\n if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)}K`\n return `${bytes}B`\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n",
|
|
15
|
-
"/**\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",
|
|
16
|
-
"import type { DeployHttpServiceName, DeployRelease, DeployReleaseService } from \"@sixb/core/deploy\"\nimport type { DeploymentLayout, DeploySlot } from \"./layout\"\nimport type { ProcessManifest } from \"./server/manifest\"\nimport { INTERRUPT_LEAD_MS, retiringKillTimeoutMs } from \"./server/supervisor\"\nimport { shellQuote } from \"./shell\"\nimport { renderUpdatePage } from \"./update-page\"\n\nconst GENERATED = \"Generated by sixb deploy. Changes are replaced on the next deploy.\"\n\nexport type SlotPorts = Readonly<\n Record<DeploySlot, Readonly<Record<DeployHttpServiceName, number>>>\n>\n\n/** Rewrites a release's HTTP services to listen on the given slot's loopback ports. */\nexport function releaseForSlot(\n release: DeployRelease,\n ports: Readonly<Record<DeployHttpServiceName, number>>\n): DeployRelease {\n return {\n ...release,\n services: release.services.map((service) => {\n if (!service.http || (service.name !== \"api\" && service.name !== \"app\")) {\n return service\n }\n const port = ports[service.name]\n return {\n ...service,\n command: {\n ...service.command,\n args: replacePortArg(service.command.args, port),\n },\n http: {\n ...service.http,\n port,\n },\n }\n }),\n }\n}\n\nfunction replacePortArg(args: readonly string[], port: number): string[] {\n const next = [...args]\n const index = next.indexOf(\"--port\")\n if (index !== -1 && index + 1 < next.length) {\n next[index + 1] = String(port)\n }\n return next\n}\n\n/** The supervisor's view of the release: absolute commands, full environments. */\nexport function renderProcessManifest(\n release: DeployRelease,\n layout: DeploymentLayout,\n options: { readonly projectDir?: string; readonly slot?: DeploySlot } = {}\n): ProcessManifest {\n const projectDir = options.projectDir ?? layout.project\n const sixb = `${projectDir}/node_modules/.bin/sixb`\n return {\n version: 1,\n name: release.name,\n ...(options.slot ? { slot: options.slot } : {}),\n cwd: projectDir,\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 kind: service.kind,\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: serviceEnvWithDrain(service),\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/**\n * A retiring `api` or `workers` drains until the supervisor's SIGINT, so it finishes its work on\n * its own rather than being cut short. The window follows the service's own kill timeout.\n */\nfunction serviceEnvWithDrain(service: DeployReleaseService): Record<string, string> {\n if (\n (service.name === \"api\" || service.name === \"workers\") &&\n service.env.SIXB_DRAIN_TIMEOUT_MS === undefined\n ) {\n const drainTimeoutMs = retiringKillTimeoutMs(service.process.killTimeoutMs) - INTERRUPT_LEAD_MS\n\n return {\n SIXB_DRAIN_TIMEOUT_MS: String(drainTimeoutMs),\n ...service.env,\n }\n }\n return { ...service.env }\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 active slot'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 \"\\t\\tlb_try_duration 5s\",\n ...(service.name === \"api\" ? keepWebSocketsThroughReload(service) : []),\n \"\\t}\",\n ...(pages ? updatePageOnProxyErrors() : []),\n \"}\",\n ].join(\"\\n\"),\n ]\n })\n return [`# ${GENERATED}`, \"\", sites.join(\"\\n\\n\"), \"\"].join(\"\\n\")\n}\n\n/**\n * A reload closes every WebSocket Caddy proxies unless it is told to wait, and each deploy reloads\n * Caddy before the old API retires. Kept open, a browser's socket stays on the retiring API, which\n * closes it with 1012 so the page reconnects without showing a drop. The wait covers the API's\n * whole retiring window; the API closes its sockets as soon as it starts draining.\n */\nfunction keepWebSocketsThroughReload(service: DeployReleaseService): string[] {\n const seconds = retiringKillTimeoutMs(service.process.killTimeoutMs) / 1000\n return [`\\t\\tstream_close_delay ${seconds}s`]\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 an outage — a browser asking for a page gets the update page\n * 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",
|
|
17
|
-
"import type {\n DeployCommand,\n DeployHttpServiceName,\n DeployRecord,\n DeployRelease,\n} from \"@sixb/core/deploy\"\nimport { type DeploymentLayout, type ReleaseLayout, releaseLayout } from \"./layout\"\nimport {\n releaseForSlot,\n renderCaddySnippet,\n renderCtl,\n renderProcessManifest,\n renderUnit,\n type SlotPorts,\n} 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 the release,\n // which 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 readonly releaseId?: string\n readonly slotPorts?: SlotPorts\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\nexport function defaultSlotPorts(release: DeployRelease): SlotPorts {\n const portOf = (name: DeployHttpServiceName, fallback: number): number =>\n release.services.find((service) => service.name === name)?.http?.port ?? fallback\n const blueApp = portOf(\"app\", 3001)\n const blueApi = portOf(\"api\", 3002)\n return {\n blue: { app: blueApp, api: blueApi },\n green: {\n app: blueApp + 10 <= 65535 ? blueApp + 10 : blueApp - 10,\n api: blueApi + 10 <= 65535 ? blueApi + 10 : blueApi - 10,\n },\n }\n}\n\nexport function deriveReleaseId(record: DeployRecord): string {\n const stamp = record.deployedAt.replace(/[-:.]/g, \"\").slice(0, 15)\n const sha = record.commit.slice(0, 12).replace(/[^a-zA-Z0-9_-]/g, \"\")\n return `${stamp}Z-${sha || \"release\"}`\n}\n\n/**\n * Everything the server does once the source is uploaded, as one script that holds the\n * deployment's lock throughout. Every build, migration, provider check, and readiness check runs\n * against the new release directory before routes flip or the previous release retires.\n */\nexport function renderDeployScript(input: DeployScriptInput): DeployScript {\n const { release, layout } = input\n const releaseId = input.releaseId ?? deriveReleaseId(input.record)\n const targetRelease = releaseLayout(layout, releaseId)\n const slots = input.slotPorts ?? defaultSlotPorts(release)\n const blueRelease = releaseForSlot(release, slots.blue)\n const greenRelease = releaseForSlot(release, slots.green)\n\n const readinessUrl = (candidate: DeployRelease): string | null => {\n const api = candidate.services.find((service) => service.http?.readinessPath)\n return api?.http ? `http://${api.http.host}:${api.http.port}${api.http.readinessPath}` : null\n }\n\n const steps: Step[] = [\n {\n label: \"Prepare release\",\n body: renderPrepareRelease(layout, targetRelease, input.incoming),\n },\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, index, all) =>\n index === all.length - 1 ? withCarriedAssets(runStep(command)) : runStep(command)\n ),\n ...release.steps.beforeStart.flatMap((command) =>\n isStorageMigration(command) ? [stopForSchemaChange(), runStep(command)] : [runStep(command)]\n ),\n {\n label: \"Start new release\",\n body: renderStartCandidate({\n layout,\n targetRelease,\n blueRelease,\n greenRelease,\n slots,\n }),\n },\n {\n label: \"Check services\",\n body: renderCheckServices({\n blueReadyUrl: readinessUrl(blueRelease),\n greenReadyUrl: readinessUrl(greenRelease),\n }),\n },\n {\n label: \"Update routes\",\n body: renderUpdateRoutes({\n layout,\n blueCaddy: renderCaddySnippet(blueRelease),\n greenCaddy: renderCaddySnippet(greenRelease),\n }),\n },\n {\n label: \"Activate release\",\n body: renderActivateRelease({ release: blueRelease, layout, slots }),\n },\n ]\n\n const script = [\n \"set -euo pipefail\",\n \"main() {\",\n renderEnvironment(release, layout, targetRelease),\n renderTakeLock(layout),\n renderUseRelease(layout, input.record),\n renderRestoreRoutes(),\n renderCandidateTrap(),\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(\n release: DeployRelease,\n layout: DeploymentLayout,\n targetRelease: ReleaseLayout\n): string {\n const variables: Record<string, string> = {\n ROOT: layout.root,\n RELEASES_DIR: layout.releasesDir,\n CURRENT: layout.currentLink,\n CODE: layout.code,\n PROJECT: layout.project,\n SHARED_DIR: layout.sharedDir,\n SHARED_ENV: layout.sharedEnv,\n RELEASE_ID: targetRelease.id,\n RELEASE_ROOT: targetRelease.root,\n RELEASE_PROJECT: targetRelease.project,\n DEPLOY: layout.deployDir,\n MANIFEST: layout.manifest,\n CANDIDATE_MANIFEST: layout.candidateManifest,\n STATE_FILE: `${layout.runDir}/state.json`,\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 PREVIOUS_ROUTES: `${layout.deployDir}/Caddyfile.previous`,\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 'deploy_mode=\"none\"',\n 'target_slot=\"blue\"',\n 'prev_release=\"\"',\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 * Points `current` at the new release and records it in `release.json` at the same moment, so\n * `sixb deploy status` names the commit that serves from then on, even when a later check fails.\n * Callers set `deploy_mode` right after it, with nothing in between that can fail.\n */\nfunction renderUseRelease(layout: DeploymentLayout, record: DeployRecord): string {\n return [\n \"use_release() {\",\n ' ln -sfn \"releases/$RELEASE_ID\" \"$CURRENT\"',\n ' ln -sfn \"current\" \"$CODE\"',\n ` ${writeFileCommand(layout.releaseRecord, `${JSON.stringify(record)}\\n`)}`,\n \"}\",\n ].join(\"\\n\")\n}\n\n/** Puts back the routes \"Update routes\" replaced: the live release's, or none on a first deploy. */\nfunction renderRestoreRoutes(): string {\n return [\n \"restore_routes() {\",\n ' if [ -f \"$PREVIOUS_ROUTES\" ]; then cp \"$PREVIOUS_ROUTES\" \"$CADDY_SNIPPET\"; else rm -f \"$CADDY_SNIPPET\"; fi',\n \"}\",\n ].join(\"\\n\")\n}\n\n/**\n * A failure before the switch discards the candidate, and the live release keeps serving. When\n * Caddy already routes to the candidate, its routes go back to the live release first. After the\n * switch there is nothing to discard: the new release serves, and the operator is told so.\n */\nfunction renderCandidateTrap(): string {\n return [\n \"cleanup_candidate() {\",\n \" status=$?\",\n ' if [ \"$status\" -eq 0 ]; then return; fi',\n \"\",\n ' case \"$deploy_mode\" in',\n \" staged | routed)\",\n ' if [ \"$deploy_mode\" = \"routed\" ]; then',\n \" restore_routes || true\",\n \" if sudo -n /usr/bin/systemctl reload caddy > /dev/null 2>&1; then\",\n \" echo 'The routes are back on the live release.' >&2\",\n \" else\",\n \" echo 'Caddy did not reload the previous routes: run sudo systemctl reload caddy on the server.' >&2\",\n \" fi\",\n \" fi\",\n ' \"$BUN\" \"$RELEASE_PROJECT/node_modules/.bin/sixb-deploy-ssh\" discard --manifest \"$MANIFEST\" > /dev/null 2>&1 || true',\n ' rm -f \"$CANDIDATE_MANIFEST\" \"$DEPLOY/manifest.blue.json\" \"$DEPLOY/manifest.green.json\"',\n \" ;;\",\n \" stopped)\",\n \" echo 'The services were stopped for the storage migration and stay stopped. Fix what failed and deploy again.' >&2\",\n \" ;;\",\n \" activated | cold)\",\n \" echo 'The new release is in place, but it did not pass its checks.' >&2\",\n \" echo 'sixb deploy status and sixb deploy logs show what failed. To go back, deploy the previous commit with --ref.' >&2\",\n \" ;;\",\n \" esac\",\n \"}\",\n \"trap cleanup_candidate EXIT\",\n ].join(\"\\n\")\n}\n\n/**\n * Unpacks the upload into an immutable `releases/<id>` directory, migrating an in-place `code/`\n * directory on upgrade. The release's `.env` links to the server's `shared/.env`, so an edit to\n * that one file reaches the services on their next restart, and a committed `.env` never\n * replaces it.\n */\nexport function renderPrepareRelease(\n layout: DeploymentLayout,\n targetRelease: ReleaseLayout,\n incoming: string\n): string {\n return [\n `incoming=${shellQuote(incoming)}`,\n `releases_dir=${shellQuote(layout.releasesDir)}`,\n `current=${shellQuote(layout.currentLink)}`,\n `code=${shellQuote(layout.code)}`,\n `project=${shellQuote(layout.project)}`,\n `shared_dir=${shellQuote(layout.sharedDir)}`,\n `shared_env=${shellQuote(layout.sharedEnv)}`,\n `release_root=${shellQuote(targetRelease.root)}`,\n `release_project=${shellQuote(targetRelease.project)}`,\n 'mkdir -p \"$releases_dir\" \"$shared_dir\"',\n // Migrate a pre-blue-green deployment whose `code/` is still a plain directory.\n 'if [ -d \"$code\" ] && [ ! -L \"$code\" ]; then',\n ' if [ -f \"$project/.env\" ] && [ ! -f \"$shared_env\" ]; then',\n ' cp -pf \"$project/.env\" \"$shared_env\" && chmod 600 \"$shared_env\"',\n \" fi\",\n ' rm -rf \"$releases_dir/legacy\"',\n ' mv \"$code\" \"$releases_dir/legacy\"',\n ' ln -sfn \"releases/legacy\" \"$current\"',\n ' ln -sfn \"current\" \"$code\"',\n \"fi\",\n // A release deployed before `.env` became a link holds a copy: keep the edits made to it.\n 'if [ -f \"$project/.env\" ] && { [ ! -f \"$shared_env\" ] || [ \"$project/.env\" -nt \"$shared_env\" ]; }; then',\n ' cp -pf \"$project/.env\" \"$shared_env\" && chmod 600 \"$shared_env\"',\n \"fi\",\n 'if [ -L \"$current\" ]; then prev_release=\"$(basename \"$(readlink \"$current\")\")\"; fi',\n 'rm -rf \"$release_root\"',\n 'mkdir -p \"$release_root\"',\n `(cd \"$incoming\" && tar -c -f - --exclude=.env .) | (cd \"$release_root\" && tar -x -f -)`,\n 'chmod 755 \"$release_root\"',\n 'mkdir -p \"$release_project\"',\n 'if [ -f \"$shared_env\" ]; then ln -sfn \"$shared_env\" \"$release_project/.env\"; fi',\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 \"$RELEASE_PROJECT\"',\n '\"$BUN\" install --frozen-lockfile --backend=hardlink',\n \"for bin in sixb sixb-deploy-ssh; do\",\n ' if [ ! -e \"$RELEASE_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 isStorageMigration(command: DeployCommand): boolean {\n return command.program === \"sixb\" && command.args[0] === \"db\" && command.args[1] === \"migrate\"\n}\n\n/**\n * The live release cannot run against a schema it does not know, so a release with storage\n * migrations pending stops the services before migrating. \"Start new release\" then finds nothing\n * running and starts it cold. `sixb db migrate --check` reads the schema without changing it, and\n * exits 3 when migrations are pending. A release whose `sixb` predates `--check` rejects the\n * option with 2: nothing says the schema stays, so the services stop too.\n */\nfunction stopForSchemaChange(): Step {\n return {\n label: \"Check storage migrations\",\n body: [\n 'cd \"$RELEASE_PROJECT\"',\n \"migrations=0\",\n '\"$BUN\" \"$RELEASE_PROJECT/node_modules/.bin/sixb\" db migrate --check || migrations=$?',\n \"\",\n 'case \"$migrations\" in',\n \" 0) ;;\",\n \" 2 | 3)\",\n ' if [ \"$migrations\" = 3 ]; then',\n \" echo 'This release changes the storage schema, so the services stop while it migrates.'\",\n \" else\",\n \" echo 'This release cannot tell whether its schema changes, so the services stop while it migrates.'\",\n \" fi\",\n ' if systemctl --user is-active --quiet \"$UNIT\"; then systemctl --user stop \"$UNIT\"; fi',\n ' deploy_mode=\"stopped\"',\n \" ;;\",\n ' *) exit \"$migrations\" ;;',\n \"esac\",\n ].join(\"\\n\"),\n }\n}\n\nfunction runStep(command: DeployCommand): Step {\n const program = command.program === \"sixb\" ? '\"$RELEASE_PROJECT/node_modules/.bin/sixb\"' : \"\"\n return {\n label: [command.program, ...command.args].join(\" \"),\n body: [\n 'cd \"$RELEASE_PROJECT\"',\n `\"$BUN\" ${program} ${command.args.map(shellQuote).join(\" \")}`.replace(/ {2,}/g, \" \"),\n ].join(\"\\n\"),\n }\n}\n\n/**\n * Pulls `.env` with the token only this step reads. The pull replaces the release's link with a\n * file, which becomes the server's `shared/.env` before the link comes back.\n */\nfunction envStep(command: DeployCommand, layout: DeploymentLayout): Step {\n const step = runStep(command)\n return {\n ...step,\n body: [\n `${step.body} --token-file ${shellQuote(layout.envToken)}`,\n 'if [ -f \"$RELEASE_PROJECT/.env\" ] && [ ! -L \"$RELEASE_PROJECT/.env\" ]; then',\n ' mv -f \"$RELEASE_PROJECT/.env\" \"$SHARED_ENV\" && chmod 600 \"$SHARED_ENV\"',\n ' ln -sfn \"$SHARED_ENV\" \"$RELEASE_PROJECT/.env\"',\n \"fi\",\n ].join(\"\\n\"),\n }\n}\n\n/**\n * Carries one generation of immutable content-hashed assets from the previous `current` build into\n * the new `.sixb/dist/app` directory so open browser tabs never 404 on lazy chunks after cutover.\n */\nfunction withCarriedAssets(step: Step): Step {\n return {\n ...step,\n body: [\n step.body,\n 'new_app=\"$RELEASE_PROJECT/.sixb/dist/app\"',\n 'old_app=\"$PROJECT/.sixb/dist/app\"',\n 'own_list=\"$RELEASE_PROJECT/.sixb/dist/.own-assets\"',\n 'old_own=\"$PROJECT/.sixb/dist/.own-assets\"',\n 'if [ -d \"$new_app\" ]; then',\n ' (cd \"$new_app\" && find . -type f | LC_ALL=C sort) > \"$own_list\"',\n ' if [ -d \"$old_app\" ]; then',\n ' source_list=\"$old_own\"',\n ' if [ ! -f \"$source_list\" ]; then',\n ' source_list=\"$(mktemp)\"',\n ' (cd \"$old_app\" && find . -type f | LC_ALL=C sort) > \"$source_list\"',\n ' temp_source_list=\"$source_list\"',\n \" else\",\n ' temp_source_list=\"\"',\n \" fi\",\n \" while IFS= read -r rel; do\",\n ' base=\"$(basename \"$rel\")\"',\n ' case \"$base\" in',\n \" chunk-* | asset-* | app-*.* | shared-app-*.* | auth-*.*)\",\n ' if [ ! -e \"$new_app/$rel\" ] && [ -f \"$old_app/$rel\" ]; then',\n ' mkdir -p \"$(dirname \"$new_app/$rel\")\"',\n ' ln \"$old_app/$rel\" \"$new_app/$rel\" 2>/dev/null || cp -p \"$old_app/$rel\" \"$new_app/$rel\"',\n \" fi\",\n \" ;;\",\n \" esac\",\n ' done < \"$source_list\"',\n ' if [ -n \"$temp_source_list\" ]; then rm -f \"$temp_source_list\"; fi',\n \" fi\",\n \"fi\",\n ].join(\"\\n\"),\n }\n}\n\nfunction renderStartCandidate(input: {\n readonly layout: DeploymentLayout\n readonly targetRelease: ReleaseLayout\n readonly blueRelease: DeployRelease\n readonly greenRelease: DeployRelease\n readonly slots: SlotPorts\n}): string {\n const { layout, targetRelease, blueRelease, greenRelease, slots } = input\n const blueManifest = renderProcessManifest(blueRelease, layout, {\n projectDir: targetRelease.project,\n slot: \"blue\",\n })\n const greenManifest = renderProcessManifest(greenRelease, layout, {\n projectDir: targetRelease.project,\n slot: \"green\",\n })\n const installServiceFiles = renderInstallServiceFiles(blueRelease, layout, slots)\n\n return [\n writeFileCommand(\n `${layout.deployDir}/manifest.blue.json`,\n `${JSON.stringify(blueManifest, null, 2)}\\n`\n ),\n writeFileCommand(\n `${layout.deployDir}/manifest.green.json`,\n `${JSON.stringify(greenManifest, null, 2)}\\n`\n ),\n // Blue-green needs a running supervisor that knows `stage`. Anything else starts cold: the\n // first deploy, a stopped deployment, or a release whose migrations stopped the services.\n \"start_cold=1\",\n 'if [ -f \"$MANIFEST\" ] && systemctl --user is-active --quiet \"$UNIT\"; then start_cold=0; fi',\n \"\",\n // Temporary, for the first deploy after upgrading to blue-green deploys (#1174): the\n // supervisor still running predates `stage` and never answers it. Its manifest is the only\n // one without a `slot`, so it is restarted cold once. Remove this once no server runs a\n // supervisor from before #1174.\n 'if [ \"$start_cold\" = 0 ] && ! grep -qs \\'\"slot\":\\' \"$MANIFEST\"; then',\n \" echo 'The running supervisor predates blue-green deploys, so this deploy restarts it once.'\",\n \" start_cold=1\",\n \"fi\",\n \"\",\n 'if [ \"$start_cold\" = 0 ]; then',\n ' if grep -qs \\'\"slot\": \"green\"\\' \"$MANIFEST\"; then target_slot=\"blue\"; else target_slot=\"green\"; fi',\n ' cp \"$DEPLOY/manifest.$target_slot.json\" \"$CANDIDATE_MANIFEST\"',\n ' \"$BUN\" \"$RELEASE_PROJECT/node_modules/.bin/sixb-deploy-ssh\" stage \"$CANDIDATE_MANIFEST\" --manifest \"$MANIFEST\"',\n ' deploy_mode=\"staged\"',\n \" started=$SECONDS\",\n \"else\",\n ' target_slot=\"blue\"',\n \" use_release\",\n ' deploy_mode=\"cold\"',\n ...installServiceFiles.map((line) => ` ${line}`),\n ' mv \"$DEPLOY/manifest.blue.json\" \"$MANIFEST\"',\n ' rm -f \"$DEPLOY/manifest.green.json\" \"$CANDIDATE_MANIFEST\"',\n ' systemctl --user restart \"$UNIT\"',\n ' systemctl --user is-active --quiet \"$UNIT\"',\n \" started=$SECONDS\",\n \"fi\",\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 new release\", so the time the API\n * takes to boot is part of them rather than added to them.\n */\nexport function renderCheckServices(input: {\n readonly blueReadyUrl: string | null\n readonly greenReadyUrl?: string | null\n}): string {\n const blueUrl = input.blueReadyUrl\n const greenUrl = input.greenReadyUrl ?? input.blueReadyUrl\n const waitForApi =\n blueUrl || greenUrl\n ? [\n `ready_url=${shellQuote(blueUrl ?? \"\")}`,\n 'if [ \"$target_slot\" = \"green\" ]; then',\n ` ready_url=${shellQuote(greenUrl ?? \"\")}`,\n \"fi\",\n 'if [ -n \"$ready_url\" ]; then',\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 \"fi\",\n ]\n : []\n return [\n ...waitForApi,\n \"quiet=$((5 - (SECONDS - started)))\",\n 'if [ \"$quiet\" -gt 0 ]; then sleep \"$quiet\"; fi',\n 'if [ \"$deploy_mode\" = \"staged\" ]; then',\n ' \"$BUN\" \"$RELEASE_PROJECT/node_modules/.bin/sixb-deploy-ssh\" status --check --candidate --manifest \"$MANIFEST\"',\n \"else\",\n ' \"$CTL\" status --check',\n \"fi\",\n ].join(\"\\n\")\n}\n\n/**\n * Installs the deployment's Caddy routes for the verified slot. Caddy has to accept the whole\n * configuration before it reloads; otherwise the previous routes come back and the deploy stops.\n */\nfunction renderUpdateRoutes(input: {\n readonly layout: DeploymentLayout\n readonly blueCaddy: string\n readonly greenCaddy: string\n}): string {\n const { layout, blueCaddy, greenCaddy } = input\n return [\n writeFileCommand(`${layout.deployDir}/Caddyfile.blue`, blueCaddy),\n writeFileCommand(`${layout.deployDir}/Caddyfile.green`, greenCaddy),\n 'new=\"$DEPLOY/Caddyfile.$target_slot\"',\n 'cp \"$new\" \"$DEPLOY/Caddyfile\"',\n 'rm -f \"$DEPLOY/Caddyfile.blue\" \"$DEPLOY/Caddyfile.green\"',\n 'if cmp -s \"$DEPLOY/Caddyfile\" \"$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 ' rm -f \"$PREVIOUS_ROUTES\"',\n ' if [ -f \"$CADDY_SNIPPET\" ]; then cp \"$CADDY_SNIPPET\" \"$PREVIOUS_ROUTES\"; fi',\n ' cp \"$DEPLOY/Caddyfile\" \"$CADDY_SNIPPET\"',\n \"\",\n ' if ! caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile > \"$DEPLOY/caddy-validate.log\" 2>&1; then',\n \" restore_routes\",\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 \"\",\n // Caddy keeps the routes it had when a reload fails: the file goes back to match them.\n \" if ! sudo -n /usr/bin/systemctl reload caddy; then\",\n \" restore_routes\",\n \" echo 'Caddy did not reload; the previous routes are back in place.' >&2\",\n \" exit 1\",\n \" fi\",\n \"\",\n // From here a failure has to bring traffic back to the live release before discarding.\n ' if [ \"$deploy_mode\" = \"staged\" ]; then deploy_mode=\"routed\"; fi',\n \"fi\",\n ].join(\"\\n\")\n}\n\nfunction renderInstallServiceFiles(\n release: DeployRelease,\n layout: DeploymentLayout,\n slots: SlotPorts\n): string[] {\n const reservedPorts = [\n ...new Set(\n release.services.flatMap((service) =>\n service.http && (service.name === \"api\" || service.name === \"app\")\n ? [slots.blue[service.name], slots.green[service.name]]\n : []\n )\n ),\n ]\n .map(String)\n .join(\"\\n\")\n\n return [\n writeFileCommand(`${layout.deployDir}/ports.txt`, reservedPorts ? `${reservedPorts}\\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 ]\n}\n\nfunction renderActivateRelease(input: {\n readonly release: DeployRelease\n readonly layout: DeploymentLayout\n readonly slots: SlotPorts\n}): string {\n const hasExclusiveServices = input.release.services.some(\n (service) => service.kind === \"singleton\" || service.kind === \"script\"\n )\n const installServiceFiles = renderInstallServiceFiles(input.release, input.layout, input.slots)\n return [\n 'if [ \"$deploy_mode\" = \"staged\" ] || [ \"$deploy_mode\" = \"routed\" ]; then',\n ...installServiceFiles.map((line) => ` ${line}`),\n \" use_release\",\n ' deploy_mode=\"activated\"',\n ' mv \"$CANDIDATE_MANIFEST\" \"$MANIFEST\"',\n ' rm -f \"$DEPLOY/manifest.blue.json\" \"$DEPLOY/manifest.green.json\"',\n ' \"$CTL\" activate',\n ...(hasExclusiveServices ? [\" sleep 2\"] : []),\n ' \"$CTL\" status --check',\n \"fi\",\n renderPruneReleases(),\n ].join(\"\\n\")\n}\n\n/** Keeps the active release, the previous release, and any release still draining in `state.json`. */\nexport function renderPruneReleases(): string {\n return [\n 'if [ -d \"$RELEASES_DIR\" ]; then',\n ' for candidate_dir in \"$RELEASES_DIR\"/*; do',\n ' [ -d \"$candidate_dir\" ] || continue',\n ' name=\"$(basename \"$candidate_dir\")\"',\n ' if [ \"$name\" = \"$RELEASE_ID\" ] || [ \"$name\" = \"$prev_release\" ]; then continue; fi',\n ' if [ -f \"$STATE_FILE\" ] && grep -qsF \"$candidate_dir\" \"$STATE_FILE\"; then continue; fi',\n ' rm -rf \"$candidate_dir\"',\n \" done\",\n \"fi\",\n ].join(\"\\n\")\n}\n",
|
|
18
|
-
"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",
|
|
19
|
-
"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",
|
|
20
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"
|
|
21
15
|
],
|
|
22
|
-
"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;AAAA,IAAG,OAAO;AAAA,EAChD,MAAM,QAAQ,QAAQ,MAAM,KAAK;AAAA,EACjC,MAAM,YAAY,MAAM,UAAU,CAAC,SAAS,UAAU,IAAI,IAAI,CAAC;AAAA,EAC/D,IAAI,cAAc;AAAA,IAAI,OAAO;AAAA,EAC7B,MAAM,OAAO,MAAM,cAAc;AAAA,EACjC,MAAM,UAAU,MAAM,YAAY,MAAM;AAAA,EAExC,MAAM,OAAO,OAAO,KAAK,SAAS,QAAQ;AAAA,EAE1C,MAAM,aAAa,KAAK,UAAU,IAAI,KAAK,aAAa,CAAC,IAAI;AAAA,EAC7D,IAAI,KAAK,SAAS,GAAG,IAAI,UAAU,EAAE,SAAS,MAAM;AAAA,IAAM,OAAO;AAAA,EAEjE,MAAM,UAAU,YAAY,IAAI,MAAM,MAAM,GAAG,SAAS,EAAE,KAAK,GAAG,IAAI;AAAA,EACtE,OAAO;AAAA,IACL;AAAA,IACA,aAAa,UAAU,WAAW,QAAQ,EAAE,OAAO,IAAI,EAAE,OAAO,QAAQ,EAAE,QAAQ,OAAO,EAAE;AAAA,IAC3F,SAAS,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