Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 17 additions & 0 deletions Apps/iOS/BetterFitApp/Resources/PrivacyInfo.xcprivacy
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyAccessedAPITypes</key>
<array>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>CA92.1</string>
</array>
</dict>
</array>
</dict>
</plist>
20 changes: 20 additions & 0 deletions Apps/iOS/BetterFitAppUITests/GuestStartupUITests.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}
15 changes: 15 additions & 0 deletions Apps/iOS/project.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
30 changes: 24 additions & 6 deletions Sources/BetterFit/Services/AppConfiguration.swift
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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
Expand All @@ -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
}

Expand Down
69 changes: 69 additions & 0 deletions Tests/BetterFitTests/BundledConfigurationTests.swift
Original file line number Diff line number Diff line change
@@ -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"
]
}
}
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
108 changes: 108 additions & 0 deletions docs/testflight.md
Original file line number Diff line number Diff line change
@@ -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).
5 changes: 5 additions & 0 deletions mise.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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
Expand Down
67 changes: 67 additions & 0 deletions scripts/opaque_app_icons.swift
Original file line number Diff line number Diff line change
@@ -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 <AppIcon.appiconset> <background RGB hex>
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..<source.pixelsHigh {
for x in 0..<source.pixelsWide {
var pixel = [UInt](repeating: 0, count: 4)
source.getPixel(&pixel, atX: x, y: y)
let alpha = pixel[alphaIndex]
var rgb = channels.map { pixel[$0] }
if alpha < 255 {
composited += 1
for channel in 0..<3 {
let foreground = straightAlpha ? rgb[channel] * alpha : rgb[channel] * 255
rgb[channel] = min(255, (foreground + background[channel] * (255 - alpha) + 127) / 255)
}
}
result.setPixel(&rgb, atX: x, y: y)
}
}
let encoded = result.representation(using: .png, properties: [:])!
let verified = NSBitmapImageRep(data: encoded)!
precondition(!verified.hasAlpha)
// Check encoded pixels too: opaque artwork must survive the export byte-for-byte.
for y in 0..<source.pixelsHigh {
for x in 0..<source.pixelsWide {
var original = [UInt](repeating: 0, count: 4)
source.getPixel(&original, atX: x, y: y)
if original[alphaIndex] == 255 {
var actual = [UInt](repeating: 0, count: 3)
verified.getPixel(&actual, atX: x, y: y)
precondition(actual == channels.map { original[$0] }, "Opaque artwork changed during export")
}
}
}
try encoded.write(to: file, options: .atomic)
print("\(file.lastPathComponent): RGB PNG, \(composited) transparent pixels composited, opaque artwork unchanged")
}
Loading
Loading