{{ message }}
Repository navigation
Expand file tree
/
Copy pathBuild-Project.command
More file actions
executable file
·285 lines (238 loc) · 12.7 KB
/
Copy pathBuild-Project.command
File metadata and controls
executable file
·285 lines (238 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#!/usr/bin/env python3
"""
Build-Project.command: Generate OpenCore-Patcher-T2.app and OpenCore-Patcher-T2.pkg
"""
import os
import re
import sys
import time
import argparse
import traceback
import subprocess
import threading
import rich
from rich.live import Live
from rich.spinner import Spinner
from pathlib import Path
# Fix: Force the execution directory immediately before importing local modules.
# This guarantees that 'ci_tooling' looks for assets in the right relative path.
SCRIPT_DIR = Path(__file__).resolve().parent
os.chdir(SCRIPT_DIR)
# Import der internen Module
from ci_tooling.build_modules import (
application,
disk_images,
package,
sign_notarize,
hash as hash_pkg
)
TOTAL_STEPS = 9
# Written by the build thread, read by the spinner in the main thread.
status = f"[0/{TOTAL_STEPS}] Starting"
# Filled in by _run_build(). "completed" is only True when main() returned normally,
# so the "Build script completed" line can never be printed after a failed build.
# Do NOT replace this with a module level flag assigned inside main(): an assignment
# there creates a function local unless 'global' is declared, and the module level
# value stays False forever - the failure mode this structure exists to prevent.
build_result = {"exit_code": 0, "completed": False}
def check_file_exists(path: Path) -> None:
if not path.exists():
rich.print(f"[red]Error: Expected file/directory not found: {path}[/red]")
sys.exit(3)
def available_codesigning_identities() -> list:
"""
Return (SHA-1 hash, name, status) for every valid code signing identity in the keychain
'security find-identity -v' already filters out expired or otherwise unusable
certificates. A self signed "Code Signing" certificate made in Keychain Access shows
up here exactly like a Developer ID one.
"""
if sys.platform != "darwin":
return []
try:
result = subprocess.run(
["/usr/bin/security", "find-identity", "-v", "-p", "codesigning"],
capture_output=True, text=True, timeout=30,
)
except (OSError, subprocess.SubprocessError) as e:
rich.print(f"[yellow]Warning: could not query signing identities: {e}[/yellow]")
return []
identities = []
for line in result.stdout.splitlines():
# "security find-identity" hängt bei nicht vertrauenswuerdigen Zertifikaten
# eine Statusmeldung an, z.B. (CSSMERR_TP_NOT_TRUSTED). Ein selbst signiertes
# Zertifikat ist damit trotzdem brauchbar: das Helper Tool vergleicht nur die
# Zertifikatsketten und fuehrt keine Trust-Pruefung durch.
#
# "security find-identity" appends a status note for certificates that are not
# trusted, e.g. (CSSMERR_TP_NOT_TRUSTED). A self signed certificate still works:
# the helper tool only compares certificate chains and runs no trust evaluation.
match = re.match(r'\s*\d+\)\s+([0-9A-Fa-f]{40})\s+"(.+?)"\s*(\(CSSMERR_[A-Z_]+\))?\s*$', line)
if match:
identities.append((match.group(1), match.group(2), match.group(3)))
return identities
def resolve_application_identity(requested: str, auto_detect: bool) -> "str | None":
"""
Decide which identity the app and the privileged helper tool get signed with
Both must end up carrying the same certificate: at runtime the helper compares its own
certificate chain against its parent process' chain (ci_tooling/privileged_helper_tool/main.m)
and refuses to run anything as root when they differ. It runs no trust evaluation, so a
self signed certificate satisfies it just as well as a Developer ID one - but an unsigned
or ad-hoc signed build carries no certificates at all and can never pass.
"""
requested = requested or os.environ.get("MACOS_SIGNING_IDENTITY")
identities = available_codesigning_identities()
if requested:
# Only reject when the lookup actually returned something; an empty list means the
# query failed or we are not on macOS, which is not evidence the identity is missing.
if identities and not any(requested in (identity_hash, name) for identity_hash, name, _ in identities):
rich.print(f"[red]Error: no valid signing identity found matching: {requested}[/red]")
available = ", ".join(f'"{name}"' for _, name, _ in identities) or "none"
rich.print(f"[yellow]Available: {available}[/yellow]")
sys.exit(3)
return requested
if auto_detect is False:
return None
if not identities:
rich.print(f"[yellow]Note: no code signing certificate found, the app and helper tool stay unsigned.[/yellow]")
rich.print(f"[yellow] The privileged helper tool will refuse to run commands as root unless it was[/yellow]")
rich.print(f"[yellow] compiled with 'make debug' (ci_tooling/privileged_helper_tool/README.md).[/yellow]")
rich.print(f"[yellow] To sign locally, create a self signed certificate in Keychain Access:[/yellow]")
rich.print(f"[yellow] Certificate Assistant > Create a Certificate > Self Signed Root, type Code Signing.[/yellow]")
return None
if len(identities) > 1:
rich.print(f"[yellow]Note: multiple code signing certificates found, none picked automatically:[/yellow]")
for _, name, _ in identities:
rich.print(f"[yellow] - {name}[/yellow]")
rich.print(f"[yellow] Pass --application-signing-identity \"<name>\" to choose one.[/yellow]")
return None
_, name, identity_status = identities[0]
rich.print(f"[yellow]Automatically selected signing identity: {name}[/yellow]")
if identity_status:
rich.print(f"[yellow] Note: certificate is not trusted {identity_status} - that is enough for signing,[/yellow]")
rich.print(f"[yellow] the helper tool only compares certificate chains.[/yellow]")
return name
def main() -> None:
global status
parser = argparse.ArgumentParser(description="Build OpenCore Legacy Patcher Suite")
# Signing & Notarization
parser.add_argument("--application-signing-identity", type=str, help="Application Signing Identity")
parser.add_argument("--installer-signing-identity", type=str, help="Installer Signing Identity")
parser.add_argument("--notarization-apple-id", type=str, help="Notarization Apple ID")
parser.add_argument("--notarization-password", type=str, help="Notarization Password (Alternative: Env Var)")
parser.add_argument("--notarization-team-id", type=str, help="Notarization Team ID")
# CI/CD & Local Build Parameters
parser.add_argument("--git-branch", type=str, default=None)
parser.add_argument("--git-commit-url", type=str, default=None)
parser.add_argument("--git-commit-date", type=str, default=None)
parser.add_argument("--reset-dmg-cache", action="store_true")
parser.add_argument("--reset-pyinstaller-cache", action="store_true")
parser.add_argument("--no-auto-detect-identity", action="store_true", help="Never pick a signing identity from the keychain automatically")
# Steps
parser.add_argument("--run-as-individual-steps", action="store_true")
parser.add_argument("--prepare-application", action="store_true")
parser.add_argument("--prepare-package", action="store_true")
parser.add_argument("--prepare-assets", action="store_true")
args = parser.parse_args()
# Passwort-Sicherheit: Umgebungsvariable hat Vorrang vor CLI-Argument
notarization_password = os.environ.get("NOTARIZATION_PASSWORD") or args.notarization_password
# Resolved once, so the app and the helper tool can never end up signed with two different
# certificates - which would make the helper reject the app at runtime.
application_signing_identity = resolve_application_identity(
args.application_signing_identity,
auto_detect=args.no_auto_detect_identity is False,
)
try:
# 1. Assets
if (args.run_as_individual_steps is False) or (args.run_as_individual_steps and args.prepare_assets):
status = f"[1/{TOTAL_STEPS}] Generating disk images"
disk_images.GenerateDiskImages(args.reset_dmg_cache).generate()
# 2. Application
if (args.run_as_individual_steps is False) or (args.run_as_individual_steps and args.prepare_application):
status = f"[2/{TOTAL_STEPS}] Signing Helper Tool"
sign_notarize.SignAndNotarize(
path=Path("./ci_tooling/privileged_helper_tool/com.dortania.opencore-legacy-patcher.privileged-helper"),
signing_identity=application_signing_identity,
notarization_apple_id=args.notarization_apple_id,
notarization_password=notarization_password,
notarization_team_id=args.notarization_team_id,
).sign_and_notarize()
status = f"[3/{TOTAL_STEPS}] Building the app"
application.GenerateApplication(
reset_pyinstaller_cache=args.reset_pyinstaller_cache,
git_branch=args.git_branch,
git_commit_url=args.git_commit_url,
git_commit_date=args.git_commit_date,
).generate()
check_file_exists(Path("dist/OpenCore-Patcher-T2.app"))
status = f"[4/{TOTAL_STEPS}] Signing the app"
sign_notarize.SignAndNotarize(
path=Path("dist/OpenCore-Patcher-T2.app"),
signing_identity=application_signing_identity,
notarization_apple_id=args.notarization_apple_id,
notarization_password=notarization_password,
notarization_team_id=args.notarization_team_id,
entitlements=Path("./ci_tooling/entitlements/entitlements.plist"),
).sign_and_notarize()
# 3. Packages
if (args.run_as_individual_steps is False) or (args.run_as_individual_steps and args.prepare_package):
status = f"[5/{TOTAL_STEPS}] Building packages"
package.GeneratePackage().generate()
# AutoPkg-Assets-T2.pkg is installed by the app itself during auto patching,
# so it needs a signature just as much as the two user facing packages.
step = 6
for pkg in ["OpenCore-Patcher-T2.pkg", "OpenCore-Patcher-Uninstaller.pkg", "AutoPkg-Assets-T2.pkg"]:
pkg_path = Path(f"dist/{pkg}")
check_file_exists(pkg_path)
status = f"[{step}/{TOTAL_STEPS}] Signing {pkg}"
sign_notarize.SignAndNotarize(
path=pkg_path,
signing_identity=args.installer_signing_identity,
notarization_apple_id=args.notarization_apple_id,
notarization_password=notarization_password,
notarization_team_id=args.notarization_team_id,
).sign_and_notarize()
step += 1
status = f"[{TOTAL_STEPS}/{TOTAL_STEPS}] Generating hashes"
hash_pkg.GenerateHash()
except Exception as e:
# Closing tag must match the opening one - rich raises MarkupError on a mismatch,
# which would replace the real build error with a markup error.
rich.print(f"\n[red] Building the app stopped because of some error: {e}[/red]")
# Print the traceback too. Without it the message alone gives no file or line,
# which turns any error raised deep in a build module into a repo-wide hunt.
traceback.print_exc()
sys.exit(3)
def _run_build() -> None:
"""
Thread entry point
sys.exit() inside a thread only unwinds that thread, it does not set the process
exit code. Every failure is recorded here instead, so __main__ can exit non-zero
and CI actually fails on a broken build.
"""
try:
main()
except SystemExit as e:
build_result["exit_code"] = e.code if isinstance(e.code, int) else (0 if e.code is None else 1)
except BaseException:
traceback.print_exc()
build_result["exit_code"] = 1
else:
build_result["completed"] = True
if __name__ == '__main__':
_start = time.time()
thread = threading.Thread(target=_run_build)
thread.start()
spinner = Spinner("dots", text=status)
with Live(spinner, refresh_per_second=10):
while thread.is_alive():
spinner.update(text=status)
time.sleep(0.1)
spinner.update(text=status)
thread.join()
if build_result["exit_code"] != 0:
sys.exit(build_result["exit_code"])
if build_result["completed"] is False:
# main() left early without failing, e.g. argparse handled --help.
sys.exit(0)
else: # behebt einen Fehler, indem es ohne Bedingung Build script completed ausdruckt; diesmal nicht richtig eine Sicherheitslücke
rich.print(f"\n[green]Build script completed in {str(round(time.time() - _start, 2))} seconds.[/green]")
You can’t perform that action at this time.
