diff --git a/README.md b/README.md index 943b94f..65e5eed 100644 --- a/README.md +++ b/README.md @@ -35,8 +35,8 @@ in any browser or app. - **Can type the code for you** (off by default). - **Works from the keyboard.** ⌃⌥⌘C copies the latest code. ⌃⌥⌘F opens search. - **Reads about 35 languages.** -- **Stays private.** Hidden from screen sharing, with optional blur and - clearing when the Mac locks. +- **Stays private.** Hidden from screen sharing, and can hide codes until + you point at them and clear them when the Mac locks. ## Install diff --git a/Sources/CodeCatch/Mail/APIWatcher.swift b/Sources/CodeCatch/Mail/APIWatcher.swift index a632e47..6f7d638 100644 --- a/Sources/CodeCatch/Mail/APIWatcher.swift +++ b/Sources/CodeCatch/Mail/APIWatcher.swift @@ -65,18 +65,29 @@ enum APIWatcher { try await MailWatcher.hand(messages, event: event, deliver: deliver) } + // Live once the provider has answered: a resumed account makes no call before its first check, + // and counting it as working there also reset the backoff on every failed try. + var live = false + func answered() async { + guard !live else { return } + live = true + await status(.live) + backoff = retryDelay + } + if cursor == nil { let start = try await mailbox.cursor() try await receive(try await mailbox.inbox(since: Date().addingTimeInterval(-lookback), limit: MailWatcher.backfill)) cursor = start await event(.read(.cursor(start))) resuming = false + try Task.checkCancellation() + await answered() } try Task.checkCancellation() - await status(.live) - backoff = retryDelay while !Task.isCancelled { let (added, next) = try await mailbox.added(since: cursor!) + await answered() // The same newest few on a retry, so a failed fetch can't widen the window to older mail. let pending = (resuming ? added.suffix(MailWatcher.backfill) : added[...]).filter { !seen.contains($0) } if pending.isEmpty { try await receive([]) } diff --git a/Sources/CodeCatch/Model/AppModel+Accounts.swift b/Sources/CodeCatch/Model/AppModel+Accounts.swift index 0c70fbd..c6fe5cb 100644 --- a/Sources/CodeCatch/Model/AppModel+Accounts.swift +++ b/Sources/CodeCatch/Model/AppModel+Accounts.swift @@ -23,6 +23,8 @@ extension AppModel { var account = account if let refreshToken { try keychain.write(refreshToken, account.refreshTokenKey) + // The cached access token belongs to the old sign-in and its permissions. + OAuth.forgetAccessToken(tokenKey: account.refreshTokenKey) account.signedIn = true } else if !account.usesSignIn { if !password.isEmpty { try keychain.write(password, account.secretKey) } diff --git a/Sources/CodeCatch/UI/MenuBar/MenuContent.swift b/Sources/CodeCatch/UI/MenuBar/MenuContent.swift index b14d235..1eca405 100644 --- a/Sources/CodeCatch/UI/MenuBar/MenuContent.swift +++ b/Sources/CodeCatch/UI/MenuBar/MenuContent.swift @@ -66,7 +66,7 @@ struct MenuContent: View { attention("All sources off", "Turn on a source in Settings.", fix: ("Open Settings", { openSettings(at: .sources) })) .padding(.horizontal, 10).padding(.bottom, 10) } - if model.items.count > Self.recent || hasLogins || searchRequested { searchField } + if model.items.count > Self.recent || hasLogins || searchRequested || !query.isEmpty { searchField } ScrollViewReader { scroll in ScrollView { VStack(spacing: 0) { diff --git a/Sources/CodeCatchCLI/main.swift b/Sources/CodeCatchCLI/main.swift index 8a880ff..89daca7 100644 --- a/Sources/CodeCatchCLI/main.swift +++ b/Sources/CodeCatchCLI/main.swift @@ -117,7 +117,7 @@ case "get": } var timeout: TimeInterval? if let text = option("--timeout") { - guard let seconds = Double(text), seconds > 0 else { usage("--timeout takes a number of seconds.") } + guard let seconds = Double(text), seconds > 0, seconds.isFinite else { usage("--timeout takes a number of seconds.") } timeout = seconds } guard args.count == 2, !args[1].hasPrefix("-") else { diff --git a/Sources/CodeCatchCore/CodeExtractor.swift b/Sources/CodeCatchCore/CodeExtractor.swift index 3f88e61..ef983c9 100644 --- a/Sources/CodeCatchCore/CodeExtractor.swift +++ b/Sources/CodeCatchCore/CodeExtractor.swift @@ -35,6 +35,9 @@ public enum CodeExtractor { let keywords = keyword.matches(in: text, range: NSRange(location: 0, length: ns.length)).map(\.range) guard !keywords.isEmpty else { return nil } + // Asked of the whole text, so once: a long mail has thousands of candidates. + lazy var hasBooking = matches(bookingNumber, text) + lazy var hasTransaction = matches(transactionNumber, text) var best: (code: String, score: Double, range: NSRange, context: NSRange)? for (regex, isNumeric) in [(numeric, true), (alphanumeric, false)] { for match in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) { @@ -43,8 +46,9 @@ public enum CodeExtractor { if !isNumeric, !plausibleAlphanumeric(raw) { continue } let code = isNumeric ? raw.filter(\.isNumber) : raw - let before = ns.substring(to: range.location).suffix(40) - let after = ns.substring(from: range.location + range.length).prefix(40) + // Cut from a window, not from everything on that side: copying the rest of a long mail per candidate stalled it. + let before = ns.substring(with: NSRange(location: max(0, range.location - 640), length: min(640, range.location))).suffix(40) + let after = ns.substring(with: NSRange(location: range.upperBound, length: min(640, ns.length - range.upperBound))).prefix(40) let line = ns.lineRange(for: range) // A letters-only word set straight after the keyword is just the next word ("KODE RAHASIA utk", // "NEW API TOKEN CREATED"); "YOUR CODE IS SZBPM", "code: SZBPM" and "SZBPM is your code" name one. @@ -54,8 +58,8 @@ public enum CodeExtractor { // A PIN beside a booking's confirmation number ("Confirmation: 5984715426 / PIN: 0260") // manages that booking, and an auth code beside a transaction ID ("Transaction ID: 121875559327 / // Auth Code: 051115") is a receipt's card approval: neither is one-time. - if matches(pinLabel, String(before)), matches(bookingNumber, text) { continue } - if matches(approvalLabel, String(before)), matches(transactionNumber, text) { continue } + if matches(pinLabel, String(before)), hasBooking { continue } + if matches(approvalLabel, String(before)), hasTransaction { continue } let explicit = matches(explicitBefore, String(before)) || matches(explicitAfter, String(after)) // Introduced on the keyword's line ("… Moj A1: 30718264", "Enkratno geslo … je 318842"), // or on the line above a code standing alone ("… Steam Guard code you need …:" over "6VCC5"). @@ -84,7 +88,14 @@ public enum CodeExtractor { matches(codeNoun, ns.substring(with: NSRange(location: line.upperBound, length: below - line.upperBound))) ? below : line.upperBound let context = NSRange(location: leadStart, length: end - leadStart) - let near = keywords.filter { NSIntersectionRange($0, context).length > 0 }.map { k in + // Keywords are in text order: search for the first one reaching into the context, stop at the first past it. + var first = 0 + var past = keywords.count + while first < past { + let mid = (first + past) / 2 + if keywords[mid].upperBound <= context.location { first = mid + 1 } else { past = mid } + } + let near = keywords[first...].prefix { $0.location < context.upperBound }.map { k in k.upperBound <= range.location ? range.location - k.upperBound : k.location >= range.upperBound ? k.location - range.upperBound : 0 diff --git a/Sources/CodeCatchCore/MIME.swift b/Sources/CodeCatchCore/MIME.swift index b0a236b..2d1a4b5 100644 --- a/Sources/CodeCatchCore/MIME.swift +++ b/Sources/CodeCatchCore/MIME.swift @@ -151,7 +151,9 @@ public enum MIME { var html: String? collect(headers: headers, body: body, plain: &plain, html: &html, depth: 0) let parsedHTML = html.map(readHTML) - let links = parsedHTML?.links ?? plain.map(bareLinks) ?? [] + // An HTML part without anchors can sit beside a plain part that spells the link out. + let htmlLinks = parsedHTML?.links ?? [] + let links = htmlLinks.isEmpty ? plain.map(bareLinks) ?? [] : htmlLinks if let plain, !plain.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return (plain, links) } return (parsedHTML?.text ?? "", links) } diff --git a/Tests/CodeCatchCoreTests/CodeExtractorTests.swift b/Tests/CodeCatchCoreTests/CodeExtractorTests.swift index ebab5be..b9e187d 100644 --- a/Tests/CodeCatchCoreTests/CodeExtractorTests.swift +++ b/Tests/CodeCatchCoreTests/CodeExtractorTests.swift @@ -16,6 +16,22 @@ import Testing } } +/// Detection runs on the main thread: work that grew with the square of a mail's candidates froze +/// the app for about ten seconds on one long mail. +@Test func longMailCannotStallDetection() { + // This thread's CPU time: other tests running beside this one can't stretch it. + func cost(_ count: Int) -> UInt64 { + let text = String(repeating: "Your code: 123456\n", count: count) + let start = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) + #expect(CodeExtractor.code(in: text) == "123456") + return clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) - start + } + // Sixteen times the mail may cost about sixteen times as much, not fifty or more; seconds alone depend on the machine. + _ = cost(10) // the patterns compile on first use + let short = cost(300) + #expect(cost(4_800) < short * 32) +} + /// The card's title: a wrong or missing service makes codes indistinguishable. @Test( arguments: [ diff --git a/Tests/CodeCatchCoreTests/MIMETests.swift b/Tests/CodeCatchCoreTests/MIMETests.swift index 09167d8..0713679 100644 --- a/Tests/CodeCatchCoreTests/MIMETests.swift +++ b/Tests/CodeCatchCoreTests/MIMETests.swift @@ -54,6 +54,12 @@ import Testing "Content-Type: text/plain\r\nContent-Transfer-Encoding: base64\r\n\r\n" + Data("Your code: 482913. Thanks!".utf8).base64EncodedString().dropLast(3) #expect(MIME.parse(Data(cut.utf8)).text.hasPrefix("Your code: 482913")) + // An HTML part with no anchors must not hide the link the plain part spells out. + let alt = + "Content-Type: multipart/alternative; boundary=XX\r\n\r\n--XX\r\nContent-Type: text/plain\r\n\r\nSign in: https://a.com/login?t=abc\r\n" + + "--XX\r\nContent-Type: text/html\r\n\r\n
Sign in with the link
\r\n--XX--" + #expect(MIME.parse(Data(alt.utf8)).links == [MailLink(url: "https://a.com/login?t=abc", label: "Sign in")]) + let bare = "Subject: Vaša koda\r\nContent-Type: multipart/mixed; boundary=XX\r\n\r\n--XX\r\n\r\nYour code: 482913\r\n--XX--" #expect(MIME.parse(Data(bare.utf8)) == MailMessage(fromName: "", fromAddress: "", subject: "Vaša koda", text: "Your code: 482913\n")) } diff --git a/Tests/CodeCatchTests/MailWatcherTests.swift b/Tests/CodeCatchTests/MailWatcherTests.swift index 263b795..221fa7e 100644 --- a/Tests/CodeCatchTests/MailWatcherTests.swift +++ b/Tests/CodeCatchTests/MailWatcherTests.swift @@ -146,9 +146,11 @@ private actor FakeGmail: MailAPI { var historyChecks = 0 var backfills = 0 var fetched: [String] = [] - init(expireHistoryOnce: Bool = false, signInRevoked: Bool = false) { + let unreachable: Bool + init(expireHistoryOnce: Bool = false, signInRevoked: Bool = false, unreachable: Bool = false) { self.expireHistoryOnce = expireHistoryOnce self.signInRevoked = signInRevoked + self.unreachable = unreachable } func cursor() throws -> String { if signInRevoked { throw OAuth.Failure.token("invalid_grant") } @@ -160,6 +162,7 @@ private actor FakeGmail: MailAPI { } func added(since cursor: String) throws -> (ids: [String], cursor: String) { historyChecks += 1 + if unreachable { throw URLError(.notConnectedToInternet) } if expireHistoryOnce && historyChecks == 1 { throw MailAPIError.cursorExpired } // The backfilled mail also shows up in the first history check, as it can when it lands mid-backfill. return (fetched.contains("new") ? [] : ["backfilled", "new"], "101") @@ -215,6 +218,26 @@ private actor FakeGmail: MailAPI { #expect(reported == .failed(SourceStatus.signInExpired)) } +/// A resumed account makes no call before its first check: shown as working there, an unreachable +/// provider flickered between working and failed, and each failed try reset the retry backoff. +@Test @MainActor func resumedAccountIsNotLiveBeforeItsProviderAnswers() async { + let statuses = AsyncStream