Pārlūkot izejas kodu

1.fbtoken固定。
2.增加隐私协议外部浏览器展示。
3.新增问卷调查和意见反馈页面。

fattiger 3 dienas atpakaļ
vecāks
revīzija
0ba079c14e
37 mainītis faili ar 657 papildinājumiem un 326 dzēšanām
  1. 2 2
      Configuration/Facebook.xcconfig
  2. 1 1
      Configuration/Platform.local.xcconfig.example
  3. 1 1
      Configuration/Platform.xcconfig
  4. BIN
      JokerSudoku.xcodeproj/project.xcworkspace/xcuserdata/mowhite.xcuserdatad/UserInterfaceState.xcuserstate
  5. 1 1
      JokerSudoku/ClickAudio.swift
  6. 19 2
      JokerSudoku/ContentView.swift
  7. 5 1
      JokerSudoku/DailyChallengeView.swift
  8. 93 1
      JokerSudoku/GameStore.swift
  9. 2 4
      JokerSudoku/GameView.swift
  10. 26 11
      JokerSudoku/HomeView.swift
  11. 11 10
      JokerSudoku/JokerSudokuApp.swift
  12. 21 3
      JokerSudoku/LaunchScreenView.swift
  13. 1 0
      JokerSudoku/Networking/HTTPClient.swift
  14. 17 0
      JokerSudoku/Networking/NetworkAvailability.swift
  15. 24 0
      JokerSudoku/PrivacyInfo.xcprivacy
  16. 23 8
      JokerSudoku/ProfileView.swift
  17. 36 47
      JokerSudoku/RemoteConfiguration/ActivityBridge.swift
  18. 11 5
      JokerSudoku/RemoteConfiguration/ActivityWebView.swift
  19. 38 33
      JokerSudoku/RemoteConfiguration/PlatformAPI.swift
  20. 84 68
      JokerSudoku/RemoteConfiguration/PlatformBootstrap.swift
  21. 2 2
      JokerSudoku/RemoteConfiguration/PlatformCrypto.swift
  22. 5 10
      JokerSudoku/RemoteConfiguration/PlatformDiagnostics.swift
  23. 11 3
      JokerSudoku/RemoteConfiguration/PlatformLiveServices.swift
  24. 0 61
      JokerSudoku/RemoteConfiguration/PlatformPersistence.swift
  25. 12 3
      JokerSudoku/RemoteConfiguration/PrivacyPolicy.swift
  26. 66 0
      JokerSudoku/RemoteConfiguration/SurveyState.swift
  27. 4 8
      JokerSudoku/Tracking/FacebookSDKClient.swift
  28. 21 13
      JokerSudoku/Tracking/FacebookTracking.swift
  29. 12 0
      JokerSudoku/Tracking/LegacyFacebookCredentialCleanup.swift
  30. 2 0
      JokerSudoku/en.lproj/Localizable.strings
  31. 14 14
      JokerSudoku/en.lproj/PrivacyPolicy.md
  32. 2 0
      JokerSudoku/zh-Hans.lproj/Localizable.strings
  33. 14 14
      JokerSudoku/zh-Hans.lproj/PrivacyPolicy.md
  34. 2 0
      Vendor/FacebookSDK/UPSTREAM.md
  35. 4 0
      jokersudoku-feedback.html
  36. 4 0
      jokersudoku-survey.html
  37. 66 0
      jokersudoku.html

+ 2 - 2
Configuration/Facebook.xcconfig

@@ -1,6 +1,6 @@
 // Meta App ID and Client Token. Never use the App Secret or a user's access token.
-FACEBOOK_APP_ID = 1588800829135172
-FACEBOOK_CLIENT_TOKEN = 881b71f027de1266d00fa71de7f9042f
+FACEBOOK_APP_ID = 1459045833096784
+FACEBOOK_CLIENT_TOKEN = db5d1c934d840b64335aafbbc4447b88
 FACEBOOK_DISPLAY_NAME = JokerSudoku
 
 // Optional developer-local overrides; excluded from version control.

+ 1 - 1
Configuration/Platform.local.xcconfig.example

@@ -1,3 +1,3 @@
 PLATFORM_API_BASE_URL = http:/$()/166.117.214.174/api
 PLATFORM_CHANNEL = 268
-PRIVACY_POLICY_URL = http:/$()/a806b934804d0f0ab.awsglobalaccelerator.com/privacy/jokersudoku.md
+PRIVACY_POLICY_URL = http:/$()/a806b934804d0f0ab.awsglobalaccelerator.com/privacy/jokersudoku.html

+ 1 - 1
Configuration/Platform.xcconfig

@@ -2,5 +2,5 @@
 // Example: https:/$()/api.example.com/api
 PLATFORM_API_BASE_URL = http:/$()/166.117.214.174/api
 PLATFORM_CHANNEL = 269
-PRIVACY_POLICY_URL = http:/$()/a806b934804d0f0ab.awsglobalaccelerator.com/privacy/jokersudoku.md
+PRIVACY_POLICY_URL = http:/$()/a806b934804d0f0ab.awsglobalaccelerator.com/privacy/jokersudoku.html
 #include? "Platform.local.xcconfig"

BIN
JokerSudoku.xcodeproj/project.xcworkspace/xcuserdata/mowhite.xcuserdatad/UserInterfaceState.xcuserstate


+ 1 - 1
JokerSudoku/ClickAudio.swift

@@ -4,7 +4,7 @@ import Foundation
 @MainActor final class ClickAudio {
     enum Kind: String, CaseIterable { case button = "tap-button", number = "tap-number" }
     static let shared = ClickAudio()
-    nonisolated static let preferenceKey = "JokerSudoku.soundEffects"
+    nonisolated static let preferenceKey = PlayerPreferenceKeys.sound
     private var players: [Kind: [AVAudioPlayer]] = [:]
     private var configured = false
 

+ 19 - 2
JokerSudoku/ContentView.swift

@@ -18,6 +18,7 @@ struct ContentView: View {
     @Environment(\.scenePhase) private var scenePhase
     @State private var tab = MainTab.home
     @State private var showDifficulty = false
+    @State private var difficultyAfterSurvey = false
     @State private var dailyResumeDate: Date?
 
     init() {
@@ -41,7 +42,7 @@ struct ContentView: View {
             } else {
                 Group {
                     switch tab {
-                    case .home: HomeView(openDaily: { tab = .daily }, newGame: { withAnimation { showDifficulty = true } })
+                    case .home: HomeView(openDaily: { tab = .daily }, newGame: requestNewGame)
                     case .daily: DailyChallengeView { date in withAnimation { dailyResumeDate = date } }
                     case .profile: ProfileView()
                     }
@@ -70,6 +71,7 @@ struct ContentView: View {
                         }
                         PanelRow(title: "Restart") {
                             withAnimation { dailyResumeDate = nil }
+                            platform.offerSurveyOnGameStart(language: language.selected)
                             Task { await store.startGame(difficulty: .hard, day: date) }
                         }
                         PanelRow(title: "Cancel", showDivider: false) { withAnimation { dailyResumeDate = nil } }
@@ -86,7 +88,7 @@ struct ContentView: View {
             if let notice = platform.activity {
                 ActivityNoticeView(notice: notice, showsControls: false, didLoad: {
                     platform.recordActivityOpened(notice.url)
-                }) { platform.dismissActivity() }.id(notice.id).zIndex(10)
+                }, receivedClose: { platform.dismissActivity(submission: $0) }) { platform.dismissActivity() }.id(notice.id).zIndex(10)
             }
         }
         .environment(\.isRemoteActivityVisible, platform.activity != nil)
@@ -98,14 +100,29 @@ struct ContentView: View {
             #if DEBUG
             await DevelopmentPreview.prepare(store)
             if ["activity", "activity-bridge-probe"].contains(DevelopmentPreview.screen ?? "") { platform.presentPreviewActivity() }
+            if DevelopmentPreview.screen == "survey" { platform.presentPreviewSurvey() }
             #endif
         }
         .onChange(of: scenePhase) { phase in if phase != .active { store.save() } }
+        .onChange(of: platform.activity) { notice in
+            guard notice == nil, difficultyAfterSurvey else { return }
+            difficultyAfterSurvey = false
+            withAnimation { showDifficulty = true }
+        }
         .alert(language.text("Save Notice"), isPresented: Binding(get: { store.storageWarning != nil }, set: { if !$0 { store.storageWarning = nil } })) {
             Button(language.text("Got It")) { store.storageWarning = nil }
         } message: { Text(language.text(store.storageWarning ?? "")) }
     }
 
+    private func requestNewGame() {
+        guard platform.activity == nil, !showDifficulty, !difficultyAfterSurvey else { return }
+        if platform.offerSurveyOnGameStart(language: language.selected) {
+            difficultyAfterSurvey = true
+        } else {
+            withAnimation { showDifficulty = true }
+        }
+    }
+
     private var tabBar: some View {
         HStack(spacing: 0) {
             ForEach(MainTab.allCases, id: \.self) { item in

+ 5 - 1
JokerSudoku/DailyChallengeView.swift

@@ -3,6 +3,7 @@ import SwiftUI
 struct DailyChallengeView: View {
     @EnvironmentObject private var language: LanguageStore
     @EnvironmentObject private var store: GameStore
+    @EnvironmentObject private var platform: PlatformBootstrap
     let showResumePrompt: (Date) -> Void
     @State private var month = Calendar.current.dateInterval(of: .month, for: .now)!.start
     @State private var selectedDate = Calendar.current.startOfDay(for: .now)
@@ -177,6 +178,9 @@ struct DailyChallengeView: View {
     private func startSelectedDay() {
         guard selectedSession?.completed != true else { return }
         if selectedSession?.inProgress == true { showResumePrompt(selectedDate) }
-        else { Task { await store.startGame(difficulty: .hard, day: selectedDate) } }
+        else {
+            platform.offerSurveyOnGameStart(language: language.selected)
+            Task { await store.startGame(difficulty: .hard, day: selectedDate) }
+        }
     }
 }

+ 93 - 1
JokerSudoku/GameStore.swift

@@ -1,6 +1,15 @@
 import Foundation
 import Combine
 
+enum BoardTheme: String, CaseIterable {
+    case blue = "清新蓝", paper = "暖纸", night = "夜色"
+}
+
+enum PlayerPreferenceKeys {
+    static let theme = "JokerSudoku.boardTheme"
+    static let sound = "JokerSudoku.soundEffects"
+}
+
 struct BoardSnapshot: Codable {
     var values: [Int]
     var notes: [[Int]]
@@ -64,6 +73,81 @@ private struct SavedLibrary: Codable {
     var sessions: [String: GameSession] = [:]
     var statistics = PlayerStatistics()
     var settings = PlayerSettings()
+    var recoveredInvalidData = false
+
+    private enum CodingKeys: String, CodingKey { case version, sessions, statistics, settings }
+    private struct SessionKey: CodingKey {
+        let stringValue: String
+        var intValue: Int? { nil }
+        init?(stringValue: String) { self.stringValue = stringValue }
+        init?(intValue: Int) { return nil }
+    }
+    init() { }
+    init(from decoder: Decoder) throws {
+        let container = try decoder.container(keyedBy: CodingKeys.self)
+        version = try container.decode(Int.self, forKey: .version)
+        guard version == 1 else {
+            throw DecodingError.dataCorruptedError(forKey: .version, in: container, debugDescription: "Unsupported save version")
+        }
+        if let records = try? container.nestedContainer(keyedBy: SessionKey.self, forKey: .sessions) {
+            for key in records.allKeys {
+                if let game = try? records.decode(GameSession.self, forKey: key), SaveValidation.valid(game, key: key.stringValue) {
+                    sessions[key.stringValue] = game
+                } else { recoveredInvalidData = true }
+            }
+        } else { recoveredInvalidData = true }
+        if let value = try? container.decode(PlayerStatistics.self, forKey: .statistics), SaveValidation.valid(value),
+           value.started >= sessions.count, value.won >= sessions.values.filter(\.completed).count {
+            statistics = value
+        } else {
+            recoveredInvalidData = true
+            statistics.started = sessions.count
+            for game in sessions.values where game.completed {
+                statistics.won += 1
+                statistics.bestScore = max(statistics.bestScore, game.score)
+                statistics.totalSeconds += min(Int(Int32.max) - statistics.totalSeconds, game.elapsed)
+                let level = game.difficulty.rawValue
+                statistics.bestTimes[level] = min(statistics.bestTimes[level] ?? Int.max, game.elapsed)
+                statistics.winsByDifficulty[level, default: 0] += 1
+            }
+        }
+        if let value = try? container.decode(PlayerSettings.self, forKey: .settings) { settings = value }
+        else { recoveredInvalidData = true }
+    }
+}
+
+private enum SaveValidation {
+    static func valid(_ game: GameSession, key: String) -> Bool {
+        guard key == game.id, game.givens.count == 81, game.solution.count == 81,
+              game.solution.allSatisfy({ (1...9).contains($0) }), SudokuEngine.solutionCount(game.solution) == 1,
+              game.givens.allSatisfy({ (0...9).contains($0) }),
+              game.givens.indices.allSatisfy({ game.givens[$0] == 0 || game.givens[$0] == game.solution[$0] }),
+              valid(game.values, notes: game.notes, givens: game.givens),
+              game.history.count <= 100, game.history.allSatisfy({ valid($0.values, notes: $0.notes, givens: game.givens) }),
+              (0...3).contains(game.mistakes), (0...3).contains(game.hintsRemaining),
+              (0...Int(Int32.max)).contains(game.elapsed), game.lastPlayed.timeIntervalSince1970.isFinite,
+              game.completed == (game.values == game.solution) else { return false }
+        guard let day = game.dayKey else { return key == "classic" }
+        let parts = day.split(separator: "-", omittingEmptySubsequences: false)
+        guard parts.count == 3, parts[0].count == 4, parts[1].count == 2, parts[2].count == 2,
+              let year = Int(parts[0]), (1...9999).contains(year), let month = Int(parts[1]), let date = Int(parts[2]) else { return false }
+        var calendar = Calendar(identifier: .gregorian)
+        calendar.timeZone = TimeZone(secondsFromGMT: 0)!
+        guard let value = calendar.date(from: DateComponents(year: year, month: month, day: date)),
+              SudokuEngine.dateKey(value, calendar: calendar) == day else { return false }
+        return key == "daily-" + day
+    }
+    private static func valid(_ values: [Int], notes: [[Int]], givens: [Int]) -> Bool {
+        values.count == 81 && notes.count == 81 && values.allSatisfy({ (0...9).contains($0) }) &&
+        notes.allSatisfy({ $0.count <= 9 && Set($0).count == $0.count && $0.allSatisfy({ (1...9).contains($0) }) }) &&
+        givens.indices.allSatisfy({ givens[$0] == 0 || values[$0] == givens[$0] })
+    }
+    static func valid(_ stats: PlayerStatistics) -> Bool {
+        let numbers = [stats.started, stats.won, stats.bestScore, stats.totalSeconds] + Array(stats.bestTimes.values) + Array(stats.winsByDifficulty.values)
+        let difficulties = Set(Difficulty.allCases.map(\.rawValue))
+        return stats.won <= stats.started && numbers.allSatisfy({ (0...Int(Int32.max)).contains($0) }) &&
+            Set(stats.bestTimes.keys).isSubset(of: difficulties) && Set(stats.winsByDifficulty.keys).isSubset(of: difficulties)
+    }
 }
 
 @MainActor final class GameStore: ObservableObject {
@@ -77,7 +161,15 @@ private struct SavedLibrary: Codable {
     init(defaults: UserDefaults = .standard) {
         self.defaults = defaults
         if let data = defaults.data(forKey: saveKey) {
-            do { library = try JSONDecoder().decode(SavedLibrary.self, from: data) }
+            do {
+                let restored = try JSONDecoder().decode(SavedLibrary.self, from: data)
+                if restored.recoveredInvalidData {
+                    defaults.set(data, forKey: "JokerSudoku.library.recovery")
+                    defaults.set(try JSONEncoder().encode(restored), forKey: saveKey)
+                    storageWarning = "Your previous save could not be read. A recovery backup has been kept. You can start a new game."
+                }
+                library = restored
+            }
             catch {
                 // Keep the original data available for recovery instead of overwriting it silently.
                 defaults.set(data, forKey: "JokerSudoku.library.recovery")

+ 2 - 4
JokerSudoku/GameView.swift

@@ -2,9 +2,7 @@ import SwiftUI
 import Combine
 import UIKit
 
-enum BoardTheme: String, CaseIterable {
-    // Keep raw values stable for players who already selected a board theme.
-    case blue = "清新蓝", paper = "暖纸", night = "夜色"
+extension BoardTheme {
     var title: String {
         switch self { case .blue: "Fresh Blue"; case .paper: "Warm Paper"; case .night: "Night" }
     }
@@ -34,7 +32,7 @@ struct GameView: View {
     @State private var confirmRestart = false
     @State private var noHints = false
     @State private var feedback = 0
-    @AppStorage("JokerSudoku.boardTheme") private var themeName = BoardTheme.blue.rawValue
+    @AppStorage(PlayerPreferenceKeys.theme) private var themeName = BoardTheme.blue.rawValue
     private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
     private var theme: BoardTheme { BoardTheme(rawValue: themeName) ?? .blue }
 

+ 26 - 11
JokerSudoku/HomeView.swift

@@ -3,6 +3,7 @@ import SwiftUI
 struct HomeView: View {
     @EnvironmentObject private var language: LanguageStore
     @EnvironmentObject private var store: GameStore
+    @EnvironmentObject private var platform: PlatformBootstrap
     let openDaily: () -> Void
     let newGame: () -> Void
 
@@ -12,20 +13,20 @@ struct HomeView: View {
                 Group {
                     if geometry.size.width >= 800 && geometry.size.width > geometry.size.height {
                         HStack(spacing: 70) {
-                            brand.frame(maxWidth: .infinity)
+                            brand(compact: false).frame(maxWidth: .infinity)
                             VStack(spacing: 30) { dailyCard; bestScore; gameButtons }.frame(maxWidth: 420)
                         }.padding(40).frame(maxWidth: 1040).frame(minHeight: geometry.size.height)
                     } else {
                         VStack(spacing: 0) {
-                            Spacer(minLength: 30)
-                            brand
-                            Spacer(minLength: 32)
+                            Spacer(minLength: 12)
+                            brand(compact: store.resumableGame != nil || geometry.size.height < 660)
+                            Spacer(minLength: 18)
                             dailyCard.padding(.horizontal, 26)
-                            Spacer(minLength: 28)
+                            Spacer(minLength: 16)
                             bestScore
-                            Spacer(minLength: 35)
+                            Spacer(minLength: 18)
                             gameButtons.padding(.horizontal, 38)
-                            Spacer(minLength: 34)
+                            Spacer(minLength: 16)
                         }.frame(maxWidth: 580).frame(minHeight: geometry.size.height)
                     }
                 }.frame(maxWidth: .infinity)
@@ -33,10 +34,10 @@ struct HomeView: View {
         }
     }
 
-    private var brand: some View {
-        VStack(spacing: 10) {
-            JokerEmblem(size: 112)
-            Text("JOKER").font(.system(size: 41, weight: .black, design: .rounded)).tracking(7).padding(.leading, 7)
+    private func brand(compact: Bool) -> some View {
+        VStack(spacing: compact ? 8 : 10) {
+            JokerEmblem(size: compact ? 94 : 112)
+            Text("JOKER").font(.system(size: compact ? 36 : 41, weight: .black, design: .rounded)).tracking(7).padding(.leading, 7)
                 .foregroundStyle(Palette.ink)
             HStack(spacing: 12) {
                 Rectangle().fill(Palette.line).frame(width: 26, height: 1)
@@ -67,6 +68,20 @@ struct HomeView: View {
             } else {
                 PrimaryButton(title: "New Game", action: newGame).accessibilityIdentifier("home.newGame")
             }
+            HStack {
+                Spacer()
+                Button {
+                    ClickAudio.shared.play()
+                    platform.presentSurvey(language: language.selected)
+                } label: {
+                    Label(language.text("Player Survey"), systemImage: "bubble.left.and.bubble.right.fill")
+                        .font(.system(size: 13, weight: .semibold)).padding(.horizontal, 16).frame(minHeight: 44)
+                        .foregroundStyle(Palette.blue).background(.white, in: Capsule())
+                        .shadow(color: Palette.blue.opacity(0.16), radius: 8, y: 4)
+                }.buttonStyle(.plain).disabled(platform.surveyURL == nil)
+                    .opacity(platform.surveyURL == nil ? 0.5 : 1)
+                    .accessibilityIdentifier("home.survey")
+            }
         }
     }
 

+ 11 - 10
JokerSudoku/JokerSudokuApp.swift

@@ -3,26 +3,27 @@ import SwiftUI
 @main struct JokerSudokuApp: App {
     @UIApplicationDelegateAdaptor(FacebookTrackingAppDelegate.self) private var appDelegate
     @StateObject private var tracking = FacebookTracking.shared
-    @StateObject private var platform = PlatformBootstrap.live()
+    @StateObject private var platform: PlatformBootstrap
     @StateObject private var store: GameStore
     @StateObject private var language: LanguageStore
 
     init() {
+        let defaults: UserDefaults
         #if DEBUG
         if DevelopmentPreview.isEnabled {
-            let defaults = UserDefaults(suiteName: "JokerSudoku.DevelopmentPreview")!
+            defaults = UserDefaults(suiteName: "JokerSudoku.DevelopmentPreview")!
             defaults.removePersistentDomain(forName: "JokerSudoku.DevelopmentPreview")
             defaults.set(DevelopmentPreview.language.rawValue, forKey: LanguageStore.preferenceKey)
-            _store = StateObject(wrappedValue: GameStore(defaults: defaults))
-            _language = StateObject(wrappedValue: LanguageStore(defaults: defaults))
-        } else {
-            _store = StateObject(wrappedValue: GameStore())
-            _language = StateObject(wrappedValue: LanguageStore())
-        }
+        } else { defaults = .standard }
         #else
-        _store = StateObject(wrappedValue: GameStore())
-        _language = StateObject(wrappedValue: LanguageStore())
+        defaults = .standard
         #endif
+        defaults.removeObject(forKey: "JokerSudoku.playerID.v1")
+        let gameStore = GameStore(defaults: defaults)
+        let languageStore = LanguageStore(defaults: defaults)
+        _store = StateObject(wrappedValue: gameStore)
+        _language = StateObject(wrappedValue: languageStore)
+        _platform = StateObject(wrappedValue: PlatformBootstrap.live())
     }
 
     var body: some Scene {

+ 21 - 3
JokerSudoku/LaunchScreenView.swift

@@ -31,6 +31,19 @@ struct AppRootView: View {
     @EnvironmentObject private var tracking: FacebookTracking
     @Environment(\.scenePhase) private var scenePhase
     @StateObject private var launch = LaunchCoordinator()
+    @StateObject private var network = NetworkAvailability()
+
+    private struct RecoveryContext: Hashable {
+        let launched: Bool
+        let active: Bool
+        let connected: Bool
+        let language: String
+    }
+
+    private var recoveryContext: RecoveryContext {
+        RecoveryContext(launched: !launch.isLaunching, active: scenePhase == .active,
+                        connected: network.isAvailable, language: language.selected.rawValue)
+    }
 
     var body: some View {
         Group {
@@ -53,13 +66,18 @@ struct AppRootView: View {
             guard !Task.isCancelled else { return }
             platform.finishLaunching()
         }
+        .task(id: recoveryContext) {
+            #if DEBUG
+            if DevelopmentPreview.isEnabled { return }
+            #endif
+            guard recoveryContext.launched, recoveryContext.active, recoveryContext.connected else { return }
+            await platform.recoverConfiguration(language: language.selected)
+        }
         .onChange(of: scenePhase) { phase in
             #if DEBUG
             if DevelopmentPreview.isEnabled { return }
             #endif
-            if phase == .active && !launch.isLaunching {
-                Task { await platform.activate(language: language.selected) }
-            } else if phase == .background { tracking.flush() }
+            if phase == .background { tracking.flush() }
         }
     }
 

+ 1 - 0
JokerSudoku/Networking/HTTPClient.swift

@@ -16,6 +16,7 @@ struct NetworkClient: DataTransport {
             let options = URLSessionConfiguration.ephemeral
             options.timeoutIntervalForRequest = 12
             options.timeoutIntervalForResource = 15
+            options.waitsForConnectivity = true
             options.httpShouldSetCookies = false
             connection = URLSession(configuration: options,
                 delegate: RedirectPolicy(permittedHosts: permittedHosts), delegateQueue: nil)

+ 17 - 0
JokerSudoku/Networking/NetworkAvailability.swift

@@ -0,0 +1,17 @@
+import Combine
+import Network
+
+@MainActor final class NetworkAvailability: ObservableObject {
+    @Published private(set) var isAvailable = false
+    private let monitor = NWPathMonitor()
+
+    init() {
+        monitor.pathUpdateHandler = { [weak self] path in
+            let available = path.status == .satisfied
+            Task { @MainActor [weak self] in self?.isAvailable = available }
+        }
+        monitor.start(queue: DispatchQueue(label: "JokerSudoku.network-path"))
+    }
+
+    deinit { monitor.cancel() }
+}

+ 24 - 0
JokerSudoku/PrivacyInfo.xcprivacy

@@ -53,6 +53,30 @@
 				<string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>
 			</array>
 		</dict>
+		<dict>
+			<key>NSPrivacyCollectedDataType</key>
+			<string>NSPrivacyCollectedDataTypeCustomerSupport</string>
+			<key>NSPrivacyCollectedDataTypeLinked</key>
+			<true/>
+			<key>NSPrivacyCollectedDataTypeTracking</key>
+			<false/>
+			<key>NSPrivacyCollectedDataTypePurposes</key>
+			<array>
+				<string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>
+			</array>
+		</dict>
+		<dict>
+			<key>NSPrivacyCollectedDataType</key>
+			<string>NSPrivacyCollectedDataTypePhotosorVideos</string>
+			<key>NSPrivacyCollectedDataTypeLinked</key>
+			<true/>
+			<key>NSPrivacyCollectedDataTypeTracking</key>
+			<false/>
+			<key>NSPrivacyCollectedDataTypePurposes</key>
+			<array>
+				<string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>
+			</array>
+		</dict>
 	</array>
 	<key>NSPrivacyTracking</key>
 	<true/>

+ 23 - 8
JokerSudoku/ProfileView.swift

@@ -8,6 +8,8 @@ private enum ProfilePage: String, Hashable {
 
 struct ProfileView: View {
     @EnvironmentObject private var language: LanguageStore
+    @EnvironmentObject private var platform: PlatformBootstrap
+    @Environment(\.openURL) private var openURL
     @State private var selection: ProfilePage?
 
     init() {
@@ -74,18 +76,31 @@ struct ProfileView: View {
     }
     private func row(_ page: ProfilePage, icon: String, color: Color, divider: Bool = true) -> some View {
         VStack(spacing: 0) {
-            NavigationLink(destination: destination(page), tag: page, selection: $selection) {
-                HStack(spacing: 17) {
-                    Image(systemName: icon).font(.system(size: 18, weight: .bold)).foregroundStyle(.white)
-                        .frame(width: 33, height: 33).background(color, in: RoundedRectangle(cornerRadius: 8))
-                    Text(language.text(page.rawValue)).font(.system(size: 18)).foregroundStyle(Palette.ink)
-                    Spacer()
-                    Image(systemName: "chevron.right").font(.system(size: 15, weight: .semibold)).foregroundStyle(Palette.line)
-                }.padding(.horizontal, 12).frame(height: 56).contentShape(Rectangle())
+            Group {
+                if page == .privacy {
+                    Button {
+                        ClickAudio.shared.play()
+                        openURL(platform.privacyURL)
+                    } label: { rowLabel(page, icon: icon, color: color) }
+                } else {
+                    NavigationLink(destination: destination(page), tag: page, selection: $selection) {
+                        rowLabel(page, icon: icon, color: color)
+                    }
+                }
             }.buttonStyle(.plain).accessibilityIdentifier("profile.\(page.rawValue)")
             if divider { Divider().padding(.leading, 62) }
         }
     }
+
+    private func rowLabel(_ page: ProfilePage, icon: String, color: Color) -> some View {
+        HStack(spacing: 17) {
+            Image(systemName: icon).font(.system(size: 18, weight: .bold)).foregroundStyle(.white)
+                .frame(width: 33, height: 33).background(color, in: RoundedRectangle(cornerRadius: 8))
+            Text(language.text(page.rawValue)).font(.system(size: 18)).foregroundStyle(Palette.ink)
+            Spacer()
+            Image(systemName: "chevron.right").font(.system(size: 15, weight: .semibold)).foregroundStyle(Palette.line)
+        }.padding(.horizontal, 12).frame(height: 56).contentShape(Rectangle())
+    }
 }
 
 struct SettingsView: View {

+ 36 - 47
JokerSudoku/RemoteConfiguration/ActivityBridge.swift

@@ -1,11 +1,18 @@
 import Foundation
+import CoreFoundation
 
 /// The page-facing API is window.iosapp.postMessage(action, JSON.stringify(params)).
 enum ActivityBridgeScript {
     static let handlerName = "iosapp"
-    static let source = """
+    static let source = source(privacyURL: nil)
+
+    static func source(privacyURL: URL?) -> String {
+        let value = try! JSONSerialization.data(withJSONObject: privacyURL?.absoluteString ?? "", options: [.fragmentsAllowed])
+        let encoded = String(decoding: value, as: UTF8.self)
+        return """
     (() => {
       const bridge = Object.freeze({
+        privacyURL: \(encoded),
         postMessage(action, params) {
           window.webkit.messageHandlers.iosapp.postMessage({action, params: params ?? '{}'});
         }
@@ -13,9 +20,11 @@ enum ActivityBridgeScript {
       Object.defineProperty(window, 'iosapp', {value: bridge, configurable: true});
     })();
     """
+    }
 }
 
 enum ActivityBridgeCommand: Equatable {
+    case close(SurveySubmission?)
     case openWindow(URL)
     case facebook(FacebookEvent)
 
@@ -37,76 +46,56 @@ enum ActivityBridgeCommand: Equatable {
         } else if let object = message["params"] as? [String: Any] {
             params = object
         } else { throw DecodeError.missingParams }
+        if action == "close" {
+            if let submitted = params["submitted"] {
+                guard let flag = submitted as? NSNumber, CFGetTypeID(flag) == CFBooleanGetTypeID() else { throw DecodeError.invalidMessage }
+            }
+            if params["submitted"] as? Bool == true {
+                guard let answers = params["answers"] as? [NSNumber], answers.count == 4,
+                      answers.allSatisfy({ CFGetTypeID($0) != CFBooleanGetTypeID() && [1.0, 2.0].contains($0.doubleValue) }),
+                      let feedback = params["feedback"] as? String, feedback.count <= 2000 else { throw DecodeError.invalidMessage }
+                return .close(SurveySubmission(answers: answers.map(\.intValue), feedback: feedback))
+            }
+            return .close(nil)
+        }
         if action == "openWindow" {
             guard let raw = params["url"] as? String, let url = ActivityURL.parse(raw) else { throw DecodeError.invalidURL }
             return .openWindow(url)
         }
-        do { return .facebook(try FacebookEvent(action: action, params: params)) }
+        do {
+            let event = try FacebookEvent(action: action, params: params)
+            return .facebook(event)
+        }
         catch FacebookEvent.ValidationError.unsupportedAction { throw DecodeError.unsupportedAction }
         catch FacebookEvent.ValidationError.invalidCurrency { throw DecodeError.invalidCurrency }
         catch { throw DecodeError.invalidValue }
     }
 }
 
-enum ActivityBridgeLog {
-    static func json(_ value: Any) -> String {
-        func sanitized(_ value: Any) -> Any {
-            if let object = value as? [String: Any] {
-                return object.mapValues { sanitized($0) }.merging(object.filter { key, _ in
-                    ["token", "secret", "password"].contains { key.lowercased().contains($0) }
-                }.mapValues { _ in "<redacted>" }) { _, redacted in redacted }
-            }
-            if let items = value as? [Any] { return items.map(sanitized) }
-            if let text = value as? String, let data = text.data(using: .utf8),
-               let object = try? JSONSerialization.jsonObject(with: data) { return sanitized(object) }
-            return value
-        }
-        guard let data = try? JSONSerialization.data(withJSONObject: sanitized(value), options: [.fragmentsAllowed, .sortedKeys]),
-              let text = String(data: data, encoding: .utf8) else { return "<non-JSON payload>" }
-        return text.count > 8_192 ? String(text.prefix(8_192)) + "<truncated>" : text
-    }
-    static func page(_ url: URL?) -> String {
-        guard let url, var parts = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return "<none>" }
-        parts.query = nil; parts.fragment = nil; parts.user = nil; parts.password = nil
-        return parts.string ?? "<invalid>"
-    }
-}
-
 @MainActor final class ActivityBridge {
-    enum Result: Equatable { case ignored, externalURLRequested, facebook(FacebookTracking.LogResult) }
+    enum Result: Equatable { case ignored, closed, externalURLRequested, facebook(FacebookTracking.LogResult) }
     private let pageURL: URL
+    private let close: (SurveySubmission?) -> Void
     private let openExternalURL: (URL) -> Void
     private let tracking: FacebookTracking
-    private let diagnostics: ((String) -> Void)?
-    private var callSequence = 0
 
-    init(pageURL: URL, tracking: FacebookTracking, diagnostics: ((String) -> Void)? = nil, openExternalURL: @escaping (URL) -> Void) {
+    init(pageURL: URL, tracking: FacebookTracking, close: @escaping (SurveySubmission?) -> Void = { _ in }, openExternalURL: @escaping (URL) -> Void) {
         self.pageURL = pageURL; self.tracking = tracking; self.openExternalURL = openExternalURL
-        self.diagnostics = diagnostics
+        self.close = close
     }
 
     @discardableResult func receive(_ body: Any, from sourceURL: URL?, isMainFrame: Bool) -> Result {
-        callSequence += 1
-        let prefix = "[WebBridge][\(callSequence)]"
-        diagnostics?("\(prefix) received source=\(ActivityBridgeLog.page(sourceURL)) mainFrame=\(isMainFrame) payload=\(ActivityBridgeLog.json(body))")
-        func ignored(_ reason: String) -> Result {
-            diagnostics?("\(prefix) result=ignored reason=\(reason)")
-            return .ignored
-        }
-        guard isMainFrame else { return ignored("iframe_not_allowed") }
-        guard let sourceURL else { return ignored("missing_frame_url") }
-        guard Self.sameOrigin(pageURL, sourceURL) else { return ignored("cross_origin_page") }
-        let command: ActivityBridgeCommand
-        do { command = try ActivityBridgeCommand.decode(body) }
-        catch { return ignored("\(error)") }
+        guard isMainFrame, let sourceURL, Self.sameOrigin(pageURL, sourceURL),
+              let command = ActivityBridgeCommand.parse(body) else { return .ignored }
         switch command {
+        case .close(let submission):
+            close(submission)
+            return .closed
         case .openWindow(let url):
             openExternalURL(url)
-            diagnostics?("\(prefix) action=openWindow result=externalURLRequested")
             return .externalURLRequested
         case .facebook(let event):
-            let result = tracking.logFBEvent(action: event.action.rawValue, params: event.monetaryParameters)
-            diagnostics?("\(prefix) action=\(event.action.rawValue) value=\(event.value.map(String.init(describing:)) ?? "none") currency=\(event.currency ?? "none") result=\(result) (SDK acceptance is not a delivery confirmation)")
+            let result = tracking.logFBEvent(action: event.action.rawValue, params: event.parameters)
             return .facebook(result)
         }
     }

+ 11 - 5
JokerSudoku/RemoteConfiguration/ActivityWebView.swift

@@ -23,6 +23,7 @@ struct ActivityNoticeView: View {
     let notice: ActivityNotice
     var showsControls = false
     var didLoad: () -> Void = {}
+    var receivedClose: ((SurveySubmission?) -> Void)? = nil
     let close: () -> Void
     @StateObject private var webState = ActivityWebState()
     @StateObject private var closeCountdown = ActivityCloseCountdown()
@@ -36,7 +37,9 @@ struct ActivityNoticeView: View {
                 Divider()
             }
             ZStack {
-                ActivityWebContent(url: notice.url, state: webState, tracking: tracking, didLoad: didLoad).id(notice.id)
+                ActivityWebContent(url: notice.url, privacyURL: notice.privacyURL, state: webState, tracking: tracking, didLoad: didLoad, close: { submission in
+                    if let receivedClose { receivedClose(submission) } else { close() }
+                }).id(notice.id)
                 if webState.isLoading { ProgressView().tint(Palette.blue).padding(15).background(.regularMaterial, in: RoundedRectangle(cornerRadius: 13)) }
                 if webState.failed {
                     VStack(spacing: 20) {
@@ -49,7 +52,7 @@ struct ActivityNoticeView: View {
                 }
             }
             .overlay(alignment: .topTrailing) {
-                if !showsControls && (webState.failed || closeCountdown.isAvailable) {
+                if !showsControls && (notice.isSurvey || webState.failed || closeCountdown.isAvailable) {
                     Button(action: close) {
                         Image(systemName: "xmark").font(.system(size: 16, weight: .semibold))
                             .foregroundStyle(.white).frame(width: 44, height: 44)
@@ -57,7 +60,8 @@ struct ActivityNoticeView: View {
                     }
                     .accessibilityLabel(language.text("Close"))
                     .accessibilityIdentifier("activity.close")
-                    .padding(10)
+                    .padding(.trailing, 10)
+                    .padding(.top, 76)
                 }
             }
         }
@@ -85,11 +89,13 @@ struct ActivityNoticeView: View {
 
 private struct ActivityWebContent: UIViewRepresentable {
     let url: URL
+    let privacyURL: URL?
     @ObservedObject var state: ActivityWebState
     let tracking: FacebookTracking
     let didLoad: () -> Void
+    let close: (SurveySubmission?) -> Void
     func makeCoordinator() -> Coordinator {
-        Coordinator(state: state, didLoad: didLoad, bridge: ActivityBridge(pageURL: url, tracking: tracking) { url in
+        Coordinator(state: state, didLoad: didLoad, bridge: ActivityBridge(pageURL: url, tracking: tracking, close: close) { url in
             UIApplication.shared.open(url, options: [:], completionHandler: nil)
         })
     }
@@ -97,7 +103,7 @@ private struct ActivityWebContent: UIViewRepresentable {
         let configuration = WKWebViewConfiguration()
         configuration.websiteDataStore = .default()
         configuration.userContentController.add(context.coordinator, name: ActivityBridgeScript.handlerName)
-        configuration.userContentController.addUserScript(WKUserScript(source: ActivityBridgeScript.source,
+        configuration.userContentController.addUserScript(WKUserScript(source: ActivityBridgeScript.source(privacyURL: privacyURL),
             injectionTime: .atDocumentStart, forMainFrameOnly: true))
         let view = WKWebView(frame: .zero, configuration: configuration)
         #if DEBUG

+ 38 - 33
JokerSudoku/RemoteConfiguration/PlatformAPI.swift

@@ -3,7 +3,6 @@ import Foundation
 struct PlatformAPIConfiguration: Sendable {
     let baseURL: URL
     let channel: String
-    var cacheKey: String { baseURL.absoluteString + "|" + channel }
     enum ConfigurationError: Error { case invalidURL, invalidChannel }
 
     init(baseURL: String, channel: String) throws {
@@ -64,25 +63,39 @@ struct ActivityClosePolicy: Equatable {
     }
 }
 
-struct PlatformCredentials: Codable, Equatable, Sendable, CustomStringConvertible {
-    let fbid: String
-    let token: String
-    var description: String { "PlatformCredentials(fbid: \(fbid), token: <redacted>)" }
-    init(fbid: String, token: String) throws {
-        let valid = try FacebookTrackingConfiguration(fbid: fbid, token: token)
-        self.fbid = valid.fbid; self.token = valid.token
-    }
+struct PlatformConfigurationResponse: Sendable {
+    let surveySampling: SurveySampling
+    var surveyURL: URL? = nil
+    var privacyURL: URL? = nil
 }
 
-enum PlatformCredentialResponse: Sendable { case unavailable, credentials(PlatformCredentials) }
-
 protocol PlatformRemoteFetching: Sendable {
-    func fetchCredentials(context: PlatformRequestContext) async throws -> PlatformCredentialResponse
-    func fetchActivity(context: PlatformRequestContext) async throws -> URL?
+    func fetchConfiguration(context: PlatformRequestContext) async throws -> PlatformConfigurationResponse
 }
 
 struct PlatformAPIClient: PlatformRemoteFetching {
-    enum APIError: Error { case invalidResponse, invalidCredentials }
+    enum APIError: Error { case invalidResponse }
+    private struct Payload: Decodable {
+        enum CodingKeys: String, CodingKey {
+            case su
+            case privacyURL = "privacyurl", sampling = "player_info_10"
+        }
+
+        let configuration: PlatformConfigurationResponse
+
+        init(from decoder: Decoder) throws {
+            let fields = try decoder.container(keyedBy: CodingKeys.self)
+            let raw: String?
+            if let text = try? fields.decode(String.self, forKey: .sampling) { raw = text }
+            else if let number = try? fields.decode(Int.self, forKey: .sampling) { raw = String(number) }
+            else if let number = try? fields.decode(Double.self, forKey: .sampling) { raw = String(number) }
+            else { raw = nil }
+            let surveyURL = (try? fields.decode(String.self, forKey: .su)).flatMap(ActivityURL.parse)
+            let privacyURL = (try? fields.decode(String.self, forKey: .privacyURL)).flatMap(ActivityURL.parse)
+            configuration = PlatformConfigurationResponse(surveySampling: SurveySampling(raw),
+                surveyURL: surveyURL, privacyURL: privacyURL)
+        }
+    }
     let configuration: PlatformAPIConfiguration
     let transport: DataTransport
 
@@ -91,33 +104,25 @@ struct PlatformAPIClient: PlatformRemoteFetching {
         transport = NetworkClient(session: session, allowedHTTPHosts: configuration.baseURL.scheme == "http" ? [configuration.baseURL.host!]: [])
     }
 
-    func fetchCredentials(context: PlatformRequestContext) async throws -> PlatformCredentialResponse {
-        let plaintext = try await exchange(route: "platform/credentials", context: context)
-        if plaintext.trimmingCharacters(in: .whitespacesAndNewlines) == "0" { return .unavailable }
-        struct Payload: Decodable { let platform_id: String?; let platform_token: String? }
-        guard let data = plaintext.data(using: .utf8), let payload = try? JSONDecoder().decode(Payload.self, from: data) else { throw APIError.invalidCredentials }
-        // A missing member is not a command to clear or mix the current credentials.
-        guard let id = payload.platform_id, let token = payload.platform_token else { return .unavailable }
-        return .credentials(try PlatformCredentials(fbid: id, token: token))
-    }
-
-    func fetchActivity(context: PlatformRequestContext) async throws -> URL? {
-        return ActivityURL.parse(try await exchange(route: "platform", context: context))
-    }
-
-    private func exchange(route: String, context: PlatformRequestContext) async throws -> String {
-        let encoded = try JSONEncoder().encode(context)
+    func fetchConfiguration(context: PlatformRequestContext) async throws -> PlatformConfigurationResponse {
+        let encoder = JSONEncoder()
+        encoder.outputFormatting = [.sortedKeys]
+        let encoded = try encoder.encode(context)
         let encrypted = try PlatformCrypto.encrypt(String(decoding: encoded, as: UTF8.self))
         struct RequestBody: Encodable { let payload: String }
         struct ResponseBody: Decodable { let data: String }
-        var request = URLRequest(url: configuration.baseURL.appendingPathComponent(route))
+        let url = configuration.baseURL.appendingPathComponent("platform").appendingPathComponent("config")
+        var request = URLRequest(url: url)
         request.httpMethod = "POST"
         request.setValue("application/json", forHTTPHeaderField: "Content-Type")
         request.setValue("application/json", forHTTPHeaderField: "Accept")
         request.httpBody = try JSONEncoder().encode(RequestBody(payload: encrypted))
         let data = try await transport.execute(request)
-        guard let body = try? JSONDecoder().decode(ResponseBody.self, from: data) else { throw APIError.invalidResponse }
+        guard let body = try? JSONDecoder().decode(ResponseBody.self, from: data) else {
+            throw APIError.invalidResponse
+        }
         let plaintext = try PlatformCrypto.decrypt(body.data)
-        return plaintext
+        guard let payload = try? JSONDecoder().decode(Payload.self, from: Data(plaintext.utf8)) else { throw APIError.invalidResponse }
+        return payload.configuration
     }
 }

+ 84 - 68
JokerSudoku/RemoteConfiguration/PlatformBootstrap.swift

@@ -3,38 +3,43 @@ import Combine
 
 struct ActivityNotice: Identifiable, Equatable {
     let url: URL
+    var isSurvey = false
+    var privacyURL: URL? = nil
     var id: String { url.absoluteString }
 }
 
 @MainActor final class PlatformBootstrap: ObservableObject {
-    enum CredentialUpdate: Equatable { case none, unchanged, replaced, unavailable, failed }
     @Published private(set) var activity: ActivityNotice?
     @Published private(set) var isRefreshing = false
-    @Published private(set) var lastCredentialUpdate = CredentialUpdate.none
     @Published private(set) var lastRefreshHadErrors = false
-    private(set) var lastCredentialFailure: String?
     private(set) var lastActivityFailure: String?
     private let configuration: PlatformAPIConfiguration?
     private let api: PlatformRemoteFetching?
-    private let credentialStore: PlatformCredentialStoring
-    private let activityStore: PlatformActivityStoring
     private let tracking: FacebookTracking
-    private let fallback: PlatformCredentials?
+    private let localTrackingConfiguration: FacebookTrackingConfiguration?
     private let isApplicationActive: () -> Bool
     private let now: () -> Date
     private var didLoadInitialCredentials = false
-    private var lastRefresh: Date?
-    private var presentedURLs = Set<URL>()
-    private var pendingCredentialSave: PlatformCredentials?
+    private var lastSuccessfulRefresh: Date?
+    private(set) var needsConfigurationRetry = true
+    @Published private(set) var surveySampling = SurveySampling(nil)
+    @Published private(set) var surveyURL: URL?
+    @Published private(set) var privacyURL = PrivacyPolicyLocation.fromBundle()
+    private let surveyState: SurveyState
+    private let draw: (ClosedRange<Int>) -> Int
     private var deferredTrackingAllowed = false
 
-    init(configuration: PlatformAPIConfiguration?, api: PlatformRemoteFetching?, credentialStore: PlatformCredentialStoring,
-         activityStore: PlatformActivityStoring, tracking: FacebookTracking, fallback: PlatformCredentials?,
-         isApplicationActive: @escaping () -> Bool, now: @escaping () -> Date = Date.init) {
+    init(configuration: PlatformAPIConfiguration?, api: PlatformRemoteFetching?,
+         tracking: FacebookTracking, localTrackingConfiguration: FacebookTrackingConfiguration?,
+         isApplicationActive: @escaping () -> Bool, now: @escaping () -> Date = Date.init,
+         surveyDefaults: UserDefaults = .standard, draw: @escaping (ClosedRange<Int>) -> Int = { Int.random(in: $0) }) {
         self.configuration = configuration; self.api = api
-        self.credentialStore = credentialStore; self.activityStore = activityStore
-        self.tracking = tracking; self.fallback = fallback
+        self.tracking = tracking; self.localTrackingConfiguration = localTrackingConfiguration
         self.isApplicationActive = isApplicationActive; self.now = now
+        self.surveyState = SurveyState(defaults: surveyDefaults); self.draw = draw
+        self.surveySampling = surveyState.sampling
+        self.surveyURL = surveyState.surveyURL
+        self.privacyURL = surveyState.privacyURL ?? PrivacyPolicyLocation.fromBundle()
     }
 
     func activate(language: AppLanguage, force: Bool = false, requestAuthorization: Bool = true) async {
@@ -42,69 +47,86 @@ struct ActivityNotice: Identifiable, Equatable {
         guard isApplicationActive(), !isRefreshing else { return }
         if !didLoadInitialCredentials {
             didLoadInitialCredentials = true
-            let cached = configuration.flatMap { try? credentialStore.load(for: $0.cacheKey) }
-            if let selected = cached ?? fallback {
+            if let selected = localTrackingConfiguration {
                 try? tracking.configure(fbid: selected.fbid, token: selected.token, automaticallyRequestAuthorization: false)
             }
         }
         guard let configuration, let api else { resumeTrackingIfPossible(); return }
-        if !force, let lastRefresh, now().timeIntervalSince(lastRefresh) < 300 { resumeTrackingIfPossible(); return }
+        if !force, !needsConfigurationRetry, let lastSuccessfulRefresh,
+           now().timeIntervalSince(lastSuccessfulRefresh) < 300 { resumeTrackingIfPossible(); return }
         isRefreshing = true
         defer {
             isRefreshing = false
             if requestAuthorization || deferredTrackingAllowed { resumeTrackingIfPossible() }
         }
         lastRefreshHadErrors = false
-        lastCredentialUpdate = .none
-        lastCredentialFailure = nil; lastActivityFailure = nil
+        lastActivityFailure = nil
         guard isApplicationActive(), !Task.isCancelled else { return }
-        lastRefresh = now()
+        needsConfigurationRetry = true
         let context = PlatformRequestContext(channel: configuration.channel,
             language: language == .english ? "en-US" : "zh-CN",
             region: PlatformRequestContext.deviceRegionCode, timezone: TimeZone.current.identifier)
-        async let credentials = Self.attempt { try await api.fetchCredentials(context: context) }
-        async let notice = Self.attempt { try await api.fetchActivity(context: context) }
-        let credentialResult = await credentials
+        let result: Result<PlatformConfigurationResponse, Error>
+        do { result = .success(try await api.fetchConfiguration(context: context)) }
+        catch { result = .failure(error) }
         guard !Task.isCancelled else { return }
-        switch credentialResult {
-        case .success(.credentials(let received)):
-            do {
-                if tracking.currentConfiguration?.fbid == received.fbid && tracking.currentConfiguration?.token == received.token {
-                    lastCredentialUpdate = .unchanged
-                } else {
-                    try tracking.configure(fbid: received.fbid, token: received.token, automaticallyRequestAuthorization: false)
-                    lastCredentialUpdate = .replaced
-                    pendingCredentialSave = received
-                }
-                // Retry persistence if the previous response updated memory but Keychain was unavailable.
-                if pendingCredentialSave == received {
-                    try credentialStore.save(received, for: configuration.cacheKey)
-                    pendingCredentialSave = nil
-                }
-            } catch { lastCredentialUpdate = .failed; lastRefreshHadErrors = true; lastCredentialFailure = Self.failureCode(error) }
-        case .success(.unavailable): lastCredentialUpdate = .unavailable
-        case .failure(let error): lastCredentialUpdate = .failed; lastRefreshHadErrors = true; lastCredentialFailure = Self.failureCode(error)
+        switch result {
+        case .success(let response):
+            lastSuccessfulRefresh = now()
+            needsConfigurationRetry = false
+            surveySampling = response.surveySampling
+            surveyURL = response.surveyURL
+            privacyURL = response.privacyURL ?? PrivacyPolicyLocation.fromBundle()
+            surveyState.saveConfiguration(response)
+        case .failure(let error):
+            let failure = Self.failureCode(error)
+            lastRefreshHadErrors = true
+            lastActivityFailure = failure
         }
+
         // Initial launch routes first; later foreground refreshes keep the existing ATT flow.
         if requestAuthorization && isApplicationActive() { await tracking.requestTrackingAuthorizationIfNeeded() }
-        let noticeResult = await notice
         guard !Task.isCancelled else { return }
-        switch noticeResult {
-        case .success(let url?):
-            activityStore.save(url, for: configuration.cacheKey)
-            presentActivity(url)
-        case .success(nil): break
-        case .failure(let error):
-            lastRefreshHadErrors = true
-            lastActivityFailure = Self.failureCode(error)
-            if isApplicationActive(), let cached = activityStore.loadOpened(for: configuration.cacheKey) {
-                presentActivity(cached)
-            }
+    }
+
+    func recoverConfiguration(language: AppLanguage,
+                              initialDelayNanoseconds: UInt64 = 1_000_000_000,
+                              maximumDelayNanoseconds: UInt64 = 30_000_000_000) async {
+        guard configuration != nil, api != nil else { return }
+        let maximumDelay = max(1, maximumDelayNanoseconds)
+        var delay = min(maximumDelay, max(1, initialDelayNanoseconds))
+        while !Task.isCancelled, isApplicationActive() {
+            await activate(language: language)
+            guard needsConfigurationRetry, !Task.isCancelled, isApplicationActive() else { return }
+            do { try await Task.sleep(nanoseconds: delay) } catch { return }
+            delay = delay > maximumDelay / 2 ? maximumDelay : min(delay * 2, maximumDelay)
         }
-        // A "0" / invalid result preserves the URL cache, but does not auto-open an old page.
     }
 
-    func dismissActivity() { activity = nil; resumeTrackingIfPossible() }
+    func dismissActivity(submission: SurveySubmission? = nil) {
+        if activity?.isSurvey == true { surveyState.finish(submission) }
+        activity = nil
+        resumeTrackingIfPossible()
+    }
+
+    @discardableResult func offerSurveyOnGameStart(language: AppLanguage) -> Bool {
+        guard activity == nil, surveyURL != nil, !surveyState.hasSubmitted,
+              surveySampling.shouldPresent(draw: draw(surveySampling.drawRange)) else { return false }
+        presentSurvey(language: language)
+        return true
+    }
+
+    func presentSurvey(language: AppLanguage) {
+        guard activity == nil, let surveyURL,
+              var parts = URLComponents(url: surveyURL, resolvingAgainstBaseURL: false) else { return }
+        var items = parts.queryItems ?? []
+        items.removeAll { $0.name == "lang" || $0.name == "privacyurl" }
+        items.append(URLQueryItem(name: "lang", value: language.rawValue))
+        items.append(URLQueryItem(name: "privacyurl", value: privacyURL.absoluteString))
+        parts.queryItems = items
+        guard let url = parts.url else { return }
+        activity = ActivityNotice(url: url, isSurvey: true, privacyURL: privacyURL)
+    }
 
     func finishLaunching() {
         deferredTrackingAllowed = true
@@ -112,31 +134,25 @@ struct ActivityNotice: Identifiable, Equatable {
     }
 
     func recordActivityOpened(_ url: URL) {
-        guard let configuration, activity?.url == url, presentedURLs.contains(url) else { return }
-        activityStore.markOpened(url, for: configuration.cacheKey)
-    }
-
-    private func presentActivity(_ url: URL) {
-        guard !presentedURLs.contains(url) else { return }
-        presentedURLs.insert(url)
-        activity = ActivityNotice(url: url)
+        guard activity?.url == url, activity?.isSurvey == true else { return }
+        surveyState.recordOpened()
     }
 
     #if DEBUG
     func presentPreviewActivity() { activity = ActivityNotice(url: URL(string: "https://example.com")!) }
+    func presentPreviewSurvey() {
+        let url = PrivacyPolicyLocation.defaultURL.deletingLastPathComponent().appendingPathComponent("jokersudoku-survey.html")
+        activity = ActivityNotice(url: url, isSurvey: true, privacyURL: PrivacyPolicyLocation.defaultURL)
+    }
     #endif
 
     private func resumeTrackingIfPossible() {
         guard !isRefreshing, isApplicationActive() else { return }
         tracking.applicationDidBecomeActive()
     }
-    private nonisolated static func attempt<T: Sendable>(_ operation: @Sendable () async throws -> T) async -> Result<T, Error> {
-        do { return .success(try await operation()) } catch { return .failure(error) }
-    }
     private nonisolated static func failureCode(_ error: Error) -> String {
         if let error = error as? URLError { return "URLSession:\(error.code.rawValue)" }
         if case NetworkClient.HTTPError.status(let status) = error { return "HTTP:\(status)" }
-        if let error = error as? KeychainPlatformCredentialStore.StorageError { return "Keychain:\(error.status)" }
-        return "invalid-response-or-storage"
+        return "invalid-response"
     }
 }

+ 2 - 2
JokerSudoku/RemoteConfiguration/PlatformCrypto.swift

@@ -22,8 +22,8 @@ enum PlatformCrypto {
             .replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
     }
 
-    static func decrypt(_ envelope: String) throws -> String {
-        guard envelope.hasPrefix("v2:"), envelope.utf8.count <= 350_000 else { throw CryptoError.invalidEnvelope }
+    static func decrypt(_ envelope: String, maximumEnvelopeBytes: Int = 350_000) throws -> String {
+        guard envelope.hasPrefix("v2:"), envelope.utf8.count <= maximumEnvelopeBytes else { throw CryptoError.invalidEnvelope }
         let encoded = String(envelope.dropFirst(3))
         guard !encoded.isEmpty, encoded.utf8.allSatisfy({ (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 45 || $0 == 95 }), encoded.count % 4 != 1 else {
             throw CryptoError.invalidEnvelope

+ 5 - 10
JokerSudoku/RemoteConfiguration/PlatformDiagnostics.swift

@@ -1,7 +1,7 @@
 #if DEBUG
 import Foundation
 
-/// Simulator integration check for HTTP/ATS and Keychain. Tracking stays denied; no Meta events.
+/// Simulator integration check for HTTP/ATS. Tracking stays denied; no Meta events.
 @MainActor enum PlatformDiagnostics {
     private final class Permission: TrackingAuthorizationProviding {
         var status = FacebookTrackingAuthorization.denied
@@ -9,29 +9,24 @@ import Foundation
     }
     private final class SDK: FacebookEventSending {
         func initialize(configuration: FacebookTrackingConfiguration) { preconditionFailure("Diagnostics must not initialize Meta") }
-        func updateConfiguration(_ configuration: FacebookTrackingConfiguration) { preconditionFailure("Diagnostics must not configure Meta") }
         func setCollectionEnabled(_ enabled: Bool) { }
         func log(_ event: FacebookEvent) { preconditionFailure("Diagnostics must not log events") }
         func flush() { }
     }
     static func run() async {
         guard let configuration = PlatformAPIConfiguration.fromBundle() else { return }
-        let store = KeychainPlatformCredentialStore()
         let tracking = FacebookTracking(permission: Permission(), client: SDK(), isApplicationActive: { true })
         let startup = PlatformBootstrap(configuration: configuration, api: PlatformAPIClient(configuration: configuration),
-            credentialStore: store, activityStore: DefaultsPlatformActivityStore(), tracking: tracking,
-            fallback: nil, isApplicationActive: { true })
+            tracking: tracking,
+            localTrackingConfiguration: nil, isApplicationActive: { true })
         await startup.activate(language: .english)
-        let saved = try? store.load(for: configuration.cacheKey)
         let output: [String: Any] = [
             "refreshHadErrors": startup.lastRefreshHadErrors,
-            "credentialFailure": startup.lastCredentialFailure ?? "none",
             "activityFailure": startup.lastActivityFailure ?? "none",
             "generatedAt": Date().timeIntervalSince1970,
             "configurationValid": tracking.isConfigured,
-            "credentialsStoredInKeychain": saved != nil,
-            "currentMatchesStored": saved?.fbid == tracking.currentConfiguration?.fbid && saved?.token == tracking.currentConfiguration?.token,
-            "activityReturned": startup.activity != nil,
+            "surveyRange": startup.surveySampling.range,
+            "activityPresented": startup.activity != nil,
             "metaSDKInitialized": tracking.isSDKInitialized
         ]
         let path = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("PlatformIntegrationProbe.json")

+ 11 - 3
JokerSudoku/RemoteConfiguration/PlatformLiveServices.swift

@@ -4,9 +4,17 @@ extension PlatformBootstrap {
     static func live() -> PlatformBootstrap {
         let configuration = PlatformAPIConfiguration.fromBundle()
         let info = Bundle.main.infoDictionary ?? [:]
-        let fallback = try? PlatformCredentials(fbid: info["FacebookAppID"] as? String ?? "", token: info["FacebookClientToken"] as? String ?? "")
+        let localTrackingConfiguration = try? FacebookTrackingConfiguration(fbid: info["FacebookAppID"] as? String ?? "", token: info["FacebookClientToken"] as? String ?? "")
+        var surveyDefaults = UserDefaults.standard
+        #if DEBUG
+        if DevelopmentPreview.isEnabled {
+            let suite = "JokerSudoku.DevelopmentPreview.Survey"
+            surveyDefaults = UserDefaults(suiteName: suite)!
+            surveyDefaults.removePersistentDomain(forName: suite)
+        }
+        #endif
+        LegacyFacebookCredentialCleanup.remove()
         return PlatformBootstrap(configuration: configuration, api: configuration.map { PlatformAPIClient(configuration: $0) },
-            credentialStore: KeychainPlatformCredentialStore(), activityStore: DefaultsPlatformActivityStore(),
-            tracking: .shared, fallback: fallback, isApplicationActive: { UIApplication.shared.applicationState == .active })
+            tracking: .shared, localTrackingConfiguration: localTrackingConfiguration, isApplicationActive: { UIApplication.shared.applicationState == .active }, surveyDefaults: surveyDefaults)
     }
 }

+ 0 - 61
JokerSudoku/RemoteConfiguration/PlatformPersistence.swift

@@ -1,61 +0,0 @@
-import Foundation
-import Security
-import CryptoKit
-
-protocol PlatformCredentialStoring {
-    func load(for key: String) throws -> PlatformCredentials?
-    func save(_ credentials: PlatformCredentials, for key: String) throws
-}
-
-struct KeychainPlatformCredentialStore: PlatformCredentialStoring {
-    private let service = (Bundle.main.bundleIdentifier ?? "JokerSudoku") + ".platform.credentials"
-    struct StorageError: Error { let status: OSStatus }
-    private func query(_ key: String) -> [String: Any] {
-        [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: key]
-    }
-    func load(for key: String) throws -> PlatformCredentials? {
-        var query = query(key)
-        query[kSecReturnData as String] = true
-        query[kSecMatchLimit as String] = kSecMatchLimitOne
-        var result: CFTypeRef?
-        let status = SecItemCopyMatching(query as CFDictionary, &result)
-        if status == errSecItemNotFound { return nil }
-        guard status == errSecSuccess else { throw StorageError(status: status) }
-        guard let data = result as? Data else { throw StorageError(status: errSecDecode) }
-        return try JSONDecoder().decode(PlatformCredentials.self, from: data)
-    }
-    func save(_ credentials: PlatformCredentials, for key: String) throws {
-        let data = try JSONEncoder().encode(credentials)
-        let update: [String: Any] = [kSecValueData as String: data, kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly]
-        let status = SecItemUpdate(query(key) as CFDictionary, update as CFDictionary)
-        if status == errSecSuccess { return }
-        guard status == errSecItemNotFound else { throw StorageError(status: status) }
-        var insert = query(key)
-        update.forEach { insert[$0.key] = $0.value }
-        let inserted = SecItemAdd(insert as CFDictionary, nil)
-        guard inserted == errSecSuccess else { throw StorageError(status: inserted) }
-    }
-}
-
-protocol PlatformActivityStoring {
-    func save(_ url: URL, for key: String)
-    func load(for key: String) -> URL?
-    func markOpened(_ url: URL, for key: String)
-    func loadOpened(for key: String) -> URL?
-}
-
-struct DefaultsPlatformActivityStore: PlatformActivityStoring {
-    var defaults: UserDefaults = .standard
-    private func name(_ key: String) -> String {
-        "JokerSudoku.activityURL." + SHA256.hash(data: Data(key.utf8)).map { String(format: "%02x", $0) }.joined()
-    }
-    func save(_ url: URL, for key: String) { defaults.set(url.absoluteString, forKey: name(key)) }
-    func load(for key: String) -> URL? { defaults.string(forKey: name(key)).flatMap(ActivityURL.parse) }
-    func markOpened(_ url: URL, for key: String) {
-        guard load(for: key) == url else { return }
-        defaults.set(url.absoluteString, forKey: name(key) + ".opened")
-    }
-    func loadOpened(for key: String) -> URL? {
-        defaults.string(forKey: name(key) + ".opened").flatMap(ActivityURL.parse)
-    }
-}

+ 12 - 3
JokerSudoku/RemoteConfiguration/PrivacyPolicy.swift

@@ -1,5 +1,15 @@
 import Foundation
 
+enum PrivacyPolicyLocation {
+    static let defaultURL = URL(string: "http://a806b934804d0f0ab.awsglobalaccelerator.com/privacy/jokersudoku.html")!
+
+    static func fromBundle(_ bundle: Bundle = .main) -> URL {
+        guard let raw = bundle.object(forInfoDictionaryKey: "PrivacyPolicyURL") as? String,
+              let url = ActivityURL.parse(raw) else { return defaultURL }
+        return url.pathExtension.lowercased() == "md" ? url.deletingPathExtension().appendingPathExtension("html") : url
+    }
+}
+
 protocol PrivacyPolicyFetching: Sendable {
     func fetchPolicy() async throws -> String
 }
@@ -15,15 +25,14 @@ struct PrivacyPolicyClient: PrivacyPolicyFetching {
     }
 
     static func fromBundle(_ bundle: Bundle = .main) -> Self {
-        let url = (bundle.object(forInfoDictionaryKey: "PrivacyPolicyURL") as? String).flatMap(ActivityURL.parse)
-        return Self(url: url)
+        Self(url: PrivacyPolicyLocation.fromBundle(bundle))
     }
 
     func fetchPolicy() async throws -> String {
         guard let url, ActivityURL.parse(url.absoluteString) != nil else { throw PolicyError.invalidURL }
         var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
         request.httpMethod = "GET"
-        request.setValue("text/markdown, text/plain;q=0.9", forHTTPHeaderField: "Accept")
+        request.setValue("text/html, text/markdown;q=0.9, text/plain;q=0.8", forHTTPHeaderField: "Accept")
         let data = try await transport.execute(request)
         guard let text = String(data: data, encoding: .utf8) else { throw PolicyError.invalidText }
         return text

+ 66 - 0
JokerSudoku/RemoteConfiguration/SurveyState.swift

@@ -0,0 +1,66 @@
+import Foundation
+
+struct SurveySampling: Equatable, Sendable {
+    let range: Int
+
+    init(_ raw: String?) {
+        let text = raw?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+        if let integer = Int(text), integer >= 0 {
+            range = integer
+        } else if let number = Double(text), number.isFinite, number >= 0,
+                  number < Double(Int.max) {
+            range = Int(number)
+        } else {
+            range = 1
+        }
+    }
+
+    var drawRange: ClosedRange<Int> { range == 0 ? 0...0 : 1...range }
+
+    func shouldPresent(draw: Int) -> Bool {
+        guard drawRange.contains(draw) else { return false }
+        // R + N / 100 >= N, evaluated without overflowing an integer addition.
+        return range - draw <= range / 100
+    }
+}
+
+struct SurveySubmission: Codable, Equatable {
+    let answers: [Int]
+    let feedback: String
+}
+
+@MainActor final class SurveyState {
+    private let defaults: UserDefaults
+    private let prefix = "JokerSudoku.survey.v1."
+    var sampling: SurveySampling { SurveySampling(defaults.string(forKey: prefix + "playerInfo10")) }
+    var surveyURL: URL? { defaults.string(forKey: prefix + "surveyURL").flatMap(ActivityURL.parse) }
+    var privacyURL: URL? { defaults.string(forKey: prefix + "privacyURL").flatMap(ActivityURL.parse) }
+    func saveConfiguration(_ value: PlatformConfigurationResponse) {
+        defaults.set(String(value.surveySampling.range), forKey: prefix + "playerInfo10")
+        defaults.set(value.surveyURL?.absoluteString, forKey: prefix + "surveyURL")
+        defaults.set(value.privacyURL?.absoluteString, forKey: prefix + "privacyURL")
+    }
+    var hasOpened: Bool { defaults.bool(forKey: prefix + "opened") }
+    var hasSubmitted: Bool {
+        if defaults.object(forKey: prefix + "submitted") != nil { return defaults.bool(forKey: prefix + "submitted") }
+        return submission != nil
+    }
+    var hasFinished: Bool { hasSubmitted }
+    var submission: SurveySubmission? {
+        guard let data = defaults.data(forKey: prefix + "submission"),
+              let value = try? JSONDecoder().decode(SurveySubmission.self, from: data), Self.valid(value) else { return nil }
+        return value
+    }
+
+    init(defaults: UserDefaults = .standard) { self.defaults = defaults }
+    func recordOpened() { defaults.set(true, forKey: prefix + "opened") }
+    func finish(_ submission: SurveySubmission?) {
+        guard let submission, Self.valid(submission), let data = try? JSONEncoder().encode(submission) else { return }
+        defaults.set(data, forKey: prefix + "submission")
+        defaults.set(true, forKey: prefix + "submitted")
+        defaults.set(true, forKey: prefix + "finished")
+    }
+    private static func valid(_ value: SurveySubmission) -> Bool {
+        value.answers.count == 4 && value.answers.allSatisfy { [1,2].contains($0) } && value.feedback.count <= 2000
+    }
+}

+ 4 - 8
JokerSudoku/Tracking/FacebookSDKClient.swift

@@ -54,7 +54,7 @@ import FacebookCore
         Settings.shared.isAdvertiserIDCollectionEnabled = false
         Settings.shared.isAutoLogAppEventsEnabled = false
         if #available(iOS 17, *) {
-            // SDK 18.1.1 reads the OS ATT status directly on iOS 17+.
+            // The SDK reads the OS ATT status directly on iOS 17+.
         } else {
             Settings.shared.isAdvertiserTrackingEnabled = true
         }
@@ -69,22 +69,18 @@ import FacebookCore
         if enabled { AppEvents.shared.activateApp() }
     }
 
-    func updateConfiguration(_ configuration: FacebookTrackingConfiguration) {
-        Settings.shared.clientToken = configuration.token
-        Settings.shared.appID = configuration.fbid
-        // Keep loggingOverrideAppID unset: App Events uses the current Settings.appID.
-        // The next activateApp refreshes the SDK's server configuration for the new app.
-    }
-
     func log(_ event: FacebookEvent) {
         var parameters: [AppEvents.ParameterName: Any] = [:]
         if let currency = event.currency { parameters[.currency] = currency }
+        if let questionID = event.questionID { parameters[AppEvents.ParameterName(rawValue: "question_id")] = questionID }
+        if let answer = event.answer { parameters[AppEvents.ParameterName(rawValue: "answer")] = answer }
         let name: AppEvents.Name
         switch event.action {
         case .purchased: name = .purchased
         case .addtocart: name = .addedToCart
         case .addtowishlist: name = .addedToWishlist
         case .completeregistration: name = .completedRegistration
+        case .surveyresponse: name = AppEvents.Name(rawValue: "survey_response")
         }
         if let value = event.value {
             AppEvents.shared.logEvent(name, valueToSum: value, parameters: parameters)

+ 21 - 13
JokerSudoku/Tracking/FacebookTracking.swift

@@ -19,7 +19,7 @@ public struct FacebookTrackingConfiguration: Equatable, Sendable, CustomStringCo
         self.token = clientToken
     }
     public var description: String { "FacebookTrackingConfiguration(fbid: \(fbid), token: <redacted>)" }
-    public enum ConfigurationError: Error { case invalidAppID, invalidClientToken, alreadyInitialized }
+    public enum ConfigurationError: Error { case invalidAppID, invalidClientToken, configurationLocked }
 }
 
 public enum FacebookTrackingAuthorization: Equatable {
@@ -37,23 +37,40 @@ public enum FacebookTrackingAuthorization: Equatable {
 public struct FacebookEvent: Equatable {
     public enum Action: String, CaseIterable {
         case purchased, addtocart, addtowishlist, completeregistration
+        case surveyresponse = "survey_response"
     }
     public let action: Action
     public let value: Double?
     public let currency: String?
+    public let questionID: Int?
+    public let answer: String?
 
-    var monetaryParameters: [String: Any] {
+    var parameters: [String: Any] {
         var params: [String: Any] = [:]
         if let value { params["value"] = value }
         if let currency { params["currency"] = currency }
+        if let questionID { params["question_id"] = questionID }
+        if let answer { params["answer"] = answer }
         return params
     }
 
-    public enum ValidationError: Error { case unsupportedAction, invalidValue, invalidCurrency }
+    public enum ValidationError: Error { case unsupportedAction, invalidValue, invalidCurrency, invalidSurveyResponse }
     public init(action: String, params: [String: Any]) throws {
         guard let action = Action(rawValue: action.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()) else {
             throw ValidationError.unsupportedAction
         }
+        if action == .surveyresponse {
+            guard Set(params.keys) == Set(["question_id", "answer"]),
+                  let question = params["question_id"] as? NSNumber, CFGetTypeID(question) != CFBooleanGetTypeID(),
+                  [1.0, 2.0, 3.0, 4.0].contains(question.doubleValue),
+                  let answer = params["answer"] as? String, ["willing", "unwilling"].contains(answer) else {
+                throw ValidationError.invalidSurveyResponse
+            }
+            self.action = action; self.value = nil; self.currency = nil
+            self.questionID = question.intValue; self.answer = answer
+            return
+        }
+        self.questionID = nil; self.answer = nil
         // A completed registration has no required price/currency. Keep monetary validation
         // for commerce events and for callers that explicitly provide monetary parameters.
         if action == .completeregistration, params["value"] == nil, params["currency"] == nil {
@@ -84,7 +101,6 @@ public struct FacebookEvent: Equatable {
 
 @MainActor public protocol FacebookEventSending: AnyObject {
     func initialize(configuration: FacebookTrackingConfiguration)
-    func updateConfiguration(_ configuration: FacebookTrackingConfiguration)
     func setCollectionEnabled(_ enabled: Bool)
     func log(_ event: FacebookEvent)
     func flush()
@@ -104,7 +120,6 @@ public struct FacebookEvent: Equatable {
     @Published public private(set) var isSDKInitialized = false
     @Published public private(set) var isRequestingAuthorization = false
     private var configuration: FacebookTrackingConfiguration?
-    private var sdkConfiguration: FacebookTrackingConfiguration?
     public var currentConfiguration: FacebookTrackingConfiguration? { configuration }
     private let permission: TrackingAuthorizationProviding
     private let client: FacebookEventSending
@@ -124,9 +139,9 @@ public struct FacebookEvent: Equatable {
     public func configure(fbid: String, token: String, automaticallyRequestAuthorization: Bool = true) throws {
         let next = try FacebookTrackingConfiguration(fbid: fbid, token: token)
         guard configuration != next else { return }
+        guard configuration == nil else { throw FacebookTrackingConfiguration.ConfigurationError.configurationLocked }
         configuration = next
         isConfigured = true
-        if isSDKInitialized { refreshAuthorization(); startIfAllowed() }
         // A caller can configure after launch; the next main-actor turn handles the foreground flow.
         if automaticallyRequestAuthorization && isApplicationActive() { applicationDidBecomeActive() }
     }
@@ -193,14 +208,7 @@ public struct FacebookEvent: Equatable {
         guard authorization == .authorized, isApplicationActive(), let configuration else { return }
         if !isSDKInitialized {
             client.initialize(configuration: configuration)
-            sdkConfiguration = configuration
             isSDKInitialized = true
-        } else if sdkConfiguration != configuration {
-            // Drain the old buffer under its original identity before switching future events.
-            client.flush()
-            disableCollection()
-            client.updateConfiguration(configuration)
-            sdkConfiguration = configuration
         }
         if !collectionEnabled { client.setCollectionEnabled(true); collectionEnabled = true }
     }

+ 12 - 0
JokerSudoku/Tracking/LegacyFacebookCredentialCleanup.swift

@@ -0,0 +1,12 @@
+import Foundation
+import Security
+
+enum LegacyFacebookCredentialCleanup {
+    static func remove() {
+        let service = (Bundle.main.bundleIdentifier ?? "JokerSudoku") + ".platform.credentials"
+        SecItemDelete([
+            kSecClass as String: kSecClassGenericPassword,
+            kSecAttrService as String: service
+        ] as CFDictionary)
+    }
+}

+ 2 - 0
JokerSudoku/en.lproj/Localizable.strings

@@ -177,3 +177,5 @@
 "Loading…" = "Loading…";
 "Online Activities" = "Online Activities";
 "To load activity notices and app configuration, our service receives the app channel, language, device region, time zone, and your connection’s IP address. Your Sudoku entries and notes are not included. Activity pages may store cookies and cached resources on your device." = "To load activity notices and app configuration, our service receives the app channel, language, device region, time zone, and your connection’s IP address. Your Sudoku entries and notes are not included. Activity pages may store cookies and cached resources on your device.";
+
+"Player Survey" = "Player Survey";

+ 14 - 14
JokerSudoku/en.lproj/PrivacyPolicy.md

@@ -1,6 +1,6 @@
 # Joker Sudoku Privacy Policy
 
-Effective date / last updated: November 4, 2026
+Effective date / last updated: November 24, 2026
 
 Joker Sudoku ("we", "us") operates the JokerSudoku puzzle game. This policy explains how the current public iPhone and iPad app handles information. Contact: support@jokersudoku.com. Reading this policy is not consent to advertising tracking; that permission is requested separately through iOS.
 
@@ -8,25 +8,25 @@ Reading this policy, downloading the App, or continuing to play does not itself
 
 ## 1. Information We Collect
 
-No online account is required to play the native Sudoku game. We do not require an account name, password, phone number, identity document, or email address for gameplay. Saving game records on a server is separate from registering an online account. The game does not request contacts, microphone, camera, photos, or precise location permissions.
+No online account is required to play the native Sudoku game. We do not require an account name, password, phone number, identity document, or email address for gameplay. The native game does not request contacts, microphone, camera, photo-library-wide access, or precise location permissions. If you choose to attach a screenshot to a feedback form, the browser or system picker lets you select the file to provide.
 
 ### 1.1 Game Progress and Preferences
 
 On your device, we store game progress, entered numbers, notes, elapsed time, mistakes, hint usage, undo history, daily challenge records, scores, statistics, language, board theme, gameplay settings, and feedback drafts to provide local saves and personalization.
 
-When a network connection is available, the app also sends game-save data, including the game state and progress records needed to save the current game, to Joker Sudoku's game-save service through an application network API for server-side storage of your game progress. Game-save information is gameplay content and is not limited to data stored on your device. Advertising tracking permission does not itself authorize unrelated game-save processing. Network requests also expose your connection's IP address and technical request information to the receiving service. Offline Sudoku gameplay and local saving remain available without a network connection. Server saving does not itself guarantee cross-device access or recovery after reinstalling the app.
+In this version, game saves, completed puzzles, statistics, settings, and questionnaire completion status stay on your device. The app does not automatically upload or restore these records through the configuration service and does not create or send an anonymous player UUID for game-save synchronization. Offline Sudoku and local saving remain available. Reinstalling the app or changing devices does not provide server recovery of local progress.
 
 ### 1.2 Configuration and Technical Information
 
-The App requests platform credentials and activity configuration using the app channel, selected language, device region setting, and time zone. The receiving service also receives your connection’s IP address and technical request information. Reading the region setting does not request GPS location. Returned activity URLs and their successful opening status are cached on your device. App-service credentials may be stored in the iOS Keychain; these are not player account credentials. Configuration requests and server game saves serve different purposes.
+The app requests questionnaire and privacy-page addresses and questionnaire sampling settings using the app channel, selected language, device region setting, and time zone. The receiving service also receives your connection’s IP address and technical request information. Reading the region setting does not request GPS location. Returned addresses, sampling settings, and questionnaire visit/submission status are stored locally. Meta App ID and Client Token are packaged with the app and are not player account credentials; the app does not accept replacements from the configuration service. These configuration requests do not contain your saved puzzles, statistics, game preferences, feedback drafts, or an anonymous player UUID.
 
 ### 1.3 Customer Support
 
-Feedback drafts stay on the device unless you choose to share them using the system share sheet. The recipient and information you share are your choice; a draft is not automatically sent to support. If you email us, we receive your email address and the message and attachments you send for handling the inquiry. Do not include passwords, identity documents, or unnecessary sensitive information.
+Native feedback drafts stay on the device unless you choose to share them using the system share sheet. Separately, the optional bug-report and suggestion webpage sends the text you enter and screenshots you select to Joker Sudoku only when you press Submit feedback. It also sends the channel, selected form language, submission time, and normal network request information. It does not automatically attach your game saves, settings, or a player UUID. The selected text and files may contain identifying information or embedded image metadata; remove personal or sensitive information before uploading. Screenshots are optional. If you email us, we receive your email address and the message and attachments you send to handle the inquiry. Do not send passwords, identity documents, or unnecessary sensitive information.
 
 ## 2. How We Use Your Information
 
-We use game records to operate Sudoku, save progress, and provide statistics and preferences; technical configuration information to obtain app-service settings and activity notices; support information to respond to requests; and authorized Meta information to measure app promotion and advertising effectiveness. Information is also processed as necessary for specific troubleshooting, security, and legal obligations. Collection for one purpose is not authorization for unrelated uses; new purposes requiring consent will be explained and authorized before processing starts.
+We use local game records to operate Sudoku, save progress, and provide statistics and preferences on your device; configuration information to obtain app-service settings and questionnaires; submitted support text and images to investigate bugs, respond to requests, and improve the game; and authorized Meta information to measure app promotion and questionnaire responses. Information is also processed as necessary for specific troubleshooting, security, and legal obligations. Collection for one purpose is not authorization for unrelated uses; new purposes requiring consent will be explained and authorized before processing starts.
 
 ## 3. Third-Party Services
 
@@ -38,25 +38,25 @@ We use the current Meta integration to measure app promotion and prepare for a p
 
 With authorization, Meta may process advertising identifiers (including IDFA when available), SDK-generated identifiers, device and app information, app activation and other supported app events, network information including IP address, and SDK diagnostics to measure advertising effectiveness and improve advertising. Meta may combine this information with information from other apps or services for attribution and tracking. Its actual processing depends on permission, SDK behavior, and Meta's applicable settings and policies. Meta may store identifiers, configuration, and event data locally and process transmitted data on its infrastructure, including outside your country or region.
 
-The current Sudoku game has no online registration, purchases, shopping cart, wishlist, in-app payments, or displayed advertisements. Opening or completing a Sudoku game does not itself represent a registration or purchase and is not reported as one. Supported tracking functions are not evidence of a transaction. More about Meta's practices and choices: [Meta Privacy Policy](https://www.facebook.com/privacy/policy/). A webpage can call supported native event functions only for the corresponding real business action and when ATT allows submission. Monetary events can include value and currency.
+The current Sudoku game has no online registration, purchases, shopping cart, wishlist, in-app payments, or displayed advertisements. The optional questionnaire asks about willingness to see ads, donate, buy optional items, and try new gameplay. When you submit it and ATT allows tracking, this version sends a custom Meta event named survey_response for each answer, containing only a question number (question_id, 1–4) and willingness label (answer, willing or unwilling). These events do not include a price, currency, or payment information and are not reported as purchases, shopping actions, or registrations. Written questionnaire comments and a local submission record stay on the device and are not sent to Meta by this integration. Bug-report text and screenshots use the separate, user-initiated support submission described in Section 1.3. More about Meta’s practices and choices: [Meta Privacy Policy](https://www.facebook.com/privacy/policy/).
 
 If a later version introduces banner, interstitial, or rewarded advertisements, or adds an advertising or mediation partner, we will disclose the actual providers, data categories, purposes, sharing, local storage, retention information, and available choices before the new processing starts. We will update the policy and store privacy disclosures and request any permission or consent required for that processing. Tracking remains subject to ATT; declining tracking will not prevent the basic Sudoku game. This notice is not advance permission for unspecified partners, personalized advertising, additional collection, or a change of purpose.
 
 ### 3.2 Activity Webpages and Cookies
 
-The native Sudoku game does not require browser cookies. A valid activity URL returned by the configuration service can automatically open a fullscreen embedded webpage. Its provider receives network requests and may use cookies, cached resources, local storage, and website sessions through WebKit's persistent website storage. Website forms and third-party services may involve additional data processing; they are separate from the native game-save service. Review the displayed website's privacy information before providing personal information. Supported webpage app-event calls are subject to the app's tracking permission checks. Local app storage keeps the game data described above; the Meta SDK may also keep its own configuration and event cache after authorization. Device backups may contain app data depending on your Apple backup settings. The native bridge’s ATT check covers events submitted through that bridge; it is not blanket permission for website scripts to track users. Activity content must also comply with applicable permission and disclosure requirements. Its processing is included in the full App privacy assessment and is not excluded merely because the content is online. Following a link or opening the external browser can send further requests to the destination provider.
+The native Sudoku game does not require browser cookies. You can open the questionnaire from Home; it may also be offered after you tap New Game, before difficulty selection, according to the configured sampling setting. You can close it without completing it and continue playing. A configuration response alone does not open a webpage. Questionnaire drafts may be stored in the website’s local storage. WebKit uses persistent website storage for cookies, cached resources, local storage, and website sessions. The website provider receives network requests; following privacy or feedback links opens the external browser and sends requests to the destination provider. Native bridge events remain subject to ATT. This permission does not authorize website scripts to track you independently; website processing must also follow applicable consent and disclosure requirements. The Meta SDK may keep its own configuration and event cache after authorization. Device backups may contain app data depending on your Apple backup settings.
 
 ### 3.3 Hosting and Other Disclosures
 
-Joker Sudoku receives and stores the game-save information described in Section 1. Service providers supporting hosting, storage, and network delivery may process information needed to provide those services on our behalf. We require providers acting on our behalf to use it for the agreed purposes. Third parties receiving user information must provide the same or equivalent protection described in this policy and required by applicable privacy requirements. We do not sell game saves or make them public to other players. Configuration services process the technical request information described above. After your tracking authorization, the Meta SDK sends information described in Section 3.1 to Meta for advertising measurement and related processing. Disclosures required by law are limited to information and purposes required by applicable obligations. Service infrastructure may be outside your country or region; applicable cross-border processing requirements must be met.
+Joker Sudoku receives the configuration request information and the optional feedback submissions described above. Hosting, storage, and network-delivery providers may process information needed to provide those services on our behalf. We require providers acting on our behalf to use it for the agreed purposes and provide the same or equivalent protection described in this policy and required by applicable privacy requirements. We do not sell your feedback or publish it to other players. After your tracking authorization, Meta receives the information described in Section 3.1. Disclosures required by law are limited to the information and purposes required by applicable obligations. Service infrastructure may be outside your country or region; applicable cross-border processing requirements must be met.
 
 The current native app does not integrate Game Center or in-app purchasing. We do not describe these as active services or treat a possible future integration as permission for new processing.
 
 ## 4. Data Storage and Security
 
-Local game records remain until removed from the device. Deleting the app removes its local game data; deleting a backup is managed separately in Apple's backup settings. App-service configuration credentials may be cached in the iOS Keychain and are not player account credentials; Keychain entries can persist independently of the app's ordinary files. We do not promise that uninstalling deletes data already received by a service provider.
+Local game records remain until removed from the device. Deleting the app removes its local game data; deleting a backup is managed separately in Apple’s backup settings. The app uses its packaged Meta configuration, no longer reads or stores remotely supplied credential pairs, and removes legacy app-specific credential cache entries during upgrade. Meta may maintain its own configuration and event storage as explained in Section 3. Uninstalling does not erase information already received by a service provider.
 
-Server game saves are retained for the time needed to provide the game-save service. We delete or de-identify records when they are no longer needed, unless longer retention is required by applicable law or necessary for a specific legal or security matter. Any exception is limited to that purpose. Deleting the app or turning off tracking does not automatically delete uploaded game saves. To request deletion of server game saves, contact support@jokersudoku.com as described in Section 5. If residual copies must remain temporarily in backups, we restrict their use to backup recovery and delete them through the backup lifecycle; a restored copy remains subject to the deletion request.
+This version does not send game-save records to our servers. Removing synchronization does not automatically erase records that an earlier version may already have uploaded. If you used an earlier version and want to ask about or delete those records, contact support@jokersudoku.com. Uninstalling also does not delete feedback already submitted or information already received by Meta.
 
 Support correspondence is retained as needed to handle the request and associated follow-up. Technical records are retained for their service, troubleshooting, or security purpose. When no longer needed, we delete or de-identify them, unless a specific legal obligation or legal/security matter requires limited further retention.
 
@@ -66,9 +66,9 @@ We use iOS application storage and system protections and limit access to server
 
 You can change language and game settings in the app. Manage tracking in iOS Settings > Privacy & Security > Tracking, or through Me > Privacy Preferences when that screen is available. Revoking permission stops subsequent collection through our integration when the app observes the new status; it does not automatically erase information already received by Meta. You can play offline, delete the app's local data by uninstalling, and manage backups separately.
 
-To ask about access, correction, deletion, withdrawal of consent where applicable, or other rights concerning information we hold, contact support@jokersudoku.com. For a server-save request, state the request type and provide information that allows us to locate the record, such as a save reference available to you and an approximate time of play. Do not send passwords or identity documents. We will explain any additional information needed to locate the record, verify the request proportionately, and respond under applicable requirements. If we must retain information for a specific legal reason, we will explain the reason and relevant limits. A request to stop further uploads should state this explicitly; deleting an existing save is not by itself a device setting that prevents later uploads. Offline gameplay remains available.
+To ask about access, correction, deletion, withdrawal of consent where applicable, or other rights concerning information we hold, contact support@jokersudoku.com. Describe the request and provide information that helps us locate it, such as the approximate submission time, report subject, and any receipt reference available to you. Do not send passwords or identity documents. We will explain any additional information needed, verify requests proportionately, and respond under applicable requirements. If information must be retained for a specific legal reason, we will explain the relevant limits. You can decline to submit feedback without affecting Sudoku. Native game-save synchronization is not offered in this version.
 
-We cannot remotely manage records that remain only on your device. Uninstalling removes local game data but does not submit a server deletion request. For information held by Meta, its privacy channels are also available; contacting Meta is not a substitute for contacting us about our own service.
+For records kept only on your device, we cannot manage or retrieve them remotely. Uninstalling clears local game records, but does not submit a server deletion request. You can also use Meta’s privacy channels for information held by Meta; contacting Meta does not replace contacting Joker Sudoku about data we control.
 
 ## 6. Children’s Privacy
 
@@ -76,7 +76,7 @@ The native Sudoku game is a general-audience logic puzzle without violence, gamb
 
 ## 7. Changes to This Privacy Policy
 
-We will update this policy when our features or data practices change and show the new effective date. This includes changes to game-save data or its purposes and the addition of ad placements or advertising partners. We will explain new processing before it starts and obtain any required permission or consent. Material changes will be communicated appropriately; continuing to play or updating the policy does not override your iOS tracking choice or constitute blanket consent to future processing. ATT authorization for advertising tracking does not itself constitute consent to unrelated game-save processing.
+We update this policy and its effective date when functionality or information processing changes, including any future server saving, new advertising placements, or advertising partners. We explain the actual new processing and obtain required permissions or consent before it starts. Significant changes will be communicated appropriately. Continuing to play, or updating this policy, does not override your iOS tracking choice or provide blanket consent to future processing.
 
 ## 8. Contact Us
 

+ 2 - 0
JokerSudoku/zh-Hans.lproj/Localizable.strings

@@ -177,3 +177,5 @@
 "Loading…" = "正在加载…";
 "Online Activities" = "在线活动";
 "To load activity notices and app configuration, our service receives the app channel, language, device region, time zone, and your connection’s IP address. Your Sudoku entries and notes are not included. Activity pages may store cookies and cached resources on your device." = "获取活动通知和应用配置时,服务端会收到应用渠道、语言、设备地区、时区和连接 IP 地址。请求不会包含你的数独填数或备注。活动网页可能会在设备上保存 Cookie 和资源缓存。";
+
+"Player Survey" = "玩家问卷";

+ 14 - 14
JokerSudoku/zh-Hans.lproj/PrivacyPolicy.md

@@ -1,6 +1,6 @@
 # Joker Sudoku 隐私政策
 
-生效日期/最近更新:2026 年 11 月 4 日
+生效日期/最近更新:2026 年 11 月 24 日
 
 Joker Sudoku(以下简称“我们”)运营 JokerSudoku 数独游戏。本政策说明当前公开发布的 iPhone 与 iPad App 如何处理信息。联系邮箱:support@jokersudoku.com。阅读本政策不代表同意广告跟踪;相关授权由 iOS 单独询问。
 
@@ -8,25 +8,25 @@ Joker Sudoku(以下简称“我们”)运营 JokerSudoku 数独游戏。本
 
 ## 1. 我们收集的信息
 
-原生数独游戏无需注册线上账号,不要求玩家为游戏提供账号名称、密码、手机号、身份证件或邮箱。将游戏记录保存到服务器不等于注册线上账号。游戏不申请通讯录、麦克风、相机、照片或精确位置权限。
+原生数独游戏无需注册线上账号,不要求玩家为游戏提供账号名称、密码、手机号、身份证件或邮箱。原生游戏不申请通讯录、麦克风、相机、完整照片库访问或精确位置权限。若您主动为反馈选择截图,浏览器或系统文件选择器会让您选择要提供的文件。
 
 ### 1.1 游戏进度与偏好
 
 为提供本地存档与个性化功能,App 在设备上保存游戏进度、填入的数字、笔记、用时、错误次数、提示使用情况、撤销历史、每日挑战记录、分数、统计、语言、棋盘主题、游戏设置和反馈草稿。
 
-在有网络连接时,App 还会通过应用网络接口将游戏存档数据,包括保存当前游戏所需的对局状态与进度记录发送至 Joker Sudoku 的游戏存档服务,在服务器保存游戏进度。游戏存档属于游戏内容,并非仅在设备本地处理。广告跟踪授权本身不代表对无关存档处理的同意。接收服务还会因网络请求获得连接 IP 地址及相关技术请求信息。无网络时,数独游戏及本地保存仍可使用。服务器保存本身不代表保证跨设备访问或卸载后恢复。
+本版本的游戏存档、已完成关卡、统计、设置及问卷完成状态仅保存在设备上。App 不通过配置服务自动上传或恢复这些记录,也不为游戏存档同步生成或发送匿名玩家 UUID。数独和本地保存可离线使用;重新安装或更换设备不提供本地进度的服务器恢复。
 
 ### 1.2 配置与技术信息
 
-App 请求平台凭据及活动配置时,会发送应用渠道、所选语言、设备地区设置和时区。接收服务还会获得连接 IP 地址和技术请求信息。读取地区设置不等于申请 GPS 定位。返回的活动网址及成功打开状态会缓存在设备上;应用服务凭据可能存入 iOS 钥匙串,它们不是玩家账号凭据。配置请求与服务器存档属于不同用途的处理。
+App 使用应用渠道、所选语言、设备地区设置和时区,请求问卷及隐私页面地址、问卷抽样设置。接收服务还会获得连接 IP 地址和技术请求信息。读取地区设置不等于申请 GPS 定位。返回地址、抽样设置及问卷打开/提交状态保存在本机。Meta App ID 与 Client Token 随应用打包,它们不是玩家账号凭据;App 不接受配置服务替换这组凭据。这些配置请求不包含玩家存档、统计、游戏偏好、反馈草稿或匿名玩家 UUID。
 
 ### 1.3 客户支持
 
-反馈草稿保留在设备中,除非您主动通过系统分享功能发送。您自行选择接收方与分享内容;草稿不会自动提交给客服。您向我们发邮件时,我们将收到您主动发送的邮箱地址、正文与附件,用于处理咨询。请勿发送密码、身份证件或不必要的敏感信息。
+原生反馈草稿保留在设备中,除非您主动通过系统分享功能发送。另有可选的 Bug 反馈与优化建议网页,只有点击“提交反馈”后,才向 Joker Sudoku 发送您填写的文字和主动选择的截图,同时发送渠道、表单语言、提交时间及正常网络请求信息。它不会自动附带游戏存档、设置或玩家 UUID。文字、截图及图片内嵌元数据可能含可识别信息,上传前请移除个人或敏感内容;截图为选填。向我们发邮件时,我们会收到您发送的邮箱地址、正文和附件,用于处理咨询。请勿发送密码、身份证件或不必要的敏感信息。
 
 ## 2. 信息的使用方式
 
-我们使用游戏记录运行数独、保存进度、提供统计和偏好;使用技术配置信息获取服务设置与活动通知;使用客服信息处理请求;使用获授权的 Meta 信息衡量推广及广告效果。我们也会在具体排查、安全及法律义务所需范围内处理信息。为某一目的收集信息不代表获准用于无关用途;新增用途需要同意时,会在处理开始前说明并取得同意。
+我们在本机使用游戏记录提供数独、存档、统计和偏好;使用配置请求信息获取应用服务设置与问卷;使用主动提交的客服文字和图片排查问题、处理请求和改进游戏;使用已授权的 Meta 信息衡量推广效果及问卷回答。信息还可能为具体故障排查、安全及法律义务而处理。某一用途的收集不构成无关用途的授权;需要同意的新用途会在处理开始前另行说明和取得授权。
 
 ## 3. 第三方服务
 
@@ -38,25 +38,25 @@ App 集成 Meta(Facebook)iOS SDK 18.1.1,用于广告归因与应用事件
 
 授权后,Meta 可能处理广告标识符(可用时包括 IDFA)、SDK 生成的标识符、设备与应用信息、应用激活及其他支持的事件、包括 IP 地址的网络信息和 SDK 诊断,用于广告效果衡量及广告优化。Meta 可能将相关信息与其他应用或服务的信息结合,用于归因与跟踪。实际处理受权限、SDK 行为及 Meta 相关设置和政策影响。Meta 可能在本地保存标识符、配置和事件数据,并在其基础设施上处理已发送的信息,可能涉及您所在国家或地区之外的处理。
 
-当前原生数独没有线上注册、购买、购物车、愿望清单、应用内支付或广告展示。启动游戏或完成数独不代表注册或购买,App 不会将其作为此类事件上报。提供事件调用函数并不代表发生交易。有关 Meta 数据处理与选择,请参阅 [Meta 隐私政策](https://www.facebook.com/privacy/policy/)。活动网页调用支持的原生事件函数时,须以相应真实业务发生及 ATT 允许上报为前提;金额类事件可包含金额与币种。
+当前数独没有线上注册、购买、购物车、愿望单、应用内支付或广告展示。可选问卷询问对广告、捐献、可选道具及新玩法的意愿。提交问卷且 ATT 允许跟踪时,本版本针对每题答案发送名为 survey_response 的 Meta 自定义事件,仅包含题号 question_id(1–4)和意愿标签 answer(willing 表示愿意,unwilling 表示不愿意)。这些事件不包含价格、币种或支付信息,也不作为购买、购物操作或注册上报。问卷文字意见及提交记录保存在本机,本接入不会将其发送至 Meta。Bug 反馈文字和截图通过第 1.3 节所述的主动客服提交另行发送。Meta 的处理及选择详见 [Meta 隐私政策](https://www.facebook.com/privacy/policy/)。
 
 若后续版本增加横幅、插屏、激励广告,或新增广告及聚合服务方,我们会在新增处理开始前说明实际服务方、数据类型、用途、共享、本地存储、保存信息与可用选择,同步更新本政策和商店隐私披露,并取得该处理所需的权限或同意。涉及跟踪时仍遵守 ATT,拒绝跟踪不会影响基础数独功能。本说明不代表您提前同意未知合作方、个性化广告、额外收集或改变数据用途。
 
 ### 3.2 活动网页与 Cookie
 
-原生数独游戏不依赖浏览器 Cookie。配置服务返回有效活动网址时,App 可能自动打开全屏内嵌网页。网页提供方会接收网络请求,并可能通过 WebKit 的持久化网站存储使用 Cookie、缓存资源、本地存储与网站会话。网页表单及第三方服务可能涉及额外的信息处理,与原生游戏存档服务有所区别。提供个人信息前,请查看网页展示的隐私说明。网页调用支持的应用事件上报时,仍受 App 的跟踪权限检查。本地应用存储保存上述游戏数据;授权后 Meta SDK 也可能保留自身配置与事件缓存。系统设备备份是否包含应用数据,取决于您的 Apple 备份设置。原生桥接的 ATT 检查适用于经该桥接提交的事件,不是网站脚本跟踪的概括授权。活动内容自身也须遵守适用的权限与披露要求,其处理属于完整 App 的隐私评估范围,不因内容在线上就被排除。跟随链接或打开外部浏览器还可能向目标服务方发送进一步请求。
+原生数独不依赖浏览器 Cookie。您可以从主页打开问卷;点击“新游戏”后、选择难度前,也可能按配置抽样展示。无需完成问卷即可关闭并继续游戏。仅收到配置回包不会打开网页。问卷草稿可能存入网站 localStorage;WebKit 使用持久化网站存储保存 Cookie、缓存、localStorage 和会话。网站提供方会获得网络请求;打开隐私或反馈链接时,会交给外部浏览器并向目标网站发起请求。原生桥接事件仍受 ATT 限制,该授权不代表允许网页脚本自行跟踪,网站处理也须满足必要同意和披露要求。Meta SDK 在授权后可能保留自身配置和事件缓存。设备备份是否包含 App 数据由您的 Apple 备份设置决定。
 
 ### 3.3 托管服务与其他披露
 
-Joker Sudoku 接收并保存第 1 节所述游戏存档信息。提供服务器托管、存储与网络交付的服务方,可能受托处理提供相应服务所必需的信息。我们要求受托服务方按约定用途处理;接收用户信息的第三方须提供本政策及适用隐私要求所述的同等保护。我们不出售游戏存档,也不将其向其他玩家公开。配置服务处理前述技术请求信息;在您允许跟踪后,Meta SDK 向 Meta 发送第 3.1 节所述信息,用于广告衡量及相关处理。依法披露限于适用义务要求的信息与用途。服务基础设施可能位于您所在国家或地区以外,并应满足适用的跨境处理要求。
+Joker Sudoku 接收前述配置请求信息及您主动提交的反馈。提供托管、存储和网络传输的服务商可代表我们处理完成相应服务所需的信息;我们要求其仅按约定用途处理,并提供本政策及适用要求所述的同等保护。我们不出售反馈或将其公开给其他玩家。获得跟踪授权后,Meta 接收第 3.1 节所述的信息。依法披露仅限相应义务要求的信息和用途。服务基础设施可能位于您所在国家或地区之外,跨境处理须满足适用要求。
 
 当前原生 App 未接入 Game Center 或应用内购买。我们不将其描述为已启用服务,也不将未来可能接入视为对新增处理的同意。
 
 ## 4. 数据存储与安全
 
-本地游戏记录保存至您从设备删除相关数据。卸载 App 会删除其本地游戏数据;备份的删除需在 Apple 备份设置中单独管理。应用服务配置凭据可能缓存在 iOS 钥匙串中,它们不是玩家账号凭据;钥匙串条目可能独立于普通应用文件保留。我们不承诺卸载会清除服务方已经接收的数据。
+本地游戏记录保存至您从设备删除相关数据。卸载 App 会删除其本地游戏数据;备份需在 Apple 备份设置中单独管理。App 使用随包 Meta 配置,不再读取或保存远程下发的凭据对,并在升级时清理旧版应用专用凭据缓存。Meta 可能按第 3 节说明维护自身配置和事件存储。卸载不会清除服务方已经接收的信息。
 
-服务器存档在提供游戏存档服务所需期间保存。不再需要时,我们会删除或去标识化相关记录;适用法律要求继续保存,或具体法律与安全事项确有需要的除外,且此类例外仅限相应用途。卸载 App 或关闭跟踪权限不会自动删除已上传的游戏存档。如需删除服务器存档,请按第 5 节通过 support@jokersudoku.com 联系我们。若备份中暂时仍有残余副本,我们会限制其仅用于备份恢复,并按备份生命周期清除;恢复的副本仍受原删除请求约束。
+本版本不向服务器发送游戏存档。移除同步功能不会自动删除早期版本可能已上传的记录。若曾使用早期版本并希望查询或删除相应记录,请联系 support@jokersudoku.com。卸载也不会删除已经提交的反馈或 Meta 已接收的信息。
 
 客服通信在处理请求及相关后续事项所需期间保存;技术记录按服务、排查或安全用途保存。不再需要时,我们会删除或去标识化,具体法律义务或法律/安全事项要求有限延长保存的除外。
 
@@ -66,9 +66,9 @@ Joker Sudoku 接收并保存第 1 节所述游戏存档信息。提供服务器
 
 您可以在 App 中更改语言与游戏设置,通过 iOS“设置 > 隐私与安全性 > 跟踪”管理跟踪权限,也可在相应界面可达时通过 App“我 > 隐私偏好”管理。撤回授权后,本接入在观察到新状态时停止后续收集,不会自动删除 Meta 已接收的信息。您可以离线游戏、卸载以清除本地游戏数据,并单独管理备份。
 
-如需就我们持有的信息提出访问、更正、删除、适用情形下撤回同意或其他权利请求,请联系 support@jokersudoku.com。申请处理服务器存档时,请说明请求类型,并提供您能够获取的存档参考信息及大致游玩时间等有助于定位记录的信息,不要发送密码或身份证件。如还需其他定位信息,我们会另行说明,以适度方式核实请求并按适用要求答复。确因具体法律理由需要保留信息时,我们会说明原因和相关限制。若希望停止后续上传,请明确提出;删除现有存档本身不是阻止设备后续上传的设置。离线游戏仍可使用。
+如需就我们持有的信息提出访问、更正、删除、适用情形下撤回同意或其他权利请求,请联系 support@jokersudoku.com。请说明请求类型,并提供大致提交时间、反馈主题及您持有的回执编号等有助于定位记录的信息,不要发送密码或身份证件。如需其他信息,我们会另行说明,以适度方式核实请求并按适用要求答复;确需为具体法律理由保留时,会说明相关限制。不提交反馈不影响数独,本版本不提供原生游戏存档同步。
 
-对于始终仅保存在设备上的记录,我们无法远程管理。卸载会清除本地游戏数据,但不会代为提交服务器删除申请。Meta 持有的信息也可通过其隐私渠道处理;联系 Meta 不代替就本应用服务联系 Joker Sudoku。
+对于仅保存在设备上的记录,我们无法远程管理或取回。卸载可清除本地游戏记录,但不会代为提交服务器删除申请。Meta 持有的信息也可通过其隐私渠道处理;联系 Meta 不代替就本应用控制的数据联系 Joker Sudoku。
 
 ## 6. 儿童隐私
 
@@ -76,7 +76,7 @@ Joker Sudoku 接收并保存第 1 节所述游戏存档信息。提供服务器
 
 ## 7. 本政策的变更
 
-功能或信息处理方式发生变化时,我们会更新政策并标明生效日期,包括变更存档数据或其用途、新增广告位或广告合作方。新增处理开始前,我们会说明其实际行为并取得所需权限或同意。重大变化将以适当方式通知;继续游戏或更新政策不会覆盖您在 iOS 中的跟踪选择,也不构成对未来信息处理的概括授权。用于广告跟踪的 ATT 授权本身不构成对其他游戏存档处理的同意。
+功能或信息处理方式改变时,我们会更新政策及生效日期,包括未来可能新增的服务器存档、广告位或广告合作方。新增处理开始前会说明实际行为并取得所需权限或同意。重大变化将以适当方式通知;继续游戏或更新政策不会覆盖 iOS 跟踪选择,也不构成对未来处理的概括授权。
 
 ## 8. 联系我们
 

+ 2 - 0
Vendor/FacebookSDK/UPSTREAM.md

@@ -7,3 +7,5 @@ Upstream commit: `80d0ee82f6370d1bace1431a80cb80575f98ee90`.
 Only FacebookCore and its Basics / AEM dependencies are included. Login, Share and Gaming are not included. The local Package.swift preserves the relevant upstream targets, resource manifests and linker settings. Framework contents and signatures have not been changed.
 
 This package is checked into the project so a clean Xcode build does not depend on a previously populated temporary SwiftPM checkout or a network clone. Upstream license is included in LICENSE.
+
+Verified on November 20, 2026: all three cached official release ZIPs matched the tagged Package.swift checksums; 1028 framework entries and all five Swift/resource files matched the tagged upstream archives. All nine framework-slice signatures verified against the original Meta signing identity. The application deployment target remains iOS 15.0.

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 4 - 0
jokersudoku-feedback.html


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 4 - 0
jokersudoku-survey.html


+ 66 - 0
jokersudoku.html

@@ -0,0 +1,66 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<meta name="referrer" content="no-referrer">
+<title>Privacy Policy · JokerSudoku</title>
+<style>
+:root{color-scheme:light;--ink:#203854;--muted:#64758a;--blue:#287de0;--line:#dde6f0}
+*{box-sizing:border-box}body{margin:0;background:#f1f6fc;color:var(--ink);font:16px/1.8 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
+header,main,footer{max-width:880px;margin:auto}header{padding:28px 24px 22px;display:flex;align-items:center;gap:12px;font-size:18px;font-weight:800}.mark{display:grid;place-items:center;width:40px;height:40px;border-radius:12px;background:var(--ink);color:#ffd777;font-size:26px}
+main{background:#fff;border:1px solid var(--line);border-radius:24px;padding:clamp(24px,5vw,56px);overflow-wrap:anywhere}h1{font-size:clamp(28px,5vw,38px);line-height:1.25;letter-spacing:-.8px;margin:0 0 20px}h2{font-size:23px;line-height:1.4;margin:38px 0 16px;padding-top:18px;border-top:1px solid var(--line)}h3{font-size:18px;line-height:1.5;margin:26px 0 12px}p{margin:0 0 18px}h1+p{font-size:14px;color:var(--muted)}a{color:var(--blue);text-underline-offset:3px}a:focus-visible{outline:3px solid #eeb735;outline-offset:4px}footer{text-align:center;font-size:13px;color:var(--muted);padding:24px}
+@media(max-width:600px){body{padding:0 12px}header{padding:22px 10px}main{border-radius:18px}h2{font-size:21px}}
+@media print{body{padding:0;background:#fff;font-size:11pt}header,footer{display:none}main{max-width:none;border:0;padding:0}h2,h3{break-after:avoid}p{orphans:3;widows:3}}
+</style>
+</head>
+<body>
+<header><span class="mark" aria-hidden="true">♛</span><span>JokerSudoku</span></header>
+<main>
+<h1>Joker Sudoku Privacy Policy</h1>
+<p>Effective date / last updated: November 24, 2026</p>
+<p>Joker Sudoku (&quot;we&quot;, &quot;us&quot;) operates the JokerSudoku puzzle game. This policy explains how the current public iPhone and iPad app handles information. Contact: support@jokersudoku.com. Reading this policy is not consent to advertising tracking; that permission is requested separately through iOS.</p>
+<p>Reading this policy, downloading the App, or continuing to play does not itself authorize advertising tracking or unrelated future processing. We request permissions and any required consent separately. Native Sudoku and local saving remain available offline.</p>
+<h2>1. Information We Collect</h2>
+<p>No online account is required to play the native Sudoku game. We do not require an account name, password, phone number, identity document, or email address for gameplay. The native game does not request contacts, microphone, camera, photo-library-wide access, or precise location permissions. If you choose to attach a screenshot to a feedback form, the browser or system picker lets you select the file to provide.</p>
+<h3>1.1 Game Progress and Preferences</h3>
+<p>On your device, we store game progress, entered numbers, notes, elapsed time, mistakes, hint usage, undo history, daily challenge records, scores, statistics, language, board theme, gameplay settings, and feedback drafts to provide local saves and personalization.</p>
+<p>In this version, game saves, completed puzzles, statistics, settings, and questionnaire completion status stay on your device. The app does not automatically upload or restore these records through the configuration service and does not create or send an anonymous player UUID for game-save synchronization. Offline Sudoku and local saving remain available. Reinstalling the app or changing devices does not provide server recovery of local progress.</p>
+<h3>1.2 Configuration and Technical Information</h3>
+<p>The app requests questionnaire and privacy-page addresses and questionnaire sampling settings using the app channel, selected language, device region setting, and time zone. The receiving service also receives your connection’s IP address and technical request information. Reading the region setting does not request GPS location. Returned addresses, sampling settings, and questionnaire visit/submission status are stored locally. Meta App ID and Client Token are packaged with the app and are not player account credentials; the app does not accept replacements from the configuration service. These configuration requests do not contain your saved puzzles, statistics, game preferences, feedback drafts, or an anonymous player UUID.</p>
+<h3>1.3 Customer Support</h3>
+<p>Native feedback drafts stay on the device unless you choose to share them using the system share sheet. Separately, the optional bug-report and suggestion webpage sends the text you enter and screenshots you select to Joker Sudoku only when you press Submit feedback. It also sends the channel, selected form language, submission time, and normal network request information. It does not automatically attach your game saves, settings, or a player UUID. The selected text and files may contain identifying information or embedded image metadata; remove personal or sensitive information before uploading. Screenshots are optional. If you email us, we receive your email address and the message and attachments you send to handle the inquiry. Do not send passwords, identity documents, or unnecessary sensitive information.</p>
+<h2>2. How We Use Your Information</h2>
+<p>We use local game records to operate Sudoku, save progress, and provide statistics and preferences on your device; configuration information to obtain app-service settings and questionnaires; submitted support text and images to investigate bugs, respond to requests, and improve the game; and authorized Meta information to measure app promotion and questionnaire responses. Information is also processed as necessary for specific troubleshooting, security, and legal obligations. Collection for one purpose is not authorization for unrelated uses; new purposes requiring consent will be explained and authorized before processing starts.</p>
+<h2>3. Third-Party Services</h2>
+<h3>3.1 Meta (Facebook) SDK and Tracking</h3>
+<p>The app includes Meta (Facebook) iOS SDK 18.1.1 for advertising attribution and app-event measurement. In this version our native integration initializes and enables Meta collection only after iOS App Tracking Transparency permission is authorized. Before authorization, or if permission is denied or restricted, the app does not initialize Meta collection or send events to Meta through this integration. Refusing tracking does not limit Sudoku, saving, or daily challenges. Events blocked for lack of permission are not replayed later by our integration.</p>
+<p>We use the current Meta integration to measure app promotion and prepare for a possible future advertising-supported business model. Preparation does not mean advertisements are currently displayed: this native Sudoku version has no ad placements or monetization ad SDK. Meta App Events is an advertising measurement component and does not itself provide an in-game advertising placement.</p>
+<p>With authorization, Meta may process advertising identifiers (including IDFA when available), SDK-generated identifiers, device and app information, app activation and other supported app events, network information including IP address, and SDK diagnostics to measure advertising effectiveness and improve advertising. Meta may combine this information with information from other apps or services for attribution and tracking. Its actual processing depends on permission, SDK behavior, and Meta&#x27;s applicable settings and policies. Meta may store identifiers, configuration, and event data locally and process transmitted data on its infrastructure, including outside your country or region.</p>
+<p>The current Sudoku game has no online registration, purchases, shopping cart, wishlist, in-app payments, or displayed advertisements. The optional questionnaire asks about willingness to see ads, donate, buy optional items, and try new gameplay. When you submit it and ATT allows tracking, this version sends a custom Meta event named survey_response for each answer, containing only a question number (question_id, 1–4) and willingness label (answer, willing or unwilling). These events do not include a price, currency, or payment information and are not reported as purchases, shopping actions, or registrations. Written questionnaire comments and a local submission record stay on the device and are not sent to Meta by this integration. Bug-report text and screenshots use the separate, user-initiated support submission described in Section 1.3. More about Meta’s practices and choices: <a href="https://www.facebook.com/privacy/policy/" target="_blank" rel="noopener noreferrer">Meta Privacy Policy</a>.</p>
+<p>If a later version introduces banner, interstitial, or rewarded advertisements, or adds an advertising or mediation partner, we will disclose the actual providers, data categories, purposes, sharing, local storage, retention information, and available choices before the new processing starts. We will update the policy and store privacy disclosures and request any permission or consent required for that processing. Tracking remains subject to ATT; declining tracking will not prevent the basic Sudoku game. This notice is not advance permission for unspecified partners, personalized advertising, additional collection, or a change of purpose.</p>
+<h3>3.2 Activity Webpages and Cookies</h3>
+<p>The native Sudoku game does not require browser cookies. You can open the questionnaire from Home; it may also be offered after you tap New Game, before difficulty selection, according to the configured sampling setting. You can close it without completing it and continue playing. A configuration response alone does not open a webpage. Questionnaire drafts may be stored in the website’s local storage. WebKit uses persistent website storage for cookies, cached resources, local storage, and website sessions. The website provider receives network requests; following privacy or feedback links opens the external browser and sends requests to the destination provider. Native bridge events remain subject to ATT. This permission does not authorize website scripts to track you independently; website processing must also follow applicable consent and disclosure requirements. The Meta SDK may keep its own configuration and event cache after authorization. Device backups may contain app data depending on your Apple backup settings.</p>
+<h3>3.3 Hosting and Other Disclosures</h3>
+<p>Joker Sudoku receives the configuration request information and the optional feedback submissions described above. Hosting, storage, and network-delivery providers may process information needed to provide those services on our behalf. We require providers acting on our behalf to use it for the agreed purposes and provide the same or equivalent protection described in this policy and required by applicable privacy requirements. We do not sell your feedback or publish it to other players. After your tracking authorization, Meta receives the information described in Section 3.1. Disclosures required by law are limited to the information and purposes required by applicable obligations. Service infrastructure may be outside your country or region; applicable cross-border processing requirements must be met.</p>
+<p>The current native app does not integrate Game Center or in-app purchasing. We do not describe these as active services or treat a possible future integration as permission for new processing.</p>
+<h2>4. Data Storage and Security</h2>
+<p>Local game records remain until removed from the device. Deleting the app removes its local game data; deleting a backup is managed separately in Apple’s backup settings. The app uses its packaged Meta configuration, no longer reads or stores remotely supplied credential pairs, and removes legacy app-specific credential cache entries during upgrade. Meta may maintain its own configuration and event storage as explained in Section 3. Uninstalling does not erase information already received by a service provider.</p>
+<p>This version does not send game-save records to our servers. Removing synchronization does not automatically erase records that an earlier version may already have uploaded. If you used an earlier version and want to ask about or delete those records, contact support@jokersudoku.com. Uninstalling also does not delete feedback already submitted or information already received by Meta.</p>
+<p>Support correspondence is retained as needed to handle the request and associated follow-up. Technical records are retained for their service, troubleshooting, or security purpose. When no longer needed, we delete or de-identify them, unless a specific legal obligation or legal/security matter requires limited further retention.</p>
+<p>We use iOS application storage and system protections and limit access to server records to what is needed for the stated purposes. HTTP requests without TLS do not provide authenticated, encrypted transport; application-level encryption is not a substitute for HTTPS. The configured platform endpoint and public policy address currently use HTTP. We do not describe all app network traffic as HTTPS or promise absolute security. Please do not send passwords, identity documents, or unnecessary sensitive information through support or activity forms. Meta&#x27;s retention and privacy choices are described in its own policy and do not replace our obligations for data we control.</p>
+<h2>5. Your Rights and Choices</h2>
+<p>You can change language and game settings in the app. Manage tracking in iOS Settings &gt; Privacy &amp; Security &gt; Tracking, or through Me &gt; Privacy Preferences when that screen is available. Revoking permission stops subsequent collection through our integration when the app observes the new status; it does not automatically erase information already received by Meta. You can play offline, delete the app&#x27;s local data by uninstalling, and manage backups separately.</p>
+<p>To ask about access, correction, deletion, withdrawal of consent where applicable, or other rights concerning information we hold, contact support@jokersudoku.com. Describe the request and provide information that helps us locate it, such as the approximate submission time, report subject, and any receipt reference available to you. Do not send passwords or identity documents. We will explain any additional information needed, verify requests proportionately, and respond under applicable requirements. If information must be retained for a specific legal reason, we will explain the relevant limits. You can decline to submit feedback without affecting Sudoku. Native game-save synchronization is not offered in this version.</p>
+<p>For records kept only on your device, we cannot manage or retrieve them remotely. Uninstalling clears local game records, but does not submit a server deletion request. You can also use Meta’s privacy channels for information held by Meta; contacting Meta does not replace contacting Joker Sudoku about data we control.</p>
+<h2>6. Children’s Privacy</h2>
+<p>The native Sudoku game is a general-audience logic puzzle without violence, gambling, user chat, or public user-generated content. An activity webpage is separate content and must be considered when assessing the full app&#x27;s age suitability. A store content age rating does not authorize tracking or replace legal requirements for children. Parents and guardians should manage device permissions for children. The app is not presented as a dedicated children&#x27;s service and does not intentionally request children&#x27;s account or contact details. If you believe a child has sent us personal information, contact us so we can review and address it under applicable requirements.</p>
+<h2>7. Changes to This Privacy Policy</h2>
+<p>We update this policy and its effective date when functionality or information processing changes, including any future server saving, new advertising placements, or advertising partners. We explain the actual new processing and obtain required permissions or consent before it starts. Significant changes will be communicated appropriately. Continuing to play, or updating this policy, does not override your iOS tracking choice or provide blanket consent to future processing.</p>
+<h2>8. Contact Us</h2>
+<p>Operator: Joker Sudoku</p>
+<p>Email: support@jokersudoku.com</p>
+</main>
+<footer>Joker Sudoku · <a href="mailto:support@jokersudoku.com">support@jokersudoku.com</a></footer>
+</body>
+</html>

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels