@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class) package eu.friedcutlet.yokan.services.http import eu.friedcutlet.yokan.domain.ProfileId import kotlinx.coroutines.test.runTest import kotlin.test.* class IsolatedBrowserHttpTest { @Test fun anonymousFetchRetainsExplicitAuthorizationAndBinaryResponse() = runTest { installFetchProbe() val client = createPlatformHttpService(Extra) try { val response = client.request(HttpRequest("https://example.test/data", headers = mapOf("Authorization" to "Bearer own-token"))) assertEquals(200, response.statusCode) assertContentEquals(byteArrayOf(65, 0, 66), response.bodyBytes) assertEquals("omit:no-store:Bearer own-token", capturedOptions()) } finally { client.closeAndJoin(); removeFetchProbe() } } @Test fun cookieAuthenticationIsRefusedBeforeCallingSharedBrowserTransport() = runTest { installFetchProbe() val client = createPlatformHttpService(Extra) try { assertFailsWith { client.request(HttpRequest("https://example.test/data", headers = mapOf("Cookie" to "owner=extra"))) } assertEquals(0, capturedCalls()) } finally { client.closeAndJoin(); removeFetchProbe() } } companion object { private val Extra = ProfileId("p_${"e".repeat(32)}") } } private fun capturedOptions(): String = js("globalThis.__yokanFetchProbe.options") private fun capturedCalls(): Int = js("globalThis.__yokanFetchProbe.calls") private fun installFetchProbe(): Unit = js( """ (() => { globalThis.__yokanFetchProbe = { original: globalThis.fetch, calls: 0, options: '' }; globalThis.fetch = async (url, init) => { const probe = globalThis.__yokanFetchProbe; probe.calls++; probe.options = init.credentials + ':' + init.cache + ':' + init.headers.Authorization; return new Response(new Uint8Array([65, 0, 66]), {status: 200}); }; })() """, ) private fun removeFetchProbe(): Unit = js( """ (() => { globalThis.fetch = globalThis.__yokanFetchProbe.original; delete globalThis.__yokanFetchProbe; })() """, )