@sixb/deploy-ssh 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -0
  3. package/dist/access.d.ts +11 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/check.d.ts +28 -0
  6. package/dist/check.d.ts.map +1 -0
  7. package/dist/ci.d.ts +27 -0
  8. package/dist/ci.d.ts.map +1 -0
  9. package/dist/index.d.ts +3 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +1415 -0
  12. package/dist/index.js.map +24 -0
  13. package/dist/keys.d.ts +13 -0
  14. package/dist/keys.d.ts.map +1 -0
  15. package/dist/layout.d.ts +38 -0
  16. package/dist/layout.d.ts.map +1 -0
  17. package/dist/operations.d.ts +10 -0
  18. package/dist/operations.d.ts.map +1 -0
  19. package/dist/render.d.ts +15 -0
  20. package/dist/render.d.ts.map +1 -0
  21. package/dist/scripts.d.ts +37 -0
  22. package/dist/scripts.d.ts.map +1 -0
  23. package/dist/server/cli.d.ts +3 -0
  24. package/dist/server/cli.d.ts.map +1 -0
  25. package/dist/server/logs.d.ts +25 -0
  26. package/dist/server/logs.d.ts.map +1 -0
  27. package/dist/server/manifest.d.ts +30 -0
  28. package/dist/server/manifest.d.ts.map +1 -0
  29. package/dist/server/state.d.ts +32 -0
  30. package/dist/server/state.d.ts.map +1 -0
  31. package/dist/server/supervisor.d.ts +16 -0
  32. package/dist/server/supervisor.d.ts.map +1 -0
  33. package/dist/setup.d.ts +25 -0
  34. package/dist/setup.d.ts.map +1 -0
  35. package/dist/shell.d.ts +5 -0
  36. package/dist/shell.d.ts.map +1 -0
  37. package/dist/ssh-config.d.ts +12 -0
  38. package/dist/ssh-config.d.ts.map +1 -0
  39. package/dist/ssh-target.d.ts +39 -0
  40. package/dist/ssh-target.d.ts.map +1 -0
  41. package/dist/transport.d.ts +45 -0
  42. package/dist/transport.d.ts.map +1 -0
  43. package/dist/tsconfig.json +5 -0
  44. package/dist/update-page.d.ts +6 -0
  45. package/dist/update-page.d.ts.map +1 -0
  46. package/package.json +61 -0
  47. package/src/access.ts +107 -0
  48. package/src/check.ts +215 -0
  49. package/src/ci.ts +88 -0
  50. package/src/index.ts +2 -0
  51. package/src/keys.ts +57 -0
  52. package/src/layout.ts +69 -0
  53. package/src/operations.ts +158 -0
  54. package/src/render.ts +129 -0
  55. package/src/scripts.ts +305 -0
  56. package/src/server/cli.ts +157 -0
  57. package/src/server/logs.ts +180 -0
  58. package/src/server/manifest.ts +112 -0
  59. package/src/server/state.ts +81 -0
  60. package/src/server/supervisor.ts +542 -0
  61. package/src/setup.ts +166 -0
  62. package/src/shell.ts +10 -0
  63. package/src/ssh-config.ts +35 -0
  64. package/src/ssh-target.ts +347 -0
  65. package/src/transport.ts +211 -0
  66. package/src/update-page.ts +44 -0
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Everything that needs root, run once per server and once per deploy user, safe to run again.
3
+ * Afterwards the deploy user needs no sudo but reloading Caddy.
4
+ *
5
+ * Caddy's configuration is taken over only when it is still the one the package installed. A
6
+ * server that already serves other sites keeps its configuration and gains one import line (the
7
+ * old file is kept beside it), and its admin API stays where that configuration puts it.
8
+ */
9
+ export declare function renderAdminScript(input: {
10
+ readonly user: string;
11
+ readonly publicKey: string;
12
+ readonly admin: string;
13
+ }): string;
14
+ /**
15
+ * The public key to authorize for deploys: the one given, else the first key SSH would offer to
16
+ * the server that has a `.pub` beside it, else the first key in the SSH agent.
17
+ */
18
+ export declare function pickPublicKey(input: {
19
+ readonly key?: string;
20
+ readonly identityFiles: readonly string[];
21
+ }): Promise<{
22
+ readonly text: string;
23
+ readonly source: string;
24
+ }>;
25
+ //# sourceMappingURL=setup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../src/setup.ts"],"names":[],"mappings":"AAMA;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IACvC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CACvB,GAAG,MAAM,CAoHT;AAED;;;GAGG;AACH,wBAAsB,aAAa,CAAC,KAAK,EAAE;IACzC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAA;CAC1C,GAAG,OAAO,CAAC;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAsB9D"}
@@ -0,0 +1,5 @@
1
+ /** Quotes a value as one POSIX shell word. */
2
+ export declare function shellQuote(value: string): string;
3
+ /** A shell command that writes `content` to `path`, whatever bytes it holds. */
4
+ export declare function writeFileCommand(path: string, content: string): string;
5
+ //# sourceMappingURL=shell.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../src/shell.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAC9C,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEhD;AAED,gFAAgF;AAChF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAGtE"}
@@ -0,0 +1,12 @@
1
+ export interface ResolvedSshConfig {
2
+ /** The real hostname or address behind the target's host, which may be an SSH config alias. */
3
+ readonly hostname: string;
4
+ readonly port: number;
5
+ /** The host SSH jumps through first, when the config sets one. */
6
+ readonly proxyJump?: string;
7
+ /** Identity files SSH would offer, in order, with `~` expanded. */
8
+ readonly identityFiles: readonly string[];
9
+ }
10
+ /** What OpenSSH makes of a destination once its config applies, from `ssh -G`. */
11
+ export declare function resolveSshConfig(destination: string): Promise<ResolvedSshConfig>;
12
+ //# sourceMappingURL=ssh-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssh-config.d.ts","sourceRoot":"","sources":["../src/ssh-config.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,iBAAiB;IAChC,+FAA+F;IAC/F,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,kEAAkE;IAClE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAC3B,mEAAmE;IACnE,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAA;CAC1C;AAED,kFAAkF;AAClF,wBAAsB,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAqBtF"}
@@ -0,0 +1,39 @@
1
+ import type { DeployAccess, DeployCheck, DeployCheckContext, DeployCi, DeployContext, DeployControlAction, DeployHttpServiceName, DeployListenAddress, DeployLogsOptions, DeployOperationContext, DeployRelease, DeploySetupContext, DeploySource, DeployStatus, DeployTarget } from "@sixb/core/deploy";
2
+ export interface SshTargetOptions {
3
+ /** The server: a hostname, an IP address, or a `Host` alias from your SSH config. */
4
+ readonly host: string;
5
+ /**
6
+ * The Linux user the deployment runs as. Projects under one user can read each other's files,
7
+ * so give a project its own user to wall it off from the others on the server. Defaults to
8
+ * `"sixb"`.
9
+ */
10
+ readonly user?: string;
11
+ /**
12
+ * Local ports for the HTTP services, which Caddy on the server forwards to. Set them when
13
+ * projects share a server, so that each has its own. Defaults: atlas 3000, app 3001, api 3002.
14
+ */
15
+ readonly ports?: Readonly<Partial<Record<DeployHttpServiceName, number>>>;
16
+ }
17
+ /** A server reached over SSH, where Caddy routes each domain to its service. */
18
+ export declare class SshTarget implements DeployTarget {
19
+ #private;
20
+ readonly kind = "ssh";
21
+ readonly host: string;
22
+ readonly user: string;
23
+ readonly location: string;
24
+ constructor(options: SshTargetOptions);
25
+ listenAddress(service: DeployHttpServiceName): DeployListenAddress;
26
+ deploy(release: DeployRelease, source: DeploySource, context: DeployContext): Promise<void>;
27
+ status(context: DeployOperationContext): Promise<DeployStatus>;
28
+ logs(options: DeployLogsOptions, context: DeployOperationContext): Promise<void>;
29
+ control(action: DeployControlAction, service: string | undefined, context: DeployOperationContext): Promise<void>;
30
+ check(release: DeployRelease, context: DeployCheckContext): Promise<DeployCheck[]>;
31
+ /**
32
+ * Prepares the server as the admin login when the deploy user or the server is not set up
33
+ * yet, then the project as the deploy user. Running it again changes nothing that is right.
34
+ */
35
+ setup(release: DeployRelease, context: DeploySetupContext): Promise<void>;
36
+ readonly access: DeployAccess;
37
+ readonly ci: DeployCi;
38
+ }
39
+ //# sourceMappingURL=ssh-target.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssh-target.d.ts","sourceRoot":"","sources":["../src/ssh-target.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,YAAY,EAEZ,WAAW,EACX,kBAAkB,EAClB,QAAQ,EAER,aAAa,EACb,mBAAmB,EACnB,qBAAqB,EACrB,mBAAmB,EACnB,iBAAiB,EACjB,sBAAsB,EACtB,aAAa,EACb,kBAAkB,EAClB,YAAY,EACZ,YAAY,EACZ,YAAY,EACb,MAAM,mBAAmB,CAAA;AAU1B,MAAM,WAAW,gBAAgB;IAC/B,qFAAqF;IACrF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB;;;;OAIG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;IACtB;;;OAGG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC,CAAC,CAAA;CAC1E;AAkBD,gFAAgF;AAChF,qBAAa,SAAU,YAAW,YAAY;;IAC5C,QAAQ,CAAC,IAAI,SAAQ;IACrB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;gBAGb,OAAO,EAAE,gBAAgB;IAkBrC,aAAa,CAAC,OAAO,EAAE,qBAAqB,GAAG,mBAAmB;IAIlE,MAAM,CAAC,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IAI3F,MAAM,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,YAAY,CAAC;IAI9D,IAAI,CAAC,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IAMhF,OAAO,CACL,MAAM,EAAE,mBAAmB,EAC3B,OAAO,EAAE,MAAM,GAAG,SAAS,EAC3B,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAAC,IAAI,CAAC;IAIV,KAAK,CAAC,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAsBxF;;;OAGG;IACG,KAAK,CAAC,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAsC/E,QAAQ,CAAC,MAAM,EAAE,YAAY,CAK5B;IAED,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAEpB;CAqDF"}
@@ -0,0 +1,45 @@
1
+ export interface RunOptions {
2
+ /** Streamed to the script's standard input. The script itself then travels as an argument. */
3
+ readonly stdin?: ReadableStream<Uint8Array>;
4
+ /**
5
+ * Every line the script prints, and which stream it came from. Read results from `stdout`
6
+ * only: a login script or a failed redirection can write to `stderr` first.
7
+ */
8
+ readonly onLine?: (line: string, stream: "stdout" | "stderr") => void;
9
+ /** Attach the terminal, so the remote command stops when you press Ctrl-C. */
10
+ readonly terminal?: boolean;
11
+ }
12
+ /** Runs bash scripts on a deployment's server. */
13
+ export interface RemoteShell {
14
+ /** Rejects with the script's last output lines when it exits non-zero. */
15
+ run(script: string, options?: RunOptions): Promise<void>;
16
+ close(): Promise<void>;
17
+ }
18
+ export declare class RemoteScriptError extends Error {
19
+ readonly exitCode: number;
20
+ constructor(message: string, exitCode: number);
21
+ }
22
+ /**
23
+ * One SSH connection, shared by every script a command runs through OpenSSH's connection
24
+ * multiplexing. Never prompts: a password, passphrase, or unknown host key fails with a message
25
+ * instead of hanging a deploy.
26
+ */
27
+ export declare class SshShell implements RemoteShell {
28
+ private readonly destination;
29
+ private readonly controlDir;
30
+ private constructor();
31
+ static open(destination: string): Promise<SshShell>;
32
+ run(script: string, options?: RunOptions): Promise<void>;
33
+ close(): Promise<void>;
34
+ private options;
35
+ }
36
+ /** Runs the scripts on this machine instead, with its own home. For tests. */
37
+ export declare class LocalShell implements RemoteShell {
38
+ private readonly env;
39
+ constructor(env?: Readonly<Record<string, string>>);
40
+ run(script: string, options?: RunOptions): Promise<void>;
41
+ close(): Promise<void>;
42
+ }
43
+ /** OpenSSH's own failures, which exit 255, reworded as what to do about them. */
44
+ export declare function sshError(destination: string, error: unknown): Error;
45
+ //# sourceMappingURL=transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,UAAU;IACzB,8FAA8F;IAC9F,QAAQ,CAAC,KAAK,CAAC,EAAE,cAAc,CAAC,UAAU,CAAC,CAAA;IAC3C;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,GAAG,QAAQ,KAAK,IAAI,CAAA;IACrE,8EAA8E;IAC9E,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;CAC5B;AAED,kDAAkD;AAClD,MAAM,WAAW,WAAW;IAC1B,0EAA0E;IAC1E,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACxD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CACvB;AAED,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;gBAEb,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;CAK9C;AAID;;;;GAIG;AACH,qBAAa,QAAS,YAAW,WAAW;IAExC,OAAO,CAAC,QAAQ,CAAC,WAAW;IAC5B,OAAO,CAAC,QAAQ,CAAC,UAAU;IAF7B,OAAO;WAKM,IAAI,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;IAanD,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,UAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAsB5D,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAK5B,OAAO,CAAC,OAAO;CAmBhB;AAED,8EAA8E;AAC9E,qBAAa,UAAW,YAAW,WAAW;IAChC,OAAO,CAAC,QAAQ,CAAC,GAAG;gBAAH,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAM;IAEjE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,UAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAS5D,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAC7B;AAqED,iFAAiF;AACjF,wBAAgB,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,KAAK,CAkBnE"}
@@ -0,0 +1,5 @@
1
+ // Written by scripts/build-package.ts, and published on purpose.
2
+ // Bun applies the nearest tsconfig paths map to every import it resolves, node_modules
3
+ // included. An empty map here keeps a consumer's aliases from sending a module in this
4
+ // directory back into a second copy of its own source.
5
+ { "compilerOptions": { "paths": {} } }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Shown by Caddy for a page request while the app or Atlas cannot answer — during a deploy, or
3
+ * an outage. It needs no assets or JavaScript and reloads itself every 10 seconds.
4
+ */
5
+ export declare function renderUpdatePage(): string;
6
+ //# sourceMappingURL=update-page.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-page.d.ts","sourceRoot":"","sources":["../src/update-page.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAuCzC"}
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@sixb/deploy-ssh",
3
+ "version": "0.1.0",
4
+ "description": "Deploy a Sixb project to your own server over SSH",
5
+ "keywords": [
6
+ "sixb",
7
+ "bun",
8
+ "deploy",
9
+ "ssh"
10
+ ],
11
+ "homepage": "https://sixb.ai",
12
+ "bugs": {
13
+ "url": "https://github.com/sixb-ai/sixb/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/sixb-ai/sixb.git",
18
+ "directory": "deploy/ssh"
19
+ },
20
+ "author": "Sixb contributors",
21
+ "type": "module",
22
+ "bin": {
23
+ "sixb-deploy-ssh": "./src/server/cli.ts"
24
+ },
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "bun": "./src/index.ts",
31
+ "import": "./dist/index.js",
32
+ "default": "./dist/index.js"
33
+ }
34
+ },
35
+ "scripts": {
36
+ "build": "bun ../../scripts/build-package.ts",
37
+ "typecheck": "tsc --noEmit",
38
+ "prepack": "bun run build"
39
+ },
40
+ "peerDependencies": {
41
+ "@sixb/core": "^0.1.15"
42
+ },
43
+ "devDependencies": {
44
+ "@sixb/core": "0.1.15",
45
+ "@types/bun": "latest",
46
+ "typescript": "^5.7.0"
47
+ },
48
+ "license": "MIT",
49
+ "engines": {
50
+ "bun": ">=1.4.2"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ },
55
+ "files": [
56
+ "dist",
57
+ "src",
58
+ "README.md",
59
+ "LICENSE"
60
+ ]
61
+ }
package/src/access.ts ADDED
@@ -0,0 +1,107 @@
1
+ import { createHash } from "node:crypto"
2
+ import type { DeployAccessKey } from "@sixb/core/deploy"
3
+ import { type AuthorizedKey, parseAuthorizedKey, parsePublicKey } from "./keys"
4
+ import { shellQuote } from "./shell"
5
+ import type { RemoteShell } from "./transport"
6
+
7
+ interface KeysFile {
8
+ readonly lines: readonly string[]
9
+ readonly keys: readonly AuthorizedKey[]
10
+ readonly hash: string
11
+ }
12
+
13
+ export async function listKeys(shell: RemoteShell): Promise<AuthorizedKey[]> {
14
+ return [...(await readKeysFile(shell)).keys]
15
+ }
16
+
17
+ /** Authorizes a public key once, with `options` (such as `restrict`) in front of it. */
18
+ export async function addKey(
19
+ shell: RemoteShell,
20
+ text: string,
21
+ options?: string
22
+ ): Promise<AuthorizedKey> {
23
+ const parsed = parsePublicKey(text)
24
+ const key = options ? (parseAuthorizedKey(`${options} ${parsed.line}`) ?? parsed) : parsed
25
+ const file = await readKeysFile(shell)
26
+ if (file.keys.some((candidate) => candidate.fingerprint === key.fingerprint)) return key
27
+ await rewrite(shell, [...file.lines, key.line], file.hash)
28
+ return key
29
+ }
30
+
31
+ /** Removes the keys whose fingerprint or comment is `match`. Never removes the last one. */
32
+ export async function removeKeys(shell: RemoteShell, match: string): Promise<DeployAccessKey[]> {
33
+ const removed = await removeKeysWhere(
34
+ shell,
35
+ (key) => key.fingerprint === match || key.comment === match
36
+ )
37
+ if (removed.length === 0) {
38
+ throw new Error(`[SshTarget] No authorized key has the fingerprint or comment '${match}'.`)
39
+ }
40
+ return removed
41
+ }
42
+
43
+ /** Removes the keys `matches` picks, if any. Never removes the last one. */
44
+ export async function removeKeysWhere(
45
+ shell: RemoteShell,
46
+ matches: (key: AuthorizedKey) => boolean
47
+ ): Promise<AuthorizedKey[]> {
48
+ const file = await readKeysFile(shell)
49
+ const removed = file.keys.filter(matches)
50
+ if (removed.length === 0) return []
51
+ if (removed.length === file.keys.length) {
52
+ throw new Error(
53
+ "[SshTarget] That would remove every key, and nobody could reach the deployment. " +
54
+ "Add another key first."
55
+ )
56
+ }
57
+ const gone = new Set(removed.map((key) => key.line))
58
+ await rewrite(
59
+ shell,
60
+ file.lines.filter((line) => !gone.has(line.trim())),
61
+ file.hash
62
+ )
63
+ return removed
64
+ }
65
+
66
+ async function readKeysFile(shell: RemoteShell): Promise<KeysFile> {
67
+ const encoded: string[] = []
68
+ await shell.run('(base64 < "$HOME/.ssh/authorized_keys" 2> /dev/null || true) | tr -d "\\n"', {
69
+ onLine: (line, stream) => {
70
+ if (stream === "stdout") encoded.push(line)
71
+ },
72
+ })
73
+ const content = Buffer.from(encoded.join(""), "base64").toString("utf8")
74
+ const lines = content.split("\n").filter((line, index, all) => line || index < all.length - 1)
75
+ return {
76
+ lines,
77
+ keys: lines.flatMap((line) => parseAuthorizedKey(line) ?? []),
78
+ hash: sha256(content),
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Replaces `authorized_keys` through a rename, other lines untouched. Fails if the file changed
84
+ * since it was read, so two people changing access at once cannot drop each other's key.
85
+ */
86
+ async function rewrite(shell: RemoteShell, lines: readonly string[], readHash: string) {
87
+ const content = `${lines.join("\n")}\n`
88
+ await shell.run(
89
+ [
90
+ "set -euo pipefail",
91
+ 'keys="$HOME/.ssh/authorized_keys"',
92
+ 'mkdir -p -m 700 "$HOME/.ssh"',
93
+ 'current="$( (cat "$keys" 2> /dev/null || true) | sha256sum | cut -d" " -f1)"',
94
+ `if [ "$current" != ${shellQuote(readHash)} ]; then`,
95
+ ' echo "authorized_keys changed while this ran; run the command again." >&2',
96
+ " exit 1",
97
+ "fi",
98
+ `printf '%s' ${shellQuote(Buffer.from(content).toString("base64"))} | base64 -d > "$keys.new"`,
99
+ 'chmod 600 "$keys.new"',
100
+ 'mv "$keys.new" "$keys"',
101
+ ].join("\n")
102
+ )
103
+ }
104
+
105
+ function sha256(content: string): string {
106
+ return createHash("sha256").update(content).digest("hex")
107
+ }
package/src/check.ts ADDED
@@ -0,0 +1,215 @@
1
+ import { resolve4, resolve6 } from "node:dns/promises"
2
+ import { isIP } from "node:net"
3
+ import { posix } from "node:path"
4
+ import type { DeployCheck, DeployRelease } from "@sixb/core/deploy"
5
+ import { shellQuote } from "./shell"
6
+ import type { RemoteShell } from "./transport"
7
+
8
+ export const CHECK_MARKER = "__SIXB_CHECK__"
9
+
10
+ /** The tools a deploy runs on the server. */
11
+ const TOOLS = ["git", "curl", "unzip", "tar", "flock", "sha256sum", "caddy"]
12
+
13
+ type Status = DeployCheck["status"]
14
+
15
+ /**
16
+ * Checks the server as the deploy user, changing nothing. Each check prints one
17
+ * `__SIXB_CHECK__ id status detail` line; labels and remedies are added on this side.
18
+ */
19
+ export function renderCheckScript(input: {
20
+ readonly name: string
21
+ readonly projectPath: string
22
+ readonly ports: readonly { readonly service: string; readonly port: number }[]
23
+ }): string {
24
+ const project = posix.join(input.name, "code", input.projectPath)
25
+ return [
26
+ `emit() { printf '${CHECK_MARKER}\\t%s\\t%s\\t%s\\n' "$1" "$2" "$(printf '%s' "$3" | tr '\\t\\n' ' ')"; }`,
27
+ `project="$HOME"/${shellQuote(project)}`,
28
+ `manifest="$HOME"/${shellQuote(input.name)}/deploy/processes.json`,
29
+ 'routes_dir="/etc/caddy/sixb.d/$USER"',
30
+ `snippet="$routes_dir"/${shellQuote(`${input.name}.caddy`)}`,
31
+ "",
32
+ "if command -v apt-get > /dev/null && command -v systemctl > /dev/null; then",
33
+ ' emit server.os ok "$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"',
34
+ "else",
35
+ ' emit server.os manual "$(uname -s) without apt and systemd"',
36
+ "fi",
37
+ "",
38
+ 'missing=""',
39
+ `for tool in ${TOOLS.join(" ")}; do command -v "$tool" > /dev/null || missing="$missing $tool"; done`,
40
+ 'if [ -n "$missing" ]; then emit server.tools fixable "missing:$missing"',
41
+ 'else emit server.tools ok "Caddy $(caddy version 2>/dev/null | cut -d" " -f1), git, curl, unzip"; fi',
42
+ "",
43
+ 'if [ -e "/var/lib/systemd/linger/$USER" ]; then emit server.linger ok "on for $USER"',
44
+ 'else emit server.linger fixable "off for $USER: services would stop when you log out"; fi',
45
+ "",
46
+ "if sudo -n -l /usr/bin/systemctl reload caddy > /dev/null 2>&1; then",
47
+ ' emit server.reload ok "$USER may reload Caddy"',
48
+ "else",
49
+ ' emit server.reload fixable "$USER may not run sudo systemctl reload caddy"',
50
+ "fi",
51
+ "",
52
+ 'problems=""',
53
+ '[ -d "$routes_dir" ] && [ -w "$routes_dir" ] || problems="$problems; $routes_dir is missing or not writable"',
54
+ 'grep -qsF "import $routes_dir/*.caddy" "/etc/caddy/sixb.d/$USER.caddy" || problems="$problems; /etc/caddy/sixb.d/$USER.caddy does not import it"',
55
+ "grep -qsF 'import /etc/caddy/sixb.d/*.caddy' /etc/caddy/Caddyfile || problems=\"$problems; /etc/caddy/Caddyfile does not import /etc/caddy/sixb.d/*.caddy\"",
56
+ 'if [ -z "$problems" ]; then emit server.routes ok "$routes_dir"',
57
+ "else emit server.routes fixable \"$(printf '%s' \"$problems\" | sed 's/^; //')\"; fi",
58
+ "",
59
+ "if ss -ltnH 2> /dev/null | grep -qE '(127\\.0\\.0\\.1|\\[::1\\]):2019 '; then",
60
+ ' emit server.admin-api warning "Caddy\'s admin API listens on localhost:2019, where any process on the server can change every route"',
61
+ "else",
62
+ ' emit server.admin-api ok "not on localhost:2019"',
63
+ "fi",
64
+ "",
65
+ 'if [ ! -f "$project/.env" ]; then emit project.env manual "$project/.env does not exist"',
66
+ 'elif [ "$(stat -c %a "$project/.env")" != 600 ]; then emit project.env fixable "$project/.env is readable by others (mode $(stat -c %a "$project/.env"))"',
67
+ 'else emit project.env ok "$project/.env"; fi',
68
+ "",
69
+ ...input.ports.flatMap(({ service, port }) => [
70
+ `if ss -ltnH "sport = :${port}" 2> /dev/null | grep -q .; then`,
71
+ ` if grep -qs '"--port",' "$manifest" && grep -A1 -s '"--port",' "$manifest" | grep -q '"${port}"'; then`,
72
+ ` emit project.port.${service} ok "${port}, used by this deployment"`,
73
+ " else",
74
+ ` emit project.port.${service} manual "${port} is in use by another program"`,
75
+ " fi",
76
+ `elif grep -ls '127.0.0.1:${port}\\b' /etc/caddy/sixb.d/*/*.caddy 2> /dev/null | grep -qv "^$snippet$"; then`,
77
+ ` emit project.port.${service} manual "${port} is routed to another deployment"`,
78
+ "else",
79
+ ` emit project.port.${service} ok "${port}"`,
80
+ "fi",
81
+ ]),
82
+ "",
83
+ 'free_kb="$(df -Pk "$HOME" | awk \'NR == 2 { print $4 + 0 }\')"',
84
+ 'if [ "$free_kb" -lt 2097152 ]; then emit server.disk warning "$((free_kb / 1024)) MB free"',
85
+ 'else emit server.disk ok "$((free_kb / 1048576)) GB free"; fi',
86
+ ].join("\n")
87
+ }
88
+
89
+ /** Reads the check script's output into checks, with labels and remedies. */
90
+ export function parseCheckOutput(
91
+ lines: readonly string[],
92
+ context: { readonly location: string; readonly name: string }
93
+ ): DeployCheck[] {
94
+ return lines.flatMap((line) => {
95
+ const [marker, id, status, detail] = line.split("\t")
96
+ if (marker !== CHECK_MARKER || !id || !isStatus(status)) return []
97
+ return [describe(id, status, detail ?? "", context)]
98
+ })
99
+ }
100
+
101
+ /** Where each HTTP domain resolves, against where the target is. */
102
+ export async function checkDns(release: DeployRelease, hostname: string): Promise<DeployCheck[]> {
103
+ const expected = isIP(hostname) ? [hostname] : await lookup(hostname)
104
+ return Promise.all(
105
+ release.services.flatMap((service) => {
106
+ const http = service.http
107
+ if (!http) return []
108
+ return [
109
+ (async (): Promise<DeployCheck> => {
110
+ const found = await lookup(http.domain)
111
+ const id = `dns.${service.name}`
112
+ const label = `${service.name} DNS`
113
+ if (expected.length > 0 && found.some((address) => expected.includes(address))) {
114
+ return { id, label, status: "ok", detail: `${http.domain} → ${found.join(", ")}` }
115
+ }
116
+ const target = expected[0] ?? hostname
117
+ return {
118
+ id,
119
+ label,
120
+ status: "warning",
121
+ detail:
122
+ found.length > 0
123
+ ? `${http.domain} → ${found.join(", ")}`
124
+ : `${http.domain} does not resolve`,
125
+ remedy: `Point ${http.domain} at ${target} with an ${isIP(target) === 6 ? "AAAA" : "A"} record. Until then, Caddy cannot get it a certificate.`,
126
+ }
127
+ })(),
128
+ ]
129
+ })
130
+ )
131
+ }
132
+
133
+ /** The checks that stop a deploy. */
134
+ export function blocksDeploy(check: DeployCheck): boolean {
135
+ return check.status === "fixable" || check.status === "manual"
136
+ }
137
+
138
+ export async function runChecks(
139
+ shell: RemoteShell,
140
+ input: Parameters<typeof renderCheckScript>[0] & { readonly location: string }
141
+ ): Promise<DeployCheck[]> {
142
+ const lines: string[] = []
143
+ await shell.run(renderCheckScript(input), {
144
+ onLine: (line, stream) => {
145
+ if (stream === "stdout") lines.push(line)
146
+ },
147
+ })
148
+ return parseCheckOutput(lines, input)
149
+ }
150
+
151
+ const LABELS: Readonly<Record<string, string>> = {
152
+ "server.os": "Server",
153
+ "server.tools": "Server tools",
154
+ "server.linger": "Services at boot",
155
+ "server.reload": "Caddy reload",
156
+ "server.routes": "Caddy routes",
157
+ "server.admin-api": "Caddy admin API",
158
+ "server.disk": "Disk space",
159
+ "project.env": ".env",
160
+ }
161
+
162
+ function describe(
163
+ id: string,
164
+ status: Status,
165
+ detail: string,
166
+ context: { readonly location: string; readonly name: string }
167
+ ): DeployCheck {
168
+ const label = LABELS[id] ?? (id.startsWith("project.port.") ? `${id.slice(13)} port` : id)
169
+ const check = { id, label, status, detail }
170
+ if (status === "ok") return check
171
+ if (status === "fixable") return { ...check, remedy: "Run `sixb deploy setup`." }
172
+ if (id === "server.os") return { ...check, remedy: "Deploy to an Ubuntu or Debian server." }
173
+ if (id === "project.env") {
174
+ const path = detail.replace(/ does not exist$/, "")
175
+ return {
176
+ ...check,
177
+ remedy: `Create it with the project's settings: \`ssh ${context.location} 'install -m 600 /dev/null ${path}'\`, then edit it.`,
178
+ }
179
+ }
180
+ if (id.startsWith("project.port.")) {
181
+ return { ...check, remedy: "Give this service another port in the target's `ports`." }
182
+ }
183
+ if (id === "server.admin-api") {
184
+ return {
185
+ ...check,
186
+ remedy:
187
+ "Set `admin unix//var/lib/caddy/admin.sock` in the global options of /etc/caddy/Caddyfile.",
188
+ }
189
+ }
190
+ return check
191
+ }
192
+
193
+ function isStatus(value: string | undefined): value is Status {
194
+ return value === "ok" || value === "fixable" || value === "manual" || value === "warning"
195
+ }
196
+
197
+ async function lookup(hostname: string): Promise<string[]> {
198
+ const [v4, v6] = await Promise.all([settle(resolve4(hostname)), settle(resolve6(hostname))])
199
+ return [...v4, ...v6]
200
+ }
201
+
202
+ /** A lookup's answers, or none once it fails or takes over four seconds. */
203
+ async function settle(query: Promise<string[]>): Promise<string[]> {
204
+ let timer: ReturnType<typeof setTimeout> | undefined
205
+ try {
206
+ return await Promise.race([
207
+ query.catch(() => []),
208
+ new Promise<string[]>((resolveTimeout) => {
209
+ timer = setTimeout(() => resolveTimeout([]), 4_000)
210
+ }),
211
+ ])
212
+ } finally {
213
+ clearTimeout(timer)
214
+ }
215
+ }
package/src/ci.ts ADDED
@@ -0,0 +1,88 @@
1
+ import { mkdtemp, readFile, rm } from "node:fs/promises"
2
+ import { tmpdir } from "node:os"
3
+ import { join } from "node:path"
4
+ import type { RemoteShell } from "./transport"
5
+
6
+ /**
7
+ * A new key pair for a CI job. It is made in a directory that is removed before this returns, so
8
+ * the private key exists only in memory here and, afterwards, in the CI system's secrets.
9
+ */
10
+ export async function generateCiKey(
11
+ comment: string
12
+ ): Promise<{ readonly privateKey: string; readonly publicKey: string }> {
13
+ const dir = await mkdtemp(join(tmpdir(), "sixb-ci-key-"))
14
+ try {
15
+ const path = join(dir, "key")
16
+ const child = Bun.spawn(
17
+ ["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", comment, "-f", path],
18
+ {
19
+ stdin: "ignore",
20
+ stdout: "ignore",
21
+ stderr: "pipe",
22
+ }
23
+ )
24
+ if ((await child.exited) !== 0) {
25
+ const reason = (await new Response(child.stderr).text()).trim()
26
+ throw new Error(`[SshTarget] ssh-keygen could not make a key for CI: ${reason}`)
27
+ }
28
+ return {
29
+ privateKey: await readFile(path, "utf8"),
30
+ publicKey: (await readFile(`${path}.pub`, "utf8")).trim(),
31
+ }
32
+ } finally {
33
+ await rm(dir, { recursive: true, force: true })
34
+ }
35
+ }
36
+
37
+ /**
38
+ * The server's host keys, read over a connection SSH has already checked against your own
39
+ * `known_hosts`. CI trusts these instead of whatever answers at the address the first time.
40
+ */
41
+ export async function readHostKeys(shell: RemoteShell): Promise<string[]> {
42
+ const keys: string[] = []
43
+ await shell.run("cat /etc/ssh/ssh_host_*_key.pub", {
44
+ onLine: (line, stream) => {
45
+ const [type, key] = line.trim().split(/\s+/)
46
+ if (stream === "stdout" && type && key) keys.push(`${type} ${key}`)
47
+ },
48
+ })
49
+ if (keys.length === 0) throw new Error("[SshTarget] Could not read the server's SSH host keys.")
50
+ return keys
51
+ }
52
+
53
+ /** `known_hosts` lines for the host keys, under the name and port CI connects to. */
54
+ export function knownHostsLines(
55
+ hostKeys: readonly string[],
56
+ hostname: string,
57
+ port: number
58
+ ): string[] {
59
+ const name = port === 22 ? hostname : `[${hostname}]:${port}`
60
+ return hostKeys.map((key) => `${name} ${key}`)
61
+ }
62
+
63
+ /**
64
+ * Shell lines that install the key on the CI runner, reading `SIXB_DEPLOY_SSH_KEY` and
65
+ * `SIXB_DEPLOY_KNOWN_HOSTS` from the environment. `host` is what `sixb.deploy.ts` names, which may
66
+ * be an alias from your SSH config; the runner gets the same alias.
67
+ */
68
+ export function renderCiInstall(input: {
69
+ readonly host: string
70
+ readonly hostname: string
71
+ readonly port: number
72
+ }): string[] {
73
+ return [
74
+ "install -d -m 700 ~/.ssh",
75
+ "install -m 600 /dev/null ~/.ssh/sixb_deploy",
76
+ `printf '%s\\n' "$SIXB_DEPLOY_SSH_KEY" > ~/.ssh/sixb_deploy`,
77
+ `printf '%s\\n' "$SIXB_DEPLOY_KNOWN_HOSTS" > ~/.ssh/sixb_known_hosts`,
78
+ "cat >> ~/.ssh/config <<'__SIXB_SSH_CONFIG__'",
79
+ `Host ${input.host}`,
80
+ ` HostName ${input.hostname}`,
81
+ ` Port ${input.port}`,
82
+ " IdentityFile ~/.ssh/sixb_deploy",
83
+ " IdentitiesOnly yes",
84
+ " UserKnownHostsFile ~/.ssh/sixb_known_hosts",
85
+ " StrictHostKeyChecking yes",
86
+ "__SIXB_SSH_CONFIG__",
87
+ ]
88
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export type { SshTargetOptions } from "./ssh-target"
2
+ export { SshTarget } from "./ssh-target"