Branchwell

Jotley / app · jotley.ai / scripts / configure-signed-build.py

1#!/usr/bin/env python3
2"""Prepare private signing configuration; never provision, archive or upload an app."""
3import argparse
4import os
5from pathlib import Path
6import plistlib
7import re
8import subprocess
9from signing_identity import KINDS, local_signing_identity
10
11
12def main() -> None:
13 parser = argparse.ArgumentParser(description=__doc__)
14 parser.add_argument("platform", choices=["macos", "ios"])
15 parser.add_argument("--team", required=True, help="Apple developer team identifier")
16 parser.add_argument("--container", required=True, help="Provisioned CloudKit container")
17 parser.add_argument("--environment", choices=["development", "production"], default="development")
18 parser.add_argument("--signing-style", choices=["Automatic", "Manual"], help="Defaults to Manual for local Mac builds, Automatic for iOS")
19 parser.add_argument("--mac-signing-kind", choices=KINDS, help="Local Mac certificate type; production defaults to Developer ID for website distribution")
20 parser.add_argument("--signing-identity", help="Exact local Mac certificate name or SHA-1; selected only from login")
21 parser.add_argument("--mac-profile", help="Existing Mac provisioning profile name, applied only to the app target")
22 parser.add_argument("--isolated-local-test", action="store_true", help="Use a separate Mac test library and disable iCloud sync and updates")
23 parser.add_argument("--bundle-id", default="com.protomota.jotley", help="Existing Jotley listing identity; forks must use their own")
24 parser.add_argument("--build-number", required=True, type=int)
25 parser.add_argument("--version", default="2.3.0", help="Marketing version for this build")
26 parser.add_argument("--output", required=True, type=Path)
27 args = parser.parse_args()
28 signing_style = args.signing_style or ("Manual" if args.platform == "macos" else "Automatic")
29 if args.platform != "macos" and (args.mac_signing_kind or args.signing_identity or args.mac_profile):
30 parser.error("Mac signing options cannot be used for iOS. iOS uses Apple Development or Apple Distribution.")
31 if args.isolated_local_test and (args.platform != "macos" or args.environment != "development" or args.mac_signing_kind not in (None, "development")):
32 parser.error("An isolated local test requires a Mac development build.")
33 if args.mac_profile and any(c in args.mac_profile for c in ['\n', '\r', '"', '$']):
34 parser.error("Profile name contains unsupported xcconfig characters.")
35 if not re.fullmatch(r"[A-Z0-9]{10}", args.team):
36 parser.error("Team must be a ten-character Apple developer team identifier.")
37 if not re.fullmatch(r"iCloud\.[A-Za-z0-9.-]+", args.container):
38 parser.error("Container must start with iCloud. and contain only identifier characters.")
39 if not re.fullmatch(r"[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+", args.bundle_id):
40 parser.error("Invalid bundle identifier.")
41 if args.build_number < 1:
42 parser.error("Build number must be positive and newer than the listing's existing builds.")
43 if not re.fullmatch(r"\d+\.\d+(?:\.\d+)?", args.version):
44 parser.error("Version must contain two or three numeric components.")
45 identity = "Apple Development" if args.environment == "development" else "Apple Distribution"
46 if args.platform == "macos":
47 kind = args.mac_signing_kind or ("development" if args.environment == "development" else "developer-id")
48 if signing_style == "Automatic" and (kind != "development" or args.mac_profile):
49 parser.error("Automatic Mac signing uses an installed Xcode-managed development profile. Use Manual for an explicit profile or distribution identity.")
50 try:
51 identity = local_signing_identity(args.signing_identity or KINDS[kind], kind)
52 except ValueError as error:
53 parser.error(str(error))
54 if signing_style == "Automatic":
55 identity = KINDS[kind]
56 repo = Path(__file__).resolve().parent.parent
57 output = args.output.expanduser().resolve()
58 if any(c in str(output) for c in ['\n', '\r', '"', '$']):
59 parser.error("Output path contains unsupported xcconfig characters.")
60 if output.is_relative_to(repo):
61 relative = output.relative_to(repo)
62 if subprocess.run(["git", "check-ignore", "-q", "--", str(relative)], cwd=repo).returncode:
63 parser.error("Signing configuration inside the checkout must be git-ignored (use .private-release/).")
64 paths = [output / name for name in ["Info.plist", "Jotley.entitlements", "Signing.xcconfig"]]
65 widget_paths = [output / name for name in ["Widget-Info.plist", "Widget.entitlements"]] if args.platform == "ios" else []
66 if any(path.exists() for path in paths + widget_paths):
67 parser.error("Output already contains configuration; use a fresh directory to avoid overwriting it.")
68 source = repo / ("macOS" if args.platform == "macos" else "iOS")
69 with (source / "Info.plist").open("rb") as handle:
70 info = plistlib.load(handle)
71 info.update(CFBundleDisplayName="Jotley", CFBundleIdentifier="$(PRODUCT_BUNDLE_IDENTIFIER)",
72 CFBundleShortVersionString="$(MARKETING_VERSION)", CFBundleVersion="$(CURRENT_PROJECT_VERSION)",
73 JotleyCloudKitContainerIdentifier=args.container, ITSAppUsesNonExemptEncryption=False)
74 if args.platform == "ios":
75 info["UIBackgroundModes"] = list(dict.fromkeys(info.get("UIBackgroundModes", []) + ["remote-notification"]))
76 with (source / "Jotley.entitlements").open("rb") as handle:
77 entitlements = plistlib.load(handle)
78 if args.platform == "macos" and kind == "developer-id" and entitlements.get("com.apple.developer.applesignin"):
79 parser.error("Developer ID does not support native Sign in with Apple. Use a development build for local testing; website distribution needs browser-based sign-in before signing.")
80 entitlements.update({"com.apple.developer.icloud-container-identifiers": [args.container],
81 "com.apple.developer.ubiquity-kvstore-identifier": args.team + "." + args.bundle_id,
82 "com.apple.developer.icloud-services": ["CloudKit"],
83 "com.apple.developer.icloud-container-environment": args.environment.capitalize(),
84 "com.apple.developer.aps-environment" if args.platform == "macos" else "aps-environment": args.environment})
85 if args.platform == "macos":
86 entitlements["com.apple.security.network.client"] = True
87 # These entitlements are also passed directly to codesign during packaging.
88 # Only Xcode expands build settings in an entitlements file.
89 installer_lookup = "com.apple.security.temporary-exception.mach-lookup.global-name"
90 if installer_lookup in entitlements:
91 entitlements[installer_lookup] = [
92 service.replace("$(PRODUCT_BUNDLE_IDENTIFIER)", args.bundle_id)
93 for service in entitlements[installer_lookup]
94 ]
95 info["SUEnableDownloaderService"] = False
96 if kind == "developer-id" and args.environment == "production":
97 info["JotleyEnableSparkle"] = True
98 if args.isolated_local_test:
99 info.update(CFBundleDisplayName="Jotley Test", CFBundleName="Jotley Test",
100 JotleyIsolatedLocalTest=True, JotleyEnableSparkle=False)
101 info.pop("JotleyCloudKitContainerIdentifier", None)
102 for key in ["com.apple.developer.icloud-container-identifiers", "com.apple.developer.ubiquity-kvstore-identifier",
103 "com.apple.developer.icloud-services", "com.apple.developer.icloud-container-environment",
104 "com.apple.developer.aps-environment"]:
105 entitlements.pop(key, None)
106 output.mkdir(parents=True, exist_ok=True, mode=0o700)
107 for path, value in zip(paths[:2], [info, entitlements]):
108 with path.open("wb") as handle:
109 plistlib.dump(value, handle)
110 os.chmod(path, 0o600)
111 if widget_paths:
112 widget_info = plistlib.loads((repo / "JotleyWidgets" / "Info.plist").read_bytes())
113 widget_info.update(CFBundleIdentifier="$(PRODUCT_BUNDLE_IDENTIFIER)",
114 CFBundleShortVersionString="$(MARKETING_VERSION)",
115 CFBundleVersion="$(CURRENT_PROJECT_VERSION)")
116 for path, value in zip(widget_paths, [widget_info, {}]):
117 path.write_bytes(plistlib.dumps(value)); os.chmod(path, 0o600)
118 config = f'''// Private build configuration. Generated files must not be committed.
119DEVELOPMENT_TEAM = {args.team}
120PRODUCT_BUNDLE_IDENTIFIER = {args.bundle_id}
121MARKETING_VERSION = {args.version}
122CURRENT_PROJECT_VERSION = {args.build_number}
123CODE_SIGN_STYLE = {signing_style}
124CODE_SIGN_IDENTITY = {identity}
125CODE_SIGN_ENTITLEMENTS = {paths[1]}
126INFOPLIST_FILE = {paths[0]}
127'''
128 if args.platform == "ios":
129 # -xcconfig applies to every archive target. Resolve target-specific
130 # settings so the extension never receives the app's identity/profile,
131 # CloudKit entitlements or application Info.plist.
132 config += f'''TARGETED_DEVICE_FAMILY = 1,2
133JOTLEY_TARGET_KEY = $(TARGET_NAME:c99extidentifier)
134JOTLEY_BUNDLE_Jotley_iOS = {args.bundle_id}
135JOTLEY_BUNDLE_JotleyWidgetsExtension = {args.bundle_id}.JotleyWidgets
136JOTLEY_INFO_Jotley_iOS = {paths[0]}
137JOTLEY_INFO_JotleyWidgetsExtension = {widget_paths[0]}
138JOTLEY_MICROPHONE_Jotley_iOS = Jotley uses your microphone for live, on-device transcription. No audio files are saved.
139INFOPLIST_KEY_NSMicrophoneUsageDescription = $(JOTLEY_MICROPHONE_$(JOTLEY_TARGET_KEY))
140JOTLEY_ENTITLEMENTS_Jotley_iOS = {paths[1]}
141JOTLEY_ENTITLEMENTS_JotleyWidgetsExtension = {widget_paths[1]}
142PRODUCT_BUNDLE_IDENTIFIER = $(JOTLEY_BUNDLE_$(JOTLEY_TARGET_KEY))
143INFOPLIST_FILE = $(JOTLEY_INFO_$(JOTLEY_TARGET_KEY))
144CODE_SIGN_ENTITLEMENTS = $(JOTLEY_ENTITLEMENTS_$(JOTLEY_TARGET_KEY))
145PROVISIONING_PROFILE_SPECIFIER = $(JOTLEY_PROFILE_$(JOTLEY_TARGET_KEY))
146'''
147 else:
148 # An override xcconfig also reaches SwiftPM resource bundles. Keep the
149 # app's identity, profile and entitlements off the NIO resource target.
150 config += f'''JOTLEY_TARGET_KEY = $(TARGET_NAME:c99extidentifier)
151JOTLEY_BUNDLE_Jotley = {args.bundle_id}
152JOTLEY_BUNDLE_swift_nio_NIOPosix = swift-nio.NIOPosix.resources
153JOTLEY_INFO_Jotley = {paths[0]}
154JOTLEY_ENTITLEMENTS_Jotley = {paths[1]}
155JOTLEY_IDENTITY_Jotley = {identity}
156JOTLEY_IDENTITY_swift_nio_NIOPosix = -
157JOTLEY_PROFILE_Jotley = {args.mac_profile or ""}
158PRODUCT_BUNDLE_IDENTIFIER = $(JOTLEY_BUNDLE_$(JOTLEY_TARGET_KEY))
159INFOPLIST_FILE = $(JOTLEY_INFO_$(JOTLEY_TARGET_KEY))
160CODE_SIGN_ENTITLEMENTS = $(JOTLEY_ENTITLEMENTS_$(JOTLEY_TARGET_KEY))
161CODE_SIGN_IDENTITY = $(JOTLEY_IDENTITY_$(JOTLEY_TARGET_KEY))
162PROVISIONING_PROFILE_SPECIFIER = $(JOTLEY_PROFILE_$(JOTLEY_TARGET_KEY))
163ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES
164'''
165 config += f'OTHER_CODE_SIGN_FLAGS = $(inherited) --keychain "{Path.home() / "Library/Keychains/login.keychain-db"}"\n'
166 paths[2].write_text(config)
167 os.chmod(paths[2], 0o600)
168 print(paths[2])
169
170
171if __name__ == "__main__":
172 main()