baro 0.1.0__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.
baro/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """baro: 폐쇄망·내부망 Windows PC용 Python 앱 번들 빌드 도구."""
2
+
3
+ __version__ = "0.1.0"
baro/allowlist.py ADDED
@@ -0,0 +1,44 @@
1
+ """허용 목록(화이트리스트) 제품에 넘길 실행 파일 목록.
2
+
3
+ 허용 목록 제품은 주로 PE(.exe/.dll/.pyd)를 통제한다. 각 PE에 대해 서명 상태를 붙여
4
+ - 게시자 규칙으로 처리 가능한 것(유효한 Authenticode 서명)
5
+ - 해시 규칙이 필요한 것(미서명)
6
+ 을 나눈다. 제품별 import 형식(AhnLab EPS, TXOne, WDAC 등)은 이후 어댑터로 추가한다.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import csv
11
+ from pathlib import Path
12
+
13
+ from . import authenticode
14
+ from .util import is_pe, sha256_file
15
+
16
+
17
+ def export(bundle: Path, out_dir: Path) -> dict:
18
+ out_dir.mkdir(parents=True, exist_ok=True)
19
+ pes = sorted(p for p in bundle.rglob("*") if p.is_file() and is_pe(p))
20
+ sigs = authenticode.check(pes)
21
+ rows = []
22
+ for p in pes:
23
+ s = sigs[p]
24
+ rows.append({"path": p.relative_to(bundle).as_posix(), "sha256": sha256_file(p).upper(),
25
+ "size": p.stat().st_size, "authenticode": s.status, "signer": s.signer,
26
+ "rule": "publisher" if s.valid else "hash"})
27
+ with open(out_dir / "pe_files.csv", "w", newline="", encoding="utf-8-sig") as f:
28
+ w = csv.DictWriter(f, fieldnames=list(rows[0].keys()) if rows else ["path"])
29
+ w.writeheader()
30
+ w.writerows(rows)
31
+ by_signer: dict[str, int] = {}
32
+ for r in rows:
33
+ if r["rule"] == "publisher":
34
+ by_signer[r["signer"]] = by_signer.get(r["signer"], 0) + 1
35
+ summary = {"pe_files": len(rows), "publisher_rule": sum(r["rule"] == "publisher" for r in rows),
36
+ "hash_rule": sum(r["rule"] == "hash" for r in rows), "publishers": by_signer,
37
+ "csv": str(out_dir / "pe_files.csv")}
38
+ lines = [f"PE 파일 {summary['pe_files']}개",
39
+ f" 게시자 규칙 가능(유효 서명): {summary['publisher_rule']}",
40
+ *[f" - {k}: {v}" for k, v in sorted(by_signer.items(), key=lambda x: -x[1])],
41
+ f" 해시 규칙 필요(미서명): {summary['hash_rule']}",
42
+ "상세: pe_files.csv (path, sha256, size, authenticode, signer, rule)"]
43
+ (out_dir / "summary.txt").write_text("\n".join(lines) + "\n", encoding="utf-8-sig")
44
+ return summary
baro/authenticode.py ADDED
@@ -0,0 +1,62 @@
1
+ """Authenticode 서명 조회. Windows의 Get-AuthenticodeSignature를 한 번의 PowerShell 호출로 일괄 실행한다.
2
+
3
+ 카탈로그 서명(System32의 OS DLL 대부분)도 Valid로 판정된다.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import sys
9
+ import tempfile
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+
13
+ from .errors import BaroError
14
+ from .util import run
15
+
16
+ _PS = r"""
17
+ param([string]$ListFile, [string]$OutFile)
18
+ $ErrorActionPreference = 'Stop'
19
+ $paths = [IO.File]::ReadAllLines($ListFile, [Text.Encoding]::UTF8)
20
+ $r = foreach ($p in $paths) {
21
+ if (-not $p) { continue }
22
+ $s = Get-AuthenticodeSignature -LiteralPath $p
23
+ $n = ''
24
+ if ($s.SignerCertificate) {
25
+ $n = $s.SignerCertificate.GetNameInfo([Security.Cryptography.X509Certificates.X509NameType]::SimpleName, $false)
26
+ }
27
+ [pscustomobject]@{ path = $p; status = [string]$s.Status; signer = $n }
28
+ }
29
+ $json = ConvertTo-Json -InputObject @($r) -Compress -Depth 3
30
+ [IO.File]::WriteAllText($OutFile, $json, (New-Object Text.UTF8Encoding $false))
31
+ """
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Signature:
36
+ status: str # Valid, NotSigned, HashMismatch, UnknownError, ...
37
+ signer: str
38
+
39
+ @property
40
+ def valid(self) -> bool:
41
+ return self.status == "Valid"
42
+
43
+
44
+ def check(paths: list[Path]) -> dict[Path, Signature]:
45
+ if not paths:
46
+ return {}
47
+ if sys.platform != "win32":
48
+ raise BaroError("runtime", "Authenticode 조회는 Windows에서만 됩니다.",
49
+ hint="v0.1 빌드는 Windows 빌드 PC가 필요합니다.")
50
+ with tempfile.TemporaryDirectory(prefix="baro-sig-") as td:
51
+ td = Path(td)
52
+ script = td / "sig.ps1"
53
+ script.write_text(_PS, encoding="utf-8-sig") # PS 5.1은 BOM이 있어야 UTF-8로 읽는다
54
+ lst = td / "list.txt"
55
+ lst.write_text("\n".join(str(p) for p in paths), encoding="utf-8")
56
+ out = td / "out.json"
57
+ run(["powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
58
+ "-File", script, "-ListFile", lst, "-OutFile", out],
59
+ kind="runtime", what="Authenticode 서명 조회", timeout=900)
60
+ rows = json.loads(out.read_text(encoding="utf-8") or "[]")
61
+ by = {str(Path(r["path"])).lower(): Signature(r["status"], r.get("signer") or "") for r in rows}
62
+ return {p: by.get(str(p).lower(), Signature("Missing", "")) for p in paths}
baro/build.py ADDED
@@ -0,0 +1,128 @@
1
+ """`baro build`: pyproject.toml + uv.lock → 폴더 번들 + 매니페스트(+서명) + 허용 목록 목록 + 리포트."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import shutil
6
+ import time
7
+ from pathlib import Path
8
+
9
+ from . import allowlist, depscan, install, layout, manifest, runtime, signing
10
+ from .config import load_config
11
+ from .errors import BaroError
12
+ from .util import clean_env, decode, iter_files
13
+
14
+ import subprocess
15
+
16
+
17
+ def _snapshot(root: Path) -> dict[str, tuple[int, int]]:
18
+ return {p.relative_to(root).as_posix(): (p.stat().st_size, p.stat().st_mtime_ns) for p in iter_files(root)}
19
+
20
+
21
+ def _smoke(cfg, bundle: Path) -> dict:
22
+ """진입 모듈을 import만 해 본다(창을 띄우거나 서비스를 시작하지 않음). 번들 자기 쓰기도 감지."""
23
+ before = _snapshot(bundle)
24
+ code = f"import importlib; importlib.import_module({cfg.entry_module!r})"
25
+ if cfg.entry_func:
26
+ code += f"; getattr(importlib.import_module({cfg.entry_module!r}), {cfg.entry_func!r})"
27
+ p = subprocess.run([str(bundle / "runtime" / "python.exe"), "-B", "-c", code],
28
+ capture_output=True, cwd=bundle, env=clean_env(), timeout=300)
29
+ after = _snapshot(bundle)
30
+ writes = sorted(set(after) - set(before)) + sorted(k for k in before if k in after and before[k] != after[k])
31
+ if p.returncode != 0:
32
+ err = decode(p.stderr)[-2000:]
33
+ hint = "진입 모듈 import가 실패했습니다."
34
+ if "DLL load failed" in err:
35
+ hint += " 네이티브 DLL을 찾지 못했습니다. 리포트의 deps(번들 밖 의존 DLL)를 확인하세요."
36
+ elif "ModuleNotFoundError" in err:
37
+ hint += " pyproject.toml의 dependencies와 [tool.baro] entry를 확인하세요."
38
+ raise BaroError("smoke", f"스모크 테스트 실패: import {cfg.entry_module}", hint=hint, detail=err)
39
+ return {"ok": True, "self_writes": writes[:20], "self_write_count": len(writes)}
40
+
41
+
42
+ def build(project_dir: Path, *, out_dir: Path | None = None, python_zip: Path | None = None,
43
+ sign_key: Path | None = None, allow_unsigned_runtime: bool = False,
44
+ strict_deps: bool = False, skip_allowlist: bool = False, log=print) -> dict:
45
+ t0 = time.perf_counter()
46
+ steps: dict[str, float] = {}
47
+ warnings: list[dict] = []
48
+
49
+ def step(name):
50
+ steps[name] = round(time.perf_counter() - t0, 2)
51
+ log(f" [{steps[name]:6.1f}s] {name}")
52
+
53
+ cfg = load_config(project_dir)
54
+ out_root = (out_dir or cfg.project_dir / "dist" / "baro").resolve()
55
+ bundle = out_root / f"{cfg.app_id}-{cfg.version}"
56
+ side = out_root / f"{cfg.app_id}-{cfg.version}.baro" # 번들 밖 부속물(리포트·허용 목록)
57
+ log(f"baro build: {cfg.app_id} {cfg.version} (python {cfg.python}, profile {cfg.profile})")
58
+ log(f" 출력: {bundle}")
59
+
60
+ lock_sha = install.check_lock(cfg)
61
+ step("uv.lock 확인")
62
+ for d in (bundle, side):
63
+ if d.exists():
64
+ shutil.rmtree(d)
65
+ bundle.mkdir(parents=True)
66
+ side.mkdir(parents=True)
67
+
68
+ zip_path = runtime.fetch_embed(cfg.python, python_zip)
69
+ rt = runtime.install_runtime(zip_path, bundle / "runtime", cfg.python_tag, allow_unsigned=allow_unsigned_runtime)
70
+ step("런타임 준비·서명 검증")
71
+
72
+ inst = install.install(cfg, bundle / "site-packages", bundle / "runtime" / "python.exe")
73
+ step("의존성·프로젝트 설치")
74
+
75
+ pruned = layout.prune(cfg, bundle / "site-packages")
76
+ layout.write_entry(cfg, bundle)
77
+ comp = layout.compile_bytecode(bundle)
78
+ if not comp["ok"]:
79
+ warnings.append({"kind": "compile", "message": "일부 파일을 바이트코드로 컴파일하지 못했습니다(해당 .py는 실행 시 컴파일되지 않고 소스로 실행).",
80
+ "detail": comp.get("detail")})
81
+ step("정리·진입점·컴파일")
82
+
83
+ deps = depscan.scan(bundle)
84
+ if deps["vc_runtime_missing"]:
85
+ w = {"kind": "deps", "message": f"VC++ 런타임 {len(deps['vc_runtime_missing'])}종이 번들에 없습니다. 대상 PC에 VC++ 재배포가 필요합니다.",
86
+ "detail": ", ".join(deps["vc_runtime_missing"])}
87
+ if strict_deps:
88
+ raise BaroError("deps", w["message"], hint="해당 DLL을 번들에 포함하거나 preflight 전제조건으로 문서화하세요.", detail=w["detail"])
89
+ warnings.append(w)
90
+ if deps["driver_or_thirdparty"]:
91
+ warnings.append({"kind": "deps", "message": "드라이버·제3자 DLL에 의존합니다(대상 PC 전제조건).",
92
+ "detail": ", ".join(deps["driver_or_thirdparty"])})
93
+ step("번들 밖 DLL 검사")
94
+
95
+ smoke = _smoke(cfg, bundle)
96
+ if smoke["self_write_count"]:
97
+ warnings.append({"kind": "self_write", "message": f"스모크 테스트 중 번들에 {smoke['self_write_count']}개 파일이 쓰였습니다(번들 불변 위반).",
98
+ "detail": "\n".join(smoke["self_writes"])})
99
+ step("스모크 테스트(import)")
100
+
101
+ m = manifest.build_manifest(cfg, bundle, runtime_info=rt, uv_lock_sha256=lock_sha)
102
+ mbytes = manifest.write_manifest(bundle, m)
103
+ signed = False
104
+ if sign_key:
105
+ (bundle / "manifest.sig").write_text(signing.sign(mbytes, sign_key), encoding="ascii")
106
+ signed = True
107
+ else:
108
+ warnings.append({"kind": "unsigned", "message": "서명하지 않은 개발용 빌드입니다.",
109
+ "hint": "배포용은 `baro keygen`으로 만든 키로 --sign-key를 주세요."})
110
+ step("매니페스트" + ("·서명" if signed else ""))
111
+
112
+ allow = None
113
+ if not skip_allowlist:
114
+ allow = allowlist.export(bundle, side / "allowlist")
115
+ step("허용 목록 목록")
116
+
117
+ size = sum(p.stat().st_size for p in iter_files(bundle))
118
+ report = {
119
+ "ok": True, "app_id": cfg.app_id, "version": cfg.version, "profile": cfg.profile,
120
+ "bundle": str(bundle), "sidecar": str(side), "signed": signed,
121
+ "files": len(m["files"]), "size_mb": round(size / 2**20, 1),
122
+ "runtime": {k: rt[k] for k in ("pe_files", "signed_valid", "signers", "zip_sha256")},
123
+ "install": inst, "pruned": pruned, "compile_ok": comp["ok"], "deps": deps,
124
+ "smoke": smoke, "allowlist": allow, "warnings": warnings, "steps_sec": steps,
125
+ "elapsed_sec": round(time.perf_counter() - t0, 1),
126
+ }
127
+ (side / "build-report.json").write_text(json.dumps(report, ensure_ascii=False, indent=1), encoding="utf-8")
128
+ return report
baro/cli.py ADDED
@@ -0,0 +1,123 @@
1
+ """baro CLI. 모든 명령은 --json(기계용 출력)과 고정 종료 코드를 지원한다."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from . import __version__, manifest, signing
10
+ from .errors import EXIT_CODES, BaroError
11
+
12
+
13
+ def _out(args, data: dict, human: list[str]) -> None:
14
+ if args.json:
15
+ print(json.dumps(data, ensure_ascii=False, indent=1))
16
+ else:
17
+ print("\n".join(human))
18
+
19
+
20
+ def cmd_build(args) -> int:
21
+ from .build import build
22
+ log = (lambda *_: None) if args.json else (lambda s: print(s, flush=True))
23
+ r = build(Path(args.project), out_dir=Path(args.out) if args.out else None,
24
+ python_zip=Path(args.python_zip) if args.python_zip else None,
25
+ sign_key=Path(args.sign_key) if args.sign_key else None,
26
+ allow_unsigned_runtime=args.allow_unsigned_runtime, strict_deps=args.strict_deps,
27
+ skip_allowlist=args.no_allowlist, log=log)
28
+ human = ["", f"완료: {r['bundle']}",
29
+ f" 파일 {r['files']}개, {r['size_mb']}MB, {r['elapsed_sec']}초, 서명 {'있음' if r['signed'] else '없음(개발용)'}",
30
+ f" 런타임 서명: {r['runtime']['signed_valid']}/{r['runtime']['pe_files']} 유효 {r['runtime']['signers']}",
31
+ f" 정리: {r['pruned']}",
32
+ f" 번들 밖 DLL: {r['deps']['counts']}"]
33
+ if r["allowlist"]:
34
+ a = r["allowlist"]
35
+ human.append(f" 허용 목록: PE {a['pe_files']}개 = 게시자 규칙 {a['publisher_rule']} + 해시 규칙 {a['hash_rule']} ({a['csv']})")
36
+ for w in r["warnings"]:
37
+ human.append(f" 경고[{w['kind']}]: {w['message']}" + (f"\n {w['detail']}" if w.get("detail") else ""))
38
+ human.append(f" 리포트: {Path(r['sidecar']) / 'build-report.json'}")
39
+ _out(args, r, human)
40
+ return 0
41
+
42
+
43
+ def cmd_verify(args) -> int:
44
+ b = Path(args.bundle).resolve()
45
+ if not (b / "manifest.json").exists():
46
+ raise BaroError("verify", f"manifest.json이 없습니다: {b}")
47
+ r = manifest.verify_bundle(b)
48
+ code = 0 if r["ok"] else EXIT_CODES["verify"]
49
+ sig_path = b / "manifest.sig"
50
+ if args.pubkey:
51
+ if not sig_path.exists():
52
+ r["signature"] = "missing"
53
+ code = code or EXIT_CODES["signature"]
54
+ else:
55
+ ok = signing.verify((b / "manifest.json").read_bytes(), sig_path.read_text(encoding="ascii"), Path(args.pubkey))
56
+ r["signature"] = "valid" if ok else "invalid"
57
+ if not ok:
58
+ code = code or EXIT_CODES["signature"]
59
+ else:
60
+ r["signature"] = "not_checked" if sig_path.exists() else "unsigned"
61
+ r["exit_code"] = code
62
+ human = [f"verify {r['app_id']} {r['version']}: {'OK' if code == 0 else 'FAIL'} (파일 {r['files']}개, 서명 {r['signature']})"]
63
+ for k in ("missing", "changed", "extra"):
64
+ if r[k]:
65
+ human.append(f" {k} {len(r[k])}: " + ", ".join(r[k][:10]) + (" ..." if len(r[k]) > 10 else ""))
66
+ _out(args, r, human)
67
+ return code
68
+
69
+
70
+ def cmd_keygen(args) -> int:
71
+ r = signing.keygen(Path(args.out), args.name)
72
+ _out(args, r, [f"개인키: {r['private_key']} ← 사람이 보관(하드웨어 토큰 권장). 저장소·AI 도구에 넣지 마세요.",
73
+ f"공개키(PEM): {r['public_pem']}", f"공개키(CNG blob, PowerShell apply용): {r['public_cng_blob']}"])
74
+ return 0
75
+
76
+
77
+ def main(argv: list[str] | None = None) -> int:
78
+ for s in (sys.stdout, sys.stderr):
79
+ if hasattr(s, "reconfigure"):
80
+ s.reconfigure(encoding="utf-8")
81
+ ap = argparse.ArgumentParser(prog="baro", description="폐쇄망·내부망 Windows PC용 Python 앱 번들 도구")
82
+ ap.add_argument("--version", action="version", version=f"baro {__version__}")
83
+ sub = ap.add_subparsers(dest="cmd", required=True)
84
+
85
+ b = sub.add_parser("build", help="pyproject.toml + uv.lock → 폴더 번들")
86
+ b.add_argument("project", nargs="?", default=".")
87
+ b.add_argument("--out", help="출력 폴더(기본: <project>/dist/baro)")
88
+ b.add_argument("--python-zip", help="미리 받은 python.org embeddable zip(오프라인 빌드)")
89
+ b.add_argument("--sign-key", help="ECDSA P-256 개인키(PEM). 없으면 서명 없는 개발용 빌드")
90
+ b.add_argument("--allow-unsigned-runtime", action="store_true", help="런타임 서명 검증 실패를 무시")
91
+ b.add_argument("--strict-deps", action="store_true", help="VC++ 런타임 누락을 오류로 처리")
92
+ b.add_argument("--no-allowlist", action="store_true", help="허용 목록 목록 생성 생략")
93
+ b.set_defaults(func=cmd_build)
94
+
95
+ v = sub.add_parser("verify", help="번들이 매니페스트와 일치하는지(무결성·서명)")
96
+ v.add_argument("bundle")
97
+ v.add_argument("--pubkey", help="공개키 PEM. 주면 manifest.sig도 검증")
98
+ v.set_defaults(func=cmd_verify)
99
+
100
+ k = sub.add_parser("keygen", help="릴리스 서명 키 쌍 생성(ECDSA P-256)")
101
+ k.add_argument("--out", default=".")
102
+ k.add_argument("--name", default="baro-release")
103
+ k.set_defaults(func=cmd_keygen)
104
+
105
+ for p in (b, v, k):
106
+ p.add_argument("--json", action="store_true", help="기계가 읽는 JSON 출력")
107
+ args = ap.parse_args(argv)
108
+ try:
109
+ return args.func(args)
110
+ except BaroError as e:
111
+ if getattr(args, "json", False):
112
+ print(json.dumps(e.to_dict(), ensure_ascii=False, indent=1))
113
+ else:
114
+ print(f"오류[{e.kind}]: {e.message}", file=sys.stderr)
115
+ if e.hint:
116
+ print(f" 해결: {e.hint}", file=sys.stderr)
117
+ if e.detail:
118
+ print(" 상세:\n " + e.detail.strip().replace("\n", "\n "), file=sys.stderr)
119
+ return e.exit_code
120
+
121
+
122
+ if __name__ == "__main__":
123
+ sys.exit(main())
baro/config.py ADDED
@@ -0,0 +1,82 @@
1
+ """pyproject.toml의 [project]와 [tool.baro]를 읽는다. 새 설정 파일은 만들지 않는다."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ import tomllib
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ from .errors import BaroError
10
+
11
+ PROFILES = ("gui", "service", "job")
12
+ _PY_EXACT = re.compile(r"^3\.(\d+)\.(\d+)$")
13
+ _ENTRY = re.compile(r"^[A-Za-z_][\w.]*(:[A-Za-z_]\w*)?$")
14
+
15
+
16
+ @dataclass
17
+ class BaroConfig:
18
+ project_dir: Path
19
+ name: str
20
+ version: str
21
+ app_id: str
22
+ python: str
23
+ entry: str
24
+ profile: str
25
+ prune_tests: bool = True
26
+ exclude: list[str] = field(default_factory=list)
27
+
28
+ @property
29
+ def entry_module(self) -> str:
30
+ return self.entry.split(":")[0]
31
+
32
+ @property
33
+ def entry_func(self) -> str | None:
34
+ return self.entry.split(":")[1] if ":" in self.entry else None
35
+
36
+ @property
37
+ def python_tag(self) -> str:
38
+ """'3.14.10' -> '314'"""
39
+ major, minor = self.python.split(".")[:2]
40
+ return f"{major}{minor}"
41
+
42
+
43
+ def load_config(project_dir: Path) -> BaroConfig:
44
+ project_dir = project_dir.resolve()
45
+ pp = project_dir / "pyproject.toml"
46
+ if not pp.exists():
47
+ raise BaroError("config", f"pyproject.toml이 없습니다: {pp}",
48
+ hint="프로젝트 루트(pyproject.toml이 있는 폴더)를 지정하세요.")
49
+ try:
50
+ data = tomllib.loads(pp.read_text(encoding="utf-8"))
51
+ except tomllib.TOMLDecodeError as e:
52
+ raise BaroError("config", f"pyproject.toml 구문 오류: {e}") from e
53
+
54
+ project = data.get("project", {})
55
+ tool = data.get("tool", {}).get("baro")
56
+ if tool is None:
57
+ raise BaroError("config", "[tool.baro] 설정이 없습니다.",
58
+ hint='pyproject.toml에 추가하세요:\n[tool.baro]\npython = "3.14.10"\n'
59
+ 'entry = "mypkg.app:main"\nprofile = "gui" # gui | service | job')
60
+ name = project.get("name")
61
+ version = project.get("version")
62
+ if not name or not version:
63
+ raise BaroError("config", "[project]의 name과 version이 필요합니다(정적 값).",
64
+ hint="dynamic version은 v0.1에서 지원하지 않습니다.")
65
+
66
+ python = str(tool.get("python", ""))
67
+ if not _PY_EXACT.match(python):
68
+ raise BaroError("config", f'[tool.baro] python은 정확한 버전이어야 합니다(받은 값: "{python}").',
69
+ hint='재현 빌드를 위해 "3.14.10"처럼 패치 버전까지 고정하세요.')
70
+ entry = str(tool.get("entry", ""))
71
+ if not _ENTRY.match(entry):
72
+ raise BaroError("config", f'[tool.baro] entry 형식이 잘못됐습니다(받은 값: "{entry}").',
73
+ hint='"패키지.모듈:함수" 또는 "패키지.모듈" 형식으로 쓰세요. 예: "vision_hmi.app:main"')
74
+ profile = str(tool.get("profile", ""))
75
+ if profile not in PROFILES:
76
+ raise BaroError("config", f'[tool.baro] profile은 {"/".join(PROFILES)} 중 하나여야 합니다(받은 값: "{profile}").',
77
+ hint="v0.1은 프로파일을 자동 감지하지 않습니다(숨은 마법 금지). 명시적으로 선언하세요.")
78
+ app_id = str(tool.get("app_id", name))
79
+ exclude = [str(x) for x in tool.get("exclude", [])]
80
+ return BaroConfig(project_dir=project_dir, name=name, version=str(version), app_id=app_id,
81
+ python=python, entry=entry, profile=profile,
82
+ prune_tests=bool(tool.get("prune_tests", True)), exclude=exclude)
baro/depscan.py ADDED
@@ -0,0 +1,77 @@
1
+ """번들 밖에서 와야 하는 DLL 검사.
2
+
3
+ 번들의 모든 PE가 import하는 DLL을 분류한다.
4
+ bundled 번들 안에 같은 이름이 있음
5
+ os_apiset api-ms-win-*/ext-ms-* (OS API set)
6
+ os 빌드 PC System32에 있고 'Microsoft Windows' 서명 → 대상 PC에도 있다고 본다
7
+ vc_runtime_missing VC++ 런타임인데 번들에 없음 → 대상 PC에 VC++ 재배포가 필요
8
+ driver_or_thirdparty System32에 있지만 Microsoft Windows 서명이 아님(예: nvcuda.dll) → 드라이버 전제조건
9
+ unresolved 어디에도 없음(선택 플러그인일 수 있음)
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from collections import defaultdict
15
+ from pathlib import Path
16
+
17
+ import pefile
18
+
19
+ from . import authenticode
20
+ from .util import is_pe
21
+
22
+ VC_RUNTIME_PREFIXES = ("vcruntime140", "msvcp140", "concrt140", "vcomp140", "vccorlib140", "mfc140")
23
+ OS_SIGNERS = {"Microsoft Windows", "Microsoft Windows Publisher"}
24
+
25
+
26
+ def _imports(path: Path) -> set[str]:
27
+ try:
28
+ pe = pefile.PE(str(path), fast_load=True)
29
+ pe.parse_data_directories(directories=[
30
+ pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_IMPORT"],
31
+ pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT"]])
32
+ names = set()
33
+ for attr in ("DIRECTORY_ENTRY_IMPORT", "DIRECTORY_ENTRY_DELAY_IMPORT"):
34
+ for e in getattr(pe, attr, []):
35
+ names.add(e.dll.decode("ascii", "replace").lower())
36
+ pe.close()
37
+ return names
38
+ except pefile.PEFormatError:
39
+ return set()
40
+
41
+
42
+ def scan(bundle: Path) -> dict:
43
+ pes = [p for p in bundle.rglob("*") if p.is_file() and is_pe(p)]
44
+ provided = {p.name.lower() for p in pes}
45
+ importers: dict[str, list[str]] = defaultdict(list)
46
+ for p in pes:
47
+ for d in _imports(p):
48
+ importers[d].append(p.relative_to(bundle).as_posix())
49
+
50
+ sys32 = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32"
51
+ classes: dict[str, str] = {}
52
+ to_check: list[Path] = []
53
+ for d in importers:
54
+ if d in provided:
55
+ classes[d] = "bundled"
56
+ elif d.startswith(("api-ms-win-", "ext-ms-")):
57
+ classes[d] = "os_apiset"
58
+ elif d.startswith(VC_RUNTIME_PREFIXES):
59
+ classes[d] = "vc_runtime_missing"
60
+ elif (sys32 / d).exists():
61
+ to_check.append(sys32 / d)
62
+ else:
63
+ classes[d] = "unresolved"
64
+ for path, sig in authenticode.check(to_check).items():
65
+ classes[path.name.lower()] = "os" if (sig.valid and sig.signer in OS_SIGNERS) else "driver_or_thirdparty"
66
+
67
+ def group(c):
68
+ return {d: {"importers": len(importers[d]), "sample": sorted(importers[d])[:3]}
69
+ for d in sorted(importers) if classes[d] == c}
70
+
71
+ counts: dict[str, int] = defaultdict(int)
72
+ for c in classes.values():
73
+ counts[c] += 1
74
+ return {"pe_files": len(pes), "counts": dict(counts),
75
+ "vc_runtime_missing": group("vc_runtime_missing"),
76
+ "driver_or_thirdparty": group("driver_or_thirdparty"),
77
+ "unresolved": group("unresolved")}
baro/errors.py ADDED
@@ -0,0 +1,42 @@
1
+ """구조화 오류와 종료 코드.
2
+
3
+ 종료 코드는 플랜트 절차·AI 루프가 분기할 수 있게 고정한다.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ EXIT_CODES = {
8
+ "ok": 0,
9
+ "usage": 1,
10
+ "config": 2, # pyproject.toml [tool.baro] 문제
11
+ "lock": 3, # uv.lock 없음·오래됨
12
+ "runtime": 4, # 런타임 다운로드·서명 검증 실패
13
+ "install": 5, # 의존성 설치 실패
14
+ "deps": 6, # 번들 밖 DLL 의존(엄격 모드에서만 오류)
15
+ "smoke": 7, # 진입 모듈 import 실패
16
+ "verify": 10, # 매니페스트 해시 불일치
17
+ "signature": 11, # 서명 검증 실패
18
+ "io": 20,
19
+ }
20
+
21
+
22
+ class BaroError(Exception):
23
+ """사람과 기계가 모두 읽을 수 있는 오류. hint에는 고치는 방법을 적는다."""
24
+
25
+ def __init__(self, kind: str, message: str, hint: str | None = None, detail: str | None = None):
26
+ super().__init__(message)
27
+ self.kind = kind
28
+ self.message = message
29
+ self.hint = hint
30
+ self.detail = detail
31
+
32
+ @property
33
+ def exit_code(self) -> int:
34
+ return EXIT_CODES.get(self.kind, 1)
35
+
36
+ def to_dict(self) -> dict:
37
+ d = {"error": self.kind, "exit_code": self.exit_code, "message": self.message}
38
+ if self.hint:
39
+ d["hint"] = self.hint
40
+ if self.detail:
41
+ d["detail"] = self.detail
42
+ return d
baro/install.py ADDED
@@ -0,0 +1,58 @@
1
+ """uv로 잠긴 의존성과 프로젝트 wheel을 번들의 site-packages에 설치한다.
2
+
3
+ - 의존성: uv.lock에서 해시 포함 requirements로 내보내 --require-hashes·--only-binary로 설치(휠만)
4
+ - 프로젝트: uv build로 wheel을 만들어 --no-deps로 설치(편집 설치 아님)
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import shutil
9
+ import tempfile
10
+ from pathlib import Path
11
+
12
+ from .config import BaroConfig
13
+ from .errors import BaroError
14
+ from .util import clean_env, run, sha256_file
15
+
16
+
17
+ def uv_exe() -> str:
18
+ uv = shutil.which("uv")
19
+ if not uv:
20
+ raise BaroError("install", "uv를 찾을 수 없습니다.", hint="https://docs.astral.sh/uv/ 에서 uv를 설치하세요.")
21
+ return uv
22
+
23
+
24
+ def check_lock(cfg: BaroConfig) -> str:
25
+ lock = cfg.project_dir / "uv.lock"
26
+ if not lock.exists():
27
+ raise BaroError("lock", "uv.lock이 없습니다.", hint=f"프로젝트 폴더에서 `uv lock`을 먼저 실행하세요: {cfg.project_dir}")
28
+ run([uv_exe(), "lock", "--check", "--project", cfg.project_dir], kind="lock",
29
+ what="uv.lock 최신 여부 확인", hint="pyproject.toml이 바뀌었습니다. `uv lock`을 다시 실행하세요.",
30
+ env=clean_env())
31
+ return sha256_file(lock)
32
+
33
+
34
+ def install(cfg: BaroConfig, site_packages: Path, python_exe: Path) -> dict:
35
+ uv = uv_exe()
36
+ env = clean_env()
37
+ site_packages.mkdir(parents=True, exist_ok=True)
38
+ with tempfile.TemporaryDirectory(prefix="baro-build-") as td:
39
+ td = Path(td)
40
+ reqs = td / "requirements.txt"
41
+ run([uv, "export", "--project", cfg.project_dir, "--frozen", "--no-dev", "--no-emit-project",
42
+ "--format", "requirements-txt", "-o", reqs], kind="install", what="잠긴 의존성 내보내기", env=env)
43
+ n_deps = sum(1 for line in reqs.read_text(encoding="utf-8").splitlines()
44
+ if line and not line.startswith((" ", "#", "-")))
45
+ if n_deps:
46
+ run([uv, "pip", "install", "--target", site_packages, "--python", python_exe,
47
+ "--only-binary", ":all:", "--require-hashes", "--no-deps", "-r", reqs],
48
+ kind="install", what="의존성 설치(휠 전용, 해시 검증)", env=env,
49
+ hint="sdist만 있는 패키지는 v0.1에서 지원하지 않습니다. 빌드 PC에서 휠을 만들어 사내 인덱스에 올리세요.")
50
+ wheel_dir = td / "wheel"
51
+ run([uv, "build", "--wheel", "--project", cfg.project_dir, "-o", wheel_dir],
52
+ kind="install", what="프로젝트 wheel 빌드", env=env)
53
+ wheels = list(wheel_dir.glob("*.whl"))
54
+ if len(wheels) != 1:
55
+ raise BaroError("install", f"프로젝트 wheel이 1개가 아닙니다: {[w.name for w in wheels]}")
56
+ run([uv, "pip", "install", "--target", site_packages, "--python", python_exe, "--no-deps", wheels[0]],
57
+ kind="install", what="프로젝트 설치", env=env)
58
+ return {"dependencies": n_deps, "project_wheel": wheels[0].name}
baro/layout.py ADDED
@@ -0,0 +1,100 @@
1
+ """번들 정리·진입점 생성·바이트코드 컴파일.
2
+
3
+ - site-packages/bin의 entry-point exe는 빌드 시점 python 경로를 박아 옮기면 깨진다 → 제거.
4
+ - timestamp .pyc는 반입 중 mtime이 바뀌면 번들에 다시 쓰인다 → unchecked-hash로 컴파일.
5
+ 컴파일 시 빌드 경로를 지운다(co_filename에 절대 경로가 남지 않게).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import fnmatch
10
+ import shutil
11
+ from pathlib import Path
12
+
13
+ from .config import BaroConfig
14
+ from .util import clean_env, run
15
+
16
+ _MAIN_TMPL = '''"""baro가 생성한 진입점. 직접 수정하지 마세요(다음 빌드에서 덮어씀)."""
17
+ import os
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ BUNDLE = Path(__file__).resolve().parent.parent
22
+
23
+
24
+ def _data_dir() -> Path:
25
+ env = os.environ.get("BARO_DATA")
26
+ if env:
27
+ return Path(env)
28
+ if BUNDLE.parent.name.lower() == "releases": # app-root/releases/<ver>/ 구조
29
+ return BUNDLE.parent.parent / "data"
30
+ return BUNDLE.parent / "{app_id}-data"
31
+
32
+
33
+ DATA = _data_dir()
34
+ # 번들은 불변: 라이브러리 캐시는 번들 밖 data/cache로 돌린다.
35
+ for _key, _sub in (("MPLCONFIGDIR", "matplotlib"), ("TORCH_HOME", "torch"),
36
+ ("HF_HOME", "huggingface"), ("XDG_CACHE_HOME", "xdg")):
37
+ os.environ.setdefault(_key, str(DATA / "cache" / _sub))
38
+ os.environ.setdefault("BARO_BUNDLE", str(BUNDLE))
39
+ os.environ.setdefault("BARO_DATA_DIR", str(DATA))
40
+ sys.dont_write_bytecode = True
41
+
42
+ {entry_code}
43
+ '''
44
+
45
+ _LAUNCH_CMD = {
46
+ "console": '@echo off\r\n"%~dp0runtime\\python.exe" -B "%~dp0app\\__baro_main__.py" %*\r\nexit /b %ERRORLEVEL%\r\n',
47
+ "gui": '@echo off\r\nstart "" "%~dp0runtime\\pythonw.exe" -B "%~dp0app\\__baro_main__.py" %*\r\n',
48
+ }
49
+
50
+
51
+ def prune(cfg: BaroConfig, site_packages: Path) -> dict:
52
+ removed = {"bin": 0, "tests_dirs": 0, "pycache_dirs": 0, "excluded": 0}
53
+ b = site_packages / "bin"
54
+ if b.exists():
55
+ removed["bin"] = sum(1 for _ in b.rglob("*") if _.is_file())
56
+ shutil.rmtree(b)
57
+ for d in sorted(site_packages.rglob("__pycache__"), key=lambda p: len(p.parts), reverse=True):
58
+ if d.is_dir():
59
+ shutil.rmtree(d)
60
+ removed["pycache_dirs"] += 1
61
+ if cfg.prune_tests:
62
+ for d in sorted(site_packages.rglob("tests"), key=lambda p: len(p.parts), reverse=True):
63
+ # 최상위 'tests' 패키지(배포판 이름이 tests인 경우)는 건드리지 않는다
64
+ if d.is_dir() and d.parent != site_packages:
65
+ shutil.rmtree(d)
66
+ removed["tests_dirs"] += 1
67
+ for pat in cfg.exclude:
68
+ for p in list(site_packages.rglob("*")):
69
+ rel = p.relative_to(site_packages).as_posix()
70
+ if p.exists() and fnmatch.fnmatch(rel, pat):
71
+ shutil.rmtree(p) if p.is_dir() else p.unlink()
72
+ removed["excluded"] += 1
73
+ return removed
74
+
75
+
76
+ def write_entry(cfg: BaroConfig, bundle: Path) -> None:
77
+ app = bundle / "app"
78
+ app.mkdir(parents=True, exist_ok=True)
79
+ if cfg.entry_func:
80
+ code = (f"from {cfg.entry_module} import {cfg.entry_func} as _entry\n\n"
81
+ f"if __name__ == \"__main__\":\n sys.exit(_entry())\n")
82
+ else:
83
+ code = ("import runpy\n\nif __name__ == \"__main__\":\n"
84
+ f" runpy.run_module(\"{cfg.entry_module}\", run_name=\"__main__\", alter_sys=True)\n")
85
+ (app / "__baro_main__.py").write_text(
86
+ _MAIN_TMPL.replace("{app_id}", cfg.app_id).replace("{entry_code}", code), encoding="utf-8")
87
+ kind = "gui" if cfg.profile == "gui" else "console"
88
+ (bundle / "launch.cmd").write_bytes(_LAUNCH_CMD[kind].encode("ascii"))
89
+
90
+
91
+ def compile_bytecode(bundle: Path) -> dict:
92
+ py = bundle / "runtime" / "python.exe"
93
+ try:
94
+ run([py, "-m", "compileall", "-q", "-f", "--invalidation-mode", "unchecked-hash",
95
+ "-s", bundle, "-p", "<bundle>", bundle / "site-packages", bundle / "app"],
96
+ kind="install", what="바이트코드 컴파일", env=clean_env(), cwd=bundle)
97
+ return {"ok": True}
98
+ except Exception as e: # 일부 패키지의 템플릿·py2 파일은 컴파일 실패가 정상일 수 있다
99
+ detail = getattr(e, "detail", "") or str(e)
100
+ return {"ok": False, "detail": detail[-1500:]}
baro/manifest.py ADDED
@@ -0,0 +1,67 @@
1
+ """매니페스트 생성과 검증.
2
+
3
+ manifest.json의 files는 번들 안 모든 파일(manifest.json·manifest.sig 제외)의 sha256·크기다.
4
+ 장비 쪽 apply 스크립트(PowerShell)가 같은 manifest.json + manifest.sig 형식을 읽는다.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import time
10
+ from pathlib import Path
11
+
12
+ from . import __version__
13
+ from .config import BaroConfig
14
+ from .util import iter_files, sha256_file
15
+
16
+ SCHEMA_VERSION = 1
17
+ EXCLUDED = {"manifest.json", "manifest.sig"}
18
+
19
+
20
+ def collect_files(bundle: Path) -> dict[str, dict]:
21
+ out = {}
22
+ for p in iter_files(bundle):
23
+ rel = p.relative_to(bundle).as_posix()
24
+ if rel in EXCLUDED:
25
+ continue
26
+ out[rel] = {"sha256": sha256_file(p), "size": p.stat().st_size}
27
+ return out
28
+
29
+
30
+ def build_manifest(cfg: BaroConfig, bundle: Path, *, runtime_info: dict, uv_lock_sha256: str) -> dict:
31
+ files = collect_files(bundle)
32
+ return {
33
+ "schema_version": SCHEMA_VERSION,
34
+ "app_id": cfg.app_id,
35
+ "version": cfg.version,
36
+ "profile": cfg.profile,
37
+ "entrypoint": {"entry": cfg.entry, "launcher": "launch.cmd"},
38
+ "python": {"version": cfg.python, "source": "python.org embeddable",
39
+ "zip_sha256": runtime_info["zip_sha256"]},
40
+ "build": {"baro_version": __version__, "uv_lock_sha256": uv_lock_sha256,
41
+ "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())},
42
+ # apply 스크립트와 호환: files는 {경로: sha256}
43
+ "files": {k: v["sha256"] for k, v in files.items()},
44
+ "sizes": {k: v["size"] for k, v in files.items()},
45
+ }
46
+
47
+
48
+ def manifest_bytes(m: dict) -> bytes:
49
+ return (json.dumps(m, indent=1, sort_keys=True, ensure_ascii=False) + "\n").encode("utf-8")
50
+
51
+
52
+ def write_manifest(bundle: Path, m: dict) -> bytes:
53
+ data = manifest_bytes(m)
54
+ (bundle / "manifest.json").write_bytes(data)
55
+ return data
56
+
57
+
58
+ def verify_bundle(bundle: Path) -> dict:
59
+ m = json.loads((bundle / "manifest.json").read_text(encoding="utf-8"))
60
+ expected: dict[str, str] = m["files"]
61
+ actual = collect_files(bundle)
62
+ missing = sorted(k for k in expected if k not in actual)
63
+ changed = sorted(k for k in expected if k in actual and actual[k]["sha256"] != expected[k])
64
+ extra = sorted(k for k in actual if k not in expected)
65
+ return {"app_id": m.get("app_id"), "version": m.get("version"), "files": len(expected),
66
+ "missing": missing, "changed": changed, "extra": extra,
67
+ "ok": not (missing or changed or extra)}
baro/runtime.py ADDED
@@ -0,0 +1,76 @@
1
+ """python.org Windows embeddable 런타임 준비.
2
+
3
+ python.org embeddable은 PE 파일 전부가 PSF·Microsoft 서명이고, python-build-standalone은
4
+ python.exe가 미서명이었다. 그래서 기본 런타임은 python.org embeddable이고, 서명을 검증한다.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import shutil
10
+ import urllib.request
11
+ import zipfile
12
+ from pathlib import Path
13
+
14
+ from . import authenticode
15
+ from .errors import BaroError
16
+ from .util import is_pe, sha256_file
17
+
18
+ EMBED_URL = "https://www.python.org/ftp/python/{v}/python-{v}-embed-amd64.zip"
19
+ TRUSTED_RUNTIME_SIGNERS = {"Python Software Foundation", "Microsoft Windows", "Microsoft Corporation"}
20
+
21
+
22
+ def cache_dir() -> Path:
23
+ base = os.environ.get("BARO_CACHE") or os.path.join(os.environ.get("LOCALAPPDATA", str(Path.home())), "baro", "cache")
24
+ p = Path(base)
25
+ p.mkdir(parents=True, exist_ok=True)
26
+ return p
27
+
28
+
29
+ def fetch_embed(version: str, local_zip: Path | None = None) -> Path:
30
+ """embeddable zip 경로를 돌려준다. local_zip이 있으면 네트워크를 쓰지 않는다."""
31
+ if local_zip:
32
+ if not local_zip.exists():
33
+ raise BaroError("runtime", f"지정한 런타임 zip이 없습니다: {local_zip}")
34
+ return local_zip
35
+ dst = cache_dir() / f"python-{version}-embed-amd64.zip"
36
+ if dst.exists():
37
+ return dst
38
+ url = EMBED_URL.format(v=version)
39
+ tmp = dst.with_suffix(".part")
40
+ try:
41
+ with urllib.request.urlopen(url, timeout=120) as r, open(tmp, "wb") as f:
42
+ shutil.copyfileobj(r, f)
43
+ except Exception as e:
44
+ tmp.unlink(missing_ok=True)
45
+ raise BaroError("runtime", f"런타임 다운로드 실패: {url}",
46
+ hint="버전이 python.org에 있는지 확인하거나, 오프라인이면 --python-zip으로 미리 받은 파일을 지정하세요.",
47
+ detail=str(e)) from e
48
+ tmp.replace(dst)
49
+ return dst
50
+
51
+
52
+ def install_runtime(embed_zip: Path, runtime_dir: Path, python_tag: str, *, allow_unsigned: bool = False) -> dict:
53
+ with zipfile.ZipFile(embed_zip) as z:
54
+ z.extractall(runtime_dir)
55
+ pth = runtime_dir / f"python{python_tag}._pth"
56
+ if not pth.exists():
57
+ raise BaroError("runtime", f"embeddable 런타임에 {pth.name}이 없습니다.",
58
+ hint="[tool.baro] python 버전과 런타임 zip 버전이 같은지 확인하세요.")
59
+ # sys.path를 명시적으로 고정. 'import site'는 넣지 않는다(.pth 처리·사용자 site 없음).
60
+ pth.write_text(f"python{python_tag}.zip\n.\n..\\site-packages\n..\\app\n", encoding="utf-8")
61
+
62
+ pes = [p for p in runtime_dir.rglob("*") if p.is_file() and is_pe(p)]
63
+ sigs = authenticode.check(pes)
64
+ bad = {str(p.relative_to(runtime_dir)): f"{s.status} {s.signer}".strip()
65
+ for p, s in sigs.items() if not (s.valid and s.signer in TRUSTED_RUNTIME_SIGNERS)}
66
+ if bad and not allow_unsigned:
67
+ raise BaroError("runtime", f"런타임 바이너리 {len(bad)}개의 서명이 신뢰 목록과 다릅니다.",
68
+ hint="python.org 공식 embeddable zip을 쓰세요. 의도한 것이면 --allow-unsigned-runtime.",
69
+ detail="\n".join(f"{k}: {v}" for k, v in list(bad.items())[:20]))
70
+ signers: dict[str, int] = {}
71
+ for s in sigs.values():
72
+ if s.valid:
73
+ signers[s.signer] = signers.get(s.signer, 0) + 1
74
+ return {"zip": str(embed_zip), "zip_sha256": sha256_file(embed_zip), "pe_files": len(pes),
75
+ "signed_valid": sum(s.valid for s in sigs.values()), "signers": signers,
76
+ "untrusted": bad}
baro/signing.py ADDED
@@ -0,0 +1,64 @@
1
+ """업데이트 서명: ECDSA P-256 / SHA-256, 서명은 IEEE P1363(r||s 64바이트) base64.
2
+
3
+ Windows CNG(ECDsaCng)로 검증할 수 있는 형식이다(Ed25519는 CNG 미지원이라 쓰지 않음).
4
+ 공개키는 PEM과 CNG용 BCRYPT_ECCKEY_BLOB(base64) 두 형식으로 내보낸다.
5
+ 릴리스 서명 키는 사람이 보관한다. 이 모듈은 키 파일을 만들 뿐 보관하지 않는다.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ from pathlib import Path
11
+
12
+ from cryptography.exceptions import InvalidSignature
13
+ from cryptography.hazmat.primitives import hashes, serialization
14
+ from cryptography.hazmat.primitives.asymmetric import ec
15
+ from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature, encode_dss_signature
16
+
17
+ from .errors import BaroError
18
+
19
+
20
+ def keygen(out_dir: Path, name: str = "baro-release") -> dict:
21
+ out_dir.mkdir(parents=True, exist_ok=True)
22
+ priv_path = out_dir / f"{name}.key.pem"
23
+ if priv_path.exists():
24
+ raise BaroError("io", f"키 파일이 이미 있습니다: {priv_path}", hint="덮어쓰지 않습니다. 다른 --name을 쓰세요.")
25
+ key = ec.generate_private_key(ec.SECP256R1())
26
+ priv_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
27
+ serialization.NoEncryption()))
28
+ pub = key.public_key()
29
+ pub_pem = out_dir / f"{name}.pub.pem"
30
+ pub_pem.write_bytes(pub.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo))
31
+ n = pub.public_numbers()
32
+ blob = b"ECS1" + (32).to_bytes(4, "little") + n.x.to_bytes(32, "big") + n.y.to_bytes(32, "big")
33
+ pub_blob = out_dir / f"{name}.pub.eccblob.b64"
34
+ pub_blob.write_text(base64.b64encode(blob).decode("ascii"), encoding="ascii")
35
+ return {"private_key": str(priv_path), "public_pem": str(pub_pem), "public_cng_blob": str(pub_blob)}
36
+
37
+
38
+ def _load_private(path: Path) -> ec.EllipticCurvePrivateKey:
39
+ try:
40
+ key = serialization.load_pem_private_key(path.read_bytes(), password=None)
41
+ except Exception as e:
42
+ raise BaroError("signature", f"서명 키를 읽을 수 없습니다: {path}", detail=str(e)) from e
43
+ if not isinstance(key, ec.EllipticCurvePrivateKey) or key.curve.name != "secp256r1":
44
+ raise BaroError("signature", "서명 키는 ECDSA P-256이어야 합니다.", hint="`baro keygen`으로 만드세요.")
45
+ return key
46
+
47
+
48
+ def sign(data: bytes, key_path: Path) -> str:
49
+ key = _load_private(key_path)
50
+ r, s = decode_dss_signature(key.sign(data, ec.ECDSA(hashes.SHA256())))
51
+ return base64.b64encode(r.to_bytes(32, "big") + s.to_bytes(32, "big")).decode("ascii")
52
+
53
+
54
+ def verify(data: bytes, sig_b64: str, pub_pem: Path) -> bool:
55
+ pub = serialization.load_pem_public_key(pub_pem.read_bytes())
56
+ raw = base64.b64decode(sig_b64.strip())
57
+ if len(raw) != 64:
58
+ return False
59
+ der = encode_dss_signature(int.from_bytes(raw[:32], "big"), int.from_bytes(raw[32:], "big"))
60
+ try:
61
+ pub.verify(der, data, ec.ECDSA(hashes.SHA256())) # type: ignore[union-attr]
62
+ return True
63
+ except InvalidSignature:
64
+ return False
baro/util.py ADDED
@@ -0,0 +1,57 @@
1
+ """공용 도우미."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import os
6
+ import subprocess
7
+ from pathlib import Path
8
+
9
+ from .errors import BaroError
10
+
11
+
12
+ def sha256_file(path: Path) -> str:
13
+ h = hashlib.sha256()
14
+ with open(path, "rb") as f:
15
+ for chunk in iter(lambda: f.read(1 << 20), b""):
16
+ h.update(chunk)
17
+ return h.hexdigest()
18
+
19
+
20
+ def clean_env() -> dict[str, str]:
21
+ """PYTHON* 환경변수를 뺀 환경. 빌드 머신의 오염이 번들 작업에 섞이지 않게 한다."""
22
+ return {k: v for k, v in os.environ.items() if not k.upper().startswith("PYTHON")}
23
+
24
+
25
+ def run(cmd: list[str], *, kind: str, what: str, hint: str | None = None, cwd: Path | None = None,
26
+ env: dict[str, str] | None = None, timeout: int = 1800) -> subprocess.CompletedProcess:
27
+ try:
28
+ p = subprocess.run([str(c) for c in cmd], capture_output=True, cwd=cwd, env=env, timeout=timeout)
29
+ except FileNotFoundError as e:
30
+ raise BaroError(kind, f"{what}: 실행 파일을 찾을 수 없습니다 ({cmd[0]})", hint=hint) from e
31
+ except subprocess.TimeoutExpired as e:
32
+ raise BaroError(kind, f"{what}: 시간 초과({timeout}초)", hint=hint) from e
33
+ p.stdout_text = decode(p.stdout) # type: ignore[attr-defined]
34
+ p.stderr_text = decode(p.stderr) # type: ignore[attr-defined]
35
+ if p.returncode != 0:
36
+ tail = (p.stderr_text or p.stdout_text)[-2000:] # type: ignore[attr-defined]
37
+ raise BaroError(kind, f"{what} 실패 (exit {p.returncode})", hint=hint, detail=tail)
38
+ return p
39
+
40
+
41
+ def decode(b: bytes) -> str:
42
+ for enc in ("utf-8", "cp949", "latin-1"):
43
+ try:
44
+ return b.decode(enc)
45
+ except UnicodeDecodeError:
46
+ continue
47
+ return b.decode("utf-8", "replace")
48
+
49
+
50
+ def iter_files(root: Path):
51
+ for p in sorted(root.rglob("*")):
52
+ if p.is_file():
53
+ yield p
54
+
55
+
56
+ def is_pe(path: Path) -> bool:
57
+ return path.suffix.lower() in (".exe", ".dll", ".pyd", ".drv", ".sys")
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: baro
3
+ Version: 0.1.0
4
+ Summary: 폐쇄망·내부망 Windows PC용 Python 앱 번들 빌드 도구
5
+ Keywords: air-gapped,offline,deployment,windows,bundle,allowlisting,ot
6
+ Author: cpprhtn
7
+ Author-email: cpprhtn <cpprhtn@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Manufacturing
14
+ Classifier: Natural Language :: Korean
15
+ Classifier: Operating System :: Microsoft :: Windows
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Software Development :: Build Tools
22
+ Classifier: Topic :: System :: Software Distribution
23
+ Requires-Dist: cryptography>=42
24
+ Requires-Dist: pefile>=2023.2.7
25
+ Requires-Python: >=3.11
26
+ Project-URL: Homepage, https://github.com/cpprhtn/baro
27
+ Project-URL: Repository, https://github.com/cpprhtn/baro
28
+ Project-URL: Issues, https://github.com/cpprhtn/baro/issues
29
+ Description-Content-Type: text/markdown
30
+
31
+ # baro
32
+
33
+ **폐쇄망·내부망 Windows PC에 Python 앱을 폴더 하나로 넣기 위한 빌드 도구.**
34
+
35
+ 인터넷도 Python도 없는 현장 PC(공장 장비, 검사 PC, 내부망 업무 PC)에 Python 앱을 배포하면 문제가 반복됩니다. 개발 PC에서는 되는데 현장에서는 DLL이 없다고 뜨고, 보안팀은 서명 없는 실행 파일 수천 개를 승인해야 하며, 반입 중에 파일이 바뀌어도 알 방법이 없습니다. baro는 `pyproject.toml`과 `uv.lock`에서 **검증된 폴더 번들**을 만들어 이 문제를 빌드 단계에서 막습니다.
36
+
37
+ > **상태: v0.1 (pre-alpha).** 빌드 쪽 골격만 있습니다. API와 출력 형식은 바뀔 수 있습니다. Windows 10/11 x64 빌드 PC가 필요합니다.
38
+
39
+ ## 설치
40
+
41
+ ```powershell
42
+ uv tool install baro # 또는: pip install baro
43
+ ```
44
+
45
+ 빌드 PC에 [uv](https://docs.astral.sh/uv/)가 있어야 합니다. 대상(현장) PC에는 아무것도 설치하지 않습니다.
46
+
47
+ ## 빠른 시작
48
+
49
+ `pyproject.toml`에 `[tool.baro]`를 추가합니다.
50
+
51
+ ```toml
52
+ [tool.baro]
53
+ python = "3.14.10" # 패치 버전까지 고정 (재현 빌드)
54
+ entry = "vision_hmi.app:main" # "모듈:함수" 또는 "모듈"
55
+ profile = "gui" # gui | service | job (자동 감지하지 않음)
56
+ # app_id = "vision-hmi" # 기본값: [project].name
57
+ # prune_tests = true # 패키지 내부 tests 폴더 제거
58
+ # exclude = ["PySide6/qml/*"] # site-packages 기준 glob으로 제외
59
+ ```
60
+
61
+ ```powershell
62
+ uv lock
63
+ baro keygen --out C:\keys # 릴리스 서명 키 (개인키는 사람이 보관)
64
+ baro build . --sign-key C:\keys\baro-release.key.pem
65
+ baro verify dist\baro\my-app-1.0.0 --pubkey C:\keys\baro-release.pub.pem
66
+ dist\baro\my-app-1.0.0\launch.cmd # 현장 PC에서 실행
67
+ ```
68
+
69
+ 예제는 [`examples/vision-hmi`](https://github.com/cpprhtn/baro/tree/main/examples/vision-hmi)에 있습니다(numpy + OpenCV + PySide6).
70
+
71
+ ## `baro build`가 하는 일
72
+
73
+ 각 단계는 Windows 현장 PC에서 실제로 재현한 문제에 대응합니다.
74
+
75
+ | 단계 | 내용 | 막는 문제 |
76
+ | --- | --- | --- |
77
+ | 서명된 런타임 | python.org Windows embeddable을 받아 모든 PE의 Authenticode 서명(PSF·Microsoft)을 검증 | 미서명 인터프리터는 허용 목록 게시자 규칙을 못 씀 |
78
+ | 잠긴 의존성 | `uv.lock`에서 해시 포함으로 내보내 휠만 `--require-hashes`로 설치. 프로젝트는 wheel로 설치 | 빌드마다 다른 패키지, 변조된 휠 |
79
+ | 격리 | `._pth`로 `sys.path` 고정 | `PYTHONPATH`·`PYTHONHOME`·작업 폴더를 통한 오염 |
80
+ | 정리 | `site-packages/bin`(entry-point exe)과 패키지 내부 `tests` 제거 | 옮기면 깨지는 exe, 불필요한 허용 목록 항목 |
81
+ | 불변 번들 | `.pyc`를 unchecked-hash로, 빌드 경로를 지워 컴파일 | 반입 중 mtime이 바뀌면 번들에 다시 써서 무결성 검증이 깨짐 |
82
+ | 번들 밖 DLL 검사 | 모든 PE의 import를 분석해 VC++ 런타임 누락·드라이버 의존·미해결 DLL 보고 | "개발 PC에선 되는데 현장에선 DLL이 없음" |
83
+ | 스모크 테스트 | 번들의 python으로 진입 모듈을 import하고, 그 사이 번들에 쓰기가 생기는지 감지 | 빌드는 됐는데 실행이 안 되는 번들 |
84
+ | 매니페스트·서명 | 파일별 sha256 + ECDSA P-256 서명(Windows CNG로 검증 가능한 P1363 형식) | 반입 경로(USB·공유 폴더)에서의 변조 |
85
+ | 허용 목록 목록 | PE마다 sha256·서명자를 적고 "게시자 규칙 가능 / 해시 규칙 필요"로 분류 | 보안팀 승인 자료를 손으로 만드는 일 |
86
+
87
+ ## 출력
88
+
89
+ ```
90
+ dist/baro/<app_id>-<version>/ 번들 — 이 폴더만 현장 PC로 반입
91
+ runtime/ python.org embeddable (서명 검증됨)
92
+ site-packages/ 잠긴 의존성 + 프로젝트
93
+ app/__baro_main__.py 생성된 진입점 (캐시 경로를 번들 밖 data/로 돌림)
94
+ launch.cmd 실행 (gui 프로파일은 pythonw)
95
+ manifest.json, manifest.sig 파일 해시와 서명
96
+ dist/baro/<app_id>-<version>.baro/ 부속물 — 반입 대상 아님
97
+ build-report.json 단계별 결과, DLL 의존, 경고
98
+ allowlist/pe_files.csv, summary.txt 허용 목록 제출용
99
+ ```
100
+
101
+ 모든 명령은 `--json`을 지원합니다. 종료 코드는 고정입니다.
102
+
103
+ | 코드 | 의미 | 코드 | 의미 |
104
+ | --- | --- | --- | --- |
105
+ | 0 | 성공 | 6 | 번들 밖 DLL 의존 (`--strict-deps`) |
106
+ | 2 | `[tool.baro]` 설정 | 7 | 스모크 테스트 실패 |
107
+ | 3 | `uv.lock` 없음·오래됨 | 10 | 무결성 불일치 |
108
+ | 4 | 런타임 다운로드·서명 | 11 | 서명 검증 실패 |
109
+ | 5 | 의존성 설치 | 20 | 입출력 |
110
+
111
+ ## 설계 원칙 (요약)
112
+
113
+ - **현장 PC에 전역 설치 없음.** Python, 패키지, VC++ 런타임이 모두 번들 안에 있습니다.
114
+ - **번들은 baro 없이도 실행됩니다.** 평범한 폴더와 `python.exe`입니다.
115
+ - **기본으로 네트워크 접속 없음.** 런타임·패키지 다운로드는 빌드 PC에서만 합니다.
116
+ - **표준 그대로.** `pyproject.toml`과 `uv.lock`을 씁니다. 새 설정 언어는 없습니다.
117
+ - **릴리스 서명 키는 사람이 보관합니다.** 빌드·검증은 자동화해도, 출고 서명은 사람이 합니다.
118
+
119
+ ## 아직 안 되는 것
120
+
121
+ - 서명된 런처 exe (지금은 `launch.cmd`)
122
+ - 업데이트 패키지 생성과 장비 쪽 적용(apply)·롤백
123
+ - 허용 목록 제품별 import 형식 (AhnLab EPS, TXOne, WDAC 등)
124
+ - 서비스 프로파일 등록, Windows 외 빌드 호스트
125
+
126
+ ## 라이선스
127
+
128
+ [MIT](https://github.com/cpprhtn/baro/blob/main/LICENSE)
@@ -0,0 +1,19 @@
1
+ baro/__init__.py,sha256=qW3rHvVEBdXlRShN5NDZuU7FCw3PryRefnZ94eArrXw,103
2
+ baro/allowlist.py,sha256=rlgj3trD7SEJtxkY7t2W4VmqKFNQlz8ZsPiVBNPUU2s,2202
3
+ baro/authenticode.py,sha256=Oqn7Tf_OgugAEGhfrM7KzU9H_kQnrVo6mxMcYAgR78U,2396
4
+ baro/build.py,sha256=6CNr-9n6VQzMcbT1fmluoaSAY_5FWvLKeQcF9l4-ZQk,6467
5
+ baro/cli.py,sha256=P0BiKcqmSgVt6bQ539BxuVU1wxf9SNYDxi48LPhsbiQ,5798
6
+ baro/config.py,sha256=bmXNbnjoI332r_18O8mZVDdS-6C14EccQUmWznR6bFU,3530
7
+ baro/depscan.py,sha256=6dauRCiktcmvSP609KJ_qhAq8ehO8vOBBlU6NzqLLxk,3124
8
+ baro/errors.py,sha256=LUa3yToGdw-gAMmgMeykXR4-0KB5c6z12u2k5CDoK6s,1404
9
+ baro/install.py,sha256=s4iOOJokG_2llPlWXYHLFfq1N9TvJA0dJi4IbCVQGB8,2988
10
+ baro/layout.py,sha256=RcAJk_pby2lPnpYadxBgNMwmRbzWUOcedHhW63hL41s,4253
11
+ baro/manifest.py,sha256=NfXEeNl_Q2QsdRnKlDYl1M5I2lkwFVgOHu5z5OFbgoc,2549
12
+ baro/runtime.py,sha256=99JcqQKozfuHVZG35C1Gz5NEPfRtuk1kIRMG4z5bkfw,3618
13
+ baro/signing.py,sha256=QiMXKAKghPDjNo-pGpyF_xBQ8z_0xcMPSoKLXOEc60c,3150
14
+ baro/util.py,sha256=CuDx1DRfdzjoUVii3JqDCy7fsFT0PSIw5mnQ7JIesPw,1985
15
+ baro-0.1.0.dist-info/licenses/LICENSE,sha256=jehfcuZ12VxAgmOhwxAyQ1frU-G_8T7-jWlnBRqOFHg,1067
16
+ baro-0.1.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
17
+ baro-0.1.0.dist-info/entry_points.txt,sha256=KDakzJnogHQp1Pt-raDCqNYXpmP-1Fg4K3Cyo3H_8Zw,40
18
+ baro-0.1.0.dist-info/METADATA,sha256=UZSi7F09h3eYlv80U3VVWiGfOe0jlNf_xHr4qabViEg,6968
19
+ baro-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.10
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ baro = baro.cli:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Junwon Lee
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.