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
+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,