IosProfileDataStore.kt
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/webview/IosProfileDataStore.kt
1package eu.friedcutlet.yokan.services.webview23import eu.friedcutlet.yokan.domain.ProfileId4import eu.friedcutlet.yokan.services.logging.AppLogger5import kotlin.coroutines.resume6import kotlinx.cinterop.ExperimentalForeignApi7import kotlinx.cinterop.cValue8import kotlinx.coroutines.Dispatchers9import kotlinx.coroutines.suspendCancellableCoroutine10import kotlinx.coroutines.withContext11import platform.Foundation.NSError12import platform.Foundation.NSHTTPCookie13import platform.Foundation.NSOperatingSystemVersion14import platform.Foundation.NSProcessInfo15import platform.Foundation.NSUUID16import platform.Foundation.timeIntervalSinceNow17import platform.WebKit.WKWebsiteDataStore1819@OptIn(ExperimentalForeignApi::class)20private val persistentProfileStores = NSProcessInfo.processInfo.isOperatingSystemAtLeastVersion(21 cValue<NSOperatingSystemVersion> { majorVersion = 17; minorVersion = 0; patchVersion = 0 },22)2324// ponytail: iOS 15/16 have no identified stores, so extras browse in a per-process ephemeral store (logins last until relaunch).25private val ephemeralStores = mutableMapOf<ProfileId, WKWebsiteDataStore>()2627/** The UUID naming [id]'s persistent WebKit store: its 32 hex digits in 8-4-4-4-12 form. */28internal fun profileBrowserStoreUuid(id: ProfileId): String {29 require(id != ProfileId.Default)30 val hex = id.value.removePrefix("p_")31 return listOf(0..7, 8..11, 12..15, 16..19, 20..31).joinToString("-") { hex.substring(it) }32}3334/** [id]'s WebKit data store; Default keeps the app-wide store. Main thread only. */35internal fun profileDataStore(id: ProfileId): WKWebsiteDataStore = when {36 id == ProfileId.Default -> WKWebsiteDataStore.defaultDataStore()37 persistentProfileStores -> WKWebsiteDataStore.dataStoreForIdentifier(NSUUID(uUIDString = profileBrowserStoreUuid(id)))38 else -> ephemeralStores.getOrPut(id) { WKWebsiteDataStore.nonPersistentDataStore() }39}4041/** Removes a deleted extra profile's WebKit store. Failures are logged: profile deletion must still finish. */42internal suspend fun deleteProfileDataStore(id: ProfileId): Unit = withContext(Dispatchers.Main) {43 require(id != ProfileId.Default)44 ephemeralStores.remove(id)45 if (!persistentProfileStores) return@withContext46 val uuid = NSUUID(uUIDString = profileBrowserStoreUuid(id))47 val exists = suspendCancellableCoroutine<Boolean> { cont ->48 WKWebsiteDataStore.fetchAllDataStoreIdentifiers { ids -> cont.resume(ids.orEmpty().any { it == uuid }) }49 }50 if (!exists) return@withContext51 val error = suspendCancellableCoroutine<NSError?> { cont ->52 WKWebsiteDataStore.removeDataStoreForIdentifier(uuid) { error -> cont.resume(error) }53 }54 if (error != null) AppLogger.warn("[profiles] Could not remove WebKit store for ${id.value}: ${error.localizedDescription}")55}5657/** Every cookie in this store; null when WebKit refuses the read. */58internal suspend fun WKWebsiteDataStore.allCookies(): List<NSHTTPCookie>? = withContext(Dispatchers.Main) {59 suspendCancellableCoroutine<List<NSHTTPCookie>?> { cont ->60 runCatching {61 httpCookieStore.getAllCookies { array ->62 // NSArray<NSHTTPCookie> erases to List<*> at the bridge; keep only real cookies.63 if (cont.isActive) cont.resume(array.orEmpty().mapNotNull { it as? NSHTTPCookie })64 }65 }.onFailure { if (cont.isActive) cont.resume(null) }66 }67}6869/**70 * RFC 6265-style host match: an exact-host cookie matches when the (lowercased) domain equals [host];71 * a leading-dot (domain) cookie also matches any subdomain of it.72 */73internal fun NSHTTPCookie.matchesHost(host: String): Boolean {74 val rawDomain = domain.lowercase()75 val cookieDomain = rawDomain.removePrefix(".")76 if (cookieDomain.isEmpty()) return false77 return host == cookieDomain || (rawDomain.startsWith(".") && host.endsWith(".$cookieDomain"))78}7980internal fun NSHTTPCookie.toSetCookieHeader(): String = buildList {81 add("$name=$value")82 if (domain.startsWith(".")) add("Domain=$domain")83 add("Path=${path.ifBlank { "/" }}")84 expiresDate?.timeIntervalSinceNow?.let { remaining -> add("Max-Age=${remaining.toLong().coerceAtLeast(0L)}") }85 if (isSecure()) add("Secure")86 if (isHTTPOnly()) add("HttpOnly")87}.joinToString("; ")88