diff --git a/Interceptor/Automation/PackageCatalogDatabase.swift b/Interceptor/Automation/PackageCatalogDatabase.swift index 8e2193e..f8abdc2 100644 --- a/Interceptor/Automation/PackageCatalogDatabase.swift +++ b/Interceptor/Automation/PackageCatalogDatabase.swift @@ -45,6 +45,8 @@ protocol PackageCatalogStoring: AnyObject { func detail(in record: RepositoryRecord, entryID: UUID) throws -> PluginPackagePresentation? func packageBytes(in record: RepositoryRecord, entry: IndexEntry) throws -> Data? func reusableBytes(sha256: String) throws -> Data? + /// Background-only accepted content read and bounded package validation for display. + func icon(sha256: String) async throws -> PluginIcon? func isComplete(_ snapshot: VerifiedSnapshot) throws -> Bool } @@ -189,6 +191,10 @@ final class PackageCatalogDatabase: PackageCatalogStoring { try content(sha256: sha256, size: nil, in: readContext()) } + func icon(sha256: String) async throws -> PluginIcon? { + try await writer.icon(sha256: sha256) + } + func isComplete(_ snapshot: VerifiedSnapshot) throws -> Bool { let context = readContext() let snapshotKey = PackageCatalogKeys.snapshot(snapshot) @@ -278,6 +284,13 @@ actor PackageCatalogWriter { return context } + func icon(sha256: String) throws -> PluginIcon? { + let context = makeContext() + guard let content = try context.fetch(FetchDescriptor(predicate: #Predicate { $0.sha256 == sha256 })).first, + content.bytes.count <= Limits.package, Digest.sha256Hex(content.bytes) == sha256 else { throw PackageCatalogError.contentMismatch } + return try PluginPackage.validate(content.bytes).icon + } + func stage(_ snapshot: VerifiedSnapshot, packages: [PluginPackage], leaseID: UUID) throws { let plugins = snapshot.index.plugins guard plugins.count <= Limits.plugins, packages.count == plugins.count else { throw PackageCatalogError.invalidSnapshot } diff --git a/Interceptor/Automation/PluginBrowserModel.swift b/Interceptor/Automation/PluginBrowserModel.swift index 74e75fe..44d6818 100644 --- a/Interceptor/Automation/PluginBrowserModel.swift +++ b/Interceptor/Automation/PluginBrowserModel.swift @@ -98,6 +98,19 @@ final class PluginBrowserModel { init(controller: AutomationController) { self.controller = controller } + /// Selected installed content takes precedence over an advertised repository update. + func iconSource(for family: PluginBrowserFamilyID, entry: IndexEntry?, record: RepositoryRecord?) -> PluginIconSource? { + if let selected = selectedRevision(for: family) { return .bundled(selected.package) } + guard let entry, let record, entry.id == family.manifestID, record.url.canonical == family.source, + let current = currentRecord(record), current.repositoryID == record.repositoryID, + current.snapshot?.index.plugins.contains(entry) == true, + let database = controller.packageCatalog else { return nil } + let sha = entry.sha256 + return PluginIconSource(id: sha + ":" + String(controller.packageCatalogRevision), cacheKey: sha) { + try await database.icon(sha256: sha) + } + } + var canDismissQueue: Bool { !isProcessing } var hasSourceRefreshFailures: Bool { diff --git a/Interceptor/Automation/PluginIconLoader.swift b/Interceptor/Automation/PluginIconLoader.swift new file mode 100644 index 0000000..efc6fba --- /dev/null +++ b/Interceptor/Automation/PluginIconLoader.swift @@ -0,0 +1,111 @@ +import AutomationCore +import Foundation +import ImageIO +import UIKit + +/// Display-only input. Repository reads use accepted local content; this closure never fetches a URL. +struct PluginIconSource: Sendable { + let id: String + let cacheKey: String + let load: @Sendable () async throws -> PluginIcon? + + static func bundled(_ package: PluginPackage) -> PluginIconSource? { + guard let icon = package.icon else { return nil } + let key = Digest.sha256Hex(icon.data) + return .init(id: key, cacheKey: key, load: { icon }) + } +} + +/// UIImage is immutable after construction; decoding happens away from the UI actor. +struct DecodedPluginIcon: @unchecked Sendable { + let image: UIImage + let cost: Int +} + +/// Bounded thumbnails shared by list, hero and queue. Missing catalog content is not negatively cached. +actor PluginIconLoader { + static let shared = PluginIconLoader() + private struct Loaded: Sendable { + let available: Bool + let image: DecodedPluginIcon? + } + private var entries: [String: Loaded] = [:] + private var order: [String] = [] + private var absent = Set() + private var absentOrder: [String] = [] + private let absentLimit = Limits.plugins * Limits.repositories + private struct PendingKey: Hashable { let revision: String; let generation: String } + private var pending: [PendingKey: (id: UUID, task: Task)] = [:] + private var cost = 0 + private let countLimit: Int + private let costLimit: Int + + init(countLimit: Int = 64, costLimit: Int = 8 * 1024 * 1024) { + self.countLimit = max(1, countLimit) + self.costLimit = max(0, costLimit) + } + + func image(for source: PluginIconSource) async -> DecodedPluginIcon? { + if absent.contains(source.cacheKey) { return nil } + if let hit = entries[source.cacheKey] { + touch(source.cacheKey) + return hit.image + } + let pendingKey = PendingKey(revision: source.cacheKey, generation: source.id) + let task: Task + let taskID: UUID + if let existing = pending[pendingKey] { + task = existing.task + taskID = existing.id + } else { + taskID = UUID() + task = Task.detached(priority: .utility) { + do { + let icon = try await source.load() + return Loaded(available: true, image: icon.flatMap(Self.decode)) + } catch { + return Loaded(available: false, image: nil) + } + } + pending[pendingKey] = (taskID, task) + } + let loaded = await task.value + // Only the first waiter inserts this result. + guard pending[pendingKey]?.id == taskID else { return loaded.image } + pending.removeValue(forKey: pendingKey) + if loaded.available, loaded.image == nil { + absent.insert(source.cacheKey) + absentOrder.removeAll { $0 == source.cacheKey } + absentOrder.append(source.cacheKey) + if absentOrder.count > absentLimit { absent.remove(absentOrder.removeFirst()) } + } else if loaded.available { + cost -= entries[source.cacheKey]?.image?.cost ?? 0 + entries[source.cacheKey] = loaded + cost += loaded.image?.cost ?? 0 + touch(source.cacheKey) + while order.count > countLimit || cost > costLimit { + let key = order.removeFirst() + cost -= entries.removeValue(forKey: key)?.image?.cost ?? 0 + } + } + return loaded.image + } + + private func touch(_ key: String) { + order.removeAll { $0 == key } + order.append(key) + } + + nonisolated private static func decode(_ icon: PluginIcon) -> DecodedPluginIcon? { + guard let source = CGImageSourceCreateWithData(icon.data as CFData, nil), + CGImageSourceGetCount(source) == 1, + let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceThumbnailMaxPixelSize: 192, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceCreateThumbnailWithTransform: true, + ] as CFDictionary) + else { return nil } + return DecodedPluginIcon(image: UIImage(cgImage: image), cost: image.bytesPerRow * image.height) + } +} diff --git a/Interceptor/Views/Automation/PluginBrowserComponents.swift b/Interceptor/Views/Automation/PluginBrowserComponents.swift index bc62d6a..f844a96 100644 --- a/Interceptor/Views/Automation/PluginBrowserComponents.swift +++ b/Interceptor/Views/Automation/PluginBrowserComponents.swift @@ -1,4 +1,5 @@ import SwiftUI +import AutomationCore import UIKit /// Shared browser colors follow the selected Sileo reference in both appearances. @@ -16,6 +17,7 @@ struct PluginPackageRow: View { let author: String? let version: String let summary: String + var iconSource: PluginIconSource? var systemImage = "shippingbox" var iconColor = PluginBrowserColor.accent var isInstalled = false @@ -23,7 +25,7 @@ struct PluginPackageRow: View { var body: some View { HStack(alignment: .top, spacing: 14) { - PluginBrowserIcon(systemImage: systemImage, color: iconColor, isInstalled: isInstalled) + PluginBrowserIcon(systemImage: systemImage, color: iconColor, isInstalled: isInstalled, source: iconSource) VStack(alignment: .leading, spacing: 2) { Text(verbatim: name) .font(.body.weight(.semibold)) @@ -104,6 +106,7 @@ struct PluginPackageModifyActions { struct PluginPackageHero: View { let name: String let targetHosts: [String] + var iconSource: PluginIconSource? var systemImage = "shippingbox" var iconColor = PluginBrowserColor.accent var actionTitle: LocalizedStringKey? @@ -123,6 +126,7 @@ struct PluginPackageHero: View { systemImage: systemImage, color: iconColor, size: horizontalSizeClass == .compact ? 56 : 60, + source: iconSource, ) VStack(alignment: .leading, spacing: 4) { Text(verbatim: name) @@ -234,6 +238,7 @@ struct PluginInstallQueueDisplayEntry: Identifiable { let version: String var detail: LocalizedStringKey = "AUTO_BROWSER_QUEUE_WAITING" var isValid = true + var iconSource: PluginIconSource? var systemImage = "shippingbox" var iconColor = PluginBrowserColor.accent } @@ -317,7 +322,7 @@ struct PluginInstallSheetContent: View { .disabled(isBusy) .accessibilityLabel(Text("AUTO_BROWSER_QUEUE_REMOVE \(entry.name)")) .accessibilityIdentifier("plugins.queue.remove." + entry.id) - PluginBrowserIcon(systemImage: entry.systemImage, color: entry.iconColor) + PluginBrowserIcon(systemImage: entry.systemImage, color: entry.iconColor, source: entry.iconSource) VStack(alignment: .leading, spacing: 3) { Text(verbatim: entry.name).font(.body.weight(.semibold)) (Text(verbatim: entry.version) + Text(" · ") + Text(isBusy ? LocalizedStringKey("AUTO_BROWSER_INSTALLING") : entry.detail)) @@ -382,23 +387,46 @@ private struct PluginBrowserIcon: View { let color: Color var size: CGFloat = 40 var isInstalled = false + var source: PluginIconSource? + @State private var decoded: DecodedPluginIcon? + @State private var loadedKey: String? var body: some View { - Image(systemName: systemImage) - .font(.system(size: size * 0.58, weight: .regular)) - .foregroundStyle(.white) - .frame(width: size, height: size) - .background(color, in: RoundedRectangle(cornerRadius: size * 0.225)) - .overlay(alignment: .bottomTrailing) { - if isInstalled { - Image(systemName: "checkmark") - .font(.system(size: 9, weight: .heavy)) - .foregroundStyle(.white) - .frame(width: 14, height: 14) - .background(AutomationStatusColor.ok, in: Circle()) - .offset(x: 4, y: 4) - } + Group { + if loadedKey == source?.cacheKey, let decoded { + Image(uiImage: decoded.image) + .resizable() + .scaledToFit() + } else { + Image(systemName: systemImage) + .font(.system(size: size * 0.58, weight: .regular)) + .foregroundStyle(.white) + } + } + .frame(width: size, height: size) + .background(color, in: RoundedRectangle(cornerRadius: size * 0.225)) + .clipShape(RoundedRectangle(cornerRadius: size * 0.225)) + .overlay(alignment: .bottomTrailing) { + if isInstalled { + Image(systemName: "checkmark") + .font(.system(size: 9, weight: .heavy)) + .foregroundStyle(.white) + .frame(width: 14, height: 14) + .background(AutomationStatusColor.ok, in: Circle()) + .offset(x: 4, y: 4) } - .accessibilityHidden(true) + } + .task(id: source?.id) { + if loadedKey != source?.cacheKey { + decoded = nil + loadedKey = nil + } + guard let source else { return } + let image = await PluginIconLoader.shared.image(for: source) + guard !Task.isCancelled else { return } + decoded = image + loadedKey = source.cacheKey + } + .accessibilityHidden(true) } } diff --git a/Interceptor/Views/Automation/PluginBrowserView.swift b/Interceptor/Views/Automation/PluginBrowserView.swift index 99018f9..9b99af2 100644 --- a/Interceptor/Views/Automation/PluginBrowserView.swift +++ b/Interceptor/Views/Automation/PluginBrowserView.swift @@ -83,7 +83,7 @@ struct PluginBrowserView: View { PluginInstallQueueDisplayEntry( id: queueID(entry.id), name: entry.package.manifest.name, version: entry.package.manifest.version, detail: queueEntryIsValid(entry) ? queueDetail(entry) : "AUTO_BROWSER_QUEUE_ITEM_CHANGED", - isValid: queueEntryIsValid(entry), systemImage: "shippingbox", + isValid: queueEntryIsValid(entry), iconSource: .bundled(entry.package), systemImage: "shippingbox", ) }, isBusy: model.isProcessing, canConfirm: !model.queue.isEmpty && model.queue.allSatisfy(queueEntryIsValid), @@ -200,6 +200,17 @@ struct PluginSourcesView: View { @State private var addedURL: RepositoryURL? @State private var pendingAddedURL: RepositoryURL? @State private var pendingRemoval: RepositoryRecord? + @State private var editMode: EditMode = .inactive + + private var isEditing: Bool { editMode.isEditing } + private var canModifySources: Bool { + isEditing && !model.isProcessing && model.controller.storeError == nil + } + + private var editButtonRole: ButtonRole? { + if #available(iOS 26.0, *), isEditing { return .confirm } + return nil + } var body: some View { List { @@ -226,10 +237,17 @@ struct PluginSourcesView: View { } .accessibilityIdentifier("plugins.repo." + record.displayName) .swipeActions { - Button("AUTO_BROWSER_DELETE", role: .destructive) { pendingRemoval = record } + if !model.isProcessing { + Button("AUTO_BROWSER_DELETE", role: .destructive) { + guard !model.isProcessing else { return } + pendingRemoval = record + } + } } + .deleteDisabled(model.isProcessing) } .onDelete { offsets in + guard !model.isProcessing else { return } if let index = offsets.first, model.controller.repositories.indices.contains(index) { pendingRemoval = model.controller.repositories[index] } @@ -251,20 +269,42 @@ struct PluginSourcesView: View { .refreshable { await model.refreshSources() } .accessibilityAction(named: Text("AUTO_BROWSER_REFRESH")) { Task { await model.refreshSources() } } .toolbar { - ToolbarItemGroup(placement: .primaryAction) { - EditButton().disabled(model.isProcessing) - Menu { - Button("AUTO_ADD_REPOSITORY") { showAdd = true }.accessibilityIdentifier("plugins.addRepository") - Button("AUTO_IMPORT_FILE") { showImporter = true }.accessibilityIdentifier("plugins.importFile") - } label: { Label("AUTO_BROWSER_ADD", systemImage: "plus") } - .disabled(model.isProcessing || model.controller.storeError != nil) + if isEditing { + ToolbarItem(placement: .primaryAction) { + Menu { + Button("AUTO_ADD_REPOSITORY") { + guard canModifySources else { return } + showAdd = true + }.accessibilityIdentifier("plugins.addRepository") + Button("AUTO_IMPORT_FILE") { + guard canModifySources else { return } + showImporter = true + }.accessibilityIdentifier("plugins.importFile") + } label: { Label("AUTO_BROWSER_ADD", systemImage: "plus") } + .disabled(!canModifySources) .accessibilityIdentifier("plugins.add") + } + } + // Keep one trailing Edit/Done button while Add appears or disappears. + ToolbarItem(placement: .primaryAction) { + Button(role: editButtonRole) { + editMode = isEditing ? .inactive : .active + } label: { + if #available(iOS 26.0, *), isEditing { + Label("SSL_LIST_DONE", systemImage: "checkmark") + } else { + Text(isEditing ? "SSL_LIST_DONE" : "SSL_LIST_EDIT") + } + } + .disabled(model.isProcessing) + .accessibilityIdentifier("plugins.sources.edit") } } .sheet(isPresented: $showAdd, onDismiss: { addedURL = pendingAddedURL; pendingAddedURL = nil }) { AddRepositorySheet(controller: model.controller) { pendingAddedURL = $0 } + .environment(\.editMode, .constant(.inactive)) } .navigationDestination(isPresented: Binding(get: { addedURL != nil }, set: { if !$0 { @@ -276,7 +316,8 @@ struct PluginSourcesView: View { } } .fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in - guard case let .success(url) = result else { return } + guard !model.isProcessing, model.controller.storeError == nil, + case let .success(url) = result else { return } let scoped = url.startAccessingSecurityScopedResource() Task { _ = await model.controller.importFile(at: url) @@ -292,11 +333,16 @@ struct PluginSourcesView: View { })) { Button("AUTO_BROWSER_CANCEL", role: .cancel) { pendingRemoval = nil } Button("AUTO_BROWSER_DELETE", role: .destructive) { - guard let record = pendingRemoval else { return } + guard !model.isProcessing, let record = pendingRemoval else { + pendingRemoval = nil + return + } pendingRemoval = nil Task { await model.controller.deleteRepository(record.url) } } } message: { Text("AUTO_BROWSER_REMOVE_SOURCE_FOOTER") } + .environment(\.editMode, $editMode) + .onDisappear { editMode = .inactive } } private var localPackages: [InstalledRevision] { @@ -392,7 +438,8 @@ struct PluginCatalogPackageLink: View { PluginPackageDetailView(model: model, family: item.id, sourceURL: item.record?.url) } label: { PluginPackageRow(name: item.name, author: item.author, version: item.version, - summary: item.summary ?? "", isInstalled: item.installed != nil) + summary: item.summary ?? "", iconSource: model.iconSource(for: item.id, entry: item.entry, record: item.record), + isInstalled: item.installed != nil) .accessibilityHint(Text(verbatim: item.record?.displayName ?? item.id.source)) } .accessibilityIdentifier(identifier) @@ -489,7 +536,7 @@ struct PluginInstalledPackagesView: View { } label: { let manifest = revision.package.manifest PluginPackageRow(name: manifest.name, author: manifest.author, version: manifest.version, - summary: manifest.summary ?? "", isInstalled: true) + summary: manifest.summary ?? "", iconSource: .bundled(revision.package), isInstalled: true) } .accessibilityIdentifier("plugins.package." + revision.package.manifest.id.uuidString) .swipeActions { diff --git a/Interceptor/Views/Automation/PluginPackageDetailView.swift b/Interceptor/Views/Automation/PluginPackageDetailView.swift index 3d190db..99d590a 100644 --- a/Interceptor/Views/Automation/PluginPackageDetailView.swift +++ b/Interceptor/Views/Automation/PluginPackageDetailView.swift @@ -90,6 +90,7 @@ struct PluginPackageDetailView: View { private func ready(_ package: PluginPackagePresentation) -> some View { List { PluginPackageHero(name: package.manifest.name, targetHosts: package.manifest.targetHosts, + iconSource: model.iconSource(for: family, entry: entry, record: record), actionTitle: selected != nil ? "AUTO_BROWSER_MODIFY" : queued ? "AUTO_BROWSER_QUEUED" : "AUTO_BROWSER_GET", isActionEnabled: !busy && package.isComplete && (selected != nil || record != nil), isWorking: busy, modifyActions: selected.map { _ in @@ -213,12 +214,6 @@ struct PluginPackageDetailView: View { .contentShape(Rectangle()) } .accessibilityIdentifier("plugins.package.manifestJSON") - if let selected { - NavigationLink("AUTO_BROWSER_TEST") { - ScriptDetailView(session: ScriptSession(controller: model.controller, revision: selected), testOnly: true) - } - .accessibilityIdentifier("plugins.package.test") - } } header: { Text("AUTO_BROWSER_CONTENTS") } } } diff --git a/Interceptor/Views/Automation/ScriptDetailView.swift b/Interceptor/Views/Automation/ScriptDetailView.swift deleted file mode 100644 index aee99ea..0000000 --- a/Interceptor/Views/Automation/ScriptDetailView.swift +++ /dev/null @@ -1,350 +0,0 @@ -import AutomationCore -import AutomationRuntime -import SwiftUI - -struct ScriptDetailView: View { - @State var session: ScriptSession - var testOnly = false - @State private var approvalReview: ApprovalReview? - @State private var approvalStale = false - /// A full-screen cover can report the detail view as disappeared; only a real pop may cancel a dry run. - @State private var isSourcePresented = false - @State private var sampleJSON: SampleJSON? - - private struct SampleJSON: Identifiable { - let id = UUID() - let title: LocalizedStringKey - let json: String - } - - /// Frozen at capture time so the sheet can only ever show the package the generation was read for. - private struct ApprovalReview: Identifiable { - let id = UUID() - let revision: InstalledRevision - let expectedGeneration: UUID - } - - var body: some View { - Form { - if !testOnly { - Section { - TrustBadgeLabel(badge: session.badge) - VStack(alignment: .leading, spacing: 4) { - Text("AUTO_REVISION_HASH").font(.footnote).foregroundStyle(.secondary) - HashText(value: session.revision.package.revision) - } - if case let .localEdit(parent) = session.revision.provenance.origin { - VStack(alignment: .leading, spacing: 4) { - Text("AUTO_PARENT_HASH").font(.footnote).foregroundStyle(.secondary) - HashText(value: parent) - } - } - } header: { Text(verbatim: session.revision.package.manifest.name) } footer: { Text("AUTO_DISABLED_FOOTER") } - ScriptMetadataSection(manifest: session.revision.package.manifest) - ScriptTargetsSection(manifest: session.revision.package.manifest) - if session.isV2 { - activationSection - } - Section { - PluginSourceRow(fileName: session.isV2 ? session.selectedSourceFile : nil, identifier: "script.openSource") { - isSourcePresented = true - } - } header: { Text("AUTO_SOURCE") } - } - Section { - if session.isV2 { - Picker("AUTO_HOOK", selection: $session.hook) { - ForEach(session.hooks, id: \.self) { hook in Text(verbatim: hook.rawValue).tag(hook) } - } - .pickerStyle(.menu).accessibilityIdentifier("script.hook") - } else { - Picker("AUTO_HOOK", selection: $session.hook) { - Text("AUTO_HOOK_REQUEST").tag(JavaScriptHook.request) - Text("AUTO_HOOK_RESPONSE").tag(JavaScriptHook.response) - } - .pickerStyle(.segmented).accessibilityIdentifier("script.hook") - } - jsonViewer("AUTO_SYNTHETIC_EVENT", json: session.eventText, id: "script.event") - jsonViewer("AUTO_SYNTHETIC_CONFIG", json: session.configText, id: "script.config") - } header: { - if testOnly { Text(verbatim: session.revision.package.manifest.name) } - else { Text("AUTO_DRY_RUN") } - } footer: { Text("AUTO_SYNTHETIC_FOOTER") } - if !testOnly { - Section { - runControls - } - .listRowBackground(Color.clear).listRowInsets(EdgeInsets()) - } - Section { result } - } - .accessibilityIdentifier("script.form") - .safeAreaInset(edge: .bottom) { - if testOnly { runControls.padding().background(.bar) } - } - .navigationTitle(testOnly ? Text("AUTO_DRY_RUN") : Text(verbatim: session.revision.package.manifest.name)) - .navigationBarTitleDisplayMode(.inline) - .task { await session.refreshActivation() } - .sheet(item: $approvalReview) { review in - approvalSheet(review) - } - .alert("AUTO_TEST_COMPLETE", isPresented: Binding( - get: { session.emptyResultNotice != nil }, - set: { if !$0 { session.dismissEmptyResultNotice() } }, - )) { - Button("AUTO_ALERT_OK") {} - } message: { - Text("AUTO_TEST_NO_CHANGES") - } - .fullScreenCover(isPresented: $isSourcePresented) { - PluginSourceReader(fileNames: session.isV2 ? session.sourceFileNames : [], selection: $session.selectedSourceFile, - source: { _ in session.source }, sourceIdentifier: "plugin.source", - pickerIdentifier: "script.sourceFile", closeIdentifier: "script.closeSource") { - isSourcePresented = false - } - } - .fullScreenCover(item: $sampleJSON) { sample in - NavigationStack { - PluginJSONViewer(json: Self.display(sample.json), identifier: "script.sampleJSON", fillsAvailableSpace: true) - .frame(maxWidth: .infinity, maxHeight: .infinity) - .padding(.horizontal) - .navigationTitle(Text(sample.title)) - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .confirmationAction) { - Button("AUTO_KEYBOARD_DONE") { sampleJSON = nil } - .accessibilityIdentifier("script.closeJSON") - } - } - } - } - // A full-screen cover may report this view as disappearing; that must not cancel a pending dry run. - // The cover can only be closed by the reader itself, so a disappear while it is up is never a pop. - .onDisappear { if !isSourcePresented, sampleJSON == nil { session.leave() } } - .tint(Color("PluginAccent")) - } - - private var activationSection: some View { - Section { - LabeledContent("AUTO_LIVE_STATUS") { - Text(LocalizedStringKey(session.isActive ? "AUTO_LIVE_ACTIVE" : "AUTO_LIVE_INACTIVE")) - } - if session.isActive { - Button("AUTO_REVOKE", role: .destructive) { Task { await session.revokeActivation() } } - .accessibilityIdentifier("script.revoke") - } else { - Button("AUTO_ACTIVATE") { - Task { - approvalStale = false - await session.refreshActivation() - guard !session.isDirty, !session.isSaving, let generation = session.activationGeneration else { return } - approvalReview = ApprovalReview(revision: session.revision, expectedGeneration: generation) - } - } - .disabled(session.isDirty || !session.activationAvailable) - .accessibilityIdentifier("script.activate") - } - } header: { Text("AUTO_LIVE") } footer: { - VStack(alignment: .leading, spacing: 6) { - Text("AUTO_ACTIVATION_CONNECTION") - if approvalStale { - Text("AUTO_ACTIVATION_STALE").foregroundStyle(AutomationStatusColor.error).accessibilityIdentifier("script.activationError") - } else if let key = session.activationErrorKey { - Text(LocalizedStringKey(key)).foregroundStyle(AutomationStatusColor.error).accessibilityIdentifier("script.activationError") - } - } - } - } - - private func approvalSheet(_ review: ApprovalReview) -> some View { - let package = review.revision.package - let manifest = package.manifest - let rules = approvalRules(manifest) - let fields = approvalFields(manifest) - return NavigationStack { - Form { - Section { - Text(verbatim: manifest.name) - Text(verbatim: String.localizedStringWithFormat(String(localized: "AUTO_APPROVAL_COUNTS"), - Int64(rules.count), Int64(fields.count))) - } footer: { Text("AUTO_ALERT_CONNECTION") } - Section { - ForEach(Array(rules.enumerated()), id: \.offset) { index, rule in - HashText(value: rule, identifier: "script.approvalRule.\(index)") - } - } header: { Text("AUTO_TARGETS") } footer: { Text("AUTO_APPROVAL_TARGETS_FOOTER") } - Section { - LabeledContent("AUTO_APPROVAL_REQUEST_JSON") { - Text(LocalizedStringKey(manifest.writeRequestBody ? "AUTO_APPROVAL_CAN_CHANGE" : "AUTO_APPROVAL_CANNOT_CHANGE")) - } - LabeledContent("AUTO_APPROVAL_RESPONSE_JSON") { - Text(LocalizedStringKey(manifest.writeResponseBody ? "AUTO_APPROVAL_CAN_CHANGE" : "AUTO_APPROVAL_CANNOT_CHANGE")) - } - } footer: { - Text("AUTO_ALERT_WEBHOOK") - } - Section { - if fields.isEmpty { - Text("AUTO_READ_NONE") - } - ForEach(Array(fields.enumerated()), id: \.offset) { index, field in - HashText(value: field, identifier: "script.approvalRead.\(index)") - } - } header: { Text("AUTO_APPROVAL_READ_DATA") } - Section { - HashText(value: package.revision, identifier: "script.approvalRevision") - } header: { Text("AUTO_ALERT_REVISION") } - } - .accessibilityIdentifier("script.approvalForm") - .navigationTitle("AUTO_APPROVAL_REVIEW") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("Cancel") { approvalReview = nil } - .accessibilityIdentifier("script.cancelActivation") - } - ToolbarItem(placement: .confirmationAction) { - Button("AUTO_ACTIVATE_CONFIRM") { approve(review) } - .accessibilityIdentifier("script.confirmActivation") - } - } - } - .presentationDetents([.large]) - .tint(Color("PluginAccent")) - } - - private func approve(_ review: ApprovalReview) { - guard approvalReview?.id == review.id else { return } - approvalReview = nil - Task { - guard session.revision.id == review.revision.id, - session.revision.package.revision == review.revision.package.revision, - !session.isDirty, !session.isSaving - else { - approvalStale = true - return - } - await session.activate(expectedGeneration: review.expectedGeneration) - } - } - - /// Every unique rule in full, in deterministic order. Names, hosts and paths come from an unverified - /// package, so they are only ever shown verbatim. - private func approvalRules(_ manifest: PluginManifest) -> [String] { - var seen = Set() - var rules: [(sort: String, text: String)] = [] - for match in manifest.matches { - let path: String = switch match.path { - case let .exact(value)?: value - case let .prefix(value)?: value + "*" - case nil: String(localized: "AUTO_RULE_ANY_PATH") - } - for host in match.hosts.sorted() { - for method in match.methods?.sorted() ?? [""] { - let key = [method, host, path, match.path == nil ? "nil" : "p"].joined(separator: "\u{1F}") - guard seen.insert(key).inserted else { continue } - let methodText = method.isEmpty ? String(localized: "AUTO_RULE_ANY_METHOD") : method - rules.append((key, [methodText, host, path].joined(separator: " "))) - } - } - } - return rules.sorted { $0.sort < $1.sort }.map(\.text) - } - - private func approvalFields(_ manifest: PluginManifest) -> [String] { - let read = manifest.read - let metadata = read.metadata.map { field in - switch field { - case "method": String(localized: "AUTO_APPROVAL_READ_METHOD") - case "host": String(localized: "AUTO_APPROVAL_READ_HOST") - case "path": String(localized: "AUTO_APPROVAL_READ_PATH") - case "status": String(localized: "AUTO_APPROVAL_READ_STATUS") - default: field - } - } - var fields = metadata + read.headers.map { String(localized: "AUTO_APPROVAL_HEADER_PREFIX") + $0 } - + read.queryKeys.map { String(localized: "AUTO_APPROVAL_QUERY_PREFIX") + $0 } - if read.body == .json { - fields.append(String(localized: "AUTO_JSON_BODY")) - } - return fields - } - - @ViewBuilder private func jsonViewer(_ title: LocalizedStringKey, json: String, id: String) -> some View { - if testOnly { - Button { - sampleJSON = SampleJSON(title: title, json: json) - } label: { - HStack { - Text(title) - Spacer() - Image(systemName: "chevron.right").foregroundStyle(.tertiary) - } - } - .accessibilityIdentifier(id) - } else { - VStack(alignment: .leading, spacing: 4) { - Text(title).font(.footnote).foregroundStyle(.secondary) - PluginJSONViewer(json: json, identifier: id) - .frame(minHeight: 80, maxHeight: 220) - } - } - } - - private var runControls: some View { - VStack(spacing: 8) { - Button { session.run() } label: { Text("AUTO_RUN_TEST").frame(maxWidth: .infinity, minHeight: 44) } - .buttonStyle(.borderedProminent).disabled(!session.canRun) - .accessibilityIdentifier("script.run") - if session.isRunning { - Button(role: .cancel) { session.cancelRun() } label: { Text("Cancel").frame(maxWidth: .infinity, minHeight: 44) } - .buttonStyle(.bordered) - .accessibilityIdentifier("script.cancel") - } - } - } - - /// Display-only layout of a validated result; the stored preview and action bytes stay compact. - private static func display(_ json: String) -> String { - JSONPrettyPrinter.format(json, maxBytes: Limits.payload, objectOnly: false) - } - - @ViewBuilder private var result: some View { - switch session.runState { - case .idle: Text("AUTO_NO_RESULT").foregroundStyle(.secondary) - case .running: ProgressView() - case let .failed(key): Text(LocalizedStringKey(key)).foregroundStyle(AutomationStatusColor.error).accessibilityIdentifier("script.error") - case let .finished(actions): - Text(LocalizedStringKey(session.isV2 ? "AUTO_TEST_RESULT" : "AUTO_VALIDATED_ACTIONS")).foregroundStyle(AutomationStatusColor.ok).font(.headline).accessibilityIdentifier("script.validated") - Label("AUTO_NOT_SENT", systemImage: "paperplane.slash") - if let preview = session.bodyPreview { - if testOnly { - jsonViewer("AUTO_BODY_PREVIEW", json: preview, id: "script.bodyPreview") - } else { - Text("AUTO_BODY_PREVIEW").font(.headline) - Text(verbatim: Self.display(preview)).font(.system(.footnote, design: .monospaced)).textSelection(.enabled) - .accessibilityIdentifier("script.bodyPreview") - } - } - if actions.isEmpty, session.bodyPreview == nil { - Text("AUTO_NO_ACTIONS").foregroundStyle(.secondary) - } - ForEach(actions) { action in - VStack(alignment: .leading, spacing: 4) { - switch action.kind { - case let .webhook(endpointID): HashText(value: endpointID.uuidString) - case let .http(binding, destination): - Text(verbatim: binding).font(.headline) - Text(verbatim: "GET " + destination).font(.footnote).textSelection(.enabled) - Text("AUTO_APPROVAL_OUTBOUND_HEADERS").font(.footnote).foregroundStyle(.secondary) - } - if testOnly { - jsonViewer("JSON", json: action.json, id: "script.actionJSON.\(action.id)") - } else { - Text(verbatim: Self.display(action.json)).font(.system(.footnote, design: .monospaced)).textSelection(.enabled) - } - } - } - } - } -} diff --git a/InterceptorTests/PackageCatalogDatabaseTests.swift b/InterceptorTests/PackageCatalogDatabaseTests.swift index 38571df..9cc7325 100644 --- a/InterceptorTests/PackageCatalogDatabaseTests.swift +++ b/InterceptorTests/PackageCatalogDatabaseTests.swift @@ -81,6 +81,31 @@ final class PackageCatalogDatabaseTests: XCTestCase { // MARK: Persistence and offline + func testIconReadDistinguishesMissingContentFromValidNoIconAfterRestart() async throws { + let raw = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==")! + let fixture = try AutomationFixtures.multiFilePackage(name: "Icon") + var root = try StrictJSON.parse(fixture.bytes).objectValue! + var manifest = root["manifest"]!.objectValue! + manifest["icon"] = .string("icon.png") + root["manifest"] = .object(manifest) + root["assets"] = .object(["icon.png": .string(raw.base64EncodedString())]) + let withIcon = try PluginPackage.validate(JSONValue.object(root).data()), plain = try package("Plain") + let snap = try snapshot(packages: [withIcon, plain]), url = directory() + do { + let db = try PackageCatalogDatabase(url: url) + try await staged(db, snap, [withIcon, plain]) + } + let reopened = try PackageCatalogDatabase(url: url) + let icon = try await reopened.icon(sha256: withIcon.revision) + XCTAssertEqual(icon?.data, raw) + let noIcon = try await reopened.icon(sha256: plain.revision) + XCTAssertNil(noIcon) + do { + _ = try await reopened.icon(sha256: String(repeating: "0", count: 64)) + XCTFail("Missing content must be retryable rather than a cached no-icon result") + } catch { XCTAssertEqual(error as? PackageCatalogError, .contentMismatch) } + } + func testCompletedCatalogSurvivesRestartAndServesDetailOffline() async throws { let dir = directory().appendingPathComponent("db") let a = try package("Alpha", author: "Ann", summary: "First", category: "Tools") diff --git a/InterceptorTests/PackageCatalogLifecycleTests.swift b/InterceptorTests/PackageCatalogLifecycleTests.swift index b536847..2502527 100644 --- a/InterceptorTests/PackageCatalogLifecycleTests.swift +++ b/InterceptorTests/PackageCatalogLifecycleTests.swift @@ -488,6 +488,7 @@ private final class FailingLifecycleCatalog: PackageCatalogStoring { func detail(in record: RepositoryRecord, entryID: UUID) throws -> PluginPackagePresentation? { try base.detail(in: record, entryID: entryID) } func packageBytes(in record: RepositoryRecord, entry: IndexEntry) throws -> Data? { try base.packageBytes(in: record, entry: entry) } func reusableBytes(sha256: String) throws -> Data? { try base.reusableBytes(sha256: sha256) } + func icon(sha256: String) async throws -> PluginIcon? { try await base.icon(sha256: sha256) } func isComplete(_ snapshot: VerifiedSnapshot) throws -> Bool { try base.isComplete(snapshot) } } diff --git a/InterceptorTests/PluginCatalogReadTests.swift b/InterceptorTests/PluginCatalogReadTests.swift index 54d345b..6b58cb2 100644 --- a/InterceptorTests/PluginCatalogReadTests.swift +++ b/InterceptorTests/PluginCatalogReadTests.swift @@ -59,6 +59,23 @@ final class PluginCatalogReadTests: XCTestCase { return try RepositoryEnvelope.verify(envelope: envelope.data(), url: url, now: AutomationFixtures.now) } + private func withIcon(_ package: PluginPackage, path: String) throws -> PluginPackage { + let encoded = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" + var root = try XCTUnwrap(JSONValue(parsing: package.bytes).objectValue) + var manifest = try XCTUnwrap(root["manifest"]?.objectValue) + manifest["icon"] = .string(path) + root["manifest"] = .object(manifest) + root["assets"] = .object([path: .string(encoded)]) + return try PluginPackage.validate(JSONValue.object(root).data()) + } + + private func install(_ package: PluginPackage, from record: RepositoryRecord) throws { + let state = try coordinator.state() + _ = try coordinator.batch([InstallationRequest(package: package, snapshot: XCTUnwrap(record.snapshot), + expectedSourceGeneration: record.generation, operation: .add)], + expectedSelectionGeneration: state.selectionGeneration, now: AutomationFixtures.now) + } + /// This database instance leaves scope before the controller opens the same persistent store. private func stageAndAccept(_ packages: [PluginPackage], url: RepositoryURL = AutomationFixtures.url, sequence: Int64 = 1, receipt: UInt64 = 1) async throws -> RepositoryRecord @@ -232,6 +249,80 @@ final class PluginCatalogReadTests: XCTestCase { assertNoNetwork(client) } + func testInstalledIconTakesPrecedenceOverPublishedUpdate() async throws { + let local = try withIcon(AutomationFixtures.multiFilePackage(name: "Selected icon"), path: "selected.png") + let original = try await stageAndAccept([local]) + try install(local, from: original) + let published = try withIcon(described(local, version: "2.0.0"), path: "published.png") + let refreshed = try await stageAndAccept([published], sequence: 2, receipt: 2) + let (controller, browser, client) = try await offlineController(packages: [published], snapshot: XCTUnwrap(refreshed.snapshot)) + let current = try XCTUnwrap(controller.repositories.first) + let entry = try XCTUnwrap(current.snapshot?.index.plugins.first) + let family = PluginBrowserFamilyID(repository: current.url, manifestID: local.manifest.id) + let source = try XCTUnwrap(browser.iconSource(for: family, entry: entry, record: current)) + let icon = try await source.load() + XCTAssertEqual(icon, try XCTUnwrap(local.icon)) + XCTAssertNotEqual(icon, try XCTUnwrap(published.icon), "The selected package owns its displayed icon, including its asset path") + assertNoNetwork(client) + } + + func testInstalledPackageWithoutIconDoesNotBorrowPublishedIcon() async throws { + let local = try AutomationFixtures.multiFilePackage(name: "Selected without icon") + let original = try await stageAndAccept([local]) + try install(local, from: original) + let published = try withIcon(described(local, version: "2.0.0"), path: "published.png") + let refreshed = try await stageAndAccept([published], sequence: 2, receipt: 2) + let (controller, browser, client) = try await offlineController(packages: [published], snapshot: XCTUnwrap(refreshed.snapshot)) + let current = try XCTUnwrap(controller.repositories.first) + let entry = try XCTUnwrap(current.snapshot?.index.plugins.first) + let family = PluginBrowserFamilyID(repository: current.url, manifestID: local.manifest.id) + XCTAssertNotNil(published.icon) + XCTAssertNil(local.icon) + XCTAssertNil(browser.iconSource(for: family, entry: entry, record: current)) + assertNoNetwork(client) + } + + func testCatalogIconRequiresCurrentEntryAndMatchingFamily() async throws { + let originalPackage = try withIcon(AutomationFixtures.multiFilePackage(name: "Catalog icon"), path: "original.png") + let original = try await stageAndAccept([originalPackage]) + let staleEntry = try XCTUnwrap(original.snapshot?.index.plugins.first) + let published = try withIcon(described(originalPackage, version: "2.0.0"), path: "published.png") + let other = try AutomationFixtures.multiFilePackage(name: "Other accepted package") + let refreshed = try await stageAndAccept([published, other], sequence: 2, receipt: 2) + let (controller, browser, client) = try await offlineController(packages: [published, other], snapshot: XCTUnwrap(refreshed.snapshot)) + let current = try XCTUnwrap(controller.repositories.first) + let entry = try XCTUnwrap(current.snapshot?.index.plugins.first { $0.id == published.manifest.id }) + let otherEntry = try XCTUnwrap(current.snapshot?.index.plugins.first { $0.id == other.manifest.id }) + let family = PluginBrowserFamilyID(repository: current.url, manifestID: published.manifest.id) + let source = try XCTUnwrap(browser.iconSource(for: family, entry: entry, record: current)) + let icon = try await source.load() + XCTAssertEqual(icon, try XCTUnwrap(published.icon), "An uninstalled package uses the currently accepted local content") + XCTAssertNil(browser.iconSource(for: family, entry: staleEntry, record: original)) + XCTAssertNil(browser.iconSource(for: family, entry: otherEntry, record: current)) + let otherSource = PluginBrowserFamilyID(repository: try RepositoryURL(parsing: "https://other.example.com/repository.json"), + manifestID: published.manifest.id) + XCTAssertNil(browser.iconSource(for: otherSource, entry: entry, record: current)) + XCTAssertNil(browser.iconSource(for: family, entry: nil, record: current)) + XCTAssertNil(browser.iconSource(for: family, entry: entry, record: nil)) + assertNoNetwork(client) + } + + func testCatalogIconIsUnavailableWithoutDisplayDatabase() async throws { + let package = try withIcon(AutomationFixtures.multiFilePackage(name: "Catalog unavailable"), path: "icon.png") + let record = try await stageAndAccept([package]) + let client = FakeRepositoryClient(snapshot: try XCTUnwrap(record.snapshot), packages: [package]) + let controller = AutomationController(store: AutomationStore(fileURL: catalogURL), client: client, + executor: FakeScriptRunner(), clock: { AutomationFixtures.now }, packageCatalog: nil, + installationCoordinator: coordinator, hasCaptureConsent: { true }, stopCapture: {}) + await controller.load() + let browser = PluginBrowserModel(controller: controller) + let current = try XCTUnwrap(controller.repositories.first) + let entry = try XCTUnwrap(current.snapshot?.index.plugins.first) + let family = PluginBrowserFamilyID(repository: current.url, manifestID: package.manifest.id) + XCTAssertNil(browser.iconSource(for: family, entry: entry, record: current)) + assertNoNetwork(client) + } + func testSameManifestFromTwoSourcesStaysDistinctAndInstalledOrphanRemainsOffline() async throws { let first = try described(AutomationFixtures.package(name: "Same identity"), author: "First source", category: "Tools") let second = try described(first, author: "Second source") @@ -291,6 +382,7 @@ private final class CountingReadCatalog: PackageCatalogStoring { try base.packageBytes(in: record, entry: entry) } func reusableBytes(sha256: String) throws -> Data? { try base.reusableBytes(sha256: sha256) } + func icon(sha256: String) async throws -> PluginIcon? { try await base.icon(sha256: sha256) } func isComplete(_ snapshot: VerifiedSnapshot) throws -> Bool { try base.isComplete(snapshot) } } diff --git a/InterceptorTests/PluginIconLoaderTests.swift b/InterceptorTests/PluginIconLoaderTests.swift new file mode 100644 index 0000000..998d906 --- /dev/null +++ b/InterceptorTests/PluginIconLoaderTests.swift @@ -0,0 +1,135 @@ +import AutomationCore +import XCTest +@testable import Interceptor + +final class PluginIconLoaderTests: XCTestCase { + private enum Failure: Error { case missing } + private actor Gate { + private var continuation: CheckedContinuation? + private var entered = false + func wait() async { await withCheckedContinuation { continuation = $0; entered = true } } + func isWaiting() -> Bool { entered } + func open() { continuation?.resume(); continuation = nil } + } + private actor Counter { + var value = 0 + func increment() { value += 1 } + } + + private func icon(corrupt: Bool = false) throws -> PluginIcon { + let valid = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" + let invalid = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAA0lEQVRiYWSEoK5LAAAAAElFTkSuQmCC" + return try .validate(data: XCTUnwrap(Data(base64Encoded: corrupt ? invalid : valid)), path: "icon.png") + } + + func testConcurrentRequestsShareActualDecodeAndCachedThumbnail() async throws { + let loader = PluginIconLoader(), counter = Counter(), icon = try icon() + let source = PluginIconSource(id: "a", cacheKey: "a") { + await counter.increment() + await Task.yield() + return icon + } + async let a = loader.image(for: source) + async let b = loader.image(for: source) + let images = await (a, b) + XCTAssertEqual(images.0?.image.cgImage?.width, 1) + XCTAssertEqual(images.1?.image.cgImage?.height, 1) + _ = await loader.image(for: source) + let count = await counter.value + XCTAssertEqual(count, 1) + } + + func testMalformedCompressedImageRemainsBoundedAndDoesNotDecodeRepeatedly() async throws { + let loader = PluginIconLoader(), counter = Counter(), icon = try icon(corrupt: true) + let source = PluginIconSource(id: "bad", cacheKey: "bad") { await counter.increment(); return icon } + let first = await loader.image(for: source) + let second = await loader.image(for: source) + // ImageIO may recover a bounded image from corrupt data instead of returning nil. + // Both decoder outcomes are valid; the display cache must bound and reuse the result. + if let first { + XCTAssertLessThanOrEqual(first.image.cgImage!.width, 192) + XCTAssertLessThanOrEqual(first.image.cgImage!.height, 192) + } + XCTAssertEqual(first == nil, second == nil) + let count = await counter.value + XCTAssertEqual(count, 1) + } + + func testMissingCatalogContentCanBeLoadedAfterBackfill() async throws { + let loader = PluginIconLoader(), icon = try icon() + let missing = PluginIconSource(id: "sha:1", cacheKey: "sha") { throw Failure.missing } + let available = PluginIconSource(id: "sha:2", cacheKey: "sha") { icon } + let first = await loader.image(for: missing) + let second = await loader.image(for: available) + XCTAssertNil(first) + XCTAssertNotNil(second) + } + + func testBackfillGenerationDoesNotShareAnOlderMissingRequest() async throws { + let loader = PluginIconLoader(), gate = Gate(), icon = try icon() + let old = PluginIconSource(id: "sha:old", cacheKey: "sha") { + await gate.wait() + throw Failure.missing + } + let pending = Task { await loader.image(for: old) } + while !(await gate.isWaiting()) { await Task.yield() } + let ready = expectation(description: "new generation finishes before the old read") + let next = Task { + let image = await loader.image(for: .init(id: "sha:new", cacheKey: "sha") { icon }) + ready.fulfill() + return image + } + await fulfillment(of: [ready], timeout: 2) + await gate.open() + let current = await next.value + XCTAssertNotNil(current) + _ = await pending.value + let cached = await loader.image(for: .init(id: "sha:new", cacheKey: "sha") { throw Failure.missing }) + XCTAssertNotNil(cached) + } + + func testValidNoIconPackageCachesFallback() async { + let loader = PluginIconLoader(), counter = Counter() + let source = PluginIconSource(id: "no-icon", cacheKey: "no-icon") { await counter.increment(); return nil } + _ = await loader.image(for: source) + _ = await loader.image(for: source) + let count = await counter.value + XCTAssertEqual(count, 1) + } + + func testActualLosslessWebPDecodesWithItsNonSquareDimensions() async throws { + let data = Data(base64Encoded: "UklGRjAAAABXRUJQVlA4TCMAAAAvA0AAEB8gEEjaH3qN+RcQFPk/moCg4P/ogs2kwqFeI/ofAQA=")! + let icon = try PluginIcon.validate(data: data, path: "icon.webp") + let decoded = await PluginIconLoader().image(for: .init(id: "webp", cacheKey: "webp") { icon }) + XCTAssertEqual(decoded?.image.cgImage?.width, 4) + XCTAssertEqual(decoded?.image.cgImage?.height, 2) + } + + func testNoIconCatalogDoesNotChurnTheImageCacheLimit() async { + let loader = PluginIconLoader(countLimit: 2), counter = Counter() + for _ in 0..<2 { + for index in 0..<100 { + let key = String(index) + _ = await loader.image(for: .init(id: key, cacheKey: key) { await counter.increment(); return nil }) + } + } + let count = await counter.value + XCTAssertEqual(count, 100) + } + + func testCountAndCostLimitsEvictOldEntries() async throws { + let icon = try icon(), counter = Counter() + let loader = PluginIconLoader(countLimit: 2) + for key in ["a", "b", "c", "a"] { + _ = await loader.image(for: .init(id: key, cacheKey: key) { await counter.increment(); return icon }) + } + let count = await counter.value + XCTAssertEqual(count, 4) + let noStorage = PluginIconLoader(costLimit: 0), costCounter = Counter() + let source = PluginIconSource(id: "one", cacheKey: "one") { await costCounter.increment(); return icon } + _ = await noStorage.image(for: source) + _ = await noStorage.image(for: source) + let costCount = await costCounter.value + XCTAssertEqual(costCount, 2) + } +} diff --git a/InterceptorUITests/AutomationUITests.swift b/InterceptorUITests/AutomationUITests.swift index 8992726..ae22567 100644 --- a/InterceptorUITests/AutomationUITests.swift +++ b/InterceptorUITests/AutomationUITests.swift @@ -97,7 +97,7 @@ final class AutomationUITests: XCTestCase { } @MainActor - func testFourHookDryRunAndExplicitApproval() async { + func testExplicitApprovalCanBeGrantedAndRevoked() async { guard let repositoryURL = await requiredRepositoryURL() else { return } XCUIDevice.shared.orientation = .portrait for japanese in [false, true] { @@ -122,43 +122,8 @@ final class AutomationUITests: XCTestCase { tapEnabled(app) assertEnabled(false, app: app) - openPackageTest(app) - XCTAssertFalse(app.buttons.matching(identifier: "script.activate").firstMatch.exists, "Test has its own task, separate from grants") - XCTAssertFalse(app.buttons.matching(identifier: "script.openSource").firstMatch.exists) - let form = scrollContainer(app, "script.form") - for phase in ["request.onEnter", "request.onLeave", "response.onEnter", "response.onLeave"] { - reach(app.buttons.matching(identifier: "script.hook").firstMatch, in: form).tap() - let choice = app.buttons.matching(identifier: phase).firstMatch - XCTAssertTrue(choice.waitForExistence(timeout: 5)) - choice.tap() - let run = app.buttons.matching(identifier: "script.run").firstMatch - let ready = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in run.isHittable && run.isEnabled }, object: nil) - let settled = XCTWaiter.wait(for: [ready], timeout: 5) - if settled != .completed { attachDiagnostic("Run after Hook selection", app: app, detail: phase) } - XCTAssertEqual(settled, .completed, "Run stays at the bottom of the Test screen") - run.tap() - let expectsMutation = phase == "request.onEnter" - if !expectsMutation { - let alert = app.alerts.firstMatch - XCTAssertTrue(alert.waitForExistence(timeout: 5)) - XCTAssertEqual(alert.label, japanese ? "テスト完了" : "Test completed") - alert.buttons.matching(identifier: "OK").firstMatch.tap() - XCTAssertTrue(alert.waitForNonExistence(timeout: 5)) - } - let validated = app.staticTexts["script.validated"] - XCTAssertTrue(validated.waitForExistence(timeout: 5)) - reach(validated, in: form) - XCTAssertFalse(app.staticTexts["script.error"].exists) - if expectsMutation { - let json = openSampleJSON("script.bodyPreview", app: app) - // The first declared route is GET /other, which executes the secondary file. - assertJSON(json.value as? String ?? "", equals: #"{"limit":15}"#) - app.buttons.matching(identifier: "script.closeJSON").firstMatch.tap() - } else { - XCTAssertFalse(app.buttons.matching(identifier: "script.bodyPreview").firstMatch.exists) - } - if !japanese && phase == "request.onEnter" { attach("Separate package Test result en") } - } + XCTAssertFalse(app.buttons.matching(identifier: "plugins.package.test").firstMatch.exists) + XCTAssertFalse(app.buttons.matching(identifier: "script.run").firstMatch.exists) } } @@ -235,7 +200,7 @@ final class AutomationUITests: XCTestCase { } @MainActor - func testJSONSamplesAreReadOnlyAndFormatted() async { + func testManifestJSONIsReadOnlyAndFormatted() async { guard let repositoryURL = await requiredRepositoryURL() else { return } let app = launch(japanese: false, suite: "Interceptor.UITests.\(UUID().uuidString)") defer { app.terminate() } @@ -252,33 +217,38 @@ final class AutomationUITests: XCTestCase { attach("Full screen manifest JSON en") app.buttons.matching(identifier: "plugins.manifest.close").firstMatch.tap() XCTAssertTrue(scrollContainer(app, "plugins.package.detail").waitForExistence(timeout: 5)) - openPackageTest(app) - attach("Sample traffic and plugin configuration en") - let event = openSampleJSON("script.event", app: app) - let eventText = event.value as? String ?? "" - let sample = try? JSONSerialization.jsonObject(with: Data(eventText.utf8)) as? [String: Any] - let request = sample?["request"] as? [String: Any] - XCTAssertEqual(request?["host"] as? String, "example.com") - XCTAssertEqual(request?["method"] as? String, "GET") - XCTAssertEqual(request?["path"] as? String, "/other") - XCTAssertTrue(eventText.contains("\n ")) - assertReadOnly(event, app: app) - app.buttons.matching(identifier: "script.closeJSON").firstMatch.tap() - let config = openSampleJSON("script.config", app: app) - assertJSON(config.value as? String ?? "", equals: #"{"settings":{},"endpoints":{}}"#) - assertReadOnly(config, app: app) - app.buttons.matching(identifier: "script.closeJSON").firstMatch.tap() - app.buttons.matching(identifier: "script.run").firstMatch.tap() - let validated = app.staticTexts["script.validated"] - XCTAssertTrue(validated.waitForExistence(timeout: 5)) - reach(validated, in: scrollContainer(app, "script.form")) - let result = openSampleJSON("script.bodyPreview", app: app) - assertJSON(result.value as? String ?? "", equals: #"{"limit":15}"#) - assertReadOnly(result, app: app) - attach("Full screen formatted Test JSON en") - app.buttons.matching(identifier: "script.closeJSON").firstMatch.tap() - XCTAssertTrue(app.buttons.matching(identifier: "script.bodyPreview").firstMatch.exists, "Done preserves the completed result") - XCTAssertFalse(app.buttons.matching(identifier: "script.save").firstMatch.exists) + XCTAssertFalse(app.buttons.matching(identifier: "plugins.package.test").firstMatch.exists) + } + + @MainActor + func testSourcesAddMenuAppearsOnlyWhileEditing() { + let app = launch(japanese: false, suite: "Interceptor.UITests.\(UUID().uuidString)") + defer { app.terminate() } + openPlugins(app, japanese: false) + + let edit = app.buttons.matching(identifier: "plugins.sources.edit").firstMatch + let add = app.buttons.matching(identifier: "plugins.add").firstMatch + XCTAssertTrue(add.waitForNonExistence(timeout: 2), "Sources starts in viewing mode") + XCTAssertTrue(edit.waitForExistence(timeout: 5)) + XCTAssertEqual(edit.label, "Edit") + attach("Sources viewing en") + + enterSourcesEditMode(app) + XCTAssertEqual(edit.label, "Done") + attach("Sources editing en") + XCTAssertLessThan(add.frame.midX, edit.frame.midX, "Done stays at the trailing edge after Add appears") + edit.tap() + XCTAssertTrue(add.waitForNonExistence(timeout: 5), "Done returns Sources to viewing mode") + XCTAssertEqual(edit.label, "Edit") + + openAddRepository(app) + app.buttons.matching(identifier: "repo.cancel").firstMatch.tap() + XCTAssertTrue(app.textFields["repo.url"].waitForNonExistence(timeout: 5)) + enterSourcesEditMode(app) + selectTab("packages", app: app) + selectTab("sources", app: app) + XCTAssertTrue(add.waitForNonExistence(timeout: 5), "Returning to Sources resets edit mode") + XCTAssertEqual(edit.label, "Edit") } @MainActor @@ -641,9 +611,22 @@ private extension AutomationUITests { XCTAssertTrue(scrollContainer(app, "plugins." + tab).waitForExistence(timeout: 5)) } + @MainActor + func enterSourcesEditMode(_ app: XCUIApplication) { + let add = app.buttons.matching(identifier: "plugins.add").firstMatch + if !add.exists { + let edit = app.buttons.matching(identifier: "plugins.sources.edit").firstMatch + XCTAssertTrue(edit.waitForExistence(timeout: 5)) + edit.tap() + } + XCTAssertTrue(add.waitForExistence(timeout: 5)) + } + @MainActor func openAddRepository(_ app: XCUIApplication) { + enterSourcesEditMode(app) app.buttons.matching(identifier: "plugins.add").firstMatch.tap() + XCTAssertTrue(app.buttons.matching(identifier: "plugins.importFile").firstMatch.waitForExistence(timeout: 5)) app.buttons.matching(identifier: "plugins.addRepository").firstMatch.tap() XCTAssertTrue(app.textFields["repo.url"].waitForExistence(timeout: 5)) } @@ -837,27 +820,6 @@ private extension AutomationUITests { XCTAssertEqual(XCTWaiter.wait(for: [settled], timeout: 5), .completed, file: file, line: line) } - @MainActor - func openPackageTest(_ app: XCUIApplication) { - reach(app.buttons.matching(identifier: "plugins.package.test").firstMatch, in: scrollContainer(app, "plugins.package.detail")).tap() - XCTAssertTrue(scrollContainer(app, "script.form").waitForExistence(timeout: 5)) - let run = app.buttons.matching(identifier: "script.run").firstMatch - let ready = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in run.isHittable }, object: nil) - let visible = XCTWaiter.wait(for: [ready], timeout: 5) - if visible != .completed { attachDiagnostic("Package Test controls", app: app) } - XCTAssertEqual(visible, .completed) - } - - @MainActor - func openSampleJSON(_ id: String, app: XCUIApplication) -> XCUIElement { - reach(app.buttons.matching(identifier: id).firstMatch, in: scrollContainer(app, "script.form")).tap() - let viewer = app.textViews["script.sampleJSON"] - XCTAssertTrue(viewer.waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons.matching(identifier: "script.closeJSON").firstMatch.isHittable) - assertFullScreen(viewer, app: app) - return viewer - } - @MainActor func openFile(_ file: String, packageID: String, app: XCUIApplication) { reach(app.buttons.matching(identifier: "plugins.file." + packageID + "." + file).firstMatch, in: scrollContainer(app, "plugins.scripts")).tap() diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/Manifest.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/Manifest.swift index 5db2a9d..16582fa 100644 --- a/Packages/InterceptorAutomation/Sources/AutomationCore/Manifest.swift +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/Manifest.swift @@ -38,6 +38,8 @@ public struct PluginManifest: Equatable, Sendable { public let summary: String? /// Optional display-only grouping label (1...80 Unicode scalars, <=256 UTF-8 bytes), preserved verbatim. Not a trust claim. public let category: String? + /// Schema 2 only: path of the bundled static PNG/WebP asset. Display only. + public let icon: String? /// Optional publisher-declared static release date (`yyyy-MM-ddTHH:mm:ssZ`, UTC whole seconds). Display only; not a /// trust, ordering or freshness claim. Covered by the package bytes/revision hash. public let publishedAt: Date? @@ -61,7 +63,7 @@ public struct PluginManifest: Equatable, Sendable { let f = try JSONFields(v, required: isV2 ? ["schemaVersion", "id", "name", "version", "matches", "read", "write", "endpointBindings", "settings"] : ["schemaVersion", "id", "name", "version", "subscriptions", "read", "endpointBindings", "settings"], - optional: isV2 ? ["author", "summary", "category", "publishedAt", "outbound"] + optional: isV2 ? ["author", "summary", "category", "publishedAt", "outbound", "icon"] : ["author", "summary", "category", "publishedAt"], error: bad) let name = try f.string("name"), version = try f.string("version") guard Text.isDisplayName(name) else { throw bad } @@ -120,12 +122,20 @@ public struct PluginManifest: Equatable, Sendable { publishedAt = d } + var icon: String? + if f.has("icon") { + let path = try f.string("icon") + guard PluginIcon.isPath(path) else { throw bad } + icon = path + } + id = try f.uuid("id") self.publishedAt = publishedAt self.outbound = outbound self.author = author self.summary = summary self.category = category + self.icon = icon self.name = name self.version = version subscriptions = subs diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginIcon.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginIcon.swift new file mode 100644 index 0000000..68fe8aa --- /dev/null +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginIcon.swift @@ -0,0 +1,141 @@ +import Foundation + +/// Bounded, static PNG/WebP package asset. Structural validation never decompresses image data; +/// platform decoders may still reject the compressed stream and should use their normal fallback. +public struct PluginIcon: Equatable, Sendable { + public let data: Data + public let path: String + public let width: Int + public let height: Int + + private init(data: Data, path: String, width: Int, height: Int) { + self.data = data; self.path = path; self.width = width; self.height = height + } + + public static func isPath(_ path: String) -> Bool { + PluginPackage.isSourcePath(path) && (path.hasSuffix(".png") || path.hasSuffix(".webp")) + } + + public static func validate(data: Data, path: String) throws -> PluginIcon { + guard isPath(path), (1...65_536).contains(data.count) else { throw AutomationError.invalidManifest } + let parser = Parser(bytes: Array(data)) + let dimensions = try path.hasSuffix(".png") ? parser.png() : parser.webp() + return PluginIcon(data: data, path: path, width: dimensions.0, height: dimensions.1) + } + + private struct Parser { + let bytes: [UInt8] + private var bad: AutomationError { .invalidManifest } + private func be(_ at: Int) -> Int { + (0..<4).reduce(0) { ($0 << 8) | Int(bytes[at + $1]) } + } + private func le(_ at: Int, count: Int = 4) -> Int { + (0.. (Int, Int) { + guard (1...1024).contains(width), (1...1024).contains(height) else { throw bad } + return (width, height) + } + private func crc(_ range: Range) -> UInt32 { + var value = UInt32.max + for i in range { + value ^= UInt32(bytes[i]) + for _ in 0..<8 { value = (value >> 1) ^ (value & 1 == 0 ? 0 : 0xedb88320) } + } + return value ^ UInt32.max + } + + func png() throws -> (Int, Int) { + guard bytes.starts(with: [137, 80, 78, 71, 13, 10, 26, 10]) else { throw bad } + var offset = 8, size: (Int, Int)?, color = 0, depth = 0 + var palette = false, image = false, endedImage = false, imageBytes = 0 + while offset < bytes.count { + guard bytes.count - offset >= 12 else { throw bad } + let length = be(offset) + guard length <= bytes.count - offset - 12 else { throw bad } + let start = offset + 8, end = start + length + let type = Array(bytes[(offset + 4)..] = [0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16]] + guard depths[color]?.contains(depth) == true, bytes[start + 10] == 0, + bytes[start + 11] == 0, bytes[start + 12] <= 1 else { throw bad } + case "PLTE": + guard !palette, !image, color != 0, color != 4, length > 0, length % 3 == 0, + length <= 768, color != 3 || length / 3 <= (1 << depth) else { throw bad } + palette = true + case "IDAT": + guard !endedImage, color != 3 || palette else { throw bad } + image = true; imageBytes += length + case "IEND": + guard length == 0, image, imageBytes > 0, end + 4 == bytes.count, let size else { throw bad } + return size + default: + guard type[0] & 0x20 != 0 else { throw bad } + } + offset = end + 4 + } + throw bad + } + + func webp() throws -> (Int, Int) { + guard bytes.count >= 12, bytes[0..<4].elementsEqual("RIFF".utf8), + bytes[8..<12].elementsEqual("WEBP".utf8), le(4) == bytes.count - 8 else { throw bad } + var offset = 12, canvas: (Int, Int)?, image: (Int, Int)?, imageKind: String? + var flags: UInt8 = 0, metadata: Set = [] + while offset < bytes.count { + guard bytes.count - offset >= 8 else { throw bad } + let type = Array(bytes[offset..<(offset + 4)]) + guard type.allSatisfy({ (32...126).contains($0) }) else { throw bad } + let name = String(decoding: type, as: UTF8.self), length = le(offset + 4) + guard length <= bytes.count - offset - 8 else { throw bad } + let start = offset + 8, end = start + length, next = end + length % 2 + guard next <= bytes.count, length % 2 == 0 || bytes[end] == 0 else { throw bad } + switch name { + case "VP8X": + guard offset == 12, canvas == nil, length == 10, bytes[start] & 0xc3 == 0, + bytes[(start + 1)..<(start + 4)].allSatisfy({ $0 == 0 }) else { throw bad } + flags = bytes[start] + canvas = try dimensions(le(start + 4, count: 3) + 1, le(start + 7, count: 3) + 1) + case "VP8 ": + guard image == nil, length >= 10, bytes[start] & 1 == 0, + bytes[(start + 3)..<(start + 6)].elementsEqual([0x9d, 1, 0x2a]), + bytes[start + 7] & 0xc0 == 0, bytes[start + 9] & 0xc0 == 0 else { throw bad } + image = try dimensions(le(start + 6, count: 2), le(start + 8, count: 2)) + imageKind = name + case "VP8L": + guard image == nil, length >= 5, bytes[start] == 0x2f, bytes[start + 4] & 0xe0 == 0 else { throw bad } + let packed = le(start + 1) + image = try dimensions((packed & 0x3fff) + 1, ((packed >> 14) & 0x3fff) + 1) + imageKind = name + case "ANIM", "ANMF": throw bad + case "ICCP", "ALPH", "EXIF", "XMP ": + guard canvas != nil, metadata.insert(name).inserted else { throw bad } + if name == "ICCP" || name == "ALPH" { + guard image == nil, name != "ALPH" || length >= 1 else { throw bad } + } else { guard image != nil else { throw bad } } + default: break // Unknown printable ancillary chunks are ignored by WebP readers. + } + offset = next + } + guard let image else { throw bad } + if let canvas { + guard canvas.0 == image.0, canvas.1 == image.1, + metadata.contains("ICCP") == (flags & 0x20 != 0), + metadata.contains("EXIF") == (flags & 0x08 != 0), + metadata.contains("XMP ") == (flags & 0x04 != 0), + !metadata.contains("ALPH") || (flags & 0x10 != 0 && imageKind == "VP8 "), + flags & 0x10 == 0 || imageKind == "VP8L" || metadata.contains("ALPH") else { throw bad } + } + return image + } + } +} diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginPackage.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginPackage.swift index 246c72e..c64d947 100644 --- a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginPackage.swift +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginPackage.swift @@ -4,6 +4,7 @@ public struct PluginPackage: Equatable, Sendable { public let manifest: PluginManifest public let source: String? public let sourceFiles: [String: String] + public let icon: PluginIcon? public let bytes: Data /// Revision = SHA-256 of exact package bytes. public var revision: String { Digest.sha256Hex(bytes) } @@ -21,9 +22,9 @@ public struct PluginPackage: Equatable, Sendable { let f = try JSONFields(value, required: ["manifest", "source"], error: .invalidManifest) let source = try f.string("source") guard source.utf8.count <= Limits.source else { throw AutomationError.limitExceeded } - return PluginPackage(manifest: manifest, source: source, sourceFiles: [:], bytes: bytes) + return PluginPackage(manifest: manifest, source: source, sourceFiles: [:], icon: nil, bytes: bytes) } - let f = try JSONFields(value, required: ["manifest", "sourceFiles"], error: .invalidManifest) + let f = try JSONFields(value, required: ["manifest", "sourceFiles"], optional: ["assets"], error: .invalidManifest) guard try manifest.json.data().count <= 32 * 1024 else { throw AutomationError.limitExceeded } guard case .object(let rawFiles) = try f.value("sourceFiles"), (1...64).contains(rawFiles.count) else { throw AutomationError.invalidManifest } var files: [String: String] = [:] @@ -36,7 +37,18 @@ public struct PluginPackage: Equatable, Sendable { } let referenced = Set(manifest.matches.flatMap { $0.hooks.values }) guard referenced == Set(files.keys) else { throw AutomationError.invalidManifest } - return PluginPackage(manifest: manifest, source: nil, sourceFiles: files, bytes: bytes) + let icon: PluginIcon? + if let path = manifest.icon { + guard files[path] == nil, case .object(let assets) = try f.value("assets"), + assets.count == 1, case .string(let text)? = assets[path], + text.utf8.count <= 87_384, let data = Data(base64Encoded: text), + data.base64EncodedString() == text else { throw AutomationError.invalidManifest } + icon = try PluginIcon.validate(data: data, path: path) + } else { + guard !f.has("assets") else { throw AutomationError.invalidManifest } + icon = nil + } + return PluginPackage(manifest: manifest, source: nil, sourceFiles: files, icon: icon, bytes: bytes) } static func isSourcePath(_ path: String) -> Bool { @@ -81,7 +93,9 @@ public struct PluginPackage: Equatable, Sendable { /// Atomically replaces the exact set of routed source files without changing the manifest. public func replacingSources(_ files: [String: String]) throws -> PluginPackage { guard manifest.schemaVersion == 2, Set(files.keys) == Set(sourceFiles.keys) else { throw AutomationError.invalidManifest } - let bytes = try JSONValue.object(["manifest": manifest.json, "sourceFiles": .object(files.mapValues(JSONValue.string))]).data() + var object: [String: JSONValue] = ["manifest": manifest.json, "sourceFiles": .object(files.mapValues(JSONValue.string))] + if let icon { object["assets"] = .object([icon.path: .string(icon.data.base64EncodedString())]) } + let bytes = try JSONValue.object(object).data() return try PluginPackage.validate(bytes) } diff --git a/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c b/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c index ea452cb..d920ea9 100644 --- a/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c +++ b/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c @@ -1224,6 +1224,34 @@ static int source_path_ok(const Str *s) { return 1; } +// Image bytes are display-only; Core/SDK validate the media structure before installation. +// The runtime independently bounds and validates the inert asset envelope without evaluating it. +static int icon_path_ok(const Str *s) { + return source_path_ok(s) && + ((s->n >= 4 && memcmp(s->s + s->n - 4, ".png", 4) == 0) || + (s->n >= 5 && memcmp(s->s + s->n - 5, ".webp", 5) == 0)); +} + +static int asset_b64_digit(unsigned char c) { + if (c >= 'A' && c <= 'Z') return c - 'A'; + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + if (c >= '0' && c <= '9') return c - '0' + 52; + if (c == '+') return 62; + if (c == '/') return 63; + return -1; +} + +static int asset_base64_ok(const Str *s) { + if (s->n < 4 || s->n > 87384 || s->n % 4) return 0; + size_t padding = s->s[s->n - 1] == '=' ? 1 : 0; + if (padding && s->s[s->n - 2] == '=') padding++; + size_t length = s->n - padding; + for (size_t i = 0; i < length; i++) if (asset_b64_digit((unsigned char)s->s[i]) < 0) return 0; + if (padding && (asset_b64_digit((unsigned char)s->s[length - 1]) & ((1 << (padding * 2)) - 1))) return 0; + size_t raw = s->n / 4 * 3 - padding; + return raw >= 1 && raw <= 65536; +} + static int parse_match(RunState *st, JSContext *ctx, JSValueConst obj, Match *m) { static const char *const mk[] = {"hosts", "methods", "path", "hooks"}; static const char *const pk[] = {"kind", "value"}; @@ -1857,14 +1885,14 @@ static int load_read(RunState *st, JSContext *ctx, JSValueConst v) { static int load_manifest(RunState *st, JSContext *ctx, JSValueConst root, int *write_request, int *write_response) { static const char *const mk[] = {"schemaVersion", "id", "name", "version", "matches", "read", "write", "endpointBindings", "settings", "author", "summary", "category", - "publishedAt", "outbound"}; + "publishedAt", "outbound", "icon"}; static const char *const wk[] = {"requestBody", "responseBody", "files"}; - JSValue f[14], w[3]; + JSValue f[15], w[3]; Str s = {NULL, 0}, *bind = NULL; size_t nbind = 0; int ok = 0; w[0] = w[1] = w[2] = JS_UNDEFINED; - if (!read_obj(st, ctx, root, mk, 14, 0x1FFu, f)) return 0; + if (!read_obj(st, ctx, root, mk, 15, 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; str_free(&s); @@ -1888,6 +1916,10 @@ static int load_manifest(RunState *st, JSContext *ctx, JSValueConst root, int *w if (!get_str(ctx, f[12], &s, 20) || !published_at_ok(&s)) goto done; str_free(&s); } + if (!JS_IsUndefined(f[14])) { + if (!get_str(ctx, f[14], &s, 256) || !icon_path_ok(&s)) goto done; + str_free(&s); + } { V tmp; int32_t n; @@ -1928,7 +1960,7 @@ static int load_manifest(RunState *st, JSContext *ctx, JSValueConst root, int *w done: str_free(&s); strs_free(bind, nbind); - for (int i = 0; i < 14; i++) JS_FreeValue(ctx, f[i]); + for (int i = 0; i < 15; i++) JS_FreeValue(ctx, f[i]); JS_FreeValue(ctx, w[0]); JS_FreeValue(ctx, w[1]); JS_FreeValue(ctx, w[2]); @@ -1937,14 +1969,24 @@ static int load_manifest(RunState *st, JSContext *ctx, JSValueConst root, int *w // Validate every decoded source and all references, including files that will never evaluate. static int load_package(RunState *st, JSContext *ctx, JSValueConst root, int *write_request, int *write_response) { - static const char *const keys[] = {"manifest", "sourceFiles"}; - JSValue f[2]; - if (!read_obj(st, ctx, root, keys, 2, 3u, f)) return 0; + static const char *const keys[] = {"manifest", "sourceFiles", "assets"}; + JSValue f[3]; + if (!read_obj(st, ctx, root, keys, 3, 3u, f)) return 0; int ok = 0; Buf manifest = {NULL, 0, 0, 0}; + Str icon = {NULL, 0}, encoded = {NULL, 0}; + JSValue raw_icon = JS_UNDEFINED, asset[1] = {JS_UNDEFINED}; if (!serialize_value(st, ctx, f[0], 1, 32, QJS_MAX_MANIFEST_BYTES, &manifest)) goto done; free(manifest.p); manifest.p = NULL; if (!load_manifest(st, ctx, f[0], write_request, write_response)) goto done; + raw_icon = JS_GetPropertyStr(ctx, f[0], "icon"); + if (JS_IsException(raw_icon) || JS_IsUndefined(raw_icon) != JS_IsUndefined(f[2])) goto done; + if (!JS_IsUndefined(raw_icon)) { + if (!get_str(ctx, raw_icon, &icon, 256) || !icon_path_ok(&icon)) goto done; + const char *const asset_keys[] = {icon.s}; + if (!read_obj(st, ctx, f[2], asset_keys, 1, 1u, asset) || + !get_str(ctx, asset[0], &encoded, 87384) || !asset_base64_ok(&encoded)) goto done; + } if (JS_GetClassID(f[1]) != st->cls_object) goto done; JSPropertyEnum *tab; uint32_t count; @@ -1955,6 +1997,7 @@ static int load_package(RunState *st, JSContext *ctx, JSValueConst root, int *wr SourceFile *file = &st->files[st->nfiles++]; JSValue key = JS_AtomToValue(ctx, tab[i].atom), code = JS_UNDEFINED; good = get_str(ctx, key, &file->name, 256) && source_path_ok(&file->name) && + (!icon.s || str_cmp(&icon, &file->name) != 0) && own_data(ctx, f[1], tab[i].atom, &code) && get_str(ctx, code, &file->code, 128u * 1024u); JS_FreeValue(ctx, key); JS_FreeValue(ctx, code); total += file->code.n; @@ -1975,7 +2018,9 @@ static int load_package(RunState *st, JSContext *ctx, JSValueConst root, int *wr ok = 1; done: free(manifest.p); - JS_FreeValue(ctx, f[0]); JS_FreeValue(ctx, f[1]); + str_free(&icon); str_free(&encoded); + JS_FreeValue(ctx, raw_icon); JS_FreeValue(ctx, asset[0]); + JS_FreeValue(ctx, f[0]); JS_FreeValue(ctx, f[1]); JS_FreeValue(ctx, f[2]); return ok; } diff --git a/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginIconFixtures.swift b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginIconFixtures.swift new file mode 100644 index 0000000..52ccda6 --- /dev/null +++ b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginIconFixtures.swift @@ -0,0 +1,96 @@ +// Shared byte vectors from the SDK icon contract fixture; entropy is intentionally opaque. +let pluginIconVectorJSON = #""" +[ + { + "name": "png-1x1", + "format": "png", + "path": "icon.png", + "base64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==", + "expectedValid": true, + "width": 1, + "height": 1 + }, + { + "name": "png-1024x1024", + "format": "png", + "path": "icon.png", + "base64": "iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAYAAAB/HSuDAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==", + "expectedValid": true, + "width": 1024, + "height": 1024 + }, + { + "name": "webp-1x1", + "format": "webp", + "path": "icon.webp", + "base64": "UklGRhIAAABXRUJQVlA4TAUAAAAvAAAAAAA=", + "expectedValid": true, + "width": 1, + "height": 1 + }, + { + "name": "webp-1024x1024", + "format": "webp", + "path": "icon.webp", + "base64": "UklGRhIAAABXRUJQVlA4TAUAAAAv/8P/AAA=", + "expectedValid": true, + "width": 1024, + "height": 1024 + }, + { + "name": "png-width-1025", + "format": "png", + "path": "icon.png", + "base64": "iVBORw0KGgoAAAANSUhEUgAABAEAAAABCAYAAACvzLcLAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==", + "expectedValid": false, + "width": 1025, + "height": 1 + }, + { + "name": "png-bad-crc", + "format": "png", + "path": "icon.png", + "base64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAeFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==", + "expectedValid": false, + "width": 1, + "height": 1 + }, + { + "name": "png-truncated", + "format": "png", + "path": "icon.png", + "base64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5E", + "expectedValid": false, + "width": 1, + "height": 1 + }, + { + "name": "webp-height-1025", + "format": "webp", + "path": "icon.webp", + "base64": "UklGRhIAAABXRUJQVlA4TAUAAAAvAAAAAQA=", + "expectedValid": false, + "width": 1, + "height": 1025 + }, + { + "name": "webp-animated", + "format": "webp", + "path": "icon.webp", + "base64": "UklGRiQAAABXRUJQVlA4WAoAAAACAAAAAAAAAAAAVlA4TAUAAAAvAAAAAAA=", + "expectedValid": false, + "width": 1, + "height": 1 + }, + { + "name": "webp-wrong-magic", + "format": "webp", + "path": "icon.webp", + "base64": "UklGWBIAAABXRUJQVlA4TAUAAAAvAAAAAAA=", + "expectedValid": false, + "width": 1, + "height": 1 + } +] + +"""# diff --git a/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginIconTests.swift b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginIconTests.swift new file mode 100644 index 0000000..1d5950a --- /dev/null +++ b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginIconTests.swift @@ -0,0 +1,215 @@ +import Foundation +import XCTest +@testable import AutomationCore + +final class PluginIconTests: XCTestCase { + func testSharedSDKVectorsAndPublicValidatedMetadata() throws { + struct Vector: Decodable { + let name: String, path: String, base64: String + let expectedValid: Bool + let width: Int, height: Int + } + for vector in try JSONDecoder().decode([Vector].self, from: Data(pluginIconVectorJSON.utf8)) { + let bytes = try XCTUnwrap(Data(base64Encoded: vector.base64)) + if vector.expectedValid { + let icon = try PluginIcon.validate(data: bytes, path: vector.path) + XCTAssertEqual(icon.data, bytes, vector.name) + XCTAssertEqual(icon.path, vector.path, vector.name) + XCTAssertEqual(icon.width, vector.width, vector.name) + XCTAssertEqual(icon.height, vector.height, vector.name) + XCTAssertEqual(try PluginPackage.validate(package(path: vector.path, bytes: bytes)).icon, icon) + } else { + XCTAssertThrowsError(try PluginIcon.validate(data: bytes, path: vector.path), vector.name) + } + } + } + + func testStaticPNGAndWebPVariantsAreAccepted() throws { + for (path, bytes) in [("art/icon.png", png()), ("icon.webp", webp([("VP8L", lossless())])), + ("icon.webp", webp([("VP8 ", lossy())])), + ("icon.webp", webp([("VP8X", extended()), ("VP8L", lossless())]))] { + let input = try package(path: path, bytes: bytes) + XCTAssertEqual(try PluginPackage.validate(input).bytes, input) + } + } + + func testIconAssetsMustBeAnExactPair() throws { + let encoded = png().base64EncodedString() + let variants: [(String?, JSONValue?)] = [ + ("icon.png", nil), (nil, .object([:])), (nil, .object(["icon.png": .string(encoded)])), + ("icon.png", .object([:])), ("icon.png", .object(["other.png": .string(encoded)])), + ("icon.png", .object(["icon.png": .string(encoded), "extra.png": .string(encoded)])), + ("icon.png", .null), ("icon.png", .object(["icon.png": .integer(1)])) + ] + for (path, assets) in variants { + XCTAssertThrowsError(try PluginPackage.validate(package(path: path, assets: assets))) + } + } + + func testSchemaOneRejectsIconAndAssets() throws { + let legacy = try StrictJSON.parse(packageBytes()) + var object = try XCTUnwrap(legacy.objectValue) + object["assets"] = .object(["icon.png": .string(png().base64EncodedString())]) + XCTAssertThrowsError(try PluginPackage.validate(JSONValue.object(object).data())) + var manifest = try XCTUnwrap(object["manifest"]?.objectValue) + manifest["icon"] = .string("icon.png") + object["manifest"] = .object(manifest) + object.removeValue(forKey: "assets") + XCTAssertThrowsError(try PluginPackage.validate(JSONValue.object(object).data())) + } + + func testIconPathsAndSourceCollisionAreRejected() throws { + for path in ["", "/icon.png", "../icon.png", "a//icon.png", "a/./icon.png", "a\\icon.png", + "https://example.com/a.png", "é.png", "icon.PNG", "icon.jpg", String(repeating: "a", count: 253) + ".png"] { + XCTAssertThrowsError(try PluginPackage.validate(package(path: path, bytes: png())), path) + } + XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.png", bytes: png(), sourcePath: "icon.png"))) + XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.webp", bytes: png()))) + XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.png", bytes: webp([("VP8L", lossless())])))) + } + + func testBase64MustBeCanonical() throws { + let encoded = png().base64EncodedString() + for value in [encoded + "\n", " " + encoded, "!!!!", "", "AB=="] { + XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.png", assets: .object(["icon.png": .string(value)])))) + } + } + + func testRawBytesAndDimensionsAreBounded() throws { + XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.png", bytes: Data()))) + XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.png", bytes: png(extra: [("tEXt", Data(repeating: 0, count: 65_536))])))) + for (w, h) in [(0, 1), (1, 0), (1025, 1), (1, 1025)] { + XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.png", bytes: png(width: w, height: h)))) + } + _ = try PluginPackage.validate(package(path: "icon.png", bytes: png(width: 1024, height: 1024))) + XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.webp", bytes: webp([("VP8L", lossless(width: 1025))])))) + } + + func testMalformedAndAnimatedPNGIsRejected() throws { + let header = ihdr() + var badCRC = png(); badCRC[badCRC.count - 1] ^= 1 + let variants = [Data(png().dropLast()), png() + Data([0]), badCRC, + pngChunks([("IHDR", header), ("IEND", Data())]), + pngChunks([("IDAT", Data([1])), ("IHDR", header), ("IEND", Data())]), + pngChunks([("IHDR", header), ("IHDR", header), ("IDAT", Data([1])), ("IEND", Data())]), + png(extra: [("acTL", Data(repeating: 0, count: 8))]), + png(extra: [("fcTL", Data())]), png(extra: [("fdAT", Data())]), + png(extra: [("ABCD", Data())]), + pngChunks([("IHDR", header), ("IDAT", Data([1])), ("tEXt", Data()), ("IDAT", Data([2])), ("IEND", Data())])] + for bytes in variants { XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.png", bytes: bytes))) } + } + + func testPNGPaletteRules() throws { + let indexed = ihdr(color: 3, depth: 1) + let tail: [(String, Data)] = [("IDAT", Data([1])), ("IEND", Data())] + _ = try PluginPackage.validate(package(path: "icon.png", bytes: pngChunks([("IHDR", indexed), ("PLTE", Data([1, 2, 3]))] + tail))) + for chunks in [[("IHDR", indexed)] + tail, + [("IHDR", indexed), ("PLTE", Data(repeating: 0, count: 9))] + tail, + [("IHDR", ihdr(color: 0)), ("PLTE", Data([1, 2, 3]))] + tail, + [("IHDR", indexed), ("PLTE", Data([1, 2, 3])), ("PLTE", Data([1, 2, 3]))] + tail] { + XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.png", bytes: pngChunks(chunks)))) + } + } + + func testMalformedAndAnimatedWebPIsRejected() throws { + let image = ("VP8L", lossless()) + var wrongLength = webp([image]); wrongLength[4] ^= 2 + var badPadding = webp([image]); badPadding[badPadding.count - 1] = 1 + for bytes in [wrongLength, badPadding, Data(webp([image]).dropLast()), webp([image]) + Data([0]), + webp([]), webp([image, image]), webp([("ANIM", Data()), image]), + webp([("VP8X", extended(flags: 2)), image]), webp([("VP8X", extended(width: 2)), image]), + webp([image, ("VP8X", extended())]), webp([("VP8L", Data([0x2f]))])] { + XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.webp", bytes: bytes))) + } + } + + func testWebPExtendedMetadataFlagsAndOrdering() throws { + _ = try PluginPackage.validate(package(path: "icon.webp", bytes: webp([ + ("VP8X", extended(flags: 0x2c)), ("ICCP", Data([1])), ("VP8L", lossless()), + ("EXIF", Data([1])), ("XMP ", Data([1]))]))) + for chunks in [[("VP8X", extended(flags: 0x20)), ("VP8L", lossless())], + [("VP8X", extended()), ("ICCP", Data([1])), ("VP8L", lossless())], + [("VP8X", extended(flags: 8)), ("EXIF", Data([1])), ("VP8L", lossless())], + [("VP8X", extended(flags: 0x10)), ("ALPH", Data([0])), ("VP8L", lossless())]] { + XCTAssertThrowsError(try PluginPackage.validate(package(path: "icon.webp", bytes: webp(chunks)))) + } + } + + func testSourceEditsRetainBundledIconAndChangeRevision() throws { + let original = try PluginPackage.validate(package(path: "icon.png", bytes: png())) + let edited = try original.replacingSource("// changed", file: "main.js") + let originalObject = try XCTUnwrap(StrictJSON.parse(original.bytes).objectValue) + let editedObject = try XCTUnwrap(StrictJSON.parse(edited.bytes).objectValue) + XCTAssertEqual(originalObject["assets"], editedObject["assets"]) + XCTAssertEqual(original.manifest.json, edited.manifest.json) + XCTAssertEqual(edited.sourceFiles["main.js"], "// changed") + XCTAssertNotEqual(original.revision, edited.revision) + } + + func testLegacyPackagesRemainByteIdenticalAndOmitAssets() throws { + for bytes in [packageBytes(), try package(path: nil, assets: nil)] { + let validated = try PluginPackage.validate(bytes) + XCTAssertEqual(validated.bytes, bytes) + XCTAssertNil(try StrictJSON.parse(bytes).objectValue?["assets"]) + } + } + + private func package(path: String?, bytes: Data, sourcePath: String = "main.js") throws -> Data { + try package(path: path, assets: .object([path ?? "icon.png": .string(bytes.base64EncodedString())]), sourcePath: sourcePath) + } + + private func package(path: String?, assets: JSONValue?, sourcePath: String = "main.js") throws -> Data { + var manifest: [String: JSONValue] = [ + "schemaVersion": .integer(2), "id": .string(pluginID.uuidString), "name": .string("Icon test"), "version": .string("1.0.0"), + "matches": .array([.object(["hosts": .array([.string("example.com")]), "methods": .array([.string("GET")]), + "path": .object(["kind": .string("exact"), "value": .string("/")]), + "hooks": .object(["request": .object(["onLeave": .string(sourcePath)])])])]), + "read": .object(["metadata": .array([]), "headers": .array([]), "queryKeys": .array([]), "body": .object(["mode": .string("none")])]), + "write": .object(["requestBody": .bool(false), "responseBody": .bool(false)]), "endpointBindings": .array([]), "settings": .object([:]) + ] + if let path { manifest["icon"] = .string(path) } + var object: [String: JSONValue] = ["manifest": .object(manifest), "sourceFiles": .object([sourcePath: .string("// source")])] + if let assets { object["assets"] = assets } + return try JSONValue.object(object).data() + } + + private func be(_ value: Int) -> Data { Data((0..<4).reversed().map { UInt8(truncatingIfNeeded: value >> ($0 * 8)) }) } + private func le(_ value: Int) -> Data { Data((0..<4).map { UInt8(truncatingIfNeeded: value >> ($0 * 8)) }) } + private func crc(_ data: Data) -> UInt32 { + var value = UInt32.max + for byte in data { + value ^= UInt32(byte) + for _ in 0..<8 { value = (value >> 1) ^ (value & 1 == 0 ? 0 : 0xedb88320) } + } + return value ^ UInt32.max + } + private func ihdr(width: Int = 1, height: Int = 1, color: UInt8 = 6, depth: UInt8 = 8) -> Data { + be(width) + be(height) + Data([depth, color, 0, 0, 0]) + } + private func png(width: Int = 1, height: Int = 1, extra: [(String, Data)] = []) -> Data { + pngChunks([("IHDR", ihdr(width: width, height: height))] + extra + [("IDAT", Data([1])), ("IEND", Data())]) + } + private func pngChunks(_ chunks: [(String, Data)]) -> Data { + var data = Data([137, 80, 78, 71, 13, 10, 26, 10]) + for (name, payload) in chunks { + let body = Data(name.utf8) + payload + data += be(payload.count) + body + be(Int(crc(body))) + } + return data + } + private func lossless(width: Int = 1, height: Int = 1) -> Data { + Data([0x2f]) + le((width - 1) | ((height - 1) << 14)) + } + private func lossy() -> Data { Data([0x10, 0, 0, 0x9d, 1, 0x2a, 1, 0, 1, 0]) } + private func extended(flags: UInt8 = 0, width: Int = 1) -> Data { + Data([flags, 0, 0, 0, UInt8(width - 1), 0, 0, 0, 0, 0]) + } + private func webp(_ chunks: [(String, Data)]) -> Data { + var data = Data("WEBP".utf8) + for (name, payload) in chunks { + data += Data(name.utf8) + le(payload.count) + payload + if payload.count % 2 == 1 { data.append(0) } + } + return Data("RIFF".utf8) + le(data.count) + data + } +} diff --git a/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/PluginIconRuntimeTests.swift b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/PluginIconRuntimeTests.swift new file mode 100644 index 0000000..c54d18c --- /dev/null +++ b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/PluginIconRuntimeTests.swift @@ -0,0 +1,134 @@ +import AutomationCore +@testable import AutomationRuntime +import Foundation +import XCTest + +/// The VM independently admits package metadata before evaluating code. Decorative assets must not +/// disable any lifecycle hook or fetch/createFile, and must never enter the source-file map. +final class PluginIconRuntimeTests: XCTestCase, @unchecked Sendable { + private let sourcePath = "hooks/api.example.com/search/POST.js" + private let iconBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==" + private let event = Data(#"{"request":{"method":"POST","host":"api.example.com","path":"/search","headers":{},"query":{},"body":{"limit":50,"query":"x"}},"response":{"status":200,"headers":{},"body":{"ok":true}}}"#.utf8) + private let config = Data(#"{"endpoints":{"preview":"5E1D0C4A-0000-4000-8000-00000000A001"}}"#.utf8) + + func testSDKIconPackageExecutesAllFourHooksWithoutChangingBehavior() async throws { + let baseline = Data(sdkIconRuntimeBaseline.utf8) + let decorated = try package() + _ = try PluginPackage.validate(decorated) + for hook in [JavaScriptHook.requestEnter, .requestLeave, .responseEnter, .responseLeave] { + let expected = try await run(baseline, hook: hook) + let actual = try await run(decorated, hook: hook) + XCTAssertEqual(try JSONValue(parsing: actual), try JSONValue(parsing: expected), hook.rawValue) + if hook == .requestEnter { + let result = try XCTUnwrap(JSONSerialization.jsonObject(with: actual) as? [String: Any]) + let mutation = try XCTUnwrap(result["mutation"] as? [String: Any]) + XCTAssertEqual((mutation["body"] as? [String: Any])?["limit"] as? Int, 5) + } + } + } + + func testIconPackageCanFetchAndCreateFileFromResponseLeave() async throws { + let bytes = Data("{\"results\":[1]}".utf8) + let recorder = Recorder() + let source = """ + Interceptor.attach({response:{async onLeave(){ + const response = await fetch('https://api.example.com/history', {method:'POST', body:'{}'}); + await Interceptor.createFile({storage:Interceptor.Storage.iCloudDrive, + atPath:'Salmon Run/history.json',contents:await response.text()}); + }}}); + """ + let input = try package { object, manifest in + manifest["write"] = ["requestBody": false, "responseBody": false, "files": true] + var routes = manifest["matches"] as! [[String: Any]] + routes[0]["hooks"] = ["response": ["onLeave": self.sourcePath]] + manifest["matches"] = routes + object["sourceFiles"] = [self.sourcePath: source] + } + _ = try PluginPackage.validate(input) + let result = try await JavaScriptFetchExecutor().runV2( + packageJSON: input, hook: .responseLeave, eventJSON: event, configJSON: config, + createFile: { destination, contents in await recorder.write(destination, contents) }, + transport: { request in + await recorder.fetch(request) + return JavaScriptFetchResponse(status: 200, body: bytes) + }) + XCTAssertEqual(try JSONValue(parsing: result), .object(["actions": .array([])])) + let state = await recorder.snapshot() + XCTAssertEqual(state.requests.count, 1) + XCTAssertEqual(state.requests.first?.url, "https://api.example.com/history") + XCTAssertEqual(state.requests.first?.method, "POST") + XCTAssertEqual(state.files.count, 1) + XCTAssertEqual(state.files.first?.0.storage, .icloud) + XCTAssertEqual(state.files.first?.0.atPath, "Salmon Run/history.json") + XCTAssertEqual(state.files.first?.1, bytes) + } + + func testMalformedAssetPairsAreRejectedBeforeBothRuntimeEntryPoints() async throws { + let edits: [(inout [String: Any], inout [String: Any]) -> Void] = [ + { object, _ in object.removeValue(forKey: "assets") }, + { _, manifest in manifest.removeValue(forKey: "icon") }, + { object, _ in object["assets"] = [:] as [String: String] }, + { object, _ in object["assets"] = NSNull() }, + { object, _ in object["assets"] = ["other.png": self.iconBase64] }, + { object, _ in object["assets"] = ["icon.png": self.iconBase64, "extra.png": self.iconBase64] }, + { object, _ in object["assets"] = ["icon.png": 1] }, + { _, manifest in manifest["icon"] = NSNull() }, + { object, manifest in manifest["icon"] = "../icon.png"; object["assets"] = ["../icon.png": self.iconBase64] }, + { object, manifest in manifest["icon"] = "icon.PNG"; object["assets"] = ["icon.PNG": self.iconBase64] }, + { object, _ in object["assets"] = ["icon.png": "AB=="] }, + { object, _ in object["assets"] = ["icon.png": "AA"] }, + { object, _ in object["assets"] = ["icon.png": self.iconBase64 + "\n"] }, + { object, _ in object["assets"] = ["icon.png": ""] }, + { object, _ in object["assets"] = ["icon.png": Data(repeating: 0, count: 65_537).base64EncodedString()] }, + { object, manifest in + let files = object["sourceFiles"] as! [String: String] + object["sourceFiles"] = ["icon.png": files[self.sourcePath]!] + var routes = manifest["matches"] as! [[String: Any]] + routes[0]["hooks"] = ["request": ["onEnter": "icon.png"]] + manifest["matches"] = routes + } + ] + for (index, edit) in edits.enumerated() { + let input = try package(edit) + do { _ = try await run(input); XCTFail("sync accepted malformed asset case \(index)") } + catch { XCTAssertEqual(error as? JavaScriptExecutionError, .invalidInput, "sync case \(index)") } + do { + _ = try await JavaScriptFetchExecutor().runV2( + packageJSON: input, hook: .responseLeave, eventJSON: event, configJSON: config, + createFile: { _, _ in XCTFail("invalid package reached file callback") }, + transport: { _ in + XCTFail("invalid package reached transport") + return JavaScriptFetchResponse(status: 200, body: Data()) + }) + XCTFail("fetch accepted malformed asset case \(index)") + } catch { XCTAssertEqual(error as? JavaScriptExecutionError, .invalidInput, "fetch case \(index)") } + } + } + + private func package(_ edit: ((inout [String: Any], inout [String: Any]) -> Void)? = nil) throws -> Data { + var object = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(sdkIconRuntimeBaseline.utf8)) as? [String: Any]) + var manifest = object["manifest"] as! [String: Any] + manifest["icon"] = "icon.png" + object["assets"] = ["icon.png": iconBase64] + edit?(&object, &manifest) + object["manifest"] = manifest + return try JSONSerialization.data(withJSONObject: object, options: .sortedKeys) + } + + private func run(_ input: Data, hook: JavaScriptHook = .requestEnter) async throws -> Data { + try await JavaScriptExecutor().runV2(packageJSON: input, hook: hook, eventJSON: event, configJSON: config) + } + + private actor Recorder { + var requests: [JavaScriptFetchRequest] = [] + var files: [(PluginFileDestination, Data)] = [] + func fetch(_ request: JavaScriptFetchRequest) { requests.append(request) } + func write(_ destination: PluginFileDestination, _ contents: Data) { files.append((destination, contents)) } + func snapshot() -> (requests: [JavaScriptFetchRequest], files: [(PluginFileDestination, Data)]) { (requests, files) } + } +} + +// Exact SDK baseline package from the icon/runtime integration repro, kept self-contained for CI. +private let sdkIconRuntimeBaseline = #""" +{"manifest":{"endpointBindings":["preview"],"id":"76532D8C-608A-4EA3-AC16-755BABF2AB7E","matches":[{"hooks":{"request":{"onEnter":"hooks/api.example.com/search/POST.js","onLeave":"hooks/api.example.com/search/POST.js"},"response":{"onEnter":"hooks/api.example.com/search/POST.js","onLeave":"hooks/api.example.com/search/POST.js"}},"hosts":["api.example.com"],"methods":["POST"],"path":{"kind":"exact","value":"/search"}}],"name":"Request summary","read":{"body":{"mode":"json"},"headers":[],"metadata":["method","host","path","status"],"queryKeys":[]},"schemaVersion":2,"settings":{},"version":"2.0.0","write":{"requestBody":true,"responseBody":true}},"sourceFiles":{"hooks/api.example.com/search/POST.js":"\"use strict\";\nInterceptor.attach({\n request: {\n onEnter(req, cfg) {\n if (!req.body || typeof req.body !== 'object' || Array.isArray(req.body))\n return;\n req.body.limit = 5;\n },\n onLeave(req, cfg) {\n const endpointId = cfg.endpoints?.preview;\n if (!endpointId)\n return;\n return { actions: [{ type: 'webhook', endpointId,\n json: { summary: req.method + ' ' + req.host + req.path } }] };\n }\n },\n response: {\n onEnter(res, cfg) {\n if (!res.body || typeof res.body !== 'object' || Array.isArray(res.body))\n return;\n res.body.maintenance = true;\n },\n onLeave(res, cfg) {\n const endpointId = cfg.endpoints?.preview;\n if (!endpointId)\n return;\n return { actions: [{ type: 'webhook', endpointId,\n json: { path: res.request.path, status: res.status } }] };\n }\n }\n});\n"}} +"""# diff --git a/docs/superpowers/plans/2026-10-24-plugin-icons.md b/docs/superpowers/plans/2026-10-24-plugin-icons.md new file mode 100644 index 0000000..8e13767 --- /dev/null +++ b/docs/superpowers/plans/2026-10-24-plugin-icons.md @@ -0,0 +1,39 @@ +# Bundled Plugin Icons and Sources Editing Implementation Plan + +> **For agentic workers:** Use superpowers:executing-plans for assigned tasks. Keep file ownership separate. + +**Goal:** Package PNG/WebP icons with Plugins and reveal Sources + only after Edit. + +**Architecture:** Schema 2 may declare `icon: "icon.webp"`. The portable package adds exactly one matching `assets` member encoded as canonical base64. Native reads validated local content asynchronously, reuses a bounded SHA-keyed decode cache and keeps existing tile geometry. Sources owns one EditMode binding. + +**Tech Stack:** Swift/Foundation/SwiftUI/UIKit/ImageIO, SwiftData, Python/Bun SDK. + +**Spec:** User selected bundled PNG/WebP images and Edit-before-+. Canonical visual rules live in `interceptor-live-scripts-20261018/Interceptor/docs/mock-diff/SPEC.md` (updated before native edits). + +## Constraints and decisions + +- Optional schema 2 only; v1 unchanged. No icon => no assets field; legacy generated bytes unchanged. +- Icon paths use existing ASCII relative path grammar, <=256 bytes, `.png` or `.webp` lowercase; no source-path collision. +- Exactly one asset matching manifest.icon; base64 decode/re-encode identical. Raw bytes 1...65,536; dimensions 1...1,024 each. Reject animated PNG/WebP and malformed chunk structure. Core validates bounded structure; platform decoder failure safely falls back. +- Preserve 262,144-byte whole-package and 32,768-byte canonical-manifest budgets. Signature/index shape unchanged; icon bytes covered by existing package SHA. +- SDK image file must be regular and every path component must be a real directory (no symlinks/traversal). No remote icon URL, extra asset API, new settings, or image editor. +- Preserve assets across routed source edits. Queue and installed packages use their own validated icon; remote catalog uses accepted cached SHA, never a network request for display. +- Cache decoded thumbnails, max64 image entries / 8MiB decoded cost, plus at most1,600 negative results for the bounded repository catalog; decode and full package reads off MainActor; cache failure safely; key changes reset visible old image. +- Existing clients reject icon packages. Do not publish an icon-bearing production package to existing sources until compatible native release. SDK support and isolated fixtures only in this task. + +## Review focus + +Source edit retention, strict Swift/Python parity, legacy byte preservation, catalog refresh SHA/fallback, bounded decode/cache, edit state after sheet/cancel/navigation. + +## Tasks + +- [ ] Core: tests for valid PNG/WebP, pair/keys/path/base64/size/dimensions/static structure, legacy and source edit retention; run red then implement Manifest/PluginPackage/PluginIcon and run affected Core tests. +- [ ] SDK: strict authored/generated/repository validation, local asset loading and deterministic bundling across load_samples/build/publish/setup. Add portable positive/negative fixtures and byte preservation tests; run red then green, `bun run build` and relevant tools gates. Do not repin to an unpublished native commit. +- [ ] Sources: reuse ServerListView EditMode ownership, stable Edit/Done with conditional + before it; inactive sheet environment, reset on exit; update existing Add test helper and visibility regression. +- [ ] Native icons: background SwiftData accepted-content read + validated SHA-keyed icon request, common bounded ImageIO thumbnail cache; pass local/queue/hero/catalog requests through current shared tile. Verify no network/row parsing and selected installed image precedence. +- [ ] Verification: affected Core tests, native build, affected app-host/catalog/cache tests and Sources UI transition; compare affected capture with Mock Diff, record actual baseline limitations. Use private lossless WebP captures and owned Simulator cleanup. +- [ ] Independent actual-files Claude review (use verified accessible immutable review snapshot if managed path unavailable), fix material findings and revalidate. Preserve old file API review snapshots and existing work. + +## Independent preimplementation reviews + +LocalGPT Thinking `a892fbdb-ede7-42e0-ae34-0c6294af0c86` and Claude Sonnet `job_a11b875ed03cbc0e49599acf671c2bda` → `job_c2f5f41bf101dad8e5449e3348102cb4` completed against native9242212 / SDKe4d5918. Their material issues are covered by the constraints/tasks above. Managed native worktree is outside Claude's mount; exact access probe was denied, so native editing remains with Codex workers and Mac verification.