fix: comprehensive codebase hardening — crashes, silent failures, performance, and security

Fixes ~95 issues from deep audit across 12 categories in 82 files:

- Crash prevention: double-resume in PhotoMetadataExtractor, force unwraps in
  DateRangePicker, array bounds checks in polls/achievements, ProGate hit-test
  bypass, Dictionary(uniqueKeysWithValues:) → uniquingKeysWith in 4 files
- Silent failure elimination: all 34 try? sites replaced with do/try/catch +
  logging (SavedTrip, TripDetailView, CanonicalSyncService, BootstrapService,
  CanonicalModels, CKModels, SportsTimeApp, and more)
- Performance: cached DateFormatters (7 files), O(1) team lookups via
  AppDataProvider, achievement definition dictionary, AnimatedBackground
  consolidated from 19 Tasks to 1, task cancellation in SharePreviewView
- Concurrency: UIKit drawing → MainActor.run, background fetch timeout guard,
  @MainActor on ThemeManager/AppearanceManager, SyncLogger read/write race fix
- Planning engine: game end time in travel feasibility, state-aware city
  normalization, exact city matching, DrivingConstraints parameter propagation
- IAP: unknown subscription states → expired, unverified transaction logging,
  entitlements updated before paywall dismiss, restore visible to all users
- Security: API key to Info.plist lookup, filename sanitization in PDF export,
  honest User-Agent, removed stale "Feels" analytics super properties
- Navigation: consolidated competing navigationDestination, boolean → value-based
- Testing: 8 sleep() → waitForExistence, duplicates extracted, Swift 6 compat
- Service bugs: infinite retry cap, duplicate achievement prevention, TOCTOU vote
  fix, PollVote.odg → voterId rename, deterministic placeholder IDs, parallel
  MKDirections, Sendable-safe POI struct

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Trey t
2026-02-27 17:03:09 -06:00
parent e046cb6b34
commit c94e373e33
82 changed files with 1163 additions and 599 deletions

View File

@@ -811,6 +811,15 @@ final class ExportService {
private let pdfGenerator = PDFGenerator()
private let assetPrefetcher = PDFAssetPrefetcher()
/// Sanitize a string for use as a filename by removing invalid characters.
private func sanitizeFilename(_ name: String) -> String {
let invalidChars = CharacterSet(charactersIn: "/\\:*?\"<>|")
return name.components(separatedBy: invalidChars).joined(separator: "_")
.trimmingCharacters(in: .whitespacesAndNewlines)
.prefix(255)
.description
}
/// Export trip to PDF with full prefetched assets
/// - Parameters:
/// - trip: The trip to export
@@ -839,7 +848,8 @@ final class ExportService {
)
// Save to temp file
let fileName = "\(trip.name.replacingOccurrences(of: " ", with: "_"))_\(Date().timeIntervalSince1970).pdf"
let safeName = sanitizeFilename(trip.name)
let fileName = "\(safeName)_\(Date().timeIntervalSince1970).pdf"
let url = FileManager.default.temporaryDirectory.appendingPathComponent(fileName)
try data.write(to: url)
@@ -859,7 +869,8 @@ final class ExportService {
itineraryItems: itineraryItems
)
let fileName = "\(trip.name.replacingOccurrences(of: " ", with: "_"))_\(Date().timeIntervalSince1970).pdf"
let safeName = sanitizeFilename(trip.name)
let fileName = "\(safeName)_\(Date().timeIntervalSince1970).pdf"
let url = FileManager.default.temporaryDirectory.appendingPathComponent(fileName)
try data.write(to: url)

View File

@@ -62,14 +62,16 @@ actor MapSnapshotService {
let snapshotter = MKMapSnapshotter(options: options)
let snapshot = try await snapshotter.start()
// Draw route and markers on snapshot
let image = drawRouteOverlay(
on: snapshot,
coordinates: coordinates,
stops: stops,
routeColor: routeColor,
size: size
)
// Draw route and markers on snapshot (UIKit drawing must run on main thread)
let image = await MainActor.run {
drawRouteOverlay(
on: snapshot,
coordinates: coordinates,
stops: stops,
routeColor: routeColor,
size: size
)
}
return image
}
@@ -105,13 +107,15 @@ actor MapSnapshotService {
let snapshotter = MKMapSnapshotter(options: options)
let snapshot = try await snapshotter.start()
// Draw stadium marker
let image = drawStadiumMarker(
on: snapshot,
coordinate: coordinate,
cityName: stop.city,
size: size
)
// Draw stadium marker (UIKit drawing must run on main thread)
let image = await MainActor.run {
drawStadiumMarker(
on: snapshot,
coordinate: coordinate,
cityName: stop.city,
size: size
)
}
return image
}
@@ -149,7 +153,7 @@ actor MapSnapshotService {
}
/// Draw route line and numbered markers on snapshot
private func drawRouteOverlay(
private nonisolated func drawRouteOverlay(
on snapshot: MKMapSnapshotter.Snapshot,
coordinates: [CLLocationCoordinate2D],
stops: [TripStop],
@@ -196,7 +200,7 @@ actor MapSnapshotService {
}
/// Draw stadium marker on city map
private func drawStadiumMarker(
private nonisolated func drawStadiumMarker(
on snapshot: MKMapSnapshotter.Snapshot,
coordinate: CLLocationCoordinate2D,
cityName: String,
@@ -247,7 +251,7 @@ actor MapSnapshotService {
}
/// Draw a numbered circular marker
private func drawNumberedMarker(
private nonisolated func drawNumberedMarker(
at point: CGPoint,
number: Int,
color: UIColor,

View File

@@ -7,6 +7,9 @@
import Foundation
import UIKit
import os
private let logger = Logger(subsystem: "com.88oakapps.SportsTime", category: "PDFAssetPrefetcher")
actor PDFAssetPrefetcher {
@@ -138,6 +141,7 @@ actor PDFAssetPrefetcher {
let mapSize = CGSize(width: 512, height: 350)
return try await mapService.generateRouteMap(stops: stops, size: mapSize)
} catch {
logger.error("Failed to generate route map for PDF: \(error.localizedDescription)")
return nil
}
}

View File

@@ -13,14 +13,14 @@ actor POISearchService {
// MARK: - Types
struct POI: Identifiable, Hashable, @unchecked Sendable {
struct POI: Identifiable, Hashable, Sendable {
let id: UUID
let name: String
let category: POICategory
let coordinate: CLLocationCoordinate2D
let distanceMeters: Double
let address: String?
let mapItem: MKMapItem?
let url: URL?
var formattedDistance: String {
let miles = distanceMeters * 0.000621371
@@ -32,6 +32,15 @@ actor POISearchService {
}
}
/// Open this POI's location in Apple Maps
@MainActor
func openInMaps() {
let placemark = MKPlacemark(coordinate: coordinate)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = name
mapItem.openInMaps()
}
// Hashable conformance for CLLocationCoordinate2D
func hash(into hasher: inout Hasher) {
hasher.combine(id)
@@ -218,7 +227,7 @@ actor POISearchService {
coordinate: itemCoordinate,
distanceMeters: distance,
address: formatAddress(item),
mapItem: item
url: item.url
)
}

View File

@@ -114,10 +114,11 @@ actor RemoteImageService {
/// Fetch team logos by team ID
func fetchTeamLogos(teams: [Team]) async -> [String: UIImage] {
let urlToTeam: [URL: String] = Dictionary(
uniqueKeysWithValues: teams.compactMap { team in
teams.compactMap { team in
guard let logoURL = team.logoURL else { return nil }
return (logoURL, team.id)
}
},
uniquingKeysWith: { _, last in last }
)
let images = await fetchImages(from: Array(urlToTeam.keys))
@@ -135,10 +136,11 @@ actor RemoteImageService {
/// Fetch stadium photos by stadium ID
func fetchStadiumPhotos(stadiums: [Stadium]) async -> [String: UIImage] {
let urlToStadium: [URL: String] = Dictionary(
uniqueKeysWithValues: stadiums.compactMap { stadium in
stadiums.compactMap { stadium in
guard let imageURL = stadium.imageURL else { return nil }
return (imageURL, stadium.id)
}
},
uniquingKeysWith: { _, last in last }
)
let images = await fetchImages(from: Array(urlToStadium.keys))

View File

@@ -18,6 +18,7 @@ struct SharePreviewView<Content: ShareableContent>: View {
@State private var isGenerating = false
@State private var error: String?
@State private var showCopiedToast = false
@State private var loadTask: Task<Void, Never>?
init(content: Content) {
self.content = content
@@ -61,7 +62,11 @@ struct SharePreviewView<Content: ShareableContent>: View {
await generatePreview()
}
.onChange(of: selectedTheme) { _, _ in
Task { await generatePreview() }
loadTask?.cancel()
loadTask = Task {
guard !Task.isCancelled else { return }
await generatePreview()
}
}
}
}