Repository Public
1import XCTest2@testable import SPBrowserCore34final class AuraMotionTests: XCTestCase {5 func testEveryTokenHasASpecAndDurationsGrow() {6 let policy = MotionPolicy.standard7 for token in MotionToken.allCases { XCTAssertNotNil(policy.spec(for: token), token.rawValue) }8 let d = { (t: MotionToken) in policy.spec(for: t)!.duration }9 XCTAssertLessThan(d(.instant), d(.quick))10 XCTAssertLessThan(d(.quick), d(.standard))11 XCTAssertLessThan(d(.standard), d(.expressive))12 XCTAssertLessThan(d(.expressive), d(.cinematic))13 }1415 func testReduceMotionRemovesTravelAndBounce() {16 let policy = MotionPolicy(reduceMotion: true)17 XCTAssertNil(policy.spec(for: .instant))18 for token in MotionToken.allCases where token != .instant {19 let spec = policy.spec(for: token)!20 XCTAssertTrue(spec.isCrossfade, token.rawValue)21 XCTAssertLessThanOrEqual(spec.duration, 0.16)22 if case .spring = spec.curve { XCTFail("no spring under Reduce Motion") }23 }24 XCTAssertFalse(policy.allowsDecorative)25 XCTAssertFalse(policy.allowsSpatial)26 }2728 func testLowPowerShortensBigMovesAndStopsDecoration() {29 let policy = MotionPolicy(lowPower: true)30 XCTAssertFalse(policy.allowsDecorative)31 XCTAssertTrue(policy.allowsSpatial)32 XCTAssertEqual(policy.spec(for: .cinematic)?.duration, 0.24)33 XCTAssertEqual(policy.spec(for: .quick), MotionPolicy.base(.quick))34 XCTAssertFalse(MotionPolicy(isBackground: true).allowsDecorative)35 }3637 func testGestureResolution() {38 XCTAssertTrue(GestureResolution.shouldCommit(progress: 0.6, velocity: 0))39 XCTAssertFalse(GestureResolution.shouldCommit(progress: 0.4, velocity: 0))40 XCTAssertTrue(GestureResolution.shouldCommit(progress: 0.1, velocity: 3), "a flick commits")41 XCTAssertFalse(GestureResolution.shouldCommit(progress: 0.9, velocity: -3), "a flick back cancels")42 let pulled = GestureResolution.rubberBand(400, limit: 120)43 XCTAssertGreaterThan(pulled, 0)44 XCTAssertLessThan(pulled, 120)45 XCTAssertEqual(GestureResolution.rubberBand(-400, limit: 120), -pulled, accuracy: 0.0001)46 }47}4849final class AuraFlowTests: XCTestCase {50 let tab = UUID()5152 func testSearchResultArticleReferenceFormOnePath() {53 var trail = FlowTrail()54 let search = trail.record(url: "spsearch://results?q=webkit", title: "", tabID: tab, transition: .typed)55 let result = trail.record(url: "https://a.example/list", title: "List", tabID: tab, transition: .link)56 let article = trail.record(url: "https://a.example/article", title: "Article", tabID: tab, transition: .link)57 let pdf = trail.record(url: "https://b.example/paper.pdf", title: "", tabID: tab, transition: .link)58 XCTAssertEqual(search.kind, .search)59 XCTAssertEqual(pdf.kind, .document)60 XCTAssertEqual(trail.path(to: pdf.id).map(\.id), [search.id, result.id, article.id, pdf.id])61 XCTAssertEqual(trail.journeys.count, 1)62 XCTAssertEqual(trail.journeys[0].nodeCount, 4)63 XCTAssertEqual(search.displayTitle, "webkit")64 }6566 func testGoingBackThenAnotherLinkCreatesABranch() {67 var trail = FlowTrail()68 let root = trail.record(url: "https://a.example/", title: "A", tabID: tab, transition: .typed)69 let one = trail.record(url: "https://a.example/1", title: "1", tabID: tab, transition: .link)70 let back = trail.record(url: "https://a.example/", title: "A", tabID: tab, transition: .revisit)71 XCTAssertEqual(back.id, root.id, "going back returns to the existing step")72 XCTAssertEqual(trail.nodes.count, 2)73 let two = trail.record(url: "https://a.example/2", title: "2", tabID: tab, transition: .link)74 XCTAssertEqual(Set(trail.children(of: root.id).map(\.id)), [one.id, two.id])75 XCTAssertEqual(trail.branchPoints.map(\.id), [root.id])76 XCTAssertEqual(trail.journeys[0].branchCount, 1)77 // Forward to a page already below: no duplicate.78 _ = trail.record(url: "https://a.example/", title: "A", tabID: tab, transition: .revisit)79 let again = trail.record(url: "https://a.example/1", title: "1", tabID: tab, transition: .link)80 XCTAssertEqual(again.id, one.id)81 XCTAssertEqual(trail.nodes.count, 3)82 XCTAssertEqual(again.visits, 2)83 }8485 func testGoingBackAcrossATypedAddressReturnsToTheEarlierJourney() {86 var trail = FlowTrail()87 let first = trail.record(url: "https://a.example/", title: "A", tabID: tab, transition: .typed)88 let second = trail.record(url: "https://b.example/", title: "B", tabID: tab, transition: .typed)89 let back = trail.record(url: "https://a.example/", title: "A", tabID: tab, transition: .revisit)90 XCTAssertEqual(back.id, first.id)91 XCTAssertEqual(trail.nodes.count, 2)92 XCTAssertEqual(trail.cursor[tab], first.id)93 let forward = trail.record(url: "https://b.example/", title: "B", tabID: tab, transition: .revisit)94 XCTAssertEqual(forward.id, second.id)95 XCTAssertEqual(trail.nodes.count, 2)96 }9798 func testTabOpenedFromAnotherTabContinuesItsPath() {99 var trail = FlowTrail()100 let parent = trail.record(url: "https://a.example/", title: "A", tabID: tab, transition: .typed)101 let other = UUID()102 let child = trail.record(url: "https://c.example/", title: "C", tabID: other, transition: .opened(from: tab))103 XCTAssertEqual(child.parentID, parent.id)104 XCTAssertEqual(trail.cursor[other], child.id)105 XCTAssertEqual(trail.cursor[tab], parent.id, "the opener stays where it was")106 let typed = trail.record(url: "https://d.example/", title: "D", tabID: other, transition: .typed)107 XCTAssertNil(typed.parentID, "a typed address starts a new journey")108 XCTAssertEqual(trail.journeys.count, 2)109 }110111 func testReloadAndTitleUpdateDoNotAddSteps() {112 var trail = FlowTrail()113 let a = trail.record(url: "https://a.example/", title: "", tabID: tab, transition: .typed)114 let same = trail.record(url: "https://a.example/", title: "Loaded", tabID: tab, transition: .revisit)115 XCTAssertEqual(a.id, same.id)116 trail.updateTitle("Final title", tabID: tab)117 XCTAssertEqual(trail.nodes.count, 1)118 XCTAssertEqual(trail.nodes[0].title, "Final title")119 }120121 func testMapPlacesDepthInColumnsAndLeavesInRows() {122 var trail = FlowTrail()123 let root = trail.record(url: "https://a.example/", title: "A", tabID: tab, transition: .typed)124 let one = trail.record(url: "https://a.example/1", title: "1", tabID: tab, transition: .link)125 _ = trail.record(url: "https://a.example/", title: "A", tabID: tab, transition: .revisit)126 let two = trail.record(url: "https://a.example/2", title: "2", tabID: tab, transition: .link)127 let deep = trail.record(url: "https://a.example/2/x", title: "x", tabID: tab, transition: .link)128 let map = FlowMap(trail: trail, rootID: root.id)129 XCTAssertEqual(map.columns, 3)130 XCTAssertEqual(map.rows, 2)131 XCTAssertEqual(map.position(of: root.id)?.column, 0)132 XCTAssertEqual(map.position(of: one.id)?.column, 1)133 XCTAssertEqual(map.position(of: deep.id)?.column, 2)134 XCTAssertEqual(map.position(of: root.id)?.row, 0.5, "a parent sits between its branches")135 XCTAssertNotEqual(map.position(of: one.id)?.row, map.position(of: two.id)?.row)136 XCTAssertEqual(map.edges.count, 3)137 }138139 func testForgettingFollowsHistoryDeletion() {140 var trail = FlowTrail()141 let a = trail.record(url: "https://a.example/", title: "A", tabID: tab, transition: .typed, at: Date(timeIntervalSince1970: 100))142 _ = trail.record(url: "https://secret.example/", title: "S", tabID: tab, transition: .link, at: Date(timeIntervalSince1970: 200))143 let c = trail.record(url: "https://c.example/", title: "C", tabID: tab, transition: .link, at: Date(timeIntervalSince1970: 300))144 trail.forget(url: "https://secret.example/")145 XCTAssertFalse(trail.nodes.contains { $0.url.contains("secret") })146 XCTAssertEqual(trail.node(c.id)?.parentID, a.id, "the path is stitched back together")147 trail.forget(since: Date(timeIntervalSince1970: 250))148 XCTAssertEqual(trail.nodes.map(\.id), [a.id])149 trail.forget(since: nil)150 XCTAssertTrue(trail.nodes.isEmpty)151 XCTAssertTrue(trail.cursor.isEmpty)152 }153154 func testTrailStaysBoundedAndKeepsLiveJourneys() {155 var trail = FlowTrail()156 let live = UUID()157 let liveRoot = trail.record(url: "https://live.example/", title: "", tabID: live, transition: .typed, at: Date(timeIntervalSince1970: 1))158 for i in 0..<(FlowTrail.maxNodes + 80) {159 let t = UUID()160 trail.record(url: "https://x.example/\(i)", title: "", tabID: t, transition: .typed, at: Date(timeIntervalSince1970: Double(10 + i)))161 trail.tabClosed(t)162 }163 XCTAssertLessThanOrEqual(trail.nodes.count, FlowTrail.maxNodes)164 XCTAssertNotNil(trail.node(liveRoot.id), "the journey of an open tab is never pruned, however old")165 }166167 func testStoreRoundTripAndPrivateStoreStaysInMemory() throws {168 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("flow-\(UUID().uuidString)")169 defer { try? FileManager.default.removeItem(at: dir) }170 let url = dir.appendingPathComponent("flow.json")171 let store = FlowStore(url: url)172 store.update { $0.record(url: "https://a.example/", title: "A", tabID: self.tab, transition: .typed) }173 XCTAssertEqual(FlowStore(url: url).trail.nodes.count, 1)174 let memory = FlowStore(url: nil)175 memory.update { $0.record(url: "https://p.example/", title: "P", tabID: self.tab, transition: .typed) }176 XCTAssertEqual(memory.trail.nodes.count, 1)177 XCTAssertEqual((try? FileManager.default.contentsOfDirectory(atPath: dir.path))?.count, 1, "nothing else was written")178 }179}180181final class AuraConstellationTests: XCTestCase {182 private func item(_ title: String, _ url: String, group: UUID? = nil, parent: UUID? = nil, id: UUID = UUID()) -> ConstellationItem {183 ConstellationItem(id: id, title: title, url: url, groupID: group, groupName: group == nil ? nil : "Research", colorIndex: 2, parentID: parent)184 }185186 func testClustersByGroupThenBySiteThenLoose() {187 let g = UUID()188 let items = [item("a", "https://www.apple.com/mac", group: g), item("b", "https://news.example/x", group: g),189 item("c", "https://en.wikipedia.org/wiki/A"), item("d", "https://fr.wikipedia.org/wiki/B"),190 item("e", "https://solo.example/"), item("f", "about:blank")]191 let map = ConstellationMap(items: items)192 XCTAssertEqual(Set(map.clusters.map(\.kind)), [.group, .domain, .loose])193 XCTAssertEqual(map.clusters.first { $0.kind == .group }?.members.count, 2)194 XCTAssertEqual(map.clusters.first { $0.kind == .domain }?.label, "wikipedia.org")195 XCTAssertEqual(map.clusters.first { $0.kind == .loose }?.members.count, 2)196 XCTAssertEqual(map.positions.count, items.count)197 XCTAssertTrue(map.links.contains { $0.kind == .group })198 XCTAssertTrue(map.links.contains { $0.kind == .domain })199 XCTAssertFalse(map.isLightweight)200 }201202 func testLayoutIsDeterministicAndClustersDoNotOverlap() {203 var items: [ConstellationItem] = []204 for site in 0..<6 { for page in 0..<(site + 2) { items.append(item("t", "https://site\(site).example/\(page)", id: UUID(uuidString: String(format: "00000000-0000-0000-%04d-%012d", site, page))!)) } }205 let a = ConstellationMap(items: items), b = ConstellationMap(items: items.reversed())206 XCTAssertEqual(a.positions, b.positions)207 for (i, first) in a.clusters.enumerated() {208 for second in a.clusters[(i + 1)...] {209 XCTAssertGreaterThanOrEqual(hypot(first.center.x - second.center.x, first.center.y - second.center.y), first.radius + second.radius)210 }211 }212 // No two cards on the same spot.213 XCTAssertEqual(Set(a.positions.values.map { "\(Int($0.x)),\(Int($0.y))" }).count, items.count)214 XCTAssertGreaterThan(a.bounds.width, 0)215 XCTAssertLessThanOrEqual(a.fittingScale(in: CGSize(width: 800, height: 600)), 1.15)216 }217218 func testParentLinksAndKeyboardNeighbours() {219 let parent = UUID(), child = UUID()220 let items = [item("p", "https://a.example/", id: parent), item("c", "https://b.example/", parent: parent, id: child), item("o", "https://c.example/")]221 let map = ConstellationMap(items: items)222 XCTAssertTrue(map.links.contains(ConstellationMap.Link(from: parent, to: child, kind: .parent)))223 var reached = Set<UUID>()224 for id in items.map(\.id) { for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] { if let n = map.neighbour(of: id, dx: dx, dy: dy) { reached.insert(n) } } }225 XCTAssertEqual(reached, Set(items.map(\.id)), "every tab can be reached with the arrow keys")226 XCTAssertEqual(map.cluster(at: map.positions[parent]!)?.members.contains(parent), true)227 }228229 func testLargeSetsSwitchToTheLightweightRendition() {230 let items = (0..<90).map { item("t\($0)", "https://s\($0 % 9).example/\($0)") }231 let map = ConstellationMap(items: items)232 XCTAssertTrue(map.isLightweight)233 XCTAssertTrue(map.links.allSatisfy { $0.kind == .parent })234 XCTAssertEqual(ConstellationMap.filter(items, query: "t89").count, 1)235 XCTAssertEqual(ConstellationMap.filter(items, query: " ").count, 90)236 }237}238239final class AuraCanvasTests: XCTestCase {240 func testAddingCardsNeverStacksThemExactly() {241 var board = CanvasBoard(name: "Research")242 let a = board.add(.link, title: "A", url: "https://a.example/", at: CGPoint(x: 300, y: 300))!243 let b = board.add(.note, text: "idea", at: CGPoint(x: 300, y: 300))!244 XCTAssertNotEqual(a.frame.origin, CGPoint(x: b.x + 0, y: b.y + 0 - (b.height - a.height) / 2 - 0.0001))245 XCTAssertFalse(abs(a.x - b.x) < 12 && abs(a.y - b.y) < 12)246 let c = board.add(.text, text: "quote")!247 XCTAssertFalse(board.cards.filter { $0.id != c.id }.contains { $0.frame.intersects(c.frame) }, "auto-placed cards land on free space")248 }249250 func testMagneticSnapAlignsEdgesAndReportsGuides() {251 var board = CanvasBoard(name: "B")252 let anchor = board.add(.note, at: CGPoint(x: 200, y: 200))!253 let moving = CGRect(x: anchor.x + 5, y: anchor.frame.maxY + 40, width: 240, height: 150)254 let snap = board.snap(moving, excluding: [])255 XCTAssertEqual(snap.origin.x, anchor.x, accuracy: 0.001)256 XCTAssertEqual(snap.origin.y, moving.minY, accuracy: 0.001, "nothing to align with vertically")257 XCTAssertEqual(snap.verticalGuides, [anchor.x])258 XCTAssertTrue(snap.horizontalGuides.isEmpty)259 let far = board.snap(CGRect(x: anchor.x + 60, y: 900, width: 240, height: 150), excluding: [])260 XCTAssertEqual(far.origin.x, anchor.x + 60, accuracy: 0.001, "beyond the snap distance nothing moves")261 XCTAssertEqual(CanvasBoard.clampZoom(50), 3.0)262 XCTAssertEqual(CanvasBoard.clampZoom(0.01), 0.2)263 }264265 func testConnectionsGroupsRemovalAndSearch() {266 var board = CanvasBoard(name: "B")267 let a = board.add(.link, title: "WebKit", url: "https://webkit.org/")!268 let b = board.add(.note, text: "Compare with Blink")!269 let c = board.add(.text, title: "Quote", text: "fast and open")!270 board.toggleConnection(a.id, b.id)271 board.toggleConnection(b.id, a.id)272 XCTAssertTrue(board.connections.isEmpty, "connecting twice removes the link")273 board.toggleConnection(a.id, b.id)274 board.toggleConnection(a.id, a.id)275 XCTAssertEqual(board.connections.count, 1)276 let group = board.group([a.id, b.id], name: "Engines")!277 XCTAssertNotNil(board.bounds(ofGroup: group.id))278 XCTAssertEqual(board.search("blink").map(\.id), [b.id])279 XCTAssertEqual(board.search("webkit").map(\.id), [a.id])280 board.move([c.id], by: CGSize(width: 10, height: -4))281 XCTAssertEqual(board.card(c.id)!.x, c.x + 10)282 board.remove([b.id])283 XCTAssertTrue(board.connections.isEmpty)284 XCTAssertEqual(board.groups.count, 1, "the group survives while it has a member")285 board.remove([a.id])286 XCTAssertTrue(board.groups.isEmpty)287 }288289 func testMarkdownExport() {290 var board = CanvasBoard(name: "Trip")291 let a = board.add(.link, title: "Hotel [new]", url: "https://h.example/", at: CGPoint(x: 100, y: 100))!292 let b = board.add(.note, title: "Budget", text: "line one\nline two", at: CGPoint(x: 500, y: 100))!293 board.toggleConnection(a.id, b.id)294 let md = board.markdown()295 XCTAssertTrue(md.hasPrefix("# Trip\n"))296 XCTAssertTrue(md.contains("- [Hotel [new\\]](https://h.example/)"))297 XCTAssertTrue(md.contains("- **Budget**\n > line one\n > line two"))298 XCTAssertTrue(md.contains("- Hotel [new] → Budget"))299 }300301 func testStorePersistsBoardsAndRefusesAssetPathsOutsideItsFolder() throws {302 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("canvas-\(UUID().uuidString)")303 defer { try? FileManager.default.removeItem(at: dir) }304 let store = CanvasStore(directory: dir)305 var board = store.create(name: "")306 XCTAssertFalse(board.name.isEmpty)307 let asset = try XCTUnwrap(store.storeAsset(Data([1, 2, 3]), board: board.id))308 board.add(.capture, title: "Shot", asset: asset)309 store.save(board)310 let reopened = CanvasStore(directory: dir)311 XCTAssertEqual(reopened.board(board.id)?.cards.first?.asset, asset)312 XCTAssertEqual(try Data(contentsOf: XCTUnwrap(reopened.assetURL(asset, board: board.id))), Data([1, 2, 3]))313 XCTAssertNil(reopened.assetURL("../settings.json", board: board.id))314 XCTAssertNil(reopened.assetURL("a/b.png", board: board.id))315 reopened.delete(board.id)316 XCTAssertTrue(CanvasStore(directory: dir).boards.isEmpty)317 XCTAssertFalse(FileManager.default.fileExists(atPath: dir.appendingPathComponent(board.id.uuidString + ".assets").path))318 }319320 func testOnlyOptedInBoardsReachTheSyncMirrorAndAssetsNeverDo() throws {321 let mirror = try SyncDatabase(url: nil)322 let store = CanvasStore(directory: nil)323 var local = store.create(name: "Private notes")324 local.add(.note, text: "stays here")325 store.save(local)326 var shared = store.create(name: "Shared")327 let card = shared.add(.capture, title: "Shot", asset: "x.png")!328 shared.isSynced = true329 store.save(shared)330 let bridge = CanvasSyncBridge(store: store, mirror: mirror)331 bridge.captureLocalChanges()332 let records = mirror.records(SyncCollection.canvas)333 XCTAssertEqual(records.count, 2, "one header and one card, for the synced board only")334 XCTAssertFalse(records.contains { String(decoding: $0.json, as: UTF8.self).contains("stays here") })335 XCTAssertFalse(records.contains { String(decoding: $0.json, as: UTF8.self).contains("x.png") })336337 // Another device rebuilds the board from the mirror.338 let otherStore = CanvasStore(directory: nil)339 CanvasSyncBridge(store: otherStore, mirror: mirror).applyRemoteChanges()340 XCTAssertEqual(otherStore.boards.map(\.name), ["Shared"])341 XCTAssertEqual(otherStore.boards[0].cards.map(\.id), [card.id])342 XCTAssertNil(otherStore.boards[0].cards[0].asset)343344 // Applying remote data keeps this device's own image asset.345 bridge.applyRemoteChanges()346 XCTAssertEqual(store.board(shared.id)?.cards.first?.asset, "x.png")347348 // Turning sync off withdraws the board; removing a card withdraws that card.349 shared = store.board(shared.id)!350 shared.isSynced = false351 store.save(shared)352 bridge.captureLocalChanges()353 XCTAssertTrue(mirror.values(SyncCollection.canvas, as: CanvasSyncBridge.BoardHeader.self).isEmpty)354 XCTAssertTrue(mirror.values(SyncCollection.canvas, as: CanvasSyncBridge.CardRecord.self).isEmpty)355 }356}357358final class AuraPeekTests: XCTestCase {359 func testParserReadsOpenGraphTitleDescriptionImageAndExcerpt() {360 let html = """361 <!doctype html><html><head><title>Plain & simple</title>362 <meta property="og:title" content="The "Real" Title"><meta name='description' content='A short description.'>363 <meta content="https://cdn.example/img.png" property="og:image"><meta property=og:site_name content=Example>364 </head><body><nav><p>Menu item that is long enough to look like a paragraph but sits in the navigation.</p></nav>365 <script>var p = "<p>not text, this is script content that should never be shown to anyone</p>";</script>366 <p>Too short.</p>367 <p>The first real paragraph of the article, with <a href="/x">a link</a> and enough words to count as running text.</p>368 </body></html>369 """370 let url = URL(string: "https://example.com/a")!371 let p = LinkPreviewParser.parse(html: html, url: url, finalURL: url)372 XCTAssertEqual(p.title, "The \"Real\" Title")373 XCTAssertEqual(p.summary, "A short description.")374 XCTAssertEqual(p.siteName, "Example")375 XCTAssertEqual(p.imageURL?.absoluteString, "https://cdn.example/img.png")376 XCTAssertTrue(p.excerpt.hasPrefix("The first real paragraph of the article, with a link"))377 XCTAssertFalse(p.excerpt.contains("script content"))378 XCTAssertFalse(p.excerpt.contains("Menu item"))379 }380381 func testParserFallsBackToTitleTagResolvesRelativeImagesAndRejectsOddSchemes() {382 let url = URL(string: "https://example.com/dir/page")!383 let a = LinkPreviewParser.parse(html: "<title> Café — menu </title><meta name=twitter:image content='../i.jpg'>", url: url, finalURL: url)384 XCTAssertEqual(a.title, "Café — menu")385 XCTAssertEqual(a.imageURL?.absoluteString, "https://example.com/i.jpg")386 let b = LinkPreviewParser.parse(html: "<meta property='og:image' content='javascript:alert(1)'><meta property='og:image' content='data:image/png;base64,AA'>", url: url, finalURL: url)387 XCTAssertNil(b.imageURL)388 XCTAssertEqual(b.title, "")389 let redirected = LinkPreview(url: URL(string: "https://short.example/x")!, finalURL: URL(string: "https://www.other.org/y")!)390 XCTAssertTrue(redirected.wasRedirectedToAnotherSite)391 XCTAssertFalse(LinkPreview(url: URL(string: "https://example.com/x")!, finalURL: URL(string: "https://www.example.com/y")!).wasRedirectedToAnotherSite)392 }393394 func testPolicyRefusesLocalNetworkCredentialsAndOtherSchemes() {395 let allowed = { (s: String) in LinkPreviewPolicy.isAllowed(URL(string: s)!) }396 XCTAssertTrue(allowed("https://example.com/"))397 XCTAssertTrue(allowed("http://93.184.216.34/"))398 for refused in ["http://localhost:3000/", "http://127.0.0.1/", "http://192.168.2.1/admin", "http://10.0.0.5/", "http://172.20.1.1/", "http://169.254.169.254/latest",399 "http://100.100.1.1/", "http://[::1]/", "http://router/", "http://printer.local/", "https://user:pw@example.com/", "file:///etc/passwd",400 "javascript:alert(1)", "spsearch://results?q=x", "ftp://example.com/"] {401 XCTAssertFalse(allowed(refused), refused)402 }403 XCTAssertTrue(LinkPreviewPolicy.isAllowed(URL(string: "http://localhost:3000/")!, sourceIsLocal: true), "a local page may preview its own local links")404 }405406 func testHoveredLinkMessagesAreValidated() {407 let ok = HoveredLink.parse(["t": "hover", "href": "https://example.com/a", "text": "A", "x": 100, "y": 50, "w": 200, "h": 20, "vw": 1000, "vh": 500, "alt": true])408 XCTAssertEqual(ok?.unitRect, CGRect(x: 0.1, y: 0.1, width: 0.2, height: 0.04))409 XCTAssertEqual(ok?.optionHeld, true)410 XCTAssertNil(HoveredLink.parse(["href": ""]))411 XCTAssertNil(HoveredLink.parse(["href": "javascript:alert(1)"]))412 XCTAssertNil(HoveredLink.parse(["href": 42]))413 let wild = HoveredLink.parse(["href": "https://e.example/", "x": -50, "y": 99999, "w": Double.nan, "h": 10, "vw": 0, "vh": 100])414 XCTAssertEqual(wild?.unitRect.minX, 0)415 XCTAssertEqual(wild?.unitRect.minY, 1)416 XCTAssertEqual(wild?.unitRect.width, 0)417 }418}419420final class AuraPortalAndOrbitTests: XCTestCase {421 func testHandoffReachesOnlyItsTargetExpiresAndIsConsumed() throws {422 let library = SyncedLibrary(mirror: try SyncDatabase(url: nil))423 let tabs = [RemoteTab(title: "A", url: "https://a.example/"), RemoteTab(title: "internal", url: "spsearch://results?q=x"), RemoteTab(title: "file", url: "file:///tmp/x")]424 let now = Date()425 let item = try XCTUnwrap(library.sendHandoff(tabs: tabs, title: "Trip", to: "phone", fromDeviceID: "mac", fromDeviceName: "Mac", fromPlatform: "macos", now: now))426 XCTAssertEqual(item.tabs.map(\.url), ["https://a.example/"], "only real web pages are handed off")427 XCTAssertEqual(library.pendingHandoffs(for: "phone", now: now).map(\.id), [item.id])428 XCTAssertTrue(library.pendingHandoffs(for: "ipad", now: now).isEmpty)429 XCTAssertTrue(library.pendingHandoffs(for: "mac", now: now).isEmpty, "the sender does not receive its own hand-off")430 let any = try XCTUnwrap(library.sendHandoff(tabs: tabs, to: nil, fromDeviceID: "mac", fromDeviceName: "Mac", fromPlatform: "macos", now: now))431 XCTAssertEqual(Set(library.pendingHandoffs(for: "ipad", now: now).map(\.id)), [any.id])432 XCTAssertTrue(library.pendingHandoffs(for: "phone", now: now.addingTimeInterval(HandoffItem.lifetime + 1)).isEmpty)433 library.consumeHandoff(item)434 XCTAssertEqual(library.pendingHandoffs(for: "phone", now: now).map(\.id), [any.id])435 library.purgeExpiredHandoffs(now: now.addingTimeInterval(HandoffItem.lifetime + 1))436 XCTAssertTrue(library.pendingHandoffs(for: "phone", now: now).isEmpty)437 XCTAssertNil(library.sendHandoff(tabs: [RemoteTab(title: "", url: "file:///x")], to: nil, fromDeviceID: "mac", fromDeviceName: "Mac", fromPlatform: "macos"))438 }439440 func testPortalDevicesMergeOpenAndClosedTabs() throws {441 let library = SyncedLibrary(mirror: try SyncDatabase(url: nil))442 library.publishTabs([RemoteTab(title: "A", url: "https://a.example/")], closed: [RemoteTab(title: "Z", url: "https://z.example/")], deviceID: "phone", deviceName: "iPhone", platform: "ios")443 library.publishTabs([], closed: [RemoteTab(title: "Y", url: "https://y.example/")], deviceID: "pad", deviceName: "iPad", platform: "ipados")444 library.publishTabs([RemoteTab(title: "Mine", url: "https://m.example/")], closed: [], deviceID: "mac", deviceName: "Mac", platform: "macos")445 let devices = library.portalDevices(excluding: "mac")446 XCTAssertEqual(Set(devices.map(\.id)), ["phone", "pad"])447 XCTAssertEqual(devices.first { $0.id == "phone" }?.closed.count, 1)448 XCTAssertEqual(devices.first { $0.id == "pad" }?.tabs.count, 0)449 XCTAssertEqual(devices.first { $0.id == "pad" }?.symbol, "ipad")450 XCTAssertEqual(devices[0].freshness(), .live)451 XCTAssertEqual(devices[0].freshness(now: Date().addingTimeInterval(3 * 86400)), .stale)452 }453454 func testOrbitRingIsContextualBoundedAndPlatformAware() {455 let reading = OrbitCatalog.ring(for: OrbitContext(platform: .mac, hasPage: true, aiEnabled: true, isSignedIn: true, tabCount: 12, hasOtherDevices: true))456 XCTAssertLessThanOrEqual(reading.count, 8)457 XCTAssertEqual(reading.first, .openLocation)458 XCTAssertTrue(reading.contains(.toggleReader))459 XCTAssertTrue(reading.contains(.toggleIntelligence))460 XCTAssertTrue(reading.contains(.showConstellation))461 XCTAssertEqual(Set(reading).count, reading.count)462463 let phone = OrbitCatalog.ring(for: OrbitContext(platform: .phone, hasPage: true, aiEnabled: true))464 XCTAssertFalse(phone.contains(.toggleIntelligence), "SP Intelligence is not available on iOS")465 XCTAssertTrue(phone.allSatisfy(OrbitCatalog.supported(on: .phone).contains))466467 let blank = OrbitCatalog.ring(for: OrbitContext(platform: .mac))468 XCTAssertFalse(blank.contains(.toggleReader))469 XCTAssertFalse(blank.contains(.sharePage))470 XCTAssertTrue(blank.contains(.showCanvas))471472 let privateRing = OrbitCatalog.ring(for: OrbitContext(platform: .mac, hasPage: true, isPrivate: true, isSignedIn: true, hasOtherDevices: true))473 XCTAssertFalse(privateRing.contains(.addToReadingList))474 XCTAssertFalse(privateRing.contains(.showPortal))475 }476477 func testOrbitRankingAndNewCommandsFitTheCatalog() {478 let ranked = OrbitCatalog.rank(CommandID.allCases, query: "can")479 XCTAssertTrue(ranked.prefix(3).contains(.showCanvas) || ranked.prefix(3).contains(.addToCanvas))480 XCTAssertTrue(OrbitCatalog.rank(CommandID.allCases, query: "zzzz").isEmpty)481 XCTAssertEqual(OrbitCatalog.rank([.reload, .newTab], query: "", recent: [.reload]).first, .reload)482 XCTAssertTrue(CommandID.conflicts(overrides: [:]).isEmpty, "the 3.0 shortcuts collide with nothing")483 for command in [CommandID.commandOrbit, .showConstellation, .showFlow, .showCanvas, .addToCanvas, .showPortal, .peekLink] {484 XCTAssertFalse(command.title.isEmpty)485 XCTAssertNotNil(command.defaultShortcut)486 }487 }488}489490final class AuraMigrationTests: XCTestCase {491 func testStartPageBackgroundBecomesAnAmbientTheme() throws {492 for (old, expected) in [("aurora", AmbientTheme.aurora), ("plain", .minimal), ("graphite", .obsidian), ("dusk", .liquid), ("forest", .liquid)] {493 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("settings-\(UUID().uuidString)")494 defer { try? FileManager.default.removeItem(at: dir) }495 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)496 let url = dir.appendingPathComponent("settings.json")497 try Data(#"{"schemaVersion":3,"searchEngineID":"google","startPage":{"background":"\#(old)","showGreeting":false},"tabLayout":"vertical"}"#.utf8).write(to: url)498 let settings = SettingsStore(url: url).settings499 XCTAssertEqual(settings.startPage.ambient, expected, old)500 XCTAssertEqual(settings.schemaVersion, 4)501 XCTAssertEqual(settings.searchEngineID, "google", "nothing else is touched")502 XCTAssertEqual(settings.tabLayout, .vertical)503 XCTAssertFalse(settings.startPage.showGreeting)504 XCTAssertTrue(settings.flowEnabled)505 XCTAssertFalse(settings.peekOnHover)506 }507 }508509 func testSessionsSavedByVersion2StillDecode() throws {510 let json = #"{"version":1,"savedAt":"2026-11-18T10:00:00Z","windows":[{"tabs":[{"id":"6F9619FF-8B86-D011-B42D-00C04FC964FF","url":"https://a.example/","title":"A","isPinned":true}],"groups":[],"sidebarVisible":true}]}"#511 let session = try JSONFile.decoder().decode(SessionSnapshot.self, from: Data(json.utf8))512 XCTAssertEqual(session.windows[0].tabs[0].title, "A")513 XCTAssertNil(session.windows[0].tabs[0].openerID)514 var tab = session.windows[0].tabs[0]515 tab.openerID = UUID()516 let again = try JSONFile.decoder().decode(TabSnapshot.self, from: JSONFile.encoder().encode(tab))517 XCTAssertEqual(again.openerID, tab.openerID)518 }519520 func testUnknownCollectionsFromANewerClientAreKeptOpaqueByTheMirror() throws {521 // What a 2.0 client does with 3.0 records: the mirror stores any collection name; nothing reads it.522 let mirror = try SyncDatabase(url: nil)523 mirror.put("canvas", key: "b:x", json: Data("{}".utf8))524 XCTAssertEqual(mirror.records("canvas").count, 1)525 XCTAssertTrue(SyncCollection.all.contains(SyncCollection.canvas))526 XCTAssertTrue(SyncCollection.all.contains(SyncCollection.handoff))527 }528529 func testReadingTime() {530 let article = ReaderArticle(title: "T", byline: nil, blocks: [.init(kind: "p", text: Array(repeating: "word", count: 690).joined(separator: " "))])531 XCTAssertEqual(article.readingMinutes, 3)532 XCTAssertTrue(article.isReadable)533 }534}535