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
333 changes: 176 additions & 157 deletions Source/iOS/App/Common/Ecosystem/EcosystemBridge.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import Foundation
import PVLibrarySnapshot
#if os(iOS)
#if canImport(UIKit)
import UIKit
#endif

Expand All @@ -22,172 +22,191 @@ import UIKit
/// the system share sheet, where the peer appears as a "Copy to" target.
/// (There is no `fetch` callback: on one device the peer cannot download
/// from iCube, which is suspended the moment the peer opens.)
/// - `dolphinios://handoff?id=<id>&from=<scheme>` → a sibling put a game in
/// iCube's inbox in the shared App Group container; import it
/// (`EcosystemHandoff`). The query is informational: the inbox is the truth.
///
/// Parsing (`parse`) is plain, synchronous and side-effect free so it can run
/// on any thread and be unit tested without `@MainActor`. Everything that
/// touches `UIApplication` or app state (`perform`, `openCallback`,
/// `replyWithGameList`, `peerInstalled`) is `@MainActor`.
enum EcosystemBridge {

// MARK: - Wire types

/// One library entry in the gameInfo reply. Field names match
/// Provenance's `EcosystemGameScheme` exactly.
struct GamePayload: Codable {
var titleName: String
var titleId: String
var developer: String?
var version: String?
var iconData: String?
// MARK: - Wire types

/// One library entry in the gameInfo reply. Field names match
/// Provenance's `EcosystemGameScheme` exactly.
struct GamePayload: Codable {
var titleName: String
var titleId: String
var developer: String?
var version: String?
var iconData: String?
}

// MARK: - Incoming requests

enum Request: Equatable {
case gameInfo(callbackScheme: String)
case open(gameID: String)
case requestGame(gameID: String, callbackScheme: String)
case handoff
}

/// Parses a `dolphinios://` URL into an ecosystem request, or nil when
/// it's not one of the ecosystem routes (callers fall through to the
/// existing `play`/`dsu` handlers).
static func parse(_ url: URL) -> Request? {
guard url.scheme?.lowercased() == EcosystemSchemes.ownScheme,
let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return nil
}

// MARK: - Incoming requests

enum Request: Equatable {
case gameInfo(callbackScheme: String)
case open(gameID: String)
case requestGame(gameID: String, callbackScheme: String)
let query = { (name: String) -> String? in
components.queryItems?.first { $0.name.lowercased() == name }?.value
}

/// Parses a `dolphinios://` URL into an ecosystem request, or nil when
/// it's not one of the three ecosystem routes (callers fall through to
/// the existing `play`/`dsu` handlers).
static func parse(_ url: URL) -> Request? {
guard url.scheme?.lowercased() == EcosystemSchemes.ownScheme,
let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return nil
}
let query = { (name: String) -> String? in
components.queryItems?.first { $0.name.lowercased() == name }?.value
}
switch components.host?.lowercased() {
case "gameinfo":
guard let scheme = query("scheme"), isSafeCallbackScheme(scheme) else { return nil }
return .gameInfo(callbackScheme: scheme)
case "open":
guard let id = query("id"), !id.isEmpty else { return nil }
return .open(gameID: id)
case "requestgame":
guard let id = query("id"), !id.isEmpty,
let scheme = query("scheme"), isSafeCallbackScheme(scheme) else { return nil }
return .requestGame(gameID: id, callbackScheme: scheme)
default:
return nil
}
switch components.host?.lowercased() {
case "gameinfo":
guard let scheme = query("scheme"), isSafeCallbackScheme(scheme) else { return nil }
return .gameInfo(callbackScheme: scheme)
case "open":
guard let id = query("id"), !id.isEmpty else { return nil }
return .open(gameID: id)
case "requestgame":
guard let id = query("id"), !id.isEmpty,
let scheme = query("scheme"), isSafeCallbackScheme(scheme) else { return nil }
return .requestGame(gameID: id, callbackScheme: scheme)
case EcosystemHandoff.urlHost:
// Anyone can open this URL, and it carries nothing to trust: it only
// makes iCube look in an inbox that App Group members alone can write.
return .handoff
default:
return nil
}

/// Callback schemes are attacker-supplied (any app can open `dolphinios://`
/// URLs); constrain to plain scheme charset so the reply URL can't be
/// shaped.
private static func isSafeCallbackScheme(_ scheme: String) -> Bool {
!scheme.isEmpty && scheme.count <= 64 && scheme.range(
of: "^[A-Za-z][A-Za-z0-9+.-]*$", options: .regularExpression
) != nil
}

/// Callback schemes are attacker-supplied (any app can open `dolphinios://`
/// URLs); constrain to plain scheme charset so the reply URL can't be
/// shaped.
private static func isSafeCallbackScheme(_ scheme: String) -> Bool {
!scheme.isEmpty && scheme.count <= 64 && scheme.range(
of: "^[A-Za-z][A-Za-z0-9+.-]*$", options: .regularExpression
) != nil
}

// MARK: - Dispatch

/// Executes a parsed request. Split from `parse` so `URLRouterService` can
/// synchronously decide whether to claim the URL (`parse != nil`) before
/// dispatching the actual (MainActor, possibly UI-presenting) handling.
@MainActor
static func perform(_ request: Request) {
switch request {
case .gameInfo(let callbackScheme):
replyWithGameList(callbackScheme: callbackScheme)
case .open(let gameID):
GameLaunchRequest.launch(gameID: gameID)
case .requestGame(let gameID, let callbackScheme):
EcosystemShareCenter.shared.handleRequest(gameID: gameID, callbackScheme: callbackScheme)
case .handoff:
Task { await EcosystemHandoffImporter.importPending() }
}

// MARK: - Dispatch

/// Executes a parsed request. Split from `parse` so `URLRouterService` can
/// synchronously decide whether to claim the URL (`parse != nil`) before
/// dispatching the actual (MainActor, possibly UI-presenting) handling.
@MainActor
static func perform(_ request: Request) {
switch request {
case .gameInfo(let callbackScheme):
replyWithGameList(callbackScheme: callbackScheme)
case .open(let gameID):
GameLaunchRequest.launch(gameID: gameID)
case .requestGame(let gameID, let callbackScheme):
EcosystemShareCenter.shared.handleRequest(gameID: gameID, callbackScheme: callbackScheme)
}
}

// MARK: - Install detection

/// Is a peer ecosystem app installed? Only schemes listed in
/// LSApplicationQueriesSchemes are probeable; anything else returns false.
@MainActor
static func peerInstalled(scheme: String) -> Bool {
#if os(iOS)
guard let url = URL(string: "\(scheme)://") else { return false }
return UIApplication.shared.canOpenURL(url)
#else
return false
#endif
}

// MARK: - gameInfo reply

/// Games in the gameInfo reply, most-recently-played first, capped — the
/// list rides in a URL, so it can't grow unbounded.
static let gameListCap = 300

/// Answers a gameInfo query by opening the peer's callback URL with this
/// library's game-id-identified games, from the App Group snapshot (the
/// same one Top Shelf and Spotlight read).
@MainActor
static func replyWithGameList(callbackScheme: String) {
let snapshot = LibrarySnapshotStore().load()
let payload = snapshot.byGameID.values
.sorted { ($0.lastPlayed ?? .distantPast) > ($1.lastPlayed ?? .distantPast) }
.prefix(gameListCap)
.map { game in
GamePayload(
titleName: game.title,
titleId: game.id,
developer: makerCode(forGameID: game.id),
version: game.icubePlatform.displayName,
iconData: nil
)
}
guard let data = try? JSONEncoder().encode(Array(payload)) else { return }
openCallback(scheme: callbackScheme, query: "games", value: base64url(data))
}

// MARK: - Install detection

/// Is a peer ecosystem app installed? Only schemes listed in
/// LSApplicationQueriesSchemes are probeable; anything else returns false.
@MainActor
static func peerInstalled(scheme: String) -> Bool {
#if canImport(UIKit)
guard let url = URL(string: "\(scheme)://") else { return false }
return UIApplication.shared.canOpenURL(url)
#else
return false
#endif
}
Comment thread
JoeMatt marked this conversation as resolved.
Resolved

/// Opens a peer's URL (the hand-off wake-up). False when the system refused.
@MainActor
static func open(_ url: URL) async -> Bool {
#if canImport(UIKit)
return await UIApplication.shared.open(url)
#else
return false
#endif
}

// MARK: - gameInfo reply

/// Games in the gameInfo reply, most-recently-played first, capped — the
/// list rides in a URL, so it can't grow unbounded.
static let gameListCap = 300

/// Answers a gameInfo query by opening the peer's callback URL with this
/// library's game-id-identified games, from the App Group snapshot (the
/// same one Top Shelf and Spotlight read).
@MainActor
static func replyWithGameList(callbackScheme: String) {
let snapshot = LibrarySnapshotStore().load()
let payload = snapshot.byGameID.values
.sorted { ($0.lastPlayed ?? .distantPast) > ($1.lastPlayed ?? .distantPast) }
.prefix(gameListCap)
.map { game in
GamePayload(
titleName: game.title,
titleId: game.id,
developer: makerCode(forGameID: game.id),
version: game.icubePlatform.displayName,
iconData: nil
)
}
guard let data = try? JSONEncoder().encode(Array(payload)) else { return }
openCallback(scheme: callbackScheme, query: "games", value: base64url(data))
}

/// Resolves a game id to a library entry, from the App Group snapshot.
static func game(forID gameID: String) -> LibrarySnapshotGame? {
LibrarySnapshotStore().load().game(id: gameID)
}

/// Nintendo disc IDs are Console(1) + GameCode(2) + Region(1) + Maker(2):
/// the maker code is always the last two characters. Derived from the id
/// alone (no file IO) — `DiscHeaderReader` parses the same bytes out of
/// the disc header, but the snapshot's id already carries them.
static func makerCode(forGameID gameID: String) -> String? {
guard gameID.count >= 6 else { return nil }
return String(gameID.suffix(2))
}

// MARK: - Callback plumbing

/// Builds `<scheme>://dolphinios?<query>=<value>` — pure and side-effect
/// free so it's unit-testable without touching `UIApplication`.
static func callbackURL(scheme: String, query: String, value: String) -> URL? {
URL(string: "\(scheme)://\(EcosystemSchemes.ownScheme)?\(query)=\(value)")
}

@MainActor
static func openCallback(scheme: String, query: String, value: String,
completion: ((Bool) -> Void)? = nil) {
guard let url = callbackURL(scheme: scheme, query: query, value: value) else {
completion?(false)
return
}

/// Resolves a game id to a library entry, from the App Group snapshot.
static func game(forID gameID: String) -> LibrarySnapshotGame? {
LibrarySnapshotStore().load().game(id: gameID)
}

/// Nintendo disc IDs are Console(1) + GameCode(2) + Region(1) + Maker(2):
/// the maker code is always the last two characters. Derived from the id
/// alone (no file IO) — `DiscHeaderReader` parses the same bytes out of
/// the disc header, but the snapshot's id already carries them.
static func makerCode(forGameID gameID: String) -> String? {
guard gameID.count >= 6 else { return nil }
return String(gameID.suffix(2))
}

// MARK: - Callback plumbing

/// Builds `<scheme>://dolphinios?<query>=<value>` — pure and side-effect
/// free so it's unit-testable without touching `UIApplication`.
static func callbackURL(scheme: String, query: String, value: String) -> URL? {
URL(string: "\(scheme)://\(EcosystemSchemes.ownScheme)?\(query)=\(value)")
}

@MainActor
static func openCallback(scheme: String, query: String, value: String,
completion: ((Bool) -> Void)? = nil) {
guard let url = callbackURL(scheme: scheme, query: query, value: value) else {
completion?(false)
return
}
#if os(iOS)
UIApplication.shared.open(url) { success in
completion?(success)
}
#else
completion?(false)
#endif
}

/// base64url (RFC 4648 §5), no padding — what Provenance's parser
/// reverses.
static func base64url(_ data: Data) -> String {
data.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
#if os(iOS)
UIApplication.shared.open(url) { success in
completion?(success)
}
#else
completion?(false)
#endif
}

/// base64url (RFC 4648 §5), no padding — what Provenance's parser
/// reverses.
static func base64url(_ data: Data) -> String {
data.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
}
Loading
Loading