SPB Git

Repository Public License

ScriptTests.swift 32.3 KB 488 lines swift

1import Foundation2import NavigatorCore3import TestSupport4import Testing5import WebKit6@testable import WebRuntime78extension WebRuntimeTests {9    @Suite struct Scripts {10        @Test func worldsAreIsolatedFromThePageAndFromEachOther() async throws {11            try await withHarness { harness in12                let engine = harness.makeEngine()13                try await harness.load(engine, "/adversarial", expectingTitle: "adversarial-done")1415                // The page defined window.__probe in its own world; isolated worlds do not see it…16                #expect(await engine.string("return typeof window.__probe;", in: .agent) == "undefined")17                // …but they share the DOM.18                #expect(await engine.string("return document.title;", in: .agent) == "adversarial-done")1920                // A global set in one isolated world exists in that world only.21                try await engine.evaluate("window.__secret = 'agent-only'; return true;", in: .agent)22                #expect(await engine.string("return window.__secret || 'none';", in: .agent) == "agent-only")23                #expect(await engine.string("return window.__secret || 'none';", in: .reader) == "none")24                #expect(await engine.string("return window.__secret || 'none';", in: .bridge) == "none")2526                // The bridge handler exists in the browser's worlds and nowhere else.27                let probe = "return String(!!(window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.orixBridge));"28                #expect(await engine.string(probe, in: .bridge) == "true")29                #expect(await engine.string(probe, in: .lens) == "true")30                #expect(await engine.string(probe, in: .agent) == "false")31                #expect(await engine.string(probe, in: .userScripts) == "false")3233                // Arguments and results are typed values.34                let result = try await engine.evaluate("return { sum: a + b, list: [name, true, null] };",35                                                       arguments: ["a": 2, "b": 3.5, "name": "x"])36                let expected = ScriptValue.object(["sum": .number(5.5), "list": .array([.string("x"), .bool(true), .null])])37                #expect(result == expected)38                await #expect(throws: WebEngineError.self) { try await engine.evaluate("throw new Error('boom');") }39            }40        }4142        @Test func adversarialPageCannotReachPrivilegedHandlersOrInternalPages() async throws {43            try await withHarness { harness in44                let engine = harness.makeEngine()45                try await harness.load(engine, "/adversarial", expectingTitle: "adversarial-done")46                let json = await engine.string("return document.getElementById('probe').textContent;")47                let probe = try #require(try JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: [String: Any]])4849                // No message handler of the browser is visible from page JavaScript.50                let handlers = try #require(probe["handlers"] as? [String: Bool])51                #expect(handlers.count == 8 && handlers.values.allSatisfy { !$0 }, "\(handlers)")52                #expect((probe["posts"] as? [String: Int])?.values.allSatisfy { $0 == 0 } == true)5354                // orix:// and file:// cannot be framed, fetched or used as an image by a web page.55                let frames = try #require(probe["frames"] as? [String: String])56                #expect(frames["orix"] != "loaded-readable" && frames["file"] != "loaded-readable", "\(frames)")57                let fetches = try #require(probe["fetches"] as? [String: String])58                #expect(fetches["orix"]?.hasPrefix("ok") == false && fetches["file"]?.hasPrefix("ok") == false, "\(fetches)")59                #expect((probe["images"] as? [String: String])?["orix"] != "loaded")6061                // Nothing forged reached the engine; the page's real metadata did.62                try await waitUntil("genuine metadata") { engine.metadata != nil }63                #expect(engine.metadata?.title != "FORGED")64                #expect(engine.rejectedBridgeMessageCount == 0)65                #expect(engine.lastUserActivation == nil)66                #expect(engine.contextElement == nil)67                #expect(!engine.isPlayingAudio)68                // The framed orix:// navigation was refused by the policy.69                #expect(engine.blockedNavigations.contains { $0.reason == .internalPageFromWeb && !$0.isMainFrame })70            }71        }7273        @Test func consoleMirrorHandlerAcceptsOnlyConsoleText() async throws {74            try await withHarness { harness in75                var settings = WebEngineSettings()76                settings.mirrorsConsole = true77                let engine = harness.makeEngine(settings: settings)78                try await harness.load(engine, "/adversarial", expectingTitle: "adversarial-done")79                let json = await engine.string("return document.getElementById('probe').textContent;")80                let probe = try #require(try JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: [String: Any]])81                let handlers = try #require(probe["handlers"] as? [String: Bool])82                // With the mirror on, the page can see exactly one handler: the write-only console one.83                #expect(handlers.filter(\.value).map(\.key) == ["orixConsole"])84                #expect((probe["posts"] as? [String: Int])?["orixConsole"] == 8)8586                // All eight forged messages were refused: none is a console entry, none changed any state.87                try await waitUntil("forged messages rejected") { engine.rejectedBridgeMessageCount == 8 }88                #expect(engine.consoleEntries.allSatisfy { $0.source != .console || !$0.message.contains("FORGED") })89                #expect(engine.metadata?.title != "FORGED")90                #expect(engine.lastUserActivation == nil && engine.contextElement == nil && !engine.isPlayingAudio)91            }92        }9394        @Test func consoleAndErrorCapture() async throws {95            try await withHarness { harness in96                let engine = harness.makeEngine()97                try await harness.load(engine, "/console", expectingTitle: "Console Fixture")98                try await engine.evaluate("document.getElementById('emit').click();")99                // Without the mirror: errors only, captured from the isolated dev world.100                try await waitUntil("errors captured") { engine.consoleEntries.count >= 2 }101                await settle(milliseconds: 150)102                #expect(Set(engine.consoleEntries.map(\.source)) == [.exception, .rejection])103                #expect(engine.consoleEntries.allSatisfy { $0.isFromIsolatedWorld })104                #expect(engine.consoleEntries.contains { $0.source == .exception && $0.message.contains("uncaught-fixture-error") && $0.line > 0 })105                #expect(engine.consoleEntries.contains { $0.source == .rejection && $0.message.contains("rejected-fixture-promise") })106107                // With the mirror: console.* lines too, flagged as coming from the page world.108                engine.setConsoleMirroring(true)109                try await harness.load(engine, "/console", expectingTitle: "Console Fixture")110                #expect(engine.consoleEntries.isEmpty, "the log is per page")111                try await engine.evaluate("document.getElementById('emit').click();")112                try await waitUntil("console mirrored") { engine.consoleEntries.filter { $0.source == .console }.count == 3 }113                let mirrored = engine.consoleEntries.filter { $0.source == .console }114                #expect(mirrored.map(\.level) == [.log, .warning, .error])115                #expect(mirrored.first?.message == "log-line 42 {\"a\":1}")116                #expect(mirrored.allSatisfy { !$0.isFromIsolatedWorld })117118                engine.setConsoleMirroring(false)119                try await harness.load(engine, "/console", expectingTitle: "Console Fixture")120                try await engine.evaluate("document.getElementById('emit').click();")121                try await waitUntil("errors again") { engine.consoleEntries.count >= 2 }122                await settle(milliseconds: 150)123                #expect(!engine.consoleEntries.contains { $0.source == .console })124            }125        }126127        @Test func pageMetadataFaviconAndThemeColor() async throws {128            try await withHarness { harness in129                let engine = harness.makeEngine()130                try await harness.load(engine, "/meta", expectingTitle: "Meta Fixture")131                try await waitUntil("metadata reported") { engine.metadata != nil }132                let metadata = try #require(engine.metadata)133                #expect(metadata.url == harness.server.url("/meta"))134                #expect(metadata.title == "Meta Fixture")135                #expect(metadata.description == "A page with metadata.")136                #expect(metadata.language == "fr-CA")137                #expect(metadata.themeColor == "#336699")138                #expect(metadata.canonicalURL == harness.server.url("/meta/canonical"))139                #expect(metadata.icons.map(\.declaredSize) == [32, 180])140                #expect(metadata.openGraph.title == "Open Graph Title")141                #expect(metadata.openGraph.siteName == "Fixture Site" && metadata.openGraph.type == "article")142                #expect(metadata.openGraph.imageURL == harness.server.url("/resource/pixel.png"))143                // 32 pt at 2x wants 64 px: the 180 px touch icon is the smallest that is large enough.144                #expect(engine.faviconURL == harness.server.url("/icons/icon-180.png"))145                #expect(metadata.bestIcon(pointSize: 16, scale: 2)?.url == harness.server.url("/icons/icon-32.png"))146                try await waitUntil("theme colour from WebKit") { engine.themeColor?.hexString == "#336699" }147148                // A single-page app changing its head is reported again.149                try await engine.evaluate("document.querySelector('meta[name=description]').setAttribute('content', 'Changed.');")150                try await waitUntil("metadata update") { engine.metadata?.description == "Changed." }151152                // Per page: the next document starts from the default icon.153                try await harness.load(engine, "/", expectingTitle: "Fixture Home")154                #expect(engine.faviconURL == harness.server.url("/favicon.ico"))155            }156        }157158        @Test func scrollReporting() async throws {159            try await withHarness { harness in160                let engine = harness.makeEngine()161                try await harness.load(engine, "/tall", expectingTitle: "Tall Fixture")162                try await waitUntil("initial metrics") { engine.scroll.contentHeight >= 6000 }163                #expect(engine.scroll.isAtTop && engine.scroll.progress == 0)164                try await engine.evaluate("window.scrollTo(0, 1200);")165                try await waitUntil("scrolled down") { engine.scroll.y == 1200 }166                #expect(engine.scrollDirection == .down)167                #expect(engine.scroll.progress > 0 && engine.scroll.progress < 1)168                try await engine.evaluate("window.scrollTo(0, 300);")169                try await waitUntil("scrolled up") { engine.scroll.y == 300 }170                #expect(engine.scrollDirection == .up)171            }172        }173174        @Test func readerExtractsTheArticle() async throws {175            try await withHarness { harness in176                let engine = harness.makeEngine()177                try await harness.load(engine, "/article")178                try await waitUntil("article loaded") { engine.title.hasPrefix("The Quiet Return") && !engine.isLoading }179                let article = try await engine.extractReaderArticle()180181                #expect(article.title == "The Quiet Return of the Night Train")182                #expect(article.byline == "Maya Okonkwo")183                #expect(article.language == "en-GB")184                #expect(article.publishedTime == "2026-10-03T07:30:00Z")185                #expect(article.url == harness.server.url("/article"))186                #expect(!article.isTruncated)187188                // The body is there, in order…189                let text = article.textContent190                #expect(text.contains("sleeper carriages were shunted into sidings"))191                #expect(text.contains("Why now"))192                #expect(text.contains("You go to bed in one country"))193                #expect(text.contains("the platforms at midnight are no longer empty"))194                #expect(text.contains("Brussels to Prague, nightly"))195                let first = try #require(text.range(of: "For most of the last thirty years")), last = try #require(text.range(of: "platforms at midnight"))196                #expect(first.lowerBound < last.lowerBound)197                // …and the page furniture is not.198                for junk in ["Subscribe to our newsletter", "Advertisement", "First! Great piece", "Ten best stations", "Sign in",199                             "Fixture Gazette", "Share", "Tweet", "window.inArticleScriptRan"] {200                    #expect(!text.contains(junk), "reader text contains “\(junk)”")201                }202                #expect(article.wordCount > 230 && article.wordCount < 400)203                #expect(article.estimatedReadingMinutes >= 1)204205                // The HTML is inside the safe subset: no script, no handlers, no styles, absolute http(s) URLs only.206                let html = article.contentHTML207                #expect(ReaderHTMLPolicy.firstViolation(in: html) == nil)208                for forbidden in ["<script", "onclick", "style=", "class=", "javascript:", "<div", "<h1"] {209                    #expect(!html.contains(forbidden), "reader HTML contains “\(forbidden)”")210                }211                #expect(html.contains("<h2>Why now</h2>"))212                #expect(html.contains("<blockquote><p>"))213                #expect(html.contains("<a href=\"\(harness.server.url("/page/figures").absoluteString)\">sold out within"))214                #expect(html.contains("<img src=\"\(harness.server.url("/resource/pixel.png").absoluteString)\" alt=\"A sleeper carriage at dusk\">"))215                #expect(html.contains("<figcaption>A restored sleeper carriage waits at the platform.</figcaption>"))216                #expect(html.contains("<li>Stockholm to Hamburg, four times a week</li>"))217                #expect(html.contains("This closing paragraph carries inline handlers"))218                // Extraction ran in its own world and did not disturb the page.219                #expect(await engine.string("return typeof __orixReaderExtract;", in: .agent) == "undefined")220            }221        }222223        @Test func readerRefusesPagesWithoutAnArticle() async throws {224            try await withHarness { harness in225                let engine = harness.makeEngine()226                try await harness.load(engine, "/", expectingTitle: "Fixture Home")227                await #expect(throws: WebEngineError.self) { try await engine.extractReaderArticle() }228                try await harness.load(engine, "/form", expectingTitle: "Form Fixture")229                await #expect(throws: WebEngineError.self) { try await engine.extractReaderArticle() }230            }231        }232233        @Test func installingAndRemovingScriptsKeepsEveryoneElses() async throws {234            try await withHarness { harness in235                let engine = harness.makeEngine()236                let controller = try #require(engine.webView?.configuration.userContentController)237                let builtIn = controller.userScripts.count238                #expect(builtIn >= 6)239240                // A script another module put directly on the controller.241                let foreign = WKUserScript(source: "document.documentElement.setAttribute('data-foreign', '1');",242                                           injectionTime: .atDocumentEnd, forMainFrameOnly: true, in: .world(name: "someone.else"))243                controller.addUserScript(foreign)244                engine.installUserScript(UserScriptDescriptor(id: "feature.a", source: "document.documentElement.setAttribute('data-a', '1');", world: .userScripts))245                engine.installUserScript(UserScriptDescriptor(id: "feature.b", source: "document.documentElement.setAttribute('data-b', '1');", world: .userScripts))246                try engine.installStylesheet(id: "dark", css: "body { color: rgb(1, 2, 3) !important; }", hosts: ["127.0.0.1"])247                #expect(controller.userScripts.count == builtIn + 4)248249                engine.removeUserScript(id: "feature.a")250                #expect(controller.userScripts.count == builtIn + 3)251                #expect(controller.userScripts.contains { $0.source == foreign.source })252                // Replacing a script by id does not duplicate it.253                engine.installUserScript(UserScriptDescriptor(id: "feature.b", source: "document.documentElement.setAttribute('data-b', '2');", world: .userScripts))254                #expect(controller.userScripts.count == builtIn + 3)255                engine.setMuted(true); engine.setMuted(false)256                #expect(controller.userScripts.count == builtIn + 3)257258                try await harness.load(engine, "/", expectingTitle: "Fixture Home")259                let attributes = "var e = document.documentElement; return [e.dataset.foreign, e.dataset.a, e.dataset.b].join(',');"260                #expect(await engine.string(attributes) == "1,,2")261                // Built-in reporters survived all of that.262                try await waitUntil("metadata still reported") { engine.metadata?.title == "Fixture Home" }263264                // Feature scripts follow the tab through suspension.265                await engine.suspend(thumbnailWidth: nil)266                engine.resume()267                try await waitUntil("resumed") { engine.title == "Fixture Home" && !engine.isLoading }268                #expect(await engine.string(attributes) == ",,2", "the foreign script belonged to the old controller; feature scripts are re-installed")269                #expect(Set(engine.installedUserScriptIDs) == ["feature.b", "orix.morph.dark"])270            }271        }272273        @Test func morphStylesheetsArePerHostAndRemovable() async throws {274            try await withHarness { harness in275                let engine = harness.makeEngine()276                let color = "return getComputedStyle(document.body).color;"277                try await harness.load(engine, "/", expectingTitle: "Fixture Home")278                #expect(await engine.string(color) == "rgb(0, 0, 0)")279280                // Applied to the live page at once…281                try engine.installStylesheet(id: "tint", css: "body { color: rgb(10, 20, 30) !important; }", hosts: ["127.0.0.1"])282                try await waitUntilAsync("live apply") { await engine.string(color) == "rgb(10, 20, 30)" }283                #expect(engine.installedStylesheetIDs == ["tint"])284                // …and to later loads of that host, from document start.285                try await harness.load(engine, "/page/a", expectingTitle: "Fixture a")286                #expect(await engine.string(color) == "rgb(10, 20, 30)")287                // Another host is untouched.288                try await harness.load(engine, "/page/a", host: "localhost", expectingTitle: "Fixture a")289                #expect(await engine.string(color) == "rgb(0, 0, 0)")290291                try await harness.load(engine, "/page/a", expectingTitle: "Fixture a")292                engine.removeStylesheet(id: "tint")293                try await waitUntilAsync("live removal") { await engine.string(color) == "rgb(0, 0, 0)" }294                try await harness.load(engine, "/page/b", expectingTitle: "Fixture b")295                #expect(await engine.string(color) == "rgb(0, 0, 0)")296                #expect(engine.installedStylesheetIDs.isEmpty)297            }298        }299300        @Test func morphRejectsAnythingThatIsNotPlainCSS() {301            #expect(throws: Never.self) { try MorphStylesheet.validate("a { color: red; background: url(data:image/png;base64,AAAA); filter: url(#f); }") }302            for hostile in [303                "@import url(https://tracker.invalid/a.css);",304                "@imp\\6frt 'https://tracker.invalid/a.css';",305                "@im/**/port 'x.css';",306                "a { background: url(https://tracker.invalid/pixel.gif); }",307                "a { background: url( 'http://tracker.invalid/p' ); }",308                "a { background: URL(//tracker.invalid/p); }",309                "</style><script>alert(1)</script>",310                "a { width: expression(alert(1)); }",311                "a { background: url(javascript:alert(1)); }",312                "a { background-image: image-set('https://tracker.invalid/a.png' 1x); }",313            ] {314                #expect(throws: WebEngineError.self, "accepted: \(hostile)") { try MorphStylesheet.validate(hostile) }315            }316        }317318        @Test func lensSelectionAndElementDescription() async throws {319            try await withHarness { harness in320                let engine = harness.makeEngine()321                try await harness.load(engine, "/find", expectingTitle: "Find Fixture")322                let initial = try await engine.currentSelection()323                #expect(initial == nil)324                // (A partial range on purpose: see "Selections and web view lifetime" in WEBKIT_LIMITATIONS.md.)325                try await engine.evaluate("""326                var range = document.createRange(), node = document.querySelectorAll('p')[1].firstChild;327                range.setStart(node, 0); range.setEnd(node, 12);328                var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);329                """)330                try await waitUntil("selection reported") { engine.selection?.text == "Nothing else" }331                #expect(engine.selection?.url == harness.server.url("/find"))332                #expect((engine.selection?.rect.width ?? 0) > 0)333                let onDemand = try await engine.currentSelection()334                #expect(onDemand?.text == "Nothing else")335                try await engine.evaluate("window.getSelection().removeAllRanges();")336                try await waitUntil("selection cleared") { engine.selection == nil }337338                // Picking mode toggles; the pick itself needs a trusted click (not producible from a test).339                try await engine.startElementPicking()340                #expect(engine.isPickingElement)341                #expect(await engine.string("return String(window.__orixLens.isPicking());", in: .lens) == "true")342                #expect(await engine.string("return String(!!document.querySelector('[data-orix-lens]'));") == "true")343                try await engine.evaluate("document.querySelector('p').click();")344                await settle(milliseconds: 100)345                #expect(engine.isPickingElement && engine.lastPickedElement == nil, "untrusted clicks do not pick")346                await engine.stopElementPicking()347                #expect(!engine.isPickingElement)348                #expect(await engine.string("return String(!!document.querySelector('[data-orix-lens]'));") == "false")349350                // The description the pick would send, validated through the same path.351                let described = try await engine.evaluate("return window.__orixLens.describe('p');", in: .lens)352                let payload = try #require(described.objectValue)353                let element = try #require(try BridgeValidator.pickedElement(payload))354                #expect(element.tag == "p" && element.selector == "html > body > p:nth-of-type(1)")355                #expect(element.text.hasPrefix("The quick brown fox"))356            }357        }358359        /// Mute plumbing. WebKit does not load or play media in a document that is not visible, and a test may360        /// not put a window on the owner's screen: detection of *playing* audio is therefore not exercised here.361        @Test func muteReachesMediaElementsAndSurvivesNavigation() async throws {362            try await withHarness { harness in363                let engine = harness.makeEngine()364                let muted = "return String(document.getElementById('tone').muted);"365                try await harness.load(engine, "/media", expectingTitle: "Media Fixture")366                try await waitUntil("media element seen") { engine.mediaActivity.totalElements == 1 }367                #expect(!engine.isPlayingAudio && engine.mediaActivity.playingElements == 0)368                #expect(await engine.string(muted) == "false")369370                engine.setMuted(true)371                #expect(engine.isMuted)372                try await waitUntilAsync("element muted") { await engine.string(muted) == "true" }373                // A new document is muted from its first script on.374                try await harness.load(engine, "/media", expectingTitle: "Media Fixture")375                try await waitUntilAsync("new document muted") { await engine.string(muted) == "true" }376                // An element the page adds later is muted as soon as it does anything.377                try await engine.evaluate("""378                var extra = document.createElement('audio'); extra.id = 'extra'; extra.src = '/media/silence.wav';379                document.body.appendChild(extra); extra.dispatchEvent(new Event('loadeddata'));380                """)381                try await waitUntilAsync("added element muted") { await engine.string("return String(document.getElementById('extra').muted);") == "true" }382                #expect(engine.mediaActivity.totalElements == 2)383384                engine.setMuted(false)385                try await waitUntilAsync("unmuted") { await engine.string(muted) == "false" }386                #expect(await engine.string("return String(document.getElementById('extra').muted);") == "false")387                // An element the page itself muted stays muted through a mute/unmute cycle of the tab.388                try await engine.evaluate("document.getElementById('tone').muted = true;")389                engine.setMuted(true); engine.setMuted(false)390                await settle(milliseconds: 150)391                #expect(await engine.string(muted) == "true")392            }393        }394395        /// The decision logic behind `requestMediaCapturePermissionFor` (and device motion / geolocation).396        /// WebKit only delivers a `getUserMedia` request for a *visible* document, and a test may not put a397        /// window on the owner's screen, so the WebKit → delegate hop itself is not exercised here.398        @Test func permissionResolutionGoesThroughProviderThenUser() async throws {399            try await withHarness { harness in400                let origin = try #require(WebOrigin(url: harness.server.baseURL))401                let engine = harness.makeEngine()402                let ui = UISpy()403                engine.uiDelegate = ui404                try await harness.load(engine, "/media-permission", expectingTitle: "Media Permission Fixture")405406                // Stored "deny" for one of the kinds: refused without asking.407                await harness.permissions.set(.deny, .microphone, origin)408                #expect(!(await engine.resolvePermission([.camera, .microphone], requestingOrigin: origin, isMainFrame: true)))409                #expect(ui.permissionRequests.isEmpty)410411                // Stored "allow" for everything: granted without asking.412                await harness.permissions.set(.allow, .microphone, origin)413                await harness.permissions.set(.allow, .camera, origin)414                #expect(await engine.resolvePermission([.camera, .microphone], requestingOrigin: origin, isMainFrame: true))415                #expect(ui.permissionRequests.isEmpty)416417                // Camera back to "ask": the user is asked for the camera only, denies, and asks to remember.418                await harness.permissions.set(.ask, .camera, origin)419                ui.permissionResponse = PermissionPromptResponse(allow: false, remember: true)420                let embedded = WebOrigin(scheme: "https", host: "widget.example")421                #expect(!(await engine.resolvePermission([.camera, .microphone], requestingOrigin: embedded, isMainFrame: false)))422                let request = try #require(ui.permissionRequests.first)423                #expect(request.kinds == [.camera])424                // The decision belongs to the page the user sees; the embedded frame is only mentioned.425                #expect(request.origin == origin && request.requestingOrigin == embedded && !request.isMainFrame)426                let recorded = await harness.permissions.recorded427                #expect(recorded.count == 1 && recorded.first?.kind == .camera && recorded.first?.verdict == .deny && recorded.first?.origin == origin)428                #expect(!(await engine.resolvePermission([.camera], requestingOrigin: origin, isMainFrame: true)))429                #expect(ui.permissionRequests.count == 1, "the remembered answer is used")430431                // "Allow once" is not recorded.432                await harness.permissions.set(.ask, .location, origin)433                ui.permissionResponse = PermissionPromptResponse(allow: true, remember: false)434                #expect(await engine.resolvePermission([.location], requestingOrigin: origin, isMainFrame: true))435                #expect(await harness.permissions.recorded.count == 1)436437                // Without a UI nobody can consent: undecided means no.438                engine.uiDelegate = nil439                #expect(!(await engine.resolvePermission([.location], requestingOrigin: origin, isMainFrame: true)))440441                // A ghost profile never records a decision, even when asked to remember.442                let ghost = harness.makeEngine(profile: harness.makeProfile("Ghost", ghost: true))443                ghost.uiDelegate = ui444                try await harness.load(ghost, "/", expectingTitle: "Fixture Home")445                ui.permissionResponse = PermissionPromptResponse(allow: false, remember: true)446                #expect(!(await ghost.resolvePermission([.location], requestingOrigin: origin, isMainFrame: true)))447                #expect(await harness.permissions.recorded.count == 1)448            }449        }450451        @Test func javaScriptDialogsAndSuppression() async throws {452            try await withHarness { harness in453                let engine = harness.makeEngine()454                // Without a UI every dialog is dismissed: the page cannot hang the tab.455                try await harness.load(engine, "/dialogs", expectingTitle: "Dialogs Fixture")456                try await engine.evaluate("document.getElementById('run').click();")457                try await waitUntil("dialogs auto-dismissed") { engine.title == "dialogs-done" }458                #expect(await engine.string("return document.getElementById('out').textContent;") == #"{"confirm":false,"prompt":null}"#)459460                let ui = UISpy()461                engine.uiDelegate = ui462                ui.dialogResponse = { dialog in463                    if case .prompt = dialog.kind { return JavaScriptDialogResponse(accepted: true, text: "typed") }464                    return JavaScriptDialogResponse(accepted: true)465                }466                try await harness.load(engine, "/dialogs", expectingTitle: "Dialogs Fixture")467                try await engine.evaluate("document.getElementById('run').click();")468                try await waitUntil("dialogs answered") { engine.title == "dialogs-done" }469                #expect(ui.dialogs.map(\.message) == ["alert-message", "confirm-message", "prompt-message"])470                #expect(ui.dialogs.map(\.kind) == [.alert, .confirm, .prompt(defaultText: "default-text")])471                #expect(ui.dialogs.map(\.sequenceOnPage) == [1, 2, 3])472                #expect(ui.dialogs.allSatisfy { $0.isMainFrame && $0.origin == WebOrigin(url: harness.server.baseURL) })473                #expect(await engine.string("return document.getElementById('out').textContent;") == #"{"confirm":true,"prompt":"typed"}"#)474475                // A page spamming alerts: the user suppresses on the second one, the other ten never show.476                ui.dialogs.removeAll()477                ui.dialogResponse = { dialog in JavaScriptDialogResponse(accepted: true, suppressFurtherDialogs: dialog.sequenceOnPage >= 2) }478                try await harness.load(engine, "/adversarial/dialogs", expectingTitle: "spam-done")479                #expect(ui.dialogs.count == 2)480                #expect(engine.areDialogsSuppressed && engine.suppressedDialogCount == 10)481                // Suppression is per page.482                try await harness.load(engine, "/", expectingTitle: "Fixture Home")483                #expect(!engine.areDialogsSuppressed && engine.suppressedDialogCount == 0)484            }485        }486    }487}488
Files main
Menu

Theme