feat(account): add multi-account switcher and passphrase vault

- Enable Windows multi-account sign-in via loopback PKCE OAuth and unified borderless quota cards with Ultra 5x/20x tier detection and instant cached-list preloading
- Keep active-account quota strictly on live host telemetry while supporting configurable background OAuth refresh intervals (10m-24h, default 1h) for saved backup accounts
- Add optional scrypt + AES-256-GCM secondary passphrase encryption with per-email AAD binding, unlock backoff, key zeroing, at-rest token minimization, and OAuth client_id allowlisting
- Harden account mutations with inline two-step switch/remove confirmations, HMAC action nonces, Webview context checks, standalone web 403 isolation, and user-only vault directory ACLs
This commit is contained in:
fish
2026-11-25 03:42:06 +09:00
parent b9dc2b960c
commit 1330b31ef7
32 changed files with 6737 additions and 364 deletions
+1559 -18
View File
File diff suppressed because it is too large Load Diff
+304 -33
View File
@@ -1,7 +1,11 @@
param([string]$JobPath = '')
$ErrorActionPreference = 'Stop'
[Console]::InputEncoding = [Text.UTF8Encoding]::new($false)
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
$utf8 = [Console]::OutputEncoding
$script:clientsToRestart = @()
$script:clientsStopped = $false
function Test-AccountFile($path) {
if (-not (Test-Path -LiteralPath $path)) { return $false }
@@ -26,11 +30,168 @@ function Write-AccountFile($path, [byte[]]$bytes) {
}
}
function Ensure-VaultDirectory($path) {
$dir = [IO.Path]::GetDirectoryName($path)
if (-not $dir) { return }
[void][IO.Directory]::CreateDirectory($dir)
if ([IO.Path]::GetFileName($dir) -ieq 'AntigravityUsageMonitor') {
try {
$acl = Get-Acl -LiteralPath $dir
if (-not $acl.AreAccessRulesProtected) {
$userSid = [Security.Principal.WindowsIdentity]::GetCurrent().User
$sysSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
$admSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$inherit = [Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
$prop = [Security.AccessControl.PropagationFlags]::None
$right = [Security.AccessControl.FileSystemRights]::FullControl
$allow = [Security.AccessControl.AccessControlType]::Allow
$acl.SetAccessRuleProtection($true, $false)
foreach ($rule in @($acl.Access)) { [void]$acl.RemoveAccessRule($rule) }
foreach ($sid in @($userSid, $sysSid, $admSid)) {
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid, $right, $inherit, $prop, $allow))
}
Set-Acl -LiteralPath $dir -AclObject $acl
}
} catch {}
}
try {
$cutoff = [DateTime]::UtcNow.AddMinutes(-10)
Get-ChildItem -LiteralPath $dir -Filter 'switch-*.dpapi' -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTimeUtc -lt $cutoff } |
ForEach-Object { [IO.File]::Delete($_.FullName) }
} catch {}
}
function Save-Vault($path, $vault) {
$bytes = $utf8.GetBytes((ConvertTo-Json -InputObject $vault -Depth 4 -Compress))
$encrypted = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser')
[void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($path))
Write-AccountFile $path $encrypted
$bytes = $utf8.GetBytes((ConvertTo-Json -InputObject $vault -Depth 10 -Compress))
try {
$encrypted = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser')
Ensure-VaultDirectory $path
Write-AccountFile $path $encrypted
} finally {
if ($bytes) { [Array]::Clear($bytes, 0, $bytes.Length) }
}
}
function Write-SwitchState($request, $state, $errorCode = '') {
$data = @{ email = $request.email; state = $state; error = $errorCode; updatedAt = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }
Write-AccountFile $request.statusFile ($utf8.GetBytes((ConvertTo-Json -InputObject $data -Compress)))
}
function Get-AccountClients {
$sessionId = (Get-Process -Id $PID).SessionId
$userSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$candidates = @(Get-CimInstance Win32_Process -Filter "Name = 'Antigravity.exe' OR Name = 'Antigravity IDE.exe' OR Name = 'agy.exe' OR Name = 'language_server.exe'")
$owned = @($candidates | Where-Object {
$_.SessionId -eq $sessionId -and $_.ExecutablePath -and (Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $userSid
})
$roots = @($owned | Where-Object {
$_.Name -in @('Antigravity.exe', 'Antigravity IDE.exe') -and
$_.CommandLine -notmatch '(?:^|\s)(?:--type|--import|--inspect|--inspect-brk|--ms-enable-electron-run-as-node)(?:=|\s)' -and
$_.CommandLine -notmatch 'sidecar_sdk[\\/]register_loader\.js' -and
[Diagnostics.FileVersionInfo]::GetVersionInfo($_.ExecutablePath).ProductName -like 'Antigravity*'
})
$installDirectories = @($roots | ForEach-Object { [IO.Path]::GetDirectoryName($_.ExecutablePath) + [IO.Path]::DirectorySeparatorChar } | Select-Object -Unique)
$agyCliHubPath = [IO.Path]::GetFullPath((Join-Path $env:USERPROFILE '.gemini\bin\agy.exe'))
$hubs = @($owned | Where-Object {
$candidate = $_
$trustedPath = [string]::Equals($candidate.ExecutablePath, $agyCliHubPath, [StringComparison]::OrdinalIgnoreCase) -or
@($installDirectories | Where-Object { $candidate.ExecutablePath.StartsWith($_, [StringComparison]::OrdinalIgnoreCase) }).Count -gt 0
($candidate.Name -eq 'language_server.exe' -or
($candidate.Name -eq 'agy.exe' -and $candidate.CommandLine -match '(?:^|\s)--hub(?:\s|$)')) -and $trustedPath
})
return @{ roots = $roots; hubs = $hubs; sessionId = $sessionId }
}
function Stop-AccountClients {
$snapshot = Get-AccountClients
$roots = $snapshot.roots
$hubs = $snapshot.hubs
$sessionId = $snapshot.sessionId
$byExe = @{}
$launch = @()
foreach ($root in $roots) {
$exeKey = $root.ExecutablePath.ToLowerInvariant()
$hasDebugPort = $root.CommandLine -match '(?:^|\s)--remote-debugging-port(?:=|\s)'
if (-not $byExe.ContainsKey($exeKey)) {
$entry = @{ path = $root.ExecutablePath; useDebugPort = [bool]$hasDebugPort }
$byExe[$exeKey] = $entry
$launch += $entry
} elseif ($hasDebugPort) {
$byExe[$exeKey].useDebugPort = $true
}
}
$script:clientsToRestart = $launch
$script:clientsStopped = $true
foreach ($root in $roots) {
$process = Get-Process -Id $root.ProcessId -ErrorAction SilentlyContinue
if ($process -and $process.MainWindowHandle -ne 0) { [void]$process.CloseMainWindow() }
}
$clientPaths = @($launch | ForEach-Object { $_.path })
if ($roots.Count) {
for ($i = 0; $i -lt 10; $i++) {
$aliveRoots = @(Get-Process -Id @($roots.ProcessId) -ErrorAction SilentlyContinue)
if ($aliveRoots.Count -eq 0) { break }
Start-Sleep -Milliseconds 150
}
}
$remaining = @(Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $sessionId -and $_.Path -in $clientPaths })
foreach ($process in $remaining) { Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue }
foreach ($hub in $hubs) {
if (Get-Process -Id $hub.ProcessId -ErrorAction SilentlyContinue) { Stop-Process -Id $hub.ProcessId -Force -ErrorAction SilentlyContinue }
}
foreach ($processId in @($remaining.Id) + @($hubs.ProcessId)) {
if ($processId) { Wait-Process -Id $processId -Timeout 10 -ErrorAction SilentlyContinue }
}
if (@(Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $sessionId -and $_.Path -in $clientPaths }).Count) {
throw 'clientCloseFailed'
}
foreach ($hub in $hubs) {
if (Get-Process -Id $hub.ProcessId -ErrorAction SilentlyContinue) { throw 'clientCloseFailed' }
}
}
function Start-AccountClients {
foreach ($envVar in @('ELECTRON_RUN_AS_NODE', 'ELECTRON_NO_ATTACH_CONSOLE', 'VSCODE_IPC_HOOK', 'CHROME_CRASHPAD_PIPE_NAME')) {
Remove-Item -Path ("Env:\" + $envVar) -ErrorAction SilentlyContinue
}
foreach ($client in $script:clientsToRestart) {
$start = @{ FilePath = $client.path; WorkingDirectory = [IO.Path]::GetDirectoryName($client.path) }
if ($client.useDebugPort) { $start.ArgumentList = '--remote-debugging-port=0' }
[void](Start-Process @start -PassThru)
}
$script:clientsToRestart = @()
$script:clientsStopped = $false
}
function Schedule-AccountSwitch($request) {
if (Test-AccountFile $request.statusFile) {
$status = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($request.statusFile))
if ($status.state -eq 'starting' -and ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $status.updatedAt) -lt 120000) {
return @{ error = 'busy' }
}
}
$request.action = 'switch'
$request | Add-Member -NotePropertyName restartClients -NotePropertyValue $true -Force
$job = Join-Path ([IO.Path]::GetDirectoryName($request.vault)) ('switch-' + [guid]::NewGuid().ToString() + '.dpapi')
Save-Vault $job $request
Write-SwitchState $request 'starting'
$scriptPath = $request.scriptPath.Replace("'", "''")
$jobLiteral = $job.Replace("'", "''")
$code = "& '$scriptPath' -JobPath '$jobLiteral'"
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code))
$shell = Join-Path $env:SystemRoot 'System32/WindowsPowerShell/v1.0/powershell.exe'
$command = '"' + $shell + '" -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand ' + $encoded
try {
# WMI starts the worker outside the client job so closing the App cannot terminate the switch.
$started = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = $command }
if ($started.ReturnValue -ne 0) { throw 'switchStartFailed' }
} catch {
[IO.File]::Delete($job)
Write-SwitchState $request 'failed' 'switchStartFailed'
return @{ error = 'switchStartFailed' }
}
return @{ scheduled = $true; accounts = @(); selectedEmail = $request.email }
}
function Add-NativeCredentialType {
@@ -114,91 +275,201 @@ function Invoke-AccountAction($request) {
$vault = @{ entries = @(); selectedEmail = '' }
if (Test-AccountFile $request.vault) {
$plain = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($request.vault), $null, 'CurrentUser')
$vault = ConvertFrom-Json -InputObject ($utf8.GetString($plain))
try {
$vault = ConvertFrom-Json -InputObject ($utf8.GetString($plain))
} finally {
if ($plain) { [Array]::Clear($plain, 0, $plain.Length) }
}
}
$vaultSecured = [bool]($vault.security -and $vault.security.enabled)
$entry = $vault.entries | Where-Object { $_.email -eq $request.email } | Select-Object -First 1
if ($null -ne $request.expectedCredential -and $entry.credential -cne $request.expectedCredential) {
return @{ error = 'credentialChanged' }
}
switch ($request.action) {
'inspectClients' {
$clients = Get-AccountClients
return @{ clients = @($clients.roots | ForEach-Object { @{ name = $_.Name; path = $_.ExecutablePath } }); hubs = $clients.hubs.Count }
}
'readVault' {
return @{
entries = @($vault.entries)
selectedEmail = [string]$vault.selectedEmail
security = $vault.security
}
}
'writeVault' {
$nextVault = @{
entries = @($request.entries)
selectedEmail = [string]$request.selectedEmail
}
if ($request.security) {
$nextVault.security = $request.security
}
Save-Vault $request.vault $nextVault
$vault = $nextVault
$vaultSecured = [bool]($vault.security -and $vault.security.enabled)
if ($request.clearStatus -and $request.statusFile -and (Test-AccountFile $request.statusFile)) {
try { [IO.File]::Delete($request.statusFile) } catch {}
}
}
'scheduleSwitch' {
if ($vaultSecured -and (-not $request.vaultUnlocked -or $request.expectedSecuritySalt -cne [string]$vault.security.salt)) {
return @{ error = 'vaultLocked' }
}
if (-not $entry) { return @{ error = 'notFound' } }
$scheduled = Schedule-AccountSwitch $request
$scheduled.accounts = @($vault.entries | ForEach-Object { $_.email })
if ($vaultSecured) {
$scheduled.security = @{ enabled = $true; salt = [string]$vault.security.salt }
}
return $scheduled
}
'readCurrent' {
Add-NativeCredentialType
$bytes = [NativeAccountCredential]::Read($request.target)
if (-not $bytes) {
foreach ($path in $request.fallbacks) {
if (Test-AccountFile $path) {
$bytes = [IO.File]::ReadAllBytes($path)
if ($bytes) { break }
try {
if (-not $bytes) {
foreach ($path in $request.fallbacks) {
if (Test-AccountFile $path) {
$bytes = [IO.File]::ReadAllBytes($path)
if ($bytes) { break }
}
}
}
if (-not $bytes) { return @{ error = 'noCurrentCredential' } }
return @{ credential = $utf8.GetString($bytes).TrimStart([char]0xfeff).Trim() }
} finally {
if ($bytes) { [Array]::Clear($bytes, 0, $bytes.Length) }
}
if (-not $bytes) { return @{ error = 'noCurrentCredential' } }
return @{ credential = $utf8.GetString($bytes).TrimStart([char]0xfeff).Trim() }
}
'read' {
if (-not $entry) { return @{ error = 'notFound' } }
return @{ credential = $entry.credential }
$readOut = @{ credential = $entry.credential }
if ($vaultSecured) {
$readOut.security = @{ enabled = $true; salt = [string]$vault.security.salt }
}
return $readOut
}
'save' {
if ($vaultSecured -and (-not $request.vaultUnlocked -or $request.expectedSecuritySalt -cne [string]$vault.security.salt)) {
return @{ error = 'vaultLocked' }
}
if ($entry) { $entry.credential = $request.credential }
else { $vault.entries = @($vault.entries) + @(@{ email = $request.email; credential = $request.credential }) }
Save-Vault $request.vault $vault
}
'saveQuota' {
if (-not $entry) { return @{ error = 'notFound' } }
$entry | Add-Member -NotePropertyName quota -NotePropertyValue $request.quota -Force
Save-Vault $request.vault $vault
}
'switch' {
if (-not $entry) { return @{ error = 'notFound' } }
$replacement = $utf8.GetBytes($request.credential)
if ($replacement.Length -gt 2560) { return @{ error = 'credentialTooLarge' } }
if ($replacement.Length -gt 2560) {
[Array]::Clear($replacement, 0, $replacement.Length)
return @{ error = 'credentialTooLarge' }
}
Add-NativeCredentialType
if ($request.restartClients) { Stop-AccountClients }
$previous = [NativeAccountCredential]::Read($request.target)
$fallbacks = @(foreach ($path in $request.fallbacks) {
if (Test-AccountFile $path) { @{ path = $path; original = [IO.File]::ReadAllBytes($path) } }
elseif ([IO.Directory]::Exists([IO.Path]::GetDirectoryName($path))) { @{ path = $path; original = $null } }
})
$written = @()
[NativeAccountCredential]::Write($request.target, $replacement)
try {
foreach ($fallback in $fallbacks) {
Write-AccountFile $fallback.path $replacement
$written += $fallback
[NativeAccountCredential]::Write($request.target, $replacement)
try {
foreach ($fallback in $fallbacks) {
Write-AccountFile $fallback.path $replacement
$written += $fallback
}
$entry.credential = if ($request.vaultCredential) { $request.vaultCredential } else { $entry.credential }
$vault.selectedEmail = $request.email
Save-Vault $request.vault $vault
} catch {
$restored = $true
try { [NativeAccountCredential]::Restore($request.target, $previous) } catch { $restored = $false }
foreach ($fallback in $written) {
try {
if ($null -eq $fallback.original) { [IO.File]::Delete($fallback.path) }
else { Write-AccountFile $fallback.path $fallback.original }
} catch { $restored = $false }
}
if (-not $restored) { return @{ error = 'rollbackFailed' } }
throw
}
$entry.credential = $request.credential
$vault.selectedEmail = $request.email
Save-Vault $request.vault $vault
} catch {
$restored = $true
try { [NativeAccountCredential]::Restore($request.target, $previous) } catch { $restored = $false }
foreach ($fallback in $written) {
try { Write-AccountFile $fallback.path $fallback.original } catch { $restored = $false }
}
if (-not $restored) { return @{ error = 'rollbackFailed' } }
throw
} finally {
if ($replacement) { [Array]::Clear($replacement, 0, $replacement.Length) }
if ($previous) { [Array]::Clear($previous, 0, $previous.Length) }
}
}
'remove' {
if ($vaultSecured -and (-not $request.vaultUnlocked -or $request.expectedSecuritySalt -cne [string]$vault.security.salt)) {
return @{ error = 'vaultLocked' }
}
if (-not $entry) { return @{ error = 'notFound' } }
$vault.entries = @($vault.entries | Where-Object { $_.email -ne $request.email })
if ($vault.selectedEmail -eq $request.email) { $vault.selectedEmail = '' }
Save-Vault $request.vault $vault
if ($request.statusFile -and (Test-AccountFile $request.statusFile)) {
try {
$st = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($request.statusFile))
if ($st.email -eq $request.email -and $st.state -ne 'starting') { [IO.File]::Delete($request.statusFile) }
} catch {}
}
}
}
return @{ accounts = @($vault.entries | ForEach-Object { $_.email }); selectedEmail = $vault.selectedEmail }
$quotas = @{}
foreach ($account in $vault.entries) { if ($account.quota) { $quotas[$account.email] = $account.quota } }
$result = @{ accounts = @($vault.entries | ForEach-Object { $_.email }); selectedEmail = $vault.selectedEmail; quotas = $quotas }
if ($vaultSecured) {
$result.security = @{ enabled = $true; salt = [string]$vault.security.salt }
}
if ($request.statusFile -and (Test-AccountFile $request.statusFile)) {
try { $result.switchState = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($request.statusFile)) } catch {}
}
return $result
}
$mutex = $null
$locked = $false
try {
$request = ConvertFrom-Json -InputObject ([Console]::In.ReadToEnd())
if ($JobPath) {
Add-Type -AssemblyName System.Security
$jobPlain = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($JobPath), $null, 'CurrentUser')
try {
$request = ConvertFrom-Json -InputObject ($utf8.GetString($jobPlain))
} finally {
if ($jobPlain) { [Array]::Clear($jobPlain, 0, $jobPlain.Length) }
}
} else {
$request = ConvertFrom-Json -InputObject ([Console]::In.ReadToEnd())
}
$mutex = [Threading.Mutex]::new($false, 'Local\AntigravityUsageMonitor.AccountCredentials')
try { $locked = $mutex.WaitOne(4000) } catch [Threading.AbandonedMutexException] { $locked = $true }
$waitTimeoutMs = if ($JobPath) { 15000 } else { 5000 }
try { $locked = $mutex.WaitOne($waitTimeoutMs) } catch [Threading.AbandonedMutexException] { $locked = $true }
$result = if ($locked) { Invoke-AccountAction $request } else { @{ error = 'busy' } }
if ($JobPath) { Write-SwitchState $request $(if ($result.error) { 'failed' } else { 'written' }) $result.error }
} catch {
$result = @{ error = 'storeFailed' }
$nativeError = $_.Exception.InnerException
if ($nativeError -is [ComponentModel.Win32Exception] -and $nativeError.NativeErrorCode -in 5, 1312) {
$result.error = 'credentialAccessDenied'
}
if ($_.Exception.Message -match 'clientCloseFailed') { $result.error = 'clientCloseFailed' }
if ($JobPath -and $request) { Write-SwitchState $request 'failed' $result.error }
} finally {
if ($JobPath) {
if ($script:clientsStopped) {
try { Start-AccountClients } catch { Write-SwitchState $request 'failed' 'clientRestartFailed' }
}
[IO.File]::Delete($JobPath)
}
if ($locked) { $mutex.ReleaseMutex() }
if ($mutex) { $mutex.Dispose() }
}
[Console]::Write((ConvertTo-Json -InputObject $result -Compress))
[Console]::Write((ConvertTo-Json -InputObject $result -Depth 10 -Compress))
+67
View File
@@ -0,0 +1,67 @@
/** @fileoverview Google account requests using the panel's system proxy transport. */
import * as http from 'node:http';
import * as https from 'node:https';
import * as net from 'node:net';
import * as tls from 'node:tls';
import { detectSystemHttpsProxy, openCcProxyTunnelSocket } from './cloudcode-proxy.mjs';
export async function fetchGoogleAccount(url, { method = 'GET', body, headers = {}, signal } = {}) {
const target = new URL(url);
if (target.protocol !== 'https:' || !/^(?:oauth2|www|cloudcode-pa|daily-cloudcode-pa(?:\.sandbox)?)\.googleapis\.com$/.test(target.hostname)) {
throw new Error('Unsupported Google account endpoint');
}
signal?.throwIfAborted();
const proxy = await detectSystemHttpsProxy(target.hostname);
signal?.throwIfAborted();
const socket = proxy
? await openCcProxyTunnelSocket({ http, https, net, tls }, target.hostname, 443, proxy, { timeoutMs: 4500 })
: null;
if (signal?.aborted) {
socket?.destroy();
signal.throwIfAborted();
}
const textBody = body === undefined ? undefined : String(body);
const requestHeaders = { Accept: 'application/json', ...headers };
if (body instanceof URLSearchParams) requestHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
if (textBody !== undefined) requestHeaders['Content-Length'] = Buffer.byteLength(textBody);
let socketConsumed = false;
const agent = socket ? new https.Agent({ keepAlive: false }) : null;
if (agent) {
agent.createConnection = () => {
socketConsumed = true;
return socket;
};
}
const onAbort = () => {
if (!socketConsumed) socket?.destroy();
};
signal?.addEventListener?.('abort', onAbort, { once: true });
return new Promise((resolve, reject) => {
const request = https.request(target, { method, headers: requestHeaders, signal, ...(agent ? { agent } : {}) }, (response) => {
const chunks = [];
let bytes = 0;
response.on('data', (chunk) => {
bytes += chunk.length;
if (bytes > 4 * 1024 * 1024) return request.destroy(new Error('Account response too large'));
chunks.push(chunk);
});
response.on('error', reject);
response.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
const status = response.statusCode || 0;
resolve({ status, ok: status >= 200 && status < 300, json: async () => JSON.parse(raw) });
});
});
request.on('error', (err) => {
if (!socketConsumed) socket?.destroy();
reject(err);
});
request.on('close', () => {
signal?.removeEventListener?.('abort', onAbort);
agent?.destroy();
});
request.end(textBody);
});
}
+168
View File
@@ -0,0 +1,168 @@
/** @fileoverview Browser authorization and loopback callbacks for adding Google accounts. */
import { execFile } from 'node:child_process';
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import { createServer } from 'node:http';
import { join } from 'node:path';
import { buildGoogleAccountLoginUrl, exchangeGoogleAccountCode } from './account-oauth.mjs';
function openGoogleAccountBrowser(url) {
const shell = join(process.env.SystemRoot || 'C:/Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
return new Promise((resolve) => {
execFile(shell, ['-NoProfile', '-NonInteractive', '-Command', 'Start-Process -FilePath $env:USAGE_MONITOR_LOGIN_URL'], {
windowsHide: true, timeout: 5000,
env: { ...process.env, USAGE_MONITOR_LOGIN_URL: url },
}, (error) => resolve(!error));
});
}
function loginCallbackPage(language, success) {
const english = language === 'en-US';
const title = english ? success ? 'Account added' : 'Sign-in incomplete' : success ? '账号已添加' : '登录未完成';
const detail = english ? 'Return to the Antigravity account page. You can close this browser tab.' : '请返回 Antigravity 的账号页,可关闭此浏览器标签页。';
return `<!doctype html><html lang="${english ? 'en' : 'zh-CN'}"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${title}</title><style>body{font:16px system-ui,sans-serif;max-width:36rem;margin:15vh auto;padding:24px;line-height:1.6}h1{font-size:24px}</style><h1>${title}</h1><p>${detail}</p></html>`;
}
export function createAccountLoginController({
openBrowser = openGoogleAccountBrowser,
buildLoginUrl = buildGoogleAccountLoginUrl,
exchangeCode = exchangeGoogleAccountCode,
getClients,
timeoutMs = 10 * 60 * 1000,
} = {}) {
let current = null;
let starting = null;
function snapshot(flow = current) {
if (!flow) return null;
return { id: flow.id, status: flow.status, error: flow.error || '',
...(flow.status === 'waiting' ? { url: flow.url, opened: flow.opened } : {}),
...(flow.email ? { email: flow.email } : {}) };
}
function finish(flow, status, error = '') {
clearTimeout(flow.timer);
flow.status = status;
flow.error = error;
flow.server?.close();
flow.codeVerifier = '';
}
function cancel(id) {
if (!current || current.id !== id) return null;
if (current.status === 'waiting' || current.status === 'exchanging') finish(current, 'cancelled');
return snapshot();
}
async function start(onCredential, language = 'zh-CN') {
if (starting) return starting;
if (current && ['waiting', 'exchanging', 'saving'].includes(current.status)) return snapshot();
starting = prepare(onCredential, language).finally(() => { starting = null; });
return starting;
}
async function prepare(onCredential, language) {
const flow = { id: randomUUID(), state: randomBytes(32).toString('base64url'),
codeVerifier: randomBytes(32).toString('base64url'), status: 'waiting', opened: false };
current = flow;
const server = createServer({ maxHeaderSize: 16384 }, async (request, response) => {
response.setHeader('Cache-Control', 'no-store');
response.setHeader('Referrer-Policy', 'no-referrer');
response.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'");
let url;
try { url = new URL(request.url || '/', 'http://127.0.0.1'); } catch {
response.writeHead(400).end();
return;
}
if (!flow.redirectUri || request.method !== 'GET' || request.headers.host !== new URL(flow.redirectUri).host || url.pathname !== '/oauth-callback') {
response.writeHead(404).end();
return;
}
if (url.searchParams.get('state') !== flow.state) {
response.writeHead(400).end();
return;
}
if (current !== flow || flow.status !== 'waiting') {
response.writeHead(409).end();
return;
}
response.setHeader('Content-Type', 'text/html; charset=utf-8');
if (url.searchParams.has('error')) {
finish(flow, 'cancelled', 'loginDenied');
response.writeHead(200).end(loginCallbackPage(language, false));
return;
}
const code = url.searchParams.get('code');
if (!code || code.length > 4096) {
response.writeHead(400).end(loginCallbackPage(language, false));
return;
}
flow.status = 'exchanging';
try {
const credential = await exchangeCode(
code,
flow.redirectUri,
flow.codeVerifier,
getClients ? { getClients } : undefined
);
if (current !== flow || flow.status !== 'exchanging') {
response.writeHead(409).end(loginCallbackPage(language, false));
return;
}
flow.status = 'saving';
await onCredential(credential);
flow.email = credential.email;
finish(flow, 'success');
response.writeHead(200).end(loginCallbackPage(language, true));
} catch (error) {
if (current === flow && ['exchanging', 'saving'].includes(flow.status)) {
const preservedError = [
'storeFailed',
'credentialTooLarge',
'credentialAccessDenied',
'busy',
'oauthClientUnavailable',
].includes(error?.message);
finish(flow, 'error', preservedError ? error.message : 'loginExchangeFailed');
}
response.writeHead(500).end(loginCallbackPage(language, false));
}
});
flow.server = server;
server.headersTimeout = 10000;
server.requestTimeout = 30000;
server.keepAliveTimeout = 1000;
try {
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => { server.off('error', reject); resolve(); });
});
flow.redirectUri = `http://127.0.0.1:${server.address().port}/oauth-callback`;
const challenge = createHash('sha256').update(flow.codeVerifier).digest('base64url');
flow.url = await buildLoginUrl(
flow.redirectUri,
flow.state,
challenge,
getClients ? { getClients } : undefined
);
server.unref();
flow.timer = setTimeout(() => {
if (current === flow && ['waiting', 'exchanging'].includes(flow.status)) finish(flow, 'expired', 'loginExpired');
}, timeoutMs);
flow.timer.unref?.();
flow.opened = await openBrowser(flow.url).catch(() => false);
return snapshot(flow);
} catch (error) {
finish(
flow,
'error',
error?.message === 'oauthClientUnavailable' ? 'oauthClientUnavailable' : 'loginStartFailed'
);
return snapshot(flow);
}
}
return { start, cancel, getStatus: (id) => !id || current?.id === id ? snapshot() : null };
}
export const accountLoginController = createAccountLoginController();
+444 -69
View File
@@ -1,86 +1,413 @@
/** @fileoverview Google OAuth identity and quota queries for saved Antigravity credentials. */
import { readFile } from 'node:fs/promises';
import { execFile } from 'node:child_process';
import { createHash } from 'node:crypto';
import { existsSync, promises as fsPromises } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { basename, dirname, join } from 'node:path';
import { fetchGoogleAccount } from './account-http.mjs';
import { buildOfficialQuotaPools } from './quota-pools.mjs';
const OAUTH_TOKEN_URL = 'https://oauth2.googleapis.com/token';
const OAUTH_USER_URL = 'https://www.googleapis.com/oauth2/v2/userinfo';
const CLOUD_CODE_HOSTS = ['cloudcode-pa.googleapis.com', 'daily-cloudcode-pa.googleapis.com'];
let nativeOAuthClients;
const CLOUD_CODE_HOSTS = [
'daily-cloudcode-pa.googleapis.com',
'cloudcode-pa.googleapis.com',
'daily-cloudcode-pa.sandbox.googleapis.com',
];
const OAUTH_CLIENT_ID_RE = /^\d+-[\w-]+\.apps\.googleusercontent\.com$/;
const OAUTH_CLIENT_SECRET_RE = /^GOCSPX-[\w-]+$/;
// One-way SHA-256 digest of the official Antigravity desktop OAuth client_id for synchronous allowlist checks
// without embedding plaintext OAuth credentials in source control.
const OFFICIAL_OAUTH_CLIENT_ID_HASHES = Object.freeze(
new Set(['bf00c418024ba6bf606ccdc37120976e41bc429dd1d46ecf16a729aa532626ea'])
);
const ACCOUNT_USER_AGENT = `antigravity/hub/4.3.0 (os_type=${process.platform === 'win32' ? 'windows' : process.platform}; arch=${process.arch === 'x64' ? 'amd64' : process.arch})`;
const PE_ID_LEN_OP = Buffer.from([0x48, 0xc7, 0x40, 0x08]);
const PE_LEA_RIP_OP = Buffer.from([0x48, 0x8d, 0x0d]);
const PE_BETWEEN_OP = Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]);
let nativeOAuthClientsPromise = null;
const discoveredAllowedClientIds = new Set();
function sha256Hex(value) {
return createHash('sha256').update(String(value || ''), 'utf8').digest('hex');
}
function parsePeTextAndRdata(headerBuf) {
if (!Buffer.isBuffer(headerBuf) || headerBuf.length < 64) return null;
const pe = headerBuf.readUInt16LE(0) === 0x5a4d ? headerBuf.readUInt32LE(60) : 0;
if (!pe || pe + 24 > headerBuf.length || headerBuf.readUInt32LE(pe) !== 0x4550 || headerBuf.readUInt16LE(pe + 4) !== 0x8664) {
return null;
}
const count = headerBuf.readUInt16LE(pe + 6);
const table = pe + 24 + headerBuf.readUInt16LE(pe + 20);
if (table + count * 40 > headerBuf.length) return null;
let text = null;
let rodata = null;
for (let i = 0; i < count; i += 1) {
const offset = table + i * 40;
const name = headerBuf.toString('ascii', offset, offset + 8).replace(/\0+$/, '');
const section = {
name,
rva: headerBuf.readUInt32LE(offset + 12),
size: headerBuf.readUInt32LE(offset + 16),
start: headerBuf.readUInt32LE(offset + 20),
};
if (name === '.text') text = section;
else if (name === '.rdata') rodata = section;
}
return text && rodata ? { text, rodata } : null;
}
// Go's x64 OAuth config initializer stores ClientID and ClientSecret as two consecutive pointer/length pairs.
function scanGoOAuthInitializerMatches(machineCode, textRva, rodata) {
const matches = [];
for (
let i = machineCode.indexOf(PE_ID_LEN_OP);
i >= 0 && i + 33 <= machineCode.length;
i = machineCode.indexOf(PE_ID_LEN_OP, i + 1)
) {
if (
!machineCode.subarray(i + 8, i + 11).equals(PE_LEA_RIP_OP) ||
!machineCode.subarray(i + 15, i + 22).equals(PE_BETWEEN_OP) ||
!machineCode.subarray(i + 26, i + 29).equals(PE_LEA_RIP_OP)
) {
continue;
}
const idLen = machineCode.readUInt32LE(i + 4);
const secretLen = machineCode.readUInt32LE(i + 22);
if (idLen <= 0 || idLen > 100 || secretLen <= 0 || secretLen > 100) continue;
const idRva = textRva + (i + 11) + 4 + machineCode.readInt32LE(i + 11);
const secretRva = textRva + (i + 29) + 4 + machineCode.readInt32LE(i + 29);
const idOffset = idRva - rodata.rva;
const secretOffset = secretRva - rodata.rva;
if (
idOffset < 0 ||
idOffset + idLen > rodata.size ||
secretOffset < 0 ||
secretOffset + secretLen > rodata.size
) {
continue;
}
matches.push({ idOffset, idLen, secretOffset, secretLen });
}
return matches;
}
export function extractNativeOAuthClients(binary) {
const pe = binary.length >= 64 && binary.readUInt16LE(0) === 0x5a4d ? binary.readUInt32LE(60) : 0;
if (!pe || pe + 24 > binary.length || binary.readUInt32LE(pe) !== 0x4550 || binary.readUInt16LE(pe + 4) !== 0x8664) return [];
const count = binary.readUInt16LE(pe + 6);
const table = pe + 24 + binary.readUInt16LE(pe + 20);
if (table + count * 40 > binary.length) return [];
const sections = Array.from({ length: count }, (_, i) => {
const offset = table + i * 40;
return {
name: binary.toString('ascii', offset, offset + 8).replace(/\0+$/, ''),
rva: binary.readUInt32LE(offset + 12),
size: binary.readUInt32LE(offset + 16),
start: binary.readUInt32LE(offset + 20),
};
});
const text = sections.find(({ name }) => name === '.text');
const rodata = sections.find(({ name }) => name === '.rdata');
if (!text || !rodata || text.start + text.size > binary.length || rodata.start + rodata.size > binary.length) return [];
const machineCode = binary.subarray(text.start, text.start + text.size);
function readLiteral(displacementOffset, length) {
const rva = text.rva + displacementOffset + 4 + machineCode.readInt32LE(displacementOffset);
const offset = rva - rodata.rva;
if (length > 100 || offset < 0 || offset + length > rodata.size) return '';
return binary.toString('ascii', rodata.start + offset, rodata.start + offset + length);
const sections = parsePeTextAndRdata(binary);
if (!sections) return [];
const { text, rodata } = sections;
if (text.start + text.size > binary.length || rodata.start + rodata.size > binary.length) {
return [];
}
// Go's x64 OAuth config initializer sets ClientID and ClientSecret as two consecutive pointer/length pairs.
const idLength = Buffer.from([0x48, 0xc7, 0x40, 0x08]);
const loadAndStoreId = Buffer.from([0x48, 0x8d, 0x0d]);
const betweenLiterals = Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]);
const machineCode = binary.subarray(text.start, text.start + text.size);
const clients = new Map();
for (let i = machineCode.indexOf(idLength); i >= 0 && i + 33 <= machineCode.length; i = machineCode.indexOf(idLength, i + 1)) {
if (!machineCode.subarray(i + 8, i + 11).equals(loadAndStoreId) ||
!machineCode.subarray(i + 15, i + 22).equals(betweenLiterals) ||
!machineCode.subarray(i + 26, i + 29).equals(loadAndStoreId)) continue;
const id = readLiteral(i + 11, machineCode.readUInt32LE(i + 4));
const secret = readLiteral(i + 29, machineCode.readUInt32LE(i + 22));
if (/^\d+-[\w-]+\.apps\.googleusercontent\.com$/.test(id) && /^GOCSPX-[\w-]+$/.test(secret)) {
for (const m of scanGoOAuthInitializerMatches(machineCode, text.rva, rodata)) {
const id = binary.toString('ascii', rodata.start + m.idOffset, rodata.start + m.idOffset + m.idLen);
const secret = binary.toString('ascii', rodata.start + m.secretOffset, rodata.start + m.secretOffset + m.secretLen);
if (OAUTH_CLIENT_ID_RE.test(id) && OAUTH_CLIENT_SECRET_RE.test(secret)) {
clients.set(id, { id, secret });
}
}
return Array.from(clients.values()).reverse();
}
async function loadNativeOAuthClients() {
if (!nativeOAuthClients) {
nativeOAuthClients = (async () => {
const local = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local');
const binaries = [
join(local, 'Programs', 'Antigravity', 'resources', 'bin', 'language_server.exe'),
join(homedir(), '.gemini', 'bin', 'agy.exe'),
];
for (const filename of binaries) {
const binary = await readFile(filename).catch(() => null);
const clients = binary ? extractNativeOAuthClients(binary) : [];
if (clients.length) return clients;
async function extractNativeOAuthClientsFromFile(filePath) {
if (typeof fsPromises === 'undefined' || typeof fsPromises?.open !== 'function') {
return [];
}
let handle = null;
try {
handle = await fsPromises.open(filePath, 'r');
const st = await handle.stat();
if (!st.isFile() || st.size < 64) return [];
const headerLen = Math.min(4096, st.size);
const headerBuf = Buffer.alloc(headerLen);
await handle.read(headerBuf, 0, headerLen, 0);
const sections = parsePeTextAndRdata(headerBuf);
if (!sections) return [];
const { text, rodata } = sections;
if (text.start + text.size > st.size || rodata.start + rodata.size > st.size) {
return [];
}
// Read only .text into memory and fetch matching <=100B literals directly from .rdata on demand.
const textBuf = Buffer.allocUnsafe(text.size);
let offset = 0;
while (offset < text.size) {
const { bytesRead } = await handle.read(textBuf, offset, text.size - offset, text.start + offset);
if (bytesRead <= 0) return [];
offset += bytesRead;
}
const matches = scanGoOAuthInitializerMatches(textBuf, text.rva, rodata);
const clients = new Map();
for (const m of matches) {
const idBuf = Buffer.allocUnsafe(m.idLen);
const secBuf = Buffer.allocUnsafe(m.secretLen);
const [idRead, secRead] = await Promise.all([
handle.read(idBuf, 0, m.idLen, rodata.start + m.idOffset),
handle.read(secBuf, 0, m.secretLen, rodata.start + m.secretOffset),
]);
if (idRead.bytesRead !== m.idLen || secRead.bytesRead !== m.secretLen) continue;
const id = idBuf.toString('ascii');
const secret = secBuf.toString('ascii');
if (OAUTH_CLIENT_ID_RE.test(id) && OAUTH_CLIENT_SECRET_RE.test(secret)) {
clients.set(id, { id, secret });
}
}
return Array.from(clients.values()).reverse();
} catch {
return [];
} finally {
await handle?.close?.().catch(() => {});
}
}
export function collectNativeOAuthBinaryCandidates({
env = process.env,
homeDir = homedir(),
existsFn = existsSync,
} = {}) {
const seen = new Set();
const candidates = [];
const add = (filePath) => {
const clean = String(filePath || '').trim();
if (!clean) return;
const key = clean.toLowerCase();
if (seen.has(key)) return;
seen.add(key);
candidates.push(clean);
};
const addFromInstallRoot = (installRoot) => {
if (!installRoot) return;
add(join(installRoot, 'resources', 'bin', 'language_server.exe'));
add(join(installRoot, 'resources', 'app', 'extensions', 'antigravity', 'bin', 'language_server_windows_x64.exe'));
};
add(env?.ANTIGRAVITY_LS_BIN);
const hints = [
env?.USAGE_MONITOR_HOST_EXE,
env?.ANTIGRAVITY_AGENTAPI_EXE,
env?.CHROME_DEVTOOLS_MCP_JS,
];
for (const rawHint of hints) {
const hint = String(rawHint || '').trim();
if (!hint) continue;
const leaf = basename(hint).toLowerCase();
if (/^(?:language_server.*|agy)\.exe$/i.test(leaf)) {
add(hint);
continue;
}
if (/\.exe$/i.test(leaf)) {
addFromInstallRoot(dirname(hint));
}
let cur = hint;
for (let depth = 0; depth < 8 && cur && dirname(cur) !== cur; depth += 1) {
if (basename(cur).toLowerCase() === 'resources') {
addFromInstallRoot(dirname(cur));
break;
}
cur = dirname(cur);
}
}
const localAppData = String(env?.LOCALAPPDATA || '').trim() || join(homeDir, 'AppData', 'Local');
const programFiles = String(env?.ProgramFiles || '').trim() || 'C:\\Program Files';
const geminiBase = String(env?.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homeDir, '.gemini');
addFromInstallRoot(join(localAppData, 'Programs', 'Antigravity'));
addFromInstallRoot(join(localAppData, 'Programs', 'Antigravity IDE'));
addFromInstallRoot(join(programFiles, 'Antigravity'));
addFromInstallRoot(join(programFiles, 'Antigravity IDE'));
add(join(geminiBase, 'bin', 'agy.exe'));
if (typeof existsFn !== 'function') return candidates;
return candidates.filter((p) => {
try {
return Boolean(existsFn(p));
} catch {
return false;
}
});
}
function discoverRunningOAuthBinaryPaths() {
if (process.platform !== 'win32' || typeof execFile !== 'function') {
return Promise.resolve([]);
}
const shell = join(
process.env.SystemRoot || 'C:/Windows',
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe'
);
const cmd =
"Get-CimInstance Win32_Process -Filter \"Name LIKE 'language_server%' OR Name LIKE 'agy%'\" | Select-Object -ExpandProperty ExecutablePath -Unique";
return new Promise((resolve) => {
execFile(
shell,
['-NoProfile', '-NonInteractive', '-Command', cmd],
{ windowsHide: true, timeout: 3000, encoding: 'utf8' },
(err, stdout) => {
if (err || !stdout) {
resolve([]);
return;
}
const paths = String(stdout)
.split(/\r?\n/)
.map((line) => line.trim())
.filter((p) => /^(?:language_server.*|agy)\.exe$/i.test(basename(p)));
resolve(paths);
}
return [];
})();
);
});
}
function rememberDiscoveredClients(clients) {
for (const client of clients) {
if (client?.id) discoveredAllowedClientIds.add(client.id);
}
return Object.freeze(clients.map((c) => Object.freeze({ id: c.id, secret: c.secret })));
}
export async function loadNativeOAuthClients(options = undefined) {
const customRun = Boolean(options && Object.keys(options).length > 0);
const env = options?.env ?? process.env;
const overrideId = String(env?.USAGE_MONITOR_OAUTH_CLIENT_ID || '').trim();
const overrideSecret = String(env?.USAGE_MONITOR_OAUTH_CLIENT_SECRET || '').trim();
if (OAUTH_CLIENT_ID_RE.test(overrideId) && OAUTH_CLIENT_SECRET_RE.test(overrideSecret)) {
return rememberDiscoveredClients([{ id: overrideId, secret: overrideSecret }]);
}
const runLoad = async () => {
const extractFromFileFn = options?.extractFromFileFn || extractNativeOAuthClientsFromFile;
const discoverRunningFn = options?.discoverRunningFn || discoverRunningOAuthBinaryPaths;
const candidates = collectNativeOAuthBinaryCandidates({
env,
homeDir: options?.homeDir ?? homedir(),
existsFn: options?.existsFn ?? existsSync,
});
const tried = new Set();
for (const filePath of candidates) {
tried.add(filePath.toLowerCase());
const clients = await extractFromFileFn(filePath);
if (Array.isArray(clients) && clients.length > 0) {
return rememberDiscoveredClients(clients);
}
}
const runningPaths = await discoverRunningFn().catch(() => []);
for (const filePath of runningPaths) {
const key = String(filePath || '').trim().toLowerCase();
if (!key || tried.has(key)) continue;
tried.add(key);
const clients = await extractFromFileFn(filePath);
if (Array.isArray(clients) && clients.length > 0) {
return rememberDiscoveredClients(clients);
}
}
return Object.freeze([]);
};
if (customRun) {
return runLoad();
}
if (!nativeOAuthClientsPromise) {
nativeOAuthClientsPromise = runLoad();
}
const clients = await nativeOAuthClientsPromise;
if (!clients.length) {
nativeOAuthClientsPromise = null;
}
const clients = await nativeOAuthClients;
if (!clients.length) nativeOAuthClients = null;
return clients;
}
export async function resolveGoogleCredential(credential, { refresh = false, fetchFn = fetch, getClients = loadNativeOAuthClients } = {}) {
export function isAllowedOAuthClientId(clientId, allowedIds = null) {
if (typeof clientId !== 'string') return false;
const clean = clientId.trim();
if (!clean) return false;
if (allowedIds) {
if (allowedIds instanceof Set && allowedIds.has(clean)) return true;
if (Array.isArray(allowedIds) && allowedIds.includes(clean)) return true;
}
if (discoveredAllowedClientIds.has(clean)) return true;
return OFFICIAL_OAUTH_CLIENT_ID_HASHES.has(sha256Hex(clean));
}
export async function buildGoogleAccountLoginUrl(
redirectUri,
state,
codeChallenge,
{ getClients = loadNativeOAuthClients } = {}
) {
const clients = await getClients();
if (!Array.isArray(clients) || !clients.length || !clients[0]?.id) {
throw new Error('oauthClientUnavailable');
}
const url = new URL('https://accounts.google.com/o/oauth2/v2/auth');
url.search = new URLSearchParams({
client_id: clients[0].id,
redirect_uri: redirectUri,
response_type: 'code',
scope: [
'openid',
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/aicode',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/cclog',
'https://www.googleapis.com/auth/experimentsandconfigs',
].join(' '),
access_type: 'offline',
prompt: 'consent select_account',
state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
}).toString();
return url.toString();
}
export async function exchangeGoogleAccountCode(
code,
redirectUri,
codeVerifier,
{ fetchFn = fetchGoogleAccount, getClients = loadNativeOAuthClients } = {}
) {
const clients = await getClients();
if (!Array.isArray(clients) || !clients.length || !clients[0]?.id || !clients[0]?.secret) {
throw new Error('oauthClientUnavailable');
}
const client = clients[0];
const response = await fetchFn(OAUTH_TOKEN_URL, {
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(15000),
headers: { 'User-Agent': ACCOUNT_USER_AGENT },
body: new URLSearchParams({
client_id: client.id,
client_secret: client.secret,
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier,
}),
});
const result = await response.json();
if (!response.ok || !result.access_token || !result.refresh_token ||
!Number.isFinite(result.expires_in) || result.expires_in <= 0) throw new Error('loginExchangeFailed');
return resolveGoogleCredential({
token: { ...result, expiry: new Date(Date.now() + result.expires_in * 1000).toISOString() },
...(result.id_token ? { id_token: result.id_token } : {}),
}, { fetchFn, getClients: async () => clients });
}
export async function resolveGoogleCredential(
credential,
{ refresh = false, fetchFn = fetchGoogleAccount, getClients = loadNativeOAuthClients } = {}
) {
let { access_token: accessToken, refresh_token: refreshToken, expiry } = credential.token;
let idToken = credential.id_token;
if (refresh || !accessToken || Date.parse(expiry) <= Date.now() + 60_000) {
if (refresh || !accessToken || !Number.isFinite(Date.parse(expiry)) || Date.parse(expiry) <= Date.now() + 60_000) {
const clients = await getClients();
if (!clients.length) throw new Error('oauthClientUnavailable');
let refreshed = false;
@@ -117,23 +444,67 @@ export async function resolveGoogleCredential(credential, { refresh = false, fet
auth_method: 'consumer',
id_token_email: user.email,
...(idToken ? { id_token: idToken } : {}),
...(Number.isSafeInteger(credential.aicode_scope_sign_out_attempted_at) &&
credential.aicode_scope_sign_out_attempted_at > 0
? { aicode_scope_sign_out_attempted_at: credential.aicode_scope_sign_out_attempted_at }
: {}),
},
};
}
export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
async function post(method, data) {
for (const host of CLOUD_CODE_HOSTS) {
export function resolveSetupTierInfo(setup) {
const tierObj = setup?.paidTier || setup?.currentTier || setup?.userTier || null;
if (!tierObj) return null;
const tierId = String(tierObj?.id || '').trim();
const rawName = String(tierObj?.name || '').trim();
const rawDesc = String(tierObj?.description || '').trim();
const tierIdLower = tierId.toLowerCase();
const tierText = `${tierId} ${rawName} ${rawDesc}`;
const tierMultiplier = /(?:^|[-_\s])5x(?:$|[-_\s])|ultra[-_]?lite/i.test(tierText)
? '5x'
: /(?:^|[-_\s])20x(?:$|[-_\s])/i.test(tierText) ||
tierIdLower === 'g1-ultra-tier' ||
(/^g1-ultra(?:-[a-z0-9]+)?-tier$/i.test(tierIdLower) && !/lite|5x/i.test(tierIdLower))
? '20x'
: '';
const tierName =
rawName ||
(/ultra/i.test(tierIdLower)
? 'Google AI Ultra'
: /pro/i.test(tierIdLower)
? 'Google AI Pro'
: /free|standard/i.test(tierIdLower)
? 'Google AI Free'
: '');
if (!tierName && !tierId) return null;
return { tierId, tierName: tierName || 'Google AI', tierMultiplier };
}
export async function retrieveCredentialQuota(accessToken, fetchFn = fetchGoogleAccount) {
let preferredHost = '';
async function post(method, data, retryWithoutProject = true) {
const hosts = preferredHost
? [preferredHost, ...CLOUD_CODE_HOSTS.filter((h) => h !== preferredHost)]
: CLOUD_CODE_HOSTS;
for (const host of hosts) {
const response = await fetchFn(`https://${host}/v1internal:${method}`, {
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(4500),
headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json', 'User-Agent': ACCOUNT_USER_AGENT },
body: JSON.stringify(data),
}).catch(() => null);
if (response?.ok) {
const payload = await response.json().catch(() => null);
if (payload) return payload.response ?? payload;
const result = payload?.response ?? payload;
const valid = method === 'loadCodeAssist' ? result && typeof result === 'object' :
method === 'fetchAvailableModels' ? result?.models && typeof result.models === 'object' :
Array.isArray(result?.groups) || Array.isArray(result?.quotaSummary?.groups) || Array.isArray(result?.buckets);
if (valid) {
preferredHost = host;
return result;
}
}
if (response?.status === 401 || response?.status === 403) break;
if (response?.status === 401) throw new Error('credentialRejected');
if (response?.status === 403 && data.project && retryWithoutProject) return post(method, {}, false);
}
return null;
}
@@ -141,9 +512,8 @@ export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
const setup = await post('loadCodeAssist', { metadata: { ideType: 'ANTIGRAVITY' } });
const project = setup?.cloudaicompanionProject?.id || setup?.cloudaicompanionProject;
if (!setup) throw new Error('quotaUnavailable');
const request = {
project: typeof project === 'string' && project ? project : 'cloudaicompanion-enterprise',
};
const tierInfo = resolveSetupTierInfo(setup);
const request = typeof project === 'string' && project ? { project } : {};
const clientConfigs = setup.cascadeModelConfigData?.clientModelConfigs;
const [summary, available] = await Promise.all([
post('retrieveUserQuotaSummary', request),
@@ -167,7 +537,7 @@ export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
buckets: adaptBuckets(raw?.buckets),
};
const { quotaPoolsMap } = buildOfficialQuotaPools(quota, configs);
return Array.from(quotaPoolsMap.values()).filter(({ isAvailable }) => isAvailable).map((pool) => ({
const pools = Array.from(quotaPoolsMap.values()).filter(({ isAvailable }) => isAvailable).map((pool) => ({
poolKey: pool.poolKey,
poolLabel: pool.poolLabel,
remainingPct: pool.remainingPct,
@@ -175,4 +545,9 @@ export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
resetTime: pool.resetTime,
weeklyResetTime: pool.weeklyResetTime,
}));
if (tierInfo) {
Object.defineProperty(pools, 'tierInfo', { value: tierInfo, enumerable: false });
Object.defineProperty(pools, 'tierName', { value: tierInfo.tierName, enumerable: false });
}
return pools;
}
+745 -59
View File
@@ -1,11 +1,31 @@
/** @fileoverview Antigravity shared credentials and the plugin's Windows credential vault. */
import { spawn } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { statSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { resolveGoogleCredential, retrieveCredentialQuota } from './account-oauth.mjs';
import { accountLoginController } from './account-login.mjs';
import {
isAllowedOAuthClientId,
loadNativeOAuthClients,
resolveGoogleCredential,
retrieveCredentialQuota,
} from './account-oauth.mjs';
import {
checkVaultUnlockCooldown,
createVaultSecurityMetadata,
decryptVaultEntryCredential,
encryptVaultEntryCredential,
getUnlockedVaultSessionKey,
isEncryptedVaultCredential,
isVaultSessionUnlocked,
lockVaultSession,
normalizeVaultPassword,
recordVaultUnlockFailure,
resetVaultUnlockFailures,
setUnlockedVaultSessionKey,
verifyVaultPassword,
} from './account-vault-crypto.mjs';
import { HERE } from './config.mjs';
import { callLsRpc } from './ls-rpc.mjs';
@@ -14,33 +34,113 @@ const ACCOUNT_ERRORS = new Set([
'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied',
'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable',
'oauthUnavailable', 'quotaUnavailable',
'switchStartFailed', 'clientCloseFailed', 'clientRestartFailed',
'vaultLocked', 'wrongPassword', 'invalidPassword', 'passwordRateLimited',
'vaultDecryptFailed', 'invalidActionNonce',
]);
const ALLOWED_ACTIONS = new Set([
'list', 'save', 'capture', 'switch', 'remove', 'quota',
'loginStart', 'loginStatus', 'loginCancel',
'setPassword', 'unlockVault', 'lockVault', 'changePassword', 'disablePassword', 'resetVault',
]);
const MAX_TRANSIENT_TOKENS = 32;
const transientAccessTokens = new Map();
const vaultSecurityByPath = new Map();
export function clearAccountVaultRuntimeState() {
lockVaultSession();
resetVaultUnlockFailures();
transientAccessTokens.clear();
vaultSecurityByPath.clear();
}
function rememberTransientAccessToken(email, credential) {
const addr = normalizeAccountEmail(email);
const tok = credential?.token;
if (!addr || !tok?.access_token || !tok?.refresh_token) return;
const expiryMs = Date.parse(tok.expiry || '');
if (!Number.isFinite(expiryMs) || expiryMs <= Date.now() + 60_000) return;
if (!transientAccessTokens.has(addr) && transientAccessTokens.size >= MAX_TRANSIENT_TOKENS) {
const oldestKey = transientAccessTokens.keys().next().value;
if (oldestKey !== undefined) transientAccessTokens.delete(oldestKey);
}
transientAccessTokens.set(addr, {
refreshToken: tok.refresh_token,
accessToken: tok.access_token,
expiry: tok.expiry,
...(typeof credential.id_token === 'string' && credential.id_token
? { idToken: credential.id_token }
: {}),
});
}
function clearTransientAccessTokens(email = '') {
if (email) {
transientAccessTokens.delete(normalizeAccountEmail(email));
return;
}
transientAccessTokens.clear();
}
export function normalizeAccountEmail(value) {
const email = typeof value === 'string' ? value.trim().toLowerCase() : '';
return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? email : '';
}
export function normalizeAccountCredential(input) {
export function normalizeAccountCredential(input, { allowedClientIds = null } = {}) {
if (typeof input !== 'string' || Buffer.byteLength(input, 'utf8') > 16384) return null;
const text = input.trim();
let source;
try { source = JSON.parse(text); } catch {
try {
source = JSON.parse(text);
} catch {
if (!/^1\/{1,2}[\w.-]{20,}$/.test(text)) return null;
source = { refresh_token: text };
}
if (!source || typeof source !== 'object' || Array.isArray(source)) return null;
if (
source.type !== undefined &&
!['authorized_user', 'oauth2'].includes(String(source.type).trim().toLowerCase())
) {
return null;
}
const explicitClientId =
source.client_id ??
source.token?.client_id ??
source.installed?.client_id ??
source.web?.client_id;
if (explicitClientId !== undefined && explicitClientId !== null && String(explicitClientId).trim() !== '') {
if (
typeof explicitClientId !== 'string' ||
!isAllowedOAuthClientId(explicitClientId, allowedClientIds)
) {
return null;
}
}
const token = source?.token || source;
if (!token || (source.auth_method && source.auth_method !== 'consumer') ||
typeof token.refresh_token !== 'string' || !token.refresh_token.trim() ||
/\s/.test(token.refresh_token) || (token.token_type && !/^bearer$/i.test(token.token_type))) return null;
const timestamp = token.expiry_date ?? (Number(token.expiry_timestamp) * 1000);
const expiry = token.expiry || (Number.isSafeInteger(timestamp) && timestamp > 0 && timestamp <= 253402300799999
? new Date(timestamp).toISOString() : '1970-01-01T00:00:00Z');
if (
!token ||
(source.auth_method && source.auth_method !== 'consumer') ||
typeof token.refresh_token !== 'string' ||
!token.refresh_token.trim() ||
/\s/.test(token.refresh_token) ||
(token.token_type && !/^bearer$/i.test(token.token_type))
) {
return null;
}
const timestamp = token.expiry_date ?? Number(token.expiry_timestamp) * 1000;
const expiry =
token.expiry ||
(Number.isSafeInteger(timestamp) && timestamp > 0 && timestamp <= 253402300799999
? new Date(timestamp).toISOString()
: '1970-01-01T00:00:00Z');
if (typeof expiry !== 'string' || !Number.isFinite(Date.parse(expiry))) return null;
const payload = {
token: {
access_token: typeof token.access_token === 'string' ? token.access_token : '',
refresh_token: token.refresh_token,
refresh_token: token.refresh_token.trim(),
token_type: 'Bearer',
expiry: new Date(expiry).toISOString(),
},
@@ -48,125 +148,711 @@ export function normalizeAccountCredential(input) {
};
const idToken = source.id_token || token.id_token;
if (typeof idToken === 'string' && idToken) payload.id_token = idToken;
if (
Number.isSafeInteger(source.aicode_scope_sign_out_attempted_at) &&
source.aicode_scope_sign_out_attempted_at > 0
) {
payload.aicode_scope_sign_out_attempted_at = source.aicode_scope_sign_out_attempted_at;
}
return JSON.stringify(payload);
}
/**
* At-rest minimization: strips short-lived `access_token`, `id_token`, `expiry`,
* and any extra fields before persisting to `accounts.dpapi`.
*/
export function serializeVaultCredential(credential) {
const refreshToken = String(credential?.token?.refresh_token || '').trim();
if (!refreshToken || /\s/.test(refreshToken)) {
throw new Error('invalidCredential');
}
return JSON.stringify({
token: { refresh_token: refreshToken, token_type: 'Bearer' },
auth_method: 'consumer',
});
}
export function runWindowsCredentialStore(request) {
const script = readFileSync(join(HERE, 'backend', 'account-credentials.ps1'), 'utf8');
const encoded = Buffer.from(script, 'utf16le').toString('base64');
const shell = join(process.env.SystemRoot || 'C:/Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
const scriptPath = join(HERE, 'backend', 'account-credentials.ps1');
const shell = join(
process.env.SystemRoot || 'C:/Windows',
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe'
);
return new Promise((resolve, reject) => {
// The helper exchanges private data over its pipes, keeping it out of process arguments.
const child = spawn(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] });
const child = spawn(
shell,
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', scriptPath],
{ windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] }
);
let output = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', (chunk) => { output += chunk; });
child.stdout.on('data', (chunk) => {
output += chunk;
});
child.on('error', reject);
child.stdin.on('error', reject);
child.on('close', (code) => {
if (code !== 0) return reject(new Error('storeFailed'));
try { resolve(JSON.parse(output.replace(/^\uFEFF/, ''))); } catch { reject(new Error('storeFailed')); }
try {
resolve(JSON.parse(output.replace(/^\uFEFF/, '')));
} catch {
reject(new Error('storeFailed'));
}
});
child.stdin.end(JSON.stringify(request), 'utf8');
});
}
function serializeHostCredential(credential) {
let payload = JSON.stringify(credential);
if (Buffer.byteLength(payload, 'utf8') > 2560 && credential.id_token) {
const { id_token, ...compact } = credential;
function serializeHostCredential(credential, { forHostSwitch = false } = {}) {
const target =
forHostSwitch && !credential.aicode_scope_sign_out_attempted_at
? { ...credential, aicode_scope_sign_out_attempted_at: Math.floor(Date.now() / 1000) }
: credential;
let payload = JSON.stringify(target);
if (Buffer.byteLength(payload, 'utf8') > 2560 && target.id_token) {
const { id_token: _ignored, ...compact } = target;
payload = JSON.stringify(compact);
}
if (Buffer.byteLength(payload, 'utf8') > 2560) throw new Error('credentialTooLarge');
return payload;
}
async function confirmHostCredential(email, rpc) {
for (let attempt = 0; attempt < 3; attempt += 1) {
await rpc('GetAuthStatus', {}, 1200).catch(() => null);
const status = await rpc('GetUserStatus', {}, 1200).catch(() => null);
if (normalizeAccountEmail(status?.userStatus?.email) === email) return true;
if (attempt < 2) await delay(300);
let cachedPublicVaultState = null;
let cachedPublicVaultSig = '';
function computePublicVaultDiskSig(config) {
try {
const vStat = statSync(config.vault, { throwIfNoEntry: false });
const sStat = config.statusFile ? statSync(config.statusFile, { throwIfNoEntry: false }) : null;
return `${config.vault}|${vStat ? `${vStat.size}:${vStat.mtimeMs}` : '0'}|${sStat ? `${sStat.size}:${sStat.mtimeMs}` : '0'}`;
} catch {
return '';
}
return false;
}
export async function handleAccountCredentialAction(data, {
platform = process.platform,
store = runWindowsCredentialStore,
rpc = callLsRpc,
resolveCredential = resolveGoogleCredential,
getQuota = retrieveCredentialQuota,
} = {}) {
function recordKnownVaultSecurity(vaultPath, security) {
if (!vaultPath) return;
if (security?.enabled) {
vaultSecurityByPath.set(vaultPath, { enabled: true, salt: String(security.salt || '') });
} else {
vaultSecurityByPath.delete(vaultPath);
}
}
function cacheSanitizedVaultState(config, result) {
const sig = computePublicVaultDiskSig(config);
if (!sig || !result || !Array.isArray(result.accounts)) return;
cachedPublicVaultSig = sig;
cachedPublicVaultState = {
accounts: [...result.accounts],
selectedEmail: result.selectedEmail || '',
quotas: result.quotas ? { ...result.quotas } : {},
...(result.security?.enabled
? { security: { enabled: true, salt: String(result.security.salt || '') } }
: {}),
...(result.switchState ? { switchState: { ...result.switchState } } : {}),
};
}
export async function warmAccountPublicListCache() {
if (process.platform !== 'win32') return;
await handleAccountCredentialAction({ action: 'list' }).catch(() => null);
}
function openStoredVaultCredential(storedRaw, email, vaultSecurity) {
let jsonText = storedRaw;
if (isEncryptedVaultCredential(storedRaw)) {
const keyBuf = getUnlockedVaultSessionKey(vaultSecurity?.salt || '');
if (!keyBuf) throw new Error('vaultLocked');
jsonText = decryptVaultEntryCredential(storedRaw, keyBuf, email);
} else if (vaultSecurity?.enabled && !isVaultSessionUnlocked(vaultSecurity)) {
throw new Error('vaultLocked');
}
const normalized = normalizeAccountCredential(jsonText);
if (!normalized) throw new Error('invalidCredential');
const parsed = JSON.parse(normalized);
if (!parsed.token.access_token) {
const cached = transientAccessTokens.get(normalizeAccountEmail(email));
if (
cached &&
cached.refreshToken === parsed.token.refresh_token &&
Date.parse(cached.expiry) > Date.now() + 60_000
) {
parsed.token.access_token = cached.accessToken;
parsed.token.expiry = cached.expiry;
if (cached.idToken && !parsed.id_token) parsed.id_token = cached.idToken;
}
}
return parsed;
}
function sealVaultCredential(credentialObj, email, vaultSecurity) {
const minJson = serializeVaultCredential(credentialObj);
if (vaultSecurity?.enabled) {
const keyBuf = getUnlockedVaultSessionKey(vaultSecurity.salt);
if (!keyBuf) throw new Error('vaultLocked');
return {
stored: encryptVaultEntryCredential(minJson, keyBuf, email),
vaultUnlocked: true,
expectedSecuritySalt: String(vaultSecurity.salt),
};
}
return { stored: minJson, vaultUnlocked: false, expectedSecuritySalt: '' };
}
export async function handleAccountCredentialAction(
data,
{
platform = process.platform,
store = runWindowsCredentialStore,
rpc = callLsRpc,
resolveCredential = resolveGoogleCredential,
getQuota = retrieveCredentialQuota,
login = accountLoginController,
} = {}
) {
if (platform !== 'win32') return { supported: false, accounts: [], error: 'unsupported' };
const action = data?.action || 'list';
if (!['list', 'save', 'capture', 'switch', 'remove', 'quota'].includes(action)) return { error: 'invalidCredential' };
if (!ALLOWED_ACTIONS.has(action)) return { error: 'invalidCredential' };
const email = normalizeAccountEmail(data?.email);
if (['switch', 'remove', 'quota'].includes(action) && !email) return { error: 'invalidEmail' };
const gemini = String(process.env.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homedir(), '.gemini');
const config = {
target: 'gemini:antigravity',
vault: join(process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), 'AntigravityUsageMonitor', 'accounts.dpapi'),
fallbacks: [join(gemini, 'jetski-standalone-oauth-token'), join(gemini, 'antigravity-cli', 'antigravity-oauth-token')],
vault: join(
process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'),
'AntigravityUsageMonitor',
'accounts.dpapi'
),
statusFile: join(
process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'),
'AntigravityUsageMonitor',
'switch-state.json'
),
scriptPath: join(HERE, 'backend', 'account-credentials.ps1'),
fallbacks: [
join(gemini, 'jetski-standalone-oauth-token'),
join(gemini, 'antigravity-cli', 'antigravity-oauth-token'),
],
};
const useDiskSigCache = store === runWindowsCredentialStore;
async function runStore(fields) {
const result = await store({ ...config, ...fields });
if (!result || result.error) throw new Error(result?.error || 'storeFailed');
if (['list', 'read', 'readVault', 'writeVault', 'scheduleSwitch'].includes(fields.action)) {
recordKnownVaultSecurity(config.vault, result.security);
}
if (useDiskSigCache) {
if (fields.action === 'scheduleSwitch') {
cachedPublicVaultState = null;
cachedPublicVaultSig = '';
} else if (['list', 'save', 'remove', 'saveQuota', 'writeVault'].includes(fields.action)) {
cacheSanitizedVaultState(config, result);
}
}
return result;
}
function resolveKnownVaultSecurity() {
if (useDiskSigCache && cachedPublicVaultState) {
return cachedPublicVaultState.security || null;
}
return vaultSecurityByPath.get(config.vault) || null;
}
async function ensureUnlockedVaultContext() {
if (useDiskSigCache && !cachedPublicVaultState) {
await runStore({ action: 'list', email: '' });
}
const sec = resolveKnownVaultSecurity();
if (sec?.enabled && !isVaultSessionUnlocked(sec)) {
throw new Error('vaultLocked');
}
return sec;
}
function publicList(result) {
const rawSwitchState = result.switchState;
const switchAgeMs = rawSwitchState ? Date.now() - Number(rawSwitchState.updatedAt || 0) : Infinity;
const stalled = rawSwitchState?.state === 'starting' && switchAgeMs > 120000;
const expiredSwitchState =
rawSwitchState && rawSwitchState.state !== 'starting' && switchAgeMs > 5 * 60 * 1000;
const switchState = expiredSwitchState ? null : rawSwitchState;
const sec = result.security?.enabled ? result.security : null;
const cooldownSec = checkVaultUnlockCooldown();
return {
supported: true,
accounts: (Array.isArray(result.accounts) ? result.accounts : []).map(normalizeAccountEmail).filter(Boolean),
selectedEmail: normalizeAccountEmail(result.selectedEmail),
accounts: (Array.isArray(result.accounts) ? result.accounts : [])
.map(normalizeAccountEmail)
.filter(Boolean),
selectedEmail: expiredSwitchState ? '' : normalizeAccountEmail(result.selectedEmail),
quotas: result.quotas || {},
...(sec || data?.includeSecurity
? {
security: {
enabled: Boolean(sec?.enabled),
unlocked: isVaultSessionUnlocked(sec),
...(cooldownSec > 0 ? { cooldownSec } : {}),
},
}
: {}),
...(login.getStatus() ? { login: login.getStatus() } : {}),
...(switchState
? {
switchState: {
email: normalizeAccountEmail(switchState.email),
state:
!stalled && ['starting', 'written', 'failed'].includes(switchState.state)
? switchState.state
: 'failed',
error: stalled
? 'switchStartFailed'
: ACCOUNT_ERRORS.has(switchState.error)
? switchState.error
: '',
},
}
: {}),
};
}
async function verifyCredential(raw, refresh = false) {
const normalized = normalizeAccountCredential(raw);
if (!normalized) throw new Error('invalidCredential');
async function verifyCredentialObj(parsedObj, refresh = false) {
let result;
try {
result = await resolveCredential(JSON.parse(normalized), { refresh });
result = await resolveCredential(parsedObj, { refresh });
} catch (error) {
throw new Error(ACCOUNT_ERRORS.has(error?.message) ? error.message : 'oauthUnavailable');
}
result.email = normalizeAccountEmail(result.email);
if (!result.email) throw new Error('credentialRejected');
rememberTransientAccessToken(result.email, result.credential);
return result;
}
try {
if (action === 'list' || action === 'remove') return publicList(await runStore({ action, email }));
if (action === 'save') {
const verified = await verifyCredential(data.credential, true);
return publicList(await runStore({ action, email: verified.email, credential: serializeHostCredential(verified.credential) }));
async function verifyCredential(raw, refresh = false) {
let normalized = normalizeAccountCredential(raw);
if (!normalized && typeof raw === 'string' && raw.includes('client_id')) {
const liveClients = await loadNativeOAuthClients().catch(() => []);
if (liveClients.length > 0) {
normalized = normalizeAccountCredential(raw, {
allowedClientIds: liveClients.map((c) => c.id),
});
}
}
if (!normalized) throw new Error('invalidCredential');
return verifyCredentialObj(JSON.parse(normalized), refresh);
}
try {
if (action === 'list') {
if (useDiskSigCache && cachedPublicVaultState) {
const curSig = computePublicVaultDiskSig(config);
if (curSig && curSig === cachedPublicVaultSig) {
return publicList(cachedPublicVaultState);
}
}
return publicList(await runStore({ action, email }));
}
if (action === 'setPassword') {
const vaultData = await runStore({ action: 'readVault' });
if (vaultData.security?.enabled) throw new Error('credentialChanged');
const { security, keyBuf } = await createVaultSecurityMetadata(
data?.newPassword ?? data?.password
);
try {
const nextEntries = (Array.isArray(vaultData.entries) ? vaultData.entries : []).map((entry) => {
const entryEmail = normalizeAccountEmail(entry?.email);
if (!entryEmail) throw new Error('invalidEmail');
const norm = normalizeAccountCredential(entry.credential);
if (!norm) throw new Error('invalidCredential');
const minJson = serializeVaultCredential(JSON.parse(norm));
return {
...entry,
email: entryEmail,
credential: encryptVaultEntryCredential(minJson, keyBuf, entryEmail),
};
});
const savedVault = await runStore({
action: 'writeVault',
entries: nextEntries,
selectedEmail: vaultData.selectedEmail || '',
security,
});
setUnlockedVaultSessionKey(security.salt, keyBuf);
resetVaultUnlockFailures();
return publicList(savedVault);
} finally {
keyBuf.fill(0);
}
}
if (action === 'unlockVault') {
const cooldownSec = checkVaultUnlockCooldown();
if (cooldownSec > 0) {
return { error: 'passwordRateLimited', retryAfterSec: cooldownSec };
}
const vaultData = await runStore({ action: 'readVault' });
if (!vaultData.security?.enabled) {
return publicList({
accounts: (vaultData.entries || []).map((e) => e.email),
selectedEmail: vaultData.selectedEmail || '',
quotas: Object.fromEntries(
(vaultData.entries || []).filter((e) => e?.quota).map((e) => [e.email, e.quota])
),
});
}
let keyBuf = null;
try {
keyBuf = await verifyVaultPassword(data?.password, vaultData.security);
} catch (err) {
if (err?.message === 'wrongPassword') {
const waitSec = recordVaultUnlockFailure();
return waitSec > 0
? { error: 'passwordRateLimited', retryAfterSec: waitSec }
: { error: 'wrongPassword' };
}
throw err;
}
try {
const firstEnc = (vaultData.entries || []).find((e) =>
isEncryptedVaultCredential(e?.credential)
);
if (firstEnc) {
decryptVaultEntryCredential(firstEnc.credential, keyBuf, firstEnc.email);
}
setUnlockedVaultSessionKey(vaultData.security.salt, keyBuf);
resetVaultUnlockFailures();
return publicList({
accounts: (vaultData.entries || []).map((e) => e.email),
selectedEmail: vaultData.selectedEmail || '',
quotas: Object.fromEntries(
(vaultData.entries || []).filter((e) => e?.quota).map((e) => [e.email, e.quota])
),
security: { enabled: true, salt: vaultData.security.salt },
});
} finally {
keyBuf.fill(0);
}
}
if (action === 'lockVault') {
lockVaultSession();
clearTransientAccessTokens();
const curLogin = login.getStatus();
if (curLogin?.id && curLogin.status === 'waiting') {
login.cancel(curLogin.id);
}
return publicList(await runStore({ action: 'list', email: '' }));
}
if (action === 'changePassword') {
const cooldownSec = checkVaultUnlockCooldown();
if (cooldownSec > 0) {
return { error: 'passwordRateLimited', retryAfterSec: cooldownSec };
}
if (!normalizeVaultPassword(data?.newPassword)) {
throw new Error('invalidPassword');
}
const vaultData = await runStore({ action: 'readVault' });
if (!vaultData.security?.enabled) throw new Error('notFound');
let oldKeyBuf = null;
try {
oldKeyBuf = await verifyVaultPassword(data?.currentPassword, vaultData.security);
} catch (err) {
if (err?.message === 'wrongPassword') {
const waitSec = recordVaultUnlockFailure();
return waitSec > 0
? { error: 'passwordRateLimited', retryAfterSec: waitSec }
: { error: 'wrongPassword' };
}
throw err;
}
resetVaultUnlockFailures();
let newKeyBuf = null;
try {
const created = await createVaultSecurityMetadata(data.newPassword);
newKeyBuf = created.keyBuf;
const nextEntries = (vaultData.entries || []).map((entry) => {
const entryEmail = normalizeAccountEmail(entry?.email);
if (!entryEmail) throw new Error('invalidEmail');
const plainJson = isEncryptedVaultCredential(entry.credential)
? decryptVaultEntryCredential(entry.credential, oldKeyBuf, entryEmail)
: entry.credential;
const norm = normalizeAccountCredential(plainJson);
if (!norm) throw new Error('invalidCredential');
const minJson = serializeVaultCredential(JSON.parse(norm));
return {
...entry,
email: entryEmail,
credential: encryptVaultEntryCredential(minJson, newKeyBuf, entryEmail),
};
});
const savedVault = await runStore({
action: 'writeVault',
entries: nextEntries,
selectedEmail: vaultData.selectedEmail || '',
security: created.security,
});
clearTransientAccessTokens();
setUnlockedVaultSessionKey(created.security.salt, newKeyBuf);
return publicList(savedVault);
} finally {
oldKeyBuf?.fill(0);
newKeyBuf?.fill(0);
}
}
if (action === 'disablePassword') {
const cooldownSec = checkVaultUnlockCooldown();
if (cooldownSec > 0) {
return { error: 'passwordRateLimited', retryAfterSec: cooldownSec };
}
const vaultData = await runStore({ action: 'readVault' });
if (!vaultData.security?.enabled) {
return publicList({
accounts: (vaultData.entries || []).map((e) => e.email),
selectedEmail: vaultData.selectedEmail || '',
quotas: Object.fromEntries(
(vaultData.entries || []).filter((e) => e?.quota).map((e) => [e.email, e.quota])
),
});
}
let oldKeyBuf = null;
try {
oldKeyBuf = await verifyVaultPassword(data?.currentPassword, vaultData.security);
} catch (err) {
if (err?.message === 'wrongPassword') {
const waitSec = recordVaultUnlockFailure();
return waitSec > 0
? { error: 'passwordRateLimited', retryAfterSec: waitSec }
: { error: 'wrongPassword' };
}
throw err;
}
resetVaultUnlockFailures();
try {
const plainEntries = (vaultData.entries || []).map((entry) => {
const entryEmail = normalizeAccountEmail(entry?.email);
if (!entryEmail) throw new Error('invalidEmail');
const plainJson = isEncryptedVaultCredential(entry.credential)
? decryptVaultEntryCredential(entry.credential, oldKeyBuf, entryEmail)
: entry.credential;
const norm = normalizeAccountCredential(plainJson);
if (!norm) throw new Error('invalidCredential');
return {
...entry,
email: entryEmail,
credential: serializeVaultCredential(JSON.parse(norm)),
};
});
const savedVault = await runStore({
action: 'writeVault',
entries: plainEntries,
selectedEmail: vaultData.selectedEmail || '',
security: null,
});
lockVaultSession();
clearTransientAccessTokens();
return publicList(savedVault);
} finally {
oldKeyBuf?.fill(0);
}
}
if (action === 'resetVault') {
if (data?.confirmReset !== 'RESET') throw new Error('invalidCredential');
lockVaultSession();
clearTransientAccessTokens();
resetVaultUnlockFailures();
const curLogin = login.getStatus();
if (curLogin?.id && curLogin.status === 'waiting') {
login.cancel(curLogin.id);
}
const savedVault = await runStore({
action: 'writeVault',
entries: [],
selectedEmail: '',
security: null,
clearStatus: true,
});
return publicList(savedVault);
}
if (action === 'loginStart') {
await ensureUnlockedVaultContext();
const session = await login.start(async (verified) => {
const address = normalizeAccountEmail(verified.email);
if (!address) throw new Error('credentialRejected');
rememberTransientAccessToken(address, verified.credential);
const activeSec = await ensureUnlockedVaultContext();
const sealed = sealVaultCredential(verified.credential, address, activeSec);
await runStore({
action: 'save',
email: address,
credential: sealed.stored,
...(sealed.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealed.expectedSecuritySalt }
: {}),
});
}, data.language);
return { supported: true, login: session };
}
if (action === 'loginStatus' || action === 'loginCancel') {
const session = action === 'loginCancel' ? login.cancel(data.id) : login.getStatus(data.id);
return {
supported: true,
login: session || { id: data.id, status: 'expired', error: 'loginExpired' },
};
}
if (action === 'remove') {
const activeSec = await ensureUnlockedVaultContext();
clearTransientAccessTokens(email);
return publicList(
await runStore({
action,
email,
...(activeSec?.enabled
? { vaultUnlocked: true, expectedSecuritySalt: String(activeSec.salt) }
: {}),
})
);
}
if (action === 'save') {
const activeSec = await ensureUnlockedVaultContext();
const verified = await verifyCredential(data.credential, true);
const sealed = sealVaultCredential(verified.credential, verified.email, activeSec);
return publicList(
await runStore({
action,
email: verified.email,
credential: sealed.stored,
...(sealed.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealed.expectedSecuritySalt }
: {}),
})
);
}
if (action === 'capture') {
const activeSec = await ensureUnlockedVaultContext();
const status = await rpc('GetUserStatus', {}, 2000).catch(() => null);
const activeEmail = normalizeAccountEmail(status?.userStatus?.email);
if (!activeEmail) throw new Error('noCurrentCredential');
const { credential } = await runStore({ action: 'readCurrent' });
const verified = await verifyCredential(credential);
if (verified.email !== activeEmail) throw new Error('identityMismatch');
return publicList(await runStore({ action: 'save', email: activeEmail, credential: serializeHostCredential(verified.credential) }));
const sealed = sealVaultCredential(verified.credential, activeEmail, activeSec);
return publicList(
await runStore({
action: 'save',
email: activeEmail,
credential: sealed.stored,
...(sealed.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealed.expectedSecuritySalt }
: {}),
})
);
}
const saved = await runStore({ action: 'read', email });
const verified = await verifyCredential(saved.credential);
const entrySec = saved.security || resolveKnownVaultSecurity();
const openedObj = openStoredVaultCredential(saved.credential, email, entrySec);
const verified = await verifyCredentialObj(openedObj);
if (verified.email !== email) throw new Error('identityMismatch');
const credential = serializeHostCredential(verified.credential);
const sealedCurrent = sealVaultCredential(verified.credential, email, entrySec);
if (action === 'quota') {
if (credential !== saved.credential) {
await runStore({ action: 'save', email, credential, expectedCredential: saved.credential });
const tokenRotated =
verified.credential.token.refresh_token !== openedObj.token.refresh_token;
const legacyUnminimized =
useDiskSigCache && !entrySec?.enabled && saved.credential !== sealedCurrent.stored;
let expectedCredForQuota = saved.credential;
if (tokenRotated || legacyUnminimized) {
await runStore({
action: 'save',
email,
credential: sealedCurrent.stored,
expectedCredential: saved.credential,
...(sealedCurrent.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealedCurrent.expectedSecuritySalt }
: {}),
});
expectedCredForQuota = sealedCurrent.stored;
}
const pools = await getQuota(verified.credential.token.access_token);
return { email, pools };
const tierInfo = pools?.tierInfo || null;
const tierName = tierInfo?.tierName || (typeof pools?.tierName === 'string' ? pools.tierName : '');
const tierMeta = {
...(tierInfo?.tierId ? { tierId: tierInfo.tierId } : {}),
...(tierName ? { tierName } : {}),
...(tierInfo?.tierMultiplier ? { tierMultiplier: tierInfo.tierMultiplier } : {}),
};
const fetchedAt = Date.now();
const quotaPayload = { pools, fetchedAt, ...tierMeta };
await runStore({
action: 'saveQuota',
email,
expectedCredential: expectedCredForQuota,
quota: quotaPayload,
});
return { email, pools, fetchedAt, ...tierMeta };
}
const updated = await runStore({ action: 'switch', email, credential, expectedCredential: saved.credential });
const confirmed = await confirmHostCredential(email, rpc);
return { ...publicList(updated), confirmed };
const prevActiveEmail = normalizeAccountEmail(data?.activeEmail);
if (prevActiveEmail && prevActiveEmail !== email) {
try {
const existingPrev = await store({ ...config, action: 'read', email: prevActiveEmail });
if (!existingPrev || existingPrev.error === 'notFound') {
const currentHost = await store({ ...config, action: 'readCurrent' });
if (currentHost?.credential) {
const verifiedPrev = await verifyCredential(currentHost.credential);
if (verifiedPrev.email === prevActiveEmail) {
const sealedPrev = sealVaultCredential(
verifiedPrev.credential,
prevActiveEmail,
entrySec
);
await runStore({
action: 'save',
email: prevActiveEmail,
credential: sealedPrev.stored,
...(sealedPrev.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealedPrev.expectedSecuritySalt }
: {}),
});
}
}
}
} catch {
// Best-effort backup of active host login before switching away
}
}
const hostSwitchCredential = serializeHostCredential(verified.credential, {
forHostSwitch: true,
});
const updated = await runStore({
action: 'scheduleSwitch',
email,
credential: hostSwitchCredential,
vaultCredential: sealedCurrent.stored,
expectedCredential: saved.credential,
...(sealedCurrent.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealedCurrent.expectedSecuritySalt }
: {}),
});
return { ...publicList(updated), restarting: updated.scheduled === true };
} catch (error) {
return { error: ACCOUNT_ERRORS.has(error?.message) ? error.message : 'storeFailed' };
}
@@ -0,0 +1,245 @@
/**
* @fileoverview Inner envelope encryption (scrypt + AES-256-GCM) for saved account
* credentials, in-memory session unlock lifecycle, unlock rate-limiting, and
* HMAC action nonces against local CSRF / blind mutation requests.
*/
import {
createCipheriv,
createDecipheriv,
createHmac,
randomBytes,
scrypt,
timingSafeEqual,
} from 'node:crypto';
export const VAULT_CIPHER_PREFIX = 'agv1:';
const VAULT_VERIFIER_CHALLENGE = 'ag-vault-v1:ok';
const VAULT_VERIFIER_AAD = 'ag-vault-verifier:v1';
const VAULT_ENTRY_AAD_PREFIX = 'ag-vault-entry:v1:';
const VAULT_SCRYPT_N = 16384;
const VAULT_SCRYPT_R = 8;
const VAULT_SCRYPT_P = 1;
const VAULT_KEY_LEN = 32;
const VAULT_SCRYPT_MAXMEM = 64 * 1024 * 1024;
export const VAULT_PASSWORD_MIN_LEN = 4;
export const VAULT_PASSWORD_MAX_LEN = 128;
const ACTION_NONCE_SECRET = randomBytes(32);
const ACTION_NONCE_BUCKET_MS = 10 * 60 * 1000;
let activeVaultKeyState = null;
let unlockFailureCount = 0;
let unlockCooldownUntilMs = 0;
export function normalizeVaultPassword(raw) {
if (typeof raw !== 'string') return null;
if (raw.length < VAULT_PASSWORD_MIN_LEN || raw.length > VAULT_PASSWORD_MAX_LEN) return null;
if (!raw.trim()) return null;
return raw;
}
export function isEncryptedVaultCredential(raw) {
return typeof raw === 'string' && raw.startsWith(VAULT_CIPHER_PREFIX);
}
function isPowerOfTwo(n) {
return Number.isInteger(n) && n >= 1024 && n <= 65536 && (n & (n - 1)) === 0;
}
function deriveVaultKey(password, saltBuf, params = {}) {
const N = isPowerOfTwo(params.N) ? params.N : VAULT_SCRYPT_N;
const r = Number.isInteger(params.r) && params.r >= 1 && params.r <= 16 ? params.r : VAULT_SCRYPT_R;
const p = Number.isInteger(params.p) && params.p >= 1 && params.p <= 8 ? params.p : VAULT_SCRYPT_P;
return new Promise((resolve, reject) => {
scrypt(
Buffer.from(password, 'utf8'),
saltBuf,
VAULT_KEY_LEN,
{ N, r, p, maxmem: VAULT_SCRYPT_MAXMEM },
(err, derivedKey) => {
if (err) reject(err);
else resolve(derivedKey);
}
);
});
}
function aeadSeal(plaintextUtf8, keyBuf, aadUtf8) {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', keyBuf, iv);
cipher.setAAD(Buffer.from(aadUtf8, 'utf8'));
const enc = Buffer.concat([cipher.update(plaintextUtf8, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, enc]).toString('base64');
}
function aeadOpen(b64Payload, keyBuf, aadUtf8) {
const raw = Buffer.from(String(b64Payload || ''), 'base64');
if (raw.length < 28) {
throw new Error('vaultDecryptFailed');
}
const iv = raw.subarray(0, 12);
const tag = raw.subarray(12, 28);
const enc = raw.subarray(28);
const decipher = createDecipheriv('aes-256-gcm', keyBuf, iv, { authTagLength: 16 });
decipher.setAAD(Buffer.from(aadUtf8, 'utf8'));
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8');
}
export async function createVaultSecurityMetadata(password) {
const validPassword = normalizeVaultPassword(password);
if (!validPassword) {
throw new Error('invalidPassword');
}
const saltBuf = randomBytes(16);
const salt = saltBuf.toString('base64');
const keyBuf = await deriveVaultKey(validPassword, saltBuf);
const verifier = aeadSeal(VAULT_VERIFIER_CHALLENGE, keyBuf, VAULT_VERIFIER_AAD);
return {
security: {
enabled: true,
version: 1,
kdf: 'scrypt',
salt,
N: VAULT_SCRYPT_N,
r: VAULT_SCRYPT_R,
p: VAULT_SCRYPT_P,
verifier,
},
keyBuf,
};
}
export async function verifyVaultPassword(password, security) {
if (!security?.enabled || typeof security.salt !== 'string' || typeof security.verifier !== 'string') {
throw new Error('storeFailed');
}
const validPassword = normalizeVaultPassword(password);
if (!validPassword) {
throw new Error('wrongPassword');
}
const saltBuf = Buffer.from(security.salt, 'base64');
if (saltBuf.length < 16) {
throw new Error('storeFailed');
}
const keyBuf = await deriveVaultKey(validPassword, saltBuf, security);
try {
const opened = aeadOpen(security.verifier, keyBuf, VAULT_VERIFIER_AAD);
if (opened !== VAULT_VERIFIER_CHALLENGE) {
keyBuf.fill(0);
throw new Error('wrongPassword');
}
return keyBuf;
} catch {
keyBuf.fill(0);
throw new Error('wrongPassword');
}
}
export function encryptVaultEntryCredential(plainJson, keyBuf, email) {
const normalizedEmail = String(email || '').trim().toLowerCase();
if (!normalizedEmail || !Buffer.isBuffer(keyBuf) || keyBuf.length !== VAULT_KEY_LEN) {
throw new Error('storeFailed');
}
return `${VAULT_CIPHER_PREFIX}${aeadSeal(plainJson, keyBuf, `${VAULT_ENTRY_AAD_PREFIX}${normalizedEmail}`)}`;
}
export function decryptVaultEntryCredential(storedText, keyBuf, email) {
const normalizedEmail = String(email || '').trim().toLowerCase();
if (!isEncryptedVaultCredential(storedText) || !normalizedEmail) {
throw new Error('vaultDecryptFailed');
}
if (!Buffer.isBuffer(keyBuf) || keyBuf.length !== VAULT_KEY_LEN) {
throw new Error('vaultLocked');
}
const payload = storedText.slice(VAULT_CIPHER_PREFIX.length);
try {
return aeadOpen(payload, keyBuf, `${VAULT_ENTRY_AAD_PREFIX}${normalizedEmail}`);
} catch {
throw new Error('vaultDecryptFailed');
}
}
export function setUnlockedVaultSessionKey(salt, keyBuf) {
if (!salt || !Buffer.isBuffer(keyBuf) || keyBuf.length !== VAULT_KEY_LEN) {
throw new Error('storeFailed');
}
const nextCopy = Buffer.from(keyBuf);
if (activeVaultKeyState?.keyBuf) {
activeVaultKeyState.keyBuf.fill(0);
}
activeVaultKeyState = { salt: String(salt), keyBuf: nextCopy };
}
export function lockVaultSession() {
if (activeVaultKeyState?.keyBuf) {
activeVaultKeyState.keyBuf.fill(0);
}
activeVaultKeyState = null;
}
export function getUnlockedVaultSessionKey(expectedSalt = '') {
if (!activeVaultKeyState?.keyBuf) return null;
if (expectedSalt && activeVaultKeyState.salt !== String(expectedSalt)) {
lockVaultSession();
return null;
}
return activeVaultKeyState.keyBuf;
}
export function isVaultSessionUnlocked(security) {
if (!security?.enabled) return true;
return Boolean(getUnlockedVaultSessionKey(security.salt));
}
export function checkVaultUnlockCooldown(nowMs = Date.now()) {
if (unlockCooldownUntilMs <= nowMs) return 0;
return Math.max(1, Math.ceil((unlockCooldownUntilMs - nowMs) / 1000));
}
export function recordVaultUnlockFailure(nowMs = Date.now()) {
unlockFailureCount += 1;
if (unlockFailureCount >= 5) {
const delayMs = Math.min(60_000, 5_000 * 2 ** Math.min(4, unlockFailureCount - 5));
unlockCooldownUntilMs = nowMs + delayMs;
}
return checkVaultUnlockCooldown(nowMs);
}
export function resetVaultUnlockFailures() {
unlockFailureCount = 0;
unlockCooldownUntilMs = 0;
}
function computeBucketNonceMac(bucket) {
return createHmac('sha256', ACTION_NONCE_SECRET)
.update(`ag-acct-nonce:${bucket}`)
.digest('base64url')
.slice(0, 32);
}
export function issueAccountActionNonce(nowMs = Date.now()) {
const bucket = Math.floor(nowMs / ACTION_NONCE_BUCKET_MS).toString(36);
return `${bucket}.${computeBucketNonceMac(bucket)}`;
}
export function verifyAccountActionNonce(token, nowMs = Date.now()) {
if (typeof token !== 'string' || token.length < 16 || token.length > 96) return false;
const dotIdx = token.indexOf('.');
if (dotIdx <= 0) return false;
const bucketStr = token.slice(0, dotIdx);
const macStr = token.slice(dotIdx + 1);
const bucketNum = Number.parseInt(bucketStr, 36);
if (!Number.isSafeInteger(bucketNum) || bucketNum <= 0) return false;
const curBucket = Math.floor(nowMs / ACTION_NONCE_BUCKET_MS);
if (Math.abs(curBucket - bucketNum) > 1) return false;
const expectedMac = computeBucketNonceMac(bucketNum.toString(36));
const a = Buffer.from(macStr, 'utf8');
const b = Buffer.from(expectedMac, 'utf8');
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
}
+44 -4
View File
@@ -9,7 +9,8 @@
import { randomUUID } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { BRIDGE_API_ROUTE_DEFS, LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs';
import { handleAccountCredentialAction } from './account-switch.mjs';
import { handleAccountCredentialAction, warmAccountPublicListCache } from './account-switch.mjs';
import { issueAccountActionNonce, verifyAccountActionNonce } from './account-vault-crypto.mjs';
import {
clearRemoteEndpointCaches,
resolveEndpointContext,
@@ -614,6 +615,20 @@ export async function executePluginUpdateAction() {
};
}
const NONCE_PROTECTED_ACCOUNT_ACTIONS = new Set([
'save',
'capture',
'switch',
'remove',
'loginStart',
'setPassword',
'unlockVault',
'lockVault',
'changePassword',
'disablePassword',
'resetVault',
]);
export async function executeAccountCredentialAction(data, opts = {}) {
const epCtx = resolveActionEndpoint(data, opts);
if (!epCtx.ok) {
@@ -628,15 +643,35 @@ export async function executeAccountCredentialAction(data, opts = {}) {
};
}
const cleanData = stripEndpointField(data);
const result = await handleAccountCredentialAction(cleanData);
if (cleanData?.action === 'switch') {
const action = cleanData?.action || 'list';
if (NONCE_PROTECTED_ACCOUNT_ACTIONS.has(action) && !verifyAccountActionNonce(cleanData?.actionNonce)) {
return {
status: 200,
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify({
error: 'invalidActionNonce',
actionNonce: issueAccountActionNonce(),
}),
};
}
const result = await handleAccountCredentialAction({
...(isPlainObject(cleanData) ? cleanData : {}),
action,
includeSecurity: true,
});
if (action === 'switch' && !result?.error) {
clearTelemetryBuilderMemo(LOCAL_ENDPOINT_ID);
}
const enriched =
result && typeof result === 'object'
? { ...result, actionNonce: issueAccountActionNonce() }
: result;
return {
status: 200,
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(result),
body: JSON.stringify(enriched),
};
}
@@ -870,6 +905,11 @@ export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = nu
if (!allowDynamicLs && !lsRuntimeEndpoint.addr) return null;
ensureCliStatusLineConfigured({ enabled: loadSettings().enableCliStatusLine !== false });
if (allowDynamicLs) {
setTimeout(() => {
void warmAccountPublicListCache();
}, 80).unref?.();
}
const triggerRestart =
typeof onRestart === 'function' ? onRestart : () => scheduleSidecarRestart(150);
@@ -6,8 +6,10 @@
import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs';
import {
ACCOUNT_QUOTA_REFRESH_MINUTES,
CLI_STATUSLINE_PRESETS,
CONTEXT_AGENT_MODES,
DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES,
DEFAULT_CLI_STATUSLINE_SLOTS,
DEFAULT_CONTEXT_AGENT_MODE,
DEFAULT_HOVER_MODULES,
@@ -32,6 +34,7 @@ import {
SUPPORTED_LANGUAGES,
THEME_ACCENT_KEYS,
TOPBAR_SLOT_KEYS,
normalizeAccountQuotaRefreshMinutes,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeExperimentalModernUi,
@@ -59,8 +62,10 @@ import {
} from '../shared/settings-normalization.mjs';
export {
ACCOUNT_QUOTA_REFRESH_MINUTES,
CLI_STATUSLINE_PRESETS,
CONTEXT_AGENT_MODES,
DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES,
DEFAULT_CLI_STATUSLINE_SLOTS,
DEFAULT_CONTEXT_AGENT_MODE,
DEFAULT_HOVER_MODULES,
@@ -85,6 +90,7 @@ export {
SUPPORTED_LANGUAGES,
THEME_ACCENT_KEYS,
TOPBAR_SLOT_KEYS,
normalizeAccountQuotaRefreshMinutes,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeExperimentalModernUi,
@@ -162,6 +168,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
stepTokenComboFormat: DEFAULT_STEP_TOKEN_COMBO_FORMAT,
stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS,
experimentalQuotaReservation: true,
accountQuotaRefreshMinutes: DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES,
contextWindowRiskAccepted: false,
contextWindowMainEnabled: true,
contextWindowSwarmEnabled: false,
@@ -246,6 +253,9 @@ export function normalizeFullSettings(rawInput) {
experimentalQuotaReservation: normalizeExperimentalQuotaReservation(
safeRaw.experimentalQuotaReservation
),
accountQuotaRefreshMinutes: normalizeAccountQuotaRefreshMinutes(
safeRaw.accountQuotaRefreshMinutes
),
contextWindowRiskAccepted: safeRaw.contextWindowRiskAccepted === true,
contextWindowMainEnabled: safeRaw.contextWindowMainEnabled !== false,
contextWindowSwarmEnabled: safeRaw.contextWindowSwarmEnabled === true,
@@ -512,6 +512,19 @@ export function createStandaloneWebServer(options = {}) {
}
if (pathname.startsWith('/api/')) {
if (pathname === '/api/accounts' || pathname === '/api/accounts/update') {
sendResponse(
res,
403,
'application/json; charset=utf-8',
JSON.stringify({
supported: false,
accounts: [],
error: 'unsupported',
})
);
return;
}
if (pathname === '/api/export-file' || pathname === '/api/reveal-file') {
sendResponse(
res,
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1795518808645">
<link rel="stylesheet" href="/styles.css?v=1795527403692">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1795518808645"></script>
<script src="/app.js?v=1795527403692"></script>
</body>
</html>
+12
View File
@@ -175,6 +175,18 @@ async function handleProtectedApi(pathname, method, data, req) {
contentType: 'application/json',
});
}
if (
!isTestHarnessEnv &&
pathname === '/api/accounts/update' &&
req?.headers &&
!req.headers.origin &&
!req.headers['sec-fetch-site']
) {
return new Response(JSON.stringify({ error: 'Forbidden non-webview account mutation' }), {
status: 403,
contentType: 'application/json',
});
}
const out = await forwardApiCall(pathname, method, data);
return new Response(out.body, {
status: out.status,
+1
View File
@@ -641,6 +641,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
'src/components/settings/SessionMigrationCard.js',
'src/views/settings/SettingsGeneralTab.js',
'src/views/settings/SettingsStructureTab.js',
'src/views/settings/SettingsAccountTab.js',
'src/views/settings/SettingsOtherTab.js',
'src/components/layout/TopSessionHeader.js',
'src/views/LiveOverviewView.js',
@@ -546,6 +546,22 @@ export function normalizeModernUi(val) {
export const CONTEXT_AGENT_MODES = Object.freeze(['main', 'auto']);
export const DEFAULT_CONTEXT_AGENT_MODE = 'main';
export const ACCOUNT_QUOTA_REFRESH_MINUTES = Object.freeze([10, 30, 60, 180, 360, 720, 1440]);
export const DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES = 60;
/**
* 归一化非当前账号的后台配额刷新间隔(分钟,默认 `60` 即 1 小时)。
*
* @param {unknown} raw
* @returns {10|30|60|180|360|720|1440}
*/
export function normalizeAccountQuotaRefreshMinutes(raw) {
const num = Number(raw);
return ACCOUNT_QUOTA_REFRESH_MINUTES.includes(num)
? /** @type {any} */ (num)
: DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES;
}
/**
* 归一化顶栏胶囊及悬停速览浮窗的上下文代理来源(默认 `'main'` 锁定主代理,可选 `'auto'` 跟随活跃)。
*
@@ -4,6 +4,7 @@
*/
import {
normalizeAccountQuotaRefreshMinutes,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeExperimentalQuotaReservation,
@@ -212,6 +213,7 @@ const PORTABLE_SETTING_DESCRIPTORS = Object.freeze([
normField('stepTokenComboFormat', normalizeStepTokenComboFormat),
arrayField('stepTableColumns', normalizeStepTableColumns),
normField('experimentalQuotaReservation', normalizeExperimentalQuotaReservation),
normField('accountQuotaRefreshMinutes', normalizeAccountQuotaRefreshMinutes),
]);
/**
+68 -4
View File
@@ -492,26 +492,54 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.account.signedOut': 'Signed out',
'settings.account.unknown': 'Account status unavailable',
'settings.account.email': 'Account email',
'settings.account.googleLogin': 'Sign in with Google',
'settings.account.loginHint': 'Sign in with Google in your browser. The account will appear in this list automatically.',
'settings.account.loginWaiting': 'Choose a Google account and complete authorization in your browser. This list will update automatically.',
'settings.account.loginFinishing': 'Authorization received. Saving the account…',
'settings.account.loginSuccess': 'Signed in. The account has been added.',
'settings.account.loginCancelled': 'Sign-in cancelled.',
'settings.account.loginExpired': 'Sign-in expired. Click Sign in with Google to try again.',
'settings.account.loginDenied': 'Google authorization was cancelled. Try signing in again.',
'settings.account.loginStartFailed': 'Sign-in could not start. Try again.',
'settings.account.loginExchangeFailed': 'Sign-in could not finish. Check your connection and authorize again.',
'settings.account.openLoginPage': 'Reopen Google authorization',
'settings.account.cancelLogin': 'Cancel sign-in',
'settings.account.importExisting': 'Import existing credentials',
'settings.account.credential': 'OAuth credential',
'settings.account.credentialPlaceholder': 'Paste 1// refresh token or OAuth JSON…',
'settings.account.importHint': 'Paste an Antigravity refresh token or OAuth JSON containing a refresh_token. The account email is verified and the credential is encrypted on this device.',
'settings.account.save': 'Import credential',
'settings.account.capture': 'Save current credential',
'settings.account.reload': 'Refresh list',
'settings.account.switch': 'Switch',
'settings.account.switch': 'Switch and restart',
'settings.account.switchHint': 'Switching closes and reopens Antigravity App and the IDE sharing its sign-in. Save your work first.',
'settings.account.restarting': 'Restarting Antigravity with the selected account…',
'settings.account.switchStartFailed': 'The account switch could not start. Refresh the list and try again.',
'settings.account.clientCloseFailed': 'Antigravity could not fully exit. The switch is incomplete.',
'settings.account.clientRestartFailed': 'The credential was updated. Open Antigravity manually to finish switching.',
'settings.account.remove': 'Remove',
'settings.account.active': 'In use',
'settings.account.savedBadge': 'Backed up',
'settings.account.written': 'Credential written',
'settings.account.pending': 'The credential for {email} was written. If Antigravity stays on the previous account, reopen it.',
'settings.account.savedCredentials': 'Saved credentials',
'settings.account.savedCredentials': 'Saved accounts',
'settings.account.empty': 'No saved credentials.',
'settings.account.loading': 'Loading saved credentials…',
'settings.account.saved': 'Credential saved.',
'settings.account.removed': 'Saved credential removed.',
'settings.account.switched': 'Account switched. Refreshing the current quota.',
'settings.account.switching': 'Replacing the credential and confirming the active account…',
'settings.account.switching': 'Verifying the credential and preparing to restart…',
'settings.account.verifying': 'Verifying the credential owner…',
'settings.account.loadQuota': 'Check quota',
'settings.account.loadingQuota': 'Checking quota for this credential…',
'settings.account.loadingQuota': 'Checking…',
'settings.account.refreshFreqAria': 'Background account quota refresh interval',
'settings.account.refresh10m': '10 min',
'settings.account.refresh30m': '30 min',
'settings.account.refresh1h': '1 hr',
'settings.account.refresh3h': '3 hr',
'settings.account.refresh6h': '6 hr',
'settings.account.refresh12h': '12 hr',
'settings.account.refresh24h': '24 hr',
'settings.account.emptyCredentialQuota': 'There are no quota pools to display for this account.',
'settings.account.quota': 'Quota remaining by pool',
'settings.account.quota5h': '5 hours {percent}%',
@@ -534,6 +562,42 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.account.oauthClientUnavailable': 'The local Antigravity OAuth client configuration could not be read.',
'settings.account.oauthUnavailable': 'Google OAuth verification is unavailable. Check your network and try again.',
'settings.account.quotaUnavailable': 'Quota for this account is unavailable. Try again shortly.',
'settings.account.switchConfirm': 'Confirm switch',
'settings.account.removeConfirm': 'Confirm remove',
'settings.account.pwdBtnSet': 'Passphrase',
'settings.account.pwdBtnManage': 'Passphrase',
'settings.account.lockNow': 'Lock',
'settings.account.lockNowTip': 'Lock credential vault now',
'settings.account.unlockBtn': 'Unlock',
'settings.account.unlockPlaceholder': 'Enter passphrase to unlock…',
'settings.account.vaultLockedHint': 'Credential vault is locked. Enter your passphrase to switch accounts, manage credentials, or refresh quotas.',
'settings.account.forgotPwdToggle': 'Forgot?',
'settings.account.resetVaultHint': 'Encrypted backups cannot be recovered without the passphrase (your active IDE sign-in is unaffected). You can clear and reset the vault.',
'settings.account.resetVaultBtn': 'Reset vault',
'settings.account.resetVaultConfirm': 'Confirm reset',
'settings.account.pwdTabChange': 'Change passphrase',
'settings.account.pwdTabDisable': 'Remove passphrase',
'settings.account.pwdCurrentPlaceholder': 'Current passphrase…',
'settings.account.pwdNewPlaceholder': 'New passphrase (4–128 chars)…',
'settings.account.pwdConfirmPlaceholder': 'Confirm passphrase…',
'settings.account.pwdEnableSubmit': 'Enable',
'settings.account.pwdChangeSubmit': 'Update',
'settings.account.pwdDisableSubmit': 'Disable',
'settings.account.pwdSetHint': 'Adds passphrase encryption to all saved refresh tokens. Asked once per session when managing accounts; cannot be recovered if forgotten.',
'settings.account.pwdManageHint': 'Verify your current passphrase to set a new one or return to default OS encryption.',
'settings.account.pwdEnabledToast': 'Passphrase encryption enabled.',
'settings.account.pwdChangedToast': 'Passphrase updated.',
'settings.account.pwdDisabledToast': 'Passphrase protection disabled.',
'settings.account.vaultUnlockedToast': 'Credential vault unlocked.',
'settings.account.vaultLockedToast': 'Credential vault locked.',
'settings.account.vaultResetToast': 'Credential vault cleared and reset.',
'settings.account.vaultLocked': 'Enter your passphrase to unlock the vault first.',
'settings.account.wrongPassword': 'Incorrect passphrase. Try again.',
'settings.account.invalidPassword': 'Passphrase must be 4–128 characters and not blank.',
'settings.account.passwordMismatch': 'Passphrases do not match.',
'settings.account.passwordRateLimited': 'Too many failed attempts. Wait a moment and try again.',
'settings.account.vaultDecryptFailed': 'Vault decryption check failed.',
'settings.account.invalidActionNonce': 'Security token expired. Please try again.',
'settings.subTab.aria': 'Preferences category tabs',
'settings.saving': 'Saving…',
'settings.saved': 'Saved',
+69 -5
View File
@@ -493,26 +493,54 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.account.signedOut': '未登录',
'settings.account.unknown': '暂未获取账号状态',
'settings.account.email': '账号邮箱',
'settings.account.googleLogin': '使用 Google 登录',
'settings.account.loginHint': '通过浏览器登录 Google,完成后账号会自动添加到列表。',
'settings.account.loginWaiting': '请在浏览器中选择 Google 账号并完成授权,完成后这里会自动更新。',
'settings.account.loginFinishing': '授权已收到,正在保存账号…',
'settings.account.loginSuccess': '登录成功,账号已添加。',
'settings.account.loginCancelled': '已取消本次登录。',
'settings.account.loginExpired': '登录已超时,请重新点击「使用 Google 登录」。',
'settings.account.loginDenied': 'Google 授权已取消,请重新登录。',
'settings.account.loginStartFailed': '未能开始登录,请重试。',
'settings.account.loginExchangeFailed': '未能完成登录,请检查网络后重新授权。',
'settings.account.openLoginPage': '重新打开 Google 授权页面',
'settings.account.cancelLogin': '取消登录',
'settings.account.importExisting': '导入已有凭证',
'settings.account.credential': 'OAuth 凭证',
'settings.account.credentialPlaceholder': '粘贴 1// 刷新令牌或 OAuth JSON…',
'settings.account.importHint': '粘贴 Antigravity 的刷新令牌或含 refresh_token 的 OAuth JSON。插件会验证账号邮箱,并在本机加密保存。',
'settings.account.save': '导入凭证',
'settings.account.capture': '保存当前凭证',
'settings.account.reload': '刷新列表',
'settings.account.switch': '切换',
'settings.account.switch': '切换并重启',
'settings.account.switchHint': '切换会关闭并重新打开 Antigravity App 和共享登录的 IDE,请先保存工作。',
'settings.account.restarting': '正在重启 Antigravity 并应用所选账号…',
'settings.account.switchStartFailed': '未能启动切号,请刷新列表后重试。',
'settings.account.clientCloseFailed': 'Antigravity 未能完全退出,切换未完成。',
'settings.account.clientRestartFailed': '凭证已更新,但自动重新打开失败,请手动打开 Antigravity。',
'settings.account.remove': '移除',
'settings.account.active': '当前使用',
'settings.account.savedBadge': '已备份',
'settings.account.written': '凭证已写入',
'settings.account.pending': '已写入 {email} 的凭证,等待宿主更新。如果一直未更新,请重开当前 Antigravity。',
'settings.account.savedCredentials': '已保存的凭证',
'settings.account.savedCredentials': '已保存的账号',
'settings.account.empty': '暂无已保存的凭证。',
'settings.account.loading': '正在读取已保存的凭证…',
'settings.account.saved': '凭证已保存。',
'settings.account.removed': '已移除保存的凭证。',
'settings.account.switched': '已切换账号,正在刷新当前额度。',
'settings.account.switching': '正在替换凭证并确认宿主账号…',
'settings.account.switching': '正在验证凭证并准备重启…',
'settings.account.verifying': '正在验证凭证所属账号…',
'settings.account.loadQuota': '查额度',
'settings.account.loadingQuota': '正在查询此凭证的额度…',
'settings.account.loadingQuota': '查询中…',
'settings.account.refreshFreqAria': '非当前账号配额刷新间隔',
'settings.account.refresh10m': '10 分钟',
'settings.account.refresh30m': '30 分钟',
'settings.account.refresh1h': '1 小时',
'settings.account.refresh3h': '3 小时',
'settings.account.refresh6h': '6 小时',
'settings.account.refresh12h': '12 小时',
'settings.account.refresh24h': '24 小时',
'settings.account.emptyCredentialQuota': '这个账号暂无可显示的额度池。',
'settings.account.quota': '额度池剩余',
'settings.account.quota5h': '5 小时 {percent}%',
@@ -531,10 +559,46 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.account.credentialAccessDenied': 'Windows 拒绝访问凭据管理器。请在当前 Windows 用户会话中打开 Antigravity 后重试。',
'settings.account.credentialChanged': '这份凭证已在其他窗口更新,请刷新列表后重试。',
'settings.account.credentialRejected': 'Google 未接受此凭证。请检查令牌是否属于 Antigravity 且仍然有效。',
'settings.account.identityMismatch': '凭证所属账号与宿主或保存的账号不一致。请重新导入该凭证。',
'settings.account.identityMismatch': '凭证所属账号跟宿主或保存的账号不一致,请重新导入该凭证。',
'settings.account.oauthClientUnavailable': '未能从本机 Antigravity 读取 OAuth 客户端配置。',
'settings.account.oauthUnavailable': '暂时无法完成 Google OAuth 验证,请检查网络后重试。',
'settings.account.quotaUnavailable': '暂时无法取得此账号的额度,请稍候重试。',
'settings.account.switchConfirm': '确认切换',
'settings.account.removeConfirm': '确认移除',
'settings.account.pwdBtnSet': '二级密码',
'settings.account.pwdBtnManage': '密码设置',
'settings.account.lockNow': '锁定',
'settings.account.lockNowTip': '立即锁定凭证库',
'settings.account.unlockBtn': '解锁',
'settings.account.unlockPlaceholder': '输入二级密码解锁…',
'settings.account.vaultLockedHint': '凭证库已加密锁定,输入二级密码后可切换账号、管理凭证和刷新后台配额。',
'settings.account.forgotPwdToggle': '忘记密码?',
'settings.account.resetVaultHint': '二级密码采用真实密钥派生加密,遗忘后无法解密旧备份(不影响当前正在使用的账号),可清空凭证库后重新添加。',
'settings.account.resetVaultBtn': '清空凭证库',
'settings.account.resetVaultConfirm': '确认清空重置',
'settings.account.pwdTabChange': '修改密码',
'settings.account.pwdTabDisable': '关闭密码',
'settings.account.pwdCurrentPlaceholder': '当前二级密码…',
'settings.account.pwdNewPlaceholder': '设置二级密码(4~128 位)…',
'settings.account.pwdConfirmPlaceholder': '再次确认密码…',
'settings.account.pwdEnableSubmit': '启用加密',
'settings.account.pwdChangeSubmit': '更新密码',
'settings.account.pwdDisableSubmit': '关闭保护',
'settings.account.pwdSetHint': '使用二级密码对所有已存刷新令牌追加一层加密,每次启动首次操作时解锁一次;请牢记密码,遗忘后无法找回备份。',
'settings.account.pwdManageHint': '验证当前二级密码后可更换新密码,或退回系统默认加密。',
'settings.account.pwdEnabledToast': '已启用二级密码加密。',
'settings.account.pwdChangedToast': '二级密码已更新。',
'settings.account.pwdDisabledToast': '已关闭二级密码保护。',
'settings.account.vaultUnlockedToast': '凭证库已解锁。',
'settings.account.vaultLockedToast': '凭证库已锁定。',
'settings.account.vaultResetToast': '凭证库已清空重置。',
'settings.account.vaultLocked': '请先输入二级密码解锁凭证库。',
'settings.account.wrongPassword': '二级密码不正确,请核对后重试。',
'settings.account.invalidPassword': '密码长度需在 4 到 128 个字符之间且不能全为空格。',
'settings.account.passwordMismatch': '两次输入的密码不一致。',
'settings.account.passwordRateLimited': '密码连续输错次数过多,请稍候再试。',
'settings.account.vaultDecryptFailed': '凭证解密校验失败,请确认密码或重置凭证库。',
'settings.account.invalidActionNonce': '安全校验令牌已过期,请重试。',
'settings.saving': '保存中…',
'settings.saved': '已保存',
'settings.saveFailed': '保存失败',
+9
View File
@@ -131,4 +131,13 @@ export const SVG_ICON_DEFS = Object.freeze({
{ tag: 'circle', attrs: { cx: '6', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } },
{ tag: 'circle', attrs: { cx: '10', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } },
],
lock: [
{ tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } },
{ tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.6 0V7' } },
{ tag: 'circle', attrs: { cx: '8', cy: '10.5', r: '0.9', fill: 'currentColor', stroke: 'none' } },
],
unlock: [
{ tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } },
{ tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.3-1.2' } },
],
});
@@ -42,6 +42,7 @@ import {
OVERVIEW_MODULE_KEYS,
STEP_TABLE_COLUMN_KEYS,
TOPBAR_SLOT_KEYS,
normalizeAccountQuotaRefreshMinutes,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeExperimentalQuotaReservation,
@@ -496,6 +497,7 @@ export const normalizeClientModelDisplayMode = normalizeModelDisplayMode;
export const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots;
export const normalizeClientContextAgentMode = normalizeContextAgentMode;
export const normalizeClientExperimentalQuotaReservation = normalizeExperimentalQuotaReservation;
export const normalizeClientAccountQuotaRefreshMinutes = normalizeAccountQuotaRefreshMinutes;
export const normalizeClientCliStatusLineSlots = normalizeCliStatusLineSlots;
/**
@@ -654,6 +656,12 @@ export function isEquivalentTelemetry(prev, next) {
) {
return false;
}
if (
normalizeClientAccountQuotaRefreshMinutes(pSet?.accountQuotaRefreshMinutes) !==
normalizeClientAccountQuotaRefreshMinutes(nSet?.accountQuotaRefreshMinutes)
) {
return false;
}
if (!sameArr(pSet?.topbarCapsuleSlots, nSet?.topbarCapsuleSlots)) return false;
if (!sameArr(pSet?.hoverModules, nSet?.hoverModules)) return false;
if (!sameArr(pSet?.overviewModules, nSet?.overviewModules)) return false;
@@ -1913,6 +1921,11 @@ export async function saveSettingsPatch(patch) {
safePatch.experimentalQuotaReservation
);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'accountQuotaRefreshMinutes')) {
safePatch.accountQuotaRefreshMinutes = normalizeClientAccountQuotaRefreshMinutes(
safePatch.accountQuotaRefreshMinutes
);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) {
safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots);
}
@@ -641,6 +641,484 @@
line-height: 1.35;
}
.settings-account-root [hidden] {
display: none !important;
}
.account-toolbar-panel {
padding: 9px 12px;
gap: 8px;
}
.account-toolbar-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
flex-wrap: wrap;
}
.account-toolbar-left,
.account-toolbar-right {
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.account-toolbar-right {
margin-left: auto;
}
.account-toolbar-btn {
display: inline-flex;
align-items: center;
gap: 5px;
min-height: calc(25px * var(--ui-font-scale, 1));
height: auto;
padding: 2px 10px;
font-size: var(--fs-md);
font-weight: 500;
border-radius: var(--radius-xs);
white-space: nowrap;
}
.account-toolbar-btn.is-open {
color: var(--accent-primary);
background: var(--accent-primary-soft);
}
.account-reload-btn {
width: calc(25px * var(--ui-font-scale, 1));
height: calc(25px * var(--ui-font-scale, 1));
padding: 0;
border-radius: var(--radius-xs);
flex-shrink: 0;
}
.account-refresh-select {
flex: 0 0 auto;
width: auto;
min-width: 0;
}
.account-refresh-select .select-trigger {
width: auto;
min-height: calc(25px * var(--ui-font-scale, 1));
height: auto;
padding: 2px 8px;
gap: 5px;
font-size: var(--fs-sm);
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
background: var(--surface-subtle);
}
[data-modern-ui="true"] .account-refresh-select .select-trigger {
border: none;
background: var(--modern-surface-subtle);
}
[data-modern-ui="true"] .account-refresh-select .select-trigger:hover,
[data-modern-ui="true"] .account-refresh-select.is-open .select-trigger {
background: var(--modern-surface-hover);
}
.account-refresh-select .select-menu {
right: 0;
left: auto;
min-width: 108px;
width: max-content;
}
.account-status-inline {
font-size: var(--fs-sm);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 210px;
}
.account-status-inline.is-ok {
color: var(--metric-ok);
}
.account-status-inline.is-error,
.account-card-note.is-error {
color: var(--metric-danger);
}
.account-status-inline.is-info {
color: var(--text-secondary);
}
.account-import-drawer {
display: flex;
flex-direction: column;
gap: 5px;
padding-top: 2px;
}
.account-import-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
}
.account-import-input {
flex: 1 1 150px;
min-width: 0;
min-height: calc(26px * var(--ui-font-scale, 1));
}
.account-import-hint {
font-size: var(--fs-xs);
color: var(--text-muted);
}
.account-unlock-box {
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px 10px;
border-radius: var(--radius-xs);
background: var(--surface-subtle);
}
.account-unlock-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.account-unlock-title {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: var(--fs-sm);
color: var(--text-secondary);
}
.account-unlock-title .svg-icon {
color: var(--metric-warn);
flex-shrink: 0;
}
.account-link-btn {
padding: 0;
border: none;
background: transparent;
font-size: var(--fs-xs);
color: var(--text-muted);
cursor: pointer;
white-space: nowrap;
}
.account-link-btn:hover {
color: var(--text-primary);
text-decoration: underline;
}
.account-reset-row {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 6px 10px;
padding-top: 4px;
}
.account-reset-row .settings-action-desc {
flex: 1 1 180px;
font-size: var(--fs-xs);
}
.account-pwd-tabs {
display: inline-flex;
align-items: center;
align-self: flex-start;
gap: 4px;
padding: 2px;
border-radius: var(--radius-xs);
background: var(--surface-subtle);
}
.account-pwd-tab {
padding: 2px 8px;
border: none;
border-radius: var(--radius-xs);
background: transparent;
font-size: var(--fs-xs);
font-weight: 500;
color: var(--text-secondary);
cursor: pointer;
}
.account-pwd-tab.is-active {
background: var(--bg-elevated);
color: var(--text-primary);
}
.account-card-btn.is-confirm-warn {
color: var(--accent-primary);
background: var(--accent-primary-soft);
font-weight: 600;
}
.account-confirm-danger-btn {
color: var(--metric-danger);
background: color-mix(in srgb, var(--metric-danger) 12%, transparent);
font-weight: 600;
}
.account-confirm-danger-btn:hover:not(:disabled) {
background: color-mix(in srgb, var(--metric-danger) 20%, transparent);
}
.account-flow-strip {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 6px 10px;
padding: 6px 9px;
border-radius: var(--radius-xs);
background: var(--surface-subtle);
font-size: var(--fs-sm);
}
.account-flow-strip.is-info {
background: var(--accent-primary-soft);
}
.account-flow-strip.is-info .account-flow-msg {
color: var(--accent-primary);
}
.account-flow-strip.is-ok {
background: color-mix(in srgb, var(--metric-ok) 10%, transparent);
}
.account-flow-strip.is-ok .account-flow-msg {
color: var(--metric-ok);
}
.account-flow-strip.is-warn {
background: color-mix(in srgb, var(--metric-warn) 10%, transparent);
color: var(--metric-warn);
}
.account-flow-strip.is-error {
background: color-mix(in srgb, var(--metric-danger) 10%, transparent);
}
.account-flow-strip.is-error .account-flow-msg {
color: var(--metric-danger);
}
.account-flow-link {
font-size: var(--fs-sm);
font-weight: 500;
color: var(--accent-primary);
text-decoration: none;
white-space: nowrap;
}
.account-flow-link:hover {
text-decoration: underline;
}
.account-cards-stack {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.account-card {
gap: 10px;
padding: 11px 14px;
}
.account-card-head {
gap: 8px;
flex-wrap: wrap;
}
.account-card-meta {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
min-width: 0;
flex: 1 1 150px;
}
.account-active-dot {
background: var(--metric-ok);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--metric-ok) 20%, transparent);
}
.account-card-email {
font-size: var(--fs-base);
font-weight: 600;
color: var(--text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 100%;
}
.account-tag {
display: inline-flex;
align-items: center;
min-height: calc(18px * var(--ui-font-scale, 1));
padding: 1px 6px;
font-size: var(--fs-xs);
font-weight: 600;
line-height: 1.2;
border-radius: var(--radius-xs);
border: none;
white-space: nowrap;
}
.account-tag.is-active {
color: var(--metric-ok);
background: color-mix(in srgb, var(--metric-ok) 12%, transparent);
}
.account-tag.is-tier {
color: var(--accent-primary);
background: var(--accent-primary-soft);
}
.account-tag.is-written {
color: var(--metric-warn);
background: color-mix(in srgb, var(--metric-warn) 12%, transparent);
}
.account-card-actions {
display: inline-flex;
align-items: center;
gap: 5px;
flex-shrink: 0;
margin-left: auto;
}
.account-card-btn {
min-height: calc(23px * var(--ui-font-scale, 1));
height: auto;
padding: 1px 8px;
font-size: var(--fs-sm);
font-weight: 500;
border-radius: var(--radius-xs);
white-space: nowrap;
}
.account-icon-btn {
width: calc(23px * var(--ui-font-scale, 1));
height: calc(23px * var(--ui-font-scale, 1));
padding: 0;
border-radius: var(--radius-xs);
}
.account-pools-stack {
display: flex;
flex-direction: column;
gap: 9px;
}
.account-pool-group {
display: flex;
flex-direction: column;
gap: 4px;
}
.account-pool-name {
font-size: var(--fs-xs);
font-weight: 600;
color: var(--text-muted);
line-height: 1.25;
letter-spacing: 0.01em;
}
.account-pool-meters {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px 14px;
}
.account-pool-meters.is-single {
grid-template-columns: minmax(0, 1fr);
}
@media (max-width: 310px) {
.account-pool-meters {
grid-template-columns: minmax(0, 1fr);
}
}
.account-meter-col {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.account-meter-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 6px;
min-width: 0;
}
.settings-account-quota {
font-size: var(--fs-sm);
font-weight: 600;
color: var(--text-primary);
white-space: nowrap;
}
.account-meter-reset {
font-size: var(--fs-2xs);
color: var(--text-muted);
white-space: nowrap;
flex-shrink: 0;
}
.account-progress-track {
height: 5px;
}
.account-empty-panel {
padding: 18px 14px;
align-items: center;
justify-content: center;
}
.account-empty-text {
text-align: center;
color: var(--text-muted);
}
@keyframes anim-account-spin {
to {
transform: rotate(360deg);
}
}
.icon-btn.is-spinning .svg-icon {
animation: anim-account-spin 0.8s linear infinite;
}
@media (prefers-reduced-motion: reduce) {
.icon-btn.is-spinning .svg-icon {
animation: none !important;
}
}
.settings-context-model .select-option-meta {
max-width: 62%;
text-align: right;
+12 -5
View File
@@ -11,11 +11,12 @@ import { telemetryStore } from '../store/telemetryStore.js';
import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
import { SettingsAccountTab } from './settings/SettingsAccountTab.js';
import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js';
import { SettingsOtherTab } from './settings/SettingsOtherTab.js';
import { SettingsStructureTab } from './settings/SettingsStructureTab.js';
export const SHOW_ACCOUNT_TAB = false;
export const SHOW_ACCOUNT_TAB = true;
function getSettingsSubTabOptions() {
return [
@@ -51,10 +52,11 @@ export const SettingsView = defineComponent({
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
const accountTab = null; // SettingsAccountTab kept in src/views/settings/ for future opt-in
const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll });
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
let showingAccount = false;
let preloadedAccountOnce = false;
function applyActiveSubTab(subTab, activeView) {
const target =
subTab === 'structure' ||
@@ -69,6 +71,10 @@ export const SettingsView = defineComponent({
patchAttr(otherTab.el, 'hidden', target !== 'other');
if (accountTab) {
patchAttr(accountTab.el, 'hidden', target !== 'account');
if (activeView === 'settings' && !preloadedAccountOnce) {
preloadedAccountOnce = true;
void accountTab.refs.preload?.();
}
const nextShowingAccount = target === 'account' && activeView === 'settings';
if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
showingAccount = nextShowingAccount;
@@ -102,6 +108,9 @@ export const SettingsView = defineComponent({
if (getVisibleMonitorView(ui) !== 'settings') return;
const telemetry = telemetryStore.getState().telemetry;
const settings = telemetry?.settings;
if (accountTab) {
accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas, settings);
}
if (settingsSubTab === 'structure') {
if (settings) {
structureTab.refs.renderSettings(
@@ -122,9 +131,7 @@ export const SettingsView = defineComponent({
telemetry?.cloudCodeProxy
);
}
} else if (accountTab && settingsSubTab === 'account') {
accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas);
} else {
} else if (settingsSubTab !== 'account') {
if (settings) generalTab.refs.renderSettings(settings);
if (telemetry?.cloudStatus) generalTab.refs.renderCloudStatus(telemetry.cloudStatus);
}
File diff suppressed because it is too large Load Diff
+478
View File
@@ -6266,6 +6266,484 @@ html[data-standalone="true"] .app-shell {
line-height: 1.35;
}
.settings-account-root [hidden] {
display: none !important;
}
.account-toolbar-panel {
padding: 9px 12px;
gap: 8px;
}
.account-toolbar-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
flex-wrap: wrap;
}
.account-toolbar-left,
.account-toolbar-right {
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.account-toolbar-right {
margin-left: auto;
}
.account-toolbar-btn {
display: inline-flex;
align-items: center;
gap: 5px;
min-height: calc(25px * var(--ui-font-scale, 1));
height: auto;
padding: 2px 10px;
font-size: var(--fs-md);
font-weight: 500;
border-radius: var(--radius-xs);
white-space: nowrap;
}
.account-toolbar-btn.is-open {
color: var(--accent-primary);
background: var(--accent-primary-soft);
}
.account-reload-btn {
width: calc(25px * var(--ui-font-scale, 1));
height: calc(25px * var(--ui-font-scale, 1));
padding: 0;
border-radius: var(--radius-xs);
flex-shrink: 0;
}
.account-refresh-select {
flex: 0 0 auto;
width: auto;
min-width: 0;
}
.account-refresh-select .select-trigger {
width: auto;
min-height: calc(25px * var(--ui-font-scale, 1));
height: auto;
padding: 2px 8px;
gap: 5px;
font-size: var(--fs-sm);
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
background: var(--surface-subtle);
}
[data-modern-ui="true"] .account-refresh-select .select-trigger {
border: none;
background: var(--modern-surface-subtle);
}
[data-modern-ui="true"] .account-refresh-select .select-trigger:hover,
[data-modern-ui="true"] .account-refresh-select.is-open .select-trigger {
background: var(--modern-surface-hover);
}
.account-refresh-select .select-menu {
right: 0;
left: auto;
min-width: 108px;
width: max-content;
}
.account-status-inline {
font-size: var(--fs-sm);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 210px;
}
.account-status-inline.is-ok {
color: var(--metric-ok);
}
.account-status-inline.is-error,
.account-card-note.is-error {
color: var(--metric-danger);
}
.account-status-inline.is-info {
color: var(--text-secondary);
}
.account-import-drawer {
display: flex;
flex-direction: column;
gap: 5px;
padding-top: 2px;
}
.account-import-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
}
.account-import-input {
flex: 1 1 150px;
min-width: 0;
min-height: calc(26px * var(--ui-font-scale, 1));
}
.account-import-hint {
font-size: var(--fs-xs);
color: var(--text-muted);
}
.account-unlock-box {
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px 10px;
border-radius: var(--radius-xs);
background: var(--surface-subtle);
}
.account-unlock-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.account-unlock-title {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: var(--fs-sm);
color: var(--text-secondary);
}
.account-unlock-title .svg-icon {
color: var(--metric-warn);
flex-shrink: 0;
}
.account-link-btn {
padding: 0;
border: none;
background: transparent;
font-size: var(--fs-xs);
color: var(--text-muted);
cursor: pointer;
white-space: nowrap;
}
.account-link-btn:hover {
color: var(--text-primary);
text-decoration: underline;
}
.account-reset-row {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 6px 10px;
padding-top: 4px;
}
.account-reset-row .settings-action-desc {
flex: 1 1 180px;
font-size: var(--fs-xs);
}
.account-pwd-tabs {
display: inline-flex;
align-items: center;
align-self: flex-start;
gap: 4px;
padding: 2px;
border-radius: var(--radius-xs);
background: var(--surface-subtle);
}
.account-pwd-tab {
padding: 2px 8px;
border: none;
border-radius: var(--radius-xs);
background: transparent;
font-size: var(--fs-xs);
font-weight: 500;
color: var(--text-secondary);
cursor: pointer;
}
.account-pwd-tab.is-active {
background: var(--bg-elevated);
color: var(--text-primary);
}
.account-card-btn.is-confirm-warn {
color: var(--accent-primary);
background: var(--accent-primary-soft);
font-weight: 600;
}
.account-confirm-danger-btn {
color: var(--metric-danger);
background: color-mix(in srgb, var(--metric-danger) 12%, transparent);
font-weight: 600;
}
.account-confirm-danger-btn:hover:not(:disabled) {
background: color-mix(in srgb, var(--metric-danger) 20%, transparent);
}
.account-flow-strip {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 6px 10px;
padding: 6px 9px;
border-radius: var(--radius-xs);
background: var(--surface-subtle);
font-size: var(--fs-sm);
}
.account-flow-strip.is-info {
background: var(--accent-primary-soft);
}
.account-flow-strip.is-info .account-flow-msg {
color: var(--accent-primary);
}
.account-flow-strip.is-ok {
background: color-mix(in srgb, var(--metric-ok) 10%, transparent);
}
.account-flow-strip.is-ok .account-flow-msg {
color: var(--metric-ok);
}
.account-flow-strip.is-warn {
background: color-mix(in srgb, var(--metric-warn) 10%, transparent);
color: var(--metric-warn);
}
.account-flow-strip.is-error {
background: color-mix(in srgb, var(--metric-danger) 10%, transparent);
}
.account-flow-strip.is-error .account-flow-msg {
color: var(--metric-danger);
}
.account-flow-link {
font-size: var(--fs-sm);
font-weight: 500;
color: var(--accent-primary);
text-decoration: none;
white-space: nowrap;
}
.account-flow-link:hover {
text-decoration: underline;
}
.account-cards-stack {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.account-card {
gap: 10px;
padding: 11px 14px;
}
.account-card-head {
gap: 8px;
flex-wrap: wrap;
}
.account-card-meta {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
min-width: 0;
flex: 1 1 150px;
}
.account-active-dot {
background: var(--metric-ok);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--metric-ok) 20%, transparent);
}
.account-card-email {
font-size: var(--fs-base);
font-weight: 600;
color: var(--text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 100%;
}
.account-tag {
display: inline-flex;
align-items: center;
min-height: calc(18px * var(--ui-font-scale, 1));
padding: 1px 6px;
font-size: var(--fs-xs);
font-weight: 600;
line-height: 1.2;
border-radius: var(--radius-xs);
border: none;
white-space: nowrap;
}
.account-tag.is-active {
color: var(--metric-ok);
background: color-mix(in srgb, var(--metric-ok) 12%, transparent);
}
.account-tag.is-tier {
color: var(--accent-primary);
background: var(--accent-primary-soft);
}
.account-tag.is-written {
color: var(--metric-warn);
background: color-mix(in srgb, var(--metric-warn) 12%, transparent);
}
.account-card-actions {
display: inline-flex;
align-items: center;
gap: 5px;
flex-shrink: 0;
margin-left: auto;
}
.account-card-btn {
min-height: calc(23px * var(--ui-font-scale, 1));
height: auto;
padding: 1px 8px;
font-size: var(--fs-sm);
font-weight: 500;
border-radius: var(--radius-xs);
white-space: nowrap;
}
.account-icon-btn {
width: calc(23px * var(--ui-font-scale, 1));
height: calc(23px * var(--ui-font-scale, 1));
padding: 0;
border-radius: var(--radius-xs);
}
.account-pools-stack {
display: flex;
flex-direction: column;
gap: 9px;
}
.account-pool-group {
display: flex;
flex-direction: column;
gap: 4px;
}
.account-pool-name {
font-size: var(--fs-xs);
font-weight: 600;
color: var(--text-muted);
line-height: 1.25;
letter-spacing: 0.01em;
}
.account-pool-meters {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px 14px;
}
.account-pool-meters.is-single {
grid-template-columns: minmax(0, 1fr);
}
@media (max-width: 310px) {
.account-pool-meters {
grid-template-columns: minmax(0, 1fr);
}
}
.account-meter-col {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.account-meter-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 6px;
min-width: 0;
}
.settings-account-quota {
font-size: var(--fs-sm);
font-weight: 600;
color: var(--text-primary);
white-space: nowrap;
}
.account-meter-reset {
font-size: var(--fs-2xs);
color: var(--text-muted);
white-space: nowrap;
flex-shrink: 0;
}
.account-progress-track {
height: 5px;
}
.account-empty-panel {
padding: 18px 14px;
align-items: center;
justify-content: center;
}
.account-empty-text {
text-align: center;
color: var(--text-muted);
}
@keyframes anim-account-spin {
to {
transform: rotate(360deg);
}
}
.icon-btn.is-spinning .svg-icon {
animation: anim-account-spin 0.8s linear infinite;
}
@media (prefers-reduced-motion: reduce) {
.icon-btn.is-spinning .svg-icon {
animation: none !important;
}
}
.settings-context-model .select-option-meta {
max-width: 62%;
text-align: right;
+131
View File
@@ -0,0 +1,131 @@
import assert from 'node:assert/strict';
import { setTimeout as delay } from 'node:timers/promises';
import test from 'node:test';
import { createAccountLoginController } from '../backend/account-login.mjs';
import { exchangeGoogleAccountCode } from '../backend/account-oauth.mjs';
const TEST_OAUTH_CLIENTS = async () => [
{
id: '1234567890-synthetic-test.apps.googleusercontent.com',
secret: 'synthetic-test-secret',
},
];
function callbackUrl(session, values) {
const authorization = new URL(session.url);
const callback = new URL(authorization.searchParams.get('redirect_uri'));
callback.search = new URLSearchParams({ state: authorization.searchParams.get('state'), ...values }).toString();
return callback;
}
test('browser login accepts its loopback callback once and saves the verified account before reporting success', async () => {
const saved = [];
let opened;
let exchanges = 0;
const controller = createAccountLoginController({
getClients: TEST_OAUTH_CLIENTS,
openBrowser: async (url) => { opened = url; return true; },
exchangeCode: async (code, redirectUri, verifier) => {
exchanges += 1;
assert.equal(code, 'synthetic-code');
assert.match(redirectUri, /^http:\/\/127\.0\.0\.1:\d+\/oauth-callback$/);
assert.match(verifier, /^[\w-]{43,128}$/);
return { email: 'verified@example.com', credential: { token: { refresh_token: 'synthetic-private' } } };
},
});
const session = await controller.start(async (account) => { saved.push(account.email); });
try {
assert.equal(session.opened, true);
const authorization = new URL(opened);
assert.equal(authorization.origin, 'https://accounts.google.com');
assert.equal(authorization.searchParams.get('access_type'), 'offline');
assert.equal(authorization.searchParams.get('code_challenge_method'), 'S256');
assert.match(authorization.searchParams.get('prompt'), /select_account/);
const invalid = await fetch(callbackUrl(session, { state: 'unrelated', code: 'bad-code' }));
assert.equal(invalid.status, 400);
assert.equal(controller.getStatus(session.id).status, 'waiting');
assert.equal(exchanges, 0);
const response = await fetch(callbackUrl(session, { code: 'synthetic-code' }));
const page = await response.text();
assert.equal(response.status, 200);
assert.match(page, /账号已添加/);
assert.equal(page.includes('synthetic-code'), false);
assert.equal(page.includes('synthetic-private'), false);
assert.deepEqual(saved, ['verified@example.com']);
assert.deepEqual(controller.getStatus(session.id), { id: session.id, status: 'success', error: '', email: 'verified@example.com' });
assert.equal(exchanges, 1);
} finally {
controller.cancel(session.id);
}
});
test('login offers a usable browser link when opening fails, and cancellation closes the listener', async () => {
const controller = createAccountLoginController({
getClients: TEST_OAUTH_CLIENTS,
openBrowser: async () => false,
});
const session = await controller.start(async () => { assert.fail('cancelled login must not save credentials'); });
assert.equal(session.opened, false);
assert.match(session.url, /^https:\/\/accounts\.google\.com\//);
assert.equal((await controller.start(async () => {})).id, session.id);
assert.equal(controller.cancel(session.id).status, 'cancelled');
await delay(10);
await assert.rejects(fetch(callbackUrl(session, { code: 'unused' })));
});
test('denied authorization and expired sessions never save an account', async () => {
const controller = createAccountLoginController({
getClients: TEST_OAUTH_CLIENTS,
openBrowser: async () => true,
timeoutMs: 50,
});
const denied = await controller.start(async () => { assert.fail('denied authorization'); }, 'en-US');
const response = await fetch(callbackUrl(denied, { error: 'access_denied' }));
assert.equal(response.status, 200);
assert.match(await response.text(), /Sign-in incomplete/);
assert.equal(controller.getStatus(denied.id).status, 'cancelled');
const expired = await controller.start(async () => { assert.fail('expired authorization'); });
await delay(100);
assert.equal(controller.getStatus(expired.id).status, 'expired');
await assert.rejects(fetch(callbackUrl(expired, { code: 'late' })));
});
test('cancelled code exchange cannot add an account after the next login starts', async () => {
let release;
let exchangeStarted;
const started = new Promise((resolve) => { exchangeStarted = resolve; });
const credential = new Promise((resolve) => { release = resolve; });
const controller = createAccountLoginController({
getClients: TEST_OAUTH_CLIENTS,
openBrowser: async () => true,
exchangeCode: async () => { exchangeStarted(); return credential; },
});
const original = await controller.start(async () => { assert.fail('old login was cancelled'); });
const request = fetch(callbackUrl(original, { code: 'pending' }));
await started;
controller.cancel(original.id);
const replacement = await controller.start(async () => {});
release({ email: 'old@example.com', credential: {} });
assert.equal((await request).status, 409);
assert.equal(controller.getStatus(replacement.id).status, 'waiting');
controller.cancel(replacement.id);
});
test('authorization code exchange sends the callback and verifier, then identifies the Google account', async () => {
const verified = await exchangeGoogleAccountCode('synthetic-code', 'http://127.0.0.1:12345/oauth-callback', 'synthetic-verifier', {
getClients: TEST_OAUTH_CLIENTS,
fetchFn: async (url, request) => {
if (url.endsWith('/token')) {
assert.equal(request.body.get('grant_type'), 'authorization_code');
assert.equal(request.body.get('code'), 'synthetic-code');
assert.equal(request.body.get('code_verifier'), 'synthetic-verifier');
assert.equal(request.body.get('redirect_uri'), 'http://127.0.0.1:12345/oauth-callback');
return { ok: true, json: async () => ({ access_token: 'test-access', refresh_token: 'test-refresh', expires_in: 3600 }) };
}
assert.equal(request.headers.Authorization, 'Bearer test-access');
return { ok: true, json: async () => ({ email: 'verified@example.com', verified_email: true }) };
},
});
assert.equal(verified.email, 'verified@example.com');
assert.equal(verified.credential.token.refresh_token, 'test-refresh');
});
+483 -14
View File
@@ -3,8 +3,28 @@ import { mkdtemp, readFile, rmdir, unlink } from 'node:fs/promises';
import { join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { resolveGoogleCredential, retrieveCredentialQuota } from '../backend/account-oauth.mjs';
import { handleAccountCredentialAction, normalizeAccountCredential, runWindowsCredentialStore } from '../backend/account-switch.mjs';
import { createAccountLoginController } from '../backend/account-login.mjs';
import {
buildGoogleAccountLoginUrl,
collectNativeOAuthBinaryCandidates,
extractNativeOAuthClients,
resolveGoogleCredential,
retrieveCredentialQuota,
} from '../backend/account-oauth.mjs';
import {
clearAccountVaultRuntimeState,
handleAccountCredentialAction,
normalizeAccountCredential,
runWindowsCredentialStore,
serializeVaultCredential,
} from '../backend/account-switch.mjs';
import {
decryptVaultEntryCredential,
issueAccountActionNonce,
resetVaultUnlockFailures,
verifyAccountActionNonce,
} from '../backend/account-vault-crypto.mjs';
import { executeAccountCredentialAction } from '../backend/api-actions.mjs';
test('accepts a shared OAuth credential or refresh token, and rejects other credential types', () => {
const refreshToken = '1//synthetic-refresh-token-for-test';
@@ -42,17 +62,17 @@ test('import uses the verified email and switches only after checking the creden
if (request.action === 'read') return { credential: saved };
assert.equal(request.target, 'gemini:antigravity');
assert.equal(request.email, 'next@example.com');
if (request.action === 'switch') assert.equal(request.expectedCredential, saved);
return { accounts: ['next@example.com'], selectedEmail: request.email, credential: saved };
if (request.action === 'scheduleSwitch') assert.equal(request.expectedCredential, saved);
return { accounts: ['next@example.com'], selectedEmail: request.email, credential: saved, scheduled: request.action === 'scheduleSwitch' };
},
};
assert.deepEqual(await handleAccountCredentialAction({ action: 'save', email: 'ignored@example.com', credential: input }, options), {
supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com',
supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', quotas: {},
});
assert.deepEqual(calls.splice(0), ['refresh-identity', 'save']);
const result = await handleAccountCredentialAction({ action: 'switch', email: 'NEXT@example.com' }, options);
assert.deepEqual(result, { supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', confirmed: true });
assert.deepEqual(calls.splice(0), ['read', 'verify-identity', 'switch', 'GetAuthStatus', 'GetUserStatus']);
assert.deepEqual(result, { supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', quotas: {}, restarting: true });
assert.deepEqual(calls.splice(0), ['read', 'verify-identity', 'scheduleSwitch']);
verifiedEmail = 'different@example.com';
assert.deepEqual(await handleAccountCredentialAction({ action: 'switch', email: 'next@example.com' }, options), { error: 'identityMismatch' });
assert.deepEqual(calls, ['read', 'verify-identity']);
@@ -64,7 +84,7 @@ test('a saved credential can query its quota without replacing the active login'
const result = await handleAccountCredentialAction({ action: 'quota', email: 'next@example.com' }, {
platform: 'win32',
store: async (request) => {
assert.equal(request.action, 'read');
assert.ok(['read', 'saveQuota'].includes(request.action));
return { credential };
},
resolveCredential: async (stored) => ({ email: 'next@example.com', credential: stored }),
@@ -73,7 +93,8 @@ test('a saved credential can query its quota without replacing the active login'
return pools;
},
});
assert.deepEqual(result, { email: 'next@example.com', pools });
assert.deepEqual({ email: result.email, pools: result.pools }, { email: 'next@example.com', pools });
assert.ok(result.fetchedAt > 0);
});
test('Google OAuth confirms the email and the same account token retrieves quota pools', async () => {
@@ -89,6 +110,7 @@ test('Google OAuth confirms the email and the same account token retrieves quota
}
assert.equal(request.headers.Authorization, 'Bearer new-access');
if (url.endsWith('/userinfo')) return { ok: true, json: async () => ({ email: 'owner@example.com', verified_email: true }) };
assert.match(request.headers['User-Agent'], /^antigravity\/hub\//);
if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ cloudaicompanionProject: { id: 'test-project' } }) };
assert.equal(JSON.parse(request.body).project, 'test-project');
if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) };
@@ -107,22 +129,469 @@ test('Google OAuth confirms the email and the same account token retrieves quota
assert.equal(endpoints.length, 5);
});
test('quota queries keep the native header and omit project when Google did not return one', async () => {
const requests = [];
const pools = await retrieveCredentialQuota('native-access', async (url, request) => {
const body = JSON.parse(request.body);
requests.push({ url, body });
assert.match(request.headers['User-Agent'], /^antigravity\/hub\//);
if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ allowedTiers: [] }) };
assert.deepEqual(body, {});
if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) };
return { ok: true, json: async () => ({ groups: [{ displayName: 'Gemini Models', buckets: [{ window: 'weekly', remainingFraction: 0.42 }] }] }) };
});
assert.equal(pools[0].weeklyRemainingPct, 42);
assert.equal(requests.length, 3);
});
test('a forbidden project is retried without that project before another endpoint', async () => {
let retried = 0;
const pools = await retrieveCredentialQuota('native-access', async (url, request) => {
const body = JSON.parse(request.body);
if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ cloudaicompanionProject: 'stale-project' }) };
if (body.project) return { ok: false, status: 403 };
retried += 1;
if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) };
return { ok: true, json: async () => ({ groups: [{ displayName: 'Claude and GPT models', buckets: [{ window: '5h', remainingFraction: 0 }] }] }) };
});
assert.equal(retried, 2);
assert.equal(pools[0].remainingPct, 0);
});
test('Windows vault atomically saves, reloads and removes encrypted entries', { skip: process.platform !== 'win32' }, async () => {
const directory = await mkdtemp(fileURLToPath(new URL('../.account-test-', import.meta.url)));
const vault = join(directory, 'test.dpapi');
const run = (action, email, credential) => runWindowsCredentialStore({ action, email, credential, vault });
try {
const credential = normalizeAccountCredential('1//synthetic-refresh-token-for-test');
assert.deepEqual(await run('list'), { accounts: [], selectedEmail: '' });
assert.deepEqual(await run('save', 'active@example.com', credential), { accounts: ['active@example.com'], selectedEmail: '' });
assert.deepEqual(await run('save', 'next@example.com', credential), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' });
assert.deepEqual(await run('list'), { accounts: [], selectedEmail: '', quotas: {} });
assert.deepEqual(await run('save', 'active@example.com', credential), { accounts: ['active@example.com'], selectedEmail: '', quotas: {} });
assert.deepEqual(await run('save', 'next@example.com', credential), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '', quotas: {} });
assert.deepEqual(await run('read', 'next@example.com'), { credential });
assert.deepEqual(await runWindowsCredentialStore({ action: 'save', email: 'next@example.com', credential, expectedCredential: 'stale', vault }), { error: 'credentialChanged' });
assert.equal((await readFile(vault)).includes('synthetic-refresh-token-for-test'), false);
assert.deepEqual(await run('list'), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' });
assert.deepEqual(await run('remove', 'next@example.com'), { accounts: ['active@example.com'], selectedEmail: '' });
assert.deepEqual(await run('list'), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '', quotas: {} });
const quota = { fetchedAt: 100, pools: [{ poolKey: 'Gemini', remainingPct: 0, weeklyRemainingPct: 70 }] };
await runWindowsCredentialStore({ action: 'saveQuota', email: 'active@example.com', expectedCredential: credential, quota, vault });
assert.deepEqual((await run('list')).quotas, { 'active@example.com': quota });
assert.deepEqual(await run('remove', 'next@example.com'), { accounts: ['active@example.com'], selectedEmail: '', quotas: { 'active@example.com': quota } });
} finally {
await unlink(vault).catch((err) => { if (err.code !== 'ENOENT') throw err; });
await rmdir(directory);
}
});
test('browser authorization adds a credential through the normal account actions and encrypted vault', { skip: process.platform !== 'win32' }, async () => {
const directory = await mkdtemp(fileURLToPath(new URL('../.account-login-test-', import.meta.url)));
const vault = join(directory, 'test.dpapi');
const credential = JSON.parse(normalizeAccountCredential('1//synthetic-browser-authorized-credential'));
const login = createAccountLoginController({
getClients: async () => [
{ id: '1234567890-synthetic-test.apps.googleusercontent.com', secret: 'synthetic-test-secret' },
],
openBrowser: async () => true,
exchangeCode: async () => ({ email: 'browser@example.com', credential }),
});
const options = { platform: 'win32', login, store: (request) => runWindowsCredentialStore({ ...request, vault, statusFile: '' }) };
let id;
try {
const result = await handleAccountCredentialAction({ action: 'loginStart', language: 'zh-CN' }, options);
assert.equal(result.supported, true);
assert.equal(result.login.status, 'waiting');
id = result.login.id;
const authorization = new URL(result.login.url);
const callback = new URL(authorization.searchParams.get('redirect_uri'));
callback.search = new URLSearchParams({ state: authorization.searchParams.get('state'), code: 'synthetic-code' }).toString();
assert.equal((await fetch(callback)).status, 200);
assert.equal((await handleAccountCredentialAction({ action: 'loginStatus', id }, options)).login.status, 'success');
const accounts = await handleAccountCredentialAction({ action: 'list' }, options);
assert.deepEqual(accounts.accounts, ['browser@example.com']);
assert.equal(accounts.selectedEmail, '');
assert.equal(JSON.stringify(accounts).includes('synthetic-browser-authorized-credential'), false);
assert.equal((await readFile(vault)).includes('synthetic-browser-authorized-credential'), false);
} finally {
if (id) login.cancel(id);
await unlink(vault).catch((error) => { if (error.code !== 'ENOENT') throw error; });
await rmdir(directory);
}
});
test('login scope includes auth/aicode, switch auto-backs-up unsaved active login with 2.34 signout guard, and quota extracts tierName', async () => {
const loginUrl = new URL(
await buildGoogleAccountLoginUrl('http://127.0.0.1:9999/oauth-callback', 'st', 'ch', {
getClients: async () => [
{ id: '1234567890-synthetic-test.apps.googleusercontent.com', secret: 'synthetic-test-secret' },
],
})
);
const scopes = (loginUrl.searchParams.get('scope') || '').split(/\s+/);
assert.ok(scopes.includes('https://www.googleapis.com/auth/aicode'));
const savedEntries = new Map([
['target@example.com', normalizeAccountCredential('1//target-refresh-token-value-1234567890')],
]);
const liveCurrent = normalizeAccountCredential('1//active-host-refresh-token-value-1234567890');
let scheduledPayload = null;
const res = await handleAccountCredentialAction(
{ action: 'switch', email: 'target@example.com', activeEmail: 'current@example.com' },
{
platform: 'win32',
resolveCredential: async (cred) => ({
email: cred.token.refresh_token.includes('active-host')
? 'current@example.com'
: 'target@example.com',
credential: cred,
}),
store: async (req) => {
if (req.action === 'read') {
const hit = savedEntries.get(req.email);
return hit ? { credential: hit } : { error: 'notFound' };
}
if (req.action === 'readCurrent') {
return { credential: liveCurrent };
}
if (req.action === 'save') {
savedEntries.set(req.email, req.credential);
return { accounts: [...savedEntries.keys()], selectedEmail: '' };
}
if (req.action === 'scheduleSwitch') {
scheduledPayload = JSON.parse(req.credential);
return {
scheduled: true,
accounts: [...savedEntries.keys()],
selectedEmail: req.email,
};
}
return { error: 'storeFailed' };
},
}
);
assert.equal(res.restarting, true);
assert.ok(savedEntries.has('current@example.com'), 'Active host account must be auto-backed-up before switching away');
assert.ok(
Number.isSafeInteger(scheduledPayload?.aicode_scope_sign_out_attempted_at) &&
scheduledPayload.aicode_scope_sign_out_attempted_at > 0,
'Switched host credential must include 2.34 aicode_scope_sign_out_attempted_at guard'
);
const pools = await retrieveCredentialQuota('tok', async (url) => {
if (url.endsWith(':loadCodeAssist')) {
return {
ok: true,
json: async () => ({
paidTier: { id: 'g1-ultra-tier', name: 'Google AI Ultra' },
cloudaicompanionProject: 'p1',
}),
};
}
if (url.endsWith(':fetchAvailableModels')) {
return { ok: true, json: async () => ({ models: {} }) };
}
return {
ok: true,
json: async () => ({
groups: [{ displayName: 'Gemini Models', buckets: [{ window: 'weekly', remainingFraction: 0.85 }] }],
}),
};
});
assert.equal(pools.tierName, 'Google AI Ultra');
assert.equal(pools.tierInfo.tierMultiplier, '20x');
assert.equal(pools[0].weeklyRemainingPct, 85);
const litePools = await retrieveCredentialQuota('tok-5x', async (url) => {
if (url.endsWith(':loadCodeAssist')) {
return {
ok: true,
json: async () => ({
paidTier: { id: 'g1-ultra-lite-tier', name: 'Google AI Ultra' },
cloudaicompanionProject: 'p2',
}),
};
}
if (url.endsWith(':fetchAvailableModels')) {
return { ok: true, json: async () => ({ models: {} }) };
}
return {
ok: true,
json: async () => ({
groups: [{ displayName: 'Gemini Models', buckets: [{ window: 'weekly', remainingFraction: 0.91 }] }],
}),
};
});
assert.deepEqual(litePools.tierInfo, {
tierId: 'g1-ultra-lite-tier',
tierName: 'Google AI Ultra',
tierMultiplier: '5x',
});
});
test('enforces OAuth client_id allowlist, minimizes at-rest vault payload, and validates actionNonce on mutations', async () => {
const rt = '1//synthetic-refresh-token-for-allowlist-check';
assert.equal(
normalizeAccountCredential(
JSON.stringify({ client_id: 'evil-third-party.apps.googleusercontent.com', refresh_token: rt })
),
null,
'Must reject unknown third-party OAuth client_id'
);
assert.equal(
normalizeAccountCredential(
JSON.stringify({ type: 'service_account', refresh_token: rt })
),
null,
'Must reject non-user OAuth credential types'
);
const syntheticOfficialId = '1234567890-synthetic-test.apps.googleusercontent.com';
const validWithOfficialClient = normalizeAccountCredential(
JSON.stringify({
client_id: syntheticOfficialId,
client_secret: 'should-be-stripped',
access_token: 'ephemeral-access-token',
id_token: 'ephemeral-id-token',
refresh_token: rt,
}),
{ allowedClientIds: [syntheticOfficialId] }
);
assert.ok(validWithOfficialClient, 'Allowlisted Antigravity OAuth client_id must be accepted');
assert.equal(validWithOfficialClient.includes('should-be-stripped'), false);
// Verify PE .text/.rdata native OAuth client extraction & multi-path candidate discovery
const fakeId = '9876543210-unit-test-client.apps.googleusercontent.com';
const fakeSecret = 'GOCSPX-unit-test';
const peBuf = Buffer.alloc(1024);
peBuf.writeUInt16LE(0x5a4d, 0);
peBuf.writeUInt32LE(0x80, 60);
peBuf.writeUInt32LE(0x4550, 0x80);
peBuf.writeUInt16LE(0x8664, 0x84);
peBuf.writeUInt16LE(2, 0x86);
peBuf.writeUInt16LE(0, 0x94);
const secTable = 0x80 + 24;
peBuf.write('.text', secTable, 'ascii');
peBuf.writeUInt32LE(0x1000, secTable + 12);
peBuf.writeUInt32LE(0x100, secTable + 16);
peBuf.writeUInt32LE(0x200, secTable + 20);
peBuf.write('.rdata', secTable + 40, 'ascii');
peBuf.writeUInt32LE(0x2000, secTable + 52);
peBuf.writeUInt32LE(0x100, secTable + 56);
peBuf.writeUInt32LE(0x300, secTable + 60);
peBuf.write(fakeId + fakeSecret + 'trailing-go-str', 0x300, 'ascii');
const codeStart = 0x200;
Buffer.from([0x48, 0xc7, 0x40, 0x08]).copy(peBuf, codeStart);
peBuf.writeUInt32LE(fakeId.length, codeStart + 4);
Buffer.from([0x48, 0x8d, 0x0d]).copy(peBuf, codeStart + 8);
peBuf.writeInt32LE(0x2000 - (0x1000 + 11 + 4), codeStart + 11);
Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]).copy(peBuf, codeStart + 15);
peBuf.writeUInt32LE(fakeSecret.length, codeStart + 22);
Buffer.from([0x48, 0x8d, 0x0d]).copy(peBuf, codeStart + 26);
peBuf.writeInt32LE(0x2000 + fakeId.length - (0x1000 + 29 + 4), codeStart + 29);
assert.deepEqual(extractNativeOAuthClients(peBuf), [{ id: fakeId, secret: fakeSecret }]);
const discoveredCands = collectNativeOAuthBinaryCandidates({
env: {
USAGE_MONITOR_HOST_EXE: 'D:\\Custom\\Antigravity\\Antigravity.exe',
ANTIGRAVITY_GEMINI_DIR: 'D:\\CustomGemini',
},
homeDir: 'C:\\Users\\Test',
existsFn: null,
});
assert.ok(discoveredCands.some((p) => /D:\\Custom\\Antigravity\\resources\\bin\\language_server\.exe$/i.test(p)));
assert.ok(discoveredCands.some((p) => /D:\\CustomGemini\\bin\\agy\.exe$/i.test(p)));
const minStored = serializeVaultCredential(JSON.parse(validWithOfficialClient));
assert.equal(minStored.includes('ephemeral-access-token'), false);
assert.equal(minStored.includes('ephemeral-id-token'), false);
assert.deepEqual(JSON.parse(minStored), {
token: { refresh_token: rt, token_type: 'Bearer' },
auth_method: 'consumer',
});
const nonce = issueAccountActionNonce(1_700_000_000_000);
assert.equal(verifyAccountActionNonce(nonce, 1_700_000_000_000), true);
assert.equal(verifyAccountActionNonce(`${nonce}x`, 1_700_000_000_000), false);
assert.equal(verifyAccountActionNonce(nonce, 1_700_000_000_000 + 45 * 60_000), false);
const missingNonceRes = await executeAccountCredentialAction({
action: 'remove',
email: 'a@example.com',
});
const missingBody = JSON.parse(missingNonceRes.body);
assert.equal(missingBody.error, 'invalidActionNonce');
assert.equal(typeof missingBody.actionNonce, 'string');
});
test('secondary passphrase encrypts credentials with scrypt + AES-256-GCM, preserves cached list while locked, throttles brute force, and rotates/resets cleanly', { skip: process.platform !== 'win32' }, async (t) => {
const directory = await mkdtemp(fileURLToPath(new URL('../.account-sec-test-', import.meta.url)));
const vault = join(directory, 'sec-test.dpapi');
t.after(async () => {
clearAccountVaultRuntimeState();
await unlink(vault).catch((err) => {
if (err.code !== 'ENOENT') throw err;
});
await rmdir(directory);
});
clearAccountVaultRuntimeState();
const options = {
platform: 'win32',
resolveCredential: async (cred) => {
const rt = cred.token.refresh_token;
const email = rt.includes('alpha') ? 'alpha@example.com' : 'beta@example.com';
return {
email,
credential: {
token: {
access_token: `live-access-for-${email}`,
refresh_token: rt,
token_type: 'Bearer',
expiry: new Date(Date.now() + 3600_000).toISOString(),
},
auth_method: 'consumer',
id_token: 'live-jwt-id-token',
},
};
},
getQuota: async () => [{ poolKey: 'Gemini', remainingPct: 88, weeklyRemainingPct: 92 }],
store: (req) => {
if (req.action === 'scheduleSwitch') {
// Verify host receives live access_token while vault receives encrypted agv1: ciphertext
assert.equal(req.credential.includes('live-access-for-'), true);
assert.equal(String(req.vaultCredential || '').startsWith('agv1:'), true);
return Promise.resolve({
scheduled: true,
accounts: ['alpha@example.com', 'beta@example.com'],
selectedEmail: req.email,
security: { enabled: true, salt: req.expectedSecuritySalt },
});
}
return runWindowsCredentialStore({ ...req, vault, statusFile: '' });
},
};
await handleAccountCredentialAction(
{ action: 'save', credential: '1//alpha-refresh-token-1234567890123456' },
options
);
await handleAccountCredentialAction(
{ action: 'save', credential: '1//beta-refresh-token-1234567890123456' },
options
);
await handleAccountCredentialAction({ action: 'quota', email: 'alpha@example.com' }, options);
// Set secondary passphrase -> encrypts all saved entries inside DPAPI vault
const setRes = await handleAccountCredentialAction(
{ action: 'setPassword', newPassword: 'correct-horse-battery' },
options
);
assert.deepEqual(setRes.security, { enabled: true, unlocked: true });
const rawVaultAfterSet = await runWindowsCredentialStore({ action: 'readVault', vault });
assert.equal(rawVaultAfterSet.entries.length, 2);
for (const entry of rawVaultAfterSet.entries) {
assert.equal(entry.credential.startsWith('agv1:'), true);
assert.equal(entry.credential.includes('refresh-token'), false);
assert.equal(entry.credential.includes('live-access'), false);
}
// AAD binds ciphertext to email: swapping ciphertext onto another email must fail decryption
assert.throws(
() =>
decryptVaultEntryCredential(
rawVaultAfterSet.entries[0].credential,
Buffer.alloc(32, 1),
'beta@example.com'
),
/vaultDecryptFailed/
);
// Lock session -> emails & cached quotas remain readable, all mutations/decryptions blocked
const lockedList = await handleAccountCredentialAction({ action: 'lockVault' }, options);
assert.deepEqual(lockedList.security, { enabled: true, unlocked: false });
assert.deepEqual(lockedList.accounts, ['alpha@example.com', 'beta@example.com']);
assert.equal(lockedList.quotas['alpha@example.com'].pools[0].remainingPct, 88);
for (const blockedAction of [
{ action: 'switch', email: 'alpha@example.com' },
{ action: 'remove', email: 'beta@example.com' },
{ action: 'quota', email: 'alpha@example.com' },
{ action: 'save', credential: '1//alpha-refresh-token-1234567890123456' },
{ action: 'loginStart', language: 'zh-CN' },
]) {
const blocked = await handleAccountCredentialAction(blockedAction, options);
assert.equal(blocked.error, 'vaultLocked', `Action ${blockedAction.action} must reject while locked`);
}
// Wrong passphrase -> wrongPassword, then rate-limited on 5th consecutive failure
for (let i = 0; i < 4; i++) {
const bad = await handleAccountCredentialAction(
{ action: 'unlockVault', password: `wrong-pass-${i}` },
options
);
assert.equal(bad.error, 'wrongPassword');
}
const throttled = await handleAccountCredentialAction(
{ action: 'unlockVault', password: 'wrong-pass-5' },
options
);
assert.equal(throttled.error, 'passwordRateLimited');
assert.ok(throttled.retryAfterSec >= 1);
resetVaultUnlockFailures();
const unlockedRes = await handleAccountCredentialAction(
{ action: 'unlockVault', password: 'correct-horse-battery' },
options
);
assert.deepEqual(unlockedRes.security, { enabled: true, unlocked: true });
// Switch while unlocked keeps vault entry encrypted
const switched = await handleAccountCredentialAction(
{ action: 'switch', email: 'alpha@example.com' },
options
);
assert.equal(switched.restarting, true);
// Change passphrase -> old password rejected, new password works
const changed = await handleAccountCredentialAction(
{
action: 'changePassword',
currentPassword: 'correct-horse-battery',
newPassword: 'new-passphrase-9876',
},
options
);
assert.deepEqual(changed.security, { enabled: true, unlocked: true });
await handleAccountCredentialAction({ action: 'lockVault' }, options);
assert.equal(
(await handleAccountCredentialAction({ action: 'unlockVault', password: 'correct-horse-battery' }, options)).error,
'wrongPassword'
);
assert.deepEqual(
(await handleAccountCredentialAction({ action: 'unlockVault', password: 'new-passphrase-9876' }, options)).security,
{ enabled: true, unlocked: true }
);
// Disable passphrase requires valid current password
assert.equal(
(await handleAccountCredentialAction({ action: 'disablePassword', currentPassword: 'wrong-current' }, options)).error,
'wrongPassword'
);
const disabled = await handleAccountCredentialAction(
{ action: 'disablePassword', currentPassword: 'new-passphrase-9876', includeSecurity: true },
options
);
assert.deepEqual(disabled.security, { enabled: false, unlocked: true });
const rawAfterDisable = await runWindowsCredentialStore({ action: 'readVault', vault });
assert.equal(rawAfterDisable.entries[0].credential.startsWith('agv1:'), false);
assert.equal(rawAfterDisable.entries[0].credential.includes('live-access'), false);
// Reset vault clears entries only when confirmReset === 'RESET'
assert.equal(
(await handleAccountCredentialAction({ action: 'resetVault' }, options)).error,
'invalidCredential'
);
const resetRes = await handleAccountCredentialAction(
{ action: 'resetVault', confirmReset: 'RESET' },
options
);
assert.deepEqual(resetRes.accounts, []);
});
+13 -2
View File
@@ -2,7 +2,16 @@ import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import vm from 'node:vm';
import { createHash, randomUUID } from 'node:crypto';
import {
createCipheriv,
createDecipheriv,
createHash,
createHmac,
randomBytes,
randomUUID,
scrypt,
timingSafeEqual,
} from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import * as metrics from '../trajectory-metrics.mjs';
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
@@ -25,6 +34,8 @@ const BACKEND_MODULE_FILES = [
'../backend/fs-atomic.mjs',
'../backend/context-windows.mjs',
'../backend/account-oauth.mjs',
'../backend/account-login.mjs',
'../backend/account-vault-crypto.mjs',
'../backend/account-switch.mjs',
'../backend/http-helpers.mjs',
'../backend/settings-schema.mjs',
@@ -106,7 +117,7 @@ export function backendHarness({
}
};
const ctx={
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, createHash, randomUUID,
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, scrypt, timingSafeEqual,
...(clock ? { Date: class extends Date {
constructor(...args) { super(...(args.length ? args : [clock()])); }
static now() { return clock(); }
@@ -1123,7 +1123,7 @@ test('P0 audit fixes: main/bridge-daemon import isolation, standalone lsAddr, du
assert.doesNotMatch(renderBody, /\buiStore\.setState\b/);
});
test('P1 audit fixes: shared third-party pool & route single-source, pure frozen resolveScopedConversation, mock schema alignment, and dead SettingsAccountTab exclusion', async () => {
test('P1 audit fixes: shared third-party pool & route single-source, pure frozen resolveScopedConversation, mock schema alignment, and account preferences inclusion', async () => {
const { normalizeI18nLanguage } = await import('../src/i18n/index.js');
const { resolveSpecificQuotaSlotSummary } = await import('../src/registries/metricRegistry.js');
const { resolveScopedConversation, isEquivalentTelemetry } = await import(
@@ -1188,7 +1188,7 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen
assert.equal(scoped.aggregated.recentSteps.length, 2);
assert.equal(scoped.mainAgent.recentSteps.length, 1);
// 3. structurePreviewMock schema completeness & dead SettingsAccountTab exclusion from app.js
// 3. structurePreviewMock schema completeness & account preferences bundled for use
const mock = buildStructurePreviewTelemetry();
assert.equal(typeof mock.activeConversation.context.compactionUsedTokens, 'number');
assert.equal(mock.activeConversation.aggregated.agentId, 'all');
@@ -1196,8 +1196,8 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen
assert.equal(mock.quotas.meta.hasOfficialData, true);
const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8');
assert.equal(appJs.includes('SettingsAccountTab.js'), false);
assert.equal(appJs.includes('function renderQuotaRows('), false);
assert.equal(appJs.includes('SettingsAccountTab.js'), true);
assert.equal(appJs.includes('function renderQuotaRows('), true);
});
test('P2 audit fixes: standalone sqlite/proto-wire primitives, structured liveActivity/agent/media i18n, full en-US SVG charts, controlled LiveActivityWidget reuse, and shared Mock DOM', async () => {
@@ -2859,7 +2859,7 @@ test('P2 regressions: bundler regex-after-paren lexer, shared URI/prompt/atomic
assert.equal(latestQuery, '');
assert.equal(sBox.clearBtnEl.hasAttribute('hidden'), true);
// 4. Declarative settingsBackup round-trips all 30 portable keys + coupled legacy flags
// 4. Declarative settingsBackup round-trips all 31 portable keys + coupled legacy flags
const exported = buildExportableSettingsJson({
language: 'en-US',
modernUi: false,
@@ -2868,9 +2868,10 @@ test('P2 regressions: bundler regex-after-paren lexer, shared URI/prompt/atomic
windowMountMode: 'composer',
showStepFilterToolbar: true,
experimentalQuotaReservation: true,
accountQuotaRefreshMinutes: 180,
});
const parsedExport = JSON.parse(exported);
assert.equal(Object.keys(parsedExport.settings).length, 30);
assert.equal(Object.keys(parsedExport.settings).length, 31);
const reimported = parseImportedSettingsJson(exported);
assert.equal(reimported.ok, true);
assert.equal(reimported.patch.modernUi, false);
@@ -2883,4 +2884,5 @@ test('P2 regressions: bundler regex-after-paren lexer, shared URI/prompt/atomic
assert.equal(reimported.patch.enableWindowOverlay, true);
assert.equal(reimported.patch.showStepFilterToolbar, true);
assert.equal(reimported.patch.experimentalQuotaReservation, true);
assert.equal(reimported.patch.accountQuotaRefreshMinutes, 180);
});
+2 -2
View File
@@ -64,8 +64,8 @@ test('pack-release-zip ships only runtime-essential files, excludes dev bloat, a
assert.ok(existsSync(zipPath));
assert.ok(summary.zipBytes > 100 * 1024, 'ZIP should contain compiled assets and backend');
assert.ok(
summary.zipBytes < 750 * 1024,
`Runtime-only ZIP should stay compact (<750 KB), got ${(summary.zipBytes / 1024).toFixed(1)} KB`
summary.zipBytes < 900 * 1024,
`Runtime-only ZIP should stay compact (<900 KB), got ${(summary.zipBytes / 1024).toFixed(1)} KB`
);
// Extract via OS-native expander (same path used by plugin-updater.mjs, where extractDir already exists)
+57 -8
View File
@@ -720,6 +720,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
const mockSettings = { ...defaultMockSettings };
let cacheRebuildCalls = 0;
let selectedEmail = '';
let browserAccountAdded = false;
let browserLoginStarts = 0;
const accountRequests = [];
const mockWindow = {
@@ -752,12 +754,23 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
if (opts.method === 'POST') {
const update = JSON.parse(opts.body);
accountRequests.push(update);
if (update.action === 'loginStart') {
browserLoginStarts += 1;
if (browserLoginStarts > 1) {
browserAccountAdded = true;
return { ok: true, status: 200, json: async () => ({ supported: true, login: { id: 'browser-login', status: 'success', email: 'browser@example.com' } }) };
}
return { ok: true, status: 200, json: async () => ({ supported: true, login: { id: 'browser-login', status: 'waiting', url: 'https://accounts.google.com/o/oauth2/v2/auth?state=synthetic', opened: true } }) };
}
if (update.action === 'loginCancel') {
return { ok: true, status: 200, json: async () => ({ supported: true, login: { id: update.id, status: 'cancelled' } }) };
}
if (update.action === 'quota') {
return { ok: true, status: 200, json: async () => ({ email: update.email, pools: [{ poolKey: 'Gemini', remainingPct: 70 }] }) };
}
if (update.action === 'switch') selectedEmail = update.email;
}
return { ok: true, status: 200, json: async () => ({ supported: true, accounts: ['next@example.com'], selectedEmail }) };
return { ok: true, status: 200, json: async () => ({ supported: true, accounts: browserAccountAdded ? ['next@example.com', 'browser@example.com'] : ['next@example.com'], selectedEmail, restarting: opts.method === 'POST' && JSON.parse(opts.body).action === 'switch' }) };
}
if (urlStr.includes('/api/settings/reset') && String(opts.method || '').toUpperCase() === 'POST') {
for (const k of Object.keys(mockSettings)) delete mockSettings[k];
@@ -1437,7 +1450,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(selectRoot.classList.contains('is-open'), true, 'CustomSelect stays open via composedPath');
selectTrigger.dispatchEvent({ type: 'click', stopPropagation() {} });
// Verify modular 3-tab SettingsView (常规 / 结构 / 其他) with Account tab hidden
// Verify account preferences are reachable between Structure and Other.
const pillTabs = popoverEl.querySelectorAll('.pill-tab');
pillTabs[pillTabs.length - 1].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15));
@@ -1445,13 +1458,13 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
const allPanes = popoverEl.querySelectorAll('.view-pane');
const settingsRoot = popoverEl.querySelector('.settings-view-root');
const subNavBtns = settingsRoot.querySelector('.settings-subnav-bar').querySelectorAll('.seg-btn');
assert.deepEqual(subNavBtns.map((button) => button.textContent), ['常规', '结构', '其他']);
assert.deepEqual(subNavBtns.map((button) => button.textContent), ['常规', '结构', '账号', '其他']);
assert.match(
stylesCss,
/\.settings-subnav-bar\s+\.segmented\s*\{[^}]*grid-auto-flow:\s*column;[^}]*grid-auto-columns:\s*minmax\(0,\s*1fr\);/,
'Settings subnav uses auto-sized equal columns regardless of visible tab count'
);
const [generalPane, structurePane, otherPane] = settingsRoot.querySelectorAll('.settings-tab-stack');
const [generalPane, structurePane, accountPane, otherPane] = settingsRoot.querySelectorAll('.settings-tab-stack');
const thirdNavBar = settingsRoot.querySelector('.settings-thirdnav-bar');
assert.ok(thirdNavBar, '3rd-level structure menu bar mounted in SettingsView');
assert.equal(thirdNavBar.hasAttribute('hidden'), true, '3rd-level menu hidden when General tab is active');
@@ -1538,7 +1551,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(pillTabs[3].querySelector('.pill-tab-label').textContent, 'Settings');
assert.equal(subNavBtns[0].textContent, 'General');
assert.equal(subNavBtns[1].textContent, 'Structure');
assert.equal(subNavBtns[2].textContent, 'Other');
assert.equal(subNavBtns[2].textContent, 'Account');
assert.equal(subNavBtns[3].textContent, 'Other');
langBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.language, 'auto');
@@ -2044,8 +2058,43 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
'Section reset restores monochrome speed classes in preview step table'
);
// --- 其他 (model format, context limits, cache rebuild, reset) ---
subNavBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 35));
assert.equal(accountPane.hasAttribute('hidden'), false);
assert.equal(accountPane.querySelector('.settings-account-identity').textContent, 'test@example.com');
assert.ok(accountPane.querySelectorAll('.settings-account-quota').some((el) => el.textContent === '5 小时 70%'));
assert.ok(accountRequests.some((item) => item.action === 'quota' && item.email === 'next@example.com'));
const googleLogin = accountPane.querySelector('.settings-account-login');
assert.equal(googleLogin.textContent, '使用 Google 登录');
googleLogin.dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 20));
assert.ok(accountRequests.some((item) => item.action === 'loginStart' && item.language === 'zh-CN'));
assert.ok(accountPane.querySelectorAll('.settings-action-desc').some((el) => el.textContent.includes('请在浏览器中选择 Google 账号')));
assert.equal(accountPane.querySelector('.settings-account-login-cancel').hasAttribute('hidden'), false);
assert.equal(accountPane.querySelector('a').getAttribute('href'), 'https://accounts.google.com/o/oauth2/v2/auth?state=synthetic');
accountPane.querySelector('.settings-account-login-cancel').dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 20));
assert.ok(accountRequests.some((item) => item.action === 'loginCancel' && item.id === 'browser-login'));
assert.equal(accountPane.querySelector('.settings-account-login-cancel').hasAttribute('hidden'), true);
assert.equal(googleLogin.hasAttribute('disabled'), false);
googleLogin.dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 20));
assert.ok(accountPane.querySelectorAll('.settings-account-identity').some((el) => el.textContent === 'browser@example.com'));
assert.ok(accountRequests.some((item) => item.action === 'quota' && item.email === 'browser@example.com'));
assert.ok(accountPane.querySelectorAll('.settings-action-desc').some((el) => el.textContent === '登录成功,账号已添加。'));
const switchButton = accountPane.querySelector('.settings-account-switch');
assert.equal(switchButton.textContent, '切换并重启');
switchButton.dispatchEvent({ type: 'click', stopPropagation() {} });
assert.equal(switchButton.textContent, '确认切换');
assert.equal(accountRequests.some((item) => item.action === 'switch'), false);
switchButton.dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 20));
assert.ok(accountRequests.some((item) => item.action === 'switch' && item.email === 'next@example.com'));
assert.equal(accountPane.querySelector('.settings-account-identity').textContent, 'test@example.com');
assert.ok(accountPane.querySelectorAll('.settings-action-desc').some((el) => el.textContent.includes('正在重启 Antigravity')));
// --- 其他 (model format, context limits, cache rebuild, reset) ---
subNavBtns[3].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15));
assert.equal(otherPane.hasAttribute('hidden'), false);
assert.equal(thirdNavBar.hasAttribute('hidden'), true, '3rd-level menu hidden when switching to Other tab');
@@ -2752,8 +2801,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
'Hover legend updates strictly in-place without DOM node replacement or appendChild'
);
assert.equal(createdForms.some((form) => form.className.includes('settings-account-form')), false);
assert.equal(fetchedUrls.some((url) => url.includes('/api/accounts')), false);
assert.equal(createdForms.some((form) => form.className.includes('settings-account-form')), true);
assert.equal(fetchedUrls.some((url) => url.includes('/api/accounts')), true);
// Verify in-place bridge port rotation preserves exact DOM host nodes without remount
fetchShouldFail = false;