sofia-deploy 1.0.0__tar.gz

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 (32) hide show
  1. sofia_deploy-1.0.0/LICENSE +21 -0
  2. sofia_deploy-1.0.0/PKG-INFO +107 -0
  3. sofia_deploy-1.0.0/README.md +82 -0
  4. sofia_deploy-1.0.0/pyproject.toml +40 -0
  5. sofia_deploy-1.0.0/setup.cfg +4 -0
  6. sofia_deploy-1.0.0/src/sofia/__init__.py +7 -0
  7. sofia_deploy-1.0.0/src/sofia/__main__.py +4 -0
  8. sofia_deploy-1.0.0/src/sofia/build.py +59 -0
  9. sofia_deploy-1.0.0/src/sofia/cli.py +191 -0
  10. sofia_deploy-1.0.0/src/sofia/config.py +107 -0
  11. sofia_deploy-1.0.0/src/sofia/console.py +78 -0
  12. sofia_deploy-1.0.0/src/sofia/deploy.py +101 -0
  13. sofia_deploy-1.0.0/src/sofia/detect.py +141 -0
  14. sofia_deploy-1.0.0/src/sofia/nginx_setup.py +69 -0
  15. sofia_deploy-1.0.0/src/sofia/node_runtime.py +82 -0
  16. sofia_deploy-1.0.0/src/sofia/packages.py +72 -0
  17. sofia_deploy-1.0.0/src/sofia/ssl_setup.py +61 -0
  18. sofia_deploy-1.0.0/src/sofia/system.py +135 -0
  19. sofia_deploy-1.0.0/src/sofia/systemd_setup.py +52 -0
  20. sofia_deploy-1.0.0/src/sofia/templates/__init__.py +1 -0
  21. sofia_deploy-1.0.0/src/sofia/templates/app.service.tpl +20 -0
  22. sofia_deploy-1.0.0/src/sofia/templates/nginx-proxy-http.conf.tpl +24 -0
  23. sofia_deploy-1.0.0/src/sofia/templates/nginx-proxy-ssl.conf.tpl +45 -0
  24. sofia_deploy-1.0.0/src/sofia/templates/nginx-static-http.conf.tpl +18 -0
  25. sofia_deploy-1.0.0/src/sofia/templates/nginx-static-ssl.conf.tpl +36 -0
  26. sofia_deploy-1.0.0/src/sofia/templates/options-ssl-nginx.conf +6 -0
  27. sofia_deploy-1.0.0/src/sofia/templates_util.py +20 -0
  28. sofia_deploy-1.0.0/src/sofia_deploy.egg-info/PKG-INFO +107 -0
  29. sofia_deploy-1.0.0/src/sofia_deploy.egg-info/SOURCES.txt +30 -0
  30. sofia_deploy-1.0.0/src/sofia_deploy.egg-info/dependency_links.txt +1 -0
  31. sofia_deploy-1.0.0/src/sofia_deploy.egg-info/entry_points.txt +2 -0
  32. sofia_deploy-1.0.0/src/sofia_deploy.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sofia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: sofia-deploy
3
+ Version: 1.0.0
4
+ Summary: Sofia — interactive Linux deployer for Angular / React / Vite / Node apps (nginx + SSL + systemd)
5
+ Author-email: Sofia <sofia@users.noreply.github.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Orbit-it/sofia-deploy
8
+ Project-URL: Documentation, https://github.com/Orbit-it/sofia-deploy#readme
9
+ Project-URL: Issues, https://github.com/Orbit-it/sofia-deploy/issues
10
+ Keywords: deploy,nginx,letsencrypt,systemd,angular,react,vite,nodejs,sofia
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: System :: Systems Administration
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Dynamic: license-file
25
+
26
+ # Sofia
27
+
28
+ Interactive Linux deployer for **Angular**, **React**, **Vite** and **Node.js** apps.
29
+
30
+ SSH into your server, run Sofia, answer a few questions — it installs Node, nginx,
31
+ Let’s Encrypt, systemd, builds your app and goes live.
32
+
33
+ > PyPI name is `sofia-deploy` (`sofia` was already taken).
34
+ > CLI and Python import remain **`sofia`**.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install sofia-deploy
40
+ # or with root for system-wide CLI:
41
+ sudo pip install sofia-deploy
42
+ ```
43
+
44
+ ## Usage (on the target server)
45
+
46
+ ```bash
47
+ cd /path/to/your/app
48
+ sudo sofia
49
+ ```
50
+
51
+ Sofia will:
52
+
53
+ 1. Detect Angular / React / Vite / Node from `package.json`
54
+ 2. Ask domain, SSL email, port, build/start commands
55
+ 3. Install dependencies (Node, nginx, certbot)
56
+ 4. Build the app
57
+ 5. Configure **systemd** + **nginx** reverse proxy (or static hosting)
58
+ 6. Issue a **Let’s Encrypt** certificate
59
+
60
+ ### Non-interactive
61
+
62
+ ```bash
63
+ sudo sofia --non-interactive --config sofia.env
64
+ ```
65
+
66
+ ### Python API
67
+
68
+ ```python
69
+ from sofia import DeployConfig, deploy
70
+
71
+ cfg = DeployConfig(
72
+ project_root="/var/www/myapp",
73
+ app_name="myapp",
74
+ domain="example.com",
75
+ email="admin@example.com",
76
+ framework="vite", # angular | react | vite | node
77
+ serve_mode="static", # static | node
78
+ build_command="npm ci && npm run build",
79
+ static_root="dist",
80
+ enable_ssl=True,
81
+ )
82
+ deploy(cfg)
83
+ ```
84
+
85
+ ## Supported project types
86
+
87
+ | Framework | Typical build | Serve mode |
88
+ |-----------|---------------|------------|
89
+ | Angular | `ng build` | `node` (custom server) or `static` |
90
+ | React (CRA) | `npm run build` | `static` → `build/` |
91
+ | Vite / Vite+React | `npm run build` | `static` → `dist/` |
92
+ | Node API / full stack | custom | `node` → `npm start` / `node server.js` |
93
+
94
+ ## Requirements
95
+
96
+ - Linux (Amazon Linux, Ubuntu, Debian, RHEL/Rocky)
97
+ - Root (`sudo`)
98
+ - DNS A/AAAA pointing to the server
99
+ - Ports **80** and **443** open
100
+
101
+ ## Publish (maintainers)
102
+
103
+ ```bash
104
+ python -m pip install build twine
105
+ python -m build
106
+ twine upload dist/*
107
+ ```
@@ -0,0 +1,82 @@
1
+ # Sofia
2
+
3
+ Interactive Linux deployer for **Angular**, **React**, **Vite** and **Node.js** apps.
4
+
5
+ SSH into your server, run Sofia, answer a few questions — it installs Node, nginx,
6
+ Let’s Encrypt, systemd, builds your app and goes live.
7
+
8
+ > PyPI name is `sofia-deploy` (`sofia` was already taken).
9
+ > CLI and Python import remain **`sofia`**.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install sofia-deploy
15
+ # or with root for system-wide CLI:
16
+ sudo pip install sofia-deploy
17
+ ```
18
+
19
+ ## Usage (on the target server)
20
+
21
+ ```bash
22
+ cd /path/to/your/app
23
+ sudo sofia
24
+ ```
25
+
26
+ Sofia will:
27
+
28
+ 1. Detect Angular / React / Vite / Node from `package.json`
29
+ 2. Ask domain, SSL email, port, build/start commands
30
+ 3. Install dependencies (Node, nginx, certbot)
31
+ 4. Build the app
32
+ 5. Configure **systemd** + **nginx** reverse proxy (or static hosting)
33
+ 6. Issue a **Let’s Encrypt** certificate
34
+
35
+ ### Non-interactive
36
+
37
+ ```bash
38
+ sudo sofia --non-interactive --config sofia.env
39
+ ```
40
+
41
+ ### Python API
42
+
43
+ ```python
44
+ from sofia import DeployConfig, deploy
45
+
46
+ cfg = DeployConfig(
47
+ project_root="/var/www/myapp",
48
+ app_name="myapp",
49
+ domain="example.com",
50
+ email="admin@example.com",
51
+ framework="vite", # angular | react | vite | node
52
+ serve_mode="static", # static | node
53
+ build_command="npm ci && npm run build",
54
+ static_root="dist",
55
+ enable_ssl=True,
56
+ )
57
+ deploy(cfg)
58
+ ```
59
+
60
+ ## Supported project types
61
+
62
+ | Framework | Typical build | Serve mode |
63
+ |-----------|---------------|------------|
64
+ | Angular | `ng build` | `node` (custom server) or `static` |
65
+ | React (CRA) | `npm run build` | `static` → `build/` |
66
+ | Vite / Vite+React | `npm run build` | `static` → `dist/` |
67
+ | Node API / full stack | custom | `node` → `npm start` / `node server.js` |
68
+
69
+ ## Requirements
70
+
71
+ - Linux (Amazon Linux, Ubuntu, Debian, RHEL/Rocky)
72
+ - Root (`sudo`)
73
+ - DNS A/AAAA pointing to the server
74
+ - Ports **80** and **443** open
75
+
76
+ ## Publish (maintainers)
77
+
78
+ ```bash
79
+ python -m pip install build twine
80
+ python -m build
81
+ twine upload dist/*
82
+ ```
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sofia-deploy"
7
+ version = "1.0.0"
8
+ description = "Sofia — interactive Linux deployer for Angular / React / Vite / Node apps (nginx + SSL + systemd)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ authors = [{ name = "Sofia", email = "sofia@users.noreply.github.com" }]
13
+ keywords = ["deploy", "nginx", "letsencrypt", "systemd", "angular", "react", "vite", "nodejs", "sofia"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: POSIX :: Linux",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Topic :: System :: Systems Administration",
25
+ ]
26
+ dependencies = []
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/Orbit-it/sofia-deploy"
30
+ Documentation = "https://github.com/Orbit-it/sofia-deploy#readme"
31
+ Issues = "https://github.com/Orbit-it/sofia-deploy/issues"
32
+
33
+ [project.scripts]
34
+ sofia = "sofia.cli:main"
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
38
+
39
+ [tool.setuptools.package-data]
40
+ sofia = ["templates/*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,7 @@
1
+ """Sofia — interactive deployer for Angular / React / Vite / Node apps."""
2
+
3
+ from .config import DeployConfig
4
+ from .deploy import deploy
5
+
6
+ __all__ = ["DeployConfig", "deploy"]
7
+ __version__ = "1.0.0"
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import stat
5
+ from pathlib import Path
6
+
7
+ from . import console
8
+ from .config import DeployConfig
9
+ from .system import run
10
+
11
+
12
+ def _chown_tree(path: Path, user: str, group: str) -> None:
13
+ try:
14
+ import grp
15
+ import pwd
16
+
17
+ uid = pwd.getpwnam(user).pw_uid
18
+ gid = grp.getgrnam(group).gr_gid
19
+ except KeyError:
20
+ return
21
+ for root, dirs, files in os.walk(path):
22
+ try:
23
+ os.chown(root, uid, gid)
24
+ except FileNotFoundError:
25
+ continue
26
+ for name in dirs + files:
27
+ try:
28
+ os.chown(os.path.join(root, name), uid, gid)
29
+ except FileNotFoundError:
30
+ continue
31
+
32
+
33
+ def build_app(cfg: DeployConfig) -> None:
34
+ app = cfg.app_dir
35
+ assert app is not None
36
+ console.log(f"Build dans {app}…")
37
+ _chown_tree(app, cfg.app_user, cfg.app_group)
38
+
39
+ if cfg.skip_build:
40
+ console.warn("skip_build — build ignoré")
41
+ else:
42
+ user = cfg.app_user if cfg.app_user != "root" else None
43
+ run(
44
+ ["bash", "-lc", f"cd {shlex_path(app)} && {cfg.build_command}"],
45
+ user=user,
46
+ )
47
+
48
+ if cfg.serve_mode == "static":
49
+ index = cfg.static_path / "index.html"
50
+ if not index.exists():
51
+ console.die(
52
+ f"Build incomplet : {index} manquant. "
53
+ "Vérifiez static_root / build_command."
54
+ )
55
+ console.log(f"Static root OK : {cfg.static_path}")
56
+
57
+
58
+ def shlex_path(path: Path) -> str:
59
+ return str(path).replace("'", "'\\''")
@@ -0,0 +1,191 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import os
5
+ from pathlib import Path
6
+
7
+ from . import console
8
+ from .config import DeployConfig
9
+ from .deploy import deploy
10
+ from .detect import FRAMEWORKS, SERVE_MODES, detect_project
11
+
12
+
13
+ def _load_env(path: Path) -> dict[str, str]:
14
+ data: dict[str, str] = {}
15
+ if not path.exists():
16
+ return data
17
+ for line in path.read_text(encoding="utf-8").splitlines():
18
+ line = line.strip()
19
+ if not line or line.startswith("#") or "=" not in line:
20
+ continue
21
+ k, v = line.split("=", 1)
22
+ data[k.strip()] = v.strip().strip('"').strip("'")
23
+ return data
24
+
25
+
26
+ def interactive_config(project_root: Path) -> DeployConfig:
27
+ console.title("Sofia — déploiement interactif")
28
+ print("À lancer sur le serveur cible (SSH + sudo).\n")
29
+
30
+ root = Path(console.ask("Chemin du projet", str(project_root)))
31
+ hints = detect_project(root)
32
+ saved = _load_env(root / "sofia.env")
33
+
34
+ console.log(
35
+ f"Détecté : {hints.framework} · mode {hints.serve_mode} · dir {hints.app_dir}"
36
+ )
37
+
38
+ app_name = console.ask("Nom de l'app (service systemd)", saved.get("APP_NAME") or root.name)
39
+ domain = console.ask("Domaine", saved.get("DOMAIN") or "example.com")
40
+ www = console.ask("Domaine www", saved.get("WWW_DOMAIN") or f"www.{domain.removeprefix('www.')}")
41
+
42
+ framework = console.ask_choice(
43
+ "Framework",
44
+ list(FRAMEWORKS),
45
+ saved.get("FRAMEWORK") or hints.framework,
46
+ )
47
+ serve_mode = console.ask_choice(
48
+ "Mode de service",
49
+ list(SERVE_MODES),
50
+ saved.get("SERVE_MODE") or hints.serve_mode,
51
+ )
52
+
53
+ app_dir = Path(console.ask("Dossier de l'app (package.json)", saved.get("APP_DIR") or str(hints.app_dir)))
54
+ build_command = console.ask("Commande de build", saved.get("BUILD_COMMAND") or hints.build_command)
55
+
56
+ start_command = saved.get("START_COMMAND") or hints.start_command
57
+ static_root = saved.get("STATIC_ROOT") or hints.static_root
58
+ port = int(saved.get("PORT") or "3000")
59
+
60
+ if serve_mode == "node":
61
+ start_command = console.ask("Commande de démarrage", start_command or "npm start")
62
+ port = int(console.ask("Port interne", str(port)))
63
+ else:
64
+ static_root = console.ask("Dossier des fichiers statiques (relatif à l'app)", static_root or "dist")
65
+
66
+ enable_ssl = console.ask_bool(
67
+ "Activer HTTPS (Let's Encrypt) ?",
68
+ saved.get("ENABLE_SSL", "true").lower() != "false",
69
+ )
70
+ email = saved.get("EMAIL", "")
71
+ if enable_ssl:
72
+ email = console.ask("Email Let's Encrypt", email or None)
73
+
74
+ admin_password = saved.get("ADMIN_PASSWORD", "")
75
+ if console.ask_bool("Définir ADMIN_PASSWORD (apps type BrainUp) ?", bool(admin_password)):
76
+ if admin_password and console.ask_bool("Réutiliser le mot de passe enregistré ?", True):
77
+ pass
78
+ else:
79
+ admin_password = console.ask("ADMIN_PASSWORD", secret=True)
80
+
81
+ skip_build = not console.ask_bool("Lancer le build maintenant ?", True)
82
+ app_user = console.ask(
83
+ "Utilisateur système",
84
+ os.environ.get("SUDO_USER") or os.environ.get("USER") or "ec2-user",
85
+ )
86
+
87
+ print()
88
+ console.title("Récapitulatif")
89
+ print(f" app : {app_name}")
90
+ print(f" framework : {framework} / {serve_mode}")
91
+ print(f" root : {root}")
92
+ print(f" app_dir : {app_dir}")
93
+ print(f" domain : {domain}")
94
+ print(f" SSL : {'oui' if enable_ssl else 'non'}")
95
+ print(f" build : {build_command}")
96
+ if serve_mode == "node":
97
+ print(f" start : {start_command} (:{port})")
98
+ else:
99
+ print(f" static : {static_root}")
100
+ print()
101
+ if not console.ask_bool("Confirmer le déploiement ?", True):
102
+ console.warn("Annulé.")
103
+ raise SystemExit(0)
104
+
105
+ return DeployConfig(
106
+ project_root=root,
107
+ app_name=app_name,
108
+ domain=domain,
109
+ www_domain=www,
110
+ email=email,
111
+ port=port,
112
+ framework=framework,
113
+ serve_mode=serve_mode,
114
+ app_dir=app_dir,
115
+ build_command=build_command,
116
+ start_command=start_command,
117
+ static_root=static_root,
118
+ enable_ssl=enable_ssl,
119
+ skip_build=skip_build,
120
+ app_user=app_user,
121
+ admin_password=admin_password,
122
+ token_secret=saved.get("TOKEN_SECRET", ""),
123
+ )
124
+
125
+
126
+ def config_from_env(project_root: Path, env: dict[str, str], *, skip_ssl: bool, skip_build: bool) -> DeployConfig:
127
+ enable_ssl = env.get("ENABLE_SSL", "true").lower() != "false" and not skip_ssl
128
+ if not env.get("DOMAIN"):
129
+ console.die("DOMAIN manquant dans sofia.env")
130
+ if enable_ssl and not env.get("EMAIL"):
131
+ console.die("EMAIL manquant dans sofia.env")
132
+ return DeployConfig(
133
+ project_root=project_root,
134
+ app_name=env.get("APP_NAME") or project_root.name,
135
+ domain=env["DOMAIN"],
136
+ www_domain=env.get("WWW_DOMAIN", ""),
137
+ email=env.get("EMAIL", ""),
138
+ port=int(env.get("PORT", "3000")),
139
+ framework=env.get("FRAMEWORK", "node"),
140
+ serve_mode=env.get("SERVE_MODE", "node"),
141
+ app_dir=Path(env["APP_DIR"]) if env.get("APP_DIR") else None,
142
+ build_command=env.get("BUILD_COMMAND", "npm ci || npm install"),
143
+ start_command=env.get("START_COMMAND", "npm start"),
144
+ static_root=env.get("STATIC_ROOT", "dist"),
145
+ enable_ssl=enable_ssl,
146
+ skip_build=skip_build,
147
+ admin_password=env.get("ADMIN_PASSWORD", ""),
148
+ token_secret=env.get("TOKEN_SECRET", ""),
149
+ )
150
+
151
+
152
+ def main(argv: list[str] | None = None) -> int:
153
+ parser = argparse.ArgumentParser(
154
+ prog="sofia",
155
+ description="Sofia — déploiement interactif Angular / React / Vite / Node.",
156
+ )
157
+ parser.add_argument("--repo", "--project", dest="project", type=Path, help="Chemin du projet")
158
+ parser.add_argument("--config", type=Path, help="Fichier sofia.env")
159
+ parser.add_argument("--non-interactive", action="store_true")
160
+ parser.add_argument("--skip-ssl", action="store_true")
161
+ parser.add_argument("--skip-build", action="store_true")
162
+ args = parser.parse_args(argv)
163
+
164
+ project = (args.project or Path.cwd()).resolve()
165
+ env_path = args.config or (project / "sofia.env")
166
+ env = _load_env(env_path)
167
+
168
+ if args.non_interactive:
169
+ if not env:
170
+ console.die(f"--non-interactive : config introuvable ({env_path})")
171
+ cfg = config_from_env(project, env, skip_ssl=args.skip_ssl, skip_build=args.skip_build)
172
+ else:
173
+ cfg = interactive_config(project)
174
+ if args.skip_ssl:
175
+ cfg.enable_ssl = False
176
+ if args.skip_build:
177
+ cfg.skip_build = True
178
+
179
+ try:
180
+ deploy(cfg)
181
+ except KeyboardInterrupt:
182
+ console.warn("Interrompu.")
183
+ return 130
184
+ except Exception as exc: # noqa: BLE001
185
+ console.error(str(exc))
186
+ return 1
187
+ return 0
188
+
189
+
190
+ if __name__ == "__main__":
191
+ raise SystemExit(main())
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ import grp
4
+ import os
5
+ import pwd
6
+ import re
7
+ import secrets
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+
11
+
12
+ def _slug(name: str) -> str:
13
+ slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
14
+ return slug or "app"
15
+
16
+
17
+ @dataclass
18
+ class DeployConfig:
19
+ project_root: Path
20
+ app_name: str = ""
21
+ domain: str = ""
22
+ www_domain: str = ""
23
+ email: str = ""
24
+ port: int = 3000
25
+ framework: str = "node" # angular | react | vite | node
26
+ serve_mode: str = "node" # node | static
27
+ app_dir: Path | None = None
28
+ build_command: str = "npm ci || npm install"
29
+ start_command: str = "npm start"
30
+ static_root: str = "dist"
31
+ enable_ssl: bool = True
32
+ skip_build: bool = False
33
+ app_user: str = ""
34
+ app_group: str = ""
35
+ node_bin: str = ""
36
+ node_version: str = "20.18.2"
37
+ env_vars: dict[str, str] = field(default_factory=dict)
38
+ # optional secrets commonly needed
39
+ admin_password: str = ""
40
+ token_secret: str = ""
41
+
42
+ def __post_init__(self) -> None:
43
+ self.project_root = Path(self.project_root).resolve()
44
+ if self.app_dir is None:
45
+ self.app_dir = self.project_root
46
+ else:
47
+ self.app_dir = Path(self.app_dir).resolve()
48
+ if not self.app_name:
49
+ self.app_name = _slug(self.project_root.name)
50
+ else:
51
+ self.app_name = _slug(self.app_name)
52
+ if not self.www_domain and self.domain:
53
+ self.www_domain = f"www.{self.domain.removeprefix('www.')}"
54
+ if not self.token_secret:
55
+ self.token_secret = secrets.token_hex(32)
56
+ if not self.app_user:
57
+ candidate = os.environ.get("SUDO_USER") or os.environ.get("USER") or "ec2-user"
58
+ try:
59
+ pwd.getpwnam(candidate)
60
+ self.app_user = candidate
61
+ except KeyError:
62
+ self.app_user = "root"
63
+ if not self.app_group:
64
+ try:
65
+ gid = pwd.getpwnam(self.app_user).pw_gid
66
+ self.app_group = grp.getgrgid(gid).gr_name
67
+ except KeyError:
68
+ self.app_group = "root"
69
+ # Inject common env
70
+ self.env_vars.setdefault("NODE_ENV", "production")
71
+ self.env_vars.setdefault("PORT", str(self.port))
72
+ if self.admin_password:
73
+ self.env_vars.setdefault("ADMIN_PASSWORD", self.admin_password)
74
+ if self.token_secret:
75
+ self.env_vars.setdefault("TOKEN_SECRET", self.token_secret)
76
+
77
+ @property
78
+ def service_name(self) -> str:
79
+ return self.app_name
80
+
81
+ @property
82
+ def env_system(self) -> Path:
83
+ return Path(f"/etc/sofia/{self.app_name}/env")
84
+
85
+ @property
86
+ def nginx_site(self) -> str:
87
+ return self.app_name
88
+
89
+ @property
90
+ def static_path(self) -> Path:
91
+ return (self.app_dir / self.static_root).resolve()
92
+
93
+ @property
94
+ def config_local(self) -> Path:
95
+ return self.project_root / "sofia.env"
96
+
97
+ def validate(self) -> None:
98
+ if not self.domain:
99
+ raise ValueError("domain obligatoire")
100
+ if self.enable_ssl and not self.email:
101
+ raise ValueError("email obligatoire si SSL activé")
102
+ if not self.app_dir or not self.app_dir.is_dir():
103
+ raise ValueError(f"app_dir introuvable : {self.app_dir}")
104
+ if self.serve_mode not in {"node", "static"}:
105
+ raise ValueError("serve_mode doit être 'node' ou 'static'")
106
+ if self.serve_mode == "node" and not self.start_command:
107
+ raise ValueError("start_command obligatoire en mode node")