package eu.friedcutlet.yokan.services.webview import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.logging.AppLogger import kotlin.coroutines.resume import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.cinterop.cValue import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import platform.Foundation.NSError import platform.Foundation.NSHTTPCookie import platform.Foundation.NSOperatingSystemVersion import platform.Foundation.NSProcessInfo import platform.Foundation.NSUUID import platform.Foundation.timeIntervalSinceNow import platform.WebKit.WKWebsiteDataStore @OptIn(ExperimentalForeignApi::class) private val persistentProfileStores = NSProcessInfo.processInfo.isOperatingSystemAtLeastVersion( cValue { majorVersion = 17; minorVersion = 0; patchVersion = 0 }, ) // ponytail: iOS 15/16 have no identified stores, so extras browse in a per-process ephemeral store (logins last until relaunch). private val ephemeralStores = mutableMapOf() /** The UUID naming [id]'s persistent WebKit store: its 32 hex digits in 8-4-4-4-12 form. */ internal fun profileBrowserStoreUuid(id: ProfileId): String { require(id != ProfileId.Default) val hex = id.value.removePrefix("p_") return listOf(0..7, 8..11, 12..15, 16..19, 20..31).joinToString("-") { hex.substring(it) } } /** [id]'s WebKit data store; Default keeps the app-wide store. Main thread only. */ internal fun profileDataStore(id: ProfileId): WKWebsiteDataStore = when { id == ProfileId.Default -> WKWebsiteDataStore.defaultDataStore() persistentProfileStores -> WKWebsiteDataStore.dataStoreForIdentifier(NSUUID(uUIDString = profileBrowserStoreUuid(id))) else -> ephemeralStores.getOrPut(id) { WKWebsiteDataStore.nonPersistentDataStore() } } /** Removes a deleted extra profile's WebKit store. Failures are logged: profile deletion must still finish. */ internal suspend fun deleteProfileDataStore(id: ProfileId): Unit = withContext(Dispatchers.Main) { require(id != ProfileId.Default) ephemeralStores.remove(id) if (!persistentProfileStores) return@withContext val uuid = NSUUID(uUIDString = profileBrowserStoreUuid(id)) val exists = suspendCancellableCoroutine { cont -> WKWebsiteDataStore.fetchAllDataStoreIdentifiers { ids -> cont.resume(ids.orEmpty().any { it == uuid }) } } if (!exists) return@withContext val error = suspendCancellableCoroutine { cont -> WKWebsiteDataStore.removeDataStoreForIdentifier(uuid) { error -> cont.resume(error) } } if (error != null) AppLogger.warn("[profiles] Could not remove WebKit store for ${id.value}: ${error.localizedDescription}") } /** Every cookie in this store; null when WebKit refuses the read. */ internal suspend fun WKWebsiteDataStore.allCookies(): List? = withContext(Dispatchers.Main) { suspendCancellableCoroutine?> { cont -> runCatching { httpCookieStore.getAllCookies { array -> // NSArray erases to List<*> at the bridge; keep only real cookies. if (cont.isActive) cont.resume(array.orEmpty().mapNotNull { it as? NSHTTPCookie }) } }.onFailure { if (cont.isActive) cont.resume(null) } } } /** * RFC 6265-style host match: an exact-host cookie matches when the (lowercased) domain equals [host]; * a leading-dot (domain) cookie also matches any subdomain of it. */ internal fun NSHTTPCookie.matchesHost(host: String): Boolean { val rawDomain = domain.lowercase() val cookieDomain = rawDomain.removePrefix(".") if (cookieDomain.isEmpty()) return false return host == cookieDomain || (rawDomain.startsWith(".") && host.endsWith(".$cookieDomain")) } internal fun NSHTTPCookie.toSetCookieHeader(): String = buildList { add("$name=$value") if (domain.startsWith(".")) add("Domain=$domain") add("Path=${path.ifBlank { "/" }}") expiresDate?.timeIntervalSinceNow?.let { remaining -> add("Max-Age=${remaining.toLong().coerceAtLeast(0L)}") } if (isSecure()) add("Secure") if (isHTTPOnly()) add("HttpOnly") }.joinToString("; ")