SPB Git

Repository Public License

AgentClassifiers.swift 17.6 KB 248 lines swift

1import Diagnostics2import Foundation34private func compile(_ pattern: String, options: NSRegularExpression.Options = [.caseInsensitive]) -> NSRegularExpression? {5    try? NSRegularExpression(pattern: pattern, options: options)6}78private func firstMatch(_ regex: NSRegularExpression, in text: String) -> String? {9    guard let match = regex.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)), let range = Range(match.range, in: text) else { return nil }10    return String(text[range])11}1213// MARK: - Sensitive actions1415/// Kinds of action that need the user's specific confirmation.16public enum SensitiveActionCategory: String, Sendable, Hashable, Codable, CaseIterable {17    case purchase, payment, subscription, publishing, sendingMessage, accountChange, authentication, settingsChange, deletion, consent1819    public var label: String {20        switch self {21        case .purchase: "a purchase or an order"22        case .payment: "a payment"23        case .subscription: "a subscription, booking or donation"24        case .publishing: "publishing content"25        case .sendingMessage: "sending a message or a form"26        case .accountChange: "an account change"27        case .authentication: "signing in or out"28        case .settingsChange: "saving or changing settings"29        case .deletion: "deleting or cancelling something"30        case .consent: "accepting or confirming something"31        }32    }33}3435/// Deterministic keyword classifier for the label of a control (English and French). It errs on the side of asking:36/// "Order history" is flagged. Input is case- and diacritic-folded, so "Régler" and "regler" are the same.37public enum SensitiveActionClassifier {38    private static let terms: [(SensitiveActionCategory, [String])] = [39        (.payment, ["pay", "pay now", "payment", "paypal", "apple pay", "google pay", "checkout", "check out", "proceed to checkout", "wire", "transfer",40                    "payer", "paiement", "regler", "reglement", "passer a la caisse", "caisse", "virement", "transferer"]),41        (.purchase, ["buy", "buy now", "buy it now", "purchase", "order", "order now", "place order", "place your order", "add to cart", "add to basket",42                     "add to bag", "preorder", "pre-order", "bid", "acheter", "achat", "commander", "commande", "passer la commande",43                     "ajouter au panier", "panier", "precommander", "encherir"]),44        (.authentication, ["sign in", "signin", "log in", "login", "log on", "sign out", "signout", "log out", "logout", "continue with google",45                           "continue with apple", "continue with facebook", "se connecter", "connexion", "s'identifier", "identifiez-vous",46                           "se deconnecter", "deconnexion", "ouvrir une session"]),47        (.accountChange, ["sign up", "signup", "register", "create account", "create an account", "change password", "reset password", "update password",48                          "change email", "verify", "link account", "connect account", "creer un compte", "ouvrir un compte", "changer le mot de passe",49                          "reinitialiser le mot de passe", "mot de passe", "verifier", "associer"]),50        (.deletion, ["delete", "remove", "erase", "clear", "cancel", "cancel subscription", "unsubscribe", "deactivate", "close account", "terminate",51                     "revoke", "discard", "reset", "supprimer", "effacer", "retirer", "enlever", "annuler", "se desabonner", "desabonner",52                     "resilier", "desactiver le compte", "fermer le compte", "revoquer", "reinitialiser"]),53        (.subscription, ["subscribe", "subscription", "start trial", "free trial", "start free trial", "upgrade", "donate", "donation", "book", "book now",54                         "reserve", "enroll", "enrol", "join", "join now", "s'abonner", "abonner", "abonnement", "essai gratuit", "reserver",55                         "reservation", "faire un don", "don", "s'inscrire", "inscription", "adherer"]),56        (.publishing, ["post", "publish", "tweet", "share", "reply", "comment", "upload", "review", "rate", "publier", "poster", "partager", "repondre",57                       "commenter", "televerser", "noter", "evaluer"]),58        (.sendingMessage, ["send", "send message", "submit", "contact", "apply", "apply now", "message", "email", "invite", "envoyer", "soumettre",59                           "transmettre", "postuler", "candidater", "inviter", "contacter"]),60        (.settingsChange, ["save", "save changes", "save settings", "update", "apply changes", "enable", "disable", "turn on", "turn off", "enregistrer",61                           "sauvegarder", "mettre a jour", "appliquer", "activer", "desactiver", "modifier"]),62        (.consent, ["accept", "accept all", "agree", "i agree", "allow", "allow all", "authorize", "authorise", "grant", "confirm", "approve", "yes",63                    "ok", "continue", "proceed", "accepter", "tout accepter", "j'accepte", "autoriser", "confirmer", "valider", "approuver", "oui",64                    "continuer", "poursuivre", "d'accord"]),65    ]6667    private static let rules: [(SensitiveActionCategory, NSRegularExpression)] = terms.compactMap { category, words in68        let alternation = words.sorted { $0.count > $1.count }.map { NSRegularExpression.escapedPattern(for: $0).replacingOccurrences(of: " ", with: #"\s+"#) }69            .joined(separator: "|")70        // Unicode-aware boundaries: a keyword must not be part of a longer word ("payload" is not "pay").71        return compile(#"(?<![\p{L}\p{N}])(?:"# + alternation + #")(?![\p{L}\p{N}])"#).map { (category, $0) }72    }7374    /// The first matching category in priority order (money first), or `nil` for an ordinary control.75    public static func classify(_ label: String) -> SensitiveActionCategory? {76        let folded = AgentText.fold(String(label.prefix(400)))77        guard !folded.isEmpty else { return nil }78        for (category, regex) in rules where firstMatch(regex, in: folded) != nil { return category }79        return nil80    }81}8283// MARK: - Secret fields8485/// The runtime's own check that a form field holds a secret, independent of the kind the host reported.86public enum SecretFieldClassifier {87    private static let autocompleteTokens: Set<String> = [88        "current-password", "new-password", "one-time-code", "cc-number", "cc-csc", "cc-exp", "cc-exp-month", "cc-exp-year", "cc-name", "cc-type",89        "webauthn",90    ]91    private static let pattern = compile(92        #"pass(word|wd|phrase|code)?\b|\bpwd\b|mot\s*de\s*passe|\bmdp\b|\bpin\b|\bnip\b|secret|"#93        + #"card\s*(number|no|num)\b|cardnumber|ccnum|cc[-_]?(number|csc|exp)|credit\s*card|debit\s*card|carte\s*(de\s*)?(credit|debit|bancaire)|numero\s*de\s*carte|"#94        + #"\bcvv2?\b|\bcvc2?\b|\bcsc\b|security\s*code|code\s*de\s*securite|cryptogramme|expir|\biban\b|"#95        + #"\botp\b|\btotp\b|\b2fa\b|\bmfa\b|one[\s-]*time|verification\s*code|code\s*de\s*verification|code\s*a\s*usage\s*unique|authenticator|sms\s*code|"#96        + #"social\s*security|\bssn\b|assurance\s*sociale|\bnas\b"#)9798    public static func isSecret(_ field: AgentFormField) -> Bool {99        if field.kind.isSecret { return true }100        if field.htmlType.lowercased() == "password" { return true }101        let tokens = field.autocomplete.lowercased().split(whereSeparator: { $0.isWhitespace }).map(String.init)102        if tokens.contains(where: autocompleteTokens.contains) { return true }103        guard let pattern else { return true }104        let described = AgentText.fold("\(field.name) \(field.label)".replacingOccurrences(of: "_", with: " ").replacingOccurrences(of: "-", with: " "))105        return firstMatch(pattern, in: described) != nil106    }107108    static let mask = "••••••"109110    /// The value as it may be shown to the model or in a confirmation.111    public static func displayValue(of field: AgentFormField) -> String? {112        guard let value = field.value else { return nil }113        if value.isEmpty { return "" }114        return isSecret(field) ? mask : ResultSanitizer.redact(value)115    }116}117118// MARK: - CAPTCHA and sign-in walls119120/// Detects, from the outline of a page, the things the agent must never try to get past.121public enum WallDetector {122    private static let captcha = compile(123        #"captcha|recaptcha|hcaptcha|turnstile|i\s*(am|'m)\s*not\s*a\s*robot|je\s*ne\s*suis\s*pas\s*un\s*robot|"#124        + #"(verify|prove|confirm)\s*(that\s*)?(you\s*are|you're)\s*(a\s*)?human|verif\w*\s*que\s*vous\s*(n')?etes\s*(pas\s*)?(un\s*)?(humain|robot)|"#125        + #"are\s*you\s*a\s*robot|etes[\s-]*vous\s*un\s*robot|human\s*verification|verification\s*humaine|security\s*check|controle\s*de\s*securite|"#126        + #"unusual\s*traffic|trafic\s*inhabituel|checking\s*your\s*browser|just\s*a\s*moment|select\s*all\s*(images|squares)|"#127        + #"selectionnez\s*toutes\s*les\s*images|press\s*and\s*hold"#)128    private static let authentication = compile(129        #"(sign|log)\s*in\s*to\s*(continue|view|access|read)|(please\s*)?(sign|log)\s*in\s*(required|first)|login\s*required|authentication\s*required|"#130        + #"session\s*(has\s*)?expired|connectez[\s-]*vous\s*pour|veuillez\s*vous\s*(connecter|identifier)|connexion\s*requise|authentification\s*requise|"#131        + #"session\s*(a\s*)?expire|two[\s-]*factor|verification\s*en\s*deux\s*etapes|enter\s*the\s*code\s*(we\s*)?sent"#)132133    public static func detect(in outline: AgentPageOutline) -> [AgentChallenge] {134        var found = outline.challenges135        var kinds = Set(found.map(\.kind))136        func add(_ kind: AgentChallengeKind, _ evidence: String) {137            guard kinds.insert(kind).inserted else { return }138            found.append(AgentChallenge(kind: kind, evidence: AgentText.singleLine(evidence, limit: 100)))139        }140        var texts = [outline.info.title] + outline.headings.map(\.text) + outline.buttons.map(\.text)141        texts += outline.forms.flatMap { [$0.submitLabel] + $0.fields.flatMap { [$0.label, $0.name] } }142        // Links are scanned by address too: CAPTCHA widgets are recognisable by where they point.143        texts += outline.links.prefix(200).flatMap { [$0.text, $0.href?.host() ?? ""] }144        for text in texts {145            let folded = AgentText.fold(String(text.prefix(300)))146            if let captcha, let hit = firstMatch(captcha, in: folded) { add(.captcha, hit) }147            if let authentication, let hit = firstMatch(authentication, in: folded) { add(.authentication, hit) }148        }149        // A one-time-code field is a second factor: only the user can answer it.150        if outline.forms.contains(where: { $0.fields.contains { $0.kind == .oneTimeCode || $0.autocomplete.lowercased().contains("one-time-code") } }) {151            add(.authentication, "one-time code field")152        }153        return found154    }155156    /// Whether the form is a sign-in step (password or one-time code): submitting it is the user's job.157    public static func isAuthenticationForm(_ form: AgentForm) -> Bool {158        form.fields.contains { field in159            field.kind == .password || field.kind == .oneTimeCode || field.htmlType.lowercased() == "password"160                || field.autocomplete.lowercased().contains("password") || field.autocomplete.lowercased().contains("one-time-code")161        }162    }163}164165// MARK: - Injection heuristic166167public struct InjectionFinding: Sendable, Hashable, Codable {168    public enum Category: String, Sendable, Hashable, Codable, CaseIterable {169        case overridesInstructions, impersonatesRole, requestsToolUse, requestsSecrets, exfiltration, forgedEnvelope170171        public var label: String {172            switch self {173            case .overridesInstructions: "tries to override the agent's instructions"174            case .impersonatesRole: "pretends to be the system, the developer or the assistant"175            case .requestsToolUse: "tells the agent to use a tool"176            case .requestsSecrets: "asks for passwords, keys or private data"177            case .exfiltration: "asks for data to be sent to an address"178            case .forgedEnvelope: "imitates the markers the app puts around page data"179            }180        }181    }182183    public var category: Category184    /// The matched text, shortened and redacted.185    public var excerpt: String186}187188/// Flags instruction-like text in page content (English and French). A finding never changes how the content is189/// handled — it is data either way — it only annotates the step for the user and adds a warning for the model.190/// The patterns are a heuristic: an absence of findings is not evidence that content is harmless.191public enum InjectionScanner {192    static let maxScannedCharacters = 80_000193194    private static let rules: [(InjectionFinding.Category, NSRegularExpression)] = {195        let toolNames = AgentToolName.allCases.flatMap { [$0.rawValue, $0.wireName] }.filter { $0 != "finish" }196            .map { NSRegularExpression.escapedPattern(for: $0) }.joined(separator: "|")197        let patterns: [(InjectionFinding.Category, String)] = [198            (.overridesInstructions, #"\b(ignore|disregard|forget|override|bypass)\b.{0,40}\b(previous|prior|above|earlier|all|any|your|the|system|safety)\b.{0,30}\b(instructions?|prompts?|rules?|directives?|guidelines?|constraints?)"#),199            (.overridesInstructions, #"\b(ignore[zr]?|oublie[zr]?|ne\s+ten(ez|ir)\s+pas\s+compte|ne\s+tiens\s+pas\s+compte|contourne[zr]?)\b.{0,50}\b(instructions?|consignes?|directives?|regles?)"#),200            (.overridesInstructions, #"\b(new|updated|revised|real|actual)\s+(system\s+)?(instructions?|prompt|directives?)\s*[:\-]|\bnouvelles?\s+(instructions?|consignes?)\s*[:\-]"#),201            (.overridesInstructions, #"\byou\s+are\s+now\b|\bfrom\s+now\s+on\s*,?\s+you\b|\bdeveloper\s+mode\b|\bjailbr(eak|oken)\b|\b(tu\s+es|vous\s+etes)\s+(maintenant|desormais)\b|\bmode\s+developpeur\b"#),202            (.overridesInstructions, #"\bdo\s+not\s+(tell|inform|mention|reveal).{0,30}\b(user|human|person)\b|\bne\s+(dis|dites|revele[zs]?)\s+(rien|pas).{0,30}\butilisateur"#),203            (.overridesInstructions, #"\b(raise|increase|remove|lift|disable|augmente[zr]?|supprime[zr]?|desactive[zr]?)\b.{0,20}\b(budget|step\s+limit|token\s+limit|time\s+limit|limite\s+de\s+(pas|temps|jetons)|allow[\s-]?list|safety\s+(limits?|rules?)|restrictions|permissions)\b"#),204            (.impersonatesRole, #"(^|\n|[>\]\)]\s*)\s*#{0,3}\s*\[?(system|developer|assistant|systeme|developpeur)\]?\s*(override|message|prompt|note)?\s*:"#),205            (.impersonatesRole, #"\b(ai|llm)\s+(agents?|assistants?|models?)\s+(reading|visiting|processing)\b|\bagents?\s+ia\s+(qui\s+lis|lisant)"#),206            (.requestsToolUse, #"\b(call|invoke|use|run|execute|trigger|appelle[zr]?|utilise[zr]?|execute[zr]?)\b.{0,60}("# + toolNames + #")"#),207            (.requestsToolUse, #"\b(call|invoke|use|run|execute|trigger)\b.{0,30}\b(tool|function)\b.{0,40}\b(immediately|at\s+once|right\s+(away|now)|now)\b"#),208            (.requestsToolUse, #""(tool|tool_name|function|name)"\s*:\s*"[a-z_.]+"\s*,\s*"(arguments|parameters|input)"\s*:|<\s*/?\s*(tool_call|function_call|tool_use|invoke)\b"#),209            (.requestsSecrets, #"\b(reveal|print|show|send|give|share|leak|output|include|append|provide|exfiltrate|copy)\b.{0,60}\b(api[\s_\-]?keys?|passwords?|secrets?|tokens?|credentials?|cookies?|browsing\s+history|history|system\s+prompt|private\s+keys?)\b"#),210            (.requestsSecrets, #"\b(revele[zr]?|envoie[zr]?|envoye[zr]|donne[zr]?|affiche[zr]?|transmet(s|tez|tre)?)\b.{0,60}\b(cles?(\s+api)?|mots?\s+de\s+passe|jetons?|secrets?|temoins|cookies?|historique)\b"#),211            (.exfiltration, #"\b(send|post|upload|forward|transmit|submit|exfiltrate|envoie[zr]?|envoye[zr]|transmet(s|tez|tre)?)\b.{0,60}\b(conversation|chat|history|data|contents?|answers?|results?|keys?|passwords?|secrets?|donnees|historique|contenu)\b.{0,60}\b(to|a|vers)\b.{0,20}https?://"#),212            (.exfiltration, #"\b(navigate|go|open|visit|fetch|load|request|aller|ouvr(e|ez|ir)|visite[zr]?|navigue[zr]?)\b.{0,40}https?://[^\s"'<>]+[?&#][a-z_\-]{1,24}=\s*($|[\{\[<$]|%7b|%3c|YOUR|INSERT)"#),213            (.exfiltration, #"!\[[^\]]{0,80}\]\(\s*https?://[^)\s]*\?[^)\s]*="#),214            (.forgedEnvelope, #"<<<\s*/?\s*(END_)?ORIX_|‹‹‹\s*(END_)?ORIX_|\b(END_)?ORIX_DATA\b|\bsource_id\s*:\s*\d+\s*\|"#),215        ]216        return patterns.compactMap { category, pattern in217            compile(pattern, options: [.caseInsensitive, .anchorsMatchLines, .dotMatchesLineSeparators]).map { (category, $0) }218        }219    }()220221    /// Removes zero-width and bidirectional controls and folds case and accents, so that hiding an instruction from a222    /// keyword match takes more than an invisible character.223    static func normalise(_ text: String) -> String {224        var scalars = String.UnicodeScalarView()225        for scalar in text.unicodeScalars.prefix(maxScannedCharacters) {226            switch scalar.value {227            case 0x200B...0x200F, 0x202A...0x202E, 0x2060...0x2064, 0xFEFF, 0x00AD: continue228            default: scalars.append(scalar)229            }230        }231        return String(scalars).folding(options: [.diacriticInsensitive, .widthInsensitive], locale: Locale(identifier: "en_US_POSIX"))232    }233234    public static func scan(_ text: String) -> [InjectionFinding] {235        let normalised = normalise(text)236        guard normalised.count >= 8 else { return [] }237        var findings: [InjectionFinding] = []238        var seen = Set<InjectionFinding.Category>()239        let range = NSRange(normalised.startIndex..., in: normalised)240        for (category, regex) in rules where !seen.contains(category) {241            guard let match = regex.firstMatch(in: normalised, range: range), let matched = Range(match.range, in: normalised) else { continue }242            seen.insert(category)243            findings.append(InjectionFinding(category: category, excerpt: Redactor.redact(AgentText.singleLine(String(normalised[matched]), limit: 140))))244        }245        return findings246    }247}248
Files main
Menu

Theme