msingi 0.1.0a1__py3-none-any.whl

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.
msingi/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ # ramani: src/msingi/__init__.py
2
+ """msingi (Swahili for "foundation"): lay the foundation of an Ubuntu server over SSH."""
3
+
4
+ from .cli import main
5
+ from .runner import provision
6
+ from .settings import Settings
7
+
8
+ __all__ = ["Settings", "main", "provision"]
msingi/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ # ramani: src/msingi/__main__.py
2
+ """Allow ``python -m msingi``."""
3
+
4
+ from .cli import main
5
+
6
+ raise SystemExit(main())
msingi/account.py ADDED
@@ -0,0 +1,93 @@
1
+ # ramani: src/msingi/account.py
2
+ """Create the user to set up, give it sudo if asked, and let it log in with a key."""
3
+
4
+ from . import output, ssh
5
+ from .settings import Settings
6
+ from .ssh import Connection
7
+
8
+
9
+ def ensure_user(conn: Connection, settings: Settings) -> None:
10
+ """Create the target user if missing, then apply the sudo and public key options.
11
+
12
+ Runs as the admin connection. On a dry run it only says what it would do.
13
+
14
+ Examples::
15
+
16
+ ensure_user(admin, settings) # ✅ User developer already exists
17
+ """
18
+ user = settings.target_user
19
+
20
+ if ssh.succeeds(conn, ["id", user]):
21
+ output.ok(f"User {user} already exists")
22
+ elif settings.dry_run:
23
+ output.dry(f"create user: {user}")
24
+ else:
25
+ output.step(f"🔧 Creating user: {user}")
26
+ ssh.run(conn, ["useradd", "-m", "-s", "/bin/bash", user], sudo=True)
27
+ output.ok(f"User {user} created successfully")
28
+
29
+ if settings.make_user_sudo:
30
+ grant_sudo(conn, settings)
31
+ if settings.ssh_public_key:
32
+ add_public_key(conn, settings)
33
+
34
+
35
+ def grant_sudo(conn: Connection, settings: Settings) -> None:
36
+ """Add the user to the sudo group with passwordless sudo.
37
+
38
+ Examples::
39
+
40
+ grant_sudo(admin, settings) # writes /etc/sudoers.d/developer
41
+ """
42
+ user = settings.target_user
43
+ if settings.dry_run:
44
+ output.dry(f"grant sudo privileges to: {user}")
45
+ return
46
+
47
+ output.step(f"🔧 Ensuring {user} is a sudoer")
48
+ ssh.run(conn, ["usermod", "-aG", "sudo", user], sudo=True)
49
+ sudoers = f"/etc/sudoers.d/{user}"
50
+ ssh.run(conn, ["tee", sudoers], sudo=True, input=f"{user} ALL=(ALL) NOPASSWD:ALL\n")
51
+ ssh.run(conn, ["chmod", "440", sudoers], sudo=True)
52
+ output.ok(f"{user} has sudo privileges")
53
+
54
+
55
+ def home_of(conn: Connection, user: str) -> str:
56
+ """Look up a user's home directory.
57
+
58
+ Examples::
59
+
60
+ home_of(admin, "developer") # "/home/developer"
61
+ """
62
+ entry = ssh.run(conn, ["getent", "passwd", user]).stdout.strip()
63
+ return entry.split(":")[5]
64
+
65
+
66
+ def add_public_key(conn: Connection, settings: Settings) -> None:
67
+ """Add the public key to the user's ``authorized_keys`` unless it is already there.
68
+
69
+ Examples::
70
+
71
+ add_public_key(admin, settings) # ✅ Public key added
72
+ """
73
+ user, key = settings.target_user, settings.ssh_public_key.strip()
74
+ if settings.dry_run:
75
+ output.dry(f"add SSH public key for {user}")
76
+ return
77
+
78
+ output.step(f"🔑 Adding SSH public key for {user}")
79
+ ssh_dir = f"{home_of(conn, user)}/.ssh"
80
+ authorized = f"{ssh_dir}/authorized_keys"
81
+
82
+ ssh.run(conn, ["mkdir", "-p", ssh_dir], sudo=True)
83
+ current = ssh.run(conn, ["cat", authorized], sudo=True, check=False).stdout
84
+ if key in (line.strip() for line in current.splitlines()):
85
+ output.ok("Public key already exists")
86
+ else:
87
+ separator = "" if not current or current.endswith("\n") else "\n"
88
+ ssh.run(conn, ["tee", "-a", authorized], sudo=True, input=f"{separator}{key}\n")
89
+ output.ok("Public key added")
90
+
91
+ ssh.run(conn, ["chmod", "700", ssh_dir], sudo=True)
92
+ ssh.run(conn, ["chmod", "600", authorized], sudo=True)
93
+ ssh.run(conn, ["chown", "-R", f"{user}:{user}", ssh_dir], sudo=True)
msingi/cli.py ADDED
@@ -0,0 +1,178 @@
1
+ # ramani: src/msingi/cli.py
2
+ """Command-line interface."""
3
+
4
+ import argparse
5
+ import os
6
+ from pathlib import Path
7
+
8
+ from . import output, runner
9
+ from .errors import MsingiError
10
+ from .modules import MODULES
11
+ from .profiles import PROFILES, choose
12
+ from .settings import DEFAULT_NVM_VERSION, KEY_PREFIXES, Settings
13
+
14
+
15
+ def _version() -> str:
16
+ """Return the installed version, or "unknown" if msingi isn't installed.
17
+
18
+ Examples::
19
+
20
+ _version() # "0.1.0"
21
+ """
22
+ from importlib.metadata import (
23
+ PackageNotFoundError,
24
+ version,
25
+ ) # slow, only needed here
26
+
27
+ try:
28
+ return version("msingi")
29
+ except PackageNotFoundError:
30
+ return "unknown"
31
+
32
+
33
+ def _epilog() -> str:
34
+ """List the profiles and modules for ``--help``."""
35
+ profiles = "\n".join(f" {name:<8}{label}" for name, (label, _) in PROFILES.items())
36
+ names = "\n".join(
37
+ f" {module.NAME:<12}{'system (sudo)' if module.SYSTEM else 'user':<15}{module.TITLE}"
38
+ for module in MODULES
39
+ )
40
+ return f"profiles (--profile):\n{profiles}\n\nmodules (--modules):\n{names}"
41
+
42
+
43
+ def _parser() -> argparse.ArgumentParser:
44
+ """Build the argument parser."""
45
+ p = argparse.ArgumentParser(
46
+ prog="msingi",
47
+ description="Lay the foundation of an Ubuntu server over SSH: pick a profile and only the modules you chose are set up.",
48
+ epilog=_epilog(),
49
+ formatter_class=argparse.RawDescriptionHelpFormatter,
50
+ )
51
+ p.add_argument("host", help="server IP address or hostname")
52
+ p.add_argument("user", help="user to set up (created if it doesn't exist)")
53
+ p.add_argument("-p", "--port", type=int, default=22, help="SSH port (default: 22)")
54
+ p.add_argument(
55
+ "-k",
56
+ "--key",
57
+ type=Path,
58
+ default=os.environ.get("MSINGI_SSH_KEY"),
59
+ metavar="FILE",
60
+ help="private key to log in with (also MSINGI_SSH_KEY; default: ssh's own keys and agent)",
61
+ )
62
+ p.add_argument(
63
+ "-s",
64
+ "--sudo-user",
65
+ default=os.environ.get("MSINGI_SUDO_USER"),
66
+ metavar="USER",
67
+ help="existing user with passwordless sudo, used for system modules (also MSINGI_SUDO_USER)",
68
+ )
69
+ p.add_argument(
70
+ "--make-sudo",
71
+ action="store_true",
72
+ help="give the user passwordless sudo (new or existing)",
73
+ )
74
+ p.add_argument(
75
+ "--public-key",
76
+ metavar="KEY_OR_FILE",
77
+ help="public key (or a .pub file) to add to the user's authorized_keys",
78
+ )
79
+ p.add_argument(
80
+ "-P",
81
+ "--profile",
82
+ choices=list(PROFILES),
83
+ help="what to set up (default: full)",
84
+ )
85
+ p.add_argument(
86
+ "-m",
87
+ "--modules",
88
+ metavar="NAME[,NAME...]",
89
+ help="set up only these modules (custom profile)",
90
+ )
91
+ p.add_argument("--git-name", metavar="NAME", help="Git user name (git-ssh module)")
92
+ p.add_argument(
93
+ "--git-email", metavar="EMAIL", help="Git user email (git-ssh module)"
94
+ )
95
+ p.add_argument(
96
+ "--nvm-version",
97
+ default=os.environ.get("MSINGI_NVM_VERSION", DEFAULT_NVM_VERSION),
98
+ metavar="TAG",
99
+ help=f"nvm release to install (default: {DEFAULT_NVM_VERSION}; also MSINGI_NVM_VERSION)",
100
+ )
101
+ p.add_argument(
102
+ "-c",
103
+ "--copy",
104
+ action="store_true",
105
+ help="copy the new Git public key to your clipboard (git-ssh module)",
106
+ )
107
+ p.add_argument(
108
+ "-n",
109
+ "--dry-run",
110
+ action="store_true",
111
+ help="show what would happen, change nothing on the server",
112
+ )
113
+ p.add_argument("-V", "--version", action="version", version=f"msingi {_version()}")
114
+ return p
115
+
116
+
117
+ def read_public_key(value: str) -> str:
118
+ """Accept a public key as text or as the path of a ``.pub`` file.
119
+
120
+ Examples::
121
+
122
+ read_public_key("ssh-ed25519 AAAA... ada@laptop") # same text
123
+ read_public_key("~/.ssh/id_ed25519.pub") # the file's contents
124
+ """
125
+ value = value.strip()
126
+ if not value or value.startswith(KEY_PREFIXES):
127
+ return value
128
+ path = Path(value).expanduser()
129
+ if not path.is_file():
130
+ raise MsingiError(f"public key file not found: {value}")
131
+ return path.read_text(encoding="utf-8").strip()
132
+
133
+
134
+ def build_settings(args: argparse.Namespace) -> Settings:
135
+ """Turn parsed arguments into ``Settings``.
136
+
137
+ Examples::
138
+
139
+ build_settings(_parser().parse_args(["203.0.113.10", "dev", "-m", "nginx"]))
140
+ """
141
+ names = [name.strip() for name in (args.modules or "").split(",") if name.strip()]
142
+ profile, modules = choose(args.profile, names)
143
+ return Settings(
144
+ host=args.host,
145
+ target_user=args.user,
146
+ port=args.port,
147
+ key=args.key.expanduser() if args.key else None,
148
+ sudo_user=args.sudo_user or "",
149
+ make_user_sudo=args.make_sudo,
150
+ ssh_public_key=read_public_key(args.public_key or ""),
151
+ profile=profile,
152
+ modules=modules,
153
+ git_user_name=args.git_name or "",
154
+ git_user_email=args.git_email or "",
155
+ nvm_version=args.nvm_version,
156
+ copy_key=args.copy,
157
+ dry_run=args.dry_run,
158
+ )
159
+
160
+
161
+ def main(argv: list[str] | None = None) -> int:
162
+ """Run the CLI and return the exit code."""
163
+ parser = _parser()
164
+ args = parser.parse_args(argv)
165
+ try:
166
+ settings = build_settings(args)
167
+ except MsingiError as err:
168
+ parser.error(str(err))
169
+
170
+ try:
171
+ runner.provision(settings)
172
+ except MsingiError as err:
173
+ output.fail(f"msingi: {err}")
174
+ return 1
175
+ except KeyboardInterrupt:
176
+ output.fail("msingi: interrupted")
177
+ return 130
178
+ return 0
msingi/clipboard.py ADDED
@@ -0,0 +1,24 @@
1
+ # ramani: src/msingi/clipboard.py
2
+ """Copy text to the clipboard with pyperclip."""
3
+
4
+ from .errors import MsingiError
5
+
6
+
7
+ def copy(text: str) -> None:
8
+ """Copy ``text``; raises MsingiError with a readable reason on failure.
9
+
10
+ On Linux the clipboard needs ``xclip``, ``xsel`` or ``wl-clipboard`` installed.
11
+
12
+ Examples::
13
+
14
+ copy("ssh-ed25519 AAAAC3Nz... ada@example.com") # None
15
+ copy("text") # MsingiError: no clipboard available: ...
16
+ """
17
+ try:
18
+ import pyperclip # only needed when --copy is used
19
+ except ImportError:
20
+ raise MsingiError("pyperclip is not installed (uv add pyperclip)") from None
21
+ try:
22
+ pyperclip.copy(text)
23
+ except pyperclip.PyperclipException as err:
24
+ raise MsingiError(f"no clipboard available: {err}") from None
msingi/errors.py ADDED
@@ -0,0 +1,6 @@
1
+ # ramani: src/msingi/errors.py
2
+ """The one error type msingi shows as a plain message instead of a traceback."""
3
+
4
+
5
+ class MsingiError(Exception):
6
+ """A problem the user can fix, such as bad input or a failed command on the server."""
@@ -0,0 +1,39 @@
1
+ # ramani: src/msingi/modules/__init__.py
2
+ """The setup modules, in the order they run.
3
+
4
+ Each module has ``NAME`` (used on the command line), ``TITLE`` (shown in the run),
5
+ ``SYSTEM`` (True when it needs sudo) and ``setup(conn, settings)``.
6
+ """
7
+
8
+ from collections.abc import Iterable
9
+ from types import ModuleType
10
+
11
+ from ..errors import MsingiError
12
+ from . import certbot, git_ssh, nginx, nvm, openssh_ufw, packages, postgres, repos, uv
13
+
14
+ MODULES: tuple[ModuleType, ...] = (
15
+ openssh_ufw,
16
+ packages,
17
+ nginx,
18
+ certbot,
19
+ postgres,
20
+ uv,
21
+ nvm,
22
+ repos,
23
+ git_ssh,
24
+ )
25
+ NAMES = tuple(module.NAME for module in MODULES)
26
+
27
+
28
+ def by_name(names: Iterable[str]) -> list[ModuleType]:
29
+ """Pick modules by name, always in running order.
30
+
31
+ Examples::
32
+
33
+ [m.NAME for m in by_name(["nvm", "nginx"])] # ["nginx", "nvm"]
34
+ by_name(["nope"]) # MsingiError: unknown module: nope
35
+ """
36
+ wanted = set(names)
37
+ if unknown := wanted - set(NAMES):
38
+ raise MsingiError(f"unknown module: {', '.join(sorted(unknown))}")
39
+ return [module for module in MODULES if module.NAME in wanted]
@@ -0,0 +1,48 @@
1
+ # ramani: src/msingi/modules/certbot.py
2
+ """Install Certbot through snap."""
3
+
4
+ from .. import output, ssh
5
+ from ..errors import MsingiError
6
+ from ..settings import Settings
7
+ from ..ssh import Connection
8
+
9
+ NAME = "certbot"
10
+ TITLE = "Certbot"
11
+ SYSTEM = True
12
+
13
+
14
+ def setup(conn: Connection, settings: Settings) -> None:
15
+ """Install the Certbot snap and link it to ``/usr/bin/certbot``.
16
+
17
+ Needs snapd, which the packages module installs.
18
+
19
+ Examples::
20
+
21
+ setup(conn, settings) # ✅ Certbot installed successfully
22
+ """
23
+ if not ssh.command_exists(conn, "snap", sudo=True):
24
+ raise MsingiError("snapd is not installed (run the packages module first)")
25
+
26
+ if ssh.succeeds(conn, ["snap", "list", "certbot"], sudo=True):
27
+ output.ok("Certbot already installed")
28
+ return
29
+
30
+ ssh.run(conn, ["snap", "install", "core"], sudo=True, stream=True)
31
+ ssh.run(conn, ["snap", "refresh", "core"], sudo=True, stream=True)
32
+ remove_apt_certbot(conn)
33
+ ssh.run(conn, ["snap", "install", "--classic", "certbot"], sudo=True, stream=True)
34
+ ssh.run(conn, ["ln", "-sf", "/snap/bin/certbot", "/usr/bin/certbot"], sudo=True)
35
+ output.ok("Certbot installed successfully")
36
+
37
+
38
+ def remove_apt_certbot(conn: Connection) -> None:
39
+ """Remove the apt build of Certbot, which would clash with the snap."""
40
+ command = [
41
+ "env",
42
+ "DEBIAN_FRONTEND=noninteractive",
43
+ "apt-get",
44
+ "remove",
45
+ "-y",
46
+ "certbot",
47
+ ]
48
+ ssh.run(conn, command, sudo=True, check=False)
@@ -0,0 +1,82 @@
1
+ # ramani: src/msingi/modules/git_ssh.py
2
+ """Set the global Git identity and create an SSH key to give to GitHub or GitLab."""
3
+
4
+ import shlex
5
+
6
+ from .. import output, ssh
7
+ from ..errors import MsingiError
8
+ from ..settings import Settings
9
+ from ..ssh import Connection
10
+
11
+ NAME = "git-ssh"
12
+ TITLE = "Git and SSH"
13
+ SYSTEM = False
14
+
15
+ KEY_PATH = "$HOME/.ssh/id_ed25519"
16
+
17
+
18
+ def setup(conn: Connection, settings: Settings) -> None:
19
+ """Configure Git, make ``~/.ssh``, create the key if absent, and make the SSH config.
20
+
21
+ Examples::
22
+
23
+ setup(user_conn, settings) # ✅ Generated new SSH key
24
+ """
25
+ for tool in ("git", "ssh-keygen"):
26
+ if not ssh.command_exists(conn, tool):
27
+ raise MsingiError(f"{tool} command not found")
28
+
29
+ configure_git(conn, settings.git_user_name, settings.git_user_email)
30
+ ssh.run(conn, 'mkdir -p "$HOME/.ssh" && chmod 700 "$HOME/.ssh"')
31
+ create_key(conn, settings.git_user_email)
32
+ create_config(conn)
33
+
34
+
35
+ def configure_git(conn: Connection, name: str, email: str) -> None:
36
+ """Set the global Git name and email (safe to repeat).
37
+
38
+ Examples::
39
+
40
+ configure_git(conn, "Ada Lovelace", "ada@example.com")
41
+ """
42
+ ssh.run(conn, ["git", "config", "--global", "user.name", name])
43
+ ssh.run(conn, ["git", "config", "--global", "user.email", email])
44
+ output.ok(f"Git configured with name: {name}")
45
+ output.ok(f"Git configured with email: {email}")
46
+
47
+
48
+ def create_key(conn: Connection, email: str) -> None:
49
+ """Generate an ed25519 key without a passphrase unless one exists.
50
+
51
+ Examples::
52
+
53
+ create_key(conn, "ada@example.com") # ✅ SSH key already exists
54
+ """
55
+ if ssh.succeeds(conn, f'test -f "{KEY_PATH}"'):
56
+ output.ok("SSH key already exists")
57
+ return
58
+
59
+ output.warn("Generating new SSH key...")
60
+ ssh.run(
61
+ conn, f'ssh-keygen -t ed25519 -C {shlex.quote(email)} -N "" -f "{KEY_PATH}"'
62
+ )
63
+ ssh.run(conn, f'chmod 600 "{KEY_PATH}" && chmod 644 "{KEY_PATH}.pub"')
64
+ output.ok("Generated new SSH key")
65
+
66
+
67
+ def create_config(conn: Connection) -> None:
68
+ """Create an empty ``~/.ssh/config`` unless it exists."""
69
+ config = '"$HOME/.ssh/config"'
70
+ if not ssh.succeeds(conn, f"test -f {config}"):
71
+ ssh.run(conn, f"touch {config} && chmod 600 {config}")
72
+ output.ok("Created SSH config file")
73
+
74
+
75
+ def public_key(conn: Connection) -> str:
76
+ """Read the public half of the key, ready to paste into GitHub or GitLab.
77
+
78
+ Examples::
79
+
80
+ public_key(conn) # "ssh-ed25519 AAAAC3Nz... ada@example.com"
81
+ """
82
+ return ssh.run(conn, f'cat "{KEY_PATH}.pub"').stdout.strip()
@@ -0,0 +1,76 @@
1
+ # ramani: src/msingi/modules/nginx.py
2
+ """Install Nginx, open it in the firewall, and add a reusable proxy snippet."""
3
+
4
+ from .. import output, ssh, system
5
+ from ..settings import Settings
6
+ from ..ssh import Connection
7
+
8
+ NAME = "nginx"
9
+ TITLE = "Nginx"
10
+ SYSTEM = True
11
+
12
+ SNIPPET_PATH = "/etc/nginx/snippets/port-proxy.conf"
13
+ SNIPPET = """\
14
+ location / {
15
+ proxy_pass http://127.0.0.1:$upstream_port;
16
+ include proxy_params;
17
+ proxy_http_version 1.1;
18
+ proxy_set_header Upgrade $http_upgrade;
19
+ proxy_set_header Connection "upgrade";
20
+ proxy_cache_bypass $http_upgrade;
21
+ }
22
+ """
23
+
24
+
25
+ def setup(conn: Connection, settings: Settings) -> None:
26
+ """Install Nginx, allow it in UFW, start it, write the proxy snippet and test the config.
27
+
28
+ Examples::
29
+
30
+ setup(conn, settings) # ✅ Nginx is running
31
+ """
32
+ install(conn)
33
+ open_firewall(conn)
34
+ system.enable_and_start(conn, "nginx")
35
+ output.ok("Nginx is running")
36
+ write_snippet(conn)
37
+ test_config(conn)
38
+
39
+
40
+ def install(conn: Connection) -> None:
41
+ """Install Nginx unless it is already there."""
42
+ if ssh.command_exists(conn, "nginx", sudo=True):
43
+ output.ok("Nginx already installed")
44
+ else:
45
+ system.apt_install(conn, "nginx")
46
+
47
+
48
+ def open_firewall(conn: Connection) -> None:
49
+ """Allow 'Nginx Full' (ports 80 and 443) in UFW, if UFW can be used."""
50
+ if system.ensure_ufw(conn) and not system.ufw_has_rule(conn, "Nginx Full"):
51
+ system.ufw_allow(conn, "Nginx Full")
52
+
53
+
54
+ def write_snippet(conn: Connection) -> None:
55
+ """Write ``port-proxy.conf`` unless it already holds the same text.
56
+
57
+ Examples::
58
+
59
+ write_snippet(conn) # ✅ Wrote /etc/nginx/snippets/port-proxy.conf
60
+ """
61
+ current = ssh.run(conn, ["cat", SNIPPET_PATH], sudo=True, check=False).stdout
62
+ if current == SNIPPET:
63
+ output.ok(f"{SNIPPET_PATH} is up to date")
64
+ return
65
+ ssh.run(conn, ["mkdir", "-p", "/etc/nginx/snippets"], sudo=True)
66
+ ssh.run(conn, ["tee", SNIPPET_PATH], sudo=True, input=SNIPPET)
67
+ output.ok(f"Wrote {SNIPPET_PATH}")
68
+
69
+
70
+ def test_config(conn: Connection) -> None:
71
+ """Run ``nginx -t`` and warn, without failing, if the configuration is invalid."""
72
+ if ssh.succeeds(conn, ["nginx", "-t"], sudo=True):
73
+ output.ok("Nginx configuration is valid")
74
+ else:
75
+ output.warn("Nginx configuration test failed")
76
+ output.note("You may need to check /etc/nginx/nginx.conf")
msingi/modules/nvm.py ADDED
@@ -0,0 +1,63 @@
1
+ # ramani: src/msingi/modules/nvm.py
2
+ """Install nvm for the target user, then the latest Node.js."""
3
+
4
+ from .. import output, ssh
5
+ from ..settings import Settings
6
+ from ..ssh import Connection
7
+
8
+ NAME = "nvm"
9
+ TITLE = "nvm"
10
+ SYSTEM = False
11
+
12
+ LOAD_NVM = 'export NVM_DIR="$HOME/.nvm"; . "$NVM_DIR/nvm.sh"; '
13
+ MANUAL_HINT = "You can install Node.js manually after restarting your shell with: nvm install node"
14
+
15
+
16
+ def setup(conn: Connection, settings: Settings) -> None:
17
+ """Install nvm (the version in ``settings.nvm_version``), then Node.js.
18
+
19
+ Examples::
20
+
21
+ setup(user_conn, settings) # ✅ Node.js installed successfully with nvm
22
+ """
23
+ install_nvm(conn, settings.nvm_version)
24
+ if not ssh.succeeds(conn, 'test -s "$HOME/.nvm/nvm.sh"'):
25
+ output.warn("nvm.sh not found")
26
+ output.note(MANUAL_HINT)
27
+ return
28
+ install_node(conn)
29
+
30
+
31
+ def install_nvm(conn: Connection, version: str) -> None:
32
+ """Install nvm with its official script unless ``~/.nvm`` exists."""
33
+ if ssh.succeeds(conn, 'test -d "$HOME/.nvm"'):
34
+ output.ok("nvm already installed")
35
+ return
36
+ url = f"https://raw.githubusercontent.com/nvm-sh/nvm/{version}/install.sh"
37
+ ssh.run(conn, f"set -o pipefail; curl -o- {url} | bash", stream=True)
38
+
39
+
40
+ def install_node(conn: Connection) -> None:
41
+ """Install the latest Node.js unless nvm already has one, then update npm.
42
+
43
+ ``nvm version node`` prints ``N/A`` when no Node.js is installed.
44
+
45
+ Examples::
46
+
47
+ install_node(conn) # ✅ Node.js already installed with nvm
48
+ """
49
+ current = ssh.run(conn, LOAD_NVM + "nvm version node", check=False).stdout.strip()
50
+ if current not in ("", "N/A"):
51
+ output.ok("Node.js already installed with nvm")
52
+ return
53
+
54
+ output.step("Installing Node.js with nvm...")
55
+ result = ssh.run(conn, LOAD_NVM + "nvm install node", check=False, stream=True)
56
+ if result.returncode != 0:
57
+ output.warn("Failed to install Node.js in this session")
58
+ output.note(MANUAL_HINT)
59
+ return
60
+ output.ok("Node.js installed successfully with nvm")
61
+
62
+ if ssh.succeeds(conn, LOAD_NVM + "npm install -g npm@latest"):
63
+ output.ok("npm updated successfully")