package eu.friedcutlet.yokan.services.backup import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi import kotlin.js.ExperimentalWasmJsInterop import kotlin.js.JsAny import kotlin.js.Promise import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException actual fun createPlatformBackupCompression(): BackupCompression = WasmBackupCompression /** * The browser's CompressionStream API is async-only and this contract is * synchronous, so web backups export uncompressed — other platforms sniff * the gzip magic bytes and treat non-gzipped payloads as raw. Importing a * gzipped backup on the web fails with a clear error instead of corrupting. */ private object WasmBackupCompression : BackupCompression { override fun compress(data: ByteArray, level: Int): ByteArray = data override fun decompress(data: ByteArray): ByteArray { if (looksGzipped(data)) { throw UnsupportedOperationException( "Gzipped backups cannot be imported in the browser; export an uncompressed backup instead.", ) } return data } override suspend fun unzipFirstEntryAsync(data: ByteArray): ByteArray? = parseZip(data).firstOrNull { !it.name.endsWith('/') }?.let { readEntry(data, it, 0L) } override suspend fun unzipEntriesAsync(data: ByteArray): Map = buildMap { var totalOutput = 0L parseZip(data).forEach { entry -> if (!entry.name.endsWith('/')) { val decoded = readEntry(data, entry, totalOutput) totalOutput += decoded.size.toLong() put(entry.name, decoded) } } } private suspend fun readEntry(data: ByteArray, entry: ZipEntry, totalOutput: Long): ByteArray { requireZip(entry.uncompressedSize <= MaxArchiveOutputBytes, "declared entry size exceeds the 64 MiB browser limit") requireZip(totalOutput <= MaxArchiveOutputBytes - entry.uncompressedSize, "archive output exceeds the 64 MiB browser limit") val localOffset = entry.localHeaderOffset requireZip(localOffset < entry.centralDirectoryOffset, "local file header overlaps the central directory") requireRange(data, localOffset, 30L, "local file header is truncated") requireZip(u32(data, localOffset.toInt()) == LocalFileHeader, "local file header signature is invalid") val local = localOffset.toInt() val localVersionNeeded = u16(data, local + 4) val localFlags = u16(data, local + 6) val localMethod = u16(data, local + 8) val localCrc = u32(data, local + 14) val localCompressedSize = u32(data, local + 18) val localUncompressedSize = u32(data, local + 22) val nameLength = u16(data, local + 26) val extraLength = u16(data, local + 28) requireUnsupported(localVersionNeeded <= 20L, "ZIP features newer than standard stored/deflate entries are not supported") requireZip(localFlags == entry.flags, "local and central flags differ for ${entry.name}") requireZip(localMethod == entry.method, "local and central methods differ for ${entry.name}") requireZip(localCrc != Zip32Sentinel && localCompressedSize != Zip32Sentinel && localUncompressedSize != Zip32Sentinel, "ZIP64 local entries are not supported in the browser") val contentStart = localOffset + 30L + nameLength + extraLength val contentEnd = contentStart + entry.compressedSize requireZip(contentEnd <= entry.centralDirectoryOffset, "entry data overlaps the central directory") requireRange(data, contentStart, entry.compressedSize, "entry data is truncated") val localNameEnd = localOffset + 30L + nameLength requireRange(data, localOffset + 30L, nameLength, "local entry name is truncated") val localName = data.copyOfRange((localOffset + 30L).toInt(), localNameEnd.toInt()).decodeToString() requireZip(localName == entry.name, "local and central names differ") requireZip( localCrc == entry.crc32 && localCompressedSize == entry.compressedSize && localUncompressedSize == entry.uncompressedSize, "local and central metadata differ for ${entry.name}", ) val compressed = data.copyOfRange(contentStart.toInt(), contentEnd.toInt()) return when (entry.method) { Stored -> { requireZip(entry.compressedSize == entry.uncompressedSize, "stored entry sizes differ for ${entry.name}") compressed } Deflated -> inflateRaw(compressed, entry.name, entry.uncompressedSize.toInt()) else -> error("Unsupported ZIP backup: compression method ${entry.method} is not supported for ${entry.name}") }.also { decoded -> requireZip(decoded.size.toLong() == entry.uncompressedSize, "decoded size differs from central metadata for ${entry.name}") requireZip(crc32(decoded) == entry.crc32, "CRC-32 mismatch for ${entry.name}") } } } private data class ZipEntry( val name: String, val flags: Long, val method: Long, val crc32: Long, val compressedSize: Long, val uncompressedSize: Long, val localHeaderOffset: Long, val centralDirectoryOffset: Long, ) private const val EndOfCentralDirectory = 0x06054B50L private const val CentralDirectoryHeader = 0x02014B50L private const val LocalFileHeader = 0x04034B50L private const val Stored = 0L private const val Deflated = 8L private const val Zip32Sentinel = 0xFFFF_FFFFL private const val Zip16Sentinel = 0xFFFFL private const val Utf8Flag = 0x800L private const val SupportedFlags = Utf8Flag private const val MaxArchiveOutputBytes = 64L * 1024L * 1024L private fun parseZip(data: ByteArray): List { requireZip(data.size >= 22, "end-of-central-directory record is missing") val eocd = (data.size - 22 downTo (data.size - 65_557).coerceAtLeast(0)) .firstOrNull { candidate -> u32(data, candidate) == EndOfCentralDirectory && candidate.toLong() + 22L + u16(data, candidate + 20) == data.size.toLong() } ?: error("Invalid ZIP backup: end-of-central-directory record is missing") val entryCount = u16(data, eocd + 10) val centralSize = u32(data, eocd + 12) val centralOffset = u32(data, eocd + 16) val diskNumber = u16(data, eocd + 4) val centralDisk = u16(data, eocd + 6) val entriesOnDisk = u16(data, eocd + 8) requireUnsupported(diskNumber == 0L && centralDisk == 0L && entriesOnDisk == entryCount, "multi-disk ZIP archives are not supported in the browser") requireUnsupported( entryCount != Zip16Sentinel && centralSize != Zip32Sentinel && centralOffset != Zip32Sentinel, "ZIP64 archives are not supported in the browser", ) val centralEnd = centralOffset + centralSize requireZip(entryCount <= centralSize / 46L, "central directory entry count is invalid") requireZip(centralOffset <= data.size.toLong() && centralSize <= data.size.toLong() - centralOffset && centralEnd <= eocd.toLong(), "central directory is truncated") val entries = ArrayList(entryCount.toInt()) var cursor = centralOffset repeat(entryCount.toInt()) { requireRange(data, cursor, 46L, "central directory entry is truncated") requireZip(u32(data, cursor.toInt()) == CentralDirectoryHeader, "central directory entry is invalid") val versionNeeded = u16(data, cursor.toInt() + 6) val flags = u16(data, cursor.toInt() + 8) val method = u16(data, cursor.toInt() + 10) val crc32 = u32(data, cursor.toInt() + 16) val compressedSize = u32(data, cursor.toInt() + 20) val uncompressedSize = u32(data, cursor.toInt() + 24) val nameLength = u16(data, cursor.toInt() + 28) val extraLength = u16(data, cursor.toInt() + 30) val commentLength = u16(data, cursor.toInt() + 32) val diskStart = u16(data, cursor.toInt() + 34) val localHeaderOffset = u32(data, cursor.toInt() + 42) requireUnsupported(versionNeeded <= 20L, "ZIP features newer than standard stored/deflate entries are not supported") requireUnsupported(flags and 1L == 0L, "encrypted ZIP entries are not supported in the browser") requireUnsupported(flags and SupportedFlags.inv() == 0L, "unsupported ZIP entry flags") requireUnsupported( diskStart == 0L && compressedSize != Zip32Sentinel && uncompressedSize != Zip32Sentinel && localHeaderOffset != Zip32Sentinel, "ZIP64 or multi-disk entries are not supported in the browser", ) requireUnsupported(method == Stored || method == Deflated, "compression method $method is not supported in the browser") requireZip(uncompressedSize <= MaxArchiveOutputBytes, "declared entry size exceeds the 64 MiB browser limit") val nameStart = cursor + 46L val next = nameStart + nameLength + extraLength + commentLength requireZip(next >= nameStart && next <= centralEnd, "central directory entry is truncated") val name = data.copyOfRange(nameStart.toInt(), (nameStart + nameLength).toInt()).decodeToString() requireZip(name.isNotEmpty() && '\u0000' !in name, "ZIP entry name is invalid") entries += ZipEntry(name, flags, method, crc32, compressedSize, uncompressedSize, localHeaderOffset, centralOffset) cursor = next } requireZip(cursor == centralEnd, "central directory size does not match its entries") return entries } private fun u16(data: ByteArray, offset: Int): Long = (data[offset].toLong() and 0xFFL) or ((data[offset + 1].toLong() and 0xFFL) shl 8) private fun u32(data: ByteArray, offset: Int): Long = (data[offset].toLong() and 0xFFL) or ((data[offset + 1].toLong() and 0xFFL) shl 8) or ((data[offset + 2].toLong() and 0xFFL) shl 16) or ((data[offset + 3].toLong() and 0xFFL) shl 24) private fun requireZip(condition: Boolean, message: String) { if (!condition) error("Invalid ZIP backup: $message") } private fun requireUnsupported(condition: Boolean, message: String) { if (!condition) error("Unsupported ZIP backup: $message") } private fun requireRange(data: ByteArray, offset: Long, length: Long, message: String) { requireZip(offset >= 0L && length >= 0L && offset <= data.size.toLong() && length <= data.size.toLong() - offset, message) } private fun crc32(data: ByteArray): Long { var crc = 0xFFFF_FFFFL data.forEach { byte -> crc = (crc ushr 8) xor Crc32Table[((crc xor (byte.toLong() and 0xFFL)) and 0xFFL).toInt()] } return crc xor 0xFFFF_FFFFL } private val Crc32Table = LongArray(256) { index -> var value = index.toLong() repeat(8) { value = if (value and 1L != 0L) (value ushr 1) xor 0xEDB88320L else value ushr 1 } value } @OptIn(ExperimentalEncodingApi::class, ExperimentalWasmJsInterop::class) private suspend fun inflateRaw(data: ByteArray, entryName: String, maxOutputBytes: Int): ByteArray { return try { suspendCancellableCoroutine { continuation -> inflateRawJs(Base64.encode(data), maxOutputBytes).then( onFulfilled = { value -> if (value == null) { continuation.resumeWithException(IllegalStateException("DecompressionStream returned no data")) } else { runCatching { Base64.decode(jsString(value)) } .fold(continuation::resume, continuation::resumeWithException) } null }, onRejected = { error -> continuation.resumeWithException(IllegalStateException(jsString(error))) null }, ) } } catch (error: Throwable) { throw IllegalArgumentException( "Browser could not deflate ZIP entry $entryName: ${error.message.orEmpty().ifBlank { "DecompressionStream('deflate-raw') is unavailable or the entry is corrupt" }}", error, ) } } @OptIn(ExperimentalWasmJsInterop::class) private fun inflateRawJs(base64: String, maxOutputBytes: Int): Promise = js( """ (async () => { const binary = atob(base64); const input = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) input[i] = binary.charCodeAt(i); const stream = new Blob([input]).stream().pipeThrough(new DecompressionStream('deflate-raw')); const reader = stream.getReader(); const chunks = []; let outputLength = 0; while (true) { const result = await reader.read(); if (result.done) break; outputLength += result.value.byteLength; if (outputLength > maxOutputBytes) { await reader.cancel(); throw new Error('decompressed ZIP entry exceeds its declared or browser output limit'); } chunks.push(result.value); } const output = new Uint8Array(outputLength); let outputOffset = 0; for (const chunk of chunks) { output.set(chunk, outputOffset); outputOffset += chunk.byteLength; } let binaryOutput = ''; for (let i = 0; i < output.length; i += 0x8000) { binaryOutput += String.fromCharCode(...output.subarray(i, i + 0x8000)); } return btoa(binaryOutput); })() """, ) @OptIn(ExperimentalWasmJsInterop::class) private fun jsString(value: JsAny): String = js("String(value)")