Repository Public License
1// ORIX Secure2// File: App/Sources/Features/URLAnalysis/LinkAnalyzerView.swift3// Description: Link analyser: paste a link or scan a QR code and see what its structure reveals — host anatomy, each signal with4// its evidence, the scoring method and what was not inspected. The link is never opened and never sent anywhere.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AVFoundation9import ORIXDesign10import ORIXSecureModel11import ORIXURLRisk12import PhotosUI13import SwiftUI1415extension URLRiskLevel {16 var tint: Color {17 switch self {18 case .noSignals, .low: ORIX.Palette.info19 case .elevated: ORIX.Palette.warning20 case .high: ORIX.Palette.danger21 }22 }2324 var symbol: String {25 switch self {26 case .noSignals: "circle.dashed"27 case .low: "info.circle"28 case .elevated: "exclamationmark.triangle.fill"29 case .high: "exclamationmark.octagon.fill"30 }31 }32}3334struct LinkAnalyzerView: View {35 @Environment(AppModel.self) private var model36 @Environment(AppSettings.self) private var settings37 @Environment(Router.self) private var router38 @State private var input = ""39 @State private var analysis: URLAnalysis?40 @State private var qr: QRPayload?41 @State private var others: [String] = []42 @State private var photo: PhotosPickerItem?43 @State private var showScanner = false44 @State private var notice: String?45 @State private var saved = false46 @FocusState private var focused: Bool47 private let analyzer = URLRiskAnalyzer()4849 var body: some View {50 ScreenScroll {51 inputCard52 if let notice { ORIXBanner(.info, title: Text(verbatim: notice)).accessibilityIdentifier("link.notice") }53 if let qr, qr.kind != .url { qrCard(qr) }54 if let analysis { result(analysis) }55 if !others.isEmpty {56 ORIXSectionHeader("Other links in the text")57 ForEach(others, id: \.self) { link in58 Button { input = link; analyze() } label: { Text(verbatim: link).font(.orixMono).lineLimit(2).frame(maxWidth: .infinity, alignment: .leading) }59 .buttonStyle(.plain).orixCard(padding: ORIX.Space.sm)60 }61 }62 if analysis == nil, qr == nil {63 LimitsCard(title: "What link analysis is, and is not", items: URLAnalysis.standardNotInspected)64 }65 }66 .navigationTitle("Link Analyser")67 .sheet(isPresented: $showScanner) { scannerSheet }68 .onChange(of: photo) { _, item in69 guard let item else { return }70 Task { await readQR(from: item) }71 }72 .onAppear { consumePending() }73 .onChange(of: router.pendingLink) { _, _ in consumePending() }74 .accessibilityIdentifier("link")75 }7677 private var inputCard: some View {78 VStack(alignment: .leading, spacing: ORIX.Space.sm) {79 TextField("Paste a link or a message", text: $input, axis: .vertical)80 .lineLimit(1...5)81 .textInputAutocapitalization(.never)82 .autocorrectionDisabled()83 .keyboardType(.URL)84 .font(.orixMono)85 .focused($focused)86 .padding(ORIX.Space.sm)87 .background(ORIX.Palette.surfaceRaised, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))88 .accessibilityIdentifier("link.input")89 HStack(spacing: ORIX.Space.sm) {90 Button { analyze() } label: { Label("Analyse", systemImage: "magnifyingglass") }91 .buttonStyle(.orixPrimary)92 .disabled(input.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)93 .accessibilityIdentifier("link.analyze")94 PasteButton(payloadType: String.self) { strings in95 if let first = strings.first { input = first; analyze() }96 }97 .labelStyle(.iconOnly)98 .accessibilityIdentifier("link.paste")99 }100 HStack(spacing: ORIX.Space.sm) {101 PhotosPicker(selection: $photo, matching: .images) { Label("QR from Photo", systemImage: "qrcode.viewfinder") }102 .buttonStyle(.bordered)103 .accessibilityIdentifier("link.qrPhoto")104 if QRScannerView.isSupported {105 Button { openScanner() } label: { Label("Scan QR", systemImage: "camera") }106 .buttonStyle(.bordered)107 .accessibilityIdentifier("link.qrCamera")108 }109 if analysis != nil || qr != nil {110 Spacer()111 Button("Clear") { input = ""; analysis = nil; qr = nil; others = []; notice = nil; saved = false }112 .accessibilityIdentifier("link.clear")113 }114 }115 Label("Analysed on this device. ORIX Secure never opens the link and consults no online service.", systemImage: "lock.shield")116 .font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)117 }118 .orixCard()119 }120121 private var scannerSheet: some View {122 NavigationStack {123 Group {124 if QRScannerView.isAvailable {125 QRScannerView { payload in126 showScanner = false127 handleQR(payload)128 }129 .ignoresSafeArea()130 } else {131 ORIXEmptyState(systemName: "camera.badge.ellipsis", title: "Camera not available",132 message: "Allow camera access for ORIX Secure in Settings, or pick a photo of the QR code instead.") {133 Button("Open Settings") { openSettings() }.buttonStyle(.orixSecondary).frame(maxWidth: 240)134 }135 }136 }137 .navigationTitle("Scan QR Code")138 .navigationBarTitleDisplayMode(.inline)139 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { showScanner = false } } }140 }141 }142143 // MARK: Actions144145 /// Asks for the camera the first time the scanner is opened, then shows it (or the explanation if access is off).146 private func openScanner() {147 Task {148 if AVCaptureDevice.authorizationStatus(for: .video) == .notDetermined {149 _ = await AVCaptureDevice.requestAccess(for: .video)150 model.refresh()151 }152 showScanner = true153 }154 }155156 private func consumePending() {157 guard let link = router.pendingLink else { return }158 router.pendingLink = nil159 input = link160 analyze()161 }162163 private func analyze() {164 focused = false165 qr = nil166 notice = nil167 saved = false168 let text = input.trimmingCharacters(in: .whitespacesAndNewlines)169 guard !text.isEmpty else { return }170 let found = extractURLs(from: text)171 // A single token is analysed as typed, so that malformed links are reported rather than skipped.172 let target = text.contains(where: \.isWhitespace) ? found.first : text173 guard let target else {174 analysis = nil175 others = []176 notice = String(localized: "No link was found in this text.")177 return178 }179 analysis = analyzer.analyze(target)180 others = found.filter { $0 != target }181 if settings.keepLinkHistory, let analysis { save(analysis) }182 ORIXHaptics.tick()183 }184185 private func handleQR(_ payload: String) {186 let decoded = QRPayload(decoding: payload, analyzer: analyzer)187 qr = decoded188 saved = false189 notice = nil190 others = []191 if let url = decoded.urlAnalysis {192 analysis = url193 input = url.input194 } else {195 analysis = decoded.embeddedURLAnalyses.first196 input = ""197 }198 ORIXHaptics.tick()199 }200201 private func readQR(from item: PhotosPickerItem) async {202 defer { photo = nil }203 guard let data = try? await item.loadTransferable(type: Data.self) else {204 notice = String(localized: "The photo could not be read.")205 return206 }207 let payloads = await QRImageReader.payloads(in: data)208 if let first = payloads.first { handleQR(first) } else {209 analysis = nil210 qr = nil211 notice = String(localized: "No QR code was found in this photo.")212 }213 }214215 private func save(_ analysis: URLAnalysis) {216 var report = analysis.reportDocument()217 report.generator = ReportBuilder.generator218 saved = model.store.save(report)219 }220221 // MARK: Result222223 private func qrCard(_ payload: QRPayload) -> some View {224 VStack(alignment: .leading, spacing: ORIX.Space.sm) {225 Label("QR code content", systemImage: "qrcode").font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)226 ForEach(Array(payload.fields.enumerated()), id: \.offset) { _, field in227 ReadingRow(label: field.label, value: .measured(field.value))228 }229 if !payload.findings.isEmpty { FindingList(findings: payload.findings) }230 }231 .orixCard()232 .accessibilityElement(children: .combine)233 .accessibilityIdentifier("link.qr")234 }235236 @ViewBuilder private func result(_ analysis: URLAnalysis) -> some View {237 VStack(alignment: .leading, spacing: ORIX.Space.sm) {238 HStack(spacing: ORIX.Space.sm) {239 Image(systemName: analysis.level.symbol).font(.system(size: 30)).foregroundStyle(analysis.level.tint).accessibilityHidden(true)240 VStack(alignment: .leading, spacing: 2) {241 Text(verbatim: analysis.level.title).font(.orixTitle).foregroundStyle(ORIX.Palette.textPrimary)242 Text("Structural score \(analysis.score) of \(URLRiskScoring.maximumScore) · heuristic").font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)243 }244 }245 .accessibilityElement(children: .combine)246 .accessibilityIdentifier("link.level")247 Text(verbatim: analysis.summary).font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)248 if analysis.level == .noSignals || analysis.level == .low {249 Label("Few or no signals is not proof that a link is harmless: the page itself was not inspected.", systemImage: "info.circle")250 .font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)251 }252 }253 .frame(maxWidth: .infinity, alignment: .leading)254 .orixCard()255256 if analysis.isParsed {257 ORIXSectionHeader("Where it really goes")258 VStack(spacing: 0) {259 anatomy(String(localized: "Destination domain"), analysis.registrableDomain ?? analysis.host)260 if let ascii = analysis.registrableDomain, let unicode = analysis.unicodeRegistrableDomain, unicode != ascii {261 anatomy(String(localized: "How that domain is displayed"), unicode)262 }263 if let host = analysis.host, let unicode = analysis.unicodeHost, unicode != host {264 anatomy(String(localized: "Full host as encoded (Punycode)"), host)265 anatomy(String(localized: "Full host as displayed"), unicode)266 } else if analysis.host != analysis.registrableDomain {267 anatomy(String(localized: "Full host"), analysis.host)268 }269 if !analysis.subdomainLabels.isEmpty { anatomy(String(localized: "Sub-domains"), analysis.subdomainLabels.joined(separator: " · ")) }270 anatomy(String(localized: "Scheme"), analysis.scheme.map { analysis.schemeWasAssumed ? String(localized: "\($0) (assumed)") : $0 })271 if let port = analysis.port { anatomy(String(localized: "Port"), "\(port)") }272 if let ip = analysis.ipLiteral { anatomy(String(localized: "IP address"), ip.canonical) }273 if !analysis.path.isEmpty, analysis.path != "/" { anatomy(String(localized: "Path"), analysis.path) }274 if !analysis.queryItems.isEmpty { anatomy(String(localized: "Parameters"), analysis.queryItems.map(\.name).joined(separator: ", ")) }275 }276 .orixCard(padding: ORIX.Space.sm)277 .accessibilityElement(children: .combine)278 .accessibilityIdentifier("link.anatomy")279 }280281 let findings = analysis.findings282 ORIXSectionHeader(findings.isEmpty ? "Signals" : "Signals (\(findings.count))")283 if findings.isEmpty {284 Text("None of the structural checks fired.").font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)285 .frame(maxWidth: .infinity, alignment: .leading).orixCard()286 } else {287 FindingList(findings: findings)288 }289 LimitsCard(title: "How the level is computed", items: analysis.methodology)290 LimitsCard(title: "What was not inspected", items: analysis.notInspected)291 Button { save(analysis); ORIXHaptics.success() } label: { Label(saved ? "Report Saved" : "Save as Report", systemImage: saved ? "checkmark" : "square.and.arrow.down") }292 .buttonStyle(.orixSecondary)293 .disabled(saved)294 .accessibilityIdentifier("link.save")295 }296297 @ViewBuilder private func anatomy(_ label: String, _ value: String?) -> some View {298 if let value, !value.isEmpty {299 VStack(alignment: .leading, spacing: 2) {300 Text(verbatim: label).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)301 Text(verbatim: value).font(.orixMono).foregroundStyle(ORIX.Palette.textPrimary).textSelection(.enabled)302 }303 .padding(.vertical, 6)304 .frame(maxWidth: .infinity, alignment: .leading)305 .accessibilityElement(children: .combine)306 }307 }308}309