diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml index 00cba46..37d64c0 100644 --- a/.github/workflows/ios.yml +++ b/.github/workflows/ios.yml @@ -12,7 +12,7 @@ permissions: env: # Keep simulator verification and the signing build on the same package commit. - MUDMOUTH_REV: 65686d24858822627f674d8b9a22aaaa3b026812 + MUDMOUTH_REV: 72710a0910121889c76167396d4827d819bb27ef concurrency: # Every develop push must reach the deployment queue. PR runs still supersede diff --git a/.github/workflows/testflight.yaml b/.github/workflows/testflight.yaml index 5fff27f..8ab832e 100644 --- a/.github/workflows/testflight.yaml +++ b/.github/workflows/testflight.yaml @@ -81,7 +81,7 @@ jobs: - uses: actions/checkout@v5 with: repository: qtmleap/Mudmouth - ref: 65686d24858822627f674d8b9a22aaaa3b026812 + ref: 72710a0910121889c76167396d4827d819bb27ef path: Mudmouth persist-credentials: false - name: Verify the Xcode toolchain diff --git a/Interceptor/Automation/AutomationSharedConfiguration.swift b/Interceptor/Automation/AutomationSharedConfiguration.swift index da43da1..bf6fa9e 100644 --- a/Interceptor/Automation/AutomationSharedConfiguration.swift +++ b/Interceptor/Automation/AutomationSharedConfiguration.swift @@ -4,7 +4,7 @@ import Foundation enum AutomationSharedConfiguration { static let appGroup = "group.jp.qleap.intrcptr" - static func activationURL() -> URL? { + private static func sharedBaseURL() -> URL? { guard var base = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else { return nil } #if DEBUG if let name = ProcessInfo.processInfo.environment["INTERCEPTOR_TEST_AUTOMATION_STORE"], @@ -14,6 +14,17 @@ enum AutomationSharedConfiguration { base.append(path: name, directoryHint: .isDirectory) } #endif - return base.appending(path: "Interceptor/Automation/active.json") + return base + } + static func activationURL() -> URL? { + sharedBaseURL()?.appending(path: "Interceptor/Automation/active.json") + } + + static func pluginFilesURL() -> URL? { + sharedBaseURL()?.appending(path: "Library/Application Support/Interceptor/PluginFiles", directoryHint: .isDirectory) + } + + static func pluginFileRecordsURL() -> URL? { + sharedBaseURL()?.appending(path: "Library/Application Support/Interceptor/PluginFileRecords", directoryHint: .isDirectory) } } diff --git a/Interceptor/Automation/HTTPPluginProcessor.swift b/Interceptor/Automation/HTTPPluginProcessor.swift index 012a322..e0972b3 100644 --- a/Interceptor/Automation/HTTPPluginProcessor.swift +++ b/Interceptor/Automation/HTTPPluginProcessor.swift @@ -17,6 +17,7 @@ final class HTTPPluginProcessor: HTTPPluginProcessing, Sendable { private let outboundTransport: any HTTPPluginOutboundTransport private let fetchExecutor = JavaScriptFetchExecutor() private let fetchDispatcher: HTTPPluginFetchDispatcher + private let fileStore: PluginFileStore? private static let bodyLimit = 24 * 1024 private struct PhaseResult { @@ -28,6 +29,7 @@ final class HTTPPluginProcessor: HTTPPluginProcessing, Sendable { private struct DeferredRun: Sendable { let manifest: PluginManifest + let revisionID: String let packageBytes: Data let hook: JavaScriptHook let event: Data @@ -38,12 +40,14 @@ final class HTTPPluginProcessor: HTTPPluginProcessing, Sendable { hasCaptureConsent: @escaping @Sendable () -> Bool = { CaptureAuthorization.isGranted }, outboundTransport: any HTTPPluginOutboundTransport = HTTPPluginDirectTransport(), outboundObserver: HTTPPluginOutboundDispatcher.Observer? = nil, + fileStore: PluginFileStore? = nil, fetchObserver: HTTPPluginFetchDispatcher.Observer? = nil) { self.store = store self.snapshot = snapshot self.hasCaptureConsent = hasCaptureConsent self.outboundTransport = outboundTransport + self.fileStore = fileStore ?? AutomationSharedConfiguration.pluginFileRecordsURL().map { PluginFileStore(directoryURL: $0) } outbound = HTTPPluginOutboundDispatcher(transport: outboundTransport, observer: outboundObserver) fetchDispatcher = HTTPPluginFetchDispatcher(observer: fetchObserver) } @@ -97,7 +101,9 @@ final class HTTPPluginProcessor: HTTPPluginProcessing, Sendable { } let output = try await withTaskCancellationHandler { try await executor.runV2(packageJSON: run.packageBytes, hook: run.hook, eventJSON: run.event, - configJSON: run.config) + configJSON: run.config, createFile: { [self] destination, contents in + try await createFile(destination: destination, contents: contents, run: run) + }) { request in try await Self.fetch(request, via: transport, isAuthorized: authorization) } @@ -114,6 +120,23 @@ final class HTTPPluginProcessor: HTTPPluginProcessing, Sendable { } } + /// Prepare outside the activation lock; only final publication holds the exact grant fence. + private func createFile(destination: PluginFileDestination, contents: Data, run: DeferredRun) async throws { + try Task.checkCancellation() + guard let fileStore, run.manifest.writeFiles, await isAuthorized(), + let approved = snapshot.revisions.first(where: { $0.revisionID == run.revisionID }), + approved.package.bytes == run.packageBytes else { throw Failure.revoked } + let prepared = try fileStore.prepare(revisionID: run.revisionID, package: approved.package, destination: destination, contents: contents) + try Task.checkCancellation() + try await store.withCurrentActivation(admitted: snapshot, revisionID: run.revisionID) { [self] current in + guard current.package.bytes == run.packageBytes else { throw Failure.revoked } + try prepared.commit { + try Task.checkCancellation() + guard hasCaptureConsent(), outbound.isActive, fetchDispatcher.isActive else { throw Failure.revoked } + } + } + } + /// Maps a validated JS fetch onto the direct transport. Policy (public host, 443, headers, JSON body) is /// enforced by `HTTPPluginOutboundRequest.isValid` and the transport itself. private static func fetch(_ request: JavaScriptFetchRequest, via transport: any HTTPPluginOutboundTransport, @@ -192,7 +215,7 @@ final class HTTPPluginProcessor: HTTPPluginProcessing, Sendable { output = try await executor.runV2(packageJSON: package.bytes, hook: hook, eventJSON: eventBytes, configJSON: config, detectAsync: phase == .responseLeave) } catch is JavaScriptAsyncRequired { - deferred.append(DeferredRun(manifest: manifest, packageBytes: package.bytes, hook: hook, + deferred.append(DeferredRun(manifest: manifest, revisionID: approved.revisionID, packageBytes: package.bytes, hook: hook, event: eventBytes, config: config)) continue } diff --git a/Interceptor/Automation/PluginFileDestinationController.swift b/Interceptor/Automation/PluginFileDestinationController.swift new file mode 100644 index 0000000..45a9fc9 --- /dev/null +++ b/Interceptor/Automation/PluginFileDestinationController.swift @@ -0,0 +1,195 @@ +import AutomationCore +import CryptoKit +import Mudmouth +import SwiftUI +import UniformTypeIdentifiers + +/// UI-only folder authority. The tunnel can enqueue file records, but cannot obtain or use a bookmark. +@MainActor +final class PluginFileDestinationController: ObservableObject { + struct FolderRequest: Identifiable { + let family: String + let prefix: String + var id: String { family + "\n" + prefix } + } + @Published var folderRequest: FolderRequest? + @Published var showError = false + private var presentedRequest: String? + private var isActive = false + private var canPrompt = true + private var synchronizing = false + private var delivered: [String: String] = [:] + private var failures: [String: (attempt: Int, after: Date)] = [:] + private var reportedFailures = Set() + + private let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! + .appending(path: "Interceptor/FileDestinations", directoryHint: .isDirectory) + private var grants: PluginFolderGrantStore { PluginFolderGrantStore(url: base.appending(path: "grants.json")) } + private lazy var publisher = PluginFilePublisher(stateURL: base.appending(path: "ownership.json")) + + func becameActive() { + isActive = true + canPrompt = true + } + + func becameInactive() { isActive = false } + + func cancelFolderSelection() { + canPrompt = false + presentedRequest = nil + folderRequest = nil + } + + func folderSheetDismissed() { + if presentedRequest != nil { cancelFolderSelection() } + } + + func selectedFolder(_ url: URL, for request: FolderRequest) { + presentedRequest = nil + folderRequest = nil + Task { + guard url.startAccessingSecurityScopedResource() else { showError = true; canPrompt = false; return } + defer { url.stopAccessingSecurityScopedResource() } + do { + let store = grants + try await Task.detached { + let values = try url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey, .isUbiquitousItemKey, + .fileResourceIdentifierKey, .volumeUUIDStringKey]) + guard values.isDirectory == true, values.isSymbolicLink != true, + values.isUbiquitousItem == true, + request.prefix.isEmpty || Data(url.lastPathComponent.utf8) == Data(request.prefix.utf8) else { throw AutomationError.invalidURL } + let bookmark = try url.bookmarkData(options: .minimalBookmark, includingResourceValuesForKeys: nil, relativeTo: nil) + var identity = Data((values.volumeUUIDString ?? "").utf8) + identity.append(0) + if let fileID = values.fileResourceIdentifier as? Data { identity.append(fileID) } + else { identity.append(contentsOf: url.standardizedFileURL.path.utf8) } + let grant = PluginFolderGrant(bookmark: bookmark, + rootIdentity: SHA256.hash(data: identity).map { String(format: "%02x", $0) }.joined(), + pathPrefix: request.prefix) + try store.set(grant, for: request.family) + }.value + delivered.removeAll() + failures.removeAll() + await synchronize() + } catch { + canPrompt = false + showError = true + } + } + } + + func synchronize() async { + guard isActive, CaptureAuthorization.isGranted, !synchronizing, !Task.isCancelled, + let source = AutomationSharedConfiguration.pluginFileRecordsURL() else { return } + synchronizing = true + defer { synchronizing = false } + let records = PluginFileStore(directoryURL: source) + do { + let versions = try await Task.detached { try records.recordVersions() }.value + for identifier in versions.keys.sorted() { + guard isActive, CaptureAuthorization.isGranted, !Task.isCancelled else { return } + if delivered[identifier] == versions[identifier] { continue } + if let failure = failures[identifier], failure.after > Date() { continue } + do { + let record = try await Task.detached { try records.readRecord(identifier) }.value + guard delivered[identifier] != record.digest else { continue } + switch record.destination.storage { + case .local: + let root = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! + .appending(path: "Plugins/Files", directoryHint: .isDirectory) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try await publisher.publish(record, to: root, rootIdentity: String(repeating: "0", count: 64)) + case .icloud: + let store = grants + let components = record.destination.pathComponents + let prefix = components.count > 1 ? components[0] : "" + guard let grant = try await Task.detached(operation: { try store.grant(for: record.family, prefix: prefix) }).value else { + requestFolder(for: record.family, prefix: prefix) + continue + } + let root: URL + let stale: Bool + do { + (root, stale) = try await Task.detached { + var isStale = false + let resolved = try URL(resolvingBookmarkData: grant.bookmark, options: .withoutUI, + relativeTo: nil, bookmarkDataIsStale: &isStale) + return (resolved, isStale) + }.value + } catch { + requestFolder(for: record.family, prefix: prefix) + continue + } + guard root.startAccessingSecurityScopedResource() else { + requestFolder(for: record.family, prefix: prefix) + continue + } + defer { root.stopAccessingSecurityScopedResource() } + let validRoot = try await Task.detached { + let values = try root.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey, .isUbiquitousItemKey]) + return values.isDirectory == true && values.isSymbolicLink != true && values.isUbiquitousItem == true + && (grant.pathPrefix.isEmpty || Data(root.lastPathComponent.utf8) == Data(grant.pathPrefix.utf8)) + }.value + guard validRoot else { + requestFolder(for: record.family, prefix: prefix) + continue + } + if stale { + try await Task.detached { + let refreshed = try root.bookmarkData(options: .minimalBookmark, includingResourceValuesForKeys: nil, relativeTo: nil) + try store.set(.init(bookmark: refreshed, rootIdentity: grant.rootIdentity, pathPrefix: grant.pathPrefix), for: record.family) + }.value + } + try await publisher.publish(record, to: root, rootIdentity: grant.rootIdentity, pathPrefix: grant.pathPrefix) + } + // A newer private record keeps a different digest and will be delivered on the next pass. + delivered[identifier] = record.digest + failures[identifier] = nil + } catch is CancellationError { return } + catch { + let count = min(4, (failures[identifier]?.attempt ?? 0) + 1) + failures[identifier] = (count, Date().addingTimeInterval(min(60, 5 * pow(2, Double(count - 1))))) + if reportedFailures.insert(identifier).inserted { showError = true } + } + } + } catch { + if reportedFailures.insert("scan").inserted { showError = true } + } + } + + private func requestFolder(for family: String, prefix: String) { + guard isActive, canPrompt, presentedRequest == nil, folderRequest == nil else { return } + let request = FolderRequest(family: family, prefix: prefix) + presentedRequest = request.id + folderRequest = request + } +} + +/// iOS owns the selection UI; no custom file-browser or destination-management screen. +struct PluginStorageFolderPicker: UIViewControllerRepresentable { + let prefix: String + let onSelect: (URL) -> Void + let onCancel: () -> Void + func makeCoordinator() -> Coordinator { Coordinator(onSelect: onSelect, onCancel: onCancel) } + func makeUIViewController(context: Context) -> UIDocumentPickerViewController { + let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.folder]) + picker.allowsMultipleSelection = false + picker.title = prefix.isEmpty ? String(localized: "AUTO_FILES_SELECT_ICLOUD_ROOT") + : String(format: String(localized: "AUTO_FILES_SELECT_ICLOUD_FOLDER %@"), prefix) + picker.delegate = context.coordinator + return picker + } + func updateUIViewController(_: UIDocumentPickerViewController, context _: Context) {} + final class Coordinator: NSObject, UIDocumentPickerDelegate { + let onSelect: (URL) -> Void + let onCancel: () -> Void + init(onSelect: @escaping (URL) -> Void, onCancel: @escaping () -> Void) { + self.onSelect = onSelect + self.onCancel = onCancel + } + func documentPicker(_: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { + if let url = urls.first { onSelect(url) } else { onCancel() } + } + func documentPickerWasCancelled(_: UIDocumentPickerViewController) { onCancel() } + } +} diff --git a/Interceptor/Automation/PluginFilesExporter.swift b/Interceptor/Automation/PluginFilesExporter.swift new file mode 100644 index 0000000..5b72011 --- /dev/null +++ b/Interceptor/Automation/PluginFilesExporter.swift @@ -0,0 +1,68 @@ +import AutomationCore +import Foundation + +/// Files is a one-way export. Failures leave authoritative responses for a foreground retry. +actor PluginFilesExporter { + static let shared = PluginFilesExporter() + private var lastExport: [String: Signature]? + private var failedState: [String: Signature]? + private var retryAfter: ContinuousClock.Instant? + private var retryDelay = 5 + + private struct Signature: Equatable { + let size: Int? + let modified: Date? + let attributesModified: Date? + let identity: String + } + + func synchronize() { + guard !Task.isCancelled, let source = AutomationSharedConfiguration.pluginFilesURL(), + let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } + let destination = documents.appending(path: "Plugins", directoryHint: .isDirectory) + do { + let current = try signatures(source: source, destination: destination) + guard current != lastExport else { return } + if current == failedState, let retryAfter, ContinuousClock.now < retryAfter { return } + try PluginJSONFileStore(directoryURL: source).export(to: destination) + let after = try signatures(source: source, destination: destination) + // A response published during export must get another pass rather than enter the cache. + let beforeSources = current.filter { $0.key.hasPrefix("source/") } + let afterSources = after.filter { $0.key.hasPrefix("source/") } + lastExport = beforeSources == afterSources ? after : nil + failedState = nil + retryAfter = nil + retryDelay = 5 + } catch { + // Retry after a failure; never log response bodies or private paths. + failedState = try? signatures(source: source, destination: destination) + retryAfter = ContinuousClock.now.advanced(by: .seconds(retryDelay)) + retryDelay = min(60, retryDelay * 2) + lastExport = nil + } + } + + /// Compare metadata only between successful exports. User edits/deletions invalidate the mirror cache. + private func signatures(source: URL, destination: URL) throws -> [String: Signature] { + let keys: Set = [.isSymbolicLinkKey, .isRegularFileKey, .fileSizeKey, + .contentModificationDateKey, .attributeModificationDateKey, .fileResourceIdentifierKey] + guard let entries = FileManager.default.enumerator(at: source, includingPropertiesForKeys: Array(keys)) else { return [:] } + var result: [String: Signature] = [:] + for case let file as URL in entries { + try Task.checkCancellation() + let values = try file.resourceValues(forKeys: keys) + guard values.isSymbolicLink != true else { throw AutomationError.corruptStore } + guard values.isRegularFile == true, file.pathExtension == "json" else { continue } + let relative = String(file.path.dropFirst(source.path.count + 1)) + result["source/" + relative] = Signature(size: values.fileSize, modified: values.contentModificationDate, + attributesModified: values.attributeModificationDate, identity: String(describing: values.fileResourceIdentifier)) + let exported = destination.appending(path: relative) + if let visible = try? exported.resourceValues(forKeys: keys) { + guard visible.isSymbolicLink != true else { throw AutomationError.corruptStore } + result["export/" + relative] = Signature(size: visible.fileSize, modified: visible.contentModificationDate, + attributesModified: visible.attributeModificationDate, identity: String(describing: visible.fileResourceIdentifier)) + } + } + return result + } +} diff --git a/Interceptor/ContentView.swift b/Interceptor/ContentView.swift index f3eb962..d9586ef 100644 --- a/Interceptor/ContentView.swift +++ b/Interceptor/ContentView.swift @@ -17,6 +17,7 @@ struct ContentView: View { @Environment(\.scenePhase) private var scenePhase @State private var selectedTab = 0 @StateObject private var tabNavigationAlignment = TabNavigationAlignment() + @StateObject private var fileDestinations = PluginFileDestinationController() @AppStorage(CaptureAuthorization.key, store: CaptureAuthorization.defaults) private var consentVersion = 0 private var requiresConsent: Bool { @@ -33,9 +34,26 @@ struct ContentView: View { mainTabs } } + .task(id: scenePhase) { + guard scenePhase == .active else { return } + fileDestinations.becameActive() + while !Task.isCancelled { + await PluginFilesExporter.shared.synchronize() + await fileDestinations.synchronize() + do { try await Task.sleep(for: .seconds(5)) } catch { return } + } + } + .sheet(item: $fileDestinations.folderRequest, onDismiss: { fileDestinations.folderSheetDismissed() }) { request in + PluginStorageFolderPicker(prefix: request.prefix, onSelect: { fileDestinations.selectedFolder($0, for: request) }, + onCancel: { fileDestinations.cancelFolderSelection() }) + } + .alert("AUTO_FILES_EXPORT_FAILED", isPresented: $fileDestinations.showError) { + Button("OK", role: .cancel) {} + } message: { Text("AUTO_FILES_EXPORT_FAILED_DETAILS") } .onAppear { stopCaptureIfUnauthorized() } .onChange(of: consentVersion) { stopCaptureIfUnauthorized() } .onChange(of: scenePhase) { + if scenePhase != .active { fileDestinations.becameInactive() } if scenePhase == .active { consentVersion = CaptureAuthorization.defaults.integer(forKey: CaptureAuthorization.key) stopCaptureIfUnauthorized() diff --git a/Interceptor/Info.plist b/Interceptor/Info.plist index 7957411..94ebbd6 100644 --- a/Interceptor/Info.plist +++ b/Interceptor/Info.plist @@ -2,6 +2,10 @@ + UIFileSharingEnabled + + LSSupportsOpeningDocumentsInPlace + LSApplicationQueriesSchemes com.nintendo.znca diff --git a/Interceptor/Localizable.xcstrings b/Interceptor/Localizable.xcstrings index 2f123d6..1e97863 100644 --- a/Interceptor/Localizable.xcstrings +++ b/Interceptor/Localizable.xcstrings @@ -1,6 +1,57 @@ { "sourceLanguage" : "ja", "strings" : { + "AUTO_APPROVAL_FILES" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "File saving" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ファイルの保存" + } + } + } + }, + "AUTO_APPROVAL_FILES_ALLOWED" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Allowed" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "許可" + } + } + } + }, + "AUTO_APPROVAL_FILES_FOOTER" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The Plugin can save files locally or to the iCloud Drive folder you allow. Files are exported while Interceptor is open and remain after disabling or deleting the Plugin. iCloud files sync through your Apple Account." + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pluginは端末内、または許可したiCloud Driveのフォルダにファイルを保存できます。Interceptorを開いている間に書き出し、Pluginの無効化・削除後も残ります。iCloudのファイルはApple Accountを通じて同期されます。" + } + } + } + }, "SSL_LIST_EDIT" : { "localizations" : { "en" : { @@ -6054,6 +6105,74 @@ } } } + }, + "AUTO_FILES_SELECT_ICLOUD_FOLDER %@" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Choose %@ in iCloud Drive" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "iCloud Driveの%@を選択" + } + } + } + }, + "AUTO_FILES_SELECT_ICLOUD_ROOT" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Choose iCloud Drive" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "iCloud Driveを選択" + } + } + } + }, + "AUTO_FILES_EXPORT_FAILED" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Could Not Export Files" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ファイルを書き出せませんでした" + } + } + } + }, + "AUTO_FILES_EXPORT_FAILED_DETAILS" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Saved data remains in Interceptor. Check the selected iCloud Drive folder and available space. Existing files from another source are not replaced." + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "保存したデータはInterceptor内に保持しています。iCloud Driveの選択先と空き容量を確認してください。他のアプリやユーザーが作成した同名ファイルは上書きしません。" + } + } + } } }, "version" : "1.0" diff --git a/Interceptor/Views/Automation/PluginBrowserView.swift b/Interceptor/Views/Automation/PluginBrowserView.swift index 07de4b9..99018f9 100644 --- a/Interceptor/Views/Automation/PluginBrowserView.swift +++ b/Interceptor/Views/Automation/PluginBrowserView.swift @@ -575,6 +575,7 @@ struct PluginPackagesEmpty: View { Text("AUTO_BROWSER_ADD_FROM_SOURCES") } } + .listRowSeparator(.hidden) } } diff --git a/Interceptor/Views/Automation/PluginPackageApprovalView.swift b/Interceptor/Views/Automation/PluginPackageApprovalView.swift index 62dff24..994bc0a 100644 --- a/Interceptor/Views/Automation/PluginPackageApprovalView.swift +++ b/Interceptor/Views/Automation/PluginPackageApprovalView.swift @@ -40,9 +40,17 @@ struct PluginPackageApprovalView: View { LabeledContent("AUTO_APPROVAL_RESPONSE_JSON") { Text(LocalizedStringKey(package.manifest.writeResponseBody ? "AUTO_APPROVAL_CAN_CHANGE" : "AUTO_APPROVAL_CANNOT_CHANGE")) } + if package.manifest.writeFiles { + LabeledContent("AUTO_APPROVAL_FILES") { Text("AUTO_APPROVAL_FILES_ALLOWED") } + } } footer: { - if package.manifest.outbound.isEmpty { - Text("AUTO_ALERT_WEBHOOK") + VStack(alignment: .leading) { + if package.manifest.writeFiles { + Text("AUTO_APPROVAL_FILES_FOOTER") + } + if package.manifest.outbound.isEmpty { + Text("AUTO_ALERT_WEBHOOK") + } } } Section { diff --git a/InterceptorTests/HTTPPluginFetchProcessorTests.swift b/InterceptorTests/HTTPPluginFetchProcessorTests.swift index 7d96113..12ff431 100644 --- a/InterceptorTests/HTTPPluginFetchProcessorTests.swift +++ b/InterceptorTests/HTTPPluginFetchProcessorTests.swift @@ -21,7 +21,7 @@ final class HTTPPluginFetchProcessorTests: XCTestCase, @unchecked Sendable { } /// One route with a synchronous request.onEnter (to observe the next sync phase) and the given response.onLeave body. - private func package(leave: String) throws -> PluginPackage { + private func package(leave: String, files: Bool = false) throws -> PluginPackage { let file = "hooks/api.example.com/credentials/GET.js" let manifest: JSONValue = .object([ "schemaVersion": .integer(2), "id": .string(UUID().uuidString), "name": .string("Fetch test"), "version": .string("1.0.0"), @@ -33,7 +33,7 @@ final class HTTPPluginFetchProcessorTests: XCTestCase, @unchecked Sendable { "read": .object(["metadata": .array(["method", "host", "path", "status"].map(JSONValue.string)), "headers": .array([.string("set-cookie")]), "queryKeys": .array([]), "body": .object(["mode": .string("json")])]), - "write": .object(["requestBody": .bool(true), "responseBody": .bool(false)]), + "write": .object(["requestBody": .bool(true), "responseBody": .bool(false), "files": .bool(files)]), "endpointBindings": .array([]), "settings": .object([:]), "outbound": .object(["profile": .object([ "url": .string("https://secondary.example.com/profile"), "method": .string("GET"), @@ -50,8 +50,8 @@ final class HTTPPluginFetchProcessorTests: XCTestCase, @unchecked Sendable { let completions: Completions } - private func harness(leave: String, transport: FetchStubTransport) async throws -> Harness { - let package = try package(leave: leave) + private func harness(leave: String, files: Bool = false, transport: FetchStubTransport) async throws -> Harness { + let package = try package(leave: leave, files: files) let (store, revisions) = try await AutomationFixtures.activationContext(packages: [package], activationURL: directory.appendingPathComponent("active.json")) var snapshot = try await store.snapshot() @@ -60,6 +60,7 @@ final class HTTPPluginFetchProcessorTests: XCTestCase, @unchecked Sendable { } let completions = Completions() let processor = HTTPPluginProcessor(store: store, snapshot: snapshot, hasCaptureConsent: { true }, outboundTransport: transport, + fileStore: PluginFileStore(directoryURL: directory.appendingPathComponent("saved")), fetchObserver: { completions.append($0) }) return Harness(processor: processor, store: store, completions: completions) } @@ -84,6 +85,46 @@ final class HTTPPluginFetchProcessorTests: XCTestCase, @unchecked Sendable { "return (async()=>{await fetch('\(fetchURL)');\(then)})();" } + private func savedResponseBytes() throws -> [Data] { + let records = PluginFileStore(directoryURL: directory.appendingPathComponent("saved")) + return try records.recordIdentifiers().map { try records.readRecord($0).contents } + } + + func testFetchResponseIsSavedUnchangedUnderTheAdmittedRevision() async throws { + let raw = Data(" {\n \"data\": {\"results\": [1,2]}, \"label\": \"サーモン\"\n} ".utf8) + let transport = FetchStubTransport { _ in .response(status: 200, body: raw) } + // Bind the fetched Response explicitly; the captured response is deliberately different. + let scriptHarness = try await self.harness(leave: "return (async()=>{const fetched=await fetch('\(fetchURL)');await Interceptor.createFile({storage:Interceptor.Storage.iCloudDrive,atPath:'Salmon Run/history.json',contents:await fetched.text()});})();", files: true, transport: transport) + defer { scriptHarness.processor.shutdown() } + _ = try await scriptHarness.processor.process(.responseLeave, request: request, response: response) + await awaitCompletion(scriptHarness, .completed) + XCTAssertEqual(try savedResponseBytes(), [raw]) + } + + func testRevocationAfterFetchPreventsJSONPublication() async throws { + let transport = FetchStubTransport() + let harness = try await harness(leave: "return (async()=>{const fetched=await fetch('\(fetchURL)');await Interceptor.createFile({storage:Interceptor.Storage.iCloudDrive,atPath:'Salmon Run/history.json',contents:await fetched.text()});})();", files: true, transport: transport) + defer { harness.processor.shutdown() } + let store = harness.store + transport.setHandler { _ in + _ = try? await store.revokeAll() + return .response(status: 200, body: Data("{}".utf8)) + } + _ = try await harness.processor.process(.responseLeave, request: request, response: response) + await awaitCompletion(harness, .failed) + XCTAssertTrue(try savedResponseBytes().isEmpty) + } + + func testCommittedJSONSurvivesLaterFailure() async throws { + let transport = FetchStubTransport { _ in .response(status: 200, body: Data("{}".utf8)) } + let harness = try await harness(leave: "return (async()=>{await Interceptor.createFile({storage:Interceptor.Storage.iCloudDrive,atPath:'Salmon Run/first.json',contents:'{\"ok\":true}'});throw Error('later failure');})();", files: true, transport: transport) + defer { harness.processor.shutdown() } + _ = try await harness.processor.process(.responseLeave, request: request, response: response) + await awaitCompletion(harness, .failed) + XCTAssertEqual(try savedResponseBytes(), [Data(#"{"ok":true}"#.utf8)]) + XCTAssertTrue(transport.fetched.isEmpty) + } + func testResponseLeaveReturnsBeforeABlockedFetchFinishesAndTheNextSyncPhaseRuns() async throws { let gate = AsyncGate() let transport = FetchStubTransport { _ in await gate.wait(); return .response(status: 200, body: Data("{}".utf8)) } diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/Manifest.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/Manifest.swift index fde8bb7..5db2a9d 100644 --- a/Packages/InterceptorAutomation/Sources/AutomationCore/Manifest.swift +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/Manifest.swift @@ -49,6 +49,8 @@ public struct PluginManifest: Equatable, Sendable { public let matches: [PluginMatch] public let writeRequestBody: Bool public let writeResponseBody: Bool + /// Schema 2 optional `write.files` (strict boolean, default false) gating `Interceptor.createFile`. Always false for schema 1. + public let writeFiles: Bool static let metadataNames: Set = ["method", "host", "status", "path"] @@ -67,16 +69,17 @@ public struct PluginManifest: Equatable, Sendable { var subs: [PluginSubscription] = [] var matches: [PluginMatch] = [] - var writeRequest = false, writeResponse = false + var writeRequest = false, writeResponse = false, writeFiles = false let read: PluginReadDeclaration if isV2 { let rawMatches = try f.array("matches") guard (1...16).contains(rawMatches.count) else { throw bad } matches = try rawMatches.map { try PluginMatch(validating: $0) } read = try PluginManifest.readDeclaration(try f.value("read"), allowJSON: true) - let w = try JSONFields(try f.value("write"), required: ["requestBody", "responseBody"], error: bad) + let w = try JSONFields(try f.value("write"), required: ["requestBody", "responseBody"], optional: ["files"], error: bad) writeRequest = try w.bool("requestBody") writeResponse = try w.bool("responseBody") + writeFiles = try w.has("files") ? w.bool("files") : false } else { let subsRaw = try f.array("subscriptions") guard (1...8).contains(subsRaw.count) else { throw bad } @@ -130,6 +133,7 @@ public struct PluginManifest: Equatable, Sendable { self.matches = matches writeRequestBody = writeRequest writeResponseBody = writeResponse + self.writeFiles = writeFiles self.read = read endpointBindings = bindings self.settings = settings diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginActivationStore.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginActivationStore.swift index f29b8dc..b253375 100644 --- a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginActivationStore.swift +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginActivationStore.swift @@ -53,6 +53,21 @@ public actor PluginActivationStore { return current == admitted } + /// Runs `operation` while holding the activation lock, so a revocation cannot interleave. The admitted + /// snapshot must still be current and the revision actually granted (and selected, once initialized). + /// `operation` must be short, synchronous and must not await or block on other locks. + public func withCurrentActivation(admitted: PluginActivationSnapshot, revisionID: String, + _ operation: @Sendable (ActivatedPlugin) throws -> Void) throws { + try file.locked { + let document = try readUnlocked() + guard document.activation == admitted, + let plugin = document.activation.revisions.first(where: { $0.revisionID == revisionID }), + document.selections.map({ $0[InstallationIdentity.family(revisionID)] == revisionID }) ?? true + else { throw AutomationError.staleSnapshot } + try operation(plugin) + } + } + /// Legacy caller compatibility. Once v2 is initialized, this cannot switch the selected revision. /// New app callers must use InstallationCoordinator's exact-byte approval and live-consent gate. @discardableResult diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFileDestination.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFileDestination.swift new file mode 100644 index 0000000..a515ff7 --- /dev/null +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFileDestination.swift @@ -0,0 +1,78 @@ +import Foundation + +public enum PluginFileStorage: String, Codable, Sendable { + case local + case icloud +} + +/// A validated, storage-relative destination chosen by plugin JavaScript. +/// +/// Paths must already be NFC (compared by UTF-8 bytes; Swift `String` equality is canonical equivalence and +/// would accept other spellings). Aliases are detected through `canonicalIdentity`, never by renaming. +public struct PluginFileDestination: Sendable, Equatable, Codable { + public enum ValidationError: Error, Equatable, Sendable { case invalidPath } + + public static let maxPathBytes = 1024 + public static let maxComponentBytes = 255 + public static let maxDepth = 8 + + public let storage: PluginFileStorage + public let atPath: String + + public init(storage: PluginFileStorage, atPath: String) throws { + try Self.validate(atPath) + self.storage = storage + self.atPath = atPath + } + + private enum CodingKeys: String, CodingKey { case storage, atPath } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let storage = try c.decode(PluginFileStorage.self, forKey: .storage) + let path = try c.decode(String.self, forKey: .atPath) + do { try self.init(storage: storage, atPath: path) } + catch { throw DecodingError.dataCorruptedError(forKey: .atPath, in: c, debugDescription: "invalid atPath") } + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(storage, forKey: .storage) + try c.encode(atPath, forKey: .atPath) + } + + /// Conservative case/compatibility-folded identity: two destinations with the same identity are aliases. + public var canonicalIdentity: String { storage.rawValue + "\n" + Self.foldedKey(atPath) } + + /// POSIX treats every slash scalar as a separator, even when a following combining mark + /// makes it part of a larger Swift `Character`. + public var pathComponents: [String] { Self.components(in: atPath) } + + private static func components(in path: String) -> [String] { + path.unicodeScalars.split(separator: "/", omittingEmptySubsequences: false).map { String($0) } + } + + static func foldedKey(_ path: String) -> String { + path.precomposedStringWithCompatibilityMapping.uppercased().lowercased().precomposedStringWithCompatibilityMapping + } + + private static func validate(_ path: String) throws { + let bytes = path.utf8.count + guard (1...maxPathBytes).contains(bytes) else { throw AutomationError.limitExceeded } + guard Data(path.utf8) == Data(path.precomposedStringWithCanonicalMapping.utf8) else { throw ValidationError.invalidPath } + let components = Self.components(in: path) + guard components.count <= maxDepth else { throw AutomationError.limitExceeded } + for component in components { + guard (1...maxComponentBytes).contains(component.utf8.count), component.unicodeScalars.first != "." else { + throw ValidationError.invalidPath + } + for scalar in component.unicodeScalars { + if scalar == "\\" || scalar == ":" { throw ValidationError.invalidPath } + switch scalar.properties.generalCategory { + case .control, .format, .lineSeparator, .paragraphSeparator: throw ValidationError.invalidPath + default: break + } + } + } + } +} diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFilePublisher.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFilePublisher.swift new file mode 100644 index 0000000..8f6b732 --- /dev/null +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFilePublisher.swift @@ -0,0 +1,706 @@ +import Darwin +import Foundation + +/// Publishes one private `PluginFileRecord` into a user-selected File Provider root (e.g. iCloud Drive). +/// +/// The caller owns the security scope and the physical-root identity string; this type only performs +/// bounded, cancellable, coordinated I/O on a dedicated serial queue and never returns while its own +/// coordination callback or file I/O is still running. +/// +/// * Everything below the root is opened descriptor-relative with `O_NOFOLLOW`; the root itself must be a +/// real directory (the trusted prefix is resolved once, the final component is never followed). +/// * A private ledger at `stateURL` records which files this publisher owns (see `Ledger`). An existing file +/// is replaced only when it is regular, single-linked and matches a ledger-recorded digest of the same +/// family and exact path spelling. Unknown files, other families, aliases and edited files are rejected +/// without any ledger or filesystem change. +/// * An intent (`pending` digest) is journaled before the external rename; recovery after a crash accepts +/// only the recorded old (`published`) or new (`pending`) digest. +/// * An external temporary is journaled in the ledger (`tempName`, then `tempDevice`/`tempInode`) before any +/// payload byte is written. After a crash only that exact, stale (>= 60 s), unlocked, single-linked workfile +/// is reclaimed: an empty file before its inode was journaled, the recorded inode (including partial bytes), +/// or a rematerialized inode with the complete pending digest. The recorded inode belongs to this native +/// scratch operation; published files retain the digest/edit protection above. Replaced workfiles with +/// different bytes are preserved as conflicts. At most one bounded temporary exists per destination and +/// retries never accumulate names. No hard OS deadline is claimed for this recovery. +/// * New external files are installed with an exclusive rename, so an unknown concurrent file is never +/// clobbered. Replacements re-verify digest and inode inside the coordinated write immediately before +/// the rename. No backup exclusion or file protection is applied to external files. +public final class PluginFilePublisher: @unchecked Sendable { + public enum PublishError: Error, Equatable, Sendable { + /// The record failed Core re-validation (destination, size, digest, family). + case invalidRecord + /// The selected root is missing, not a real directory, or changed during coordination. + case invalidRoot + /// Unknown, cross-family, aliased, linked or externally edited file at the destination. + case conflict + /// The private ledger is unreadable, malformed or over its bounds. Nothing was changed. + case corruptState + /// The ledger would exceed its entry or byte bound. + case ledgerFull + /// Another publisher (this or another process) holds the ledger lock; retry later. + case busy + /// The operation did not finish before the deadline and was asked to cancel. + case timedOut + /// Any other filesystem or coordination failure. + case io + } + + public static let maxLedgerBytes = 16 * 1024 * 1024 + public static let maxLedgerEntries = 32_768 + static let deadline: TimeInterval = 15 + + private static let chunk = 64 * 1024 + private static let tempPrefix = ".interceptor-" + + private let stateURL: URL + private let queue = DispatchQueue(label: "com.interceptor.PluginFilePublisher", qos: .utility) + + public init(stateURL: URL) { self.stateURL = stateURL } + + /// A nonempty prefix binds exactly the first virtual path component to the granted folder. + /// The remaining path is published relative to `root`; an empty prefix retains the full path. + public func publish(_ record: PluginFileRecord, to root: URL, rootIdentity: String, + pathPrefix: String = "") async throws { + try Task.checkCancellation() + let job = Job() + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + job.arm(deadline: Self.deadline) + queue.async { + let result: Result + do { + try self.run(record, root: root, rootIdentity: rootIdentity, pathPrefix: pathPrefix, job: job) + result = .success(()) + } + catch { result = .failure(error) } + job.finish() + // Resumed only after all owned I/O and coordination callbacks have ended. + continuation.resume(with: result) + } + } + } onCancel: { + job.cancel() + } + } + + // MARK: job (cancellation token) + + private final class Job: @unchecked Sendable { + let coordinator = NSFileCoordinator(filePresenter: nil) + private let lock = NSLock() + private var cancelled = false, timedOut = false, finished = false + private var timer: DispatchSourceTimer? + + func arm(deadline: TimeInterval) { + let source = DispatchSource.makeTimerSource(queue: DispatchQueue.global(qos: .utility)) + source.schedule(deadline: .now() + deadline) + source.setEventHandler { [weak self] in self?.expire() } + lock.lock(); timer = source; lock.unlock() + source.resume() + } + + func finish() { + lock.lock(); finished = true; let t = timer; timer = nil; lock.unlock() + t?.cancel() + } + + func cancel() { request(timedOut: false) } + private func expire() { request(timedOut: true) } + + private func request(timedOut expired: Bool) { + lock.lock() + if finished { lock.unlock(); return } + cancelled = true + if expired { timedOut = true } + lock.unlock() + coordinator.cancel() + // A cancel racing the start of coordination can be a no-op; repeat a bounded number of times. + for delay in [0.25, 1.0, 3.0] { + DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + delay) { [self] in + lock.lock(); let done = finished; lock.unlock() + if !done { coordinator.cancel() } + } + } + } + + func checkpoint() throws { + lock.lock(); let c = cancelled, t = timedOut; lock.unlock() + if t { throw PublishError.timedOut } + if c { throw CancellationError() } + } + } + + // MARK: validated request + + private struct Request { + let record: PluginFileRecord + let rootIdentity: String + let key: String + let familyHash: String + let path: String + /// Physical path split on U+002F scalars (never on grapheme clusters). + let components: [String] + let digest: String + + init(_ record: PluginFileRecord, rootIdentity: String, pathPrefix: String) throws { + guard (1...1024).contains(rootIdentity.utf8.count) else { throw PublishError.invalidRoot } + guard let destination = try? PluginFileDestination(storage: record.destination.storage, atPath: record.destination.atPath), + Array(destination.atPath.utf8) == Array(record.destination.atPath.utf8), + record.contents.count <= PluginFileStore.maxContentsBytes, + Digest.isHex64(record.digest), Digest.sha256Hex(record.contents) == record.digest, + InstallationIdentity.valid(record.family + "|" + String(repeating: "0", count: 64)) + else { throw PublishError.invalidRecord } + let physicalDestination: PluginFileDestination + if pathPrefix.isEmpty { + physicalDestination = destination + } else { + guard let prefix = try? PluginFileDestination(storage: destination.storage, atPath: pathPrefix), + prefix.pathComponents.count == 1 else { throw PublishError.invalidRecord } + let components = destination.pathComponents + guard components.count >= 2, components[0].utf8.elementsEqual(pathPrefix.utf8), + let relative = try? PluginFileDestination(storage: destination.storage, + atPath: components.dropFirst().joined(separator: "/")) + else { throw PublishError.invalidRecord } + physicalDestination = relative + } + self.record = record + self.rootIdentity = rootIdentity + path = physicalDestination.atPath + components = physicalDestination.pathComponents + guard components.allSatisfy(PluginFilePublisher.validUserComponent) else { throw PublishError.invalidRecord } + digest = record.digest + familyHash = Digest.sha256Hex(Data(record.family.utf8)) + key = PluginFilePublisher.ledgerKey(rootIdentity: rootIdentity, path: physicalDestination.atPath) + } + } + + /// Same conservative alias identity as the private store, scoped to a physical destination root. + static func ledgerKey(rootIdentity: String, path: String) -> String { + let folded = PluginFileDestination.foldedKey(path) + return Digest.sha256Hex(Data("\(rootIdentity.utf8.count):\(rootIdentity)\n\(folded)".utf8)) + } + + // MARK: ledger + + /// Private ledger, compact UTF-8 JSON with sorted keys: + /// + /// {"entries":[{"device":Int?,"family":"","inode":Int?,"key":"", + /// "path":"","pending":""|null,"published":""|null, + /// "tempName":"<.interceptor-UUID.tmp>"?,"tempDevice":Int?,"tempInode":Int?}],"version":1} + /// + /// `tempName` requires `pending`; `tempDevice`/`tempInode` appear together and require `tempName`. + /// `device`/`inode` appear together or not at all. `key` = sha256(len(rootIdentity) ":" rootIdentity + /// "\n" Core-folded path). Limits: 16 MiB, 32768 entries, unique keys, no other fields. + struct FileIdentity: Equatable { let device: Int64, inode: Int64 } + + struct Entry: Equatable { + var key: String, family: String, path: String + var published: String?, pending: String? + var identity: FileIdentity? + /// Journaled external temporary (exact `.interceptor-.tmp`) and, once created, its inode. + var tempName: String? + var tempIdentity: FileIdentity? + } + + private struct Ledger { + var entries: [String: Entry] = [:] + + static func load(parent: Int32, name: String) throws -> Ledger { + var info = stat() + if fstatat(parent, name, &info, AT_SYMLINK_NOFOLLOW) != 0 { + if errno == ENOENT { return Ledger() } + throw PublishError.corruptState + } + guard info.st_mode & S_IFMT == S_IFREG, info.st_nlink == 1, info.st_size >= 0, + info.st_size <= off_t(PluginFilePublisher.maxLedgerBytes) else { throw PublishError.corruptState } + let fd = openat(parent, name, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard fd >= 0 else { throw PublishError.corruptState } + defer { close(fd) } + var opened = stat() + guard fstat(fd, &opened) == 0, opened.st_ino == info.st_ino, opened.st_dev == info.st_dev, + opened.st_size == info.st_size, let data = try? Posix.readAll(fd, size: Int(opened.st_size)) + else { throw PublishError.corruptState } + return try decode(data) + } + + static func decode(_ data: Data) throws -> Ledger { + do { + let root = try JSONFields(try StrictJSON.parse(data), required: ["version", "entries"], error: .corruptStore) + guard try root.int("version") == 1 else { throw PublishError.corruptState } + let list = try root.array("entries") + guard list.count <= PluginFilePublisher.maxLedgerEntries else { throw PublishError.corruptState } + var ledger = Ledger() + for item in list { + let f = try JSONFields(item, required: ["key", "family", "path", "published", "pending"], + optional: ["device", "inode", "tempName", "tempDevice", "tempInode"], + error: .corruptStore) + func optionalDigest(_ k: String) throws -> String? { + if case .null = try f.value(k) { return nil } + let s = try f.string(k) + guard Digest.isHex64(s) else { throw PublishError.corruptState } + return s + } + let path = try f.string("path") + let destination = try PluginFileDestination(storage: .local, atPath: path) + let key = try f.string("key"), family = try f.string("family") + guard Digest.isHex64(key), Digest.isHex64(family), ledger.entries[key] == nil else { + throw PublishError.corruptState + } + let published = try optionalDigest("published"), pending = try optionalDigest("pending") + guard published != nil || pending != nil, f.has("device") == f.has("inode") else { + throw PublishError.corruptState + } + let identity = f.has("device") ? FileIdentity(device: try f.int("device"), inode: try f.int("inode")) : nil + guard f.has("tempDevice") == f.has("tempInode"), + !f.has("tempDevice") || f.has("tempName"), + !f.has("tempName") || pending != nil else { throw PublishError.corruptState } + var tempName: String? + if f.has("tempName") { + let name = try f.string("tempName") + guard PluginFilePublisher.validTempName(name) else { throw PublishError.corruptState } + tempName = name + } + let tempIdentity = f.has("tempDevice") + ? FileIdentity(device: try f.int("tempDevice"), inode: try f.int("tempInode")) : nil + ledger.entries[key] = Entry(key: key, family: family, path: destination.atPath, + published: published, pending: pending, identity: identity, + tempName: tempName, tempIdentity: tempIdentity) + } + return ledger + } catch let error as PublishError { + throw error + } catch { + throw PublishError.corruptState + } + } + + func encode() throws -> Data { + let items: [JSONValue] = entries.values.sorted { $0.key < $1.key }.map { e in + var o: [String: JSONValue] = [ + "key": .string(e.key), "family": .string(e.family), "path": .string(e.path), + "published": e.published.map(JSONValue.string) ?? .null, + "pending": e.pending.map(JSONValue.string) ?? .null, + ] + if let id = e.identity { o["device"] = .integer(id.device); o["inode"] = .integer(id.inode) } + if let name = e.tempName { o["tempName"] = .string(name) } + if let id = e.tempIdentity { o["tempDevice"] = .integer(id.device); o["tempInode"] = .integer(id.inode) } + return .object(o) + } + guard items.count <= PluginFilePublisher.maxLedgerEntries else { throw PublishError.ledgerFull } + let data = try JSONValue.object(["version": .integer(1), "entries": .array(items)]).data() + guard data.count <= PluginFilePublisher.maxLedgerBytes else { throw PublishError.ledgerFull } + return data + } + + /// Protected temp + fsync + atomic rename + directory fsync. Private ledger only. + func save(parent: Int32, parentURL: URL, name: String) throws { + let data = try encode() + let temp: (fd: Int32, name: String) + do { + temp = try Posix.writeProtectedTemp(directoryFD: parent, directoryURL: parentURL, + prefix: ".ledger-tmp-", data: data, checkCancellation: false) + } catch { throw PublishError.io } + defer { close(temp.fd) } + guard renameat(parent, temp.name, parent, name) == 0 else { + unlinkat(parent, temp.name, 0) + throw PublishError.io + } + guard fsync(parent) == 0 else { throw PublishError.io } + } + } + + // MARK: run + + private func run(_ record: PluginFileRecord, root: URL, rootIdentity: String, pathPrefix: String, job: Job) throws { + try job.checkpoint() // before any ledger or directory side effect + let request = try Request(record, rootIdentity: rootIdentity, pathPrefix: pathPrefix) + var rootStat = stat() + guard root.isFileURL, stateURL.isFileURL, lstat(root.path, &rootStat) == 0, + rootStat.st_mode & S_IFMT == S_IFDIR else { throw PublishError.invalidRoot } + let stateName = stateURL.lastPathComponent + let parentURL = stateURL.deletingLastPathComponent() + guard !stateName.isEmpty, stateName != ".", stateName != ".." else { throw PublishError.corruptState } + + let parent: Int32 + do { parent = try Posix.openDirectory(parentURL, create: true, mode: 0o700) } catch { throw PublishError.io } + defer { close(parent) } + guard flock(parent, LOCK_EX | LOCK_NB) == 0 else { + throw errno == EWOULDBLOCK ? PublishError.busy : PublishError.io + } + defer { flock(parent, LOCK_UN) } + + var ledger = try Ledger.load(parent: parent, name: stateName) + try job.checkpoint() + try sweepLedgerTemporaries(parent: parent, stateName: stateName, job: job) + + // A directory write does not coordinate concurrent writers of its descendants. Prepare only + // the containing directories here, then release this coordination before requesting the leaf. + // Nesting write coordination inside a write accessor is prohibited by NSFileCoordinator. + let coordinatedRoot = try coordinated(root, options: [], job: job) { url in + let rootFD = try self.openRoot(url, expected: rootStat) + defer { close(rootFD) } + if let e = ledger.entries[request.key] { + guard e.family == request.familyHash, Array(e.path.utf8) == Array(request.path.utf8) + else { throw PublishError.conflict } + } + try job.checkpoint() + let directories = Array(request.components.dropLast()) + guard let parentFD = try self.openDirectories(rootFD, directories, create: true) else { + throw PublishError.io + } + close(parentFD) + return url + } + let directoryComponents = Array(request.components.dropLast()) + // An unresolved journaled temporary is resolved (or reported) before any new temporary exists. + if let tempName = ledger.entries[request.key]?.tempName { + let tempURL = (directoryComponents + [tempName]).reduce(coordinatedRoot) { $0.appendingPathComponent($1) } + try coordinated(tempURL, options: .forDeleting, job: job) { url in + let accessorRoot = try self.accessorRoot(url, suffix: directoryComponents + [tempName]) + try self.recoverTemp(request, rootURL: accessorRoot, rootStat: rootStat, ledger: &ledger, + parent: parent, parentURL: parentURL, stateName: stateName, job: job) + } + } + let requestedLeaf = request.components.reduce(coordinatedRoot) { $0.appendingPathComponent($1) } + try coordinated(requestedLeaf, options: .forReplacing, job: job) { leafURL in + // Use the accessor URL, even when the provider changed the trusted prefix. Its exact + // relative suffix must still be the requested path; the reopened root inode is checked. + let accessorRoot = try self.accessorRoot(leafURL, suffix: request.components) + try self.transact(request, rootURL: accessorRoot, rootStat: rootStat, ledger: &ledger, + parent: parent, parentURL: parentURL, stateName: stateName, job: job) + } + } + + private func accessorRoot(_ url: URL, suffix: [String]) throws -> URL { + var root = url + for component in suffix.reversed() { + guard Array(root.lastPathComponent.utf8) == Array(component.utf8) else { throw PublishError.invalidRoot } + root.deleteLastPathComponent() + } + return root + } + + private func clearTemp(_ r: Request, ledger: inout Ledger, parent: Int32, parentURL: URL, stateName: String) throws { + guard var e = ledger.entries[r.key] else { return } + e.tempName = nil; e.tempIdentity = nil + ledger.entries[r.key] = e + try ledger.save(parent: parent, parentURL: parentURL, name: stateName) + } + + /// Resolves only this destination's native scratch workfile. A journaled inode is owned even during a + /// partial write. Before its inode is recorded only an empty file is reclaimable; a rematerialized + /// inode must match the full pending digest. Published file edit protection is separate from scratch. + private func recoverTemp(_ r: Request, rootURL: URL, rootStat: stat, ledger: inout Ledger, parent: Int32, + parentURL: URL, stateName: String, job: Job) throws { + try job.checkpoint() + guard let entry = ledger.entries[r.key], let name = entry.tempName, Self.validTempName(name) else { return } + let rootFD = try openRoot(rootURL, expected: rootStat) + defer { close(rootFD) } + guard let dir = try openDirectories(rootFD, Array(r.components.dropLast()), create: false) else { + try clearTemp(r, ledger: &ledger, parent: parent, parentURL: parentURL, stateName: stateName) + return + } + defer { close(dir) } + var info = stat() + if fstatat(dir, name, &info, AT_SYMLINK_NOFOLLOW) != 0 { + guard errno == ENOENT else { throw PublishError.io } + try clearTemp(r, ledger: &ledger, parent: parent, parentURL: parentURL, stateName: stateName) + return + } + func plain(_ s: stat) -> Bool { + s.st_mode & S_IFMT == S_IFREG && s.st_nlink == 1 && s.st_size >= 0 + && s.st_size <= off_t(PluginFileStore.maxContentsBytes) + } + guard let pending = entry.pending, plain(info) else { throw PublishError.conflict } + let fd = openat(dir, name, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard fd >= 0 else { throw errno == ELOOP ? PublishError.conflict : PublishError.io } + defer { close(fd) } + var opened = stat() + guard fstat(fd, &opened) == 0, plain(opened), opened.st_ino == info.st_ino, opened.st_dev == info.st_dev + else { throw PublishError.conflict } + guard flock(fd, LOCK_EX | LOCK_NB) == 0 else { + throw errno == EWOULDBLOCK ? PublishError.busy : PublishError.io + } + let modified = Double(opened.st_mtimespec.tv_sec) + Double(opened.st_mtimespec.tv_nsec) / 1_000_000_000 + guard Date().timeIntervalSince1970 - modified >= 60 else { throw PublishError.busy } + if let identity = entry.tempIdentity { + let current = FileIdentity(device: Int64(opened.st_dev), inode: Int64(truncatingIfNeeded: opened.st_ino)) + if current != identity { + guard let data = try? Posix.readAll(fd, size: Int(opened.st_size)) else { throw PublishError.io } + guard Digest.sha256Hex(data) == pending else { throw PublishError.conflict } + } + } else { + // The intent name was durable before O_EXCL, and no payload is written before inode save. + guard opened.st_size == 0 else { throw PublishError.conflict } + } + try job.checkpoint() + var again = stat() + guard Posix.sameFile(dir, name, fd), fstat(fd, &again) == 0, plain(again), + again.st_size == opened.st_size, again.st_mtimespec.tv_sec == opened.st_mtimespec.tv_sec, + again.st_mtimespec.tv_nsec == opened.st_mtimespec.tv_nsec else { throw PublishError.conflict } + guard unlinkat(dir, name, 0) == 0 else { throw PublishError.io } + guard fsync(dir) == 0 else { throw PublishError.io } + try clearTemp(r, ledger: &ledger, parent: parent, parentURL: parentURL, stateName: stateName) + } + + static func validTempName(_ name: String) -> Bool { + guard name.utf8.count == tempPrefix.utf8.count + 36 + 4, name.hasPrefix(tempPrefix), name.hasSuffix(".tmp") + else { return false } + return UUID(uuidString: String(name.dropFirst(tempPrefix.count).dropLast(4))) != nil + } + + /// A user-export path component: nonempty, no separator or NUL scalar, not `.`/`..`, no leading dot. + static func validUserComponent(_ name: String) -> Bool { + let scalars = name.unicodeScalars + return !scalars.isEmpty && name.utf8.count <= 255 && scalars.first != "." + && !scalars.contains("/") && !scalars.contains("\0") + } + + /// Every ledger writer holds this same directory lock before creating its temporary. Once the + /// lock is acquired, unlocked regular files with our exact UUID name are abandoned writes. The + /// committed ledger (including its intent) remains authoritative; no response or export is removed. + private func sweepLedgerTemporaries(parent: Int32, stateName: String, job: Job) throws { + let prefix = ".ledger-tmp-" + var removed = false + for name in try Posix.list(parent) where name != stateName && name.hasPrefix(prefix) { + try job.checkpoint() + let suffix = String(name.dropFirst(prefix.count)) + guard suffix.utf8.count == 36, UUID(uuidString: suffix) != nil else { continue } + var info = stat() + guard fstatat(parent, name, &info, AT_SYMLINK_NOFOLLOW) == 0 else { + if errno == ENOENT { continue } + throw PublishError.io + } + guard info.st_mode & S_IFMT == S_IFREG, info.st_nlink == 1, + info.st_size >= 0, info.st_size <= off_t(Self.maxLedgerBytes) else { continue } + let fd = openat(parent, name, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard fd >= 0 else { + if errno == ENOENT { continue } + throw PublishError.io + } + defer { close(fd) } + if flock(fd, LOCK_EX | LOCK_NB) != 0 { + if errno == EWOULDBLOCK { continue } + throw PublishError.io + } + guard Posix.sameFile(parent, name, fd) else { continue } + guard unlinkat(parent, name, 0) == 0 else { throw PublishError.io } + removed = true + } + if removed, fsync(parent) != 0 { throw PublishError.io } + } + + /// Each write accessor finishes before another write is requested on this coordinator. + private func coordinated(_ url: URL, options: NSFileCoordinator.WritingOptions, job: Job, + accessor: (URL) throws -> T) throws -> T { + try job.checkpoint() + var outcome: Result = .failure(PublishError.io) + var coordinationError: NSError? + job.coordinator.coordinate(writingItemAt: url, options: options, error: &coordinationError) { coordinatedURL in + do { outcome = .success(try accessor(coordinatedURL)) } + catch { outcome = .failure(error) } + } + if coordinationError != nil { + try job.checkpoint() + if (coordinationError as NSError?)?.code == NSUserCancelledError { throw CancellationError() } + throw PublishError.io + } + return try outcome.get() + } + + private func openRoot(_ url: URL, expected: stat) throws -> Int32 { + guard url.isFileURL else { throw PublishError.invalidRoot } + // The OS-selected prefix resolves naturally (inside the caller's security scope); the final + // component is never followed and must be the verified directory. + let fd = open(url.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) + guard fd >= 0 else { throw PublishError.invalidRoot } + var opened = stat() + guard fstat(fd, &opened) == 0, opened.st_dev == expected.st_dev, opened.st_ino == expected.st_ino else { + close(fd) + throw PublishError.invalidRoot + } + return fd + } + + // MARK: coordinated transaction + + private func transact(_ r: Request, rootURL: URL, rootStat: stat, ledger: inout Ledger, parent: Int32, + parentURL: URL, stateName: String, job: Job) throws { + try job.checkpoint() + let rootFD = try openRoot(rootURL, expected: rootStat) + defer { close(rootFD) } + + let components = r.components + let fileName = components[components.count - 1] + let directories = Array(components.dropLast()) + + // Decide using only non-creating traversal. + var existing: Existing = .missing + if let dir = try openDirectories(rootFD, directories, create: false) { + defer { close(dir) } + existing = try inspect(dir, fileName) + } + var entry = ledger.entries[r.key] + if let e = entry { + guard e.family == r.familyHash, Array(e.path.utf8) == Array(r.path.utf8) else { throw PublishError.conflict } + } + var replacing: Existing? = nil + switch (entry, existing) { + case (nil, .file): throw PublishError.conflict + case (_, .missing): break + case (let e?, .file(let identity, let digest)): + let owned = digest == e.published || digest == e.pending + guard owned else { throw PublishError.conflict } + // File Providers can re-materialize an unchanged document on a different inode. Persistent + // ownership is bound to the family, exact path and known bytes. Inodes only guard races + // during this coordinated operation, where `replacing` is inspected again before rename. + if digest == r.digest { + // Already the desired bytes: no external rewrite, just finalize the ledger. + var done = e + done.published = digest; done.pending = nil; done.identity = identity + if done != e { ledger.entries[r.key] = done; try ledger.save(parent: parent, parentURL: parentURL, name: stateName) } + return + } + replacing = existing + entry = e + entry?.published = digest + entry?.identity = identity + } + + guard (entry != nil) || ledger.entries.count < Self.maxLedgerEntries else { throw PublishError.ledgerFull } + try job.checkpoint() + + // Journal the intent before publishing any external file contents. + var intent = entry ?? Entry(key: r.key, family: r.familyHash, path: r.path, published: nil, pending: nil, identity: nil) + // An unresolved journaled temporary must be recovered first; never mint a second name. + guard intent.tempName == nil, intent.tempIdentity == nil else { throw PublishError.conflict } + let tempName = Self.tempPrefix + UUID().uuidString + ".tmp" + intent.pending = r.digest + intent.tempName = tempName + ledger.entries[r.key] = intent + try ledger.save(parent: parent, parentURL: parentURL, name: stateName) + + try job.checkpoint() + // Parent creation was separately coordinated. If a parent was removed in between, retry + // from that phase instead of mutating an uncoordinated directory while holding the leaf. + guard let dir = try openDirectories(rootFD, directories, create: false) else { throw PublishError.io } + defer { close(dir) } + let temp = try writeTemp(dir, tempName, r.record.contents, job: job) { identity in + // Durable inode metadata before any payload byte exists. + intent.tempIdentity = identity + ledger.entries[r.key] = intent + try ledger.save(parent: parent, parentURL: parentURL, name: stateName) + } + defer { close(temp.fd) } + var installed = false + defer { if !installed && Posix.sameFile(dir, temp.name, temp.fd) { unlinkat(dir, temp.name, 0) } } + try job.checkpoint() + guard Posix.sameFile(dir, temp.name, temp.fd) else { throw PublishError.conflict } + + if let replacing, case .file(let identity, let digest) = replacing { + // Recheck inside the coordinated write, immediately before the replacing rename. + guard case .file(let nowIdentity, let nowDigest) = try inspect(dir, fileName), + nowIdentity == identity, nowDigest == digest else { throw PublishError.conflict } + guard renameat(dir, temp.name, dir, fileName) == 0 else { throw PublishError.io } + } else { + try installExclusively(dir, temp.name, fileName) + } + installed = true + // Past this point the bytes are visible: always finalize the ledger, ignoring cancellation. + let synced = fsync(dir) == 0 + var done = intent + var info = stat() + guard fstat(temp.fd, &info) == 0 else { throw PublishError.io } + done.published = r.digest; done.pending = nil + done.tempName = nil; done.tempIdentity = nil + done.identity = FileIdentity(device: Int64(info.st_dev), inode: Int64(truncatingIfNeeded: info.st_ino)) + ledger.entries[r.key] = done + try ledger.save(parent: parent, parentURL: parentURL, name: stateName) + guard synced else { throw PublishError.io } + } + + private enum Existing { case missing, file(FileIdentity, String) } + + /// Descriptor-relative no-follow walk. `nil` when a component is absent and `create` is false. + private func openDirectories(_ root: Int32, _ names: [String], create: Bool) throws -> Int32? { + guard names.allSatisfy(Self.validUserComponent) else { throw PublishError.invalidRecord } + var fd = dup(root) + guard fd >= 0 else { throw PublishError.io } + for name in names { + let next: Int32 + do { next = try Posix.openChild(fd, name, create: create, mode: 0o755) } + catch is Posix.Missing { close(fd); return nil } + catch { + let kind = try? Posix.kind(fd, name) + close(fd) + throw (kind != nil && kind != S_IFDIR) ? PublishError.conflict : PublishError.io + } + close(fd) + fd = next + } + return fd + } + + private func inspect(_ dir: Int32, _ name: String) throws -> Existing { + guard Self.validUserComponent(name) else { throw PublishError.invalidRecord } + var info = stat() + if fstatat(dir, name, &info, AT_SYMLINK_NOFOLLOW) != 0 { + if errno == ENOENT { return .missing } + throw PublishError.io + } + func plain(_ s: stat) -> Bool { + s.st_mode & S_IFMT == S_IFREG && s.st_nlink == 1 && s.st_size >= 0 + && s.st_size <= off_t(PluginFileStore.maxContentsBytes) + } + guard plain(info) else { throw PublishError.conflict } + let fd = openat(dir, name, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard fd >= 0 else { throw errno == ELOOP ? PublishError.conflict : PublishError.io } + defer { close(fd) } + var opened = stat() + guard fstat(fd, &opened) == 0, plain(opened), opened.st_ino == info.st_ino, opened.st_dev == info.st_dev + else { throw PublishError.conflict } + guard let data = try? Posix.readAll(fd, size: Int(opened.st_size)) else { throw PublishError.io } + return .file(FileIdentity(device: Int64(opened.st_dev), inode: Int64(truncatingIfNeeded: opened.st_ino)), + Digest.sha256Hex(data)) + } + + private func writeTemp(_ dir: Int32, _ name: String, _ data: Data, job: Job, + onCreated: (FileIdentity) throws -> Void) throws -> (fd: Int32, name: String) { + guard Self.validTempName(name) else { throw PublishError.io } + let fd = openat(dir, name, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard fd >= 0 else { throw PublishError.io } + do { + guard flock(fd, LOCK_EX | LOCK_NB) == 0 else { throw PublishError.io } + var created = stat() + guard fstat(fd, &created) == 0 else { throw PublishError.io } + try onCreated(FileIdentity(device: Int64(created.st_dev), inode: Int64(truncatingIfNeeded: created.st_ino))) + var offset = 0 + while offset < data.count { + try job.checkpoint() + let n = min(Self.chunk, data.count - offset) + let written = data.withUnsafeBytes { write(fd, $0.baseAddress! + offset, n) } + guard written > 0 else { throw PublishError.io } + offset += written + } + guard fsync(fd) == 0 else { throw PublishError.io } + return (fd, name) + } catch { + if Posix.sameFile(dir, name, fd) { unlinkat(dir, name, 0) } + close(fd) + throw error + } + } + + /// Atomic no-clobber install: exclusive rename, with an exclusive hard link where unsupported. + private func installExclusively(_ dir: Int32, _ temp: String, _ name: String) throws { + guard Self.validUserComponent(name) else { throw PublishError.invalidRecord } + if renameatx_np(dir, temp, dir, name, UInt32(RENAME_EXCL)) == 0 { return } + switch errno { + case EEXIST: throw PublishError.conflict + case ENOTSUP, EINVAL: + guard linkat(dir, temp, dir, name, 0) == 0 else { throw errno == EEXIST ? PublishError.conflict : PublishError.io } + unlinkat(dir, temp, 0) + default: throw PublishError.io + } + } +} diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFileStore.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFileStore.swift new file mode 100644 index 0000000..a8ce723 --- /dev/null +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFileStore.swift @@ -0,0 +1,460 @@ +import CryptoKit +import Darwin +import Foundation + +/// One immutable, validated private record read back from `PluginFileStore`. +public struct PluginFileRecord: Sendable { + public let identifier: String + public let family: String + public let destination: PluginFileDestination + public let contents: Data + public let digest: String +} + +/// Durable private store for plugin-created files: `//.rec`. +/// +/// Each record is a single versioned file (routing header + raw payload) published with one atomic rename, +/// so the latest commit wins and route/payload can never disagree. Payload bytes are opaque (never parsed). +/// All I/O below the root is descriptor-relative with `O_NOFOLLOW`. Prepare happens outside the activation +/// fence; commit publishes inside it under a non-blocking root lock. +public struct PluginFileStore: Sendable { + public static let maxContentsBytes = 1024 * 1024 + public static let maxFamilyBytes = 64 * 1024 * 1024 + public static let maxFamilyFiles = 2048 + public static let maxFamilies = 16 + public static let maxTotalBytes = 256 * 1024 * 1024 + static let maxHeaderBytes = 4096 + private static let maxPendingTemporaries = 256 + private static let maxRootEntries = maxFamilies + maxPendingTemporaries + + public enum StoreError: Error, Equatable, Sendable { + /// Another publisher holds the storage lock; the caller may retry later. + case busy + /// The permission, revision or package binding is invalid. + case notPermitted + /// The prepared write was already committed or discarded. + case consumed + /// Another family (or a differently spelled alias) already owns this destination. + case conflict + } + + private static let tempPrefix = ".tmp-" + private static let recordSuffix = ".rec" + private static let magic = Array("IPFREC01".utf8) + private static let prefixBytes = 12 + private static let abandonedAge: TimeInterval = 300 + + public let directoryURL: URL + public init(directoryURL: URL) { self.directoryURL = directoryURL } + + // MARK: naming + + private static func namespace(for family: String) -> String { + let uuidPart = String(family.split(separator: "|").last ?? "").lowercased() + return String(uuidPart.prefix(8)) + "-" + String(Digest.sha256Hex(Data(family.utf8)).prefix(40)) + } + + private static func fileName(for destination: PluginFileDestination) -> String { + Digest.sha256Hex(Data(destination.canonicalIdentity.utf8)) + recordSuffix + } + + private static func isHex(_ s: Substring) -> Bool { + s.utf8.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x61 && $0 <= 0x66) } + } + + private static func validNamespace(_ s: String) -> Bool { + let parts = s.split(separator: "-", omittingEmptySubsequences: false) + return parts.count == 2 && parts[0].utf8.count == 8 && parts[1].utf8.count == 40 && isHex(parts[0]) && isHex(parts[1]) + } + + private static func validFileName(_ s: String) -> Bool { + guard s.hasSuffix(recordSuffix) else { return false } + let stem = s.dropLast(recordSuffix.count) + return stem.utf8.count == 64 && isHex(stem) + } + + // MARK: record format + + private struct Header { + let family: String + let destination: PluginFileDestination + let size: Int + let digest: String + + func data() throws -> Data { + try JSONValue.object([ + "family": .string(family), "storage": .string(destination.storage.rawValue), + "atPath": .string(destination.atPath), "size": .integer(Int64(size)), "digest": .string(digest), + ]).data() + } + } + + private static func encode(_ header: Header, payload: Data) throws -> Data { + let head = try header.data() + guard head.count <= maxHeaderBytes else { throw AutomationError.limitExceeded } + var out = Data(magic) + let n = UInt32(head.count) + out.append(contentsOf: [UInt8(n >> 24), UInt8((n >> 16) & 0xFF), UInt8((n >> 8) & 0xFF), UInt8(n & 0xFF)]) + out.append(head) + out.append(payload) + return out + } + + /// Length of the header declared by a 12-byte prefix. + private static func headerLength(_ prefix: [UInt8]) throws -> Int { + guard prefix.count == prefixBytes, Array(prefix[0..<8]) == magic else { throw AutomationError.corruptStore } + let n = (Int(prefix[8]) << 24) | (Int(prefix[9]) << 16) | (Int(prefix[10]) << 8) | Int(prefix[11]) + guard (1...maxHeaderBytes).contains(n) else { throw AutomationError.corruptStore } + return n + } + + private static func parseHeader(_ bytes: Data) throws -> Header { + do { + let value = try JSONValue(parsing: bytes) + let f = try JSONFields(value, required: ["family", "storage", "atPath", "size", "digest"], error: .corruptStore) + guard let storage = PluginFileStorage(rawValue: try f.string("storage")) else { throw AutomationError.corruptStore } + let family = try f.string("family") + guard InstallationIdentity.valid(family + "|" + String(repeating: "0", count: 64)) else { throw AutomationError.corruptStore } + let size = try f.int("size") + let digest = try f.string("digest") + guard (0...Int64(maxContentsBytes)).contains(size), Digest.isHex64(digest) else { throw AutomationError.corruptStore } + let header = Header(family: family, destination: try PluginFileDestination(storage: storage, atPath: try f.string("atPath")), + size: Int(size), digest: digest) + guard try header.data() == bytes else { throw AutomationError.corruptStore } + return header + } catch { throw AutomationError.corruptStore } + } + + private static func readHeader(fd: Int32, fileSize: Int) throws -> Header { + var prefix = [UInt8](repeating: 0, count: prefixBytes) + guard fileSize >= prefixBytes, pread(fd, &prefix, prefixBytes, 0) == prefixBytes else { throw AutomationError.corruptStore } + let n = try headerLength(prefix) + guard fileSize >= prefixBytes + n else { throw AutomationError.corruptStore } + var head = [UInt8](repeating: 0, count: n) + guard pread(fd, &head, n, off_t(prefixBytes)) == n else { throw AutomationError.corruptStore } + let header = try parseHeader(Data(head)) + guard fileSize == prefixBytes + n + header.size else { throw AutomationError.corruptStore } + return header + } + + // MARK: prepare + + /// Validates, then writes a protected, fsynced temporary file. Nothing is visible to readers until commit. + public func prepare(revisionID: String, package: PluginPackage, destination: PluginFileDestination, + contents: Data) throws -> PreparedWrite { + guard InstallationIdentity.valid(revisionID, package: package), package.manifest.writeFiles else { + throw StoreError.notPermitted + } + guard contents.count <= Self.maxContentsBytes else { throw AutomationError.limitExceeded } + let family = InstallationIdentity.family(revisionID) + let record = try Self.encode(Header(family: family, destination: destination, size: contents.count, + digest: Digest.sha256Hex(contents)), payload: contents) + try Task.checkCancellation() + + let root = try Posix.openDirectory(directoryURL, create: true, mode: 0o700) + defer { close(root) } + try Posix.protect(root, url: directoryURL) + // Sweep outside the activation fence; skipped when a publisher holds the root lock. + if flock(root, LOCK_EX | LOCK_NB) == 0 { + sweepAbandonedTemporaries(root) + flock(root, LOCK_UN) + } + let entries = try Self.boundedEntries(root, limit: Self.maxRootEntries) + guard entries.lazy.filter({ $0.hasPrefix(Self.tempPrefix) }).count < Self.maxPendingTemporaries else { + throw AutomationError.limitExceeded + } + let temp = try Posix.writeProtectedTemp(directoryFD: root, directoryURL: directoryURL, + prefix: Self.tempPrefix, data: record, checkCancellation: true) + return PreparedWrite(store: self, namespace: Self.namespace(for: family), fileName: Self.fileName(for: destination), + destination: destination, tempName: temp.name, fd: temp.fd, size: record.count) + } + + /// A protected, fsynced temporary file owned by this object. Commit or discard exactly once; dropping it + /// removes the temporary. It holds an exclusive `flock` so a concurrent sweep never removes it. + public final class PreparedWrite: @unchecked Sendable { + fileprivate let store: PluginFileStore + fileprivate let namespace: String, fileName: String, tempName: String, size: Int + fileprivate let destination: PluginFileDestination + private let lock = NSLock() + private var fd: Int32 + + fileprivate init(store: PluginFileStore, namespace: String, fileName: String, destination: PluginFileDestination, + tempName: String, fd: Int32, size: Int) { + self.store = store; self.namespace = namespace; self.fileName = fileName + self.destination = destination; self.tempName = tempName; self.fd = fd; self.size = size + } + deinit { discard() } + + /// Removes the temporary file. Safe to call repeatedly. + public func discard() { + lock.lock(); defer { lock.unlock() } + releaseLocked() + } + + private func releaseLocked() { + guard fd >= 0 else { return } + if let root = try? Posix.openDirectory(store.directoryURL, create: false, mode: 0o700) { + if Posix.sameFile(root, tempName, fd) { unlinkat(root, tempName, 0) } + close(root) + } + close(fd) + fd = -1 + } + + /// `checkAuthorization` runs after every fallible preparation step and immediately before publication. + /// Once it returns, a later cancellation may leave the committed record in place. + public func commit(checkAuthorization: @Sendable () throws -> Void = {}) throws { + lock.lock(); defer { lock.unlock() } + guard fd >= 0 else { throw StoreError.consumed } + defer { releaseLocked() } + try store.publish(self, fd: fd, checkAuthorization: checkAuthorization) + } + } + + // MARK: commit + + fileprivate func publish(_ write: PreparedWrite, fd tempFD: Int32, + checkAuthorization: @Sendable () throws -> Void) throws { + let root: Int32 + do { root = try Posix.openDirectory(directoryURL, create: false, mode: 0o700) } + catch is Posix.Missing { throw AutomationError.saveFailed } + defer { close(root) } + guard flock(root, LOCK_EX | LOCK_NB) == 0 else { + if errno == EWOULDBLOCK { throw StoreError.busy } + throw AutomationError.saveFailed + } + defer { flock(root, LOCK_UN) } + guard Posix.sameFile(root, write.tempName, tempFD) else { throw AutomationError.saveFailed } + + // Metadata-only scan: names and sizes, never payloads. + var namespaces: [String] = [] + for name in try Self.boundedEntries(root, limit: Self.maxRootEntries) where !name.hasPrefix(Self.tempPrefix) { + guard Self.validNamespace(name), try Posix.kind(root, name) == S_IFDIR else { throw AutomationError.corruptStore } + namespaces.append(name) + } + guard namespaces.count <= Self.maxFamilies else { throw AutomationError.corruptStore } + var total = 0 + var own = (files: 0, bytes: 0) + var previousSize: Int? + for name in namespaces { + let dir = try Posix.openChild(root, name, create: false, mode: 0o700) + defer { close(dir) } + let entries = try Self.boundedEntries(dir, limit: Self.maxFamilyFiles) + var files = 0, bytes = 0 + for entry in entries { + var info = stat() + guard Self.validFileName(entry), fstatat(dir, entry, &info, AT_SYMLINK_NOFOLLOW) == 0, + info.st_mode & S_IFMT == S_IFREG, info.st_size >= off_t(Self.prefixBytes), + info.st_size <= off_t(Self.prefixBytes + Self.maxHeaderBytes + Self.maxContentsBytes) + else { throw AutomationError.corruptStore } + files += 1 + bytes += Int(info.st_size) + if entry == write.fileName { + // Same stable name means the same folded destination: only the owning family may replace it. + guard name == write.namespace else { throw StoreError.conflict } + previousSize = Int(info.st_size) + } + } + total += bytes + if name == write.namespace { own = (files, bytes) } + } + let exists = namespaces.contains(write.namespace) + guard exists || namespaces.count < Self.maxFamilies else { throw AutomationError.limitExceeded } + + if previousSize != nil { + let dir = try Posix.openChild(root, write.namespace, create: false, mode: 0o700) + defer { close(dir) } + let current = openat(dir, write.fileName, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard current >= 0 else { throw AutomationError.corruptStore } + defer { close(current) } + let header = try Self.readHeader(fd: current, fileSize: previousSize!) + guard Self.namespace(for: header.family) == write.namespace, + Self.fileName(for: header.destination) == write.fileName else { throw AutomationError.corruptStore } + // A differently spelled alias must be rejected, not renamed. + guard header.destination == write.destination, + Data(header.destination.atPath.utf8) == Data(write.destination.atPath.utf8) else { throw StoreError.conflict } + } + let newFiles = own.files + (previousSize == nil ? 1 : 0) + let ownBytes = own.bytes - (previousSize ?? 0) + write.size + let totalBytes = total - (previousSize ?? 0) + write.size + guard newFiles <= Self.maxFamilyFiles, ownBytes <= Self.maxFamilyBytes, + totalBytes <= Self.maxTotalBytes else { throw AutomationError.limitExceeded } + + // A denied first publish must not leave an empty family directory consuming quota. + if !exists { try checkAuthorization() } + let dir = try Posix.openChild(root, write.namespace, create: true, mode: 0o700) + defer { close(dir) } + var committed = false + defer { if !exists && !committed { unlinkat(root, write.namespace, AT_REMOVEDIR) } } + let namespaceURL = directoryURL.appendingPathComponent(write.namespace) + if !exists { + try Posix.protect(dir, url: namespaceURL) + guard fsync(root) == 0 else { throw AutomationError.saveFailed } + } + + if previousSize == write.size { + let current = openat(dir, write.fileName, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + if current >= 0 { + defer { close(current) } + if try Posix.equal(current, tempFD, size: write.size) { + // Identical retry: still restore protection and make the visible bytes durable. + try checkAuthorization() + try Posix.protect(current, url: namespaceURL.appendingPathComponent(write.fileName)) + committed = true + guard fsync(current) == 0, fsync(dir) == 0 else { throw AutomationError.saveFailed } + return + } + } + } + try checkAuthorization() + guard renameat(root, write.tempName, dir, write.fileName) == 0 else { throw AutomationError.saveFailed } + committed = true + // Bytes are now visible; a sync failure is reported without rolling them back. + guard fsync(dir) == 0, fsync(root) == 0 else { throw AutomationError.saveFailed } + } + + // MARK: read + + /// Identifiers (`namespace/filename`) of every committed record; `[]` when the store does not exist yet. + public func recordIdentifiers() throws -> [String] { + let root: Int32 + do { root = try Posix.openDirectory(directoryURL, create: false, mode: 0o700) } + catch is Posix.Missing { return [] } + defer { close(root) } + var namespaces: [String] = [] + for name in try Self.boundedEntries(root, limit: Self.maxRootEntries) where !name.hasPrefix(Self.tempPrefix) { + guard Self.validNamespace(name), try Posix.kind(root, name) == S_IFDIR else { throw AutomationError.corruptStore } + namespaces.append(name) + } + guard namespaces.count <= Self.maxFamilies else { throw AutomationError.corruptStore } + var ids: [String] = [] + for name in namespaces.sorted() { + let dir = try Posix.openChild(root, name, create: false, mode: 0o700) + defer { close(dir) } + let entries = try Self.boundedEntries(dir, limit: Self.maxFamilyFiles) + for entry in entries.sorted() { + guard Self.validFileName(entry), try Posix.kind(dir, entry) == S_IFREG else { throw AutomationError.corruptStore } + ids.append(name + "/" + entry) + } + } + return ids + } + + /// Reads only bounded routing headers to report declared content versions. This does not + /// read or verify payload bytes; `readRecord` must still validate contents before delivery. + public func recordVersions() throws -> [String: String] { + let identifiers = try recordIdentifiers() + guard !identifiers.isEmpty else { return [:] } + let root = try Posix.openDirectory(directoryURL, create: false, mode: 0o700) + defer { close(root) } + var versions: [String: String] = [:] + for identifier in identifiers { + try Task.checkCancellation() + // Identifiers were constructed from the validated ASCII namespace and record names above. + let parts = identifier.split(separator: "/").map(String.init) + let dir = try Posix.openChild(root, parts[0], create: false, mode: 0o700) + defer { close(dir) } + let fd = openat(dir, parts[1], O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard fd >= 0 else { throw AutomationError.corruptStore } + defer { close(fd) } + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, + info.st_size >= off_t(Self.prefixBytes), + info.st_size <= off_t(Self.prefixBytes + Self.maxHeaderBytes + Self.maxContentsBytes) + else { throw AutomationError.corruptStore } + let header = try Self.readHeader(fd: fd, fileSize: Int(info.st_size)) + guard parts[0] == Self.namespace(for: header.family), + parts[1] == Self.fileName(for: header.destination) else { throw AutomationError.corruptStore } + versions[identifier] = header.digest + } + return versions + } + + /// Reads one record through a single descriptor and revalidates its binding, size and digest. + public func readRecord(_ identifier: String) throws -> PluginFileRecord { + let parts = identifier.split(separator: "/", omittingEmptySubsequences: false).map(String.init) + guard identifier.utf8.count <= 128, parts.count == 2, Self.validNamespace(parts[0]), Self.validFileName(parts[1]) else { + throw AutomationError.corruptStore + } + let root: Int32 + do { root = try Posix.openDirectory(directoryURL, create: false, mode: 0o700) } + catch is Posix.Missing { throw AutomationError.corruptStore } + defer { close(root) } + let dir: Int32 + do { dir = try Posix.openChild(root, parts[0], create: false, mode: 0o700) } + catch is Posix.Missing { throw AutomationError.corruptStore } + defer { close(dir) } + let fd = openat(dir, parts[1], O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard fd >= 0 else { throw AutomationError.corruptStore } + defer { close(fd) } + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_size >= 0, + info.st_size <= off_t(Self.prefixBytes + Self.maxHeaderBytes + Self.maxContentsBytes) else { + throw AutomationError.corruptStore + } + let data = try Posix.readAll(fd, size: Int(info.st_size)) + guard data.count >= Self.prefixBytes else { throw AutomationError.corruptStore } + let n = try Self.headerLength(Array(data.prefix(Self.prefixBytes))) + guard data.count >= Self.prefixBytes + n else { throw AutomationError.corruptStore } + let header = try Self.parseHeader(data.subdata(in: Self.prefixBytes..<(Self.prefixBytes + n))) + let payload = data.subdata(in: (Self.prefixBytes + n).. [String] { + let copy = dup(dir) + guard copy >= 0 else { throw AutomationError.saveFailed } + guard let stream = fdopendir(copy) else { close(copy); throw AutomationError.saveFailed } + defer { closedir(stream) } + rewinddir(stream) + var names: [String] = [] + while true { + try Task.checkCancellation() + errno = 0 + guard let entry = readdir(stream) else { + guard errno == 0 else { throw AutomationError.saveFailed } + return names + } + let name = withUnsafePointer(to: &entry.pointee.d_name) { + $0.withMemoryRebound(to: CChar.self, capacity: Int(NAME_MAX) + 1) { String(cString: $0) } + } + guard name != ".", name != ".." else { continue } + guard names.count < limit else { throw AutomationError.corruptStore } + names.append(name) + } + } + + /// Removes only temporaries whose owner released its lock and that are old enough to rule out the + /// create-then-lock window of a live publisher. Only `.tmp-` regular files are ever removed. + private func sweepAbandonedTemporaries(_ root: Int32) { + let copy = dup(root) + guard copy >= 0 else { return } + guard let stream = fdopendir(copy) else { close(copy); return } + defer { closedir(stream) } + rewinddir(stream) + // Stream only a bounded number of entries: do not allocate an unbounded name list to recover a corrupt root. + for _ in 0..<4096 { + guard !Task.isCancelled, let entry = readdir(stream) else { return } + let name = withUnsafePointer(to: &entry.pointee.d_name) { + $0.withMemoryRebound(to: CChar.self, capacity: Int(NAME_MAX) + 1) { String(cString: $0) } + } + guard name.hasPrefix(Self.tempPrefix) else { continue } + let fd = openat(root, name, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard fd >= 0 else { continue } + defer { close(fd) } + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, + Date().timeIntervalSince1970 - Double(info.st_mtimespec.tv_sec) > Self.abandonedAge, + flock(fd, LOCK_EX | LOCK_NB) == 0 else { continue } + unlinkat(root, name, 0) + } + } +} diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFolderGrantStore.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFolderGrantStore.swift new file mode 100644 index 0000000..97bcc1c --- /dev/null +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginFolderGrantStore.swift @@ -0,0 +1,87 @@ +import Foundation + +/// App-only persistent folder authority; never available to the JS VM or tunnel extension. +public struct PluginFolderGrant: Equatable, Sendable { + public let bookmark: Data + public let rootIdentity: String + public let pathPrefix: String + public init(bookmark: Data, rootIdentity: String, pathPrefix: String = "") { + self.bookmark = bookmark + self.rootIdentity = rootIdentity + self.pathPrefix = pathPrefix + } +} + +public struct PluginFolderGrantStore: Sendable { + public enum StoreError: Error, Sendable { case invalidGrant } + private struct Entry { let family: String; let grant: PluginFolderGrant } + private let file: CatalogFile + private static let maxBytes = 2 * 1024 * 1024 + public init(url: URL) { file = CatalogFile(url: url) } + + public func grant(for family: String, prefix: String = "") throws -> PluginFolderGrant? { + try Self.decode(file.read(maximumBytes: Self.maxBytes))[Self.key(family, prefix)]?.grant + } + + public func set(_ grant: PluginFolderGrant, for family: String) throws { + guard Self.valid(family: family, grant: grant) else { throw StoreError.invalidGrant } + try file.locked { + var grants = try Self.decode(file.read(maximumBytes: Self.maxBytes)) + let entry = Entry(family: family, grant: grant) + guard !grants.values.contains(where: { Self.overlaps($0, entry) }) else { throw StoreError.invalidGrant } + grants[Self.key(family, grant.pathPrefix)] = entry + guard grants.count <= 32 else { throw AutomationError.limitExceeded } + let values = grants.mapValues { entry in + JSONValue.object(["family": .string(entry.family), "pathPrefix": .string(entry.grant.pathPrefix), + "bookmark": .string(entry.grant.bookmark.base64EncodedString()), + "rootIdentity": .string(entry.grant.rootIdentity)]) + } + let bytes = try JSONValue.object(["version": .integer(1), "grants": .object(values)]).data() + guard bytes.count <= Self.maxBytes else { throw AutomationError.limitExceeded } + try file.replace(with: bytes) + try file.synchronizeParentDirectory() + } + } + + private static func key(_ family: String, _ prefix: String) -> String { + Digest.sha256Hex(Data((family + "\n" + prefix).utf8)) + } + + private static func valid(family: String, grant: PluginFolderGrant) -> Bool { + let prefix = grant.pathPrefix + let validPrefix = prefix.isEmpty || (!prefix.unicodeScalars.contains("/") && + (try? PluginFileDestination(storage: .icloud, atPath: prefix)) != nil) + return validPrefix && InstallationIdentity.valid(family + "|" + String(repeating: "0", count: 64)) + && !grant.bookmark.isEmpty && grant.bookmark.count <= 64 * 1024 + && Digest.isHex64(grant.rootIdentity) + } + + private static func overlaps(_ lhs: Entry, _ rhs: Entry) -> Bool { + guard lhs.family == rhs.family else { return false } + let a = lhs.grant.pathPrefix, b = rhs.grant.pathPrefix + guard Data(a.utf8) != Data(b.utf8) else { return false } + return a.isEmpty || b.isEmpty || PluginFileDestination.foldedKey(a) == PluginFileDestination.foldedKey(b) + } + + private static func decode(_ data: Data?) throws -> [String: Entry] { + guard let data else { return [:] } + let document = try JSONFields(JSONValue(parsing: data), required: ["version", "grants"], error: .corruptStore) + guard try document.int("version") == 1, + case let .object(entries) = try document.value("grants"), entries.count <= 32 else { + throw AutomationError.corruptStore + } + var result: [String: Entry] = [:] + for (key, value) in entries { + let fields = try JSONFields(value, required: ["family", "pathPrefix", "bookmark", "rootIdentity"], error: .corruptStore) + let family = try fields.string("family") + guard let bookmark = try Data(base64Encoded: fields.string("bookmark")) else { throw AutomationError.corruptStore } + let grant = try PluginFolderGrant(bookmark: bookmark, rootIdentity: fields.string("rootIdentity"), + pathPrefix: fields.string("pathPrefix")) + let entry = Entry(family: family, grant: grant) + guard valid(family: family, grant: grant), key == Self.key(family, grant.pathPrefix), + !result.values.contains(where: { overlaps($0, entry) }) else { throw AutomationError.corruptStore } + result[key] = entry + } + return result + } +} diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginJSONFileProtection.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginJSONFileProtection.swift new file mode 100644 index 0000000..92714c1 --- /dev/null +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginJSONFileProtection.swift @@ -0,0 +1,79 @@ +import Darwin +import Foundation + +/// Learn Foundation's backup attributes on a private empty inode, then apply them by descriptor. +/// Response bytes and mutable Documents paths never participate in attribute discovery. +enum PluginJSONFileProtection { + private final class Template: @unchecked Sendable { + let attributes: [String: Data] + #if os(iOS) && !targetEnvironment(simulator) + let protectionClass: Int32 + #endif + + init() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("Interceptor-JSON-Protection-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, + attributes: [.posixPermissions: 0o700]) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("template") + let fd = open(url.path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard fd >= 0 else { throw AutomationError.saveFailed } + defer { close(fd) } + let original = try Self.readAttributes(fd) + try CatalogFile(url: url).protect() + attributes = try Self.readAttributes(fd).filter { original[$0.key] != $0.value } + guard !attributes.isEmpty else { throw AutomationError.saveFailed } + #if os(iOS) && !targetEnvironment(simulator) + let applied = try FileManager.default.attributesOfItem(atPath: url.path)[.protectionKey] as? String + guard applied == FileProtectionType.completeUntilFirstUserAuthentication.rawValue else { throw AutomationError.saveFailed } + protectionClass = fcntl(fd, F_GETPROTECTIONCLASS) + guard protectionClass > 0 else { throw AutomationError.saveFailed } + #endif + } + + static func readAttributes(_ fd: Int32) throws -> [String: Data] { + let length = flistxattr(fd, nil, 0, 0) + guard length >= 0, length <= 16 * 1024 else { throw AutomationError.saveFailed } + if length == 0 { return [:] } + var names = [CChar](repeating: 0, count: length) + guard flistxattr(fd, &names, names.count, 0) == length else { throw AutomationError.saveFailed } + var result: [String: Data] = [:] + for raw in names.split(separator: 0) { + let name = String(decoding: raw.map { UInt8(bitPattern: $0) }, as: UTF8.self) + let count = fgetxattr(fd, name, nil, 0, 0, 0) + guard count >= 0, count <= 64 * 1024 else { throw AutomationError.saveFailed } + var data = Data(count: count) + let read = data.withUnsafeMutableBytes { fgetxattr(fd, name, $0.baseAddress, count, 0, 0) } + guard read == count else { throw AutomationError.saveFailed } + result[name] = data + } + return result + } + } + + private static let lock = NSLock() + private nonisolated(unsafe) static var cachedTemplate: Template? + + private static func template() throws -> Template { + try lock.withLock { + if let cachedTemplate { return cachedTemplate } + let created = try Template() + cachedTemplate = created + return created + } + } + + static func apply(to fd: Int32) throws { + let template = try template() + for (name, bytes) in template.attributes { + let result = bytes.withUnsafeBytes { fsetxattr(fd, name, $0.baseAddress, bytes.count, 0, 0) } + guard result == 0 else { throw AutomationError.saveFailed } + } + #if os(iOS) && !targetEnvironment(simulator) + guard fcntl(fd, F_SETPROTECTIONCLASS, template.protectionClass) == 0, + fcntl(fd, F_GETPROTECTIONCLASS) == template.protectionClass else { throw AutomationError.saveFailed } + #endif + let actual = try Template.readAttributes(fd) + guard template.attributes.allSatisfy({ actual[$0.key] == $0.value }) else { throw AutomationError.saveFailed } + } +} diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginJSONFileStore.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginJSONFileStore.swift new file mode 100644 index 0000000..0de8815 --- /dev/null +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginJSONFileStore.swift @@ -0,0 +1,440 @@ +import CryptoKit +import Darwin +import Foundation + +/// Durable store for original plugin JSON text, published into `//.json`. +/// +/// Every path component below the root is opened descriptor-relative with `O_NOFOLLOW`; entries that are +/// not regular files/directories fail closed. The caller prepares outside the activation fence +/// (`prepare`) and publishes inside it (`PreparedWrite.commit`). Commit takes the storage lock +/// non-blockingly and does no abandoned-temporary sweeping (that happens in `prepare`). +public struct PluginJSONFileStore: Sendable { + public static let maxKeyBytes = 1024 + public static let maxJSONBytes = 1024 * 1024 + public static let maxNamespaceBytes = 64 * 1024 * 1024 + public static let maxNamespaceFiles = 2048 + public static let maxNamespaces = 16 + public static let maxTotalBytes = 256 * 1024 * 1024 + + public enum StoreError: Error, Equatable, Sendable { + /// Another publisher holds the storage lock; the caller may retry on a later capture. + case busy + /// The permission, revision or package binding is invalid. + case notPermitted + /// The prepared write was already committed or discarded. + case consumed + } + + private static let tempPrefix = ".tmp-" + fileprivate static let chunk = 64 * 1024 + private static let abandonedAge: TimeInterval = 300 + + public let directoryURL: URL + public init(directoryURL: URL) { self.directoryURL = directoryURL } + + /// Convenience: prepare then commit. + public func save(revisionID: String, package: PluginPackage, key: String, jsonText: String, + checkAuthorization: @Sendable () throws -> Void = {}) throws { + try prepare(revisionID: revisionID, package: package, key: key, jsonText: jsonText) + .commit(checkAuthorization: checkAuthorization) + } + + /// Validates, then writes a protected, fsynced temporary file. Nothing is visible to readers until commit. + public func prepare(revisionID: String, package: PluginPackage, key: String, jsonText: String) throws -> PreparedWrite { + guard InstallationIdentity.valid(revisionID, package: package), package.manifest.writeFiles else { + throw StoreError.notPermitted + } + let keyBytes = key.utf8.count + guard (1...Self.maxKeyBytes).contains(keyBytes), !key.utf8.contains(0) else { throw AutomationError.limitExceeded } + let bytes = Array(jsonText.utf8) + guard bytes.count <= Self.maxJSONBytes else { throw AutomationError.limitExceeded } + try PluginJSONSyntax.validate(bytes) + + let family = InstallationIdentity.family(revisionID) + let uuidPart = String(family.split(separator: "|").last ?? "").lowercased() + let namespace = String(uuidPart.prefix(8)) + "-" + String(Digest.sha256Hex(Data(family.utf8)).prefix(40)) + let fileName = Digest.sha256Hex(Data(key.utf8)) + ".json" + + let root = try Posix.openDirectory(directoryURL, create: true, mode: 0o700) + defer { close(root) } + try Posix.protect(root, url: directoryURL) + // Sweep outside the activation fence; skipped when a publisher holds the root lock. + if flock(root, LOCK_EX | LOCK_NB) == 0 { + sweepAbandonedTemporaries(root) + flock(root, LOCK_UN) + } + let temp = try Posix.writeProtectedTemp(directoryFD: root, directoryURL: directoryURL, + prefix: Self.tempPrefix, data: Data(bytes), checkCancellation: true) + return PreparedWrite(store: self, namespace: namespace, fileName: fileName, tempName: temp.name, + fd: temp.fd, size: bytes.count) + } + + /// Mirrors committed files into `directoryURL`. Source-only: never reads exported copies, never deletes. + public func export(to destinationURL: URL) throws { + let source: Int32 + do { source = try Posix.openDirectory(directoryURL, create: false, mode: 0o700) } + catch is Posix.Missing { return } + defer { close(source) } + let destination = try Posix.openDirectory(destinationURL, create: true, mode: 0o755) + defer { close(destination) } + + // Validate the whole source tree before writing anything. + var plan: [(namespace: String, files: [String])] = [] + for name in try Posix.list(source) where !name.hasPrefix(Self.tempPrefix) { + guard try Posix.kind(source, name) == S_IFDIR else { throw AutomationError.corruptStore } + let dir = try Posix.openChild(source, name, create: false, mode: 0o700) + defer { close(dir) } + var files: [String] = [] + for file in try Posix.list(dir) { + guard try Posix.kind(dir, file) == S_IFREG else { throw AutomationError.corruptStore } + files.append(file) + } + plan.append((name, files)) + } + // Per-entry failures do not stop other entries; the first one is reported at the end. + var firstError: Error? + func record(_ error: Error) throws { + if error is CancellationError { throw error } + if firstError == nil { firstError = error } + } + for (namespace, files) in plan { + do { + let from = try Posix.openChild(source, namespace, create: false, mode: 0o700) + defer { close(from) } + let namespaceURL = destinationURL.appendingPathComponent(namespace) + let to = try Posix.openChild(destination, namespace, create: true, mode: 0o755) + defer { close(to) } + try Posix.protect(to, url: namespaceURL) + for file in files { + try Task.checkCancellation() + do { try exportFile(file, from: from, to: to, namespaceURL: namespaceURL) } + catch { try record(error) } + } + } catch { try record(error) } + } + if let firstError { throw firstError } + } + + private func exportFile(_ file: String, from: Int32, to: Int32, namespaceURL: URL) throws { + let fd = openat(from, file, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard fd >= 0 else { throw AutomationError.saveFailed } + defer { close(fd) } + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, + info.st_size >= 0, info.st_size <= off_t(Self.maxJSONBytes) else { throw AutomationError.corruptStore } + let size = Int(info.st_size) + if try Posix.existingSize(to, file) == size { + let current = openat(to, file, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + if current >= 0 { + defer { close(current) } + if try Posix.equal(current, fd, size: size) { + try Posix.protect(current, url: namespaceURL.appendingPathComponent(file)) + return + } + } + } + let data = try Posix.readAll(fd, size: size) + let temp = try Posix.writeProtectedTemp(directoryFD: to, directoryURL: namespaceURL, + prefix: Self.tempPrefix, data: data, checkCancellation: false) + defer { close(temp.fd) } + guard renameat(to, temp.name, to, file) == 0 else { + unlinkat(to, temp.name, 0) + throw AutomationError.saveFailed + } + guard fsync(to) == 0 else { throw AutomationError.saveFailed } + } + + /// A validated, protected, fsynced temporary file owned by this object. Commit or discard exactly once; + /// dropping it removes the temporary file. Holds an exclusive `flock` on the temp so a concurrent + /// publisher's sweep never removes it. + public final class PreparedWrite: @unchecked Sendable { + fileprivate let store: PluginJSONFileStore + fileprivate let namespace: String, fileName: String, tempName: String, size: Int + private let lock = NSLock() + private var fd: Int32 + + fileprivate init(store: PluginJSONFileStore, namespace: String, fileName: String, + tempName: String, fd: Int32, size: Int) { + self.store = store; self.namespace = namespace; self.fileName = fileName + self.tempName = tempName; self.fd = fd; self.size = size + } + deinit { discard() } + + /// Removes the temporary file. Safe to call repeatedly. + public func discard() { + lock.lock(); defer { lock.unlock() } + releaseLocked() + } + + private func releaseLocked() { + guard fd >= 0 else { return } + if let root = try? Posix.openDirectory(store.directoryURL, create: false, mode: 0o700) { + if Posix.sameFile(root, tempName, fd) { unlinkat(root, tempName, 0) } + close(root) + } + close(fd) + fd = -1 + } + + /// `checkAuthorization` runs once, after every fallible preparation step and immediately before + /// publication. Once it returns, a later cancellation may leave the committed file in place. + public func commit(checkAuthorization: @Sendable () throws -> Void = {}) throws { + lock.lock(); defer { lock.unlock() } + guard fd >= 0 else { throw StoreError.consumed } + defer { releaseLocked() } + try store.publish(self, fd: fd, checkAuthorization: checkAuthorization) + } + } + + fileprivate func publish(_ write: PreparedWrite, fd tempFD: Int32, + checkAuthorization: @Sendable () throws -> Void) throws { + let root = try Posix.openDirectory(directoryURL, create: false, mode: 0o700) + defer { close(root) } + guard flock(root, LOCK_EX | LOCK_NB) == 0 else { + let contended = errno == EWOULDBLOCK + if contended { throw StoreError.busy } + throw AutomationError.saveFailed + } + defer { flock(root, LOCK_UN) } + guard Posix.sameFile(root, write.tempName, tempFD) else { throw AutomationError.saveFailed } + + var namespaces: [String] = [] + for name in try Posix.list(root) where !name.hasPrefix(Self.tempPrefix) { + guard try Posix.kind(root, name) == S_IFDIR else { throw AutomationError.corruptStore } + namespaces.append(name) + } + var total = 0 + var own = (files: 0, bytes: 0) + for name in namespaces { + let dir = try Posix.openChild(root, name, create: false, mode: 0o700) + defer { close(dir) } + let usage = try Self.usage(dir) + total += usage.bytes + if name == write.namespace { own = usage } + } + let exists = namespaces.contains(write.namespace) + guard exists || namespaces.count < Self.maxNamespaces else { throw AutomationError.limitExceeded } + + var previousSize: Int? + if exists { + let dir = try Posix.openChild(root, write.namespace, create: false, mode: 0o700) + defer { close(dir) } + previousSize = try Posix.existingSize(dir, write.fileName) + } + let newFiles = own.files + (previousSize == nil ? 1 : 0) + let ownBytes = own.bytes - (previousSize ?? 0) + write.size + let totalBytes = total - (previousSize ?? 0) + write.size + guard newFiles <= Self.maxNamespaceFiles, ownBytes <= Self.maxNamespaceBytes, + totalBytes <= Self.maxTotalBytes else { throw AutomationError.limitExceeded } + + // A denied save must not leave an empty namespace that consumes quota. + if !exists { try checkAuthorization() } + let dir = try Posix.openChild(root, write.namespace, create: true, mode: 0o700) + defer { close(dir) } + var committed = false + defer { if !exists && !committed { unlinkat(root, write.namespace, AT_REMOVEDIR) } } + let namespaceURL = directoryURL.appendingPathComponent(write.namespace) + if !exists { + try Posix.protect(dir, url: namespaceURL) + guard fsync(root) == 0 else { throw AutomationError.saveFailed } + } + + if previousSize == write.size { + let current = openat(dir, write.fileName, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + if current >= 0 { + defer { close(current) } + if try Posix.equal(current, tempFD, size: write.size) { + // Identical retry: still restore protection and make the visible bytes durable. + try checkAuthorization() + try Posix.protect(current, url: namespaceURL.appendingPathComponent(write.fileName)) + committed = true + guard fsync(current) == 0, fsync(dir) == 0 else { throw AutomationError.saveFailed } + return + } + } + } + try checkAuthorization() + guard renameat(root, write.tempName, dir, write.fileName) == 0 else { throw AutomationError.saveFailed } + committed = true + // Bytes are now visible; a sync failure is reported without rolling them back. + guard fsync(dir) == 0, fsync(root) == 0 else { throw AutomationError.saveFailed } + } + + private static func usage(_ dir: Int32) throws -> (files: Int, bytes: Int) { + var files = 0, bytes = 0 + for name in try Posix.list(dir) { + var info = stat() + guard fstatat(dir, name, &info, AT_SYMLINK_NOFOLLOW) == 0, info.st_mode & S_IFMT == S_IFREG + else { throw AutomationError.corruptStore } + files += 1 + bytes += Int(info.st_size) + } + return (files, bytes) + } + + /// Removes only temporaries whose owner released its lock and that are old enough to rule out the + /// create-then-lock window of a live publisher. Only `.tmp-` regular files are ever removed. + private func sweepAbandonedTemporaries(_ root: Int32) { + guard let names = try? Posix.list(root) else { return } + for name in names where name.hasPrefix(Self.tempPrefix) { + let fd = openat(root, name, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard fd >= 0 else { continue } + defer { close(fd) } + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, + Date().timeIntervalSince1970 - Double(info.st_mtimespec.tv_sec) > Self.abandonedAge, + flock(fd, LOCK_EX | LOCK_NB) == 0 else { continue } + unlinkat(root, name, 0) + } + } +} + +/// Descriptor-relative POSIX helpers. +enum Posix { + struct Missing: Error {} + + static func list(_ dir: Int32) throws -> [String] { + let copy = dup(dir) + guard copy >= 0, let stream = fdopendir(copy) else { + if copy >= 0 { close(copy) } + throw AutomationError.saveFailed + } + defer { closedir(stream) } + rewinddir(stream) + var names: [String] = [] + while let entry = readdir(stream) { + let name = withUnsafePointer(to: &entry.pointee.d_name) { + $0.withMemoryRebound(to: CChar.self, capacity: Int(NAME_MAX) + 1) { String(cString: $0) } + } + if name != "." && name != ".." { names.append(name) } + } + return names + } + + /// File type bits of `name` without following links. + static func kind(_ dir: Int32, _ name: String) throws -> mode_t { + var info = stat() + guard fstatat(dir, name, &info, AT_SYMLINK_NOFOLLOW) == 0 else { throw AutomationError.corruptStore } + return info.st_mode & S_IFMT + } + + /// Size of a regular file, nil when absent; anything else fails closed. + static func existingSize(_ dir: Int32, _ name: String) throws -> Int? { + var info = stat() + guard fstatat(dir, name, &info, AT_SYMLINK_NOFOLLOW) == 0 else { + if errno == ENOENT { return nil } + throw AutomationError.saveFailed + } + guard info.st_mode & S_IFMT == S_IFREG else { throw AutomationError.corruptStore } + return Int(info.st_size) + } + + static func sameFile(_ dir: Int32, _ name: String, _ fd: Int32) -> Bool { + var a = stat(), b = stat() + return fstatat(dir, name, &a, AT_SYMLINK_NOFOLLOW) == 0 && fstat(fd, &b) == 0 + && a.st_dev == b.st_dev && a.st_ino == b.st_ino && a.st_mode & S_IFMT == S_IFREG + } + + /// Apply attributes to the opened inode; `url` is retained only for caller compatibility. + static func protect(_ fd: Int32, url _: URL) throws { + try PluginJSONFileProtection.apply(to: fd) + } + + static func openChild(_ parent: Int32, _ name: String, create: Bool, mode: mode_t) throws -> Int32 { + let flags = O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC + var fd = openat(parent, name, flags) + if fd < 0, errno == ENOENT { + guard create else { throw Missing() } + if mkdirat(parent, name, mode) == 0 { guard fsync(parent) == 0 else { throw AutomationError.saveFailed } } + else if errno != EEXIST { throw AutomationError.saveFailed } + fd = openat(parent, name, flags) + } + guard fd >= 0 else { throw AutomationError.saveFailed } + return fd + } + + /// The trusted prefix of `url` (app-provided, may traverse system links) is resolved once; the final + /// component and anything created below it are never followed. + static func openDirectory(_ url: URL, create: Bool, mode: mode_t) throws -> Int32 { + let target = url.standardizedFileURL + var base = target.deletingLastPathComponent() + var missing: [String] = [] + while !FileManager.default.fileExists(atPath: base.path), base.path != "/" { + missing.insert(base.lastPathComponent, at: 0) + base = base.deletingLastPathComponent() + } + guard missing.isEmpty || create else { throw Missing() } + guard let resolved = realpath(base.path, nil) else { throw AutomationError.saveFailed } + defer { free(resolved) } + var fd = open(resolved, O_RDONLY | O_DIRECTORY | O_CLOEXEC) + guard fd >= 0 else { throw AutomationError.saveFailed } + for name in missing + [target.lastPathComponent] { + let next: Int32 + do { next = try openChild(fd, name, create: create, mode: mode) } catch { close(fd); throw error } + close(fd) + fd = next + } + return fd + } + + /// Creates `` exclusively in `directoryFD` (0600), locks it, applies protection and backup + /// exclusion before any bytes are written, then writes in chunks and fsyncs. Returns the locked fd. + static func writeProtectedTemp(directoryFD: Int32, directoryURL: URL, prefix: String, data: Data, + checkCancellation: Bool) throws -> (fd: Int32, name: String) { + let name = prefix + UUID().uuidString + let fd = openat(directoryFD, name, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard fd >= 0 else { throw AutomationError.saveFailed } + do { + guard flock(fd, LOCK_EX | LOCK_NB) == 0, fchmod(fd, 0o600) == 0 else { throw AutomationError.saveFailed } + try protect(fd, url: directoryURL.appendingPathComponent(name)) + var offset = 0 + while offset < data.count { + if checkCancellation { try Task.checkCancellation() } + let n = min(PluginJSONFileStore.chunkBytes, data.count - offset) + let written = data.withUnsafeBytes { write(fd, $0.baseAddress! + offset, n) } + guard written > 0 else { throw AutomationError.saveFailed } + offset += written + } + guard fsync(fd) == 0 else { throw AutomationError.saveFailed } + return (fd, name) + } catch { + unlinkat(directoryFD, name, 0) + close(fd) + throw error + } + } + + static func readAll(_ fd: Int32, size: Int) throws -> Data { + var out = Data(count: size) + var offset = 0 + try out.withUnsafeMutableBytes { buffer in + while offset < size { + let n = pread(fd, buffer.baseAddress! + offset, size - offset, off_t(offset)) + guard n > 0 else { throw AutomationError.corruptStore } + offset += n + } + } + return out + } + + /// Chunked comparison of two regular files of known `size` without loading either whole. + static func equal(_ a: Int32, _ b: Int32, size: Int) throws -> Bool { + var one = [UInt8](repeating: 0, count: PluginJSONFileStore.chunkBytes) + var two = one + var info = stat() + guard fstat(a, &info) == 0, info.st_mode & S_IFMT == S_IFREG, Int(info.st_size) == size else { return false } + var offset = 0 + while offset < size { + let want = min(one.count, size - offset) + let x = pread(a, &one, want, off_t(offset)), y = pread(b, &two, want, off_t(offset)) + guard x == want, y == want else { return false } + if one[0..= 3, b[0] == 0xEF, b[1] == 0xBB, b[2] == 0xBF { throw AutomationError.invalidJSON } + skipWS() + try value(depth: 0) + skipWS() + guard i == b.count else { throw AutomationError.invalidJSON } + } + + mutating func skipWS() { + while i < b.count, b[i] == 0x20 || b[i] == 0x09 || b[i] == 0x0A || b[i] == 0x0D { i += 1 } + } + + mutating func value(depth: Int) throws { + guard i < b.count else { throw AutomationError.invalidJSON } + switch b[i] { + case UInt8(ascii: "{"): try object(depth: depth + 1) + case UInt8(ascii: "["): try array(depth: depth + 1) + case UInt8(ascii: "\""): _ = try string(collect: false) + case UInt8(ascii: "t"): try literal("true") + case UInt8(ascii: "f"): try literal("false") + case UInt8(ascii: "n"): try literal("null") + default: try number() + } + } + + mutating func literal(_ s: String) throws { + let u = Array(s.utf8) + guard i + u.count <= b.count, Array(b[i..() + while true { + skipWS() + guard i < b.count, b[i] == UInt8(ascii: "\"") else { throw AutomationError.invalidJSON } + let key = try string(collect: true) + skipWS() + guard i < b.count, b[i] == UInt8(ascii: ":") else { throw AutomationError.invalidJSON } + i += 1 + skipWS() + try value(depth: depth) + guard keys.insert(key).inserted else { throw AutomationError.duplicateKey } + skipWS() + guard i < b.count else { throw AutomationError.invalidJSON } + if b[i] == UInt8(ascii: ",") { i += 1; continue } + if b[i] == UInt8(ascii: "}") { i += 1; return } + throw AutomationError.invalidJSON + } + } + + mutating func hex4() throws -> UInt32 { + guard i + 4 <= b.count else { throw AutomationError.invalidJSON } + var v: UInt32 = 0 + for _ in 0..<4 { + let c = b[i] + let d: UInt32 + switch c { + case 0x30...0x39: d = UInt32(c - 0x30) + case 0x41...0x46: d = UInt32(c - 0x41 + 10) + case 0x61...0x66: d = UInt32(c - 0x61 + 10) + default: throw AutomationError.invalidJSON + } + v = v << 4 | d + i += 1 + } + return v + } + + /// Input originates from a Swift `String`, so raw multi-byte sequences are already valid UTF-8. + /// Only keys are collected (unescaped) for duplicate detection. + mutating func string(collect: Bool) throws -> [UInt8] { + i += 1 + var out = [UInt8]() + while true { + guard i < b.count else { throw AutomationError.invalidJSON } + let c = b[i] + switch c { + case UInt8(ascii: "\""): + i += 1 + return out + case 0..<0x20: throw AutomationError.invalidJSON + case UInt8(ascii: "\\"): + i += 1 + guard i < b.count else { throw AutomationError.invalidJSON } + let e = b[i] + i += 1 + let unescaped: [UInt8] + switch e { + case UInt8(ascii: "\""): unescaped = [0x22] + case UInt8(ascii: "\\"): unescaped = [0x5C] + case UInt8(ascii: "/"): unescaped = [0x2F] + case UInt8(ascii: "b"): unescaped = [0x08] + case UInt8(ascii: "f"): unescaped = [0x0C] + case UInt8(ascii: "n"): unescaped = [0x0A] + case UInt8(ascii: "r"): unescaped = [0x0D] + case UInt8(ascii: "t"): unescaped = [0x09] + case UInt8(ascii: "u"): + var cp = try hex4() + if (0xD800...0xDBFF).contains(cp) { + guard i + 1 < b.count, b[i] == 0x5C, b[i + 1] == UInt8(ascii: "u") else { throw AutomationError.invalidJSON } + i += 2 + let low = try hex4() + guard (0xDC00...0xDFFF).contains(low) else { throw AutomationError.invalidJSON } + cp = 0x10000 + ((cp - 0xD800) << 10) + (low - 0xDC00) + } else if (0xDC00...0xDFFF).contains(cp) { + throw AutomationError.invalidJSON + } + guard let scalar = Unicode.Scalar(cp) else { throw AutomationError.invalidJSON } + unescaped = collect ? Array(String(Character(scalar)).utf8) : [] + default: throw AutomationError.invalidJSON + } + if collect { out += unescaped } + default: + if collect { out.append(c) } + i += 1 + } + } + } + + mutating func number() throws { + func isDigit(_ k: Int) -> Bool { k < b.count && b[k] >= 0x30 && b[k] <= 0x39 } + let start = i + if i < b.count, b[i] == UInt8(ascii: "-") { i += 1 } + guard isDigit(i) else { throw AutomationError.invalidJSON } + if b[i] == 0x30 { i += 1 } else { while isDigit(i) { i += 1 } } + if i < b.count, b[i] == UInt8(ascii: ".") { + i += 1 + guard isDigit(i) else { throw AutomationError.invalidJSON } + while isDigit(i) { i += 1 } + } + if i < b.count, b[i] == UInt8(ascii: "e") || b[i] == UInt8(ascii: "E") { + i += 1 + if i < b.count, b[i] == UInt8(ascii: "+") || b[i] == UInt8(ascii: "-") { i += 1 } + guard isDigit(i) else { throw AutomationError.invalidJSON } + while isDigit(i) { i += 1 } + } + // Same finite-Double rule as StrictJSON; the original spelling is still what gets stored. + guard let d = Double(String(decoding: b[start...fromOpaque(opaque).takeUnretainedValue() + guard let create = context.createFile else { return 1 } + let job = context.job + if job.isCancelled { + return 2 + } + guard let kind = PluginFileStorage(rawValue: String(decoding: UnsafeBufferPointer(start: storage, count: storageLength), as: UTF8.self)), + let destination = try? PluginFileDestination( + storage: kind, + atPath: String(decoding: UnsafeBufferPointer(start: path, count: pathLength), as: UTF8.self), + ) else { return 1 } + let data: Data + if let contents { data = Data(bytes: contents, count: contentsLength) } + else { data = Data() } // the guard above admits a nil pointer only for an empty payload + + let done = DispatchSemaphore(value: 0) + let box = CreateBox() + let task = Task { + do { try await create(destination, data) } catch { box.error = error } + done.signal() + } + job.install(task) + var timedOut = false + if done.wait(timeout: .now() + .milliseconds(Int(timeoutMs) + 250)) == .timedOut { + timedOut = true + task.cancel() + done.wait() + } + job.clearTask() + if job.isCancelled { + return 2 + } + // A callback timeout is always a failure, even if the host committed after the cancel; the write is retained. + if timedOut { return 1 } + guard let error = box.error else { return 0 } + return error is CancellationError ? 2 : 1 +} + +private final class CreateBox: @unchecked Sendable { + var error: Error? // written before the semaphore signal +} + private final class ResultBox: @unchecked Sendable { var value: Result? // written before the semaphore signal } @@ -155,12 +208,16 @@ public final class JavaScriptFetchExecutor: @unchecked Sendable { /// Trusted host transport: honor the request deadline and Task cancellation, and finish owned /// I/O before returning. The callback waits for completion so no socket outlives the invocation. public typealias Transport = @Sendable (JavaScriptFetchRequest) async throws -> JavaScriptFetchResponse + /// Trusted host write for `Interceptor.createFile`; the destination structure and raw contents were validated natively (Core validates NFC and aliases). + /// Honor Task cancellation and finish all owned I/O before returning; a thrown error rejects the script's promise. + public typealias CreateFile = @Sendable (PluginFileDestination, Data) async throws -> Void private static let globalLock = NSLock() private nonisolated(unsafe) static var globalActive = 0 private static let globalSlots = 2 private static let stackBytes = 2 * 1024 * 1024 static let cpuDeadlineMilliseconds = 250 + static let filesCpuDeadlineMilliseconds = 1000 private let lock = NSLock() private var current: FetchJob? @@ -168,7 +225,7 @@ public final class JavaScriptFetchExecutor: @unchecked Sendable { public init() {} public func runV2(packageJSON: Data, hook: JavaScriptHook, eventJSON: Data, configJSON: Data, - transport: @escaping Transport) async throws -> Data + createFile: CreateFile? = nil, transport: @escaping Transport) async throws -> Data { guard hook == .responseLeave, !packageJSON.isEmpty, packageJSON.count <= JavaScriptLimits.maxPackageBytes, @@ -191,7 +248,7 @@ public final class JavaScriptFetchExecutor: @unchecked Sendable { let thread = Thread { let outcome = Result { try Self.execute(job: job, package: packageJSON, hook: hookName, event: eventJSON, - config: configJSON, transport: transport) + config: configJSON, createFile: createFile, transport: transport) } // Release admission (instance and global) before resuming the caller. self.release(job) @@ -244,14 +301,14 @@ public final class JavaScriptFetchExecutor: @unchecked Sendable { } private static func execute(job: FetchJob, package: Data, hook: String, event: Data, config: Data, - transport: @escaping Transport) throws -> Data + createFile: CreateFile?, transport: @escaping Transport) throws -> Data { do { guard case .object = try JSONValue(parsing: event), case .object = try JSONValue(parsing: config) else { throw JavaScriptExecutionError.invalidInput } } catch { throw JavaScriptExecutionError.invalidInput } var limits = QJSLimits( - deadline_ms: cpuDeadlineMilliseconds, + deadline_ms: createFile == nil ? cpuDeadlineMilliseconds : filesCpuDeadlineMilliseconds, heap_bytes: JavaScriptLimits.heapBytes, stack_bytes: JavaScriptLimits.stackBytes, max_source_bytes: JavaScriptLimits.maxSourceBytes, @@ -261,14 +318,14 @@ public final class JavaScriptFetchExecutor: @unchecked Sendable { max_result_depth: JavaScriptLimits.maxResultDepth, max_actions: JavaScriptLimits.maxActions, ) - let context = FetchContext(job: job, transport: transport) + let context = FetchContext(job: job, transport: transport, createFile: createFile) let token = job.nativeToken var result = withExtendedLifetime(context) { let opaque = Unmanaged.passUnretained(context).toOpaque() return package.withUnsafeBytes { pkg in event.withUnsafeBytes { ev in config.withUnsafeBytes { cfg in - qjs_run_v2_fetch(token, &limits, fetchCallback, opaque, + qjs_run_v2_fetch_files(token, &limits, fetchCallback, opaque, context.createFile == nil ? nil : createFileCallback, opaque, pkg.baseAddress?.assumingMemoryBound(to: UInt8.self), pkg.count, hook, ev.baseAddress?.assumingMemoryBound(to: UInt8.self), ev.count, cfg.baseAddress?.assumingMemoryBound(to: UInt8.self), cfg.count) diff --git a/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c b/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c index 6f88f8e..ea452cb 100644 --- a/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c +++ b/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c @@ -123,6 +123,14 @@ typedef struct RunState { uint64_t wall_deadline_ns; // 0 when not in fetch mode unsigned nrequests; size_t response_total; + // createFile (qjs_run_v2_fetch_files and the scheduling probe): schema 2 `write.files` grant, separate budgets. + int write_files; + int files_exposed; // Interceptor.createFile is installed; Storage is present for all schema-2 sources + QJSCreateFileCallback create_cb; + void *create_opaque; + unsigned nwrites; + size_t write_total; + JSClassID cls_u8, cls_abuf; // pristine Uint8Array / ArrayBuffer classes (files-exposed runs only) int nout; OutDecl out[MAX_OUT]; Intent *intents; @@ -270,21 +278,40 @@ typedef struct { uint8_t *arena; // decoded keys; decoded length never exceeds raw length, so input_len suffices size_t arena_used; int max_depth; + RunState *st; // optional: polled for cancel/CPU/wall budget; NULL = unbudgeted + unsigned tick; + int aborted; // sticky: budget exhausted mid-scan (st->stop says why) } Scan; -static uint32_t fnv1a(const uint8_t *p, size_t n) { +// Cheap periodic budget poll for per-byte/per-probe loops. Returns 1 once the budget is exhausted (sticky). +#define SCAN_POLL_MASK 255u +static int scan_tick(Scan *s) { + if (s->aborted) return 1; + if (s->st && (++s->tick & SCAN_POLL_MASK) == 0 && budget_exceeded(s->st)) s->aborted = 1; + return s->aborted; +} + +static uint32_t fnv1a(Scan *s, const uint8_t *p, size_t n) { uint32_t h = 2166136261u; - for (size_t i = 0; i < n; i++) { h ^= p[i]; h *= 16777619u; } + for (size_t i = 0; i < n; i++) { + if (scan_tick(s)) break; + h ^= p[i]; h *= 16777619u; + } return h; } -static int keyset_grow_slots(KeySet *ks) { +// 1 = ok, 0 = out of memory, -2 = budget exhausted +static int keyset_grow_slots(Scan *sc, KeySet *ks) { size_t cap = ks->slot_cap ? ks->slot_cap * 2 : 16; uint32_t *slots = calloc(cap, sizeof(uint32_t)); if (!slots) return 0; for (size_t i = 0; i < ks->n; i++) { + if (scan_tick(sc)) { free(slots); return -2; } size_t j = ks->recs[i].hash & (cap - 1); - while (slots[j]) j = (j + 1) & (cap - 1); + while (slots[j]) { + if (scan_tick(sc)) { free(slots); return -2; } + j = (j + 1) & (cap - 1); + } slots[j] = (uint32_t)(i + 1); } free(ks->slots); @@ -293,12 +320,17 @@ static int keyset_grow_slots(KeySet *ks) { return 1; } -// 1 = added, 0 = duplicate, -1 = out of memory +// 1 = added, 0 = duplicate, -1 = out of memory, -2 = budget exhausted static int keyset_add(Scan *s, KeySet *ks, uint32_t off, uint32_t len) { - uint32_t h = fnv1a(s->arena + off, len); - if ((ks->n + 1) * 2 > ks->slot_cap && !keyset_grow_slots(ks)) return -1; + uint32_t h = fnv1a(s, s->arena + off, len); + if (s->aborted) return -2; + if ((ks->n + 1) * 2 > ks->slot_cap) { + int g = keyset_grow_slots(s, ks); + if (g != 1) return g == -2 ? -2 : -1; + } size_t j = h & (ks->slot_cap - 1); while (ks->slots[j]) { + if (scan_tick(s)) return -2; KeyRec *r = &ks->recs[ks->slots[j] - 1]; if (r->hash == h && r->len == len && memcmp(s->arena + r->off, s->arena + off, len) == 0) return 0; j = (j + 1) & (ks->slot_cap - 1); @@ -323,7 +355,10 @@ static void keyset_free(KeySet *ks) { } static void skip_ws(Scan *s) { - while (s->p < s->end && (*s->p == ' ' || *s->p == '\t' || *s->p == '\n' || *s->p == '\r')) s->p++; + while (s->p < s->end && (*s->p == ' ' || *s->p == '\t' || *s->p == '\n' || *s->p == '\r')) { + if (scan_tick(s)) return; + s->p++; + } } static int hexval(int c) { @@ -364,7 +399,7 @@ static int scan_string(Scan *s, int want_key, uint32_t *off, uint32_t *len) { size_t start = s->arena_used; s->p++; for (;;) { - if (s->p >= s->end) return 0; + if (s->p >= s->end || scan_tick(s)) return 0; uint8_t c = *s->p; if (c == '"') { s->p++; break; } if (c < 0x20) return 0; @@ -419,18 +454,18 @@ static int scan_number(Scan *s) { if (*q == '-') q++; if (q >= s->end) return 0; if (*q == '0') q++; - else if (*q >= '1' && *q <= '9') { while (is_digit(q, s->end)) q++; } + else if (*q >= '1' && *q <= '9') { while (is_digit(q, s->end)) { if (scan_tick(s)) return 0; q++; } } else return 0; if (q < s->end && *q == '.') { q++; if (!is_digit(q, s->end)) return 0; - while (is_digit(q, s->end)) q++; + while (is_digit(q, s->end)) { if (scan_tick(s)) return 0; q++; } } if (q < s->end && (*q == 'e' || *q == 'E')) { q++; if (q < s->end && (*q == '+' || *q == '-')) q++; if (!is_digit(q, s->end)) return 0; - while (is_digit(q, s->end)) q++; + while (is_digit(q, s->end)) { if (scan_tick(s)) return 0; q++; } } if (isinf(strtod((const char *)s->p, NULL))) return 0; s->p = q; @@ -446,7 +481,7 @@ static int scan_literal(Scan *s, const char *lit) { static int scan_value(Scan *s, int depth) { skip_ws(s); - if (s->p >= s->end) return 0; + if (s->p >= s->end || s->aborted) return 0; switch (*s->p) { case '{': { if (depth + 1 > s->max_depth) return 0; @@ -497,21 +532,31 @@ static int scan_value(Scan *s, int depth) { } } -// `z` must be NUL-terminated at z[len]. -static int json_check(const uint8_t *z, size_t len, int max_depth) { +// `z` must be NUL-terminated at z[len]. With `st`, the scan polls the run's cancel/CPU/wall budget and fails +// (leaving st->stop set) once it is exhausted; a final check also covers the tail between polls. +static int json_check_budgeted(const uint8_t *z, size_t len, int max_depth, RunState *st) { Scan s; s.p = z; s.end = z + len; s.arena = malloc(len + 1); s.arena_used = 0; s.max_depth = max_depth; + s.st = st; + s.tick = 0; + s.aborted = 0; if (!s.arena) return 0; int ok = scan_value(&s, 0); if (ok) { skip_ws(&s); ok = (s.p == s.end); } free(s.arena); + if (s.aborted) ok = 0; + if (ok && st && budget_exceeded(st)) ok = 0; return ok; } +static int json_check(const uint8_t *z, size_t len, int max_depth) { + return json_check_budgeted(z, len, max_depth, NULL); +} + static uint8_t *copy_z(const uint8_t *p, size_t n) { uint8_t *q = malloc(n + 1); if (!q) return NULL; @@ -1813,12 +1858,12 @@ static int load_manifest(RunState *st, JSContext *ctx, JSValueConst root, int *w static const char *const mk[] = {"schemaVersion", "id", "name", "version", "matches", "read", "write", "endpointBindings", "settings", "author", "summary", "category", "publishedAt", "outbound"}; - static const char *const wk[] = {"requestBody", "responseBody"}; - JSValue f[14], w[2]; + static const char *const wk[] = {"requestBody", "responseBody", "files"}; + JSValue f[14], w[3]; Str s = {NULL, 0}, *bind = NULL; size_t nbind = 0; int ok = 0; - w[0] = w[1] = JS_UNDEFINED; + w[0] = w[1] = w[2] = JS_UNDEFINED; if (!read_obj(st, ctx, root, mk, 14, 0x1FFu, f)) return 0; if (JS_VALUE_GET_TAG(f[0]) != JS_TAG_INT || JS_VALUE_GET_INT(f[0]) != 2) goto done; if (!get_str(ctx, f[1], &s, 36) || !uuid_ok(&s)) goto done; @@ -1862,8 +1907,12 @@ static int load_manifest(RunState *st, JSContext *ctx, JSValueConst root, int *w } } if (!load_read(st, ctx, f[5])) goto done; - if (!read_obj(st, ctx, f[6], wk, 2, 3u, w)) goto done; + if (!read_obj(st, ctx, f[6], wk, 3, 3u, w)) goto done; if (JS_VALUE_GET_TAG(w[0]) != JS_TAG_BOOL || JS_VALUE_GET_TAG(w[1]) != JS_TAG_BOOL) goto done; + if (!JS_IsUndefined(w[2])) { + if (JS_VALUE_GET_TAG(w[2]) != JS_TAG_BOOL) goto done; + st->write_files = JS_VALUE_GET_BOOL(w[2]); + } *write_request = JS_VALUE_GET_BOOL(w[0]); *write_response = JS_VALUE_GET_BOOL(w[1]); if (!get_list(st, ctx, f[7], 0, 4, &bind, &nbind)) goto done; @@ -1882,6 +1931,7 @@ static int load_manifest(RunState *st, JSContext *ctx, JSValueConst root, int *w for (int i = 0; i < 14; i++) JS_FreeValue(ctx, f[i]); JS_FreeValue(ctx, w[0]); JS_FreeValue(ctx, w[1]); + JS_FreeValue(ctx, w[2]); return ok; } @@ -2169,9 +2219,11 @@ static int v2_safe_integer_tokens(const uint8_t *text, size_t len) { // // One synchronous trusted host callback per request. fetch() validates natively, blocks in the callback // (the wait extends the CPU deadline but never the wall deadline) and returns an already-settled -// Promise. Promise jobs are drained only while a registered callback is active. +// Promise. Promise jobs are drained only while a registered callback is active. Fetch-only CPU is 250 ms; +// the validated files grant plus trusted createFile callback permits a bounded 1000 ms batch, enforced in C. #define FETCH_CPU_MS 250u +#define FETCH_FILES_CPU_MS 1000u #define FETCH_WALL_MS 120000ull #define FETCH_MAX_REQUESTS 64u #define FETCH_MAX_JSON_BYTES 8192u @@ -2260,7 +2312,11 @@ static JSValue js_resp_json(JSContext *ctx, JSValueConst this_val, int argc, JSV size_t n; const char *c = JS_ToCStringLen2(ctx, &n, data[0], 0); if (!c) return JS_EXCEPTION; - int ok = json_check((const uint8_t *)c, n, 64) && v2_safe_integer_tokens((const uint8_t *)c, n); + int ok = json_check_budgeted((const uint8_t *)c, n, 64, st) && v2_safe_integer_tokens((const uint8_t *)c, n); + if (st && budget_exceeded(st)) { + JS_FreeCString(ctx, c); + return JS_ThrowTypeError(ctx, "response JSON stopped"); + } JSValue parsed = JS_UNDEFINED; if (ok) parsed = JS_ParseJSON(ctx, c, n, ""); JS_FreeCString(ctx, c); @@ -2534,6 +2590,249 @@ static int install_fetch(JSContext *ctx, int probe) { return ok; } +// MARK: Interceptor.createFile / Interceptor.Storage (response.onLeave: fetch-files mode and the read-only scheduling probe) +// +// createFile({storage, atPath, contents}) validates structurally and natively: exactly three own enumerable data +// properties of a plain object (no accessors, Proxy or extras; read without running user code); storage is one of +// the Enum values; atPath is 1...1024 UTF-8 bytes in 1...8 components of 1...255 bytes without absolute, empty, +// dot-led, backslash, colon or control components; contents is a string (valid UTF-8, no lone surrogate; NUL and +// empty allowed) or an exact unshared, attached Uint8Array view of 0...1 MiB. Unicode normalization and case aliasing +// belong to the host. The contents are never parsed. After validation the call blocks in one trusted host callback with +// borrowed raw bytes (no JavaScript runs between acquiring the pointers and the callback) and returns an +// already-settled Promise. Attempts rejected before the callback do not consume the write budgets; +// attempts submitted to the host do, whatever the host answers. + +#define CREATE_MAX_PATH 1024u +#define CREATE_MAX_COMPONENT 255u +#define CREATE_MAX_DEPTH 8u +#define CREATE_MAX_CONTENTS (1024u * 1024u) +#define CREATE_MAX_COUNT 64u +#define CREATE_MAX_TOTAL (16u * 1024u * 1024u) +#define CREATE_REQUEST_MS 10000u + +// Structural path check on valid UTF-8 bytes. Controls: C0, DEL and C1 (U+0080...U+009F). +static int create_path_ok(const uint8_t *p, size_t n) { + if (n < 1 || n > CREATE_MAX_PATH) return 0; + size_t start = 0, depth = 0; + for (size_t i = 0; i <= n; i++) { + if (i < n && p[i] != '/') { + uint8_t c = p[i]; + if (c < 0x20 || c == 0x7F || c == '\\' || c == ':') return 0; + if (c == 0xC2 && i + 1 < n && p[i + 1] >= 0x80 && p[i + 1] <= 0x9F) return 0; + continue; + } + size_t len = i - start; + if (len < 1 || len > CREATE_MAX_COMPONENT || p[start] == '.') return 0; + if (++depth > CREATE_MAX_DEPTH) return 0; + start = i + 1; + } + return 1; +} + +// Exact Uint8Array view over an attached, unshared ArrayBuffer. Returns 1 with `*data`/`*len` borrowed (valid only +// until JavaScript runs again) or 0 (no exception left pending). Pristine class ids captured before user code reject +// Proxy, other TypedArrays, DataView and shared backing stores; detached or out-of-bounds views are invalid. +static int create_bytes_view(RunState *st, JSContext *ctx, JSValueConst v, const uint8_t **data, size_t *len) { + *data = NULL; + *len = 0; + if (JS_GetClassID(v) != st->cls_u8) return 0; + size_t off = 0, blen = 0, bpe = 0; + JSValue buf = JS_GetTypedArrayBuffer(ctx, v, &off, &blen, &bpe); + if (JS_IsException(buf)) { JS_FreeValue(ctx, JS_GetException(ctx)); return 0; } + int ok = 0; + if (bpe == 1 && JS_GetClassID(buf) == st->cls_abuf && blen <= CREATE_MAX_CONTENTS) { + size_t size = 0; + uint8_t *base = JS_GetArrayBuffer(ctx, &size, buf); + if (!base && JS_HasException(ctx)) { + JS_FreeValue(ctx, JS_GetException(ctx)); // detached + } else if (off <= size && blen <= size - off) { + *data = base ? base + off : (const uint8_t *)""; + *len = blen; + ok = 1; + } + } + JS_FreeValue(ctx, buf); + return ok; +} + +// Only ordinary DTO objects (including null-prototype DTOs) are options. Check the class before asking for +// its prototype so a Proxy never gets a getPrototypeOf trap. Fresh native objects use the realm's pristine +// Object prototype without reading a user-replaced global Object constructor. +static int create_options_plain(RunState *st, JSContext *ctx, JSValueConst object) { + if (JS_GetClassID(object) != st->cls_object) return 0; + JSValue prototype = JS_GetPrototype(ctx, object); + if (JS_IsException(prototype)) return 0; + if (JS_IsNull(prototype)) { JS_FreeValue(ctx, prototype); return 1; } + JSValue pristine = JS_NewObject(ctx); + if (JS_IsException(pristine)) { JS_FreeValue(ctx, prototype); return 0; } + JSValue expected = JS_GetPrototype(ctx, pristine); + int ok = JS_IsObject(prototype) && JS_IsObject(expected) && JS_VALUE_GET_PTR(prototype) == JS_VALUE_GET_PTR(expected); + JS_FreeValue(ctx, expected); + JS_FreeValue(ctx, pristine); + JS_FreeValue(ctx, prototype); + return ok; +} + +static JSValue js_create_file(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { + static const char *const keys[] = {"storage", "atPath", "contents"}; + (void)this_val; + RunState *st = JS_GetContextOpaque(ctx); + const char *storage = NULL, *path = NULL, *text_c = NULL; + const uint8_t *bytes = NULL; + size_t storage_len = 0, path_len = 0, bytes_len = 0; + JSValue f[3] = {JS_UNDEFINED, JS_UNDEFINED, JS_UNDEFINED}; + JSValue out = JS_UNDEFINED; + if (!st || !st->files_exposed || !st->in_callback) { + if (st) st->attach_failed = 1; + return JS_ThrowTypeError(ctx, "invalid createFile"); + } + if (budget_exceeded(st)) return JS_ThrowTypeError(ctx, "createFile stopped"); + if (argc != 1) return reject_error(ctx, 0, "invalid createFile arguments"); + // Grant, callback and count are checked before any conversion. + if (!st->write_files || !st->create_cb || st->nwrites >= CREATE_MAX_COUNT) return reject_error(ctx, 0, "createFile rejected"); + if (!create_options_plain(st, ctx, argv[0]) || !read_obj_fields(st, ctx, argv[0], keys, 3, 7u, f, NULL)) + return reject_error(ctx, 0, "invalid createFile options"); + + int valid = JS_IsString(f[0]) && JS_IsString(f[1]); + if (valid) { + storage = JS_ToCStringLen2(ctx, &storage_len, f[0], 0); + if (!storage) { out = JS_EXCEPTION; goto done; } + valid = (storage_len == 5 && !memcmp(storage, "local", 5)) || (storage_len == 6 && !memcmp(storage, "icloud", 6)); + } + if (valid) { + path = JS_ToCStringLen2(ctx, &path_len, f[1], 0); + if (!path) { out = JS_EXCEPTION; goto done; } + valid = utf8_valid((const uint8_t *)path, path_len) && create_path_ok((const uint8_t *)path, path_len); + } + if (valid) { + if (JS_IsString(f[2])) { + text_c = JS_ToCStringLen2(ctx, &bytes_len, f[2], 0); + if (!text_c) { out = JS_EXCEPTION; goto done; } + bytes = (const uint8_t *)text_c; + valid = bytes_len <= CREATE_MAX_CONTENTS && utf8_valid(bytes, bytes_len); + } else if (JS_IsObject(f[2])) { + // Acquired last: no JavaScript (conversion, rejection, getter, finalizer) runs between here and the + // host callback, so the view cannot be detached or resized while the pointer is borrowed. + valid = create_bytes_view(st, ctx, f[2], &bytes, &bytes_len); + } else valid = 0; + } + if (valid && bytes_len > CREATE_MAX_TOTAL - st->write_total) valid = 0; + if (!valid) { + bytes = NULL; // rejection builds an Error and settles a Promise: the borrowed bytes end here + out = budget_exceeded(st) ? JS_ThrowTypeError(ctx, "createFile stopped") : reject_error(ctx, 0, "createFile rejected"); + goto done; + } + if (budget_exceeded(st)) { out = JS_ThrowTypeError(ctx, "createFile stopped"); goto done; } + + uint64_t t0 = now_ns(); + uint64_t left_ms = st->wall_deadline_ns > t0 ? (st->wall_deadline_ns - t0) / 1000000ull : 0; + if (left_ms == 0) { + st->stop = QJS_TIMEOUT; + out = JS_ThrowTypeError(ctx, "createFile stopped"); + goto done; + } + uint32_t timeout_ms = left_ms < CREATE_REQUEST_MS ? (uint32_t)left_ms : CREATE_REQUEST_MS; + st->nwrites++; + st->write_total += bytes_len; + int32_t rc = st->create_cb(st->create_opaque, (const uint8_t *)storage, storage_len, (const uint8_t *)path, path_len, + bytes ? bytes : (const uint8_t *)"", bytes_len, timeout_ms); + bytes = NULL; + // Host wait is excluded from the cumulative CPU budget only; the wall deadline keeps running. + st->deadline_ns += now_ns() - t0; + if (rc == 2) { + st->stop = QJS_CANCELLED; + out = JS_ThrowTypeError(ctx, "createFile aborted"); + } else if (budget_exceeded(st)) { + out = JS_ThrowTypeError(ctx, "createFile stopped"); + } else if (rc != 0) { + out = reject_error(ctx, 0, "createFile failed"); + } else { + out = settled_promise(ctx, JS_UNDEFINED, 0); + } +done: + if (storage) JS_FreeCString(ctx, storage); + if (path) JS_FreeCString(ctx, path); + if (text_c) JS_FreeCString(ctx, text_c); + for (int i = 0; i < 3; i++) JS_FreeValue(ctx, f[i]); + return out; +} + +// Read-only scheduling probe: recognition only. Any call, even a swallowed one, requires the asynchronous path; +// nothing is validated, written or called back. +static JSValue js_probe_create_file(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { + (void)this_val; (void)argc; (void)argv; + RunState *st = JS_GetContextOpaque(ctx); + if (!st || !st->in_callback) { + if (st) st->attach_failed = 1; + return JS_ThrowTypeError(ctx, "createFile outside callback"); + } + st->requires_async = 1; + return JS_ThrowTypeError(ctx, "asynchronous hook required"); +} + +// Storage constants are safe to read while any schema-2 source is evaluated, including sources shared by +// request and response phases. Only the createFile operation itself needs the deferred response.leave mode. +static int install_storage_enum(JSContext *ctx) { + JSValue global = JS_GetGlobalObject(ctx); + JSValue ns = JS_GetPropertyStr(ctx, global, "Interceptor"); + JSValue en = JS_NewObject(ctx); + int ok = !JS_IsException(ns) && !JS_IsException(en); + // JS_DefinePropertyValueStr consumes the value on success and failure. + if (ok) ok = JS_DefinePropertyValueStr(ctx, en, "local", JS_NewString(ctx, "local"), JS_PROP_ENUMERABLE) > 0; + if (ok) ok = JS_DefinePropertyValueStr(ctx, en, "iCloudDrive", JS_NewString(ctx, "icloud"), JS_PROP_ENUMERABLE) > 0; + if (ok) ok = JS_PreventExtensions(ctx, en) > 0; + if (ok) ok = JS_DefinePropertyValueStr(ctx, ns, "Storage", en, JS_PROP_ENUMERABLE) > 0; + else JS_FreeValue(ctx, en); + JS_FreeValue(ctx, ns); + JS_FreeValue(ctx, global); + return ok; +} + +static int install_create_file(JSContext *ctx, int probe) { + JSValue global = JS_GetGlobalObject(ctx); + JSValue ns = JS_GetPropertyStr(ctx, global, "Interceptor"); + JSValue fn = JS_NewCFunction(ctx, probe ? js_probe_create_file : js_create_file, "createFile", 1); + int ok = !JS_IsException(ns) && !JS_IsException(fn); + if (ok) ok = JS_DefinePropertyValueStr(ctx, ns, "createFile", fn, JS_PROP_ENUMERABLE) > 0; + else JS_FreeValue(ctx, fn); + JS_FreeValue(ctx, ns); + JS_FreeValue(ctx, global); + return ok; +} + +// Files-exposed runs get only the Uint8Array/ArrayBuffer machinery createFile needs. JS_AddIntrinsicTypedArrays also +// installs SharedArrayBuffer and Atomics: those globals are removed before any user code, and pristine class ids are +// captured so shared or foreign buffers can never pass as exact bytes. Other v2 runs and v1 stay without any of it. +static int setup_binary_contents(JSContext *ctx, RunState *st) { + if (JS_AddIntrinsicTypedArrays(ctx)) return 0; + static const char *const removed[] = {"SharedArrayBuffer", "Atomics"}; + JSValue global = JS_GetGlobalObject(ctx); + int ok = 1; + for (int i = 0; i < 2 && ok; i++) { + JSAtom a = JS_NewAtom(ctx, removed[i]); + ok = a != JS_ATOM_NULL && JS_DeleteProperty(ctx, global, a, 0) >= 0; + if (a != JS_ATOM_NULL) JS_FreeAtom(ctx, a); + if (ok) { // deleted must mean absent + JSValue v = JS_GetPropertyStr(ctx, global, removed[i]); + ok = !JS_IsException(v) && JS_IsUndefined(v); + JS_FreeValue(ctx, v); + } + } + JS_FreeValue(ctx, global); + if (!ok) return 0; + JSValue buf = JS_NewArrayBufferCopy(ctx, (const uint8_t *)"", 0); + if (JS_IsException(buf)) return 0; + JSValueConst args[1] = {buf}; + JSValue u8 = JS_NewTypedArray(ctx, 1, args, JS_TYPED_ARRAY_UINT8); + if (!JS_IsException(u8)) { + st->cls_abuf = JS_GetClassID(buf); + st->cls_u8 = JS_GetClassID(u8); + } + JS_FreeValue(ctx, u8); + JS_FreeValue(ctx, buf); + return st->cls_abuf && st->cls_u8 && st->cls_abuf != st->cls_u8; +} + // Drains promise jobs until none remain, then resolves a returned Promise in place (*ret is replaced by its // fulfilment value). Pending after the drain means no job can ever settle it: a script error. static int settle_callback(RunState *st, JSContext *ctx, JSRuntime *rt, JSValue *ret) { @@ -2562,6 +2861,7 @@ static int v2_setup_failure(const RunState *st) { static QJSResult run_v2_impl(QJSCancelToken *token, const QJSLimits *limits, QJSFetchCallback fetch_cb, void *fetch_opaque, int probe_fetch, + int expose_files, QJSCreateFileCallback create_callback_in, void *create_opaque_in, const uint8_t *package_json, size_t package_len, const char *hook, const uint8_t *event_json, size_t event_len, @@ -2582,11 +2882,15 @@ static QJSResult run_v2_impl(QJSCancelToken *token, const QJSLimits *limits, memset(&id, 0, sizeof(id)); for (int i = 0; i < MAX_REGS; i++) st.regs[i].cb = JS_UNDEFINED; st.token = token; + uint64_t cpu_start_ns = now_ns(); { size_t cpu_ms = limits ? limits->deadline_ms : 0; if (fetch_cb && cpu_ms > FETCH_CPU_MS) cpu_ms = FETCH_CPU_MS; - st.deadline_ns = now_ns() + (uint64_t)cpu_ms * 1000000ull; + st.deadline_ns = cpu_start_ns + (uint64_t)cpu_ms * 1000000ull; } + st.create_cb = create_callback_in; + st.create_opaque = create_opaque_in; + st.files_exposed = expose_files || probe_fetch; if (fetch_cb) { st.fetch_cb = fetch_cb; st.fetch_opaque = fetch_opaque; @@ -2645,6 +2949,10 @@ static QJSResult run_v2_impl(QJSCancelToken *token, const QJSLimits *limits, JS_FreeValue(ctx, a); if (!st.cls_object || !st.cls_array || st.cls_object == st.cls_array) goto cleanup; } + if (st.files_exposed && !setup_binary_contents(ctx, &st)) { + status = st.oom ? QJS_MEMORY_OR_STACK : QJS_INTERNAL; + goto cleanup; + } JS_SetContextOpaque(ctx, &st); // Manifest, event and config are parsed and validated natively before user code exists. @@ -2656,6 +2964,12 @@ static QJSResult run_v2_impl(QJSCancelToken *token, const QJSLimits *limits, if (JS_IsException(cfgv)) { status = classify_exception(ctx, &st, QJS_INVALID_INPUT); goto cleanup; } if (!load_package(&st, ctx, manv, &write_request, &write_response)) { status = v2_setup_failure(&st); goto cleanup; } + // Only the validated files grant plus a trusted createFile callback admits the larger batch budget. + // Keep the original start: manifest/setup time counts, and no host callback has run yet. + if (fetch_cb && st.create_cb && st.write_files) { + size_t cpu_ms = limits->deadline_ms < FETCH_FILES_CPU_MS ? limits->deadline_ms : FETCH_FILES_CPU_MS; + st.deadline_ns = cpu_start_ns + (uint64_t)cpu_ms * 1000000ull; + } st.body_writable = kind == 0 && (leg == 0 ? write_request : write_response); if (!freeze_tree(&st, ctx, cfgv, 1, 0)) { status = v2_setup_failure(&st); goto cleanup; } have_id = 1; // ident_free tolerates a partially filled identity @@ -2702,7 +3016,8 @@ static QJSResult run_v2_impl(QJSCancelToken *token, const QJSLimits *limits, } } - if (!install_interceptor(ctx) || ((fetch_cb || probe_fetch) && !install_fetch(ctx, probe_fetch))) { status = st.oom ? QJS_MEMORY_OR_STACK : QJS_INTERNAL; goto cleanup; } + if (!install_interceptor(ctx) || !install_storage_enum(ctx) || ((fetch_cb || probe_fetch) && !install_fetch(ctx, probe_fetch)) || + (st.files_exposed && !install_create_file(ctx, probe_fetch))) { status = st.oom ? QJS_MEMORY_OR_STACK : QJS_INTERNAL; goto cleanup; } { JSValue completion = JS_Eval(ctx, (const char *)src, source_len, "", JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_STRICT); @@ -2847,7 +3162,7 @@ QJSResult qjs_run_v2(QJSCancelToken *token, const QJSLimits *limits, const char *hook, const uint8_t *event_json, size_t event_len, const uint8_t *config_json, size_t config_len) { - return run_v2_impl(token, limits, NULL, NULL, 0, package_json, package_len, hook, event_json, event_len, + return run_v2_impl(token, limits, NULL, NULL, 0, 0, NULL, NULL, package_json, package_len, hook, event_json, event_len, config_json, config_len); } @@ -2861,7 +3176,7 @@ QJSResult qjs_run_v2_fetch(QJSCancelToken *token, const QJSLimits *limits, QJSResult res = {QJS_INVALID_INPUT, NULL, 0}; return res; } - return run_v2_impl(token, limits, callback, opaque, 0, package_json, package_len, hook, event_json, event_len, + return run_v2_impl(token, limits, callback, opaque, 0, 0, NULL, NULL, package_json, package_len, hook, event_json, event_len, config_json, config_len); } @@ -2873,6 +3188,21 @@ QJSResult qjs_run_v2_probe(QJSCancelToken *token, const QJSLimits *limits, QJSResult res = {QJS_INVALID_INPUT, NULL, 0}; return res; } - return run_v2_impl(token, limits, NULL, NULL, 1, package_json, package_len, hook, + return run_v2_impl(token, limits, NULL, NULL, 1, 0, NULL, NULL, package_json, package_len, hook, event_json, event_len, config_json, config_len); } + +QJSResult qjs_run_v2_fetch_files(QJSCancelToken *token, const QJSLimits *limits, + QJSFetchCallback callback, void *opaque, + QJSCreateFileCallback create_callback, void *create_opaque, + const uint8_t *package_json, size_t package_len, + const char *hook, + const uint8_t *event_json, size_t event_len, + const uint8_t *config_json, size_t config_len) { + if (!callback) { + QJSResult res = {QJS_INVALID_INPUT, NULL, 0}; + return res; + } + return run_v2_impl(token, limits, callback, opaque, 0, 1, create_callback, create_opaque, package_json, package_len, + hook, event_json, event_len, config_json, config_len); +} diff --git a/Packages/InterceptorAutomation/Sources/CQuickJS/include/CQuickJS.h b/Packages/InterceptorAutomation/Sources/CQuickJS/include/CQuickJS.h index 06a3529..0f963dc 100644 --- a/Packages/InterceptorAutomation/Sources/CQuickJS/include/CQuickJS.h +++ b/Packages/InterceptorAutomation/Sources/CQuickJS/include/CQuickJS.h @@ -96,8 +96,35 @@ QJSResult qjs_run_v2_fetch(QJSCancelToken *token, const QJSLimits *limits, const uint8_t *event_json, size_t event_len, const uint8_t *config_json, size_t config_len); -/// Read-only response.onLeave scheduling probe. Runs sync hooks unchanged, but performs no network. -/// A fetch attempt or returned Promise gives QJS_ASYNC_REQUIRED, discarding all recorded intents. +/// `Interceptor.createFile({storage, atPath, contents})` host contract. `storage` is exactly "local" or "icloud"; +/// `path` is structurally valid UTF-8 (1...1024 bytes, 1...8 components of 1...255 bytes, no absolute, empty, dot-led, +/// backslash, colon or control component; Unicode normalization and case aliasing are the host's). `contents` is 0...1 MiB +/// of raw bytes (string UTF-8 without lone surrogates, or an exact Uint8Array view), never parsed; it may contain NUL and +/// may be empty (then the pointer is non-NULL but must not be dereferenced). All pointers are borrowed, length-delimited, +/// not NUL-terminated and valid only during the call. The callback is trusted, runs on the calling thread, may block, +/// must honor `timeout_ms` and the cancel token, and must finish all its I/O before returning. +/// Result: 0 created, 1 rejected/failed (script sees a generic rejection), 2 abort/cancel/revoked. +typedef int32_t (*QJSCreateFileCallback)(void *opaque, const uint8_t *storage, size_t storage_len, + const uint8_t *path, size_t path_len, + const uint8_t *contents, size_t contents_len, uint32_t timeout_ms); + +/// Same as `qjs_run_v2_fetch` plus `Interceptor.createFile` (response.onLeave only; Uint8Array/ArrayBuffer exist in this mode +/// and the probe, SharedArrayBuffer and Atomics never). The immutable `Interceptor.Storage` Enum is readable in all +/// schema-2 modes. Creating needs the manifest's schema 2 +/// `write.files` grant and a non-NULL `create_callback`; otherwise calls reject without host I/O. Budgets are separate from +/// fetch: 64 submitted writes / 16 MiB of submitted contents, counted before the callback runs whatever it answers. Wall time +/// stays 120 s. C caps cumulative CPU at 1000 ms only with both the files grant and trusted callback; other fetch runs stay +/// at 250 ms. Host callback wait is excluded. +QJSResult qjs_run_v2_fetch_files(QJSCancelToken *token, const QJSLimits *limits, + QJSFetchCallback callback, void *opaque, + QJSCreateFileCallback create_callback, void *create_opaque, + const uint8_t *package_json, size_t package_len, + const char *hook, + const uint8_t *event_json, size_t event_len, + const uint8_t *config_json, size_t config_len); + +/// Read-only response.onLeave scheduling probe. Runs sync hooks unchanged, but performs no network or file I/O. +/// A fetch or createFile attempt, or a returned Promise, gives QJS_ASYNC_REQUIRED, discarding all recorded intents. QJSResult qjs_run_v2_probe(QJSCancelToken *token, const QJSLimits *limits, const uint8_t *package_json, size_t package_len, const char *hook, const uint8_t *event_json, size_t event_len, diff --git a/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFilePublisherTests.swift b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFilePublisherTests.swift new file mode 100644 index 0000000..1f982c0 --- /dev/null +++ b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFilePublisherTests.swift @@ -0,0 +1,501 @@ +import Foundation +import XCTest +@testable import AutomationCore + +/// Real-filesystem tests for the generic File Provider publisher +/// (docs/superpowers/specs/2026-10-24-plugin-file-destinations-design.md). Written before +/// implementation: `PluginFilePublisher`, `PluginFileStore` and `PluginFileDestination` may not exist yet. +/// Records are produced through the Core store; root, state and record directories are separate paths. +final class PluginFilePublisherTests: XCTestCase { + private var directory: URL! + private var root: URL! + private var outside: URL! + private var stateURL: URL { directory.appendingPathComponent("state/publisher.json") } + private let fm = FileManager.default + private let rootIdentity = "test-root-identity" + private let familyA = UUID(uuidString: "44444444-4444-4444-4444-444444444444")! + private let familyB = UUID(uuidString: "55555555-5555-5555-5555-555555555555")! + + override func setUpWithError() throws { + directory = fm.temporaryDirectory.appendingPathComponent("PluginFilePublisher-" + UUID().uuidString) + root = directory.appendingPathComponent("root") + outside = directory.appendingPathComponent("outside") + try fm.createDirectory(at: root, withIntermediateDirectories: true) + try fm.createDirectory(at: outside, withIntermediateDirectories: true) + try fm.createDirectory(at: stateURL.deletingLastPathComponent(), withIntermediateDirectories: true) + } + override func tearDownWithError() throws { + if let e = fm.enumerator(at: directory, includingPropertiesForKeys: nil) { + for case let u as URL in e { try? fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: u.path) } + } + try fm.removeItem(at: directory) + } + + // MARK: tests + + func testPublishesExactBinaryBytesAtNestedPath() async throws { + let bytes = Data([0x00, 0xff, 0x7b, 0x00, 0x0a, 0xfe, 0x80, 0x00]) + let record = try makeRecord(family: familyA, path: "Salmon Run/details/abc.json", contents: bytes) + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("Salmon Run/details/abc.json")), bytes) + } + + func testPublishesEmptyFile() async throws { + let record = try makeRecord(family: familyA, path: "a/empty.bin", contents: Data()) + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity) + let url = root.appendingPathComponent("a/empty.bin") + XCTAssertTrue(fm.fileExists(atPath: url.path)) + XCTAssertEqual(try Data(contentsOf: url), Data()) + } + + func testCombiningMarkAfterSlashUsesSeparatePathComponents() async throws { + let bytes = Data("response".utf8) + let record = try makeRecord(family: familyA, path: "a/\u{0301}b", contents: bytes) + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("a").appendingPathComponent("\u{0301}b")), bytes) + } + + func testCombiningMarkAfterSlashDoesNotFollowSymlinkAncestor() async throws { + try fm.createSymbolicLink(at: root.appendingPathComponent("a"), withDestinationURL: outside) + let record = try makeRecord(family: familyA, path: "a/\u{0301}b", contents: Data("response".utf8)) + await assertRejects(record) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: outside.path), []) + } + + func testCombiningMarkAfterDotIsRejectedBeforePublication() throws { + XCTAssertThrowsError(try makeRecord(family: familyA, path: "a/.\u{0301}hidden", contents: Data("response".utf8))) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: root.path), []) + XCTAssertFalse(fm.fileExists(atPath: stateURL.path)) + } + + func testGrantedFolderPrefixPublishesWithoutNestingTheFolderAgain() async throws { + let bytes = Data("original response".utf8) + let record = try makeRecord(family: familyA, path: "Salmon Run/details/result.json", contents: bytes, storage: .icloud) + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity, + pathPrefix: "Salmon Run") + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("details/result.json")), bytes) + XCTAssertFalse(fm.fileExists(atPath: root.appendingPathComponent("Salmon Run").path)) + XCTAssertEqual(record.destination.atPath, "Salmon Run/details/result.json") + } + + func testInvalidOrMismatchedFolderPrefixIsRejectedBeforeSideEffects() async throws { + for (index, pair) in [ + ("Salmon Run/history.json", "salmon run"), + ("Salmon Run/history.json", "Salmon"), + ("Salmon Run/history.json", "Other"), + ("Salmon Run/history.json", "../Salmon Run"), + ("Salmon Run/history.json", "Salmon Run/details"), + ("Salmon Run", "Salmon Run"), + ].enumerated() { + let record = try makeRecord(family: familyA, path: pair.0, contents: Data("raw".utf8), + store: "prefix-\(index)", storage: .icloud) + do { + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity, + pathPrefix: pair.1) + XCTFail("invalid/mismatched prefix accepted: \(pair)") + } catch {} + XCTAssertFalse(fm.fileExists(atPath: stateURL.path)) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: root.path), []) + } + } + + func testPrefixedOwnedReplacementUsesPhysicalRelativePathInPersistedLedger() async throws { + let first = try makeRecord(family: familyA, path: "Salmon Run/history.json", contents: Data("one".utf8), + store: "p1", storage: .icloud) + try await PluginFilePublisher(stateURL: stateURL).publish(first, to: root, rootIdentity: rootIdentity, + pathPrefix: "Salmon Run") + let second = try makeRecord(family: familyA, path: "Salmon Run/history.json", contents: Data("two".utf8), + store: "p2", storage: .icloud) + try await PluginFilePublisher(stateURL: stateURL).publish(second, to: root, rootIdentity: rootIdentity, + pathPrefix: "Salmon Run") + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("history.json")), Data("two".utf8)) + let ledger = try String(contentsOf: stateURL, encoding: .utf8) + XCTAssertTrue(ledger.contains("\"path\":\"history.json\"")) + XCTAssertFalse(ledger.contains("Salmon Run")) + } + + func testAbandonedOwnedLedgerTempIsRemovedWithoutTouchingOtherFiles() async throws { + let parent = stateURL.deletingLastPathComponent() + let orphan = parent.appendingPathComponent(".ledger-tmp-" + UUID().uuidString) + let unrelated = parent.appendingPathComponent(".ledger-tmp-not-owned") + try Data("interrupted ledger".utf8).write(to: orphan) + try Data("keep".utf8).write(to: unrelated) + let record = try makeRecord(family: familyA, path: "history.json", contents: Data("raw".utf8)) + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity) + XCTAssertFalse(fm.fileExists(atPath: orphan.path), "crashed ledger temporaries must not accumulate") + XCTAssertEqual(try Data(contentsOf: unrelated), Data("keep".utf8)) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("history.json")), Data("raw".utf8)) + } + + func testSameFamilySamePathReplacementSurvivesFreshPublisherInstance() async throws { + let first = try makeRecord(family: familyA, path: "Salmon Run/history.json", contents: Data("one".utf8), store: "s1") + try await PluginFilePublisher(stateURL: stateURL).publish(first, to: root, rootIdentity: rootIdentity) + let second = try makeRecord(family: familyA, path: "Salmon Run/history.json", contents: Data("two, longer".utf8), store: "s2") + // A new instance only knows what the persisted ledger recorded. + try await PluginFilePublisher(stateURL: stateURL).publish(second, to: root, rootIdentity: rootIdentity) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("Salmon Run/history.json")), Data("two, longer".utf8)) + } + + func testTargetFileIsCoordinatedWhenReplacingOwnedContents() async throws { + let first = try makeRecord(family: familyA, path: "history.json", contents: Data("one".utf8), store: "s1") + try await PluginFilePublisher(stateURL: stateURL).publish(first, to: root, rootIdentity: rootIdentity) + let presenter = LeafPresenter(url: root.appendingPathComponent("history.json")) + NSFileCoordinator.addFilePresenter(presenter) + defer { NSFileCoordinator.removeFilePresenter(presenter) } + let second = try makeRecord(family: familyA, path: "history.json", contents: Data("two".utf8), store: "s2") + try await PluginFilePublisher(stateURL: stateURL).publish(second, to: root, rootIdentity: rootIdentity) + XCTAssertGreaterThan(presenter.writerCount, 0, "coordinating the containing directory does not coordinate this file") + } + + func testProviderRematerializationWithIdenticalBytesRetainsOwnership() async throws { + let first = try makeRecord(family: familyA, path: "history.json", contents: Data("one".utf8), store: "s1") + try await PluginFilePublisher(stateURL: stateURL).publish(first, to: root, rootIdentity: rootIdentity) + let target = root.appendingPathComponent("history.json") + let oldInode = try fm.attributesOfItem(atPath: target.path)[.systemFileNumber] as? NSNumber + // File Providers may materialize the same document on a new inode. Its contents still match + // the persisted published digest; only per-operation race checks may rely on the inode. + try Data("one".utf8).write(to: target, options: .atomic) + let newInode = try fm.attributesOfItem(atPath: target.path)[.systemFileNumber] as? NSNumber + XCTAssertNotEqual(oldInode, newInode) + let second = try makeRecord(family: familyA, path: "history.json", contents: Data("two".utf8), store: "s2") + try await PluginFilePublisher(stateURL: stateURL).publish(second, to: root, rootIdentity: rootIdentity) + XCTAssertEqual(try Data(contentsOf: target), Data("two".utf8)) + } + + func testPreexistingUnknownFileIsRejectedWithoutChange() async throws { + let target = root.appendingPathComponent("Salmon Run/history.json") + try fm.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("user data".utf8).write(to: target) + let record = try makeRecord(family: familyA, path: "Salmon Run/history.json", contents: Data("plugin".utf8)) + await assertRejects(record) + XCTAssertEqual(try Data(contentsOf: target), Data("user data".utf8)) + } + + func testExternallyEditedOwnedFileIsRejected() async throws { + let first = try makeRecord(family: familyA, path: "history.json", contents: Data("one".utf8), store: "s1") + try await PluginFilePublisher(stateURL: stateURL).publish(first, to: root, rootIdentity: rootIdentity) + let target = root.appendingPathComponent("history.json") + try Data("edited by user".utf8).write(to: target) + let second = try makeRecord(family: familyA, path: "history.json", contents: Data("two".utf8), store: "s2") + await assertRejects(second) + XCTAssertEqual(try Data(contentsOf: target), Data("edited by user".utf8)) + } + + func testCrossFamilyCollisionIsRejected() async throws { + let owner = try makeRecord(family: familyA, path: "shared/history.json", contents: Data("a".utf8), store: "sA") + try await PluginFilePublisher(stateURL: stateURL).publish(owner, to: root, rootIdentity: rootIdentity) + let other = try makeRecord(family: familyB, path: "shared/history.json", contents: Data("b".utf8), store: "sB") + await assertRejects(other) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("shared/history.json")), Data("a".utf8)) + } + + func testCaseAliasOfAnotherFamilysFileIsRejected() async throws { + let owner = try makeRecord(family: familyA, path: "Shared/History.json", contents: Data("a".utf8), store: "sA") + try await PluginFilePublisher(stateURL: stateURL).publish(owner, to: root, rootIdentity: rootIdentity) + let other = try makeRecord(family: familyB, path: "shared/history.json", contents: Data("b".utf8), store: "sB") + await assertRejects(other) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("Shared/History.json")), Data("a".utf8)) + } + + func testCompatibilityAliasUsesTheCoreOwnershipIdentity() async throws { + let owner = try makeRecord(family: familyA, path: "Shared/history.json", contents: Data("a".utf8), store: "sA") + try await PluginFilePublisher(stateURL: stateURL).publish(owner, to: root, rootIdentity: rootIdentity) + let other = try makeRecord(family: familyB, path: "Shared/history.json", contents: Data("b".utf8), store: "sB") + await assertRejects(other) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("Shared/history.json")), Data("a".utf8)) + XCTAssertFalse(fm.fileExists(atPath: root.appendingPathComponent("Shared/history.json").path)) + } + + func testSymlinkAncestorIsRejectedWithoutOutsideChange() async throws { + try fm.createSymbolicLink(at: root.appendingPathComponent("Salmon Run"), withDestinationURL: outside) + let record = try makeRecord(family: familyA, path: "Salmon Run/history.json", contents: Data("x".utf8)) + await assertRejects(record) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: outside.path), []) + } + + func testSymlinkFinalTargetIsRejectedWithoutOutsideChange() async throws { + let victim = outside.appendingPathComponent("victim.json") + try Data("victim".utf8).write(to: victim) + try fm.createSymbolicLink(at: root.appendingPathComponent("history.json"), withDestinationURL: victim) + let record = try makeRecord(family: familyA, path: "history.json", contents: Data("x".utf8)) + await assertRejects(record) + XCTAssertEqual(try Data(contentsOf: victim), Data("victim".utf8)) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: outside.path), ["victim.json"]) + } + + func testCancellationBeforePublishLeavesNoFileOrLedger() async throws { + let record = try makeRecord(family: familyA, path: "Salmon Run/history.json", contents: Data("x".utf8)) + let publisher = PluginFilePublisher(stateURL: stateURL) + let root = self.root!, identity = rootIdentity + let task = Task { + // Enter publish only once cancellation is already visible; no timing involved. + while !Task.isCancelled { await Task.yield() } + try await publisher.publish(record, to: root, rootIdentity: identity) + } + task.cancel() + do { + try await task.value + XCTFail("cancelled publish must not succeed") + } catch {} + XCTAssertEqual(try fm.contentsOfDirectory(atPath: root.path), []) + XCTAssertFalse(fm.fileExists(atPath: stateURL.path), "ledger mutated by a cancelled publish") + } + + private func writeLedger(_ record: PluginFileRecord, path: String, pending: String?, published: String?, + temporary: URL? = nil, includeTempIdentity: Bool = true) throws { + let key = PluginFilePublisher.ledgerKey(rootIdentity: rootIdentity, path: path) + func j(_ v: String?) -> String { v.map { "\"\($0)\"" } ?? "null" } + let family = Digest.sha256Hex(Data(record.family.utf8)) + var extra = "" + if let temporary { + extra = ",\"tempName\":\"\(temporary.lastPathComponent)\"" + if includeTempIdentity { + var info = stat() + guard lstat(temporary.path, &info) == 0 else { throw CocoaError(.fileReadUnknown) } + extra += ",\"tempDevice\":\(Int64(info.st_dev)),\"tempInode\":\(Int64(truncatingIfNeeded: info.st_ino))" + } + } + let json = "{\"entries\":[{\"family\":\"\(family)\",\"key\":\"\(key)\",\"path\":\"\(path)\",\"pending\":\(j(pending)),\"published\":\(j(published))\(extra)}],\"version\":1}" + try Data(json.utf8).write(to: stateURL) + } + + private func crashTemporary(_ bytes: Data, stale: Bool = true) throws -> URL { + let url = root.appendingPathComponent(".interceptor-" + UUID().uuidString + ".tmp") + try bytes.write(to: url) + if stale { try fm.setAttributes([.modificationDate: Date(timeIntervalSinceNow: -120)], ofItemAtPath: url.path) } + return url + } + + func testAbandonedIntentTempIsRemovedWithoutTouchingUntrackedLookalike() async throws { + let bytes = Data("complete response".utf8) + let record = try makeRecord(family: familyA, path: "history.json", contents: bytes) + let orphan = try crashTemporary(bytes) + let unrelated = try crashTemporary(bytes) + try writeLedger(record, path: "history.json", pending: record.digest, published: nil, temporary: orphan) + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity) + XCTAssertFalse(fm.fileExists(atPath: orphan.path)) + XCTAssertEqual(try Data(contentsOf: unrelated), bytes) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("history.json")), bytes) + XCTAssertFalse(try String(contentsOf: stateURL, encoding: .utf8).contains("tempName")) + } + + func testOwnedScratchInodeIsReclaimedAfterInterruptedWrite() async throws { + let bytes = Data("complete response".utf8) + let record = try makeRecord(family: familyA, path: "history.json", contents: bytes) + let orphan = try crashTemporary(Data("incomplete native scratch bytes".utf8)) + try writeLedger(record, path: "history.json", pending: record.digest, published: nil, temporary: orphan) + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity) + XCTAssertFalse(fm.fileExists(atPath: orphan.path)) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("history.json")), bytes) + } + + func testPartialScratchFromOlderResponseIsReclaimedForNewerResponse() async throws { + let old = try makeRecord(family: familyA, path: "history.json", contents: Data("old response".utf8), store: "old") + let orphan = try crashTemporary(Data("old".utf8)) + try writeLedger(old, path: "history.json", pending: old.digest, published: nil, temporary: orphan) + let new = try makeRecord(family: familyA, path: "history.json", contents: Data("new response".utf8), store: "new") + try await PluginFilePublisher(stateURL: stateURL).publish(new, to: root, rootIdentity: rootIdentity) + XCTAssertFalse(fm.fileExists(atPath: orphan.path)) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("history.json")), Data("new response".utf8)) + } + + func testEmptyScratchBeforeInodeJournalIsReclaimed() async throws { + let bytes = Data("complete response".utf8) + let record = try makeRecord(family: familyA, path: "history.json", contents: bytes) + let orphan = try crashTemporary(Data()) + try writeLedger(record, path: "history.json", pending: record.digest, published: nil, + temporary: orphan, includeTempIdentity: false) + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity) + XCTAssertFalse(fm.fileExists(atPath: orphan.path)) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("history.json")), bytes) + } + + func testReplacedScratchWithEditedBytesIsPreserved() async throws { + let record = try makeRecord(family: familyA, path: "history.json", contents: Data("complete response".utf8)) + let orphan = try crashTemporary(Data("partial".utf8)) + let oldInode = try fm.attributesOfItem(atPath: orphan.path)[.systemFileNumber] as? NSNumber + try writeLedger(record, path: "history.json", pending: record.digest, published: nil, temporary: orphan) + try Data("user replacement".utf8).write(to: orphan, options: .atomic) + XCTAssertNotEqual(oldInode, try fm.attributesOfItem(atPath: orphan.path)[.systemFileNumber] as? NSNumber) + try fm.setAttributes([.modificationDate: Date(timeIntervalSinceNow: -120)], ofItemAtPath: orphan.path) + await assertRejects(record) + XCTAssertEqual(try Data(contentsOf: orphan), Data("user replacement".utf8)) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: root.path), [orphan.lastPathComponent]) + } + + func testRematerializedScratchWithCompletePendingResponseIsReclaimed() async throws { + let bytes = Data("complete response".utf8) + let record = try makeRecord(family: familyA, path: "history.json", contents: bytes) + let orphan = try crashTemporary(Data("partial".utf8)) + let oldInode = try fm.attributesOfItem(atPath: orphan.path)[.systemFileNumber] as? NSNumber + try writeLedger(record, path: "history.json", pending: record.digest, published: nil, temporary: orphan) + try bytes.write(to: orphan, options: .atomic) + XCTAssertNotEqual(oldInode, try fm.attributesOfItem(atPath: orphan.path)[.systemFileNumber] as? NSNumber) + try fm.setAttributes([.modificationDate: Date(timeIntervalSinceNow: -120)], ofItemAtPath: orphan.path) + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity) + XCTAssertFalse(fm.fileExists(atPath: orphan.path)) + XCTAssertEqual(try Data(contentsOf: root.appendingPathComponent("history.json")), bytes) + } + + func testJournaledSymlinkScratchIsPreserved() async throws { + let bytes = Data("complete response".utf8) + let record = try makeRecord(family: familyA, path: "history.json", contents: bytes) + let target = outside.appendingPathComponent("response") + try bytes.write(to: target) + let orphan = root.appendingPathComponent(".interceptor-" + UUID().uuidString + ".tmp") + try fm.createSymbolicLink(at: orphan, withDestinationURL: target) + try writeLedger(record, path: "history.json", pending: record.digest, published: nil, temporary: orphan) + await assertRejects(record) + XCTAssertEqual(try fm.destinationOfSymbolicLink(atPath: orphan.path), target.path) + XCTAssertEqual(try Data(contentsOf: target), bytes) + } + + func testJournaledHardLinkedScratchIsPreserved() async throws { + let bytes = Data("complete response".utf8) + let record = try makeRecord(family: familyA, path: "history.json", contents: bytes) + let target = outside.appendingPathComponent("response") + try bytes.write(to: target) + let orphan = root.appendingPathComponent(".interceptor-" + UUID().uuidString + ".tmp") + try fm.linkItem(at: target, to: orphan) + try fm.setAttributes([.modificationDate: Date(timeIntervalSinceNow: -120)], ofItemAtPath: orphan.path) + try writeLedger(record, path: "history.json", pending: record.digest, published: nil, temporary: orphan) + await assertRejects(record) + XCTAssertEqual(try Data(contentsOf: orphan), bytes) + XCTAssertEqual(try Data(contentsOf: target), bytes) + } + + func testIntentTempWithoutRecordedInodeIsPreserved() async throws { + let bytes = Data("complete response".utf8) + let record = try makeRecord(family: familyA, path: "history.json", contents: bytes) + let orphan = try crashTemporary(bytes) + try writeLedger(record, path: "history.json", pending: record.digest, published: nil, + temporary: orphan, includeTempIdentity: false) + await assertRejects(record) + XCTAssertEqual(try Data(contentsOf: orphan), bytes) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: root.path), [orphan.lastPathComponent]) + } + + func testLockedIntentTempIsPreservedWithoutCreatingAnotherTemp() async throws { + let bytes = Data("complete response".utf8) + let record = try makeRecord(family: familyA, path: "history.json", contents: bytes) + let orphan = try crashTemporary(bytes) + try writeLedger(record, path: "history.json", pending: record.digest, published: nil, temporary: orphan) + let fd = open(orphan.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) + XCTAssertGreaterThanOrEqual(fd, 0) + defer { close(fd) } + XCTAssertEqual(flock(fd, LOCK_EX | LOCK_NB), 0) + await assertRejects(record) + XCTAssertEqual(try Data(contentsOf: orphan), bytes) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: root.path), [orphan.lastPathComponent]) + } + + func testRecentIntentTempIsPreservedWithoutCreatingAnotherTemp() async throws { + let bytes = Data("complete response".utf8) + let record = try makeRecord(family: familyA, path: "history.json", contents: bytes) + let orphan = try crashTemporary(bytes, stale: false) + try writeLedger(record, path: "history.json", pending: record.digest, published: nil, temporary: orphan) + await assertRejects(record) + XCTAssertEqual(try Data(contentsOf: orphan), bytes) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: root.path), [orphan.lastPathComponent]) + } + + func testRecoversInterruptedPublicationFromIntentLedger() async throws { + // Crash after the external rename but before the ledger was finalized: ledger holds old+pending. + let new = Data("new bytes".utf8) + let record = try makeRecord(family: familyA, path: "Salmon Run/history.json", contents: new) + let target = root.appendingPathComponent("Salmon Run/history.json") + try fm.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try new.write(to: target) + try writeLedger(record, path: "Salmon Run/history.json", pending: Digest.sha256Hex(new), + published: Digest.sha256Hex(Data("old".utf8))) + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity) + XCTAssertEqual(try Data(contentsOf: target), new) + let ledger = try String(contentsOf: stateURL, encoding: .utf8) + XCTAssertTrue(ledger.contains("\"pending\":null")) + XCTAssertTrue(ledger.contains("\"published\":\"\(Digest.sha256Hex(new))\"")) + } + + func testIntentLedgerDoesNotClaimUnknownFileWithDifferentBytes() async throws { + let new = Data("new".utf8) + let record = try makeRecord(family: familyA, path: "history.json", contents: new) + let target = root.appendingPathComponent("history.json") + try Data("user".utf8).write(to: target) + try writeLedger(record, path: "history.json", pending: Digest.sha256Hex(new), published: nil) + await assertRejects(record) + XCTAssertEqual(try Data(contentsOf: target), Data("user".utf8)) + } + + func testCorruptLedgerFailsClosedWithoutPublishing() async throws { + try Data("{\"entries\":[],\"version\":1,\"extra\":true}".utf8).write(to: stateURL) + let record = try makeRecord(family: familyA, path: "history.json", contents: Data("x".utf8)) + await assertRejects(record) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: root.path), []) + } + + func testSymlinkRootIsRejected() async throws { + let link = directory.appendingPathComponent("rootlink") + try fm.createSymbolicLink(at: link, withDestinationURL: outside) + let record = try makeRecord(family: familyA, path: "history.json", contents: Data("x".utf8)) + do { + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: link, rootIdentity: rootIdentity) + XCTFail("symlink root must be rejected") + } catch {} + XCTAssertEqual(try fm.contentsOfDirectory(atPath: outside.path), []) + } + + // MARK: helpers + + private final class LeafPresenter: NSObject, NSFilePresenter, @unchecked Sendable { + private let url: URL + private let lock = NSLock() + private var writers = 0 + let presentedItemOperationQueue = OperationQueue() + var presentedItemURL: URL? { url } + var writerCount: Int { lock.withLock { writers } } + + init(url: URL) { + self.url = url + super.init() + presentedItemOperationQueue.maxConcurrentOperationCount = 1 + } + + func relinquishPresentedItem(toWriter writer: @escaping @Sendable ((@Sendable () -> Void)?) -> Void) { + lock.withLock { writers += 1 } + writer(nil) + } + } + + private func assertRejects(_ record: PluginFileRecord, file: StaticString = #filePath, line: UInt = #line) async { + let stateBefore = try? Data(contentsOf: stateURL) + do { + try await PluginFilePublisher(stateURL: stateURL).publish(record, to: root, rootIdentity: rootIdentity) + XCTFail("publish should have been rejected", file: file, line: line) + } catch {} + XCTAssertEqual(try? Data(contentsOf: stateURL), stateBefore, "ledger changed by a rejected publish", file: file, line: line) + } + + /// Builds a record through the Core store. Each `store` name is its own record directory, so records of + /// different families or revisions never trip the source store's own ownership checks. + private func makeRecord(family: UUID, path: String, contents: Data, store name: String = "records", + storage: PluginFileStorage = .local) throws -> PluginFileRecord { + let store = PluginFileStore(directoryURL: directory.appendingPathComponent("records-" + name + "-" + family.uuidString)) + let package = try package(id: family) + let destination = try PluginFileDestination(storage: storage, atPath: path) + let revision = "local|\(package.manifest.id.uuidString)|\(package.revision)" + let prepared = try store.prepare(revisionID: revision, package: package, destination: destination, contents: contents) + try prepared.commit(checkAuthorization: {}) + let identifiers = try store.recordIdentifiers() + XCTAssertEqual(identifiers.count, 1) + return try store.readRecord(try XCTUnwrap(identifiers.first)) + } + + private func package(id: UUID, source: String = "// s") throws -> PluginPackage { + let json = """ + {"manifest":{"schemaVersion":2,"id":"\(id.uuidString)","name":"Test","version":"1.0.0", + "matches":[{"hosts":["example.com"],"methods":["GET"],"path":{"kind":"exact","value":"/"},"hooks":{"response":{"onLeave":"hooks/example.com/GET.js"}}}], + "read":{"metadata":["method","host","path","status"],"headers":[],"queryKeys":[],"body":{"mode":"json"}}, + "write":{"requestBody":true,"responseBody":true,"files":true},"endpointBindings":[],"settings":{}},"sourceFiles":{"hooks/example.com/GET.js":"\(source)"}} + """ + return try PluginPackage.validate(Data(json.utf8)) + } +} diff --git a/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFileStoreTests.swift b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFileStoreTests.swift new file mode 100644 index 0000000..7d17d64 --- /dev/null +++ b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFileStoreTests.swift @@ -0,0 +1,515 @@ +import CryptoKit +import Darwin +import Foundation +import XCTest +@testable import AutomationCore + +/// Real-filesystem tests for the plugin file destination contract +/// (docs/superpowers/specs/2026-10-24-plugin-file-destinations-design.md). +/// Written before implementation: `PluginFileStorage`, `PluginFileDestination`, `PluginFileStore` +/// and `PluginFileRecord` do not exist yet, so this target fails to build until they land. +final class PluginFileStoreTests: XCTestCase { + private var directory: URL! + private var outside: URL! + private var rootURL: URL { directory.appendingPathComponent("PluginFileRecords") } + private let fm = FileManager.default + + override func setUpWithError() throws { + directory = fm.temporaryDirectory.appendingPathComponent("PluginFileStore-" + UUID().uuidString) + outside = directory.appendingPathComponent("outside") + try fm.createDirectory(at: outside, withIntermediateDirectories: true) + } + override func tearDownWithError() throws { + if let e = fm.enumerator(at: directory, includingPropertiesForKeys: nil) { + for case let u as URL in e { try? fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: u.path) } + } + try fm.removeItem(at: directory) + } + + // MARK: helpers + + private func store() -> PluginFileStore { PluginFileStore(directoryURL: rootURL) } + + private func package(id: UUID = UUID(uuidString: "33333333-3333-3333-3333-333333333333")!, files: Bool = true, + source: String = "// s") throws -> PluginPackage { + let json = """ + {"manifest":{"schemaVersion":2,"id":"\(id.uuidString)","name":"Test","version":"1.0.0", + "matches":[{"hosts":["example.com"],"methods":["GET"],"path":{"kind":"exact","value":"/"},"hooks":{"response":{"onLeave":"hooks/example.com/GET.js"}}}], + "read":{"metadata":["method","host","path","status"],"headers":[],"queryKeys":[],"body":{"mode":"json"}}, + "write":{"requestBody":true,"responseBody":true,"files":\(files)},"endpointBindings":[],"settings":{}},"sourceFiles":{"hooks/example.com/GET.js":"\(source)"}} + """ + return try PluginPackage.validate(Data(json.utf8)) + } + private func revisionID(_ p: PluginPackage, origin: String = "local") -> String { "\(origin)|\(p.manifest.id.uuidString)|\(p.revision)" } + private func dest(_ path: String, _ storage: PluginFileStorage = .icloud) throws -> PluginFileDestination { + try PluginFileDestination(storage: storage, atPath: path) + } + private func prepare(_ s: PluginFileStore, _ p: PluginPackage, _ path: String, _ data: Data, + storage: PluginFileStorage = .icloud, origin: String = "local") throws -> PluginFileStore.PreparedWrite { + try s.prepare(revisionID: revisionID(p, origin: origin), package: p, destination: dest(path, storage), contents: data) + } + @discardableResult + private func write(_ s: PluginFileStore, _ p: PluginPackage, _ path: String, _ data: Data, + storage: PluginFileStorage = .icloud, origin: String = "local", + check: @escaping @Sendable () throws -> Void = {}) throws -> PluginFileStore.PreparedWrite { + let w = try prepare(s, p, path, data, storage: storage, origin: origin) + try w.commit(checkAuthorization: check) + return w + } + private func sha(_ d: Data) -> String { SHA256.hash(data: d).map { String(format: "%02x", $0) }.joined() } + + private func files(under u: URL) -> [URL] { + guard let e = fm.enumerator(at: u, includingPropertiesForKeys: [.isRegularFileKey]) else { return [] } + return e.compactMap { $0 as? URL }.filter { (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true } + } + private func onlyRecord(_ s: PluginFileStore) throws -> (id: String, url: URL) { + let ids = try s.recordIdentifiers() + XCTAssertEqual(ids.count, 1) + let id = try XCTUnwrap(ids.first) + let url = rootURL.appendingPathComponent(id) + XCTAssertTrue(fm.fileExists(atPath: url.path), "cannot locate the file of record \(id)") + return (id, url) + } + private func assertOutsideEmpty(file: StaticString = #filePath, line: UInt = #line) throws { + XCTAssertEqual(try fm.contentsOfDirectory(atPath: outside.path), [], "write escaped through a link", file: file, line: line) + } + private func assertNoEmptyDirectories(file: StaticString = #filePath, line: UInt = #line) throws { + guard let e = fm.enumerator(at: rootURL, includingPropertiesForKeys: [.isDirectoryKey]) else { return } + for case let u as URL in e where (try u.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true { + XCTAssertFalse(try fm.contentsOfDirectory(atPath: u.path).isEmpty, "empty directory \(u.lastPathComponent)", file: file, line: line) + } + } + + // MARK: contents + + func testStoresNonJSONTextNULInvalidUTF8AndEmptyBytesExactly() throws { + let p = try package(), s = store() + let cases: [(String, Data)] = [ + ("a/text.txt", Data("plain\r\ntext é 😀\n".utf8)), + ("a/binary.bin", Data([0x00, 0xFF, 0xFE, 0x00, 0xC3, 0x28, 0x80])), + ("a/empty", Data()), + ] + for (path, bytes) in cases { try write(s, p, path, bytes) } + let records = try s.recordIdentifiers().map { try s.readRecord($0) } + XCTAssertEqual(records.count, 3) + for (path, bytes) in cases { + let r = try XCTUnwrap(records.first { $0.destination.atPath == path }) + XCTAssertEqual(r.contents, bytes) + XCTAssertEqual(r.digest, sha(bytes)) + XCTAssertEqual(r.destination.storage, .icloud) + } + } + + func testRejectsContentsOverOneMiBButAcceptsExactlyOneMiB() throws { + let p = try package(), s = store() + XCTAssertNoThrow(try write(s, p, "limit", Data(count: 1 << 20))) + XCTAssertThrowsError(try prepare(s, p, "over", Data(count: (1 << 20) + 1))) + XCTAssertEqual(try s.recordIdentifiers().count, 1) + } + + // MARK: private storage + + func testMissingFilesPermissionAndWrongPackageBindingAreRejectedBeforeIO() throws { + let s = store(), denied = try package(files: false), allowed = try package(), other = try package(id: UUID()) + XCTAssertThrowsError(try prepare(s, denied, "a.txt", Data())) + XCTAssertThrowsError(try s.prepare(revisionID: revisionID(other), package: allowed, + destination: dest("a.txt"), contents: Data())) + XCTAssertFalse(fm.fileExists(atPath: rootURL.path)) + } + + func testRecordIsOwnerOnlyAndExcludedFromBackup() throws { + let p = try package(), s = store() + try write(s, p, "a/b.txt", Data("x".utf8)) + let rec = try onlyRecord(s) + let mode = try fm.attributesOfItem(atPath: rec.url.path)[.posixPermissions] as? Int + XCTAssertEqual(try XCTUnwrap(mode) & 0o777, 0o600) + XCTAssertEqual(try rec.url.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup, true) + } + + func testPreparedWriteIsInvisibleUntilCommitAndDiscardCleansUp() throws { + let p = try package(), s = store() + let w = try prepare(s, p, "a.txt", Data("new".utf8)) + XCTAssertEqual(try s.recordIdentifiers(), []) + try w.commit() + XCTAssertEqual(try s.recordIdentifiers().count, 1) + + let before = files(under: rootURL).map(\.path).sorted() + let d = try prepare(s, p, "b.txt", Data("other".utf8)) + d.discard() + XCTAssertEqual(files(under: rootURL).map(\.path).sorted(), before) + XCTAssertEqual(try s.recordIdentifiers().count, 1) + try assertNoEmptyDirectories() + } + + func testCancellationBeforeCommitLeavesPreviousRecordUntouched() throws { + let p = try package(), s = store() + try write(s, p, "a.txt", Data("old".utf8)) + let id = try XCTUnwrap(try s.recordIdentifiers().first) + let w = try prepare(s, p, "a.txt", Data("new".utf8)) + XCTAssertThrowsError(try w.commit(checkAuthorization: { throw CancellationError() })) + XCTAssertEqual(try s.recordIdentifiers(), [id]) + XCTAssertEqual(try s.readRecord(id).contents, Data("old".utf8)) + } + + func testCommittedWriteCannotBeCommittedAgain() throws { + let p = try package(), s = store() + let w = try write(s, p, "a.txt", Data("one".utf8)) + let id = try XCTUnwrap(try s.recordIdentifiers().first) + XCTAssertThrowsError(try w.commit()) + XCTAssertEqual(try s.readRecord(id).contents, Data("one".utf8)) + } + + func testDeniedFirstCommitLeavesNoEmptyFamily() throws { + let s = store() + XCTAssertThrowsError(try write(s, try package(), "a.txt", Data("x".utf8), check: { throw CancellationError() })) + XCTAssertEqual(try s.recordIdentifiers(), []) + try assertNoEmptyDirectories() + XCTAssertTrue(files(under: rootURL).isEmpty) + } + + func testPrepareSweepsOnlyOldUnlockedOwnedTemporaries() throws { + let p = try package(), s = store() + try write(s, p, "existing.txt", Data()) + let abandoned = rootURL.appendingPathComponent(".tmp-" + UUID().uuidString) + let active = rootURL.appendingPathComponent(".tmp-" + UUID().uuidString) + let recent = rootURL.appendingPathComponent(".tmp-" + UUID().uuidString) + for url in [abandoned, active, recent] { try Data("temporary".utf8).write(to: url) } + for url in [abandoned, active] { + try fm.setAttributes([.modificationDate: Date(timeIntervalSinceNow: -600)], ofItemAtPath: url.path) + } + let activeFD = open(active.path, O_RDWR | O_NOFOLLOW | O_CLOEXEC) + XCTAssertGreaterThanOrEqual(activeFD, 0) + guard activeFD >= 0 else { return } + defer { close(activeFD) } + XCTAssertEqual(flock(activeFD, LOCK_EX | LOCK_NB), 0) + let pending = try prepare(s, p, "next.txt", Data()) + defer { pending.discard() } + XCTAssertFalse(fm.fileExists(atPath: abandoned.path)) + XCTAssertTrue(fm.fileExists(atPath: active.path)) + XCTAssertTrue(fm.fileExists(atPath: recent.path)) + XCTAssertEqual(try s.recordIdentifiers().count, 1) + } + + // MARK: replacement and families + + func testSamePathReplacesAtomicallyWithStableIdentifier() throws { + let p = try package(), s = store() + try write(s, p, "Salmon Run/history.json", Data("v1".utf8)) + let rec = try onlyRecord(s) + try write(s, p, "Salmon Run/history.json", Data("version-two".utf8)) + let again = try onlyRecord(s) + XCTAssertEqual(again.id, rec.id) + XCTAssertEqual(again.url, rec.url) + XCTAssertEqual(try s.readRecord(rec.id).contents, Data("version-two".utf8)) + XCTAssertEqual(files(under: rootURL).count, 1, "replacement must leave no temporary or stale file") + } + + func testNormalPackageUpdateKeepsFamilyAndReplacesRecord() throws { + let id = UUID() + let v1 = try package(id: id, source: "// one"), v2 = try package(id: id, source: "// two") + XCTAssertNotEqual(v1.revision, v2.revision) + let s = store() + try write(s, v1, "a.json", Data("old".utf8)) + let first = try XCTUnwrap(try s.recordIdentifiers().first) + let family = try s.readRecord(first).family + try write(s, v2, "a.json", Data("new".utf8)) + XCTAssertEqual(try s.recordIdentifiers(), [first]) + let r = try s.readRecord(first) + XCTAssertEqual(r.family, family) + XCTAssertEqual(r.contents, Data("new".utf8)) + } + + func testDifferentFamiliesCannotClaimTheSameCanonicalPath() throws { + let a = try package(), b = try package(id: UUID()) + let s = store() + try write(s, a, "Shared/file.txt", Data("a".utf8)) + XCTAssertThrowsError(try write(s, b, "shared/FILE.txt", Data("b".utf8))) + XCTAssertThrowsError(try write(s, b, "Shared/file.txt", Data("b".utf8))) + XCTAssertEqual(try s.recordIdentifiers().count, 1) + XCTAssertEqual(try s.readRecord(try XCTUnwrap(try s.recordIdentifiers().first)).contents, Data("a".utf8)) + } + + func testSourceQualifiedFamiliesOfSamePackageCollide() throws { + let p = try package(), s = store() + try write(s, p, "x.txt", Data("local".utf8), origin: "local") + XCTAssertThrowsError(try write(s, p, "x.txt", Data("remote".utf8), origin: "https://example.com/plugin")) + XCTAssertEqual(try s.readRecord(try XCTUnwrap(try s.recordIdentifiers().first)).contents, Data("local".utf8)) + } + + func testLocalAndICloudStoragesAreIndependent() throws { + let p = try package(), s = store() + try write(s, p, "same.txt", Data("local".utf8), storage: .local) + try write(s, p, "same.txt", Data("cloud".utf8), storage: .icloud) + let records = try s.recordIdentifiers().map { try s.readRecord($0) } + XCTAssertEqual(records.count, 2) + XCTAssertEqual(try XCTUnwrap(records.first { $0.destination.storage == .local }).contents, Data("local".utf8)) + XCTAssertEqual(try XCTUnwrap(records.first { $0.destination.storage == .icloud }).contents, Data("cloud".utf8)) + } + + func testCaseAliasInSameFamilyIsRejectedWithoutRenaming() throws { + let p = try package(), s = store() + try write(s, p, "Salmon Run/History.json", Data("a".utf8)) + XCTAssertThrowsError(try write(s, p, "salmon run/history.json", Data("b".utf8))) + let records = try s.recordIdentifiers().map { try s.readRecord($0) } + XCTAssertEqual(records.map(\.destination.atPath), ["Salmon Run/History.json"]) + XCTAssertEqual(records.first?.contents, Data("a".utf8)) + } + + // MARK: path validation + + func testDotFollowedByCombiningMarkStillStartsAHiddenComponent() throws { + for path in [".\u{301}hidden", "a/.\u{301}hidden"] { + XCTAssertThrowsError(try dest(path), "POSIX leading dot must remain hidden: \(path)") + } + } + + func testSlashFollowedByCombiningMarkStillCountsAsAPathSeparator() throws { + let nineComponents = "a" + String(repeating: "/\u{301}b", count: 8) + XCTAssertThrowsError(try dest(nineComponents), "combining marks must not bypass the eight-component limit") + } + + func testSlashFollowedByCombiningMarkDoesNotMergeValidComponentByteLimits() throws { + let parent = String(repeating: "a", count: 255) + XCTAssertNoThrow(try dest(parent + "/\u{301}b.txt"), "POSIX has two individually valid components") + } + + func testPublicPathComponentsUsePOSIXScalarBoundaries() throws { + XCTAssertEqual(try dest("a/\u{301}b.txt").pathComponents, ["a", "\u{301}b.txt"]) + XCTAssertEqual(try dest("Salmon Run/details/result.json").pathComponents, ["Salmon Run", "details", "result.json"]) + } + + func testNonNFCPathIsRejectedNotRenamed() throws { + let decomposed = "cafe\u{301}.txt" + XCTAssertNotEqual(Data(decomposed.utf8), Data(decomposed.precomposedStringWithCanonicalMapping.utf8)) + XCTAssertThrowsError(try dest(decomposed)) + XCTAssertEqual(try dest("caf\u{e9}.txt").atPath, "caf\u{e9}.txt") + } + + func testInvalidPathsAreRejected() throws { + let c255 = String(repeating: "a", count: 255) + let invalid = [ + "", "/abs.txt", "a//b", "a/", ".", "./a", "a/./b", "..", "a/../b", "../a", + ".hidden", "a/.hidden", "a\\b", "a:b", "a/b:c", "a\tb", "a\nb", "a\u{0}b", "a\u{7f}b", + String(repeating: "a/", count: 8) + "f", // depth 9 + String(repeating: "a", count: 256), // component 256 bytes + String(repeating: "é", count: 128), // component 256 bytes (multibyte) + (0..<5).map { _ in c255 }.joined(separator: "/"), // 1279 bytes, over 1024 + ] + for path in invalid { + XCTAssertThrowsError(try dest(path), "accepted \(path.debugDescription)") + } + let valid = [ + "a", "Salmon Run/history.json", String(repeating: "a/", count: 7) + "f", + c255, "ひらがな/😀.txt", + ([String](repeating: String(repeating: "a", count: 255), count: 3) + [String(repeating: "b", count: 250)]).joined(separator: "/"), + ] + for path in valid { + XCTAssertNoThrow(try dest(path), "rejected \(path.debugDescription)") + } + // Path-length boundary: four 255-byte components + 3 separators = 1023 bytes passes; adding "/x" (1025) fails. + let four = [String](repeating: String(repeating: "a", count: 255), count: 4).joined(separator: "/") + XCTAssertEqual(four.utf8.count, 1023) + XCTAssertNoThrow(try dest(four)) + let exact = ([String](repeating: String(repeating: "a", count: 255), count: 3) + + [String(repeating: "b", count: 200), String(repeating: "c", count: 55)]).joined(separator: "/") + XCTAssertEqual(exact.utf8.count, 1024) + XCTAssertNoThrow(try dest(exact), "exactly 1024 bytes is allowed") + XCTAssertThrowsError(try dest(four + "/x"), "over 1024 bytes") + } + + func testDecodedDestinationRevalidatesPath() throws { + let good = Data(#"{"storage":"icloud","atPath":"a/b.txt"}"#.utf8) + let decoded = try JSONDecoder().decode(PluginFileDestination.self, from: good) + XCTAssertEqual(decoded.storage, .icloud) + XCTAssertEqual(decoded.atPath, "a/b.txt") + for bad in ["../x", "/x", ".h", "a\\\\b", "a:b"] { + let json = Data(#"{"storage":"local","atPath":"\#(bad)"}"#.utf8) + XCTAssertThrowsError(try JSONDecoder().decode(PluginFileDestination.self, from: json), bad) + } + XCTAssertThrowsError(try JSONDecoder().decode(PluginFileDestination.self, from: Data(#"{"storage":"dropbox","atPath":"x"}"#.utf8))) + XCTAssertEqual(PluginFileStorage.local.rawValue, "local") + XCTAssertEqual(PluginFileStorage.icloud.rawValue, "icloud") + } + + // MARK: corruption and identifiers + + func testRecordVersionsTracksReplacementAndReportsDeclaredDigestWithoutPayloadValidation() throws { + let p = try package(), s = store() + XCTAssertEqual(try s.recordVersions(), [:]) + XCTAssertFalse(fm.fileExists(atPath: rootURL.path), "metadata reads must not create a missing store") + let old = Data("old payload".utf8), new = Data("new payload".utf8) + try write(s, p, "existing.bin", old) + let record = try onlyRecord(s) + XCTAssertEqual(try s.recordVersions(), [record.id: sha(old)]) + try write(s, p, "existing.bin", new) + XCTAssertEqual(try s.recordVersions(), [record.id: sha(new)]) + + var bytes = try Data(contentsOf: record.url) + bytes[bytes.count - 1] ^= 0xFF + try bytes.write(to: record.url) + // Metadata is only the bounded header's declared version, not a claim that payload bytes were verified. + XCTAssertEqual(try s.recordVersions(), [record.id: sha(new)]) + XCTAssertThrowsError(try s.readRecord(record.id), "full reads must still validate the payload digest") + } + + func testRecordVersionsRejectsCorruptHeaderAndForeignBinding() throws { + let p = try package(), s = store() + try write(s, p, "existing.bin", Data()) + let record = try onlyRecord(s) + let original = try Data(contentsOf: record.url) + var corruptMagic = original + corruptMagic[0] ^= 0xFF + try corruptMagic.write(to: record.url) + XCTAssertThrowsError(try s.recordVersions()) + + var foreign = original + let oldID = Data("33333333-3333-3333-3333-333333333333".utf8) + let range = try XCTUnwrap(foreign.range(of: oldID)) + foreign.replaceSubrange(range, with: Data("44444444-4444-4444-4444-444444444444".utf8)) + try foreign.write(to: record.url) + XCTAssertThrowsError(try s.recordVersions(), "metadata must validate namespace/header ownership") + + try original.dropLast().write(to: record.url) + XCTAssertThrowsError(try s.recordVersions(), "metadata must validate the declared file length") + } + + func testRecordVersionsBoundsRootEnumerationWithoutChangingFiles() throws { + let p = try package(), s = store() + try write(s, p, "existing.bin", Data()) + for _ in 0..<273 { + try Data().write(to: rootURL.appendingPathComponent(".tmp-" + UUID().uuidString)) + } + let before = files(under: rootURL).map(\.path).sorted() + XCTAssertThrowsError(try s.recordVersions(), "metadata enumeration must be bounded") + XCTAssertEqual(files(under: rootURL).map(\.path).sorted(), before, "metadata must be read-only") + } + + func testCorruptTruncatedAndMismatchedRecordsFailToRead() throws { + let p = try package(), s = store() + try write(s, p, "a.bin", Data((0..<200).map { UInt8($0) })) + let rec = try onlyRecord(s) + let original = try Data(contentsOf: rec.url) + + var flipped = original + flipped[flipped.count - 1] ^= 0xFF + try flipped.write(to: rec.url) + XCTAssertThrowsError(try s.readRecord(rec.id), "payload mismatch") + + try original.dropLast(7).write(to: rec.url) + XCTAssertThrowsError(try s.readRecord(rec.id), "truncated") + + try (original + Data([0x01])).write(to: rec.url) + XCTAssertThrowsError(try s.readRecord(rec.id), "trailing bytes") + + try Data().write(to: rec.url) + XCTAssertThrowsError(try s.readRecord(rec.id), "empty file") + + try Data(repeating: 0xAA, count: original.count).write(to: rec.url) + XCTAssertThrowsError(try s.readRecord(rec.id), "garbage header") + + try original.write(to: rec.url) + XCTAssertEqual(try s.readRecord(rec.id).contents, Data((0..<200).map { UInt8($0) })) + } + + func testOversizedExistingRecordFailsClosedBeforeQuotaArithmetic() throws { + let p = try package(), s = store() + try write(s, p, "existing.bin", Data()) + let record = try onlyRecord(s) + let file = try FileHandle(forWritingTo: record.url) + defer { try? file.close() } + try file.truncate(atOffset: UInt64((1 << 20) + 4096 + 13)) + XCTAssertThrowsError(try write(s, p, "new.bin", Data()), "oversized corrupt record must reject publication") + XCTAssertEqual(try s.recordIdentifiers().count, 1) + } + + func testForeignHeaderBindingCannotBeOverwrittenAsAnOwnedRecord() throws { + let p = try package(), s = store() + try write(s, p, "existing.bin", Data()) + let record = try onlyRecord(s) + var bytes = try Data(contentsOf: record.url) + let originalFamilyID = Data("33333333-3333-3333-3333-333333333333".utf8) + let otherFamilyID = Data("44444444-4444-4444-4444-444444444444".utf8) + let range = try XCTUnwrap(bytes.range(of: originalFamilyID)) + bytes.replaceSubrange(range, with: otherFamilyID) + try bytes.write(to: record.url) + XCTAssertThrowsError(try s.readRecord(record.id), "header namespace binding is corrupt") + XCTAssertThrowsError(try write(s, p, "existing.bin", Data("replacement".utf8))) + XCTAssertEqual(try Data(contentsOf: record.url), bytes, "untrusted ownership record must remain untouched") + } + + func testTooManyPendingTemporariesRejectsBeforeCreatingMore() throws { + let p = try package(), s = store() + try write(s, p, "existing.bin", Data()) + for _ in 0..<257 { + try Data().write(to: rootURL.appendingPathComponent(".tmp-" + UUID().uuidString)) + } + let before = files(under: rootURL).count + XCTAssertThrowsError(try prepare(s, p, "new.bin", Data()), "pending temporary count is bounded to 256") + XCTAssertEqual(files(under: rootURL).count, before) + } + + func testTraversalIdentifiersAreRejectedAndNothingOutsideIsRead() throws { + let p = try package(), s = store() + try write(s, p, "a.txt", Data("x".utf8)) + try Data("secret".utf8).write(to: outside.appendingPathComponent("leak")) + for id in ["../outside/leak", "/etc/passwd", "..", ".", "", "a/b", "a\\b", String(repeating: "a", count: 4096), + "\(try XCTUnwrap(try s.recordIdentifiers().first))/../../outside/leak"] { + XCTAssertThrowsError(try s.readRecord(id), id) + } + } + + // MARK: links fail closed + + func testSymlinkedStoreRootFailsClosed() throws { + try fm.createSymbolicLink(at: rootURL, withDestinationURL: outside) + let s = store() + XCTAssertThrowsError(try write(s, try package(), "a.txt", Data("x".utf8))) + XCTAssertThrowsError(try s.recordIdentifiers()) + try assertOutsideEmpty() + } + + func testSymlinkedNamespaceFailsClosed() throws { + let p = try package(), s = store() + try write(s, p, "a.txt", Data("x".utf8)) + let rec = try onlyRecord(s) + let namespace = rec.url.deletingLastPathComponent() + XCTAssertNotEqual(namespace.standardizedFileURL, rootURL.standardizedFileURL, "records must live in a family namespace") + try fm.removeItem(at: namespace) + try fm.createSymbolicLink(at: namespace, withDestinationURL: outside) + XCTAssertThrowsError(try write(s, p, "a.txt", Data("y".utf8))) + XCTAssertThrowsError(try write(s, p, "b.txt", Data("y".utf8))) + try assertOutsideEmpty() + } + + func testSymlinkedRecordFailsClosedAndIsNeverWrittenThrough() throws { + let p = try package(), s = store() + try write(s, p, "a.txt", Data("x".utf8)) + let rec = try onlyRecord(s) + let target = outside.appendingPathComponent("target") + try Data("untouched".utf8).write(to: target) + try fm.removeItem(at: rec.url) + try fm.createSymbolicLink(at: rec.url, withDestinationURL: target) + XCTAssertThrowsError(try s.readRecord(rec.id)) + _ = try? write(s, p, "a.txt", Data("replacement".utf8)) + XCTAssertEqual(try Data(contentsOf: target), Data("untouched".utf8)) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: outside.path), ["target"]) + } + + // MARK: quotas + + func testSeventeenthFamilyIsRejectedWhileExistingFamiliesStillUpdate() throws { + let s = store() + var packages: [PluginPackage] = [] + for index in 0..<16 { + let p = try package(id: UUID()) + packages.append(p) + try write(s, p, "\(index)/f.txt", Data()) + } + XCTAssertEqual(try s.recordIdentifiers().count, 16) + XCTAssertThrowsError(try write(s, try package(id: UUID()), "sixteenth/f.txt", Data())) + XCTAssertEqual(try s.recordIdentifiers().count, 16) + XCTAssertNoThrow(try write(s, packages[0], "0/f.txt", Data("update".utf8))) + XCTAssertNoThrow(try write(s, packages[0], "second.txt", Data())) + try assertNoEmptyDirectories() + } +} diff --git a/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFilesPermissionTests.swift b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFilesPermissionTests.swift new file mode 100644 index 0000000..9c73003 --- /dev/null +++ b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFilesPermissionTests.swift @@ -0,0 +1,63 @@ +import XCTest +@testable import AutomationCore + +/// Optional schema-2 `write.files` permission (Task 1). Intended interface: `PluginManifest.writeFiles: Bool`. +final class PluginFilesPermissionTests: XCTestCase { + private static let match = #"{"hosts":["api.example.com"],"methods":["GET"],"path":{"kind":"exact","value":"/credentials"},"hooks":{"response":{"onLeave":"selected.js"}}}"# + private static let read = #"{"metadata":["host"],"headers":[],"queryKeys":[],"body":{"mode":"json"}}"# + + private func package(write: String, schema: String = "2") -> Data { + Data(#"{"manifest":{"schemaVersion":\#(schema),"id":"\#(pluginID)","name":"Hook","version":"1.0.0","matches":[\#(Self.match)],"read":\#(Self.read),"write":\#(write),"settings":{},"endpointBindings":[]},"sourceFiles":{"selected.js":"Interceptor.attach({response:{onLeave(){}}});"}}"#.utf8) + } + private func manifest(_ write: String) throws -> PluginManifest { + try PluginPackage.validate(package(write: write)).manifest + } + private func rejects(_ write: String, line: UInt = #line) { + assertThrows(.invalidManifest, try PluginPackage.validate(package(write: write)), line: line) + } + + func testFilesPermissionDefaultsFalseWhenAbsent() throws { + let m = try manifest(#"{"requestBody":false,"responseBody":false}"#) + XCTAssertFalse(m.writeFiles) + XCTAssertFalse(m.writeRequestBody) + XCTAssertFalse(m.writeResponseBody) + } + + func testFilesPermissionTrueAndExplicitFalse() throws { + let granted = try manifest(#"{"requestBody":false,"responseBody":false,"files":true}"#) + XCTAssertTrue(granted.writeFiles) + XCTAssertFalse(granted.writeRequestBody) + XCTAssertFalse(granted.writeResponseBody) + XCTAssertFalse(try manifest(#"{"requestBody":false,"responseBody":false,"files":false}"#).writeFiles) + // Independent of the body permissions. + let all = try manifest(#"{"requestBody":true,"responseBody":true,"files":true}"#) + XCTAssertTrue(all.writeFiles && all.writeRequestBody && all.writeResponseBody) + } + + func testFilesPermissionMustBeStrictBoolean() { + for bad in ["1", "0", "null", #""true""#, "[]", "{}", "2.5"] { + rejects(#"{"requestBody":false,"responseBody":false,"files":\#(bad)}"#) + } + } + + func testWriteStillRejectsUnknownKeysAndRequiresBodyFlags() { + rejects(#"{"requestBody":false,"responseBody":false,"file":true}"#) + rejects(#"{"requestBody":false,"responseBody":false,"files":true,"extra":true}"#) + rejects(#"{"files":true}"#) + rejects(#"{"requestBody":false,"files":true}"#) + } + + func testSchemaOneHasNoFilesPermission() { + let v1 = Data(#"{"manifest":\#(manifestJSON(extra: #","write":{"files":true}"#)),"source":"function onRequest(){return {actions:[]}}"}"#.utf8) + assertThrows(.invalidManifest, try PluginPackage.validate(v1)) + let v1Write = Data(#"{"manifest":\#(manifestJSON(extra: #","write":{"requestBody":false,"responseBody":false,"files":true}"#)),"source":"function onRequest(){return {actions:[]}}"}"#.utf8) + assertThrows(.invalidManifest, try PluginPackage.validate(v1Write)) + } + + func testPermissionIsPartOfPreservedManifestJSON() throws { + let granted = try manifest(#"{"requestBody":false,"responseBody":false,"files":true}"#) + let absent = try manifest(#"{"requestBody":false,"responseBody":false}"#) + XCTAssertNotEqual(granted.json, absent.json) + XCTAssertEqual(try granted.json.data(), try manifest(#"{"requestBody":false,"responseBody":false,"files":true}"#).json.data()) + } +} diff --git a/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFolderGrantStoreTests.swift b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFolderGrantStoreTests.swift new file mode 100644 index 0000000..8851523 --- /dev/null +++ b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginFolderGrantStoreTests.swift @@ -0,0 +1,91 @@ +import Foundation +import XCTest +@testable import AutomationCore + +final class PluginFolderGrantStoreTests: XCTestCase { + private var folder: URL! + private var url: URL { folder.appendingPathComponent("grants.json") } + private let family = "local|AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA" + override func setUpWithError() throws { + folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + } + override func tearDownWithError() throws { try FileManager.default.removeItem(at: folder) } + + func testBookmarkAndRootIdentitySurviveFreshInstance() throws { + let grant = PluginFolderGrant(bookmark: Data([0, 255, 1]), rootIdentity: String(repeating: "a", count: 64)) + try PluginFolderGrantStore(url: url).set(grant, for: family) + XCTAssertEqual(try PluginFolderGrantStore(url: url).grant(for: family), grant) + XCTAssertNil(try PluginFolderGrantStore(url: url).grant(for: "local|BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB")) + } + + func testInvalidGrantCannotReplacePreviouslyPersistedGrant() throws { + let store = PluginFolderGrantStore(url: url) + let grant = PluginFolderGrant(bookmark: Data([42]), rootIdentity: String(repeating: "a", count: 64)) + try store.set(grant, for: family) + let before = try Data(contentsOf: url) + XCTAssertThrowsError(try store.set(.init(bookmark: Data(), rootIdentity: "bad"), for: family)) + XCTAssertEqual(try Data(contentsOf: url), before) + XCTAssertEqual(try store.grant(for: family), grant) + } + + func testSymlinkCannotReadOrOverwriteAnotherGrantRegistry() throws { + let outside = folder.appendingPathComponent("outside.json") + try Data("private user data".utf8).write(to: outside) + try FileManager.default.createSymbolicLink(at: url, withDestinationURL: outside) + let store = PluginFolderGrantStore(url: url) + XCTAssertThrowsError(try store.grant(for: family)) + XCTAssertThrowsError(try store.set(.init(bookmark: Data([1]), rootIdentity: String(repeating: "a", count: 64)), for: family)) + XCTAssertEqual(try Data(contentsOf: outside), Data("private user data".utf8)) + } + + func testCorruptRegistryFailsClosedAndIsNotReset() throws { + let bytes = Data("{\"version\":1,\"version\":1,\"grants\":{}}".utf8) + try bytes.write(to: url) + let store = PluginFolderGrantStore(url: url) + XCTAssertThrowsError(try store.grant(for: family)) + XCTAssertThrowsError(try store.set(.init(bookmark: Data([1]), rootIdentity: String(repeating: "a", count: 64)), for: family)) + XCTAssertEqual(try Data(contentsOf: url), bytes) + } + + func testScopedPrefixGrantsAreIndependentAfterRelaunch() throws { + let first = PluginFolderGrant(bookmark: Data([1]), rootIdentity: String(repeating: "a", count: 64), pathPrefix: "Salmon Run") + let second = PluginFolderGrant(bookmark: Data([2]), rootIdentity: String(repeating: "b", count: 64), pathPrefix: "Other") + try PluginFolderGrantStore(url: url).set(first, for: family) + try PluginFolderGrantStore(url: url).set(second, for: family) + let fresh = PluginFolderGrantStore(url: url) + XCTAssertEqual(try fresh.grant(for: family, prefix: "Salmon Run"), first) + XCTAssertEqual(try fresh.grant(for: family, prefix: "Other"), second) + XCTAssertNil(try fresh.grant(for: family, prefix: "Salmon Run2")) + XCTAssertNil(try fresh.grant(for: family)) + } + + func testRootAndPrefixGrantsCannotOverlapAndCaseAliasesFailClosed() throws { + let store = PluginFolderGrantStore(url: url) + let scoped = PluginFolderGrant(bookmark: Data([1]), rootIdentity: String(repeating: "a", count: 64), pathPrefix: "Salmon Run") + try store.set(scoped, for: family) + let before = try Data(contentsOf: url) + XCTAssertThrowsError(try store.set(.init(bookmark: Data([1]), rootIdentity: String(repeating: "a", count: 64)), for: family)) + XCTAssertThrowsError(try store.set(.init(bookmark: Data([1]), rootIdentity: String(repeating: "a", count: 64), pathPrefix: "salmon run"), for: family)) + XCTAssertEqual(try Data(contentsOf: url), before) + } + + func testThirtyTwoScopedGrantsAreBoundedWithoutEviction() throws { + let store = PluginFolderGrantStore(url: url) + for i in 0..<32 { + try store.set(.init(bookmark: Data([1]), rootIdentity: String(repeating: "a", count: 64), pathPrefix: "Folder\(i)"), for: family) + } + let before = try Data(contentsOf: url) + XCTAssertThrowsError(try store.set(.init(bookmark: Data([1]), rootIdentity: String(repeating: "a", count: 64), pathPrefix: "Overflow"), for: family)) + XCTAssertEqual(try Data(contentsOf: url), before) + XCTAssertNotNil(try store.grant(for: family, prefix: "Folder0")) + } + func testScalarSlashAndHiddenPrefixCannotGrantMultipleFolders() throws { + let store = PluginFolderGrantStore(url: url) + for prefix in ["a/\u{0301}b", ".\u{0301}hidden"] { + XCTAssertThrowsError(try store.set(.init(bookmark: Data([1]), rootIdentity: String(repeating: "a", count: 64), pathPrefix: prefix), for: family)) + } + XCTAssertFalse(FileManager.default.fileExists(atPath: url.path)) + } + +} diff --git a/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginJSONFileStoreTests.swift b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginJSONFileStoreTests.swift new file mode 100644 index 0000000..b3698c1 --- /dev/null +++ b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginJSONFileStoreTests.swift @@ -0,0 +1,635 @@ +import CryptoKit +import Foundation +import XCTest +@testable import AutomationCore + +/// Real-filesystem tests for the Task 2 contract (docs/superpowers/plans/2026-10-23-plugin-json-storage.md). +/// Written before implementation: `PluginJSONFileStore` and `withCurrentActivation` do not exist yet, and +/// schema-2 `write.files` is added by Task 1, so these fail to build/run until those land. +final class PluginJSONFileStoreTests: XCTestCase { + private var directory: URL! + private var outside: URL! + private var rootURL: URL { directory.appendingPathComponent("PluginFiles") } + private var activeURL: URL { directory.appendingPathComponent("active.json") } + private var catalogURL: URL { directory.appendingPathComponent("catalog.json") } + private let fm = FileManager.default + + override func setUpWithError() throws { + directory = fm.temporaryDirectory.appendingPathComponent("PluginJSONStore-" + UUID().uuidString) + outside = directory.appendingPathComponent("outside") + try fm.createDirectory(at: outside, withIntermediateDirectories: true) + } + override func tearDownWithError() throws { + // Restore permissions a test may have removed so cleanup of this test's own directory succeeds. + if let e = fm.enumerator(at: directory, includingPropertiesForKeys: nil) { + for case let u as URL in e { try? fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: u.path) } + } + try fm.removeItem(at: directory) + } + + func testBlockedExportFileDoesNotPreventOtherResponsesFromExporting() throws { + let package = try package(), store = store() + try save(store, package, key: "blocked", "{}") + try save(store, package, key: "healthy", "{\"ok\":true}") + let destination = directory.appendingPathComponent("Documents") + let namespace = try onlyNamespace().lastPathComponent + let sourceFiles = try fm.contentsOfDirectory(atPath: onlyNamespace().path) + let blocked = try XCTUnwrap(sourceFiles.first) + let healthy = try XCTUnwrap(sourceFiles.last) + let exported = destination.appendingPathComponent(namespace) + try fm.createDirectory(at: exported.appendingPathComponent(blocked), withIntermediateDirectories: true) + XCTAssertThrowsError(try store.export(to: destination)) + XCTAssertEqual(try Data(contentsOf: exported.appendingPathComponent(healthy)), try Data(contentsOf: onlyNamespace().appendingPathComponent(healthy))) + } + + func testIdenticalSaveAndExportRestoreBackupExclusion() throws { + let package = try package(), store = store() + try save(store, package, key: "key", "{}") + var saved = try fileURL("key") + var included = URLResourceValues() + included.isExcludedFromBackup = false + try saved.setResourceValues(included) + try save(store, package, key: "key", "{}") + XCTAssertEqual(try saved.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup, true) + let destination = directory.appendingPathComponent("Documents") + try store.export(to: destination) + var exported = destination.appendingPathComponent(try onlyNamespace().lastPathComponent).appendingPathComponent(sha("key") + ".json") + try exported.setResourceValues(included) + try store.export(to: destination) + XCTAssertEqual(try exported.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup, true) + } + + func testRejectedFirstPublicationDoesNotConsumeNamespace() throws { + let store = store() + XCTAssertThrowsError(try save(store, try package(), key: "key", "{}", check: { throw CancellationError() })) + XCTAssertTrue(try namespaces().isEmpty) + } + + func testNumbersThatOverflowFiniteDoubleAreRejectedLikeTheBridge() throws { + XCTAssertThrowsError(try save(store(), try package(), key: "key", "1e999")) + } + + func testProtectionTargetsTheOpenInodeAfterItsPathIsReplaced() throws { + let original = directory.appendingPathComponent("original.json") + let moved = directory.appendingPathComponent("moved.json") + try Data("{}".utf8).write(to: original) + let fd = open(original.path, O_RDWR | O_NOFOLLOW) + XCTAssertGreaterThanOrEqual(fd, 0) + defer { close(fd) } + try fm.moveItem(at: original, to: moved) + try Data("{}".utf8).write(to: original) + try Posix.protect(fd, url: original) + XCTAssertEqual(try moved.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup, true) + XCTAssertNotEqual(try original.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup, true) + } + + // MARK: helpers + + private func store() -> PluginJSONFileStore { PluginJSONFileStore(directoryURL: rootURL) } + + private func package(id: UUID = UUID(uuidString: "33333333-3333-3333-3333-333333333333")!, + files: Bool = true, source: String = "// s") throws -> PluginPackage { + let w = files ? #"{"requestBody":true,"responseBody":true,"files":true}"# : #"{"requestBody":true,"responseBody":true}"# + let json = """ + {"manifest":{"schemaVersion":2,"id":"\(id.uuidString)","name":"Test","version":"1.0.0", + "matches":[{"hosts":["example.com"],"methods":["GET"],"path":{"kind":"exact","value":"/"},"hooks":{"response":{"onLeave":"hooks/example.com/GET.js"}}}], + "read":{"metadata":["method","host","path","status"],"headers":[],"queryKeys":[],"body":{"mode":"json"}}, + "write":\(w),"endpointBindings":[],"settings":{}},"sourceFiles":{"hooks/example.com/GET.js":"\(source)"}} + """ + return try PluginPackage.validate(Data(json.utf8)) + } + private func revisionID(_ p: PluginPackage, origin: String = "local") -> String { "\(origin)|\(p.manifest.id.uuidString)|\(p.revision)" } + + private func sha(_ s: String) -> String { SHA256.hash(data: Data(s.utf8)).map { String(format: "%02x", $0) }.joined() } + + private func save(_ s: PluginJSONFileStore, _ p: PluginPackage, key: String, _ text: String, + origin: String = "local", check: @escaping @Sendable () throws -> Void = {}) throws { + try s.save(revisionID: revisionID(p, origin: origin), package: p, key: key, jsonText: text, checkAuthorization: check) + } + + private func namespaces() throws -> [URL] { + guard fm.fileExists(atPath: rootURL.path) else { return [] } + return try fm.contentsOfDirectory(at: rootURL, includingPropertiesForKeys: nil).sorted { $0.path < $1.path } + } + private func onlyNamespace() throws -> URL { + let n = try namespaces() + XCTAssertEqual(n.count, 1) + return try XCTUnwrap(n.first) + } + private func fileURL(_ key: String) throws -> URL { try onlyNamespace().appendingPathComponent(sha(key) + ".json") } + private func entries(_ dir: URL) throws -> [String] { try fm.contentsOfDirectory(atPath: dir.path).sorted() } + private func inode(_ u: URL) throws -> (Int, Date) { + let a = try fm.attributesOfItem(atPath: u.path) + return ((a[.systemFileNumber] as? Int) ?? -1, (a[.modificationDate] as? Date) ?? .distantPast) + } + private func quoted(bytes n: Int) -> String { "\"" + String(repeating: "a", count: n - 2) + "\"" } + private func nested(_ depth: Int) -> String { String(repeating: "[", count: depth) + String(repeating: "]", count: depth) } + private func assertOutsideEmpty(file: StaticString = #filePath, line: UInt = #line) throws { + XCTAssertEqual(try entries(outside), [], "write escaped through a link", file: file, line: line) + } + private func skipIfRoot() throws { try XCTSkipIf(geteuid() == 0, "permission-denied behaviour is not observable as root") } + + // MARK: bytes, replacement, no-op + + func testSavePreservesOriginalBytesExactly() throws { + let p = try package(), s = store() + let text = "{\n \"z\" : 1,\r\n \"a\":\"caf\\u00e9 é 日本 😀 \\n\" ,\"z2\":[ 1.50 , 1e2 ]\n}\n" + try save(s, p, key: "history", text) + XCTAssertEqual(try Data(contentsOf: fileURL("history")), Data(text.utf8)) + XCTAssertEqual(try entries(onlyNamespace()), [sha("history") + ".json"]) + } + + func testFilesAreOwnerOnly() throws { + let p = try package(), s = store() + try save(s, p, key: "k", "{}") + let mode = try fm.attributesOfItem(atPath: fileURL("k").path)[.posixPermissions] as? Int + XCTAssertEqual(mode.map { $0 & 0o777 }, 0o600) + } + + func testSameKeyReplacesAndLeavesNoTemporaries() throws { + let p = try package(), s = store() + try save(s, p, key: "k", #"{"v":1}"#) + try save(s, p, key: "k", #"{"v":2}"#) + XCTAssertEqual(try String(contentsOf: fileURL("k"), encoding: .utf8), #"{"v":2}"#) + XCTAssertEqual(try entries(onlyNamespace()), [sha("k") + ".json"]) + } + + func testIdenticalBytesAreANoOp() throws { + let p = try package(), s = store() + try save(s, p, key: "k", #"{"v":1}"#) + let before = try inode(fileURL("k")) + Thread.sleep(forTimeInterval: 1.1) + try save(s, p, key: "k", #"{"v":1}"#) + let after = try inode(fileURL("k")) + XCTAssertEqual(before.0, after.0) + XCTAssertEqual(before.1, after.1) + } + + func testDifferentKeysAreIndependentFiles() throws { + let p = try package(), s = store() + try save(s, p, key: "a", "1") + try save(s, p, key: "b", "2") + XCTAssertEqual(try entries(onlyNamespace()).sorted(), [sha("a") + ".json", sha("b") + ".json"].sorted()) + } + + // MARK: prepare / commit + + func testPreparedWriteIsInvisibleUntilCommitAndCleansUp() throws { + let p = try package(), s = store() + let prepared = try s.prepare(revisionID: revisionID(p), package: p, key: "k", jsonText: "{}") + XCTAssertTrue(try namespaces().allSatisfy { $0.lastPathComponent.hasPrefix(".tmp-") }) + try prepared.commit() + XCTAssertEqual(try entries(onlyNamespace()), [sha("k") + ".json"]) + XCTAssertThrowsError(try prepared.commit()) + let dropped = try s.prepare(revisionID: revisionID(p), package: p, key: "j", jsonText: "{}") + dropped.discard() + XCTAssertEqual(try namespaces().count, 1) + } + + func testDuplicateObjectKeysAreRejectedButNumberSpellingIsPreserved() throws { + let p = try package(), s = store() + XCTAssertThrowsError(try save(s, p, key: "d", #"{"a":1,"a":2}"#)) + XCTAssertThrowsError(try save(s, p, key: "d", #"{"a":1,"a":2}"#)) + try save(s, p, key: "n", "[1.0, 1E+2, -0]") + XCTAssertEqual(try String(contentsOf: fileURL("n"), encoding: .utf8), "[1.0, 1E+2, -0]") + } + + // MARK: validation + + func testKeyLengthBoundaries() throws { + let p = try package(), s = store() + try save(s, p, key: String(repeating: "k", count: 1024), "{}") + try save(s, p, key: String(repeating: "é", count: 512), "{}") // 1024 UTF-8 bytes + try save(s, p, key: "x", "{}") + XCTAssertThrowsError(try save(s, p, key: String(repeating: "k", count: 1025), "{}")) + XCTAssertThrowsError(try save(s, p, key: String(repeating: "é", count: 513), "{}")) + XCTAssertThrowsError(try save(s, p, key: "", "{}")) + XCTAssertThrowsError(try save(s, p, key: "a\u{0}b", "{}")) + XCTAssertEqual(try entries(onlyNamespace()).count, 3) + } + + func testJSONSizeBoundary() throws { + let p = try package(), s = store() + let max = quoted(bytes: 1024 * 1024) + try save(s, p, key: "max", max) + XCTAssertEqual(try Data(contentsOf: fileURL("max")).count, 1024 * 1024) + XCTAssertThrowsError(try save(s, p, key: "over", quoted(bytes: 1024 * 1024 + 1))) + XCTAssertEqual(try entries(onlyNamespace()), [sha("max") + ".json"]) + } + + func testJSONDepthBoundary() throws { + let p = try package(), s = store() + try save(s, p, key: "d64", nested(64)) + XCTAssertThrowsError(try save(s, p, key: "d65", nested(65))) + XCTAssertThrowsError(try save(s, p, key: "obj65", String(repeating: #"{"a":"#, count: 65) + "1" + String(repeating: "}", count: 65))) + XCTAssertEqual(try entries(onlyNamespace()), [sha("d64") + ".json"]) + } + + func testInvalidJSONIsRejectedWithoutWriting() throws { + let p = try package(), s = store() + for bad in ["", " ", "{", "{} x", "[1,]", "{'a':1}", "nope", "01"] { + XCTAssertThrowsError(try save(s, p, key: "bad", bad), "accepted \(bad)") + } + XCTAssertTrue(try namespaces().isEmpty) + } + + func testRevisionMustMatchPackage() throws { + let p = try package(), other = try package(id: UUID()) + let s = store() + XCTAssertThrowsError(try s.save(revisionID: revisionID(other), package: p, key: "k", jsonText: "{}")) + XCTAssertThrowsError(try s.save(revisionID: "garbage", package: p, key: "k", jsonText: "{}")) + XCTAssertThrowsError(try s.save(revisionID: "local|\(p.manifest.id.uuidString)|" + String(repeating: "0", count: 64), package: p, key: "k", jsonText: "{}")) + XCTAssertTrue(try namespaces().allSatisfy { try entries($0).isEmpty }) + } + + // MARK: permission + + func testPackageWithoutFilesPermissionCannotSave() throws { + let p = try package(files: false), s = store() + XCTAssertThrowsError(try save(s, p, key: "k", "{}")) + XCTAssertTrue(try namespaces().allSatisfy { try entries($0).isEmpty }) + } + + // MARK: namespaces + + func testNamespacesAreIsolatedPerInstallationFamily() throws { + let a = try package(id: UUID()), b = try package(id: UUID()), s = store() + try save(s, a, key: "k", "\"a\"") + try save(s, b, key: "k", "\"b\"") + // Same manifest id from a different trusted origin is a different family. + try save(s, a, key: "k", "\"remote\"", origin: "https://example.com/r/repository.json") + let ns = try namespaces() + XCTAssertEqual(ns.count, 3) + let contents = try ns.map { try String(contentsOf: $0.appendingPathComponent(sha("k") + ".json"), encoding: .utf8) } + XCTAssertEqual(Set(contents), ["\"a\"", "\"b\"", "\"remote\""]) + } + + func testNamespaceIsStableAcrossRevisionsOfOneFamily() throws { + let v1 = try package(source: "// one"), v2 = try package(source: "// two") + XCTAssertNotEqual(v1.revision, v2.revision) + let s = store() + try save(s, v1, key: "k", "1") + try save(s, v2, key: "k", "2") + XCTAssertEqual(try namespaces().count, 1) + XCTAssertEqual(try String(contentsOf: fileURL("k"), encoding: .utf8), "2") + } + + func testNamespaceNameDoesNotLeakKeysOrPaths() throws { + let p = try package(), s = store() + try save(s, p, key: "../../escape/\(UUID().uuidString)", "{}") + let ns = try onlyNamespace() + XCTAssertEqual(ns.deletingLastPathComponent().standardizedFileURL.path, rootURL.standardizedFileURL.path) + XCTAssertFalse(ns.lastPathComponent.contains("/") || ns.lastPathComponent.contains("..")) + XCTAssertEqual(try entries(ns).count, 1) + XCTAssertEqual(try entries(directory).sorted(), ["PluginFiles", "outside"]) + } + + // MARK: quotas + + func testFileCountQuota() throws { + let p = try package(), s = store() + for i in 0..<2048 { try save(s, p, key: "k\(i)", "\(i)") } + XCTAssertThrowsError(try save(s, p, key: "one-too-many", "1")) + XCTAssertEqual(try entries(onlyNamespace()).count, 2048) + // Replacing an existing key does not grow the namespace. + try save(s, p, key: "k0", "999") + XCTAssertEqual(try String(contentsOf: fileURL("k0"), encoding: .utf8), "999") + // Another namespace has its own budget. + try save(s, try package(id: UUID()), key: "k", "1") + } + + func testByteQuota() throws { + let p = try package(), s = store() + func big(_ c: Character) -> String { "\"" + String(repeating: c, count: 1024 * 1024 - 2) + "\"" } + for i in 0..<64 { try save(s, p, key: "b\(i)", big(Character(UnicodeScalar(UInt8(97 + i % 26))))) } + XCTAssertThrowsError(try save(s, p, key: "b64", big("z"))) + XCTAssertEqual(try entries(onlyNamespace()).count, 64) + let before = try Data(contentsOf: fileURL("b1")) + // Same-size replacement fits; growing past the limit does not. + try save(s, p, key: "b0", big("Z")) + XCTAssertNotEqual(try Data(contentsOf: fileURL("b0")), Data(big("a").utf8)) + try save(s, p, key: "b1", "1") + XCTAssertEqual(try entries(onlyNamespace()).count, 64) + XCTAssertNotEqual(before, try Data(contentsOf: fileURL("b1"))) + try save(s, p, key: "b64", "1") + XCTAssertEqual(try entries(onlyNamespace()).count, 65) + } + + // MARK: links and special files + + func testSymlinkedRootIsRejected() throws { + try fm.createSymbolicLink(at: rootURL, withDestinationURL: outside) + XCTAssertThrowsError(try save(store(), try package(), key: "k", "{}")) + try assertOutsideEmpty() + } + + func testSymlinkedNamespaceIsRejected() throws { + let p = try package(), s = store() + try save(s, p, key: "first", "1") + let ns = try onlyNamespace() + let original = ns.deletingLastPathComponent().appendingPathComponent("moved") + try fm.moveItem(at: ns, to: original) + try fm.createSymbolicLink(at: ns, withDestinationURL: outside) + XCTAssertThrowsError(try save(s, p, key: "second", "2")) + try assertOutsideEmpty() + XCTAssertEqual(try entries(original), [sha("first") + ".json"]) + } + + func testSymlinkedFileIsNotFollowedOrReplaced() throws { + let p = try package(), s = store() + try save(s, p, key: "k", "1") + let target = outside.appendingPathComponent("secret.json") + try Data("secret".utf8).write(to: target) + let file = try fileURL("k") + try fm.removeItem(at: file) + try fm.createSymbolicLink(at: file, withDestinationURL: target) + XCTAssertThrowsError(try save(s, p, key: "k", "2")) + XCTAssertEqual(try String(contentsOf: target, encoding: .utf8), "secret") + XCTAssertEqual(try entries(outside), ["secret.json"]) + XCTAssertNotNil(try? fm.destinationOfSymbolicLink(atPath: file.path)) + } + + func testSymlinkOrSpecialEntryInNamespaceFailsClosed() throws { + let p = try package(), s = store() + try save(s, p, key: "keep", "1") + let ns = try onlyNamespace() + try fm.createSymbolicLink(at: ns.appendingPathComponent("link.json"), withDestinationURL: outside) + XCTAssertThrowsError(try save(s, p, key: "next", "2")) + try fm.removeItem(at: ns.appendingPathComponent("link.json")) + XCTAssertEqual(mkfifo(ns.appendingPathComponent("pipe.json").path, 0o600), 0) + XCTAssertThrowsError(try save(s, p, key: "next", "2")) + XCTAssertEqual(try Data(contentsOf: fileURL("keep")), Data("1".utf8)) + XCTAssertFalse(fm.fileExists(atPath: ns.appendingPathComponent(sha("next") + ".json").path)) + try assertOutsideEmpty() + } + + func testDirectoryAtFileLocationIsRejected() throws { + let p = try package(), s = store() + try save(s, p, key: "a", "1") + try fm.createDirectory(at: try onlyNamespace().appendingPathComponent(sha("b") + ".json"), withIntermediateDirectories: false) + XCTAssertThrowsError(try save(s, p, key: "b", "2")) + } + + // MARK: failure preservation + + func testAuthorizationFailurePreservesPriorFileAndLeavesNoTemporaries() throws { + struct Revoked: Error {} + let p = try package(), s = store() + try save(s, p, key: "k", #""old""#) + let calls = Counter() + XCTAssertThrowsError(try save(s, p, key: "k", #""new""#, check: { calls.bump(); throw Revoked() })) { XCTAssertTrue($0 is Revoked) } + XCTAssertThrowsError(try save(s, p, key: "fresh", #""new""#, check: { throw CancellationError() })) { XCTAssertTrue($0 is CancellationError) } + XCTAssertEqual(calls.value, 1, "authorization must be re-checked during the save") + XCTAssertEqual(try String(contentsOf: fileURL("k"), encoding: .utf8), #""old""#) + XCTAssertEqual(try entries(onlyNamespace()), [sha("k") + ".json"]) + } + + func testAuthorizationIsCheckedOnSuccessfulSave() throws { + let calls = Counter() + try save(store(), try package(), key: "k", "{}", check: { calls.bump() }) + XCTAssertGreaterThanOrEqual(calls.value, 1) + } + + func testInvalidReplacementPreservesPriorFile() throws { + let p = try package(), s = store() + try save(s, p, key: "k", #""old""#) + XCTAssertThrowsError(try save(s, p, key: "k", "{")) + XCTAssertThrowsError(try save(s, p, key: "k", nested(65))) + XCTAssertEqual(try String(contentsOf: fileURL("k"), encoding: .utf8), #""old""#) + } + + func testIOFailurePreservesPriorFile() throws { + try skipIfRoot() + let p = try package(), s = store() + try save(s, p, key: "k", #""old""#) + let ns = try onlyNamespace() + try fm.setAttributes([.posixPermissions: 0o500], ofItemAtPath: ns.path) + XCTAssertThrowsError(try save(s, p, key: "k", #""new""#)) + XCTAssertThrowsError(try save(s, p, key: "other", #""new""#)) + try fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: ns.path) + XCTAssertEqual(try String(contentsOf: fileURL("k"), encoding: .utf8), #""old""#) + XCTAssertEqual(try entries(ns), [sha("k") + ".json"]) + try save(s, p, key: "k", #""new""#) + XCTAssertEqual(try String(contentsOf: fileURL("k"), encoding: .utf8), #""new""#) + } + + // MARK: activation fence + + private func activationFixture() async throws -> (PluginActivationStore, PluginPackage, String, PluginActivationSnapshot) { + let p = try package(id: UUID()) + let file = CatalogFile(url: catalogURL) + try file.locked { + var catalog = try file.read().map(CatalogCodec.decode) ?? Catalog() + catalog.revisions.append(InstalledRevision(package: p, provenance: .init(origin: .localImport, trustAtImport: nil), enabled: false)) + try file.replace(with: CatalogCodec.encode(catalog)) + } + let store = PluginActivationStore(fileURL: activeURL, catalogURL: catalogURL) + let initial = try await store.snapshot() + let rid = revisionID(p) + let admitted = try await store.activate(p, revisionID: rid, expectedGeneration: initial.generation) + return (store, p, rid, admitted) + } + + func testFenceRunsOperationWithExactGrantedRevision() async throws { + let (activation, p, rid, admitted) = try await activationFixture() + let seen = Box(nil) + try await activation.withCurrentActivation(admitted: admitted, revisionID: rid) { seen.set($0) } + XCTAssertEqual(seen.get()?.revisionID, rid) + XCTAssertEqual(seen.get()?.package.bytes, p.bytes) + } + + func testFenceRejectsRevokedAdmission() async throws { + let (activation, _, rid, admitted) = try await activationFixture() + _ = try await activation.revoke(revisionID: rid) + let ran = Counter() + do { + try await activation.withCurrentActivation(admitted: admitted, revisionID: rid) { _ in ran.bump() } + XCTFail("stale admission was accepted") + } catch {} + XCTAssertEqual(ran.value, 0) + } + + func testFenceRejectsStaleGenerationAfterReactivation() async throws { + let (activation, p, rid, admitted) = try await activationFixture() + _ = try await activation.revoke(revisionID: rid) + let now = try await activation.snapshot() + _ = try await activation.activate(p, revisionID: rid, expectedGeneration: now.generation) + let ran = Counter() + do { + try await activation.withCurrentActivation(admitted: admitted, revisionID: rid) { _ in ran.bump() } + XCTFail("old generation was accepted") + } catch {} + XCTAssertEqual(ran.value, 0) + } + + func testFenceRejectsRevisionNotGrantedInSnapshot() async throws { + let (activation, p, _, admitted) = try await activationFixture() + let other = "local|\(p.manifest.id.uuidString)|" + String(repeating: "1", count: 64) + let ran = Counter() + do { + try await activation.withCurrentActivation(admitted: admitted, revisionID: other) { _ in ran.bump() } + XCTFail("ungranted revision accepted") + } catch {} + XCTAssertEqual(ran.value, 0) + } + + func testFencePropagatesOperationErrorAndStaysUsable() async throws { + struct Boom: Error {} + let (activation, _, rid, admitted) = try await activationFixture() + do { + try await activation.withCurrentActivation(admitted: admitted, revisionID: rid) { _ in throw Boom() } + XCTFail("error swallowed") + } catch { XCTAssertTrue(error is Boom) } + let ran = Counter() + try await activation.withCurrentActivation(admitted: admitted, revisionID: rid) { _ in ran.bump() } + XCTAssertEqual(ran.value, 1) + } + + func testFenceHoldsActivationLockWhileOperationRuns() async throws { + let (activation, _, rid, admitted) = try await activationFixture() + let other = PluginActivationStore(fileURL: activeURL, catalogURL: catalogURL) + let revoked = Counter() + let revokeTask = Box?>(nil) + try await activation.withCurrentActivation(admitted: admitted, revisionID: rid) { _ in + revokeTask.set(Task { _ = try await other.revoke(revisionID: rid); revoked.bump() }) + Thread.sleep(forTimeInterval: 0.5) + XCTAssertEqual(revoked.value, 0, "revocation completed while the fence was held") + } + try await revokeTask.get()?.value + XCTAssertEqual(revoked.value, 1) + } + + func testRevocationBlocksFurtherSavesButKeepsPublishedFiles() async throws { + let (activation, p, rid, admitted) = try await activationFixture() + let s = store() + try await activation.withCurrentActivation(admitted: admitted, revisionID: rid) { + try s.save(revisionID: $0.revisionID, package: $0.package, key: "k", jsonText: "{}") + } + _ = try await activation.revoke(revisionID: rid) + do { + try await activation.withCurrentActivation(admitted: admitted, revisionID: rid) { + try s.save(revisionID: $0.revisionID, package: $0.package, key: "late", jsonText: "{}") + } + XCTFail("write after revocation") + } catch {} + XCTAssertEqual(try entries(onlyNamespace()), [sha("k") + ".json"]) + _ = p + } + + // MARK: export + + private func exportDestination() throws -> URL { + let d = directory.appendingPathComponent("Documents/Plugins") + try fm.createDirectory(at: d, withIntermediateDirectories: true) + return d + } + + func testExportMirrorsCommittedFilesAndPreservesUnrelatedContent() throws { + let p = try package(), s = store() + try save(s, p, key: "a", #"{"a": 1}"#) + try save(s, p, key: "b", "[1, 2]\n") + let dest = try exportDestination() + try Data("keep".utf8).write(to: dest.appendingPathComponent("notes.txt")) + let ns = try onlyNamespace().lastPathComponent + try fm.createDirectory(at: dest.appendingPathComponent(ns), withIntermediateDirectories: true) + try Data("mine".utf8).write(to: dest.appendingPathComponent(ns).appendingPathComponent("user.txt")) + try fm.createDirectory(at: dest.appendingPathComponent("other"), withIntermediateDirectories: true) + try Data("{}".utf8).write(to: dest.appendingPathComponent("other/x.json")) + + try s.export(to: dest) + for key in ["a", "b"] { + XCTAssertEqual(try Data(contentsOf: dest.appendingPathComponent(ns).appendingPathComponent(sha(key) + ".json")), + try Data(contentsOf: fileURL(key))) + } + XCTAssertEqual(try String(contentsOf: dest.appendingPathComponent("notes.txt"), encoding: .utf8), "keep") + XCTAssertEqual(try String(contentsOf: dest.appendingPathComponent(ns).appendingPathComponent("user.txt"), encoding: .utf8), "mine") + XCTAssertEqual(try String(contentsOf: dest.appendingPathComponent("other/x.json"), encoding: .utf8), "{}") + } + + func testExportNeverImportsEditedDocumentsFiles() throws { + let p = try package(), s = store() + try save(s, p, key: "a", "1") + let dest = try exportDestination() + try s.export(to: dest) + let ns = try onlyNamespace().lastPathComponent + let exported = dest.appendingPathComponent(ns).appendingPathComponent(sha("a") + ".json") + try Data("edited".utf8).write(to: exported) + try s.export(to: dest) + XCTAssertEqual(try String(contentsOf: fileURL("a"), encoding: .utf8), "1") + XCTAssertEqual(try String(contentsOf: exported, encoding: .utf8), "1") + try s.export(to: dest) // idempotent + } + + func testExportRejectsSymlinkedSourceFile() throws { + let p = try package(), s = store() + try save(s, p, key: "a", "1") + let file = try fileURL("a") + let target = outside.appendingPathComponent("secret.json") + try Data("secret".utf8).write(to: target) + try fm.removeItem(at: file) + try fm.createSymbolicLink(at: file, withDestinationURL: target) + let dest = try exportDestination() + XCTAssertThrowsError(try s.export(to: dest)) + XCTAssertFalse(try fm.subpathsOfDirectory(atPath: dest.path).contains { $0.hasSuffix(".json") }) + XCTAssertEqual(try String(contentsOf: target, encoding: .utf8), "secret") + } + + func testExportRejectsSymlinkedSourceNamespaceAndRoot() throws { + let p = try package(), s = store() + try save(s, p, key: "a", "1") + let ns = try onlyNamespace() + let moved = directory.appendingPathComponent("moved-ns") + try fm.moveItem(at: ns, to: moved) + try fm.createSymbolicLink(at: ns, withDestinationURL: moved) + let dest = try exportDestination() + XCTAssertThrowsError(try s.export(to: dest)) + try fm.removeItem(at: ns) + try fm.moveItem(at: moved, to: ns) + let realRoot = directory.appendingPathComponent("real-root") + try fm.moveItem(at: rootURL, to: realRoot) + try fm.createSymbolicLink(at: rootURL, withDestinationURL: realRoot) + XCTAssertThrowsError(try s.export(to: dest)) + XCTAssertFalse(try fm.subpathsOfDirectory(atPath: dest.path).contains { $0.hasSuffix(".json") }) + } + + func testExportRejectsSymlinkedDestinationParts() throws { + let p = try package(), s = store() + try save(s, p, key: "a", "1") + let ns = try onlyNamespace().lastPathComponent + + // Destination root is a symlink. + let linkedDest = directory.appendingPathComponent("LinkedPlugins") + try fm.createSymbolicLink(at: linkedDest, withDestinationURL: outside) + XCTAssertThrowsError(try s.export(to: linkedDest)) + try assertOutsideEmpty() + + // Destination namespace is a symlink. + let dest = try exportDestination() + try fm.createSymbolicLink(at: dest.appendingPathComponent(ns), withDestinationURL: outside) + XCTAssertThrowsError(try s.export(to: dest)) + try assertOutsideEmpty() + try fm.removeItem(at: dest.appendingPathComponent(ns)) + + // Destination file is a symlink. + try fm.createDirectory(at: dest.appendingPathComponent(ns), withIntermediateDirectories: true) + let target = outside.appendingPathComponent("victim.json") + try Data("victim".utf8).write(to: target) + try fm.createSymbolicLink(at: dest.appendingPathComponent(ns).appendingPathComponent(sha("a") + ".json"), withDestinationURL: target) + XCTAssertThrowsError(try s.export(to: dest)) + XCTAssertEqual(try String(contentsOf: target, encoding: .utf8), "victim") + XCTAssertEqual(try entries(outside), ["victim.json"]) + } +} + +private final class Counter: @unchecked Sendable { + private let lock = NSLock(); private var n = 0 + func bump() { lock.lock(); n += 1; lock.unlock() } + var value: Int { lock.lock(); defer { lock.unlock() }; return n } +} + +private final class Box: @unchecked Sendable { + private let lock = NSLock(); private var v: T + init(_ v: T) { self.v = v } + func set(_ new: T) { lock.lock(); v = new; lock.unlock() } + func get() -> T { lock.lock(); defer { lock.unlock() }; return v } +} diff --git a/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/HTTPHooksRuntimeTests.swift b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/HTTPHooksRuntimeTests.swift index 182d0c4..5a27a0a 100644 --- a/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/HTTPHooksRuntimeTests.swift +++ b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/HTTPHooksRuntimeTests.swift @@ -369,7 +369,7 @@ final class HTTPHooksRuntimeTests: XCTestCase, @unchecked Sendable { let r = try await run(src, .requestEnter) let json = try XCTUnwrap(((r["actions"] as? [[String: Any]])?.first)?["json"] as? [String: Any]) for name in names { XCTAssertEqual(json[name] as? String, "undefined", name) } - XCTAssertEqual(json["keys"] as? String, "attach,send") + XCTAssertEqual(json["keys"] as? String, "attach,send,Storage") } func testHostCapturedIntrinsicsSurviveUserTampering() async throws { diff --git a/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/JavaScriptCreateFileTests.swift b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/JavaScriptCreateFileTests.swift new file mode 100644 index 0000000..a79cb18 --- /dev/null +++ b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/JavaScriptCreateFileTests.swift @@ -0,0 +1,908 @@ +import AutomationCore +@testable import AutomationRuntime +import XCTest + +/// `Interceptor.createFile({storage, atPath, contents})` through the real shared C runtime (`qjs_run_v2_fetch_files`), +/// response.onLeave only. Swift interface: `JavaScriptFetchExecutor.CreateFile = @Sendable (PluginFileDestination, Data) +/// async throws -> Void` and `runV2(... configJSON:, createFile: CreateFile? = nil, transport:)`. +final class JavaScriptCreateFileTests: XCTestCase, @unchecked Sendable { + private let file = "hooks/api.example.com/credentials/GET.js" + private let route = #"{"hosts":["api.example.com"],"methods":["GET"],"path":{"kind":"exact","value":"/credentials"},"hooks":{"response":{"onLeave":"hooks/api.example.com/credentials/GET.js"}}}"# + private let event = Data(#"{"request":{"method":"GET","host":"api.example.com","path":"/credentials"},"response":{"status":200,"headers":{},"body":{"accessToken":"t"}}}"#.utf8) + private let config = Data("{}".utf8) + private let url = "https://api.example.com/v1/profile" + private static let oneMiB = 1024 * 1024 + + private struct WriteFailure: Error {} + + private struct Write: Equatable { + var storage: PluginFileStorage + var path: String + var contents: Data + var text: String { String(decoding: contents, as: UTF8.self) } + } + + private actor Writes { + var items: [Write] = [] + var cancelled = 0 + func add(_ d: PluginFileDestination, _ c: Data) { items.append(Write(storage: d.storage, path: d.atPath, contents: c)) } + func markCancelled() { cancelled += 1 } + } + + private func package(_ source: String, files: Bool? = true, route override: String? = nil) throws -> Data { + let code = try JSONValue.string(source).jsonString() + let selectedRoute = override ?? route + let write = files.map { #"{"requestBody":false,"responseBody":false,"files":\#($0)}"# } ?? #"{"requestBody":false,"responseBody":false}"# + let m = #"{"schemaVersion":2,"id":"22222222-2222-4222-8222-222222222222","name":"Sample","version":"1.0.0","matches":[\#(selectedRoute)],"read":{"metadata":["host"],"headers":[],"queryKeys":[],"body":{"mode":"json"}},"write":\#(write),"endpointBindings":[],"settings":{},"outbound":{}}"# + return Data(#"{"manifest":\#(m),"sourceFiles":{"\#(file)":\#(code)}}"#.utf8) + } + + private func run(_ body: String, top: String = "", files: Bool? = true, hook: JavaScriptHook = .responseLeave, + executor: JavaScriptFetchExecutor = JavaScriptFetchExecutor(), writes: Writes = Writes(), + create: JavaScriptFetchExecutor.CreateFile? = nil, + transport: @escaping JavaScriptFetchExecutor.Transport = { _ in JavaScriptFetchResponse(status: 200, body: Data("{\"a\":1}".utf8)) }) async throws -> [[String: Any]] + { + let pkg = try package("\(top)Interceptor.attach({response:{onLeave:\(body)}});", files: files) + let callback: JavaScriptFetchExecutor.CreateFile = create ?? { d, c in await writes.add(d, c) } + let data = try await executor.runV2(packageJSON: pkg, hook: hook, eventJSON: event, configJSON: config, createFile: callback, transport: transport) + let obj = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + return try XCTUnwrap(obj["actions"] as? [[String: Any]]) + } + + private func expectError(_ expected: JavaScriptExecutionError, _ body: String, top: String = "", files: Bool? = true, + executor: JavaScriptFetchExecutor = JavaScriptFetchExecutor(), writes: Writes = Writes(), + create: JavaScriptFetchExecutor.CreateFile? = nil, line: UInt = #line) async + { + do { + let r = try await run(body, top: top, files: files, executor: executor, writes: writes, create: create) + XCTFail("expected \(expected), got \(r)", line: line) + } catch { XCTAssertEqual(error as? JavaScriptExecutionError, expected, line: line) } + } + + /// `Interceptor.createFile({...})` source for a call with the given option-object literal. + private func call(_ options: String) -> String { "Interceptor.createFile(\(options))" } + + private func opts(path: String = "'f.txt'", storage: String = "Interceptor.Storage.local", contents: String = "'x'") -> String { + "{storage: \(storage), atPath: \(path), contents: \(contents)}" + } + + /// The hook must see createFile reject catchably and the host callback never run. + private func assertRejectsWithoutCallback(_ expression: String, files: Bool? = true, line: UInt = #line) async throws { + let writes = Writes() + _ = try await run("async () => { try { await \(expression); } catch (e) { return; } throw new Error('accepted'); }", files: files, writes: writes) + let n = await writes.items.count + XCTAssertEqual(n, 0, "callback must not run for \(expression)", line: line) + } + + // MARK: exact interface and bytes + + func testGrantedWriteBatchCanUseMoreThanFetchOnlyCpuBudget() async throws { + let writes = Writes() + _ = try await run("async () => { const start = Date.now(); while (Date.now() - start < 350) {} await \(call(opts())); }", writes: writes) + let count = await writes.items.count + XCTAssertEqual(count, 1) + } + + func testMissingFilesGrantKeepsShortCpuBudget() async { + for files in [false, nil] as [Bool?] { + await expectError(.timeout, "async () => { const start = Date.now(); while (Date.now() - start < 350) {} }", files: files) + } + } + + func testCreateFileDeliversStoragePathAndRawNonJSONText() async throws { + let writes = Writes() + _ = try await run("async () => { await \(call(opts(path: "'Salmon Run/history.json'", storage: "Interceptor.Storage.iCloudDrive", contents: "'raw text not JSON'"))); }", writes: writes) + let items = await writes.items + XCTAssertEqual(items, [Write(storage: .icloud, path: "Salmon Run/history.json", contents: Data("raw text not JSON".utf8))]) + } + + func testCreateFileAcceptsEmptyTextAndReplacesSaveJSON() async throws { + let writes = Writes() + _ = try await run(""" + async () => { + if (typeof Interceptor.saveJSON !== 'undefined') throw new Error('saveJSON alias remains'); + if (typeof Interceptor.createFile !== 'function' || Interceptor.createFile.length !== 1) throw new Error('shape'); + const v = await \(call(opts(path: "'empty.txt'", contents: "''"))); + if (v !== undefined) throw new Error('value'); + } + """, writes: writes) + let items = await writes.items + XCTAssertEqual(items, [Write(storage: .local, path: "empty.txt", contents: Data())]) + } + + func testRawTextPreservesUTF8NulWhitespaceAndNormalization() async throws { + let original = " {\n\t\"z\" : 1 ,\"a\":[1.0, 1e2, -0],\"s\":\"日本語😀é\\u00e9\\ud83d\\ude00\\/\",\"n\":null }\r\n" + let decomposed = "e\u{0301}-日本-😀 \u{0}nul\u{0}" + let bytes = Data(original.utf8) + let writes = Writes() + _ = try await run(""" + async () => { + const t = await (await fetch('\(url)')).text(); + await \(call(opts(path: "'a.txt'", contents: "t"))); + await \(call(opts(path: "'b.txt'", contents: try JSONValue.string(decomposed).jsonString()))); + } + """, writes: writes, transport: { _ in JavaScriptFetchResponse(status: 200, body: bytes) }) + let items = await writes.items + XCTAssertEqual(items.map(\.contents), [bytes, Data(decomposed.utf8)]) + } + + func testNonJSONAndInvalidJSONContentsAreNeverParsedOrRequireExtension() async throws { + let docs = ["", " ", "{bad", "[1 2]", "NaN", "{\"a\":1,\"a\":2}", String(repeating: "[", count: 200), "{\"a\":\"\u{0001}\"}", "plain"] + let literal = try JSONValue.array(docs.map { .string($0) }).jsonString() + let writes = Writes() + _ = try await run("async () => { let i = 0; for (const d of \(literal)) await \(call(opts(path: "'noext' + (i++)", contents: "d"))); }", writes: writes) + let got = await writes.items.map(\.text) + XCTAssertEqual(got, docs) + } + + func testSequentialAwaitedWritesRunInOrderAndSamePathRepeats() async throws { + let writes = Writes() + _ = try await run("async () => { await \(call(opts(path: "'a'", contents: "'1'"))); await \(call(opts(path: "'a'", contents: "'2'"))); await \(call(opts(path: "'b'", contents: "'3'"))); }", writes: writes) + let items = await writes.items + XCTAssertEqual(items.map(\.path), ["a", "a", "b"]) + XCTAssertEqual(items.map(\.text), ["1", "2", "3"]) + } + + func testPromiseSettlesOnlyAfterCallbackReturns() async throws { + let writes = Writes() + _ = try await run("async () => { const p = \(call(opts())); if (!(p instanceof Promise)) throw new Error('not a promise'); const v = await p; if (v !== undefined) throw new Error('value'); }", writes: writes) + let n = await writes.items.count + XCTAssertEqual(n, 1) + let order = Writes() + _ = try await run("async () => { await \(call(opts())); await fetch('\(url)'); }", writes: order, create: { d, c in + try await Task.sleep(nanoseconds: 200_000_000) + await order.add(d, c) + }) { _ in + let done = await order.items.count + XCTAssertEqual(done, 1, "fetch must start only after the awaited write completed") + return JavaScriptFetchResponse(status: 200, body: Data()) + } + } + + // MARK: binary contents + + func testUint8ArrayBytesAreExactIncludingZerosEmptyAndHighBytes() async throws { + let writes = Writes() + _ = try await run(""" + async () => { + const all = new Uint8Array(256); + for (let i = 0; i < 256; i++) all[i] = i; + await \(call(opts(path: "'all.bin'", contents: "all"))); + await \(call(opts(path: "'zero.bin'", contents: "new Uint8Array([0, 0, 0])"))); + await \(call(opts(path: "'empty.bin'", contents: "new Uint8Array(0)"))); + await \(call(opts(path: "'nul-text'", contents: "'a\\u0000b'"))); + } + """, writes: writes) + let items = await writes.items + XCTAssertEqual(items.map(\.path), ["all.bin", "zero.bin", "empty.bin", "nul-text"]) + XCTAssertEqual(items[0].contents, Data((0 ... 255).map { UInt8($0) })) + XCTAssertEqual(items[1].contents, Data([0, 0, 0])) + XCTAssertEqual(items[2].contents, Data()) + XCTAssertEqual(items[3].contents, Data([0x61, 0, 0x62])) + } + + func testUint8ArraySubviewsAndOffsetsSendOnlyTheViewedBytes() async throws { + let writes = Writes() + _ = try await run(""" + async () => { + const buffer = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]).buffer; + await \(call(opts(path: "'mid'", contents: "new Uint8Array(buffer, 2, 3)"))); + await \(call(opts(path: "'tail'", contents: "new Uint8Array(buffer, 6)"))); + await \(call(opts(path: "'sub'", contents: "new Uint8Array(buffer).subarray(1, 4)"))); + await \(call(opts(path: "'zero-len'", contents: "new Uint8Array(buffer, 8)"))); + } + """, writes: writes) + let items = await writes.items + XCTAssertEqual(items.map(\.contents), [Data([3, 4, 5]), Data([7, 8]), Data([2, 3, 4]), Data()]) + } + + func testBinarySizeLimitIsOneMiBInclusive() async throws { + let writes = Writes() + _ = try await run("async () => { await \(call(opts(path: "'big'", contents: "new Uint8Array(\(Self.oneMiB)).fill(7)"))); }", writes: writes) + let items = await writes.items + XCTAssertEqual(items.first?.contents.count, Self.oneMiB) + XCTAssertEqual(items.first?.contents.allSatisfy { $0 == 7 }, true) + try await assertRejectsWithoutCallback(call(opts(contents: "new Uint8Array(\(Self.oneMiB + 1))"))) + } + + func testOtherBinaryShapesAreRejectedWithoutCallback() async throws { + let rejected = [ + "new ArrayBuffer(4)", "new Uint8ClampedArray(4)", "new Int8Array(4)", "new Uint16Array(2)", "new Int32Array(1)", + "new Float64Array(1)", "new DataView(new ArrayBuffer(4))", "[1, 2, 3]", "{length: 1, 0: 1}", + "new Proxy(new Uint8Array(2), {})", "new Proxy({}, {})", "Object.create(Uint8Array.prototype)", + "null", "undefined", "42", "true", "Symbol('s')", "{toString() { return 'x'; }}", "new String('x')", + ] + for contents in rejected { + try await assertRejectsWithoutCallback(call(opts(contents: contents))) + } + } + + func testSharedBuffersDoNotExistAndCannotReachTheHost() async throws { + _ = try await run(""" + async () => { + for (const name of ['SharedArrayBuffer', 'Atomics', 'WebAssembly']) { + if (typeof globalThis[name] !== 'undefined') throw new Error(name); + } + if (typeof Uint8Array !== 'function' || typeof ArrayBuffer !== 'function') throw new Error('missing'); + if (!(Uint8Array.prototype.constructor === Uint8Array)) throw new Error('shape'); + } + """) + } + + func testDetachedViewsAreRejectedWithoutCallback() async throws { + let writes = Writes() + _ = try await run(""" + async () => { + const bytes = new Uint8Array([1, 2, 3]); + const moved = bytes.buffer.transfer ? bytes.buffer.transfer() : null; + if (!moved) return; // runtime without ArrayBuffer.prototype.transfer cannot detach from script + if (bytes.byteLength !== 0) throw new Error('not detached'); + try { await \(call(opts(contents: "bytes"))); } catch (e) { return; } + throw new Error('accepted detached view'); + } + """, writes: writes) + let n = await writes.items.count + XCTAssertEqual(n, 0) + } + + func testBytesAreCapturedAtCallTimeNotAliasedAfterwards() async throws { + let writes = Writes() + _ = try await run(""" + async () => { + const bytes = new Uint8Array([1, 2, 3]); + const p = \(call(opts(contents: "bytes"))); + bytes[0] = 99; + await p; + } + """, writes: writes) + let items = await writes.items + XCTAssertEqual(items.first?.contents, Data([1, 2, 3])) + } + + func testTypedArrayGlobalsExistOnlyInDeferredLeaveRuntime() async throws { + // Synchronous v2 phases and the legacy v1 executor keep the previous surface (no typed arrays, no shared memory). + let sync = try package("Interceptor.attach({request:{onEnter(){ if (typeof Uint8Array !== 'undefined' || typeof ArrayBuffer !== 'undefined' || typeof SharedArrayBuffer !== 'undefined' || typeof Atomics !== 'undefined') throw new Error('typed arrays'); }, onLeave(){}}, response:{onEnter(){}, onLeave(){}}});") + _ = try await JavaScriptExecutor().runV2(packageJSON: sync, hook: .requestEnter, eventJSON: event, configJSON: config) + // The deferred response.onLeave runtime (with or without a create callback) has Uint8Array but never shared memory. + let leave = try package("Interceptor.attach({response:{onLeave:async () => { if (typeof Uint8Array !== 'function' || typeof SharedArrayBuffer !== 'undefined' || typeof Atomics !== 'undefined') throw new Error('surface'); }}});", files: nil) + _ = try await JavaScriptFetchExecutor().runV2(packageJSON: leave, hook: .responseLeave, eventJSON: event, configJSON: config) { _ in + JavaScriptFetchResponse(status: 200, body: Data()) + } + } + // MARK: Enum, options object and descriptors + + func testStorageEnumIsAvailableBeforeMultiPhaseSourceEvaluation() async throws { + let multiRoute = route.replacingOccurrences(of: "\"hooks\":{", with: "\"hooks\":{\"request\":{\"onEnter\":\"\(file)\"},") + let source = """ + const target = Interceptor.Storage.iCloudDrive; + Interceptor.attach({request:{onEnter(){if(target !== 'icloud') throw new Error('storage');}}, + response:{onLeave(){if(target !== 'icloud') throw new Error('storage');}}}); + """ + let pkg = try package(source, route: multiRoute) + _ = try await JavaScriptExecutor().runV2(packageJSON: pkg, hook: .requestEnter, eventJSON: event, configJSON: config) + _ = try await JavaScriptFetchExecutor().runV2(packageJSON: pkg, hook: .responseLeave, eventJSON: event, configJSON: config) { _ in + JavaScriptFetchResponse(status: 200, body: Data()) + } + } + + func testOptionsWithCustomPrototypesAreRejectedWithoutCallbacks() async throws { + for expression in [ + "Object.assign(Object.create({marker: 1}), {storage: Interceptor.Storage.local, atPath: 'a', contents: 'x'})", + "new (class Options { constructor() { this.storage = Interceptor.Storage.local; this.atPath = 'a'; this.contents = 'x'; } })()", + ] { + try await assertRejectsWithoutCallback("Interceptor.createFile(\(expression))") + } + } + + func testStorageEnumValuesAreImmutable() async throws { + _ = try await run(""" + async () => { + const s = Interceptor.Storage; + if (s.local !== 'local' || s.iCloudDrive !== 'icloud') throw new Error('values'); + if (Object.keys(s).sort().join(',') !== 'iCloudDrive,local') throw new Error('keys'); + if (!Object.isFrozen(s)) throw new Error('not frozen'); + try { s.local = 'x'; s.extra = 'y'; delete s.iCloudDrive; } catch (e) {} + if (s.local !== 'local' || s.iCloudDrive !== 'icloud' || 'extra' in s) throw new Error('mutated'); + for (const key of ['local', 'iCloudDrive']) { + const d = Object.getOwnPropertyDescriptor(s, key); + if (d.writable || d.configurable || !d.enumerable) throw new Error('descriptor ' + key); + } + const b = Object.getOwnPropertyDescriptor(Interceptor, 'Storage'); + if (b.writable || b.configurable) throw new Error('binding'); + for (const attempt of [() => { Interceptor.Storage = {}; }, () => { delete Interceptor.Storage; }, + () => Object.defineProperty(Interceptor, 'Storage', {value: {}}), + () => Object.defineProperty(s, 'local', {value: 'icloud'}), + () => Object.setPrototypeOf(s, {})]) { + try { attempt(); } catch (e) {} + if (Interceptor.Storage !== s || s.local !== 'local') throw new Error('replaced'); + } + if (Object.getPrototypeOf(s) !== Object.prototype) throw new Error('prototype'); + } + """) + } + + func testInterceptorSurfaceKeepsAttachSendAndAddsCreateFileAndStorage() async throws { + _ = try await run("async () => { const keys = Object.keys(Interceptor).sort().join(','); if (keys !== 'Storage,attach,createFile,send' && keys !== 'Storage,attach,createFile') throw new Error(keys); if (typeof fetch !== 'function' || typeof Interceptor.attach !== 'function') throw new Error('shape'); }") + } + + func testOptionsObjectMustBeExactlyThreeOwnEnumerableDataProperties() async throws { + let bad = [ + "{storage: Interceptor.Storage.local, atPath: 'a'}", "{storage: Interceptor.Storage.local, contents: 'x'}", + "{atPath: 'a', contents: 'x'}", "{}", + "{storage: Interceptor.Storage.local, atPath: 'a', contents: 'x', extra: 1}", + "{storage: Interceptor.Storage.local, atPath: 'a', contents: 'x', [Symbol('s')]: 1}", + "{storage: Interceptor.Storage.local, atPath: 'a', contents: 'x', 0: 1}", + "Object.defineProperty({storage: Interceptor.Storage.local, atPath: 'a'}, 'contents', {value: 'x', enumerable: false})", + "Object.create({storage: Interceptor.Storage.local, atPath: 'a', contents: 'x'})", + "Object.assign(Object.create({contents: 'x'}), {storage: Interceptor.Storage.local, atPath: 'a'})", + "new Proxy({storage: Interceptor.Storage.local, atPath: 'a', contents: 'x'}, {})", + "['local', 'a', 'x']", "'a'", "null", "undefined", "42", "() => {}", "new Map()", + ] + for options in bad { + try await assertRejectsWithoutCallback("Interceptor.createFile(\(options))") + } + try await assertRejectsWithoutCallback("Interceptor.createFile()") + try await assertRejectsWithoutCallback("Interceptor.createFile(\(opts()), 1)") + } + + func testAccessorsAndProxiesAreRejectedWithoutInvokingUserCode() async throws { + let writes = Writes() + _ = try await run(""" + async () => { + let invoked = 0; + const getter = {storage: Interceptor.Storage.local, atPath: 'a'}; + Object.defineProperty(getter, 'contents', {get() { invoked++; return 'x'; }, enumerable: true}); + const proxy = new Proxy({storage: Interceptor.Storage.local, atPath: 'a', contents: 'x'}, { + get() { invoked++; }, getOwnPropertyDescriptor() { invoked++; }, ownKeys() { invoked++; return []; }, has() { invoked++; }, getPrototypeOf() { invoked++; return null; }, + }); + const stringy = {toString() { invoked++; return 'local'; }}; + const objectContents = {storage: Interceptor.Storage.local, atPath: 'a', contents: {toString() { invoked++; return 'x'; }}}; + const objectPath = {storage: Interceptor.Storage.local, atPath: {toString() { invoked++; return 'a'; }}, contents: 'x'}; + const objectStorage = {storage: stringy, atPath: 'a', contents: 'x'}; + const bytes = new Uint8Array(1); + Object.defineProperty(bytes, 'buffer', {get() { invoked++; return new ArrayBuffer(1); }}); + Object.defineProperty(bytes, 'length', {get() { invoked++; return 1; }}); + Object.defineProperty(bytes, 'byteOffset', {get() { invoked++; return 0; }}); + const viewOverride = {storage: Interceptor.Storage.local, atPath: 'a', contents: bytes}; + for (const o of [getter, proxy, objectContents, objectPath, objectStorage]) { + try { await Interceptor.createFile(o); throw new Error('accepted'); } catch (e) { if (String(e && e.message) === 'accepted') throw e; } + } + // Instance-level shadowing of typed array accessors must not steer the bytes the host receives. + await Interceptor.createFile(viewOverride); + if (invoked !== 0) throw new Error('user code ran ' + invoked); + } + """, writes: writes) + let items = await writes.items + XCTAssertEqual(items.map(\.contents), [Data([0])], "only the pristine-class view with shadowed accessors is accepted, using real bytes") + } + + func testStorageValuesMustBeTheExactEnumStrings() async throws { + for storage in ["'LOCAL'", "'iCloudDrive'", "'cloud'", "'local '", "'icloud\\u0000'", "''", "'iCloud'", "1", "null", "undefined", "{}", "Interceptor.Storage", "Symbol('local')"] { + try await assertRejectsWithoutCallback(call(opts(storage: storage))) + } + // The raw strings are equivalent to the Enum values. + let writes = Writes() + _ = try await run("async () => { await \(call(opts(path: "'a'", storage: "'local'"))); await \(call(opts(path: "'b'", storage: "'icloud'"))); }", writes: writes) + let items = await writes.items + XCTAssertEqual(items.map(\.storage), [.local, .icloud]) + } + + // MARK: structural path validation + + func testPathWithCombiningMarkAfterSlashPreservesScalarComponents() async throws { + let path = "a/\u{0301}b.txt" + let writes = Writes() + let callback: JavaScriptFetchExecutor.CreateFile = { destination, contents in + XCTAssertEqual(Array(destination.atPath.utf8), Array(path.utf8)) + XCTAssertEqual(destination.pathComponents, ["a", "\u{0301}b.txt"]) + await writes.add(destination, contents) + } + let literal = try JSONValue.string(path).jsonString() + _ = try await run("async () => { await \(call(opts(path: literal))); }", writes: writes, create: callback) + let items = await writes.items + XCTAssertEqual(items.count, 1) + XCTAssertEqual(items.first?.contents, Data("x".utf8)) + } + + func testCombiningMarkDoesNotHideLeadingDotFromCPathValidation() async throws { + let path = try JSONValue.string(".\u{0301}hidden").jsonString() + let writes = Writes() + _ = try await run(""" + async () => { + for (let i = 0; i < 64; i++) { + try { await \(call(opts(path: path))); } catch (e) {} + } + await \(call(opts(path: "'visible.txt'"))); + } + """, writes: writes) + // A Swift-only rejection would consume all 64 submitted-host attempts. The valid final write proves + // the leading-dot path was rejected by C before reaching its callback or consuming the write budget. + let items = await writes.items + XCTAssertEqual(items.map(\.path), ["visible.txt"]) + } + + func testStructurallyInvalidPathsRejectWithoutCallback() async throws { + let long = String(repeating: "a", count: 256) + let deep = (0 ... 8).map { "d\($0)" }.joined(separator: "/") + let paths = [ + "''", "'/abs'", "'/'", "'a//b'", "'a/'", "'a/b/'", "'.'", "'..'", "'a/./b'", "'a/../b'", "'../a'", "'.hidden'", "'a/.hidden'", + "'a\\\\b'", "'a:b'", "'C:/x'", "'a\\u0000b'", "'a\\nb'", "'a\\tb'", "'a\\u007fb'", "'a\\u0085b'", "'a\\u009fb'", "'\\ud800'", "'x\\udc00'", + "'\(long)'", "'ok/\(long)'", "'\(deep)'", "42", "null", "undefined", "{}", "['a']", "new String('a')", + ] + for path in paths { + try await assertRejectsWithoutCallback(call(opts(path: path))) + } + } + + func testPathLimitsAreInclusiveUTF8ByteBounds() async throws { + let component255 = String(repeating: "a", count: 255) + let wide = String(repeating: "あ", count: 85) // 255 bytes + let deep8 = (0 ..< 8).map { "d\($0)" }.joined(separator: "/") + let max1024 = [component255, component255, component255, String(repeating: "c", count: 254), "d"].joined(separator: "/") + XCTAssertEqual(max1024.utf8.count, 1024) + let writes = Writes() + _ = try await run(""" + async () => { + for (const p of ['\(component255)', '\(wide)', '\(deep8)', '\(max1024)', 'a.b/c d/é.txt', 'ends.', 'Salmon Run/history.json', 'emoji😀/x']) { + await \(call(opts(path: "p"))); + } + } + """, writes: writes) + let paths = await writes.items.map(\.path) + XCTAssertEqual(paths, [component255, wide, deep8, max1024, "a.b/c d/é.txt", "ends.", "Salmon Run/history.json", "emoji😀/x"]) + try await assertRejectsWithoutCallback(call(opts(path: "'\(max1024)x'"))) + try await assertRejectsWithoutCallback(call(opts(path: "'\(String(repeating: "あ", count: 86))'"))) + } + + func testPathSpellingIsDeliveredVerbatimWithoutNormalizationOrCaseFolding() async throws { + // C only validates structure; Core owns NFC and case aliases (it rejects non-NFC, which this callback sees as `try?` failure). + let writes = Writes() + _ = try await run("async () => { await \(call(opts(path: "'Äb/ÄB.TXT'"))); }", writes: writes) + let items = await writes.items + XCTAssertEqual(items.map(\.path), ["Äb/ÄB.TXT"]) + let decomposed = Writes() + _ = try await run("async () => { try { await \(call(opts(path: "'e\\u0301.txt'"))); } catch (e) { return; } throw new Error('non-NFC accepted'); }", writes: decomposed) + let none = await decomposed.items.count + XCTAssertEqual(none, 0, "non-NFC spellings are refused by Core's destination validation, never rewritten") + } + + // MARK: permission + + func testDeniedOrAbsentFilesPermissionRejectsWithoutCallback() async throws { + for files in [false, nil] as [Bool?] { + try await assertRejectsWithoutCallback(call(opts()), files: files) + let writes = Writes() + await expectError(.scriptError, "async () => { await \(call(opts())); }", files: files, writes: writes) + let n = await writes.items.count + XCTAssertEqual(n, 0) + } + } + + func testMissingCreateCallbackRejectsEvenWithPermission() async throws { + let pkg = try package("Interceptor.attach({response:{onLeave:async () => { try { await \(call(opts())); } catch (e) { return; } throw new Error('accepted'); }}});") + _ = try await JavaScriptFetchExecutor().runV2(packageJSON: pkg, hook: .responseLeave, eventJSON: event, configJSON: config) { _ in + JavaScriptFetchResponse(status: 200, body: Data()) + } + } + + // MARK: per-invocation budgets + + func testWriteCountCapIs64() async throws { + let writes = Writes() + _ = try await run("async () => { let rejected = 0; for (let i = 0; i < 65; i++) { try { await \(call(opts(path: "'k' + i"))); } catch (e) { rejected++; } } if (rejected !== 1) throw new Error('r' + rejected); }", writes: writes) + let n = await writes.items.count + XCTAssertEqual(n, 64) + } + + func testEmptyFilesCountTowardTheWriteCount() async throws { + let writes = Writes() + _ = try await run("async () => { let rejected = 0; for (let i = 0; i < 65; i++) { try { await \(call(opts(path: "'e' + i", contents: "new Uint8Array(0)"))); } catch (e) { rejected++; } } if (rejected !== 1) throw new Error('r' + rejected); }", writes: writes) + let n = await writes.items.count + XCTAssertEqual(n, 64) + } + + func testSubmittedBytesCapIs16MiBAcrossTextAndBinary() async throws { + let writes = Writes() + // 16 files of exactly 1 MiB are accepted (mixed text/binary); the 17th is rejected and never reaches the host. + _ = try await run(""" + async () => { + const text = 'a'.repeat(\(Self.oneMiB)); + const bin = new Uint8Array(\(Self.oneMiB)); + let rejected = 0; + for (let i = 0; i < 17; i++) { + try { await \(call(opts(path: "'k' + i", contents: "i % 2 ? bin : text"))); } catch (e) { rejected++; } + } + if (rejected !== 1) throw new Error('r' + rejected); + } + """, writes: writes) + let n = await writes.items.count + XCTAssertEqual(n, 16) + } + + func testTextSizeLimitIsOneMiBOfUTF8BytesNotCharacters() async throws { + let writes = Writes() + _ = try await run("async () => { await \(call(opts(path: "'ok'", contents: "'a'.repeat(\(Self.oneMiB))"))); }", writes: writes) + let ok = await writes.items + XCTAssertEqual(ok.first?.contents.count, Self.oneMiB) + try await assertRejectsWithoutCallback(call(opts(contents: "'a'.repeat(\(Self.oneMiB + 1))"))) + // 349_526 three-byte scalars = 1_048_578 bytes > 1 MiB although only 349_526 UTF-16 units. + try await assertRejectsWithoutCallback(call(opts(contents: "'あ'.repeat(349526)"))) + let fits = Writes() + _ = try await run("async () => { await \(call(opts(path: "'wide'", contents: "'あ'.repeat(349525)"))); }", writes: fits) + let wide = await fits.items + XCTAssertEqual(wide.first?.contents.count, 349_525 * 3) + } + + func testTextRejectsLoneSurrogatesButKeepsPairs() async throws { + for contents in ["'\\ud800'", "'a\\udc00'", "'\\ud83d'", "'\\ude00\\ud83d'", "'x\\ud800y'"] { + try await assertRejectsWithoutCallback(call(opts(contents: contents))) + } + let writes = Writes() + _ = try await run("async () => { await \(call(opts(contents: "'\\ud83d\\ude00'"))); }", writes: writes) + let items = await writes.items + XCTAssertEqual(items.first?.contents, Data("😀".utf8)) + } + + func testRejectedAttemptsDoNotConsumeWriteBudget() async throws { + let writes = Writes() + _ = try await run("async () => { for (let i = 0; i < 100; i++) { try { await \(call(opts(path: "''"))); } catch (e) {} } for (let i = 0; i < 64; i++) await \(call(opts(path: "'k' + i"))); }", writes: writes) + let n = await writes.items.count + XCTAssertEqual(n, 64) + } + + func testHostFailedAttemptsStillConsumeBothBudgets() async throws { + let attempts = Writes() + _ = try await run("async () => { let failed = 0; for (let i = 0; i < 64; i++) { try { await \(call(opts(path: "'k' + i"))); } catch (e) { failed++; } } if (failed !== 64) throw new Error('f' + failed); try { await \(call(opts(path: "'extra'"))); } catch (e) { return; } throw new Error('65th reached host'); }", writes: attempts, create: { d, c in + await attempts.add(d, c) + throw WriteFailure() + }) + let n = await attempts.items.count + XCTAssertEqual(n, 64, "failed host attempts count against the 64-write budget") + + let bytes = Writes() + _ = try await run(""" + async () => { + const t = 'a'.repeat(\(Self.oneMiB)); + let failed = 0, refused = 0; + for (let i = 0; i < 17; i++) { + try { await \(call(opts(path: "'k' + i", contents: "t"))); } catch (e) { if (i < 16) failed++; else refused++; } + } + if (failed !== 16 || refused !== 1) throw new Error(failed + '/' + refused); + } + """, writes: bytes, create: { d, c in + await bytes.add(d, c) + throw WriteFailure() + }) + let reached = await bytes.items.count + XCTAssertEqual(reached, 16, "failed host attempts count against the 16 MiB budget") + } + + func testFetchAndWriteBudgetsAreSeparate() async throws { + let writes = Writes() + let fetches = Writes() + _ = try await run("async () => { for (let i = 0; i < 64; i++) { await fetch('\(url)'); } for (let i = 0; i < 64; i++) await \(call(opts(path: "'k' + i"))); try { await fetch('\(url)'); } catch (e) { try { await \(call(opts(path: "'x'"))); } catch (f) { return; } } throw new Error('caps'); }", writes: writes, transport: { req in + await fetches.add(try PluginFileDestination(storage: .local, atPath: "fetch"), Data(req.url.utf8)) + return JavaScriptFetchResponse(status: 200, body: Data()) + }) + let s = await writes.items.count, f = await fetches.items.count + XCTAssertEqual(s, 64) + XCTAssertEqual(f, 64) + } + + // MARK: errors and cancellation + + func testHostFailureRejectsCatchablyAndLaterWritesProceed() async throws { + let writes = Writes() + _ = try await run("async () => { try { await \(call(opts(path: "'bad'"))); } catch (e) { await \(call(opts(path: "'good'"))); return; } throw new Error('not rejected'); }", create: { d, c in + if d.atPath == "bad" { throw WriteFailure() } + await writes.add(d, c) + }) + let items = await writes.items + XCTAssertEqual(items.map(\.path), ["good"]) + } + + func testRejectionDoesNotLeakHostErrorDetail() async throws { + struct Secret: Error, CustomStringConvertible { var description: String { "/private/var/secret/path" } } + let actions = try await run("async () => { try { await \(call(opts())); } catch (e) { if (String(e && e.message).includes('secret') || String(e).includes('/private')) throw new Error('leaked'); return; } throw new Error('x'); }", create: { _, _ in throw Secret() }) + XCTAssertEqual(actions.count, 0) + } + + func testUncaughtWriteFailureIsScriptErrorAndStopsTheHook() async { + let writes = Writes() + await expectError(.scriptError, "async () => { await \(call(opts(path: "'a'"))); await \(call(opts(path: "'b'"))); await \(call(opts(path: "'c'"))); }", writes: writes, create: { d, c in + if d.atPath == "b" { throw WriteFailure() } + await writes.add(d, c) + }) + let paths = await writes.items.map(\.path) + XCTAssertEqual(paths, ["a"]) + } + + func testCancelDuringWriteCancelsTaskAndThrowsCancelled() async throws { + let executor = JavaScriptFetchExecutor() + let started = expectation(description: "started") + let writes = Writes() + let task = Task { () -> Error? in + do { + _ = try await self.run("async () => { try { await \(self.call(self.opts())); } catch (e) {} await \(self.call(self.opts(path: "'after'"))); }", executor: executor, writes: writes, create: { _, _ in + started.fulfill() + do { try await Task.sleep(nanoseconds: 30_000_000_000) } catch { await writes.markCancelled(); throw error } + }) + return nil + } catch { return error } + } + await fulfillment(of: [started], timeout: 5) + executor.cancel() + let error = await task.value + XCTAssertEqual(error as? JavaScriptExecutionError, .cancelled) + let cancelled = await writes.cancelled + XCTAssertEqual(cancelled, 1, "host callback task must be cancelled and awaited before runV2 returns") + let after = await writes.items.count + XCTAssertEqual(after, 0, "script must not continue after cancellation") + executor.cancel() + _ = try await run("() => {}", executor: executor) + } + + func testTaskCancellationDuringWriteThrowsCancelled() async throws { + let started = expectation(description: "started") + let task = Task { () -> Error? in + do { + _ = try await self.run("async () => { await \(self.call(self.opts())); }", create: { _, _ in + started.fulfill() + try await Task.sleep(nanoseconds: 30_000_000_000) + }) + return nil + } catch { return error } + } + await fulfillment(of: [started], timeout: 5) + task.cancel() + let error = await task.value + XCTAssertEqual(error as? JavaScriptExecutionError, .cancelled) + } + + func testCancelledBeforeRunNeverInvokesCallback() async { + let writes = Writes() + let task = Task { () -> Error? in + while !Task.isCancelled { await Task.yield() } + do { _ = try await self.run("async () => { await \(self.call(self.opts())); }", writes: writes); return nil } catch { return error } + } + task.cancel() + let error = await task.value + XCTAssertEqual(error as? JavaScriptExecutionError, .cancelled) + let n = await writes.items.count + XCTAssertEqual(n, 0) + } + + func testCpuBudgetExcludesWriteWaitOnly() async throws { + _ = try await run("async () => { await \(call(opts())); }", create: { _, _ in try await Task.sleep(nanoseconds: 600_000_000) }) + await expectError(.timeout, "async () => { await \(call(opts())); for (;;) {} }") + } + + func testSameExecutorStaysSingleFlightDuringWrite() async throws { + let executor = JavaScriptFetchExecutor() + let started = expectation(description: "started") + let first = Task { _ = try await self.run("async () => { await \(self.call(self.opts())); }", executor: executor, create: { _, _ in + started.fulfill() + try await Task.sleep(nanoseconds: 400_000_000) + }) } + await fulfillment(of: [started], timeout: 5) + await expectError(.busy, "() => {}", executor: executor) + _ = try await first.value + _ = try await run("() => {}", executor: executor) + } + + func testLateSuccessfulHostWriteAfterCallbackTimeoutRejectsAfterDrain() async throws { + // The callback timeout is a stable 10 s (+250 ms grace). The host ignores cancellation and commits at ~10.4 s. + let writes = Writes() + let clock = ContinuousClock() + let begin = clock.now + let actions = try await run("async () => { try { await \(call(opts(path: "'late'", contents: "'{\"a\":1}'"))); } catch (e) { return; } throw new Error('late success reported as success'); }", + writes: writes, create: { d, c in + await withCheckedContinuation { (cont: CheckedContinuation) in + DispatchQueue.global().asyncAfter(deadline: .now() + 10.4) { cont.resume() } + } + await writes.add(d, c) + }) + let elapsed = begin.duration(to: clock.now) + XCTAssertEqual(actions.count, 0) + let items = await writes.items + XCTAssertEqual(items.map(\.path), ["late"], "committed write is retained and was drained before runV2 returned") + XCTAssertEqual(items.first?.text, "{\"a\":1}") + XCTAssertGreaterThanOrEqual(elapsed, .milliseconds(10_400)) + } + + // MARK: response JSON scanning (fetch, unrelated to createFile) + + /// ~1 MiB object whose 16384 distinct keys all share one FNV-1a 32-bit hash (Joux multicollision), so the native + /// duplicate-key scan degrades to quadratic probing: valid JSON within every size/depth cap, yet far slower than + /// the one-second batch CPU budget. Built from the public FNV-1a definition, independent of the C implementation. + private static let collidingKeysDocument: String = { + func step(_ h: UInt32, _ bytes: [UInt8]) -> UInt32 { + bytes.reduce(h) { ($0 ^ UInt32($1)) &* 16777619 } + } + let alphabet = Array("abcdefghijklmnopqrstuvwxyz0123456789".utf8) + var state: UInt32 = 2166136261 + var pairs: [([UInt8], [UInt8])] = [] + for _ in 0 ..< 14 { + var seen: [UInt32: [UInt8]] = [:] + var found: ([UInt8], [UInt8])? + search: for a in alphabet { for b in alphabet { for c in alphabet { for d in alphabet { + let block = [a, b, c, d] + let h = step(state, block) + if let other = seen[h] { found = (other, block); state = h; break search } + seen[h] = block + } } } } + guard let f = found else { fatalError("no FNV collision block found") } + pairs.append(f) + } + var keys: [[UInt8]] = [[]] + for (x, y) in pairs { keys = keys.flatMap { [$0 + x, $0 + y] } } + var json = "{" + for (i, key) in keys.enumerated() { + if i > 0 { json += "," } + json += "\"" + String(decoding: key, as: UTF8.self) + "\":0" + } + return json + "}" + }() + + func testCollidingKeysDocumentFixtureIsValidWithinLimits() { + let doc = Self.collidingKeysDocument + XCTAssertLessThanOrEqual(doc.utf8.count, Self.oneMiB) + XCTAssertGreaterThan(doc.utf8.count, 900_000) + XCTAssertNotNil(try? JSONValue(parsing: Data(doc.utf8))) + } + + func testCreateFileNeverScansItsContents() async throws { + // The same pathological document that makes a JSON scan exceed the CPU budget is written verbatim and promptly. + let bytes = Data(Self.collidingKeysDocument.utf8) + let writes = Writes() + let clock = ContinuousClock() + let begin = clock.now + _ = try await run("async () => { const t = await (await fetch('\(url)')).text(); await \(call(opts(path: "'big'", contents: "t"))); }", writes: writes, transport: { _ in + JavaScriptFetchResponse(status: 200, body: bytes) + }) + let elapsed = begin.duration(to: clock.now) + let items = await writes.items + XCTAssertEqual(items.first?.contents, bytes) + XCTAssertLessThan(elapsed, .milliseconds(900)) + } + + func testResponseJSONScannerStopsPromptlyOnCancel() async throws { + let executor = JavaScriptFetchExecutor() + let writes = Writes() + let clock = ContinuousClock() + let fetched = expectation(description: "fetched") + let bytes = Data(Self.collidingKeysDocument.utf8) + let task = Task { () -> Error? in + do { + _ = try await self.run("async () => { await (await fetch('\(self.url)')).json(); }", + executor: executor, writes: writes, transport: { _ in + fetched.fulfill() + return JavaScriptFetchResponse(status: 200, body: bytes) + }) + return nil + } catch { return error } + } + await fulfillment(of: [fetched], timeout: 5) + try await Task.sleep(nanoseconds: 60_000_000) // let the scan start + let cancelAt = clock.now + executor.cancel() + let error = await task.value + let after = cancelAt.duration(to: clock.now) + XCTAssertEqual(error as? JavaScriptExecutionError, .cancelled) + let n = await writes.items.count + XCTAssertEqual(n, 0) + XCTAssertLessThan(after, .milliseconds(400), "cancel must interrupt the validation scan") + } + + func testGrantAndCountAreCheckedBeforeExpensiveConversion() async throws { + let clock = ContinuousClock() + let big = "'a'.repeat(\(Self.oneMiB))" + let denied = Writes() + var begin = clock.now + _ = try await run("async () => { try { await \(call(opts(contents: big))); } catch (e) { return; } throw new Error('accepted'); }", files: false, writes: denied) + var elapsed = begin.duration(to: clock.now) + XCTAssertLessThan(elapsed, .milliseconds(400), "files not granted: reject before converting") + var n = await denied.items.count + XCTAssertEqual(n, 0) + + let capped = Writes() + begin = clock.now + _ = try await run("async () => { for (let i = 0; i < 64; i++) await \(call(opts(path: "'k' + i"))); try { await \(call(opts(contents: big))); } catch (e) { return; } throw new Error('accepted'); }", writes: capped) + elapsed = begin.duration(to: clock.now) + XCTAssertLessThan(elapsed, .milliseconds(400), "write count exhausted: reject before converting") + n = await capped.items.count + XCTAssertEqual(n, 64) + } + + // MARK: phase, probe and global shape + + func testOnlyResponseLeaveAcceptsFilesMode() async throws { + let pkg = try package("Interceptor.attach({response:{onLeave(){}}});") + for hook in [JavaScriptHook.requestEnter, .requestLeave, .responseEnter, .request, .response] { + let writes = Writes() + do { + _ = try await JavaScriptFetchExecutor().runV2(packageJSON: pkg, hook: hook, eventJSON: event, configJSON: config, + createFile: { d, c in await writes.add(d, c) }) { _ in JavaScriptFetchResponse(status: 200, body: Data()) } + XCTFail("accepted \(hook)") + } catch { XCTAssertEqual(error as? JavaScriptExecutionError, .invalidInput) } + let n = await writes.items.count + XCTAssertEqual(n, 0) + } + } + + func testCreateFileIsNotExposedOutsideDeferredLeaveRuntime() async throws { + let src = "Interceptor.attach({request:{onEnter(){ if (typeof Interceptor.createFile !== 'undefined' || Interceptor.Storage.local !== 'local' || typeof createFile !== 'undefined') throw new Error('exposed'); }, onLeave(){}}, response:{onEnter(){ if (typeof Interceptor.createFile !== 'undefined' || Interceptor.Storage.iCloudDrive !== 'icloud') throw new Error('exposed'); }, onLeave(){}}});" + let pkg = try package(src) + for hook in [JavaScriptHook.requestEnter, .responseEnter] { + _ = try await JavaScriptExecutor().runV2(packageJSON: pkg, hook: hook, eventJSON: event, configJSON: config) + } + let globalProbe = try package("Interceptor.attach({response:{onLeave:async () => { if (typeof createFile !== 'undefined' || typeof globalThis.createFile !== 'undefined' || typeof Storage !== 'undefined' || typeof saveJSON !== 'undefined') throw new Error('global'); }}});") + _ = try await JavaScriptFetchExecutor().runV2(packageJSON: globalProbe, hook: .responseLeave, eventJSON: event, configJSON: config, createFile: { _, _ in XCTFail("no call") }) { _ in + JavaScriptFetchResponse(status: 200, body: Data()) + } + } + + func testSchedulingProbeDefersCreateFileWithoutAnyIO() async throws { + let executor = JavaScriptExecutor() + let invocation = call("{storage: Interceptor.Storage.local, atPath: 'k', contents: 'x'}") + for callback in ["() => { \(invocation); }", + "() => { try { \(invocation); } catch(e) {} }", + "async () => { await \(invocation); }", + "() => { try { Interceptor.createFile(); } catch(e) {} }"] + { + for files in [true, false] as [Bool?] { + let pkg = try package("Interceptor.attach({response:{onLeave:" + callback + "}});", files: files) + do { + _ = try await executor.runV2(packageJSON: pkg, hook: .responseLeave, eventJSON: event, configJSON: config, detectAsync: true) + XCTFail("expected a scheduling signal for \(callback)") + } catch { XCTAssertTrue(error is JavaScriptAsyncRequired, "\(error)") } + } + } + // A synchronous hook that never touches createFile still completes inline. + let sync = try package("Interceptor.attach({response:{onLeave(){return {actions:[]};}}});") + let output = try await executor.runV2(packageJSON: sync, hook: .responseLeave, eventJSON: event, configJSON: config, detectAsync: true) + XCTAssertEqual(try JSONValue(parsing: output), .object(["actions": .array([])])) + } + + func testTopLevelCreateFileIsStickyInvalid() async { + let writes = Writes() + await expectError(.scriptError, "() => {}", top: "try { \(call(opts())); } catch (e) {}\n", writes: writes) + let n = await writes.items.count + XCTAssertEqual(n, 0) + } + + func testNeverSettlingPromiseAfterWriteIsScriptError() async { + await expectError(.scriptError, "async () => { await \(call(opts())); await new Promise(() => {}); }") + } + + // MARK: existing fetch compatibility + + func testFetchOnlyCallSitesStillWorkWithoutCreateCallback() async throws { + let pkg = try package("Interceptor.attach({response:{onLeave:async () => { const r = await fetch('\(url)'); const j = await r.json(); if (j.a !== 1) throw new Error('x'); }}});", files: nil) + let data = try await JavaScriptFetchExecutor().runV2(packageJSON: pkg, hook: .responseLeave, eventJSON: event, configJSON: config) { _ in + JavaScriptFetchResponse(status: 200, body: Data("{\"a\":1}".utf8)) + } + XCTAssertEqual(try JSONValue(parsing: data), .object(["actions": .array([])])) + } + + func testFetchRequestShapeUnchangedWhenCreateCallbackIsPresent() async throws { + let writes = Writes() + let seen = FetchSeen() + _ = try await run("async () => { await fetch('\(url)'); }", writes: writes, transport: { req in + await seen.add(req) + return JavaScriptFetchResponse(status: 200, body: Data()) + }) + let reqs = await seen.items + XCTAssertEqual(reqs.count, 1) + XCTAssertEqual(reqs.first?.method, "GET") + XCTAssertEqual(reqs.first?.maxResponseBytes, Self.oneMiB) + XCTAssertLessThanOrEqual(reqs.first?.timeoutMilliseconds ?? .max, 5000) + let n = await writes.items.count + XCTAssertEqual(n, 0) + } + + private actor FetchSeen { + var items: [JavaScriptFetchRequest] = [] + func add(_ r: JavaScriptFetchRequest) { items.append(r) } + } +} diff --git a/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift index a6d4a1d..e12a2d9 100644 --- a/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift +++ b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift @@ -140,7 +140,7 @@ final class OutboundRuntimeTests: XCTestCase, @unchecked Sendable { let actions = try await run("return {actions:[{type:'webhook',endpointId:'\(endpoint)',json:{f:typeof fetch,k:Object.keys(Interceptor).join(','),n:Interceptor.send.length}}]};") let json = try XCTUnwrap(actions[0]["json"] as? [String: Any]) XCTAssertEqual(json["f"] as? String, "undefined") - XCTAssertEqual(json["k"] as? String, "attach,send") + XCTAssertEqual(json["k"] as? String, "attach,send,Storage") } // MARK: manifest outbound grammar diff --git a/docs/superpowers/plans/2026-10-23-plugin-json-storage.md b/docs/superpowers/plans/2026-10-23-plugin-json-storage.md new file mode 100644 index 0000000..983f3b9 --- /dev/null +++ b/docs/superpowers/plans/2026-10-23-plugin-json-storage.md @@ -0,0 +1,111 @@ +# Plugin JSON Storage Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task. + +**Goal:** Save original Salmon Run API response JSON and verify nonempty history and real details on M3. +**Architecture:** A bounded response.onLeave save callback publishes into an app-group store, fenced by current activation. The foreground app mirrors committed files into Documents/Plugins; the Plugin saves original fetch response text. +**Tech Stack:** Swift 6, QuickJS C, TypeScript, Python/Bun, iPadOS. +**Spec:** ../specs/2026-10-23-plugin-json-storage-design.md + +## Global Constraints + +- User clarified: save only original response JSON, with no wrapper or authentication data. +- Latest user update supersedes the spec's initial empty-history test assumption: real nonempty history and details are now available and must be verified. +- Logical keys are 1–1024 UTF-8 bytes, no NUL (increased from draft's 512 so a 512-byte result ID plus prefix fits). JSON <= 1 MiB, depth <= 64; preserve original bytes. +- Schema 2 optional write.files defaults false; no schema 1 permission. Existing fetch ABI stays compatible. +- Per invocation: 64 saves / 16 MiB submitted, separate fetch budget, same 120s wall; cumulative CPU1000ms for a files grant plus trusted save callback, otherwise250ms, excluding callbacks. Namespace: 64 MiB / 2048 files. +- Activation lock precedes storage lock. Recheck cancellation/consent before atomic publication; already published files survive cancellation/revocation. +- No new screens. Only existing activation permission row/footer and Files exposure. +- Workers own disjoint files, make no commits, and do not capture screens. Codex runs tools on the verified Mac and owns integration/device evidence. + +## Review Focus + +- Revocation between validation and rename must prevent the write while retaining prior files. +- Untrusted filenames and symlink ancestors must never redirect reads/writes outside owned roots. +- Repeated same-key saves, partial failures and quota replacement must preserve committed data. +- One-MiB Unicode/escaped responses must fit actual QuickJS heap without envelope duplication. +- Foreground export must tolerate user edits without importing content or deleting unrelated Files content. + +### Task 1: Permission and QuickJS bridge + +Files: AutomationCore/Manifest.swift; CQuickJS/bridge.c and include/CQuickJS.h; AutomationRuntime/JavaScriptFetchExecutor.swift; associated package tests. +Interfaces: `public typealias SaveJSON = @Sendable (String, String) async throws -> Void`; `runV2(... configJSON: Data, saveJSON: SaveJSON? = nil, transport: @escaping Transport)`. +C: add qjs_run_v2_fetch_save (old fetch arguments plus QJSSaveJSONCallback and save opaque before package). Callback receives raw key/text pointers, lengths, timeout_ms; status 0/1/2 means success/reject/cancel. Preserve old qjs_run_v2_fetch wrapper. +- [x] Write tests first: optional/denied files permission, old fetch, exact text/UTF8 callback, invalid key/JSON, limits, phase/probe/no IO, cancellation and Promise errors. +- [x] Codex runs focused tests and records expected failure, then worker implements the contract. +- [x] Run affected Swift tests and shared C validation on resulting content; expect zero failures. + +### Task 2: Durable storage and activation fence + +Files: new AutomationCore/PluginJSONFileStore.swift; PluginActivationStore.swift; core tests. +Interfaces: `public struct PluginJSONFileStore: Sendable { init(directoryURL: URL); func save(revisionID: String, package: PluginPackage, key: String, jsonText: String, checkAuthorization: @Sendable () throws -> Void = {}) throws; func export(to directoryURL: URL) throws }`. +Fence: `PluginActivationStore.withCurrentActivation(admitted: PluginActivationSnapshot, revisionID: String, _ operation: @Sendable (ActivatedPlugin) throws -> Void) throws`, holds existing activation lock across operation, verifies snapshot and exact granted revision. Store validates revision/package and permission, derives namespace with trusted InstallationIdentity family + digest, file SHA256(key).json. +- [x] Write tests first for exact bytes, invalid/large/deep JSON/key, no permission, namespace isolation, atomic replace/noop, quotas, symlinks/special files, IO errors, cancellation before publication, stale activation, export behavior. +- [x] Codex runs tests red; worker implements descriptor-relative no-follow storage, 0600 atomic temp/rename/fsync, bounded quotas, source-only export. +- [x] Run relevant core tests; expect zero failures. + +### Task 3: SDK and Salmon Run integration + +Files: types/interceptor.d.ts; tools/compile.mjs and repository_config.py; Plugin metadata/hook; authoring/compiler/hook tests; canonical API docs/templates where applicable. Native bridge simulator copy is coordinated by Codex after Task 1. +- [x] Add tests first for saveJSON types, direct-call placement in response.onLeave, aliases/shadowing, optional boolean files permission, original history/detail text and no token persistence. +- [x] Run tests red, then implement SDK contract and Plugin 1.1.0 with write.files true. Fetch text once; validate parsed history/detail before saving original text; retain IDs only. Stop on save errors. +- [x] Run affected tests, check script and manifest from `bun run build`, then required repository check; verify generated package hashes and permission. + +### Task 4: App integration and Files + +Files: HTTPPluginProcessor.swift; AutomationSharedConfiguration.swift; ContentView.swift; new foreground exporter helper; Info.plist; PluginPackageApprovalView.swift; Localizable.xcstrings; integration tests. +- [x] Add processor tests for admitted revision binding, save callback authority and no write after revocation; observe failure before integration. +- [x] Inject trusted store URL into processor, retain revisionID in deferred run, bind SaveJSON closure to admitted activation fence and consent/cancellation checks. Export on launch/foreground with cancellable ~5s loop away from main actor. +- [x] Enable UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace. Add only conditional files permission in existing approval section/footer, localized Japanese/English. +- [x] Run affected tests and required format/check gates. Build device app against immutable recorded source using existing owned DerivedData/SourcePackages. + +### Task 5: Independent review and M3 verification + +- [x] Fresh read-only Claude review of exact diff/files. LocalGPT actual-files review for native storage risk, using its verified studio LocalMCP access. Resolve material findings with affected tests. +- [x] Install app preserving data, import/enable canonical 1.1.0 package, trigger Nintendo Switch App's actual BulletToken request with live history. +- [x] Read back app-group saved JSON and exported Documents JSON; verify nonempty history/detail, exact response bytes/hashes, package and source fingerprints, and Files visibility. Never print credentials/raw player data. +- [x] UI comparisons use Mock Diff when matching adopted state is available. Captures immediately become lossless exact WebP with RGBA/profile/dimension/scale/hash verification; retain required originals only. +- [x] Clean owned streams/windows/test devices and superseded disposable artifacts. Preserve private real-data evidence and pending/unknown reviewer jobs; archive completed managed LocalGPT chats only after results saved and no continuation remains. + +## Review resolutions / execution ledger + +LocalGPT Pro actual-files plan review completed (studio connection, original spec hash verified), plus independent Claude native and SDK feasibility reviews. The additional Claude Opus plan review completed before implementation. Later checkpoints below are retained as execution history; the final accepted evidence is recorded at the end. + +- Commit boundary: authorization must hold when a publication is admitted at its final synchronous check. A cancellation after that boundary may leave the committed file. Shutdown's drain acknowledgement must wait until every admitted publication has finished. No claim of retroactive rollback or atomic UserDefaults/rename across processes is made. +- Keep activation lock work bounded: validate JSON before entering the fence; storage lock must be nonblocking when called under activation, reject contention so caller can retry on a later capture. No Documents export under activation lock. For the bounded 1MiB synchronous write, check cancellation during chunked writes and before publication; don't detach I/O that can outlive callback drain. This intentionally favors rejecting a contended save over holding up revocation. +- File and directory fsync required. If post-rename sync fails, report failure with committed bytes left intact; identical-byte retry still fsyncs file/directory. Creation ancestors are synchronized. +- Private and Documents copies use completeUntilFirstUserAuthentication and backup exclusion, applied before publication. Save success acknowledges private persistence; Files export retries only while app foreground. Existing approval footer explains Files visibility and retention after disabling. +- Aggregate retained store limit: at most16 namespaces, 256MiB total; no automatic eviction of raw data and no JS deletion. Full store rejects new writes; existing-key replacement remains possible within bounds. Native app removal reclaims its storage; deleting a public copy does not erase the authoritative response and the next export restores it. Export never deletes unrelated user files. +- Retain acquired IDs only, never all parsed detail bodies. Actual bridge batch verification must exceed8MiB cumulative replies within16MiB budget; preserve 8MiB VM heap. +- SDK Rust fixture adapter and immutable upstreamRevision pin must be updated to native storage commit; never mutate the cached upstream checkout. Pin change follows native commit and precedes final SDK build/test evidence. + +### Final plan amendments before implementation + +- Storage gains `prepare(revisionID:package:key:jsonText:) throws -> PluginJSONFileStore.PreparedWrite`; prepared write owns a protected, fsynced temporary file and cleanup. `PreparedWrite.commit(checkAuthorization: @Sendable () throws -> Void = {}) throws` acquires storage lock nonblocking and publishes. `save(...)` is convenience prepare+commit. Processor prepares outside activation fence and commits inside withCurrentActivation. Export has separate IO and never blocks activation. No hard deadline is promised for OS rename/fsync; drain waits for admitted callback completion. +- Final sync check is exactly Task.checkCancellation(), hasCaptureConsent(), outbound.isActive, fetchDispatcher.isActive; activation snapshot/revision equality is checked by withCurrentActivation. No async isAuthorized call inside the fence. +- Native store accounting uses stat sizes and chunked comparisons, not loading the whole retained store. Sweep only abandoned owned temporary files, never an active publisher's temp; lock/temp ownership must be explicit. Same-key concurrent publishers remain atomic. +- QuickJS heap stays8MiB. One-MiB text is the API byte maximum, not a promise that any caller's parsed object graph fits. Dense tiny-value JSON may exhaust the existing bounded VM; fail without host writes instead of raising heap. Test near-limit Unicode/escaped text success and dense parsed input controlled failure, plus realistic multi-detail cumulative batch >8MiB. +- Save JSON syntax validation must avoid constructing another complete JS object tree; native streaming/bounded parser validates raw UTF8. Preserve original text even when number spelling differs from canonical representation. Reject invalid text/depth/duplicate keys consistently with native parser. +- Update spec to reflect final1024 key cap, staging and actual nonempty-history M3 test. Live pass requires history count>0, validated result IDs and required player fields, at least one real detail (multiple when present), each persisted copy hash equal to original response. If history unexpectedly unavailable, report the failed live criterion; synthetic evidence cannot replace it. + +### Execution evidence and review fix pass + +- Task1 committed f9e6b117aa02a1901e5fcdeeb366944dfbe44a17 after runtime35save+21fetch tests passed; native commit policy verified and branch pushed. SDK runtime pin and Rust adapter now match that immutable commit; actual C fixture tests7 pass including >8MiB cumulative saved responses. +- SDK schema/compiler11 and hook24 tests passed. Full bun run check is running against unchanged SDK source. +- Native package suite passed before review fixes (core282, runtime/repository counts in private log); app build succeeded. Initial simulator app-host test could not access app group because signing was disabled; rebuilt with ad-hoc signing and the10processor tests passed. Both owned simulator devices were deleted and no Simulator windows were opened. +- Native review completed independently by Claude; LocalGPT actual-files review remains pending on original source. Original changed-source files/hashes retained under private review-original for delta comparison. Current fixes will require an actual-files delta review. +- RED confirmed for backup exclusion repair on identical saves/exports, partial export with a blocked first file, nonfinite numeric parity, and rejected first publication consuming a namespace. Fix worker owns Core store/parser/tests; Codex owns foreground retry/cache and preserving the existing webhook footer. No new product screens. +- Test fixture corrections: supplied raw old/new strings were invalid JSON and now correctly quoted; invalid JSON never creates a namespace. A local helper merely named saveJSON is not a host API alias. The first valid detail establishes principal; the mismatch test now checks a second detail. These corrections preserve production contracts. + + +### Final accepted evidence (2026-10-24 JST) + +- Native runtime/source commit: `5bfe74965c29a7d452ae3053ad036f172314ee91`; paired Mudmouth `72710a0910121889c76167396d4827d819bb27ef`. CI and TestFlight dependency pins use that Mudmouth revision. +- M3, iPadOS27.0.1: the installed 1.1.0 package SHA256 is `63654ef608720a3e567b6f2a5a8ae040f43f8b162831227b52eb6bddd8249c5e`. A real Nintendo Switch App BulletToken POST triggered the installed plugin automatically. History contains50 distinct IDs, all50 detail responses were saved;51 raw JSON files total2029593bytes. Every saved detail ID matches the history set, no GraphQL errors, no custom wrapper. +- Read-back private files and Documents/Plugins exports are byte-identical for all51 files. Physical metadata confirms0600 files and backup-exclusion attributes; the save path also passed physical file-protection verification before publication. Private raw data and hashes remain local under `.codex/json-storage`; no tokens or result bodies are published. +- Live fixes: gzip responses were previously ineligible. Mudmouth now strictly decodes one bounded gzip member for response.onLeave, preserving wire bytes and bypassing mutation.109 transport tests and signed iOS build passed. Opaque per-result player IDs are no longer compared as account IDs; exact result-ID checks, required player fields and one Bearer per chain remain. +- A temporary enum-only diagnostic established that the old250ms VM budget stopped acquisition at32 details. It was removed. Validated files-granted fetch/save batches now have1000ms cumulative CPU; other fetch runs stay250ms, with the same8MiB heap,120s wall and callback/count/byte/cancellation bounds. A350ms workload was RED before the fix and GREEN after it; denied/absent grants still time out.43 save tests and21 fetch tests passed, including bounded scanner and cancellation cases. +-44 native file-store tests and10 signed app integration tests passed on unchanged storage/integration content. Existing signed simulator result retained; both owned test simulators were deleted. Latest signed device build succeeded and is installed on M3. +- Independent Claude actual-files reviews completed for native storage, gzip transport, player-ID correction and CPU budget. LocalGPT Pro actual-files review findings were resolved; its final storage delta attempt was rate-limited, so the completed Claude delta review and actual tests were used. LocalGPT later completed the gzip plan review with verified studio file access. No final Pro delta review is claimed. +- Mock Diff was inspected. It has no adopted baseline for the added files permission at M3's exact27.0.1 state; no quantitative comparison pass is claimed. Existing rows/footers were reused, with no new screen. Captures were verified as lossless WebP and kept out of chat. +- PRs: Interceptor35, Interceptor-Plugins11, Mudmouth9. Build outputs, canonical generated package and private real-data evidence are retained for review/recovery; active PR worktrees remain in use. diff --git a/docs/superpowers/plans/2026-10-24-plugin-file-destinations.md b/docs/superpowers/plans/2026-10-24-plugin-file-destinations.md new file mode 100644 index 0000000..d6c5376 --- /dev/null +++ b/docs/superpowers/plans/2026-10-24-plugin-file-destinations.md @@ -0,0 +1,66 @@ +# Plugin file destinations implementation plan + +> **For agentic workers:** Use superpowers:executing-plans and test-driven-development. The user authorized execution; do not ask for another plan approval. + +**Goal:** Plugin-controlled generic file paths with Storage Enum and verified M3 iCloud Drive/Salmon Run delivery. + +**Architecture:** QuickJS passes a validated destination and raw bytes to an activation-fenced private record store. The main app exports payloads using a persistent user-selected root and coordinated File Provider writes. + +**Tech Stack:** Swift 6, QuickJS C, TypeScript/Bun, Rust simulator, native iOS document picker. + +**Spec:** ../specs/2026-10-24-plugin-file-destinations-design.md + +## Global constraints + +- Approved API and Enum, raw payloads, no manifest destination duplication or unnecessary screens. +- Preserve current fetch/lifecycle/grant/quotas and unrelated working trees. +- Native base d81deb2; SDK base 1471892; existing source-bound passing baseline evidence retained. +- Workers edit only assigned paths, no commits, screenshots or shared builds; Codex verifies on this Mac and M3. + +## Review focus + +- Binary zero bytes and Uint8Array subviews must survive without truncation. +- Canonical path aliases and cross-family external collisions must not overwrite another file. +- Route/payload must be one atomic record across crash or cancellation. +- Stale bookmark, cancellation and offline provider preserve private data and avoid prompt loops. +- M3 root selection/relaunch must produce the exact requested visible path and original response bytes. + +### Task 1: Durable generic file records + +Files: new AutomationCore/PluginFileDestination.swift, PluginFileStore.swift and focused AutomationCoreTests/PluginFileStoreTests.swift. Reuse descriptor/protection primitives without changing the legacy JSON spool. + +Interfaces: produces Core types and methods specified above, consumed by Tasks 2/3. + +- [ ] Add failing text/binary/empty/path/atomicity/alias/ownership/quota tests; Codex runs native swift test to observe RED before implementation. +- [ ] Implement bounded destination validation and single-record private publication; add header-only enumeration/read methods. +- [ ] Run focused Core tests and existing legacy JSON store tests; expected PASS. + +### Task 2: QuickJS, Swift runtime, SDK and Salmon Plugin + +Files: CQuickJS/bridge.c and include/CQuickJS.h; AutomationRuntime/JavaScriptFetchExecutor.swift and RuntimeTests/JavaScriptSaveJSONTests.swift; SDK types/interceptor.d.ts, tools/compile.mjs, tools/simulator/src/main.rs, affected tests/docs and Salmon hook. + +Interfaces: consumes Core destination, produces createFile callback and immutable Storage Enum. Header callback signatures match the spec. Codex owns HTTPPluginProcessor integration. + +- [ ] Add failing runtime tests for createFile, Enum, non-JSON/binary/empty, offsets, arguments/grants and cancellation; observe RED with Codex's native tools. +- [ ] Replace unpublished JSON API with generic createFile across native runtime and simulator. Validate before callback; retain strict object/property checks and execution budgets. +- [ ] Update TS authoring/compiler/generated sample behavior and hook paths: Salmon Run/history.json and Salmon Run/details/.json; original response text unchanged. +- [ ] Run native Runtime/fetch tests and focused SDK tests, observing PASS. Pin SDK to resulting native revision before final runtime build/check. + +### Task 3: Native coordinated export and necessary folder authorization + +Files: new Interceptor/Automation/PluginFilePublisher.swift and PluginFileDestinationController.swift (or focused equivalent); AutomationSharedConfiguration, HTTPPluginProcessor, PluginFilesExporter, ContentView, existing approval/localization and app tests. + +Interfaces: consumes record enumeration and callback. Publishes raw bytes, manages bookmark per trusted family and export ownership state. No arbitrary paths from JS or bookmark access in tunnel. + +- [ ] Add meaningful failing publisher tests for raw delivery, owned replacement, unknown-file conflict, links and temporary failure/retry. +- [ ] Integrate generic record store under existing activation fence and add foreground coordinated publisher/metadata cache. +- [ ] Present only native folder picker for pending cloud family without valid root; persist bookmark, handle cancellation/stale access, and update existing permission footer. Reuse canonical mock conventions for any custom visible change; no new custom screen. +- [ ] Run affected native tests and signed app build; expected PASS. Review final diff via fresh independent Claude; complex final file/security behavior also LocalGPT actual-files review with verified access. + +### Task 4: Build artifacts and M3 acceptance + +- [ ] Run bun run check, rebuild actual native C simulator on the final pinned revision, run affected actual-C tests, and bun run build. Confirm script, manifest and importable package hashes. +- [ ] Install signed app on physical M3 preserving catalog/history; import new Plugin through normal UI. +- [ ] Select/create the top-level iCloud Drive/Salmon Run folder using system picker; capture actual result history/detail, return to Interceptor for publishing. +- [ ] Relaunch app, re-resolve bookmark and verify matching file count/IDs and hashes in iCloud Drive/Salmon Run; verify synced Mac readback when available. Record actual server-sync limits separately. +- [ ] Verify all owned device/stream/temp resources cleaned, source identity checked, PRs updated and CI status honestly reported. diff --git a/docs/superpowers/specs/2026-10-23-plugin-json-storage-design.md b/docs/superpowers/specs/2026-10-23-plugin-json-storage-design.md new file mode 100644 index 0000000..174e433 --- /dev/null +++ b/docs/superpowers/specs/2026-10-23-plugin-json-storage-design.md @@ -0,0 +1,48 @@ +# Plugin JSON response persistence + +## Authorized scope + +Add file persistence to Interceptor and make the Salmon Run Plugin save fetched API response JSON. Verify actual files on M3. The user has now made real Salmon Run history available. Verify real nonempty history and details on M3; synthetic data is supplementary only. Save response JSON itself: no wrapper, generated summary or authentication data. Existing native work is isolated in this task's linked worktree; preserve the earlier one-line empty-row separator correction and unrelated checkouts. + +## Approach and contract + +Expose `await Interceptor.saveJSON(key, jsonText)` only inside schema-2 `response.onLeave`, alongside `fetch`. `key` is a logical UTF-8 key (1–1024 bytes, no NUL), never a filesystem path. `jsonText` is the original UTF-8 JSON response text. Validate bounded JSON and write the original bytes, preserving whitespace, ordering and Unicode. Return a settled Promise only after durable publication; reject on invalid input, missing permission, revoked authority, cancellation, quota or I/O failure. No arbitrary paths, file reads, listing or deletion are exposed to JS. + +Add optional schema-2 `write.files: boolean`, default false, identically validated by Swift, C and SDK. Bind writes to the exact active package/revision, current activation generation and capture consent. Permission-bearing package bytes change, requiring the existing explicit enable confirmation. Explain local JSON saving in the existing permission confirmation's footer/row only; no new screens or controls. + +Use the existing deferred response executor: the scheduling probe recognizes saveJSON without I/O; the deferred VM receives separate trusted fetch and save callbacks. Preserve existing fetch-only call sites through an optional Swift save callback/default. The save callback checks cancellation and authority, awaits/stops owned work before return, and shares the invocation's bounded CPU/wall lifecycle. Restrict direct references in SDK authoring consistently with fetch/attach/send. + +## Persistence and Files + +The Packet Tunnel cannot write the main app's Documents container. The authoritative store is therefore the app group's `Library/Application Support/Interceptor/PluginFiles`. Isolate namespaces by a digest of trusted source-qualified installation family, stable across revisions, with a safe manifest UUID as a display prefix. Derive each file name as SHA-256(key) plus `.json`; JS cannot select directories. Same key replaces the corresponding response atomically and identical bytes are a no-op. + +Bounds: 1 MiB per JSON, 64 MiB and 2,048 JSON files per namespace, at most 64 saves and 16 MiB submitted per invocation; the aggregate retained store is limited to 256 MiB / 16 namespaces, rejecting new writes without automatic data eviction. Serialize quota checks/publication with an interprocess lock. Use no-follow directory/file operations, regular-file checks, exclusive temporary files, atomic rename and directory fsync. Bound JSON depth; reject links/special files and clean owned temporaries on failure. Use iOS protection suitable for background execution after first unlock and exclude the private store from backup. + +Stage protected temporary bytes and fsync outside activation lock, then fence final publication with current activation under its existing file lock; order activation lock before storage lock. Acquire the storage lock nonblocking inside that fence. Check cancellation/consent again before publication admission. OS rename/fsync has no hard deadline; shutdown drain waits for completion. A cancellation after publication admission may leave committed bytes. Revoking/deleting a plugin stops later writes and does not delete already saved results. + +When Interceptor is foreground, mirror committed JSON files into app `Documents/Plugins//`. Enable iOS file sharing/open-in-place so users can access them in Files > On My iPad > Interceptor > Plugins. Both source inspection and M3's current Documents listing show no existing Documents content. Export never imports edited Documents files, never follows symlinks and only writes owned namespace JSON files. Sync on launch/activation and periodically while active; stat metadata to skip unchanged files, perform I/O away from the main actor and cancel the foreground loop when inactive. No new app screen is required. + +Alternatives considered: directly writing main Documents from the extension is outside its sandbox; a local HTTP storage server adds unnecessary transport/access; runtime result actions are too small for batches and lose earlier successful results when a later request fails. A bounded native save callback reuses the existing async execution model. + +## Salmon Run integration + +Set write.files true and update the local Plugin version to 1.1.0. Keep the fixed publication day. Fetch history using `text()`, parse and validate it, then save that original response text with a fixed history key. For each validated detail, save the original full GraphQL response text under a key derived from its result ID. Do not persist the captured BulletToken response, request headers, cookies or token. Retain existing limit, version selection, principal/ID validation and non-upload behavior. A later detail failure must not remove already committed files. Empty history still produces its actual response JSON file. + +## Verification + +1. Failing tests first for native permission/bridge and filesystem behavior; native Swift runtime/storage tests and actual C bridge. Cover absent/denied permission, phase/probe, UTF-8/original-byte preservation, duplicate keys, invalid/large/deep JSON, quotas, symlinks, I/O failure, generation revocation and cancellation. Ensure old fetch-only hooks still pass. +2. SDK tests cover direct saveJSON placement, schema parity, canonical build outputs and generated-JS hook saving the exact fixture response texts. `bun run build` must emit the updated script, manifest and importable package. +3. Independent actual-diff review, then immutable native build/test snapshots using existing caches. Relevant existing CI suites run on pushed source; preserve unrelated simulator/devices and cleanup only owned resources. +4. Install the development app on M3 normally, preserving catalog/capture data. Import/enable the new local package through regular UI, exercise actual Nintendo BulletToken capture, and save real HTTP-200 nonempty history plus validated details. Synthetic tests cannot substitute for this live criterion. +5. Read back private and exported M3 files; compare exact bytes/hashes with corresponding responses. Assert history count>0, matching detail IDs/principal, and multiple details when available. Verify Files visibility and protection/backup exclusion on both copies. Record source/dependency/toolchain/package hashes without exposing account data. +6. Any captures are immediately converted to lossless WebP, preserving dimensions, RGBA, ICC and Retina scale, with hashes/pixel verification. Keep only required originals and clean owned streams/windows/devices/build intermediates; preserve useful private evidence and original package backups. + +## Review integration points + +Native: Packages/InterceptorAutomation/Sources/{AutomationCore/Manifest.swift,AutomationCore/PluginActivationStore.swift,AutomationCore/InstallationSelection.swift,AutomationRuntime/JavaScriptFetchExecutor.swift,CQuickJS/bridge.c,CQuickJS/include/CQuickJS.h}; Interceptor/Automation/{HTTPPluginProcessor.swift,AutomationSharedConfiguration.swift}; Interceptor/{ContentView.swift,Info.plist,Views/Automation/PluginPackageApprovalView.swift,Localizable.xcstrings}. + +SDK: /Users/devonly/Developer/interceptor-splatnet3-plugin/{types/interceptor.d.ts,tools/compile.mjs,tools/repository_config.py,plugins/splatnet3-salmon/plugin.json,plugins/splatnet3-salmon/hooks/api.lp1.av5ja.srv.nintendo.net/api/bullet_tokens/POST.ts,tests/test_splatnet3_hook.py,tests/test_splatnet3_quickjs.py}. + +## Final implementation amendments + +The implementation plan records review resolutions: staged prepare/commit, durable fsync retries, bounded aggregate store, cancellation/drain commit boundary, one-way protected Files mirror, IDs-only memory retention, and immutable SDK native runtime pin plus Rust fixture adapter. saveJSON acknowledges private persistence, not export completion. The mirror restores deleted/edited owned copies on foreground sync, never imports them, and never deletes unrelated files. Quota exhaustion rejects without evicting raw data; removing the app reclaims its store. diff --git a/docs/superpowers/specs/2026-10-24-plugin-file-destinations-design.md b/docs/superpowers/specs/2026-10-24-plugin-file-destinations-design.md new file mode 100644 index 0000000..b36f463 --- /dev/null +++ b/docs/superpowers/specs/2026-10-24-plugin-file-destinations-design.md @@ -0,0 +1,43 @@ +# Plugin file destinations + +## Approved behavior + +The user approved `Interceptor.createFile({ storage, atPath, contents })`, with folders and filenames selected by the Plugin's JavaScript, and requested an Enum for storage. Verify real Salmon Run JSON delivery into the physical M3's iCloud Drive/Salmon Run folder. Preserve unrelated primary-checkout work. No extra management screen, HTTP API, or manifest destination list. + +```typescript +await Interceptor.createFile({ + storage: Interceptor.Storage.iCloudDrive, + atPath: 'Salmon Run/history.json', + contents: historyText, +}); +``` + +`Interceptor.Storage` is an immutable runtime string Enum with `local = 'local'` and `iCloudDrive = 'icloud'`. SDK typing requires the Enum. `contents` accepts UTF-8 strings or exact `Uint8Array` bytes, including empty files. Promise resolves on durable private publication; iCloud export/upload is later. Native storage does not parse JSON or require an extension. The Salmon Plugin validates each original response before submitting its unchanged text. Replace the unreleased saveJSON API throughout runtime, SDK, simulator and Plugin; no permanent alias. + +## Paths, authority and persistence + +`atPath` is relative to the virtual storage root; require NFC byte spelling and reject absolute/empty/dot/dotdot/hidden components, backslash, colon and control characters. Bound UTF-8 path to 1024 bytes, each component to 255 bytes, depth to 8. Derive a case-insensitive canonical identity; reject aliases rather than silently change user-visible spelling. Existing files belonging to another family or without native ownership cannot be overwritten. Same-family updates replace the original path. No read/delete API or permission attributes are exposed. + +Keep schema-2 response.onLeave-only direct-call enforcement, write.files grant, current activation/package/capture-consent checks and cancellation fence. Keep 64 writes/16 MiB submitted contents per invocation, 1 MiB per file, 64 MiB/2048 files per family, 256 MiB/16 families aggregate, 1000 ms cumulative VM budget for files-granted runs, ordinary fetch 250 ms and wall 120 s. Empty files count toward file quotas. Rejected submitted callback attempts consume invocation budgets. C validates structure and bytes; Core validates NFC/case aliases. Reject non-NFC byte spellings rather than silently changing visible names. Retain the existing no-eviction capacity policy: capacity exhaustion rejects further writes; automatic data retention/deletion policy is outside this change. + +New records live in App Group Library/Application Support/Interceptor/PluginFileRecords, separate from the existing JSON spool retained for previous results. Publish a single bounded versioned record containing validated routing header and original raw payload; length/digest validate on read. Exactly one stable destination-derived record name per family/storage/canonical path makes the latest commit win atomically. Cross-family aliases are checked under the root lock with bounded header-only enumeration. Descriptor-relative no-follow I/O, private protection and backup exclusion, bounded metadata and quotas, nonblocking interprocess publication lock, atomic rename/fsync. Prepare outside the activation fence and commit inside it. Do not split route and payload into independently committed files. + +## iOS delivery + +The extension only publishes private records. The main application uses its existing foreground loop to export raw payload bytes to Documents/Plugins/Files for local storage (separate from legacy namespaces), or into a user-authorized iCloud Drive folder for cloud storage. A system folder picker obtains a persistent minimalBookmark; start/stop security-scoped access and NSFileCoordinator coordinate provider writes. No hardcoded CloudDocs access path or new ubiquitous-container provisioning. The Enum object, its case properties and Interceptor.Storage binding are non-writable/non-configurable. + +Use only necessary native permission UI. When cloud records are pending and no usable bookmark exists, the main app presents the system folder picker while active. Cancellation preserves pending records and suppresses repeat prompting until a later foreground entry. Existing approval footer explains iCloud sharing and foreground delivery. No new custom management screen. Grants are keyed by installation family and exact first path component, capped at 32 without eviction. For `Salmon Run/history.json`, the picker asks for the iCloud Drive `Salmon Run` folder, and the publisher strips exactly `Salmon Run/` before writing `history.json`. Validate the NFC prefix, exact case-sensitive UTF-8 boundary and nonempty remainder before I/O; validate the remaining path again. The original private record retains the full virtual path. Selected folder names must match exactly and report iCloud ubiquity, both on selection and bookmark resolution. Root-level files require a separate Drive-root grant; forbid overlapping root/prefix grants and case/compatibility prefix aliases within a family. Bookmarks survive normal updates and are requested again after access failure. M3 must visibly select/create the top-level iCloud Drive/Salmon Run folder; a matching folder name alone cannot establish that it is top-level. + +Retain the original private payload on provider/offline/revocation failure and retry with bounded backoff. Native delivery state records what bytes were published, distinct from Apple's server upload status. A bounded private ownership ledger is keyed by persistent root identity and canonical path, recording family, published digest and an intent digest written before publication. Recover an interrupted publication only when the current file matches a recorded old/new owned digest; unknown or edited files conflict. Re-selecting the same physical root reuses its identity; another root does not inherit ownership. A serialized dedicated publisher queue uses cancellable NSFileCoordinator operations, holds scope until all owned I/O ends and compares the source again on subsequent passes. No hard OS I/O deadline is claimed. Use coordinated operations and no-follow destination traversal; do not apply app-private backup exclusion to exported iCloud documents. Native scratch filenames are journaled before creation and their inode before payload writes. Reclaim only the exact journaled, stale, unlocked regular single-link scratch: a matching recorded inode authorizes partial scratch cleanup, an absent inode requires empty contents, and a different inode requires the full pending digest. Published-file ownership/edit checks remain stricter. Never sweep unrelated external filenames. No source deletion or external-to-private import. Keep pre-existing user files and previous exported JSON. Present pending families in stable order, one picker at a time; cancellation suppresses further prompts for that foreground session. Refresh stale bookmarks while scoped when possible, otherwise re-prompt on a later active entry. + +## Interfaces and ownership + +- Core: `PluginFileDestination(storage: PluginFileStorage, atPath: String)` throwing initializer; immutable properties; `PluginFileStorage: String, Codable, Sendable` cases local/icloud (raw values above). +- Core: `PluginFileStore(directoryURL:)`, `prepare(revisionID:package:destination:contents:) -> PreparedWrite`, `PreparedWrite.commit(checkAuthorization:)`, `recordIdentifiers() -> [String]`, `readRecord(_:) -> PluginFileRecord`. Record exposes identifier, family, destination, contents, digest. Bounded header enumeration avoids loading every payload at once. +- Runtime: `JavaScriptFetchExecutor.CreateFile = @Sendable (PluginFileDestination, Data) async throws -> Void`; `runV2(..., createFile: CreateFile? = nil, transport:)`. +- C: `QJSCreateFileCallback(opaque, storage, storage_len, path, path_len, contents, contents_len, timeout_ms)` and `qjs_run_v2_fetch_files`, replacing unpublished fetch_save ABI. Borrowed length-delimited bytes; no binary string conversion. +- Native publisher/bookmark orchestration owned by Codex. Core records owned by Claude worker 1. C/Swift runtime plus SDK/simulator/hook owned by Claude worker 2. No worker commits or builds shared caches. Codex runs native tests, integrates processor, commits and verifies actual M3. + +## Verification + +Test-first generic text/binary/empty writes, buffer slicing, Enum immutability, invalid objects/paths, quota/grant/probe/cancel, original bytes, atomic records, corruption, cross-family aliases, links, external ownership collisions and retry. Run affected native Core/Runtime/app processor suites and SDK checks, actual C simulator tests, then bun run build confirming emitted JS/manifest/package. Independently review actual files/diff before completion. Verify M3 folder grant survives app relaunch and delivers real history/details with exact bytes into iCloud Drive/Salmon Run. Where available, read the synced folder on this Mac to distinguish local-provider publication from cross-device upload. Capture only necessary private evidence, immediately lossless exact WebP with pixel/profile/hash verification; never paste images into chat. Preserve pre-existing devices/services and rotate only owned superseded artifacts. diff --git a/fastlane/lib/release_config.rb b/fastlane/lib/release_config.rb index 2d4f30d..b6f5c2a 100644 --- a/fastlane/lib/release_config.rb +++ b/fastlane/lib/release_config.rb @@ -33,7 +33,7 @@ module ReleaseConfig # Pinned sibling checkouts that the project references by relative path: name => revision. SIBLINGS = { - "Mudmouth" => "65686d24858822627f674d8b9a22aaaa3b026812" + "Mudmouth" => "72710a0910121889c76167396d4827d819bb27ef" }.freeze # Secret => file written (validated, never printed) into the temporary build copy only.