baro 0.1.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.
baro-0.1.0/LICENSE ADDED
@@ -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.
baro-0.1.0/PKG-INFO ADDED
@@ -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)
baro-0.1.0/README.md ADDED
@@ -0,0 +1,98 @@
1
+ # baro
2
+
3
+ **폐쇄망·내부망 Windows PC에 Python 앱을 폴더 하나로 넣기 위한 빌드 도구.**
4
+
5
+ 인터넷도 Python도 없는 현장 PC(공장 장비, 검사 PC, 내부망 업무 PC)에 Python 앱을 배포하면 문제가 반복됩니다. 개발 PC에서는 되는데 현장에서는 DLL이 없다고 뜨고, 보안팀은 서명 없는 실행 파일 수천 개를 승인해야 하며, 반입 중에 파일이 바뀌어도 알 방법이 없습니다. baro는 `pyproject.toml`과 `uv.lock`에서 **검증된 폴더 번들**을 만들어 이 문제를 빌드 단계에서 막습니다.
6
+
7
+ > **상태: v0.1 (pre-alpha).** 빌드 쪽 골격만 있습니다. API와 출력 형식은 바뀔 수 있습니다. Windows 10/11 x64 빌드 PC가 필요합니다.
8
+
9
+ ## 설치
10
+
11
+ ```powershell
12
+ uv tool install baro # 또는: pip install baro
13
+ ```
14
+
15
+ 빌드 PC에 [uv](https://docs.astral.sh/uv/)가 있어야 합니다. 대상(현장) PC에는 아무것도 설치하지 않습니다.
16
+
17
+ ## 빠른 시작
18
+
19
+ `pyproject.toml`에 `[tool.baro]`를 추가합니다.
20
+
21
+ ```toml
22
+ [tool.baro]
23
+ python = "3.14.10" # 패치 버전까지 고정 (재현 빌드)
24
+ entry = "vision_hmi.app:main" # "모듈:함수" 또는 "모듈"
25
+ profile = "gui" # gui | service | job (자동 감지하지 않음)
26
+ # app_id = "vision-hmi" # 기본값: [project].name
27
+ # prune_tests = true # 패키지 내부 tests 폴더 제거
28
+ # exclude = ["PySide6/qml/*"] # site-packages 기준 glob으로 제외
29
+ ```
30
+
31
+ ```powershell
32
+ uv lock
33
+ baro keygen --out C:\keys # 릴리스 서명 키 (개인키는 사람이 보관)
34
+ baro build . --sign-key C:\keys\baro-release.key.pem
35
+ baro verify dist\baro\my-app-1.0.0 --pubkey C:\keys\baro-release.pub.pem
36
+ dist\baro\my-app-1.0.0\launch.cmd # 현장 PC에서 실행
37
+ ```
38
+
39
+ 예제는 [`examples/vision-hmi`](https://github.com/cpprhtn/baro/tree/main/examples/vision-hmi)에 있습니다(numpy + OpenCV + PySide6).
40
+
41
+ ## `baro build`가 하는 일
42
+
43
+ 각 단계는 Windows 현장 PC에서 실제로 재현한 문제에 대응합니다.
44
+
45
+ | 단계 | 내용 | 막는 문제 |
46
+ | --- | --- | --- |
47
+ | 서명된 런타임 | python.org Windows embeddable을 받아 모든 PE의 Authenticode 서명(PSF·Microsoft)을 검증 | 미서명 인터프리터는 허용 목록 게시자 규칙을 못 씀 |
48
+ | 잠긴 의존성 | `uv.lock`에서 해시 포함으로 내보내 휠만 `--require-hashes`로 설치. 프로젝트는 wheel로 설치 | 빌드마다 다른 패키지, 변조된 휠 |
49
+ | 격리 | `._pth`로 `sys.path` 고정 | `PYTHONPATH`·`PYTHONHOME`·작업 폴더를 통한 오염 |
50
+ | 정리 | `site-packages/bin`(entry-point exe)과 패키지 내부 `tests` 제거 | 옮기면 깨지는 exe, 불필요한 허용 목록 항목 |
51
+ | 불변 번들 | `.pyc`를 unchecked-hash로, 빌드 경로를 지워 컴파일 | 반입 중 mtime이 바뀌면 번들에 다시 써서 무결성 검증이 깨짐 |
52
+ | 번들 밖 DLL 검사 | 모든 PE의 import를 분석해 VC++ 런타임 누락·드라이버 의존·미해결 DLL 보고 | "개발 PC에선 되는데 현장에선 DLL이 없음" |
53
+ | 스모크 테스트 | 번들의 python으로 진입 모듈을 import하고, 그 사이 번들에 쓰기가 생기는지 감지 | 빌드는 됐는데 실행이 안 되는 번들 |
54
+ | 매니페스트·서명 | 파일별 sha256 + ECDSA P-256 서명(Windows CNG로 검증 가능한 P1363 형식) | 반입 경로(USB·공유 폴더)에서의 변조 |
55
+ | 허용 목록 목록 | PE마다 sha256·서명자를 적고 "게시자 규칙 가능 / 해시 규칙 필요"로 분류 | 보안팀 승인 자료를 손으로 만드는 일 |
56
+
57
+ ## 출력
58
+
59
+ ```
60
+ dist/baro/<app_id>-<version>/ 번들 — 이 폴더만 현장 PC로 반입
61
+ runtime/ python.org embeddable (서명 검증됨)
62
+ site-packages/ 잠긴 의존성 + 프로젝트
63
+ app/__baro_main__.py 생성된 진입점 (캐시 경로를 번들 밖 data/로 돌림)
64
+ launch.cmd 실행 (gui 프로파일은 pythonw)
65
+ manifest.json, manifest.sig 파일 해시와 서명
66
+ dist/baro/<app_id>-<version>.baro/ 부속물 — 반입 대상 아님
67
+ build-report.json 단계별 결과, DLL 의존, 경고
68
+ allowlist/pe_files.csv, summary.txt 허용 목록 제출용
69
+ ```
70
+
71
+ 모든 명령은 `--json`을 지원합니다. 종료 코드는 고정입니다.
72
+
73
+ | 코드 | 의미 | 코드 | 의미 |
74
+ | --- | --- | --- | --- |
75
+ | 0 | 성공 | 6 | 번들 밖 DLL 의존 (`--strict-deps`) |
76
+ | 2 | `[tool.baro]` 설정 | 7 | 스모크 테스트 실패 |
77
+ | 3 | `uv.lock` 없음·오래됨 | 10 | 무결성 불일치 |
78
+ | 4 | 런타임 다운로드·서명 | 11 | 서명 검증 실패 |
79
+ | 5 | 의존성 설치 | 20 | 입출력 |
80
+
81
+ ## 설계 원칙 (요약)
82
+
83
+ - **현장 PC에 전역 설치 없음.** Python, 패키지, VC++ 런타임이 모두 번들 안에 있습니다.
84
+ - **번들은 baro 없이도 실행됩니다.** 평범한 폴더와 `python.exe`입니다.
85
+ - **기본으로 네트워크 접속 없음.** 런타임·패키지 다운로드는 빌드 PC에서만 합니다.
86
+ - **표준 그대로.** `pyproject.toml`과 `uv.lock`을 씁니다. 새 설정 언어는 없습니다.
87
+ - **릴리스 서명 키는 사람이 보관합니다.** 빌드·검증은 자동화해도, 출고 서명은 사람이 합니다.
88
+
89
+ ## 아직 안 되는 것
90
+
91
+ - 서명된 런처 exe (지금은 `launch.cmd`)
92
+ - 업데이트 패키지 생성과 장비 쪽 적용(apply)·롤백
93
+ - 허용 목록 제품별 import 형식 (AhnLab EPS, TXOne, WDAC 등)
94
+ - 서비스 프로파일 등록, Windows 외 빌드 호스트
95
+
96
+ ## 라이선스
97
+
98
+ [MIT](https://github.com/cpprhtn/baro/blob/main/LICENSE)
@@ -0,0 +1,58 @@
1
+ [project]
2
+ name = "baro"
3
+ version = "0.1.0"
4
+ description = "폐쇄망·내부망 Windows PC용 Python 앱 번들 빌드 도구"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ keywords = [
10
+ "air-gapped",
11
+ "offline",
12
+ "deployment",
13
+ "windows",
14
+ "bundle",
15
+ "allowlisting",
16
+ "ot",
17
+ ]
18
+ classifiers = [
19
+ "Development Status :: 2 - Pre-Alpha",
20
+ "Environment :: Console",
21
+ "Intended Audience :: Developers",
22
+ "Intended Audience :: Manufacturing",
23
+ "Natural Language :: Korean",
24
+ "Operating System :: Microsoft :: Windows",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.11",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Programming Language :: Python :: 3.13",
29
+ "Programming Language :: Python :: 3.14",
30
+ "Topic :: Software Development :: Build Tools",
31
+ "Topic :: System :: Software Distribution",
32
+ ]
33
+ dependencies = [
34
+ "cryptography>=42",
35
+ "pefile>=2023.2.7",
36
+ ]
37
+
38
+ [[project.authors]]
39
+ name = "cpprhtn"
40
+ email = "cpprhtn@gmail.com"
41
+
42
+ [project.scripts]
43
+ baro = "baro.cli:main"
44
+
45
+ [project.urls]
46
+ Homepage = "https://github.com/cpprhtn/baro"
47
+ Repository = "https://github.com/cpprhtn/baro"
48
+ Issues = "https://github.com/cpprhtn/baro/issues"
49
+
50
+ [dependency-groups]
51
+ dev = ["pytest>=8"]
52
+
53
+ [build-system]
54
+ requires = ["uv_build>=0.10,<0.11"]
55
+ build-backend = "uv_build"
56
+
57
+ [tool.pytest.ini_options]
58
+ testpaths = ["tests"]
@@ -0,0 +1,47 @@
1
+ [project]
2
+ name = "baro"
3
+ version = "0.1.0"
4
+ description = "폐쇄망·내부망 Windows PC용 Python 앱 번들 빌드 도구"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "cpprhtn", email = "cpprhtn@gmail.com" }]
10
+ keywords = ["air-gapped", "offline", "deployment", "windows", "bundle", "allowlisting", "ot"]
11
+ classifiers = [
12
+ "Development Status :: 2 - Pre-Alpha",
13
+ "Environment :: Console",
14
+ "Intended Audience :: Developers",
15
+ "Intended Audience :: Manufacturing",
16
+ "Natural Language :: Korean",
17
+ "Operating System :: Microsoft :: Windows",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Topic :: Software Development :: Build Tools",
24
+ "Topic :: System :: Software Distribution",
25
+ ]
26
+ dependencies = [
27
+ "cryptography>=42",
28
+ "pefile>=2023.2.7",
29
+ ]
30
+
31
+ [project.scripts]
32
+ baro = "baro.cli:main"
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/cpprhtn/baro"
36
+ Repository = "https://github.com/cpprhtn/baro"
37
+ Issues = "https://github.com/cpprhtn/baro/issues"
38
+
39
+ [dependency-groups]
40
+ dev = ["pytest>=8"]
41
+
42
+ [build-system]
43
+ requires = ["uv_build>=0.10,<0.11"]
44
+ build-backend = "uv_build"
45
+
46
+ [tool.pytest.ini_options]
47
+ testpaths = ["tests"]
@@ -0,0 +1,3 @@
1
+ """baro: 폐쇄망·내부망 Windows PC용 Python 앱 번들 빌드 도구."""
2
+
3
+ __version__ = "0.1.0"
@@ -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
@@ -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}
@@ -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