-
Notifications
You must be signed in to change notification settings - Fork 70
M4: ALPN lock, WebSocket detection, HAR export #75
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kalil0321
wants to merge
4
commits into
claude/proxy-monitor-m3-swiftui-ui
Choose a base branch
from
claude/proxy-monitor-m4-alpn-har
base: claude/proxy-monitor-m3-swiftui-ui
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,33 +2,31 @@ import Foundation | |
| import Crypto | ||
| import X509 | ||
| import SwiftASN1 | ||
| import Security | ||
|
|
||
| public enum CAStoreError: Error { | ||
| case missingCertificateOnDisk | ||
| case missingPrivateKeyInKeychain | ||
| case keychainWriteFailed(OSStatus) | ||
| case keychainReadFailed(OSStatus) | ||
| case keychainDeleteFailed(OSStatus) | ||
| case missingPrivateKeyOnDisk | ||
| case invalidStoredPrivateKey | ||
| case certificateDeleteFailed(any Error) | ||
| case privateKeyDeleteFailed(any Error) | ||
| case privateKeyWriteFailed(any Error) | ||
| } | ||
|
|
||
| public final class CAStore: @unchecked Sendable { | ||
| public let directory: URL | ||
| public let certificateURL: URL | ||
|
|
||
| private let keychainService = "app.reverseapi" | ||
| private let keychainAccount = "ca.root-private-key" | ||
| private let legacyPrivateKeyURL: URL | ||
| public let privateKeyURL: URL | ||
|
|
||
| public init(applicationSupportURL: URL) throws { | ||
| let root = applicationSupportURL.appendingPathComponent("ReverseAPI", isDirectory: true) | ||
| try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) | ||
| try FileManager.default.createDirectory( | ||
| at: root, | ||
| withIntermediateDirectories: true, | ||
| attributes: [.posixPermissions: 0o700] | ||
| ) | ||
| self.directory = root | ||
| self.certificateURL = root.appendingPathComponent("root.cer") | ||
| self.legacyPrivateKeyURL = root.appendingPathComponent("root-key.pem") | ||
| self.privateKeyURL = root.appendingPathComponent("root-key.pem") | ||
| } | ||
|
|
||
| public func loadOrCreate() throws -> RootCertificate { | ||
|
|
@@ -69,86 +67,33 @@ public final class CAStore: @unchecked Sendable { | |
| throw CAStoreError.certificateDeleteFailed(error) | ||
| } | ||
| } | ||
| if manager.fileExists(atPath: legacyPrivateKeyURL.path) { | ||
| if manager.fileExists(atPath: privateKeyURL.path) { | ||
| do { | ||
| try manager.removeItem(at: legacyPrivateKeyURL) | ||
| try manager.removeItem(at: privateKeyURL) | ||
| } catch { | ||
| throw CAStoreError.privateKeyDeleteFailed(error) | ||
| } | ||
| } | ||
| try deletePrivateKey() | ||
| } | ||
|
|
||
| public func exists() -> Bool { | ||
| guard FileManager.default.fileExists(atPath: certificateURL.path) else { return false } | ||
| return privateKeyExists() | ||
| return FileManager.default.fileExists(atPath: privateKeyURL.path) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: Prompt for AI agents |
||
| } | ||
|
|
||
| private func storePrivateKeyPEM(_ data: Data) throws { | ||
| let query: [String: Any] = [ | ||
| kSecClass as String: kSecClassGenericPassword, | ||
| kSecAttrService as String: keychainService, | ||
| kSecAttrAccount as String: keychainAccount, | ||
| ] | ||
|
|
||
| var addQuery = query | ||
| addQuery[kSecValueData as String] = data | ||
| addQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly | ||
| let status = SecItemAdd(addQuery as CFDictionary, nil) | ||
| if status == errSecDuplicateItem { | ||
| let updateStatus = SecItemUpdate(query as CFDictionary, [kSecValueData as String: data] as CFDictionary) | ||
| guard updateStatus == errSecSuccess else { throw CAStoreError.keychainWriteFailed(updateStatus) } | ||
| return | ||
| do { | ||
| try data.write(to: privateKeyURL, options: .atomic) | ||
| try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: privateKeyURL.path) | ||
| } catch { | ||
| throw CAStoreError.privateKeyWriteFailed(error) | ||
| } | ||
| guard status == errSecSuccess else { throw CAStoreError.keychainWriteFailed(status) } | ||
| } | ||
|
|
||
| private func loadPrivateKeyPEM() throws -> Data { | ||
| let query: [String: Any] = [ | ||
| kSecClass as String: kSecClassGenericPassword, | ||
| kSecAttrService as String: keychainService, | ||
| kSecAttrAccount as String: keychainAccount, | ||
| kSecReturnData as String: true, | ||
| kSecMatchLimit as String: kSecMatchLimitOne, | ||
| ] | ||
| var result: CFTypeRef? | ||
| let status = SecItemCopyMatching(query as CFDictionary, &result) | ||
| if status == errSecItemNotFound, FileManager.default.fileExists(atPath: legacyPrivateKeyURL.path) { | ||
| let data = try Data(contentsOf: legacyPrivateKeyURL) | ||
| try storePrivateKeyPEM(data) | ||
| try? FileManager.default.removeItem(at: legacyPrivateKeyURL) | ||
| return data | ||
| } | ||
| if status == errSecItemNotFound { | ||
| throw CAStoreError.missingPrivateKeyInKeychain | ||
| } | ||
| guard status == errSecSuccess, let data = result as? Data else { | ||
| throw CAStoreError.keychainReadFailed(status) | ||
| } | ||
| return data | ||
| } | ||
|
|
||
| private func privateKeyExists() -> Bool { | ||
| let query: [String: Any] = [ | ||
| kSecClass as String: kSecClassGenericPassword, | ||
| kSecAttrService as String: keychainService, | ||
| kSecAttrAccount as String: keychainAccount, | ||
| kSecReturnData as String: false, | ||
| kSecMatchLimit as String: kSecMatchLimitOne, | ||
| ] | ||
| let status = SecItemCopyMatching(query as CFDictionary, nil) | ||
| return status == errSecSuccess || FileManager.default.fileExists(atPath: legacyPrivateKeyURL.path) | ||
| } | ||
|
|
||
| private func deletePrivateKey() throws { | ||
| let query: [String: Any] = [ | ||
| kSecClass as String: kSecClassGenericPassword, | ||
| kSecAttrService as String: keychainService, | ||
| kSecAttrAccount as String: keychainAccount, | ||
| ] | ||
| let status = SecItemDelete(query as CFDictionary) | ||
| if status != errSecSuccess && status != errSecItemNotFound { | ||
| throw CAStoreError.keychainDeleteFailed(status) | ||
| guard FileManager.default.fileExists(atPath: privateKeyURL.path) else { | ||
| throw CAStoreError.missingPrivateKeyOnDisk | ||
| } | ||
| return try Data(contentsOf: privateKeyURL) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| import Foundation | ||
|
|
||
| public enum HARExporter { | ||
| private static let dateFormatter: ISO8601DateFormatter = { | ||
| let formatter = ISO8601DateFormatter() | ||
| formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] | ||
| return formatter | ||
| }() | ||
|
|
||
| public static func export(_ flows: [CapturedFlow]) throws -> Data { | ||
| let entries = flows.map(entry(for:)) | ||
| let har: [String: Any] = [ | ||
| "log": [ | ||
| "version": "1.2", | ||
| "creator": ["name": "rae", "version": "0.1"], | ||
| "entries": entries, | ||
| ] | ||
| ] | ||
| return try JSONSerialization.data(withJSONObject: har, options: [.prettyPrinted, .sortedKeys]) | ||
| } | ||
|
|
||
| static func entry(for flow: CapturedFlow) -> [String: Any] { | ||
| let started = Self.dateFormatter.string(from: flow.startedAt) | ||
| let duration = ((flow.finishedAt ?? flow.startedAt).timeIntervalSince(flow.startedAt)) * 1000 | ||
|
|
||
| let requestContentType = header(flow.requestHeaders, "content-type") | ||
| let responseContentType = header(flow.responseHeaders, "content-type") | ||
|
|
||
| var request: [String: Any] = [ | ||
| "method": flow.method, | ||
| "url": flow.url, | ||
| "httpVersion": "HTTP/1.1", | ||
| "cookies": [], | ||
| "headers": flow.requestHeaders.map { ["name": $0.name, "value": $0.value] }, | ||
| "queryString": queryString(from: flow.path), | ||
| "headersSize": -1, | ||
| "bodySize": flow.requestBody.count, | ||
| ] | ||
| if !flow.requestBody.isEmpty { | ||
| var postData: [String: Any] = ["mimeType": requestContentType ?? ""] | ||
| if let text = String(data: flow.requestBody, encoding: .utf8) { | ||
| postData["text"] = text | ||
| } else { | ||
| postData["encoding"] = "base64" | ||
| postData["text"] = flow.requestBody.base64EncodedString() | ||
| } | ||
| request["postData"] = postData | ||
| } | ||
|
|
||
| var responseContent: [String: Any] = [ | ||
| "size": flow.responseBody.count, | ||
| "mimeType": responseContentType ?? "", | ||
| ] | ||
| if !flow.responseBody.isEmpty { | ||
| if let text = String(data: flow.responseBody, encoding: .utf8) { | ||
| responseContent["text"] = text | ||
| } else { | ||
| responseContent["encoding"] = "base64" | ||
| responseContent["text"] = flow.responseBody.base64EncodedString() | ||
| } | ||
| } | ||
|
|
||
| var record: [String: Any] = [ | ||
| "startedDateTime": started, | ||
| "time": duration, | ||
| "request": request, | ||
| "response": [ | ||
| "status": flow.responseStatus ?? 0, | ||
| "statusText": "", | ||
| "httpVersion": "HTTP/1.1", | ||
| "cookies": [], | ||
| "headers": flow.responseHeaders.map { ["name": $0.name, "value": $0.value] }, | ||
| "content": responseContent, | ||
| "redirectURL": "", | ||
| "headersSize": -1, | ||
| "bodySize": flow.responseBody.count, | ||
| ], | ||
| "cache": [:], | ||
| "timings": [ | ||
| "send": 0, | ||
| "wait": duration, | ||
| "receive": 0, | ||
| ], | ||
| ] | ||
| if let error = flow.error { | ||
| record["_error"] = error | ||
| } | ||
| return record | ||
| } | ||
|
|
||
| private static func header(_ headers: [HTTPHeader], _ name: String) -> String? { | ||
| let lower = name.lowercased() | ||
| return headers.first(where: { $0.name.lowercased() == lower })?.value | ||
| } | ||
|
|
||
| static func queryString(from path: String) -> [[String: String]] { | ||
| guard let queryIndex = path.firstIndex(of: "?") else { return [] } | ||
| let rawQuery = path[path.index(after: queryIndex)...] | ||
| let query = rawQuery.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false).first ?? "" | ||
| return query.split(separator: "&").compactMap { pair in | ||
| let parts = pair.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false) | ||
| guard let name = parts.first else { return nil } | ||
| let value = parts.count > 1 ? String(parts[1]) : "" | ||
| return [ | ||
| "name": decodeFormComponent(String(name)), | ||
| "value": decodeFormComponent(value), | ||
| ] | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
| } | ||
| } | ||
|
|
||
| static func decodeFormComponent(_ value: String) -> String { | ||
| let withSpaces = value.replacingOccurrences(of: "+", with: " ") | ||
| return withSpaces.removingPercentEncoding ?? withSpaces | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.