SPB Git

Repository Public

CoreTests.swift 27.0 KB 345 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka Admin iOS9// File             : LouKaAdminTests/CoreTests.swift10// Description      : logique pure — base64url, options et `credential` WebAuthn11//                    sur des données fixes, adresse d'activation, trousseau,12//                    bornes de session et verrouillage, courrier (réponse,13//                    citation, destinataires, HTML lu sans rien exécuter), vue14//                    isolée, décodage des réponses réelles.15// Module           : LouKaAdminTests16// Repository       : https://git.spboucher.ai/lou-ka-admin-ios17// Project Website  : https://www.lou-ka.com18// Created          : 2026-11-3019// Last Modified    : 2026-11-3020//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation94import Security95import Testing96import WebKit97@testable import LouKaAdmin9899@Suite("Clés d'accès : base64url, options, credential")100struct WebAuthnTests {101    @Test("base64url : sans remplissage, « - » et « _ », aller-retour ; chaînes refusées")102    func base64url() {103        #expect(Base64URL.encode(Data([0xFB, 0xFF, 0xFE])) == "-__-")104        #expect(Base64URL.encode(Data([0x00])) == "AA" && Base64URL.encode(Data()) == "")105        #expect(Base64URL.decode("-__-") == Data([0xFB, 0xFF, 0xFE]) && Base64URL.decode("AA") == Data([0]) && Base64URL.decode("AA==") == Data([0]))106        #expect(Base64URL.decode("+/8=") == nil, "le base64 ordinaire n'est pas du base64url")107        #expect(Base64URL.decode("pas du base64 !") == nil && Base64URL.decode("A") == nil)108        for n in [1, 2, 3, 16, 31, 32, 64, 65] {109            let d = Data((0..<n).map { UInt8(($0 * 37 + 11) % 256) })110            #expect(Base64URL.decode(Base64URL.encode(d)) == d && !Base64URL.encode(d).contains("="))111        }112    }113114    @Test("options de connexion : réponse réelle de la préproduction")115    func assertionOptions() throws {116        let json = try JSONDecoder().decode(JSONValue.self, from: Data(#"{"challenge":"J5LYnNhHTG9NULci4qETuIZa3aqRdbQ1yVBTm-rzWpwpbuW7A0_hcrGXEsHqF2ybgwqfj7vapvzbUtmn138btQ","timeout":60000,"rpId":"louka-comptes.51-161-112-61.sslip.io","allowCredentials":[],"userVerification":"required"}"#.utf8))117        let o = try PasskeyAssertionOptions(json: json, defaultRPID: "www.lou-ka.com")118        #expect(o.challenge.count == 64 && o.rpID == "louka-comptes.51-161-112-61.sslip.io" && o.allowCredentials.isEmpty && o.userVerification == "required")119        #expect(Base64URL.encode(o.challenge) == "J5LYnNhHTG9NULci4qETuIZa3aqRdbQ1yVBTm-rzWpwpbuW7A0_hcrGXEsHqF2ybgwqfj7vapvzbUtmn138btQ")120        let named = try PasskeyAssertionOptions(json: .object(["challenge": .string(Base64URL.encode(Data(repeating: 7, count: 32))),121                                                               "allowCredentials": .array([.object(["id": .string("AQID"), "type": .string("public-key")]), .object(["id": .string("pas valide !")])])]), defaultRPID: "www.lou-ka.com")122        #expect(named.rpID == "www.lou-ka.com" && named.allowCredentials == [Data([1, 2, 3])], "domaine par défaut ; une clé illisible est ignorée")123        #expect(throws: WebAuthnError.self) { try PasskeyAssertionOptions(json: .object([:]), defaultRPID: "x") }124        #expect(throws: WebAuthnError.self) { try PasskeyAssertionOptions(json: .object(["challenge": .string("AQID")]), defaultRPID: "x") }125    }126127    @Test("options d'enregistrement : user.id en base64url, domaine, clés à exclure")128    func registrationOptions() throws {129        let json = try JSONDecoder().decode(JSONValue.self, from: Data(#"{"rp":{"id":"www.lou-ka.com","name":"Lou-Ka"},"user":{"id":"MWRmOWFmN2UxMTA0","name":"lea@lou-ka.com","displayName":"Léa Tremblay"},"challenge":"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8","pubKeyCredParams":[{"type":"public-key","alg":-7}],"excludeCredentials":[{"id":"_-8","type":"public-key"}],"authenticatorSelection":{"residentKey":"required","userVerification":"required"}}"#.utf8))130        let o = try PasskeyRegistrationOptions(json: json, defaultRPID: "ailleurs.test")131        #expect(o.rpID == "www.lou-ka.com" && o.userName == "lea@lou-ka.com" && o.displayName == "Léa Tremblay")132        #expect(String(data: o.userID, encoding: .utf8) == "1df9af7e1104" && o.challenge == Data(0..<32) && o.excludeCredentials == [Data([0xFF, 0xEF])])133        #expect(throws: WebAuthnError.self) { try PasskeyRegistrationOptions(json: .object(["challenge": .string(Base64URL.encode(Data(repeating: 1, count: 32)))]), defaultRPID: "x") }134    }135136    @Test("credential de connexion : format JSON de WebAuthn, tout en base64url")137    func assertionCredential() throws {138        let id = Data([0xDE, 0xAD, 0xBE, 0xEF]), client = Data(#"{"type":"webauthn.get","challenge":"abc","origin":"https://www.lou-ka.com"}"#.utf8)139        let c = WebAuthnCredential.assertion(credentialID: id, clientDataJSON: client, authenticatorData: Data([1, 2, 3, 0xFF]), signature: Data([0x30, 0x45, 0xFB]), userHandle: Data("u1".utf8))140        let o = try #require(try JSONSerialization.jsonObject(with: JSONEncoder().encode(c)) as? [String: Any])141        #expect(o["id"] as? String == "3q2-7w" && o["rawId"] as? String == "3q2-7w" && o["type"] as? String == "public-key")142        let r = try #require(o["response"] as? [String: Any])143        #expect(Set(r.keys) == ["clientDataJSON", "authenticatorData", "signature", "userHandle"])144        #expect(r["authenticatorData"] as? String == "AQID_w" && r["signature"] as? String == "MEX7" && r["userHandle"] as? String == "dTE")145        #expect(Base64URL.decode(r["clientDataJSON"] as? String ?? "") == client)146        #expect((o["clientExtensionResults"] as? [String: Any])?.isEmpty == true)147        let anonymous = WebAuthnCredential.assertion(credentialID: id, clientDataJSON: client, authenticatorData: Data([1]), signature: Data([2]), userHandle: nil)148        #expect(anonymous["response"]?["userHandle"] == nil, "pas d'identifiant d'utilisateur : le champ est omis")149        #expect(!String(data: try JSONEncoder().encode(c), encoding: .utf8)!.contains("="), "aucun remplissage base64")150    }151152    @Test("credential d'enregistrement : clientDataJSON et attestationObject")153    func registrationCredential() throws {154        let c = WebAuthnCredential.registration(credentialID: Data([9, 8, 7]), clientDataJSON: Data("{}".utf8), attestationObject: Data([0xA3, 0x63, 0x66]))155        #expect(c["id"]?.string == "CQgH" && c["type"]?.string == "public-key")156        #expect(c["response"]?["clientDataJSON"]?.string == "e30" && c["response"]?["attestationObject"]?.string == "o2Nm")157        #expect(c["response"]?["signature"] == nil && c["response"]?["authenticatorData"] == nil)158    }159160    @Test("adresse d'activation : adresse entière ou jeton seul")161    func activation() {162        let token = "kq3ZpX9-bM_2aT7cYw8Lr5Nd4Hs1"163        #expect(ActivationLink.token(from: "https://www.lou-ka.com/admin/activation?jeton=\(token)") == token)164        #expect(ActivationLink.token(from: "  https://louka-comptes.51-161-112-61.sslip.io/admin/activation?x=1&jeton=\(token)\n") == token)165        #expect(ActivationLink.token(from: token) == token && ActivationLink.token(from: " \(token) ") == token)166        for bad in ["", "   ", "https://www.lou-ka.com/admin/activation", "https://www.lou-ka.com/admin/activation?jeton=", "court", "jeton avec espace 1234567890", "https://x.test/?jeton=<script>alert(1)</script>aaaaaaaa"] {167            #expect(ActivationLink.token(from: bad) == nil, "\(bad)")168        }169    }170}171172@Suite("Session : trousseau, bornes, verrouillage")173struct SessionLogicTests {174    @Test("trousseau : lisible appareil déverrouillé seulement, lié à cet appareil, non synchronisé")175    func keychain() {176        let k = KeychainStore(service: "com.spboucher.louka.admin.tests.\(UUID().uuidString)")177        defer { k.delete("session.token") }178        #expect(k.read("session.token") == nil && k.set("session.token", "jeton-A") && k.string("session.token") == "jeton-A")179        #expect(k.accessibility("session.token") == (kSecAttrAccessibleWhenUnlockedThisDeviceOnly as String))180        #expect(k.set("session.token", "jeton-B") && k.string("session.token") == "jeton-B")181        k.delete("session.token")182        #expect(k.read("session.token") == nil)183    }184185    @Test("bornes : 12 h sans activité, 7 jours au plus")186    func window() {187        let t0 = Date(timeIntervalSince1970: 1_800_000_000)188        var w = SessionWindow(openedAt: t0, lastActivity: t0, idleHours: 12, maxHours: 168)189        #expect(!w.isExpired(now: t0.addingTimeInterval(11.9 * 3600)) && w.isExpired(now: t0.addingTimeInterval(12.1 * 3600)))190        w.lastActivity = t0.addingTimeInterval(167 * 3600)191        #expect(!w.isExpired(now: t0.addingTimeInterval(167.5 * 3600)) && w.isExpired(now: t0.addingTimeInterval(168.1 * 3600)), "même active, une session ne dépasse pas 7 jours")192    }193194    @Test("verrouillage : après quelques minutes à l'arrière-plan, jamais sans session")195    func lock() {196        let t0 = Date()197        #expect(!LockPolicy.shouldLock(backgroundedAt: nil, now: t0, signedIn: true))198        #expect(!LockPolicy.shouldLock(backgroundedAt: t0, now: t0.addingTimeInterval(LockPolicy.delay - 1), signedIn: true))199        #expect(LockPolicy.shouldLock(backgroundedAt: t0, now: t0.addingTimeInterval(LockPolicy.delay), signedIn: true))200        #expect(!LockPolicy.shouldLock(backgroundedAt: t0, now: t0.addingTimeInterval(3600), signedIn: false))201        #expect((60...600).contains(LockPolicy.delay), "quelques minutes")202    }203}204205@Suite("Courrier : réponse, citation, destinataires, HTML")206struct MailLogicTests {207    private let message = MailMessage(id: "msg_1", mailbox: "support@lou-ka.com", from: [MailPerson(email: "Lea@Example.org", name: "Léa Tremblay")],208                                      to: [MailPerson(email: "support@lou-ka.com")], subject: "Question sur mon compte", receivedAt: "2026-11-30T22:42:33Z",209                                      text: "Bonjour,\r\n\r\nJe n'arrive pas à me connecter.\r\nMerci.\r\n\r\n")210211    @Test("sujet d'une réponse : « Re: », jamais doublé")212    func subject() {213        #expect(MailLogic.replySubject("Question") == "Re: Question" && MailLogic.replySubject("Re: Question") == "Re: Question")214        #expect(MailLogic.replySubject("RE : Question") == "RE : Question" && MailLogic.replySubject("re:x") == "re:x")215        #expect(MailLogic.replySubject(nil) == "Re:" && MailLogic.replySubject("  Réunion  ") == "Re: Réunion")216    }217218    @Test("citation : chaque ligne précédée de « > », auteur et date")219    func quote() {220        let q = MailLogic.quote(message, when: "30 nov. 2026, 17 h 42")221        #expect(q == "\n\nLe 30 nov. 2026, 17 h 42, Léa Tremblay a écrit :\n> Bonjour,\n>\n> Je n'arrive pas à me connecter.\n> Merci.")222        #expect(MailLogic.quote(message, when: "").hasPrefix("\n\nLéa Tremblay a écrit :\n> Bonjour,"))223    }224225    @Test("réponse : part de la boîte qui a reçu, vers l'adresse de réponse si elle existe, avec reply_to_message_id")226    func reply() throws {227        let d = MailLogic.replyDraft(message, when: "hier")228        #expect(d.from == "support@lou-ka.com" && d.to == ["lea@example.org"] && d.subject == "Re: Question sur mon compte" && d.replyToMessageID == "msg_1")229        #expect(d.text.contains("> Je n'arrive pas à me connecter."))230        var m = message; m.replyTo = [MailPerson(email: "reponse@example.org")]231        #expect(MailLogic.replyDraft(m, when: "").to == ["reponse@example.org"])232        let body = try #require(try JSONSerialization.jsonObject(with: JSONEncoder().encode(d)) as? [String: Any])233        #expect(body["reply_to_message_id"] as? String == "msg_1" && body["from"] as? String == "support@lou-ka.com" && body["cc"] == nil)234    }235236    @Test("destinataires : virgules, points-virgules, « Nom <adresse> », doublons ; adresses plausibles")237    func recipients() {238        #expect(MailLogic.parseRecipients("a@x.ca, B@y.ca ; Léa Tremblay <c@z.ca>\na@x.ca") == ["a@x.ca", "b@y.ca", "c@z.ca"])239        #expect(MailLogic.parseRecipients("  ") == [])240        #expect(MailLogic.looksLikeEmail("support@lou-ka.com"))241        for bad in ["support", "support@", "@lou-ka.com", "a@b", "a b@c.ca", "a@b.c", "<a@b.ca>"] { #expect(!MailLogic.looksLikeEmail(bad), "\(bad)") }242    }243244    @Test("HTML lu comme du texte : scripts et styles écartés, balises retirées, entités décodées")245    func htmlToText() {246        let html = "<html><head><style>p{color:red}</style><script>alert('x')</script></head><body><p>Bonjour&nbsp;L&eacute;a,</p><div>Ligne 1<br>Ligne 2</div><!-- caché --><script type=\"text/javascript\">document.location='https://mal.test'</script><p>A &amp; B &lt;ok&gt;</p><img src=\"https://pisteur.test/p.gif\" onerror=\"alert(1)\"></body></html>"247        let t = MailLogic.htmlToText(html)248        #expect(t == "Bonjour Léa,\nLigne 1\nLigne 2\nA & B <ok>")249        #expect(!t.contains("alert") && !t.contains("mal.test") && !t.contains("pisteur") && !t.contains("color:red"))250        var m = MailMessage(id: "m", mailbox: "contact@lou-ka.com", text: "  \n", html: "<p>Seulement du HTML</p>")251        #expect(MailLogic.bodyText(m) == "Seulement du HTML")252        m.text = "Texte brut"253        #expect(MailLogic.bodyText(m) == "Texte brut", "la version texte l'emporte toujours")254    }255256    @Test("mise en forme : document isolé (aucun chargement, aucun script), vue sans JavaScript, navigation refusée")257    @MainActor258    func isolated() {259        let doc = MailLogic.isolatedHTMLDocument("<p>x</p>")260        #expect(doc.contains("default-src 'none'") && doc.contains("img-src data:") && doc.contains("form-action 'none'") && doc.contains("no-referrer"))261        #expect(!doc.contains("script-src") && doc.contains("pointer-events:none"), "aucune source de script n'est permise ; les liens sont inertes")262        let cfg = IsolatedWeb.configuration()263        #expect(cfg.defaultWebpagePreferences.allowsContentJavaScript == false && !cfg.websiteDataStore.isPersistent && cfg.dataDetectorTypes.isEmpty)264        #expect(IsolatedWeb.blockAllRule.contains(#""url-filter":".*""#) && IsolatedWeb.blockAllRule.contains(#""type":"block""#))265        #expect(IsolatedWeb.allows(URL(string: "about:blank"), type: .other) && IsolatedWeb.allows(nil, type: .other))266        #expect(!IsolatedWeb.allows(URL(string: "https://mal.test"), type: .linkActivated) && !IsolatedWeb.allows(URL(string: "https://mal.test"), type: .other))267        #expect(!IsolatedWeb.allows(URL(string: "about:blank"), type: .linkActivated) && !IsolatedWeb.allows(URL(string: "tel:911"), type: .formSubmitted))268    }269270    @Test("pièces jointes : nom de fichier sûr, tailles lisibles")271    func attachments() throws {272        func att(_ json: String) throws -> MailAttachment { try JSONDecoder().decode(MailAttachment.self, from: Data(json.utf8)) }273        let hostile = MailLogic.fileName(try att(#"{"id":"a","name":"../../etc/passwd","type":"text/plain"}"#))274        #expect(hostile == "etc-passwd" && !hostile.contains("/") && !hostile.contains("..") && !hostile.hasPrefix("."))275        #expect(MailLogic.fileName(try att(#"{"id":"a","name":"..","type":"application/pdf"}"#)) == "piece-jointe.pdf")276        #expect(!MailLogic.fileName(try att(#"{"id":"a","name":"a/b\\c.pdf"}"#)).contains("/"))277        #expect(MailLogic.fileName(try att(#"{"id":"a","name":null,"type":"message/rfc822","size":1259}"#)) == "piece-jointe.eml")278        #expect(MailLogic.fileName(try att(#"{"id":"a","filename":"Bail.pdf","content_type":"application/pdf"}"#)) == "Bail.pdf")279        #expect(MailLogic.size(650) == "650 o" && MailLogic.size(4290) == "4 Ko" && MailLogic.size(2_621_440) == "2,5 Mo" && MailLogic.size(nil) == "" && MailLogic.size(0) == "")280    }281}282283@Suite("Décodage des réponses réelles (préproduction, 2026-11-30)")284struct ModelTests {285    @Test("compte et chiffres")286    func me() throws {287        let me = try JSONDecoder().decode(Me.self, from: Data(#"{"admin":{"id":"1df9","name":"Essai Admin iOS","email":"essai-admin-ios@lou-ka.com","mailboxes":["contact@lou-ka.com","support@lou-ka.com"]},"stats":{"comptes":17,"gestionnaires_en_attente":0,"gestionnaires_approuves":2,"verifies":15,"sessions":56,"favoris":10,"recherches":0,"signalements_ouverts":40},"keys":[{"id":"MKFXswIsIi7Y","name":"Clé d'essai","created_at":1796096209,"used_at":null}],"mail":true,"futur":1}"#.utf8))288        #expect(me.admin.name == "Essai Admin iOS" && me.admin.mailboxes.count == 2 && me.stats.comptes == 17 && me.stats.signalementsOuverts == 40 && me.stats.gestionnairesApprouves == 2)289        #expect(me.keys.count == 1 && me.keys[0].usedAt == nil && me.mail)290    }291292    @Test("demande d'un gestionnaire : états, actions offertes, approbation exigeant un rattachement")293    func manager() throws {294        let r = try JSONDecoder().decode(ManagerRequest.self, from: Data(#"{"account_id":"4a54","email":"essai@cogir.net","name":"Essai Gestion","title":"","phone":"","company":"Cogir Immobilier","website":"https://www.cogir.net","domain":"cogir.net","source_id":"cogir","in_directory":true,"directory":{"name":"Cogir Immobilier","website":"https://www.cogir.net","listings":269},"status":"approuve","reason":"","requested_at":1796082158,"verified_at":1796082158,"decided_at":1796082158,"decided_by":"ligne de commande","last_login":1796095217}"#.utf8))295        #expect(r.status == .approved && r.title == nil && r.phone == nil && r.reason == nil && r.directory?.listings == 269 && r.canBeApproved && r.decidedBy == "ligne de commande")296        let outside = try JSONDecoder().decode(ManagerRequest.self, from: Data(#"{"account_id":"x","email":"a@b.ca","company":"Inconnue inc.","source_id":null,"in_directory":false,"directory":null,"status":"etat_futur"}"#.utf8))297        #expect(outside.status == .pending && !outside.canBeApproved && !outside.inDirectory, "état inconnu = attente ; hors annuaire = pas d'approbation")298        #expect(ManagerAction.available(for: .pending) == [.approve, .refuse] && ManagerAction.available(for: .approved).contains(.suspend) && ManagerAction.available(for: .suspended) == [.restore])299        #expect(ManagerAction.refuse.needsReason && ManagerAction.suspend.needsReason && !ManagerAction.approve.needsReason && !ManagerAction.restore.needsReason)300        #expect(ManagerFilter.allCases.map(\.rawValue) == ["en_attente", "approuve", "refuse", "suspendu", "toutes"])301    }302303    @Test("signalement : conversation effacée, messages, décision")304    func report() throws {305        let gone = try JSONDecoder().decode(Report.self, from: Data(#"{"id":40,"conversation_id":"161a","message_id":null,"by_role":"locataire","reason":"Pourriel ou sollicitation","created_at":1796095361,"handled_at":null,"handled_by":null,"decision":"","source_id":null,"manager_name":"","tenant":{"name":null,"email":null},"conversation_status":null,"messages":[]}"#.utf8))306        #expect(gone.isOpen && gone.conversationGone && gone.reporter == "le chercheur de logement" && gone.managerName == nil && gone.decisionLabel == nil)307        let live = try JSONDecoder().decode(Report.self, from: Data(#"{"id":41,"conversation_id":"c1","message_id":9,"by_role":"gestionnaire","reason":"Propos déplacés","created_at":1796095361,"handled_at":1796095400,"handled_by":"Léa","decision":"bloquer","source_id":"cogir","manager_name":"Cogir Immobilier","tenant":{"name":"Sam","email":"sam@example.org"},"conversation_status":"bloquee","messages":[{"id":9,"role":"locataire","author":"Sam","text":"<b>texte</b> [lien](https://x.test)","created_at":1796082175064},{"illisible":true}]}"#.utf8))308        #expect(!live.isOpen && !live.conversationGone && live.decisionLabel == "Conversation bloquée" && live.tenantEmail == "sam@example.org" && live.messages.count == 2)309        #expect(live.messages[0].text == "<b>texte</b> [lien](https://x.test)", "le texte d'un message est gardé tel quel")310    }311312    @Test("courrier : boîtes, dossiers, résumé, message, page")313    func mail() throws {314        let boxes = try JSONDecoder().decode(MailboxList.self, from: Data(#"{"mailboxes":[{"address":"contact@lou-ka.com","folders":[{"id":"f1","name":"Inbox","role":"inbox","total":2,"unread":1},{"id":"f2","name":"Drafts","role":"drafts","total":0,"unread":0}]}]}"#.utf8)).mailboxes315        #expect(boxes[0].unreadInbox == 1 && boxes[0].folder(role: "sent") == nil && MailFolder.label(role: "inbox") == "Boîte de réception")316        let page = try JSONDecoder().decode(MailPage.self, from: Data(#"{"data":[{"id":"msg_1","thread_id":"t","mailbox":"contact@lou-ka.com","from":[{"email":"MAILER-DAEMON@spboucher.ai","name":"Mail Delivery Subsystem"}],"to":[{"email":"contact@lou-ka.com","name":null}],"cc":[],"subject":"Failed to deliver message","preview":"Your message","received_at":"2026-11-30T22:42:33Z","size":4523,"unread":false,"starred":false,"has_attachment":true}],"next_cursor":null,"has_more":false}"#.utf8))317        #expect(page.data.count == 1 && !page.hasMore && page.nextCursor == nil && page.data[0].hasAttachment && page.data[0].date != nil)318        #expect(MailLogic.label(page.data[0].from.first) == "Mail Delivery Subsystem" && MailLogic.full(page.data[0].to[0]) == "contact@lou-ka.com")319        let m = try JSONDecoder().decode(MailMessage.self, from: Data(#"{"id":"msg_1","mailbox":"contact@lou-ka.com","from":[],"to":[],"subject":null,"text":"Corps\n","html":null,"attachments":[{"id":"att_1","name":null,"type":"message/delivery-status","size":650,"inline":false}],"auth":{"spf":null,"dkim":"pass","dmarc":null,"raw":null},"unread":true}"#.utf8))320        #expect(m.text == "Corps\n" && m.html == nil && m.attachments.count == 1 && m.dkim == "pass" && m.spf == nil && m.unread && MailLogic.label(m.from.first) == "Expéditeur inconnu")321    }322323    @Test("fiche personnalisée : brouillon, version publiée, équipe")324    func fiche() throws {325        let f = try JSONDecoder().decode(AdminFiche.self, from: Data(#"{"source_id":"cogir","draft":{"tagline":"Des logements bien tenus","about":"Un.\n\nDeux <b>x</b>.","contact":{"phone":"514 555-0100","website":"https://www.cogir.net","hours":[{"days":"Lun-ven","hours":"9 h à 17 h"}]},"social":{"facebook":"https://www.facebook.com/cogir","x":""},"highlights":[{"label":"Immeubles","value":"42"}],"services":["Entretien 24 h"],"policies":[{"title":"Animaux","text":"Chats acceptés."}],"faq":[{"q":"Chauffage ?","a":"Oui."}],"team":[{"name":"Essai","role":"Location","photo":null}],"gallery":[{"media":"m1","caption":"Le hall"}],"messaging":{"enabled":true,"auto_reply":"Merci.","response_time":"24 h"},"quick_replies":[{"title":"Visite","text":"Samedi."}]},"published":null,"dirty":true,"draft_updated_at":1796081673,"published_at":null,"hidden":true,"hidden_reason":"Contenu trompeur","media":[{"id":"m1"},{"id":"m2"}],"revisions":[],"team":[{"name":"Essai Gestion","email":"e@cogir.net","title":""}],"limits":{}}"#.utf8))326        let d = try #require(f.draft)327        #expect(f.published == nil && f.dirty && f.hidden && f.hiddenReason == "Contenu trompeur" && f.mediaCount == 2 && f.team.count == 1 && f.team[0].title == nil)328        #expect(d.tagline == "Des logements bien tenus" && d.about == "Un.\n\nDeux <b>x</b>." && d.phone == "514 555-0100" && d.hours.first?.title == "Lun-ven")329        #expect(d.social.map(\.title) == ["facebook"] && d.highlights.first?.text == "42" && d.faq.first?.title == "Chauffage ?" && d.team.first?.text == "Location")330        #expect(d.galleryCaptions == ["Le hall"] && d.autoReply == "Merci." && d.responseTime == "24 h" && d.quickReplies.count == 1 && !d.isEmpty)331    }332333    @Test("journal : libellés lisibles, action inconnue montrée telle quelle")334    func journal() throws {335        let items = try JSONDecoder().decode(ItemList<JournalEntry>.self, from: Data(#"{"items":[{"id":2,"admin":"Essai","action":"cle_enregistree","target":"","detail":"","at":1796096278},{"id":3,"admin":"Essai","action":"action_future","target":"x","detail":"y","at":1}]}"#.utf8)).items336        #expect(items[0].actionLabel == "Clé d'accès enregistrée" && items[1].actionLabel == "action future")337    }338339    @Test("adresses : seules http et https s'ouvrent")340    func urls() {341        #expect(safeWebURL("https://www.cogir.net") != nil && safeWebURL(" http://x.test/a ") != nil)342        for bad in ["javascript:alert(1)", "ftp://x.test", "www.cogir.net", "", "tel:5145550100", "https://"] { #expect(safeWebURL(bad) == nil, "\(bad)") }343    }344}345
Files main
Menu

Theme