Skip to content
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
15 changes: 13 additions & 2 deletions Sources/CodeCatch/Mail/APIWatcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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([]) }
Expand Down
2 changes: 2 additions & 0 deletions Sources/CodeCatch/Model/AppModel+Accounts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand Down
2 changes: 1 addition & 1 deletion Sources/CodeCatch/UI/MenuBar/MenuContent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion Sources/CodeCatchCLI/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
21 changes: 16 additions & 5 deletions Sources/CodeCatchCore/CodeExtractor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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.
Expand All @@ -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").
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion Sources/CodeCatchCore/MIME.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
16 changes: 16 additions & 0 deletions Tests/CodeCatchCoreTests/CodeExtractorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand Down
6 changes: 6 additions & 0 deletions Tests/CodeCatchCoreTests/MIMETests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<p>Sign in with the link</p>\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"))
}
Expand Down
25 changes: 24 additions & 1 deletion Tests/CodeCatchTests/MailWatcherTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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") }
Expand All @@ -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")
Expand Down Expand Up @@ -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<SourceStatus>.makeStream()
let watcher = Task {
await APIWatcher.watch(
MailAccount(label: "Gmail", host: MailAccount.gmailHost, user: "test@gmail.com"), from: .cursor("100"),
status: { statuses.continuation.yield($0) }, deliver: { _ in },
mailbox: FakeGmail(unreachable: true))
}
var reported: SourceStatus?
for await status in statuses.stream where status != .connecting {
reported = status
break
}
watcher.cancel()
await watcher.value
#expect(reported != .live)
}

/// The status shows in the menu's banner: a system error's own text there reads as gibberish.
@Test(
arguments: [
Expand Down
1 change: 1 addition & 0 deletions scripts/make-icon.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,4 @@ p.executableURL = URL(fileURLWithPath: "/usr/bin/iconutil")
p.arguments = ["-c", "icns", iconset, "-o", out]
try! p.run()
p.waitUntilExit()
exit(p.terminationStatus)
2 changes: 1 addition & 1 deletion site/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -790,7 +790,7 @@ li.copied .tick, button.copied > svg { display: block; stroke-dasharray: 21; ani
html { scroll-behavior: auto; }
.reveal, .banner, .keys, .ring .arc, .row .ring, .button, .toc ol::before { transition: none; }
.reveal { opacity: 1; transform: none; }
li.copied .tick, button.copied > svg { animation: none; }
li.copied .tick, button.copied > svg, .caret { animation: none; }
}

/* AgentCard.swift and AgentsTab.swift: an agent's request for a code, and Settings → Agents. */
Expand Down
Loading