-
Notifications
You must be signed in to change notification settings - Fork 694
Add Codex managed-account foundation #613
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
Draft
ratulsarna
wants to merge
9
commits into
main
Choose a base branch
from
codex/rat-185-multi-account-foundation
base: main
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.
Draft
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
097dd04
Add managed Codex account foundation
ratulsarna 9cf2d2c
Route Codex remote fetches through managed homes
ratulsarna c4959cd
Fail closed Codex OpenAI web state
ratulsarna 3565620
Scope Codex credits to managed home
ratulsarna ab4b33e
Fail closed Codex web unreadable store
ratulsarna 68f5598
Document manual Codex cookie scope
ratulsarna 65556af
Document Codex login flow deferment
ratulsarna d113d05
Scope Codex fallback account info to managed home
ratulsarna 3734890
Document ambient Codex cost history scope
ratulsarna 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 |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| import CodexBarCore | ||
| import Foundation | ||
|
|
||
| protocol ManagedCodexHomeProducing: Sendable { | ||
| func makeHomeURL() -> URL | ||
| func validateManagedHomeForDeletion(_ url: URL) throws | ||
| } | ||
|
|
||
| protocol ManagedCodexLoginRunning: Sendable { | ||
| func run(homePath: String, timeout: TimeInterval) async -> CodexLoginRunner.Result | ||
| } | ||
|
|
||
| protocol ManagedCodexIdentityReading: Sendable { | ||
| func loadAccountInfo(homePath: String) throws -> AccountInfo | ||
| } | ||
|
|
||
| enum ManagedCodexAccountServiceError: Error, Equatable, Sendable { | ||
| case loginFailed | ||
| case missingEmail | ||
| case unsafeManagedHome(String) | ||
| } | ||
|
|
||
| struct ManagedCodexHomeFactory: ManagedCodexHomeProducing, Sendable { | ||
| let root: URL | ||
|
|
||
| init(root: URL = Self.defaultRootURL(), fileManager: FileManager = .default) { | ||
| let standardizedRoot = root.standardizedFileURL | ||
| if standardizedRoot.path != root.path { | ||
| self.root = standardizedRoot | ||
| } else { | ||
| self.root = root | ||
| } | ||
| _ = fileManager | ||
| } | ||
|
|
||
| func makeHomeURL() -> URL { | ||
| self.root.appendingPathComponent(UUID().uuidString, isDirectory: true) | ||
| } | ||
|
|
||
| func validateManagedHomeForDeletion(_ url: URL) throws { | ||
| let rootPath = self.root.standardizedFileURL.path | ||
| let targetPath = url.standardizedFileURL.path | ||
| let rootPrefix = rootPath.hasSuffix("/") ? rootPath : rootPath + "/" | ||
| guard targetPath.hasPrefix(rootPrefix), targetPath != rootPath else { | ||
| throw ManagedCodexAccountServiceError.unsafeManagedHome(url.path) | ||
| } | ||
| } | ||
|
|
||
| static func defaultRootURL(fileManager: FileManager = .default) -> URL { | ||
| let base = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first | ||
| ?? fileManager.homeDirectoryForCurrentUser | ||
| return base | ||
| .appendingPathComponent("CodexBar", isDirectory: true) | ||
| .appendingPathComponent("managed-codex-homes", isDirectory: true) | ||
| } | ||
| } | ||
|
|
||
| struct DefaultManagedCodexLoginRunner: ManagedCodexLoginRunning { | ||
| func run(homePath: String, timeout: TimeInterval) async -> CodexLoginRunner.Result { | ||
| await CodexLoginRunner.run(homePath: homePath, timeout: timeout) | ||
| } | ||
| } | ||
|
|
||
| struct DefaultManagedCodexIdentityReader: ManagedCodexIdentityReading { | ||
| func loadAccountInfo(homePath: String) throws -> AccountInfo { | ||
| let env = CodexHomeScope.scopedEnvironment( | ||
| base: ProcessInfo.processInfo.environment, | ||
| codexHome: homePath) | ||
| return UsageFetcher(environment: env).loadAccountInfo() | ||
| } | ||
| } | ||
|
|
||
| @MainActor | ||
| final class ManagedCodexAccountService { | ||
| private let store: any ManagedCodexAccountStoring | ||
| private let homeFactory: any ManagedCodexHomeProducing | ||
| private let loginRunner: any ManagedCodexLoginRunning | ||
| private let identityReader: any ManagedCodexIdentityReading | ||
| private let fileManager: FileManager | ||
|
|
||
| init( | ||
| store: any ManagedCodexAccountStoring, | ||
| homeFactory: any ManagedCodexHomeProducing, | ||
| loginRunner: any ManagedCodexLoginRunning, | ||
| identityReader: any ManagedCodexIdentityReading, | ||
| fileManager: FileManager = .default) | ||
| { | ||
| self.store = store | ||
| self.homeFactory = homeFactory | ||
| self.loginRunner = loginRunner | ||
| self.identityReader = identityReader | ||
| self.fileManager = fileManager | ||
| } | ||
|
|
||
| func authenticateManagedAccount( | ||
| existingAccountID: UUID? = nil, | ||
| timeout: TimeInterval = 120) | ||
| async throws -> ManagedCodexAccount | ||
| { | ||
| let snapshot = try self.store.loadAccounts() | ||
| let homeURL = self.homeFactory.makeHomeURL() | ||
| try self.fileManager.createDirectory(at: homeURL, withIntermediateDirectories: true) | ||
| let account: ManagedCodexAccount | ||
| let existingHomePathToDelete: String? | ||
|
|
||
| do { | ||
| let result = await self.loginRunner.run(homePath: homeURL.path, timeout: timeout) | ||
| guard case .success = result.outcome else { throw ManagedCodexAccountServiceError.loginFailed } | ||
|
|
||
| let info = try self.identityReader.loadAccountInfo(homePath: homeURL.path) | ||
| guard let rawEmail = info.email?.trimmingCharacters(in: .whitespacesAndNewlines), !rawEmail.isEmpty else { | ||
| throw ManagedCodexAccountServiceError.missingEmail | ||
| } | ||
|
|
||
| let now = Date().timeIntervalSince1970 | ||
| let existing = self.reconciledExistingAccount( | ||
| authenticatedEmail: rawEmail, | ||
| existingAccountID: existingAccountID, | ||
| snapshot: snapshot) | ||
|
|
||
| account = ManagedCodexAccount( | ||
| id: existing?.id ?? UUID(), | ||
| email: rawEmail, | ||
| managedHomePath: homeURL.path, | ||
| createdAt: existing?.createdAt ?? now, | ||
| updatedAt: now, | ||
| lastAuthenticatedAt: now) | ||
| existingHomePathToDelete = existing?.managedHomePath | ||
|
|
||
| let updatedSnapshot = ManagedCodexAccountSet( | ||
| version: snapshot.version, | ||
| accounts: snapshot.accounts.filter { $0.id != account.id && $0.email != account.email } + [account], | ||
| activeAccountID: account.id) | ||
| try self.store.storeAccounts(updatedSnapshot) | ||
| } catch { | ||
| try? self.removeManagedHomeIfSafe(atPath: homeURL.path) | ||
| throw error | ||
| } | ||
|
|
||
| if let existingHomePathToDelete, existingHomePathToDelete != homeURL.path { | ||
| try? self.removeManagedHomeIfSafe(atPath: existingHomePathToDelete) | ||
| } | ||
| return account | ||
| } | ||
|
|
||
| func removeManagedAccount(id: UUID) async throws { | ||
| let snapshot = try self.store.loadAccounts() | ||
| guard let account = snapshot.account(id: id) else { return } | ||
|
|
||
| let homeURL = URL(fileURLWithPath: account.managedHomePath, isDirectory: true) | ||
| try self.homeFactory.validateManagedHomeForDeletion(homeURL) | ||
|
|
||
| let remaining = snapshot.accounts.filter { $0.id != id } | ||
| let nextActive = if snapshot.activeAccountID == id { | ||
| remaining.last?.id | ||
| } else { | ||
| snapshot.activeAccountID | ||
| } | ||
| try self.store.storeAccounts(ManagedCodexAccountSet( | ||
| version: snapshot.version, | ||
| accounts: remaining, | ||
| activeAccountID: nextActive)) | ||
|
|
||
| if self.fileManager.fileExists(atPath: homeURL.path) { | ||
| try? self.fileManager.removeItem(at: homeURL) | ||
| } | ||
| } | ||
|
|
||
| private func removeManagedHomeIfSafe(atPath path: String) throws { | ||
| let homeURL = URL(fileURLWithPath: path, isDirectory: true) | ||
| try self.homeFactory.validateManagedHomeForDeletion(homeURL) | ||
| if self.fileManager.fileExists(atPath: homeURL.path) { | ||
| try self.fileManager.removeItem(at: homeURL) | ||
| } | ||
| } | ||
|
|
||
| private func reconciledExistingAccount( | ||
| authenticatedEmail: String, | ||
| existingAccountID: UUID?, | ||
| snapshot: ManagedCodexAccountSet) | ||
| -> ManagedCodexAccount? | ||
| { | ||
| if let existingByEmail = snapshot.account(email: authenticatedEmail) { | ||
| return existingByEmail | ||
| } | ||
| guard let existingAccountID else { return nil } | ||
| guard let existingByID = snapshot.account(id: existingAccountID) else { return nil } | ||
| return existingByID.email == Self.normalizeEmail(authenticatedEmail) ? existingByID : nil | ||
| } | ||
|
|
||
| private static func normalizeEmail(_ email: String) -> String { | ||
| email.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() | ||
| } | ||
| } |
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
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
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.