diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png index c31db1f..85fa3ea 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-120.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-120.png index 94167ae..6cb7bf3 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-120.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-120.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-152.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-152.png index 213afec..adf2026 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-152.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-152.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-167.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-167.png index 9e35c34..8fb67cf 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-167.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-167.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-180.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-180.png index 29b7788..09d1d3e 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-180.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-180.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-20.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-20.png index e8fa7b9..e694805 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-20.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-20.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-29.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-29.png index 7112c4f..1dc4d45 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-29.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-29.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-40.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-40.png index 7c61a2c..da0a105 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-40.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-40.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-58.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-58.png index c3ef7a2..35e94b4 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-58.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-58.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-60.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-60.png index f8d7f81..0ea49ba 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-60.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-60.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-76.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-76.png index 049778a..00d9dbf 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-76.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-76.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-80.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-80.png index 642d38a..2b7e991 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-80.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-80.png differ diff --git a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-87.png b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-87.png index 67cebd3..1c3f33d 100644 Binary files a/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-87.png and b/Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset/AppIcon-87.png differ diff --git a/Apps/iOS/BetterFitApp/Resources/PrivacyInfo.xcprivacy b/Apps/iOS/BetterFitApp/Resources/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..f0db006 --- /dev/null +++ b/Apps/iOS/BetterFitApp/Resources/PrivacyInfo.xcprivacy @@ -0,0 +1,17 @@ + + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + + diff --git a/Apps/iOS/BetterFitAppUITests/GuestStartupUITests.swift b/Apps/iOS/BetterFitAppUITests/GuestStartupUITests.swift new file mode 100644 index 0000000..6c94647 --- /dev/null +++ b/Apps/iOS/BetterFitAppUITests/GuestStartupUITests.swift @@ -0,0 +1,20 @@ +import XCTest + +final class GuestStartupUITests: XCTestCase { + func testNormalLaunchWithoutBackendReachesGuestTabs() throws { + continueAfterFailure = false + let app = XCUIApplication() + app.launchArguments = [] + app.launchEnvironment = ["SUPABASE_URL": "", "SUPABASE_ANON_KEY": ""] + app.launch() + defer { app.terminate() } + + let tabs = app.tabBars.firstMatch + XCTAssertTrue(tabs.waitForExistence(timeout: 10)) + XCTAssertEqual(tabs.buttons.count, 4) + XCTAssertTrue(tabs.buttons["Workout"].exists) + XCTAssertTrue(tabs.buttons["Body"].exists) + XCTAssertTrue(tabs.buttons["Targets"].exists) + XCTAssertTrue(tabs.buttons["Log"].exists) + } +} diff --git a/Apps/iOS/project.yml b/Apps/iOS/project.yml index bb4692f..3ca9493 100644 --- a/Apps/iOS/project.yml +++ b/Apps/iOS/project.yml @@ -29,7 +29,17 @@ targets: path: BetterFitApp/Info.plist properties: CFBundleDisplayName: BetterFit + CFBundleShortVersionString: $(MARKETING_VERSION) + CFBundleVersion: $(CURRENT_PROJECT_VERSION) + BetterFitBackend: $(BETTERFIT_BACKEND) + SUPABASE_URL: $(BETTERFIT_SUPABASE_URL) + SUPABASE_ANON_KEY: $(BETTERFIT_SUPABASE_ANON_KEY) UILaunchScreen: {} + UISupportedInterfaceOrientations~ipad: + - UIInterfaceOrientationPortrait + - UIInterfaceOrientationPortraitUpsideDown + - UIInterfaceOrientationLandscapeLeft + - UIInterfaceOrientationLandscapeRight UIAppFonts: - BBHHegarty-Regular.ttf NSHealthShareUsageDescription: BetterFit reads your health data to track workouts, monitor recovery, and provide personalized fitness insights. @@ -45,6 +55,11 @@ targets: CODE_SIGN_ENTITLEMENTS: BetterFitApp/BetterFitApp.entitlements CODE_SIGN_STYLE: Automatic DEVELOPMENT_TEAM: ${DEVELOPMENT_TEAM} + MARKETING_VERSION: "1.0" + CURRENT_PROJECT_VERSION: "1" + BETTERFIT_BACKEND: "" + BETTERFIT_SUPABASE_URL: "" + BETTERFIT_SUPABASE_ANON_KEY: "" configs: Debug: CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION: YES diff --git a/Sources/BetterFit/Services/AppConfiguration.swift b/Sources/BetterFit/Services/AppConfiguration.swift index 2f18a71..bb43ad7 100644 --- a/Sources/BetterFit/Services/AppConfiguration.swift +++ b/Sources/BetterFit/Services/AppConfiguration.swift @@ -1,6 +1,6 @@ import Foundation -/// App configuration loaded from environment variables +/// App configuration from development environment variables or bundled release values. public struct AppConfiguration { // MARK: - Supabase Configuration @@ -15,15 +15,33 @@ public struct AppConfiguration { // MARK: - Initialization - public init() { - // Load environment variables - let rawSupabaseURL = EnvironmentLoader.get("SUPABASE_URL") - let supabaseAnonKey = EnvironmentLoader.get("SUPABASE_ANON_KEY") + public init( + environment: [String: String] = ProcessInfo.processInfo.environment, + bundleInfo: [String: Any] = Bundle.main.infoDictionary ?? [:] + ) { + let backend = bundleInfo["BetterFitBackend"] as? String ?? "" + if backend == "guest" { + self.supabaseURL = nil + self.supabaseAnonKey = nil + self.isSupabaseConfigured = false + self.warnings = [] + return + } + + // Explicit release configuration must not inherit a developer's environment. + let rawSupabaseURL = backend == "supabase" + ? bundleInfo["SUPABASE_URL"] as? String : environment["SUPABASE_URL"] + let supabaseAnonKey = backend == "supabase" + ? bundleInfo["SUPABASE_ANON_KEY"] as? String : environment["SUPABASE_ANON_KEY"] self.supabaseAnonKey = supabaseAnonKey // Validate Supabase configuration var warnings: [String] = [] + let hasKnownBackend = backend.isEmpty || backend == "supabase" + if !hasKnownBackend { + warnings.append("The app's bundled backend configuration is invalid.") + } let hasSupabaseURL = rawSupabaseURL != nil && !rawSupabaseURL!.isEmpty @@ -48,7 +66,7 @@ public struct AppConfiguration { self.supabaseURL = nil } - self.isSupabaseConfigured = hasSupabaseURL && hasAnonKey && self.supabaseURL != nil + self.isSupabaseConfigured = hasKnownBackend && hasSupabaseURL && hasAnonKey && self.supabaseURL != nil self.warnings = warnings } diff --git a/Tests/BetterFitTests/BundledConfigurationTests.swift b/Tests/BetterFitTests/BundledConfigurationTests.swift new file mode 100644 index 0000000..51e14d4 --- /dev/null +++ b/Tests/BetterFitTests/BundledConfigurationTests.swift @@ -0,0 +1,69 @@ +import Testing +import BetterFit + +struct BundledConfigurationTests { + @Test + func guestBuildIgnoresEnvironmentAndBundledCredentials() { + let config = AppConfiguration( + environment: ["SUPABASE_URL": "http://localhost:54321", "SUPABASE_ANON_KEY": "local-key"], + bundleInfo: [ + "BetterFitBackend": "guest", "SUPABASE_URL": "https://example.supabase.co", + "SUPABASE_ANON_KEY": "bundled-key" + ] + ) + + #expect(!config.isSupabaseConfigured) + #expect(config.supabaseURL == nil) + #expect(config.supabaseAnonKey == nil) + #expect(config.isValid) + } + + @Test + func cloudBuildUsesBundledPublicValuesWithoutLaunchEnvironment() { + let config = AppConfiguration(environment: [:], bundleInfo: cloudInfo) + + #expect(config.isSupabaseConfigured) + #expect(config.supabaseURL?.host == "example.supabase.co") + #expect(config.supabaseAnonKey == "bundled-public-key") + } + + @Test + func cloudBuildCannotBeOverriddenByDevelopmentEnvironment() { + let config = AppConfiguration( + environment: ["SUPABASE_URL": "http://localhost:54321", "SUPABASE_ANON_KEY": "local-key"], + bundleInfo: cloudInfo + ) + + #expect(config.isSupabaseConfigured) + #expect(config.supabaseURL?.host == "example.supabase.co") + #expect(config.supabaseAnonKey == "bundled-public-key") + } + + @Test + func incompleteCloudBuildDoesNotFallBackToEnvironment() { + let config = AppConfiguration( + environment: ["SUPABASE_URL": "https://example.supabase.co", "SUPABASE_ANON_KEY": "key"], + bundleInfo: ["BetterFitBackend": "supabase"] + ) + + #expect(!config.isSupabaseConfigured) + #expect(!config.isValid) + } + + @Test + func unknownBackendDisablesCloudFeatures() { + var info = cloudInfo + info["BetterFitBackend"] = "unknown" + let config = AppConfiguration(environment: [:], bundleInfo: info) + + #expect(!config.isSupabaseConfigured) + #expect(!config.isValid) + } + + private var cloudInfo: [String: String] { + [ + "BetterFitBackend": "supabase", "SUPABASE_URL": "https://example.supabase.co", + "SUPABASE_ANON_KEY": "bundled-public-key" + ] + } +} diff --git a/docs/README.md b/docs/README.md index 2555f6f..5ca0be1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,6 +4,7 @@ - **[Local Development Guide](local-development.md)** - Set up Supabase, .env, and iOS simulator (start here!) - [Authentication Setup](auth.md) - Configure Apple Sign In, Google OAuth, email auth +- [TestFlight beta builds](testflight.md) - Configure, archive and validate an internal beta ## Run the app (iOS Simulator) diff --git a/docs/testflight.md b/docs/testflight.md new file mode 100644 index 0000000..230040b --- /dev/null +++ b/docs/testflight.md @@ -0,0 +1,108 @@ +# TestFlight beta builds + +Use the reviewed main branch and Xcode's automatic signing for +`dev.echohello.BetterFit`. This workflow is separate from package releases and +does not change their versioning. Confirm the app record, version and next unused +build number in App Store Connect before archiving. Local format validation does +not establish that a build number is unused. + +## Select the backend + +Choose the beta's backend explicitly. Guest builds store training data locally +and ignore cloud credentials, including development launch environment variables. +Cloud builds read public configuration from the installed app's Info.plist, so +they work outside Xcode. They do not inherit development environment overrides. + +For a cloud build, create a private local JSON file with exactly `SUPABASE_URL` +and `SUPABASE_ANON_KEY`. Use a public HTTPS endpoint and the project's publishable +key or anon-role JWT. The public client configuration will be readable from the +installed app; enforce access through backend authentication and Row Level +Security. Never include service-role keys, secret keys, signing keys or `.env` +files in the app. Do not commit the JSON file or print its values. + +The local development `.env` and scheme injection are not a TestFlight backend. +The archive preflight rejects local HTTP/private endpoints, privileged keys, +extra JSON fields and configuration supplied to guest builds. It validates key +type locally; verify the intended production project and backend permissions +separately before distributing a cloud beta. + +## Archive a Release build + +Supply an unused output directory outside the checkout. The following example +version and build are format examples; choose the actual values in App Store +Connect. Apple build numbers use one to three integers with maximum lengths of +four, two and two digits respectively. + +```bash +mise run ios:archive -- --backend guest --version 1.7.0 --build 2611.22.1 \ + --team YOURTEAMID --output /tmp/betterfit-beta +``` + +For cloud mode, use `--backend supabase --public-config /private/path/public.json`. +Add `--prepare-only` to validate inputs and produce build/export configuration +without contacting Apple or building. No command in this preparation step uploads +the app or changes tester access. + +The command runs `mise run ios:gen`, archives the iOS device Release scheme with +automatic provisioning, and checks the resulting app identity, version/build, +backend values and app privacy manifest. It rejects source PNGs with alpha or +transparency and verifies the archived 1024px AppIcon rendition is opaque. +It writes a redacted archive log and +local configuration/export options beside `BetterFit.xcarchive`. Keep those +working files private and outside version control. The generated Info.plist binds +the version fields to Xcode's version build settings. + +Use an Apple Developer account configured in Xcode Settings > Accounts, with +permission for this app and team. Automatic signing may acquire distribution +certificates and profiles during export. A successful development-signed archive +alone does not prove distribution or App Store Connect access. An Apple agreement +update must be reviewed by the account holder; the tool does not accept agreements. + +## Export, validate and upload + +The iOS PNG icons use the existing artwork from +`design-system/assets/app-icon-1024.png`. That reference is byte-identical to the +original marketing icon, including its rounded transparent corners. The opaque +exports extend its existing `#FFD500` background to the full image. Samples at +the four side centres and an interior background point all had RGB `255,213,0`. +The mark and every previously opaque pixel are preserved exactly; the design +reference is unchanged. This is a packaging export, not a palette update. + +The reproducible native export verifies encoded RGB pixels before writing: + +```bash +swift scripts/opaque_app_icons.swift \ + Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset FFD500 +``` + +The background argument belongs to that existing source; establish it again if +the source artwork changes. iOS applies the app-icon mask to the full-bleed image. + +```bash +xcodebuild -exportArchive \ + -archivePath /tmp/betterfit-beta/BetterFit.xcarchive \ + -exportPath /tmp/betterfit-beta/export \ + -exportOptionsPlist /tmp/betterfit-beta/ExportOptions.plist \ + -allowProvisioningUpdates +``` + +The generated export options use `app-store-connect`, automatic signing, local +export and TestFlight internal testing only. They preserve the chosen build +number. Inspect the export result and signing entitlements, verify the final +version/build and backend, and launch a Release simulator build without demo/test +arguments. Verify normal guest persistence or production authentication as +appropriate. HealthKit usage strings and the required UserDefaults API reason +are included in the app; the privacy manifest is not a substitute for accurate +App Store Connect privacy and export-compliance answers. + +Use Xcode Organizer's validation/upload flow for an authorised, reviewed beta. +After upload, monitor App Store Connect processing and any export-compliance +questions until the build is available for the intended existing internal group. +Do not treat upload success as processing or testability success. Record the app +ID, version/build, processing status and TestFlight link. Uploading a beta does +not authorise a public App Store release, public TestFlight links, tester invites +or notifications. + +Apple documents [automatic distribution signing](https://developer.apple.com/documentation/xcode/distributing-your-app-for-beta-testing-and-releases), +[build-number format](https://developer.apple.com/documentation/bundleresources/information-property-list/cfbundleversion) +and [required-reason privacy declarations](https://developer.apple.com/documentation/technotes/tn3183-adding-required-reason-api-entries-to-your-privacy-manifest). diff --git a/mise.toml b/mise.toml index 20e65fe..04b1737 100644 --- a/mise.toml +++ b/mise.toml @@ -44,6 +44,7 @@ description = "Full setup: populate .env, regenerate project, inject credentials [tasks.test] run = """ +python3 -B -m unittest discover -s scripts/tests -p 'test_*.py' bash scripts/exercise-video-pipeline/test_pipeline.sh echo "" echo '==> Swift tests' @@ -61,6 +62,10 @@ description = "Re-render all anchors and videos in scripts/exercise-video-pipeli [tasks.build] run = "swift build" +[tasks."ios:archive"] +description = "Validate explicit beta configuration and create a signed Release/device archive without uploading" +run = "python3 scripts/testflight_archive.py" + [tasks.lint] run = """ swiftlint lint --config .swiftlint.yml diff --git a/scripts/opaque_app_icons.swift b/scripts/opaque_app_icons.swift new file mode 100644 index 0000000..8d89365 --- /dev/null +++ b/scripts/opaque_app_icons.swift @@ -0,0 +1,67 @@ +import AppKit +import Foundation + +// Re-export existing icon pixels over their established background, without redrawing artwork. +// Usage: swift scripts/opaque_app_icons.swift +guard CommandLine.arguments.count == 3, + CommandLine.arguments[2].count == 6, + let hex = UInt32(CommandLine.arguments[2], radix: 16) +else { + fatalError("Supply an icon catalogue directory and six-digit background RGB hex.") +} +let background = [UInt((hex >> 16) & 255), UInt((hex >> 8) & 255), UInt(hex & 255)] +let catalogue = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true) +let files = try FileManager.default.contentsOfDirectory(at: catalogue, includingPropertiesForKeys: nil) + .filter { $0.pathExtension.lowercased() == "png" }.sorted { $0.path < $1.path } + +for file in files { + let source = NSBitmapImageRep(data: try Data(contentsOf: file))! + guard source.hasAlpha else { continue } + precondition(source.bitsPerSample == 8 && source.samplesPerPixel == 4 && !source.isPlanar) + let result = NSBitmapImageRep( + bitmapDataPlanes: nil, pixelsWide: source.pixelsWide, pixelsHigh: source.pixelsHigh, + bitsPerSample: 8, samplesPerPixel: 3, hasAlpha: false, isPlanar: false, + colorSpaceName: source.colorSpaceName, bitmapFormat: [], + bytesPerRow: source.pixelsWide * 3, bitsPerPixel: 24 + )! + if let profile = source.value(forProperty: .colorSyncProfileData) { + result.setProperty(.colorSyncProfileData, withValue: profile) + } + let alphaIndex = source.bitmapFormat.contains(.alphaFirst) ? 0 : 3 + let channels = alphaIndex == 0 ? [1, 2, 3] : [0, 1, 2] + let straightAlpha = source.bitmapFormat.contains(.alphaNonpremultiplied) + var composited = 0 + for y in 0..II", data[16:24]) + if data[25] not in (0, 2, 3): + raise ValueError("App icons must not contain an alpha channel; use an opaque source export.") + offset = 8 + while offset + 12 <= len(data): + length = struct.unpack(">I", data[offset:offset + 4])[0] + kind = data[offset + 4:offset + 8] + if offset + 12 + length > len(data): + break + if kind == b"tRNS": + raise ValueError("App icons must not contain transparency.") + if kind == b"IEND" and width > 0 and height > 0: + return width, height + offset += length + 12 + raise ValueError("App icon PNG structure is incomplete.") + + +def validate_icon_catalog(catalog): + manifest = json.loads((catalog / "Contents.json").read_text()) + marketing_found = False + for image in manifest["images"]: + filename = image.get("filename") + if not filename: + continue + dimensions = validate_icon_png((catalog / filename).read_bytes()) + if image.get("idiom") == "ios-marketing": + marketing_found = True + if dimensions != (1024, 1024): + raise ValueError("The marketing icon must be an opaque 1024 x 1024 PNG.") + if not marketing_found: + raise ValueError("The iOS marketing icon is missing.") + + +def validate_compiled_icons(metadata): + icons = [entry for entry in metadata if entry.get("Name") == "AppIcon" + and entry.get("PixelWidth") == 1024 and entry.get("PixelHeight") == 1024] + if not icons or any(entry.get("Opaque") is not True for entry in icons): + raise ValueError("The compiled 1024px AppIcon must be present and opaque.") + + +def public_configuration(backend, config_path): + if backend == "guest": + if config_path is not None: + raise ValueError("Guest archives must not receive a cloud configuration file.") + return {"SUPABASE_URL": "", "SUPABASE_ANON_KEY": ""} + if config_path is None: + raise ValueError("Cloud archives require an explicit public configuration JSON file.") + try: + data = json.loads(Path(config_path).read_text()) + except (OSError, ValueError): + raise ValueError("Unable to read public configuration JSON.") from None + if not isinstance(data, dict) or set(data) != {"SUPABASE_URL", "SUPABASE_ANON_KEY"}: + raise ValueError("Configuration must contain only SUPABASE_URL and SUPABASE_ANON_KEY.") + if any(not isinstance(value, str) or not value for value in data.values()): + raise ValueError("Both public configuration values must be non-empty strings.") + try: + url = urlsplit(data["SUPABASE_URL"]) + host = (url.hostname or "").lower().rstrip(".") + _ = url.port + except ValueError: + raise ValueError("The cloud endpoint is invalid.") from None + try: + address = ipaddress.ip_address(host) + except ValueError: + address = None + valid = ( + url.scheme == "https" and bool(host) and not url.username and not url.password + and not url.query and not url.fragment + and not host.endswith((".localhost", ".local", ".internal", ".test", ".invalid", ".example")) + and host != "localhost" and "." in host + and (address is None or address.is_global) + and bool(re.fullmatch(r"https://[A-Za-z0-9.:/_-]+", data["SUPABASE_URL"])) + ) + if not valid: + raise ValueError("Cloud archives require a public HTTPS endpoint without credentials or query parameters.") + key = data["SUPABASE_ANON_KEY"] + if re.fullmatch(r"sb_publishable_[A-Za-z0-9_-]+", key): + return data + if re.fullmatch(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", key): + try: + payload = json.loads(base64.urlsafe_b64decode(key.split(".")[1] + "===")) + if isinstance(payload, dict) and payload.get("role") == "anon": + return data + except (ValueError, UnicodeDecodeError): + pass + raise ValueError("Cloud archives require a publishable key or anon-role JWT, never a secret/service-role key.") + + +def prepare(output, version, build, team, backend, configuration): + validate_versions(version, build) + if not re.fullmatch(r"[A-Z0-9]{10}", team): + raise ValueError("A ten-character Apple Developer team ID is required.") + output.mkdir(parents=True, exist_ok=False) + settings = { + "MARKETING_VERSION": version, "CURRENT_PROJECT_VERSION": build, + "DEVELOPMENT_TEAM": team, "BETTERFIT_BACKEND": backend, + "BETTERFIT_SUPABASE_URL": configuration["SUPABASE_URL"].replace("://", ":/$()/"), + "BETTERFIT_SUPABASE_ANON_KEY": configuration["SUPABASE_ANON_KEY"], + } + config = output / "Release.xcconfig" + config.write_text("".join(f"{key} = {value}\n" for key, value in settings.items())) + config.chmod(0o600) + (output / "ExportOptions.plist").write_bytes(plistlib.dumps({ + "method": "app-store-connect", "destination": "export", "teamID": team, + "signingStyle": "automatic", "manageAppVersionAndBuildNumber": False, + "testFlightInternalTestingOnly": True, "uploadSymbols": True, + })) + return config + + +def validate_archive(archive, version, build, backend, configuration): + apps = list((archive / "Products/Applications").glob("*.app")) + if len(apps) != 1: + raise ValueError("Archive must contain exactly one iOS app.") + app = apps[0] + info = plistlib.loads((app / "Info.plist").read_bytes()) + expected = { + "CFBundleIdentifier": "dev.echohello.BetterFit", "CFBundleShortVersionString": version, + "CFBundleVersion": build, "BetterFitBackend": backend, **configuration, + } + if any(info.get(key, "") != value for key, value in expected.items()): + raise ValueError("Archived app identity, version or backend differs from the requested configuration.") + if not (app / "PrivacyInfo.xcprivacy").is_file(): + raise ValueError("The app privacy manifest is missing from the archive.") + if any(p.suffix in {".p8", ".p12"} or p.name.startswith(".env") for p in app.rglob("*")): + raise ValueError("The archive contains a credential file.") + return app + + +def redact(log, configuration): + for value in configuration.values(): + if value: + for rendered in [value, value.replace("://", ":/$()/")]: + log = log.replace(rendered, "") + return log + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--backend", choices=["guest", "supabase"], required=True) + parser.add_argument("--public-config", type=Path) + parser.add_argument("--version", required=True) + parser.add_argument("--build", required=True) + parser.add_argument("--team", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--prepare-only", action="store_true") + args = parser.parse_args() + try: + root = Path(__file__).resolve().parent.parent + configuration = public_configuration(args.backend, args.public_config) + validate_icon_catalog(root / "Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset") + output = args.output.resolve() + config = prepare(output, args.version, args.build, args.team, args.backend, configuration) + if args.prepare_only: + print("Prepared validated configuration and internal-only export options. Nothing built or uploaded.") + return + environment = {**os.environ, "DEVELOPMENT_TEAM": args.team} + generation = subprocess.run( + ["mise", "run", "ios:gen"], cwd=root, env=environment, capture_output=True + ) + if generation.returncode: + # The development scheme script can print .env values. Never relay its output. + raise ValueError("Project generation failed; inspect the mise generation setup locally.") + print("Archiving Release for iOS devices with automatic provisioning. Nothing will be uploaded.", flush=True) + archive = output / "BetterFit.xcarchive" + result = subprocess.run([ + "xcodebuild", "-project", "Apps/iOS/BetterFit.xcodeproj", "-scheme", "BetterFit", + "-configuration", "Release", "-destination", "generic/platform=iOS", + "-xcconfig", str(config), "-archivePath", str(archive), + "-allowProvisioningUpdates", "archive", + ], cwd=root, env=environment, capture_output=True, text=True) + log = redact(result.stdout + result.stderr, configuration) + (output / "archive.log").write_text(log) + if result.returncode: + raise ValueError("Archive failed; inspect archive.log in the output directory.") + app = validate_archive(archive, args.version, args.build, args.backend, configuration) + assets = subprocess.run( + ["xcrun", "assetutil", "--info", str(app / "Assets.car")], capture_output=True, text=True + ) + if assets.returncode: + raise ValueError("Unable to inspect the archived app icon metadata.") + validate_compiled_icons(json.loads(assets.stdout)) + print(f"Validated dev.echohello.BetterFit {args.version} ({args.build}), backend {args.backend}.") + print("Archive and internal-only export options are ready. Nothing has been exported or uploaded.") + except (ValueError, OSError, plistlib.InvalidFileException) as error: + parser.exit(1, f"Release preparation failed: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/tests/test_testflight_archive.py b/scripts/tests/test_testflight_archive.py new file mode 100644 index 0000000..13ff9eb --- /dev/null +++ b/scripts/tests/test_testflight_archive.py @@ -0,0 +1,129 @@ +import base64 +import importlib.util +import json +from pathlib import Path +import plistlib +import struct +import tempfile +import unittest +import zlib + +SPEC = importlib.util.spec_from_file_location( + "testflight_archive", Path(__file__).resolve().parents[1] / "testflight_archive.py" +) +release = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(release) + + +class TestFlightArchiveTests(unittest.TestCase): + def test_checked_in_ios_icon_catalog_is_opaque(self): + root = Path(__file__).resolve().parents[2] + release.validate_icon_catalog(root / "Apps/iOS/BetterFitApp/Assets.xcassets/AppIcon.appiconset") + + def test_icon_preflight_rejects_alpha_and_transparency(self): + self.assertEqual(release.validate_icon_png(self.png(2)), (1024, 1024)) + for data in [self.png(6), self.png(2, transparency=True), b"invalid"]: + with self.assertRaises(ValueError): + release.validate_icon_png(data) + + def test_compiled_marketing_icon_must_be_present_and_opaque(self): + icon = {"Name": "AppIcon", "PixelWidth": 1024, "PixelHeight": 1024, "Opaque": True} + release.validate_compiled_icons([icon]) + for metadata in [[], [{**icon, "Opaque": False}], [{**icon, "PixelWidth": 180}]]: + with self.assertRaises(ValueError): + release.validate_compiled_icons(metadata) + + def configuration(self, data): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "public.json" + path.write_text(json.dumps(data)) + return release.public_configuration("supabase", path) + + def test_guest_never_accepts_cloud_file(self): + self.assertEqual(release.public_configuration("guest", None), { + "SUPABASE_URL": "", "SUPABASE_ANON_KEY": "" + }) + with self.assertRaises(ValueError): + release.public_configuration("guest", Path("unused.json")) + + def test_rejects_local_or_credential_bearing_endpoints(self): + for url in [ + "http://project.supabase.co", "https://127.0.0.1", "https://192.168.1.2", + "https://localhost", "https://api.local", "https://user:password@project.supabase.co", + "https://project.supabase.co?token=secret", "https://[invalid", "https://example.invalid", + "https://project.supabase.co:invalid", + ]: + with self.subTest(url=url), self.assertRaises(ValueError): + self.configuration({"SUPABASE_URL": url, "SUPABASE_ANON_KEY": "sb_publishable_fixture"}) + + def test_rejects_privileged_or_unrecognised_keys(self): + for key in ["sb_secret_fixture", "unknown", self.jwt("service_role"), "x\nINJECTED = YES"]: + with self.subTest(key_type=key.split("_")[0]), self.assertRaises(ValueError): + self.configuration({"SUPABASE_URL": "https://project.supabase.co", "SUPABASE_ANON_KEY": key}) + with self.assertRaises(ValueError): + self.configuration({ + "SUPABASE_URL": "https://project.supabase.co", + "SUPABASE_ANON_KEY": "sb_publishable_fixture", "SUPABASE_SECRET_KEY": "private", + }) + + def test_accepts_only_public_client_key_types(self): + for key in ["sb_publishable_fixture", self.jwt("anon")]: + data = {"SUPABASE_URL": "https://project.supabase.co", "SUPABASE_ANON_KEY": key} + self.assertEqual(self.configuration(data), data) + + def test_build_format_rejects_timestamps_and_injection(self): + release.validate_versions("1.7.0", "2611.22.1") + for build in ["20261122", "2026.1122.1", "1.2.100", "0", "1.02.3", "1\nOTHER=YES"]: + with self.subTest(build=build), self.assertRaises(ValueError): + release.validate_versions("1.7.0", build) + + def test_export_is_local_and_internal_only(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "release" + config = release.prepare(output, "1.7.0", "2611.22.1", "ABCDEFGHIJ", "guest", { + "SUPABASE_URL": "", "SUPABASE_ANON_KEY": "" + }) + self.assertEqual(config.stat().st_mode & 0o777, 0o600) + options = plistlib.loads((output / "ExportOptions.plist").read_bytes()) + self.assertEqual(options["destination"], "export") + self.assertTrue(options["testFlightInternalTestingOnly"]) + self.assertFalse(options["manageAppVersionAndBuildNumber"]) + + def test_log_redacts_public_values_and_xcconfig_url_rendering(self): + config = {"SUPABASE_URL": "https://project.supabase.co", "SUPABASE_ANON_KEY": "sb_publishable_fixture"} + log = "https://project.supabase.co https:/$()/project.supabase.co sb_publishable_fixture" + self.assertNotIn("project.supabase.co", release.redact(log, config)) + self.assertNotIn("sb_publishable_fixture", release.redact(log, config)) + + def test_archive_requires_matching_metadata_and_no_credential_files(self): + with tempfile.TemporaryDirectory() as directory: + archive = Path(directory) + app = archive / "Products/Applications/BetterFitApp.app" + app.mkdir(parents=True) + config = {"SUPABASE_URL": "", "SUPABASE_ANON_KEY": ""} + info = { + "CFBundleIdentifier": "dev.echohello.BetterFit", "CFBundleShortVersionString": "1.7.0", + "CFBundleVersion": "2611.22.1", "BetterFitBackend": "guest", **config, + } + (app / "Info.plist").write_bytes(plistlib.dumps(info)) + (app / "PrivacyInfo.xcprivacy").write_bytes(plistlib.dumps({})) + release.validate_archive(archive, "1.7.0", "2611.22.1", "guest", config) + with self.assertRaises(ValueError): + release.validate_archive(archive, "1.7.0", "2611.22.2", "guest", config) + (app / ".env").write_text("PRIVATE=must-not-ship") + with self.assertRaises(ValueError): + release.validate_archive(archive, "1.7.0", "2611.22.1", "guest", config) + + @staticmethod + def jwt(role): + payload = base64.urlsafe_b64encode(json.dumps({"role": role}).encode()).decode().rstrip("=") + return f"header.{payload}.signature" + + @staticmethod + def png(colour_type, transparency=False): + def chunk(kind, content): + return (struct.pack(">I", len(content)) + kind + content + + struct.pack(">I", zlib.crc32(kind + content))) + header = struct.pack(">IIBBBBB", 1024, 1024, 8, colour_type, 0, 0, 0) + extra = chunk(b"tRNS", b"\x00\x00\x00\x00\x00\x00") if transparency else b"" + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + extra + chunk(b"IEND", b"")