Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
238614a94b | ||
|
|
b11507221f | ||
|
|
b6fef53264 | ||
|
|
ec6ae6621a | ||
|
|
105a7706fa | ||
|
|
a950392a6f | ||
|
|
8087cc029d | ||
|
|
11f9e0c9b6 | ||
|
|
cc835ee2b0 |
@@ -117,7 +117,7 @@ struct ContentView: View {
|
|||||||
}
|
}
|
||||||
.sheet(isPresented: $showLogin) {
|
.sheet(isPresented: $showLogin) {
|
||||||
LoginSheetView(isPresented: $showLogin) {
|
LoginSheetView(isPresented: $showLogin) {
|
||||||
Task { await vm.reloadAPIWebViewAndRefresh() }
|
Task { await vm.refresh() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.sheet(isPresented: $showUpdateSheet) {
|
.sheet(isPresented: $showUpdateSheet) {
|
||||||
|
|||||||
@@ -15,9 +15,9 @@
|
|||||||
<key>CFBundlePackageType</key>
|
<key>CFBundlePackageType</key>
|
||||||
<string>APPL</string>
|
<string>APPL</string>
|
||||||
<key>CFBundleShortVersionString</key>
|
<key>CFBundleShortVersionString</key>
|
||||||
<string>1.2.1-beta.12</string>
|
<string>1.2.1-beta.14</string>
|
||||||
<key>CFBundleVersion</key>
|
<key>CFBundleVersion</key>
|
||||||
<string>60</string>
|
<string>62</string>
|
||||||
<key>LSMinimumSystemVersion</key>
|
<key>LSMinimumSystemVersion</key>
|
||||||
<string>13.0</string>
|
<string>13.0</string>
|
||||||
<key>LSUIElement</key>
|
<key>LSUIElement</key>
|
||||||
|
|||||||
@@ -30,10 +30,6 @@ class UsageViewModel: ObservableObject {
|
|||||||
private var previousPercents: [String: Double] = [:]
|
private var previousPercents: [String: Double] = [:]
|
||||||
private var firedThresholds: [String: Set<Int>] = [:]
|
private var firedThresholds: [String: Set<Int>] = [:]
|
||||||
|
|
||||||
// Background WKWebView used for all API calls — runs fetch() in the page's auth context
|
|
||||||
private var apiWebView: WKWebView?
|
|
||||||
private var apiDelegate: APIWebViewDelegate?
|
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
let saved = UserDefaults.standard.double(forKey: "refresh_interval")
|
let saved = UserDefaults.standard.double(forKey: "refresh_interval")
|
||||||
refreshInterval = saved > 0 ? saved : 60
|
refreshInterval = saved > 0 ? saved : 60
|
||||||
@@ -42,50 +38,9 @@ class UsageViewModel: ObservableObject {
|
|||||||
burnHistoryStore = saved
|
burnHistoryStore = saved
|
||||||
}
|
}
|
||||||
loadPlaceholderData()
|
loadPlaceholderData()
|
||||||
setupAPIWebView()
|
|
||||||
Task { await checkInitialSignInState() }
|
Task { await checkInitialSignInState() }
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Background API WebView
|
|
||||||
|
|
||||||
private func setupAPIWebView() {
|
|
||||||
let config = WKWebViewConfiguration()
|
|
||||||
config.websiteDataStore = WKWebsiteDataStore.default()
|
|
||||||
let wv = WKWebView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), configuration: config)
|
|
||||||
let del = APIWebViewDelegate()
|
|
||||||
wv.navigationDelegate = del
|
|
||||||
apiWebView = wv
|
|
||||||
apiDelegate = del
|
|
||||||
wv.load(URLRequest(url: URL(string: "https://claude.ai")!))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Called after login: reloads the background WebView to pick up the new session, then refreshes.
|
|
||||||
func reloadAPIWebViewAndRefresh() async {
|
|
||||||
guard let wv = apiWebView, let del = apiDelegate else {
|
|
||||||
await refresh()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
await withCheckedContinuation { (cont: CheckedContinuation<Void, Never>) in
|
|
||||||
del.onDidFinish = { cont.resume() }
|
|
||||||
wv.load(URLRequest(url: URL(string: "https://claude.ai")!))
|
|
||||||
}
|
|
||||||
// Brief pause for the page's JS auth state to settle after navigation
|
|
||||||
try? await Task.sleep(nanoseconds: 500_000_000)
|
|
||||||
await refresh()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Runs a fetch() call inside the background WebView's page context (same-origin, credentials included).
|
|
||||||
private func webViewFetch(_ path: String) async throws -> (statusCode: Int, body: String) {
|
|
||||||
guard let wv = apiWebView else { throw AppError.networkError }
|
|
||||||
let js = "const r = await fetch(path, {credentials:'include'}); return {s: r.status, b: await r.text()};"
|
|
||||||
let result = try await wv.callAsyncJavaScript(
|
|
||||||
js, arguments: ["path": path], in: nil, in: .page)
|
|
||||||
guard let d = result as? [String: Any],
|
|
||||||
let s = (d["s"] as? NSNumber)?.intValue,
|
|
||||||
let b = d["b"] as? String else { throw AppError.networkError }
|
|
||||||
return (s, b)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func checkInitialSignInState() async {
|
private func checkInitialSignInState() async {
|
||||||
let cookies = await WKWebsiteDataStore.default().httpCookieStore.allCookies()
|
let cookies = await WKWebsiteDataStore.default().httpCookieStore.allCookies()
|
||||||
if !cookies.isEmpty { isSignedIn = true }
|
if !cookies.isEmpty { isSignedIn = true }
|
||||||
@@ -106,8 +61,6 @@ class UsageViewModel: ObservableObject {
|
|||||||
extraUsage = nil
|
extraUsage = nil
|
||||||
prepaidCredits = nil
|
prepaidCredits = nil
|
||||||
overageSpendLimit = nil
|
overageSpendLimit = nil
|
||||||
// Reload background WebView to clear its session too
|
|
||||||
apiWebView?.load(URLRequest(url: URL(string: "https://claude.ai")!))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func refresh() async {
|
func refresh() async {
|
||||||
@@ -173,14 +126,44 @@ class UsageViewModel: ObservableObject {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - HTTP helpers
|
||||||
|
|
||||||
|
// Builds a URLRequest with browser-like headers and cookies from WKWebsiteDataStore.
|
||||||
|
//
|
||||||
|
// httpShouldHandleCookies MUST be false: when true, URLSession replaces any manually-set
|
||||||
|
// Cookie header with its own HTTPCookieStorage (which is empty — claude.ai cookies live in
|
||||||
|
// WKWebsiteDataStore, not HTTPCookieStorage), causing every request to go out with no cookies.
|
||||||
|
private func claudeAPIRequest(for url: URL) async -> URLRequest {
|
||||||
|
var req = URLRequest(url: url)
|
||||||
|
req.httpShouldHandleCookies = false
|
||||||
|
req.setValue("application/json", forHTTPHeaderField: "accept")
|
||||||
|
req.setValue("https://claude.ai", forHTTPHeaderField: "origin")
|
||||||
|
req.setValue("https://claude.ai/", forHTTPHeaderField: "referer")
|
||||||
|
req.setValue(
|
||||||
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
|
||||||
|
forHTTPHeaderField: "user-agent")
|
||||||
|
if let cookie = await claudeCookieHeader() {
|
||||||
|
req.setValue(cookie, forHTTPHeaderField: "cookie")
|
||||||
|
}
|
||||||
|
return req
|
||||||
|
}
|
||||||
|
|
||||||
|
private func claudeCookieHeader() async -> String? {
|
||||||
|
let cookies = await WKWebsiteDataStore.default().httpCookieStore.allCookies()
|
||||||
|
guard !cookies.isEmpty else { return nil }
|
||||||
|
return HTTPCookie.requestHeaderFields(with: cookies)["Cookie"]
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Bootstrap (org ID + email + plan label in one call)
|
// MARK: - Bootstrap (org ID + email + plan label in one call)
|
||||||
|
|
||||||
private func fetchBootstrap() async throws -> (orgId: String?, email: String?, planLabel: String?) {
|
private func fetchBootstrap() async throws -> (orgId: String?, email: String?, planLabel: String?) {
|
||||||
let (status, body) = try await webViewFetch("/api/bootstrap")
|
let url = URL(string: "https://claude.ai/api/bootstrap")!
|
||||||
if status == 401 || status == 403 { throw AppError.notAuthenticated }
|
let req = await claudeAPIRequest(for: url)
|
||||||
guard status == 200 else { throw AppError.networkError }
|
let (data, response) = try await URLSession.shared.data(for: req)
|
||||||
guard let data = body.data(using: .utf8),
|
guard let http = response as? HTTPURLResponse else { throw AppError.networkError }
|
||||||
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
if http.statusCode == 401 || http.statusCode == 403 { throw AppError.notAuthenticated }
|
||||||
|
guard http.statusCode == 200 else { throw AppError.networkError }
|
||||||
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||||
return (nil, nil, nil)
|
return (nil, nil, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,9 +176,9 @@ class UsageViewModel: ObservableObject {
|
|||||||
orgId = (json["organizations"] as? [[String: Any]])?.first?["uuid"] as? String
|
orgId = (json["organizations"] as? [[String: Any]])?.first?["uuid"] as? String
|
||||||
}
|
}
|
||||||
if orgId == nil {
|
if orgId == nil {
|
||||||
if let (orgsStatus, orgsBody) = try? await webViewFetch("/api/organizations"),
|
let orgsReq = await claudeAPIRequest(for: URL(string: "https://claude.ai/api/organizations")!)
|
||||||
orgsStatus == 200,
|
if let (orgsData, orgsResp) = try? await URLSession.shared.data(for: orgsReq),
|
||||||
let orgsData = orgsBody.data(using: .utf8),
|
let orgsHttp = orgsResp as? HTTPURLResponse, orgsHttp.statusCode == 200,
|
||||||
let orgs = try? JSONSerialization.jsonObject(with: orgsData) as? [[String: Any]] {
|
let orgs = try? JSONSerialization.jsonObject(with: orgsData) as? [[String: Any]] {
|
||||||
orgId = orgs.first?["uuid"] as? String
|
orgId = orgs.first?["uuid"] as? String
|
||||||
}
|
}
|
||||||
@@ -216,24 +199,28 @@ class UsageViewModel: ObservableObject {
|
|||||||
// MARK: - Fetch usage
|
// MARK: - Fetch usage
|
||||||
|
|
||||||
private func fetchUsage(orgId: String) async throws -> UsageResponse {
|
private func fetchUsage(orgId: String) async throws -> UsageResponse {
|
||||||
let (status, body) = try await webViewFetch("/api/organizations/\(orgId)/usage")
|
let url = URL(string: "https://claude.ai/api/organizations/\(orgId)/usage")!
|
||||||
if status == 401 || status == 403 { throw AppError.notAuthenticated }
|
let req = await claudeAPIRequest(for: url)
|
||||||
guard status == 200 else { throw AppError.networkError }
|
let (data, response) = try await URLSession.shared.data(for: req)
|
||||||
guard let data = body.data(using: .utf8) else { throw AppError.networkError }
|
guard let http = response as? HTTPURLResponse else { throw AppError.networkError }
|
||||||
|
if http.statusCode == 401 || http.statusCode == 403 { throw AppError.notAuthenticated }
|
||||||
|
guard http.statusCode == 200 else { throw AppError.networkError }
|
||||||
return try JSONDecoder().decode(UsageResponse.self, from: data)
|
return try JSONDecoder().decode(UsageResponse.self, from: data)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func fetchPrepaidCredits(orgId: String) async throws -> PrepaidCredits? {
|
private func fetchPrepaidCredits(orgId: String) async throws -> PrepaidCredits? {
|
||||||
guard let (status, body) = try? await webViewFetch("/api/organizations/\(orgId)/prepaid/credits"),
|
let url = URL(string: "https://claude.ai/api/organizations/\(orgId)/prepaid/credits")!
|
||||||
status == 200,
|
let req = await claudeAPIRequest(for: url)
|
||||||
let data = body.data(using: .utf8) else { return nil }
|
let (data, response) = try await URLSession.shared.data(for: req)
|
||||||
|
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else { return nil }
|
||||||
return try? JSONDecoder().decode(PrepaidCredits.self, from: data)
|
return try? JSONDecoder().decode(PrepaidCredits.self, from: data)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func fetchOverageSpendLimit(orgId: String) async throws -> OverageSpendLimit? {
|
private func fetchOverageSpendLimit(orgId: String) async throws -> OverageSpendLimit? {
|
||||||
guard let (status, body) = try? await webViewFetch("/api/organizations/\(orgId)/overage_spend_limit"),
|
let url = URL(string: "https://claude.ai/api/organizations/\(orgId)/overage_spend_limit")!
|
||||||
status == 200,
|
let req = await claudeAPIRequest(for: url)
|
||||||
let data = body.data(using: .utf8) else { return nil }
|
let (data, response) = try await URLSession.shared.data(for: req)
|
||||||
|
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else { return nil }
|
||||||
return try? JSONDecoder().decode(OverageSpendLimit.self, from: data)
|
return try? JSONDecoder().decode(OverageSpendLimit.self, from: data)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,22 +337,6 @@ class UsageViewModel: ObservableObject {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - API WebView Delegate
|
|
||||||
|
|
||||||
private class APIWebViewDelegate: NSObject, WKNavigationDelegate {
|
|
||||||
var onDidFinish: (() -> Void)?
|
|
||||||
|
|
||||||
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
|
||||||
let cb = onDidFinish; onDidFinish = nil; cb?()
|
|
||||||
}
|
|
||||||
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
|
|
||||||
let cb = onDidFinish; onDidFinish = nil; cb?()
|
|
||||||
}
|
|
||||||
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
|
|
||||||
let cb = onDidFinish; onDidFinish = nil; cb?()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
enum AppError: LocalizedError {
|
enum AppError: LocalizedError {
|
||||||
case notAuthenticated
|
case notAuthenticated
|
||||||
case networkError
|
case networkError
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
[](https://swift.org)
|
[](https://swift.org)
|
||||||
[](https://github.com/superdooper86/claudechecker/releases)
|
[](https://github.com/superdooper86/claudechecker/releases)
|
||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
[](https://github.com/superdooper86/claudechecker/releases/tag/v1.2.1-beta.11) <!-- BETA_BADGE -->
|
[](https://github.com/superdooper86/claudechecker/releases/tag/v1.2.1-beta.13) <!-- BETA_BADGE -->
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
+7
-9
@@ -1,12 +1,10 @@
|
|||||||
## What's new in v1.2.1
|
## What's new in v1.2.1
|
||||||
|
|
||||||
### Bug fixes
|
### Bug fixes
|
||||||
- Fixed usage data not loading after sign-in — API calls now run inside a persistent background WebView using the page's own fetch(), so all credentials (cookies, localStorage tokens, etc.) are included automatically
|
- Fixed the root cause of "Not signed in" errors: URLSession was silently discarding the manually-set Cookie header because `httpShouldHandleCookies` defaults to `true`, which makes URLSession replace it with its own (empty) HTTPCookieStorage — claude.ai session cookies live in WKWebsiteDataStore, not HTTPCookieStorage. Setting `httpShouldHandleCookies = false` ensures the cookies are actually sent.
|
||||||
- Fixed "Not signed in" showing after login — the background WebView is now reloaded after sign-in to pick up the new session before the first data refresh
|
- Added browser-like request headers (User-Agent, Origin, Referer) matching what Claude's API expects, consistent with the working Windows implementation
|
||||||
- Fixed "Not signed in" showing incorrectly on launch when the session was already active
|
- Removed background WKWebView complexity added in beta.12–13 — reverted to simple URLSession approach with correct cookie handling
|
||||||
- Sign-in state is now detected immediately from stored cookies on startup, before the first data refresh completes
|
- Fixed login window auto-closing before the user could sign in — login window loads `/login` so auth is only detected after the actual sign-in redirect
|
||||||
- Fixed login window auto-closing before the user could sign in — the login window now correctly loads the `/login` page so it only detects auth after the actual sign-in redirect
|
- Fixed login detection for Next.js SPA navigation using KVO on WebView URL (history.pushState doesn't trigger didFinish)
|
||||||
- Fixed "No API key configured" showing after signing out — now correctly shows "Not signed in" with a prompt to sign in
|
- Added `/api/organizations` as a final fallback for org ID resolution
|
||||||
- Added `/api/organizations` as a final fallback for org ID resolution when the bootstrap API response doesn't include it
|
- Fixed Settings incorrectly showing "Signed in" after a failed refresh
|
||||||
- Fixed Settings incorrectly showing "Signed in" after a failed refresh — sign-in state now resets when authentication fails
|
|
||||||
- Rewrote login detection to use KVO on the WebView URL — correctly detects auth for Next.js SPA navigation (history.pushState) that doesn't trigger didFinish
|
|
||||||
|
|||||||
+3
-3
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"version": "1.2.1-beta.11",
|
"version": "1.2.1-beta.13",
|
||||||
"url": "https://github.com/superdooper86/claudechecker/releases/download/v1.2.1-beta.11/ClaudeChecker.zip",
|
"url": "https://github.com/superdooper86/claudechecker/releases/download/v1.2.1-beta.13/ClaudeChecker.zip",
|
||||||
"notes": "## What's new in v1.2.1\n\n### Bug fixes\n- Fixed \"Not signed in\" showing incorrectly on launch when the session was already active\n- Sign-in state is now detected immediately from stored cookies on startup, before the first data refresh completes\n- Fixed login window auto-closing before the user could sign in — the login window now correctly loads the `/login` page so it only detects auth after the actual sign-in redirect\n- Fixed \"No API key configured\" showing after signing out — now correctly shows \"Not signed in\" with a prompt to sign in\n- Added `/api/organizations` as a final fallback for org ID resolution when the bootstrap API response doesn't include it\n- Fixed usage data not loading — API requests now include required browser-like headers (Origin, Referer, User-Agent)\n- Fixed Settings incorrectly showing \"Signed in\" after a failed refresh — sign-in state now resets when authentication fails\n- Rewrote login detection to use the WebView's own fetch call instead of inspecting cookie domains — correctly detects auth regardless of which domain the session token is stored on\n- Fixed API requests not including session cookies — now sends all cookies from the app's WebView store rather than filtering by domain"
|
"notes": "## What's new in v1.2.1\n\n### Bug fixes\n- Fixed a timing race in the background API WebView — `refresh()` now correctly waits for the WebView to finish loading before making API calls, preventing silent failures on startup\n- Fixed usage data not loading after sign-in — API calls now run inside a persistent background WebView using the page's own fetch(), so all credentials (cookies, httpOnly tokens, etc.) are included automatically\n- Fixed \"Not signed in\" showing after login — the background WebView is now reloaded after sign-in to pick up the new session before the first data refresh\n- Fixed \"Not signed in\" showing incorrectly on launch when the session was already active\n- Sign-in state is now detected immediately from stored cookies on startup, before the first data refresh completes\n- Fixed login window auto-closing before the user could sign in — the login window now correctly loads the `/login` page so it only detects auth after the actual sign-in redirect\n- Fixed \"No API key configured\" showing after signing out — now correctly shows \"Not signed in\" with a prompt to sign in\n- Added `/api/organizations` as a final fallback for org ID resolution when the bootstrap API response doesn't include it\n- Fixed Settings incorrectly showing \"Signed in\" after a failed refresh — sign-in state now resets when authentication fails\n- Rewrote login detection to use KVO on the WebView URL — correctly detects auth for Next.js SPA navigation (history.pushState) that doesn't trigger didFinish"
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user