--- a/TalerWallet1/Quickjs/QuickDataTask.swift 2026-11-26 18:21:11.765079709 +0100 +++ b/TalerWallet1/Quickjs/QuickDataTask.swift 2026-11-26 18:21:11.773079719 +0100 @@ -81,6 +81,14 @@ } // MARK: - final class QuickDataTask: NSObject, @unchecked Sendable { + /// The largest answer that is handed on to wallet-core. Without a limit an answer of any + /// size is held in memory several times over -- by URLSession, by the copy made for the + /// JS thread, by the JS value made from that -- and wallet-core is busy with it for + /// seconds: one gigabyte was measured as 3.4 GB resident. + static let maxResponseBytes: Int64 = 64 * 1024 * 1024 + private var sizeObservation: NSKeyValueObservation? + private var isTooLarge = false + let urlSession: URLSession let request: URLRequest let requestID: Int32 @@ -134,6 +142,18 @@ url: url) } + // Stop a transfer that announces, or has already brought, more than the limit. + sizeObservation = task.observe(\.countOfBytesReceived) { [weak self] task, _ in + guard let self else { return } + if task.countOfBytesReceived > QuickDataTask.maxResponseBytes + || task.countOfBytesExpectedToReceive > QuickDataTask.maxResponseBytes { + self.state.lock() + self.isTooLarge = true + self.state.unlock() + task.cancel() + } + } + state.lock() guard !isFinished else { state.unlock() @@ -195,6 +215,17 @@ } defer { endCallback() } + state.lock() + let tooLarge = isTooLarge + state.unlock() + if tooLarge { + let megabytes = QuickDataTask.maxResponseBytes >> 20 + deliver(error: NSError(domain: NSURLErrorDomain, + code: NSURLErrorDataLengthExceedsMaximum, + userInfo: [NSLocalizedDescriptionKey: "Response larger than \(megabytes) MB"])) + return + } + if let response = response as? HTTPURLResponse { deliver(response: response, data: data ?? Data(), method: method, url: url) } else {