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
+131
View File
@@ -0,0 +1,131 @@
import assert from 'node:assert/strict';
import { setTimeout as delay } from 'node:timers/promises';
import test from 'node:test';
import { createAccountLoginController } from '../backend/account-login.mjs';
import { exchangeGoogleAccountCode } from '../backend/account-oauth.mjs';
const TEST_OAUTH_CLIENTS = async () => [
{
id: '1234567890-synthetic-test.apps.googleusercontent.com',
secret: 'synthetic-test-secret',
},
];
function callbackUrl(session, values) {
const authorization = new URL(session.url);
const callback = new URL(authorization.searchParams.get('redirect_uri'));
callback.search = new URLSearchParams({ state: authorization.searchParams.get('state'), ...values }).toString();
return callback;
}
test('browser login accepts its loopback callback once and saves the verified account before reporting success', async () => {
const saved = [];
let opened;
let exchanges = 0;
const controller = createAccountLoginController({
getClients: TEST_OAUTH_CLIENTS,
openBrowser: async (url) => { opened = url; return true; },
exchangeCode: async (code, redirectUri, verifier) => {
exchanges += 1;
assert.equal(code, 'synthetic-code');
assert.match(redirectUri, /^http:\/\/127\.0\.0\.1:\d+\/oauth-callback$/);
assert.match(verifier, /^[\w-]{43,128}$/);
return { email: 'verified@example.com', credential: { token: { refresh_token: 'synthetic-private' } } };
},
});
const session = await controller.start(async (account) => { saved.push(account.email); });
try {
assert.equal(session.opened, true);
const authorization = new URL(opened);
assert.equal(authorization.origin, 'https://accounts.google.com');
assert.equal(authorization.searchParams.get('access_type'), 'offline');
assert.equal(authorization.searchParams.get('code_challenge_method'), 'S256');
assert.match(authorization.searchParams.get('prompt'), /select_account/);
const invalid = await fetch(callbackUrl(session, { state: 'unrelated', code: 'bad-code' }));
assert.equal(invalid.status, 400);
assert.equal(controller.getStatus(session.id).status, 'waiting');
assert.equal(exchanges, 0);
const response = await fetch(callbackUrl(session, { code: 'synthetic-code' }));
const page = await response.text();
assert.equal(response.status, 200);
assert.match(page, /账号已添加/);
assert.equal(page.includes('synthetic-code'), false);
assert.equal(page.includes('synthetic-private'), false);
assert.deepEqual(saved, ['verified@example.com']);
assert.deepEqual(controller.getStatus(session.id), { id: session.id, status: 'success', error: '', email: 'verified@example.com' });
assert.equal(exchanges, 1);
} finally {
controller.cancel(session.id);
}
});
test('login offers a usable browser link when opening fails, and cancellation closes the listener', async () => {
const controller = createAccountLoginController({
getClients: TEST_OAUTH_CLIENTS,
openBrowser: async () => false,
});
const session = await controller.start(async () => { assert.fail('cancelled login must not save credentials'); });
assert.equal(session.opened, false);
assert.match(session.url, /^https:\/\/accounts\.google\.com\//);
assert.equal((await controller.start(async () => {})).id, session.id);
assert.equal(controller.cancel(session.id).status, 'cancelled');
await delay(10);
await assert.rejects(fetch(callbackUrl(session, { code: 'unused' })));
});
test('denied authorization and expired sessions never save an account', async () => {
const controller = createAccountLoginController({
getClients: TEST_OAUTH_CLIENTS,
openBrowser: async () => true,
timeoutMs: 50,
});
const denied = await controller.start(async () => { assert.fail('denied authorization'); }, 'en-US');
const response = await fetch(callbackUrl(denied, { error: 'access_denied' }));
assert.equal(response.status, 200);
assert.match(await response.text(), /Sign-in incomplete/);
assert.equal(controller.getStatus(denied.id).status, 'cancelled');
const expired = await controller.start(async () => { assert.fail('expired authorization'); });
await delay(100);
assert.equal(controller.getStatus(expired.id).status, 'expired');
await assert.rejects(fetch(callbackUrl(expired, { code: 'late' })));
});
test('cancelled code exchange cannot add an account after the next login starts', async () => {
let release;
let exchangeStarted;
const started = new Promise((resolve) => { exchangeStarted = resolve; });
const credential = new Promise((resolve) => { release = resolve; });
const controller = createAccountLoginController({
getClients: TEST_OAUTH_CLIENTS,
openBrowser: async () => true,
exchangeCode: async () => { exchangeStarted(); return credential; },
});
const original = await controller.start(async () => { assert.fail('old login was cancelled'); });
const request = fetch(callbackUrl(original, { code: 'pending' }));
await started;
controller.cancel(original.id);
const replacement = await controller.start(async () => {});
release({ email: 'old@example.com', credential: {} });
assert.equal((await request).status, 409);
assert.equal(controller.getStatus(replacement.id).status, 'waiting');
controller.cancel(replacement.id);
});
test('authorization code exchange sends the callback and verifier, then identifies the Google account', async () => {
const verified = await exchangeGoogleAccountCode('synthetic-code', 'http://127.0.0.1:12345/oauth-callback', 'synthetic-verifier', {
getClients: TEST_OAUTH_CLIENTS,
fetchFn: async (url, request) => {
if (url.endsWith('/token')) {
assert.equal(request.body.get('grant_type'), 'authorization_code');
assert.equal(request.body.get('code'), 'synthetic-code');
assert.equal(request.body.get('code_verifier'), 'synthetic-verifier');
assert.equal(request.body.get('redirect_uri'), 'http://127.0.0.1:12345/oauth-callback');
return { ok: true, json: async () => ({ access_token: 'test-access', refresh_token: 'test-refresh', expires_in: 3600 }) };
}
assert.equal(request.headers.Authorization, 'Bearer test-access');
return { ok: true, json: async () => ({ email: 'verified@example.com', verified_email: true }) };
},
});
assert.equal(verified.email, 'verified@example.com');
assert.equal(verified.credential.token.refresh_token, 'test-refresh');
});
+483 -14
View File
@@ -3,8 +3,28 @@ import { mkdtemp, readFile, rmdir, unlink } from 'node:fs/promises';
import { join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { resolveGoogleCredential, retrieveCredentialQuota } from '../backend/account-oauth.mjs';
import { handleAccountCredentialAction, normalizeAccountCredential, runWindowsCredentialStore } from '../backend/account-switch.mjs';
import { createAccountLoginController } from '../backend/account-login.mjs';
import {
buildGoogleAccountLoginUrl,
collectNativeOAuthBinaryCandidates,
extractNativeOAuthClients,
resolveGoogleCredential,
retrieveCredentialQuota,
} from '../backend/account-oauth.mjs';
import {
clearAccountVaultRuntimeState,
handleAccountCredentialAction,
normalizeAccountCredential,
runWindowsCredentialStore,
serializeVaultCredential,
} from '../backend/account-switch.mjs';
import {
decryptVaultEntryCredential,
issueAccountActionNonce,
resetVaultUnlockFailures,
verifyAccountActionNonce,
} from '../backend/account-vault-crypto.mjs';
import { executeAccountCredentialAction } from '../backend/api-actions.mjs';
test('accepts a shared OAuth credential or refresh token, and rejects other credential types', () => {
const refreshToken = '1//synthetic-refresh-token-for-test';
@@ -42,17 +62,17 @@ test('import uses the verified email and switches only after checking the creden
if (request.action === 'read') return { credential: saved };
assert.equal(request.target, 'gemini:antigravity');
assert.equal(request.email, 'next@example.com');
if (request.action === 'switch') assert.equal(request.expectedCredential, saved);
return { accounts: ['next@example.com'], selectedEmail: request.email, credential: saved };
if (request.action === 'scheduleSwitch') assert.equal(request.expectedCredential, saved);
return { accounts: ['next@example.com'], selectedEmail: request.email, credential: saved, scheduled: request.action === 'scheduleSwitch' };
},
};
assert.deepEqual(await handleAccountCredentialAction({ action: 'save', email: 'ignored@example.com', credential: input }, options), {
supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com',
supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', quotas: {},
});
assert.deepEqual(calls.splice(0), ['refresh-identity', 'save']);
const result = await handleAccountCredentialAction({ action: 'switch', email: 'NEXT@example.com' }, options);
assert.deepEqual(result, { supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', confirmed: true });
assert.deepEqual(calls.splice(0), ['read', 'verify-identity', 'switch', 'GetAuthStatus', 'GetUserStatus']);
assert.deepEqual(result, { supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', quotas: {}, restarting: true });
assert.deepEqual(calls.splice(0), ['read', 'verify-identity', 'scheduleSwitch']);
verifiedEmail = 'different@example.com';
assert.deepEqual(await handleAccountCredentialAction({ action: 'switch', email: 'next@example.com' }, options), { error: 'identityMismatch' });
assert.deepEqual(calls, ['read', 'verify-identity']);
@@ -64,7 +84,7 @@ test('a saved credential can query its quota without replacing the active login'
const result = await handleAccountCredentialAction({ action: 'quota', email: 'next@example.com' }, {
platform: 'win32',
store: async (request) => {
assert.equal(request.action, 'read');
assert.ok(['read', 'saveQuota'].includes(request.action));
return { credential };
},
resolveCredential: async (stored) => ({ email: 'next@example.com', credential: stored }),
@@ -73,7 +93,8 @@ test('a saved credential can query its quota without replacing the active login'
return pools;
},
});
assert.deepEqual(result, { email: 'next@example.com', pools });
assert.deepEqual({ email: result.email, pools: result.pools }, { email: 'next@example.com', pools });
assert.ok(result.fetchedAt > 0);
});
test('Google OAuth confirms the email and the same account token retrieves quota pools', async () => {
@@ -89,6 +110,7 @@ test('Google OAuth confirms the email and the same account token retrieves quota
}
assert.equal(request.headers.Authorization, 'Bearer new-access');
if (url.endsWith('/userinfo')) return { ok: true, json: async () => ({ email: 'owner@example.com', verified_email: true }) };
assert.match(request.headers['User-Agent'], /^antigravity\/hub\//);
if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ cloudaicompanionProject: { id: 'test-project' } }) };
assert.equal(JSON.parse(request.body).project, 'test-project');
if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) };
@@ -107,22 +129,469 @@ test('Google OAuth confirms the email and the same account token retrieves quota
assert.equal(endpoints.length, 5);
});
test('quota queries keep the native header and omit project when Google did not return one', async () => {
const requests = [];
const pools = await retrieveCredentialQuota('native-access', async (url, request) => {
const body = JSON.parse(request.body);
requests.push({ url, body });
assert.match(request.headers['User-Agent'], /^antigravity\/hub\//);
if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ allowedTiers: [] }) };
assert.deepEqual(body, {});
if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) };
return { ok: true, json: async () => ({ groups: [{ displayName: 'Gemini Models', buckets: [{ window: 'weekly', remainingFraction: 0.42 }] }] }) };
});
assert.equal(pools[0].weeklyRemainingPct, 42);
assert.equal(requests.length, 3);
});
test('a forbidden project is retried without that project before another endpoint', async () => {
let retried = 0;
const pools = await retrieveCredentialQuota('native-access', async (url, request) => {
const body = JSON.parse(request.body);
if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ cloudaicompanionProject: 'stale-project' }) };
if (body.project) return { ok: false, status: 403 };
retried += 1;
if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) };
return { ok: true, json: async () => ({ groups: [{ displayName: 'Claude and GPT models', buckets: [{ window: '5h', remainingFraction: 0 }] }] }) };
});
assert.equal(retried, 2);
assert.equal(pools[0].remainingPct, 0);
});
test('Windows vault atomically saves, reloads and removes encrypted entries', { skip: process.platform !== 'win32' }, async () => {
const directory = await mkdtemp(fileURLToPath(new URL('../.account-test-', import.meta.url)));
const vault = join(directory, 'test.dpapi');
const run = (action, email, credential) => runWindowsCredentialStore({ action, email, credential, vault });
try {
const credential = normalizeAccountCredential('1//synthetic-refresh-token-for-test');
assert.deepEqual(await run('list'), { accounts: [], selectedEmail: '' });
assert.deepEqual(await run('save', 'active@example.com', credential), { accounts: ['active@example.com'], selectedEmail: '' });
assert.deepEqual(await run('save', 'next@example.com', credential), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' });
assert.deepEqual(await run('list'), { accounts: [], selectedEmail: '', quotas: {} });
assert.deepEqual(await run('save', 'active@example.com', credential), { accounts: ['active@example.com'], selectedEmail: '', quotas: {} });
assert.deepEqual(await run('save', 'next@example.com', credential), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '', quotas: {} });
assert.deepEqual(await run('read', 'next@example.com'), { credential });
assert.deepEqual(await runWindowsCredentialStore({ action: 'save', email: 'next@example.com', credential, expectedCredential: 'stale', vault }), { error: 'credentialChanged' });
assert.equal((await readFile(vault)).includes('synthetic-refresh-token-for-test'), false);
assert.deepEqual(await run('list'), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' });
assert.deepEqual(await run('remove', 'next@example.com'), { accounts: ['active@example.com'], selectedEmail: '' });
assert.deepEqual(await run('list'), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '', quotas: {} });
const quota = { fetchedAt: 100, pools: [{ poolKey: 'Gemini', remainingPct: 0, weeklyRemainingPct: 70 }] };
await runWindowsCredentialStore({ action: 'saveQuota', email: 'active@example.com', expectedCredential: credential, quota, vault });
assert.deepEqual((await run('list')).quotas, { 'active@example.com': quota });
assert.deepEqual(await run('remove', 'next@example.com'), { accounts: ['active@example.com'], selectedEmail: '', quotas: { 'active@example.com': quota } });
} finally {
await unlink(vault).catch((err) => { if (err.code !== 'ENOENT') throw err; });
await rmdir(directory);
}
});
test('browser authorization adds a credential through the normal account actions and encrypted vault', { skip: process.platform !== 'win32' }, async () => {
const directory = await mkdtemp(fileURLToPath(new URL('../.account-login-test-', import.meta.url)));
const vault = join(directory, 'test.dpapi');
const credential = JSON.parse(normalizeAccountCredential('1//synthetic-browser-authorized-credential'));
const login = createAccountLoginController({
getClients: async () => [
{ id: '1234567890-synthetic-test.apps.googleusercontent.com', secret: 'synthetic-test-secret' },
],
openBrowser: async () => true,
exchangeCode: async () => ({ email: 'browser@example.com', credential }),
});
const options = { platform: 'win32', login, store: (request) => runWindowsCredentialStore({ ...request, vault, statusFile: '' }) };
let id;
try {
const result = await handleAccountCredentialAction({ action: 'loginStart', language: 'zh-CN' }, options);
assert.equal(result.supported, true);
assert.equal(result.login.status, 'waiting');
id = result.login.id;
const authorization = new URL(result.login.url);
const callback = new URL(authorization.searchParams.get('redirect_uri'));
callback.search = new URLSearchParams({ state: authorization.searchParams.get('state'), code: 'synthetic-code' }).toString();
assert.equal((await fetch(callback)).status, 200);
assert.equal((await handleAccountCredentialAction({ action: 'loginStatus', id }, options)).login.status, 'success');
const accounts = await handleAccountCredentialAction({ action: 'list' }, options);
assert.deepEqual(accounts.accounts, ['browser@example.com']);
assert.equal(accounts.selectedEmail, '');
assert.equal(JSON.stringify(accounts).includes('synthetic-browser-authorized-credential'), false);
assert.equal((await readFile(vault)).includes('synthetic-browser-authorized-credential'), false);
} finally {
if (id) login.cancel(id);
await unlink(vault).catch((error) => { if (error.code !== 'ENOENT') throw error; });
await rmdir(directory);
}
});
test('login scope includes auth/aicode, switch auto-backs-up unsaved active login with 2.34 signout guard, and quota extracts tierName', async () => {
const loginUrl = new URL(
await buildGoogleAccountLoginUrl('http://127.0.0.1:9999/oauth-callback', 'st', 'ch', {
getClients: async () => [
{ id: '1234567890-synthetic-test.apps.googleusercontent.com', secret: 'synthetic-test-secret' },
],
})
);
const scopes = (loginUrl.searchParams.get('scope') || '').split(/\s+/);
assert.ok(scopes.includes('https://www.googleapis.com/auth/aicode'));
const savedEntries = new Map([
['target@example.com', normalizeAccountCredential('1//target-refresh-token-value-1234567890')],
]);
const liveCurrent = normalizeAccountCredential('1//active-host-refresh-token-value-1234567890');
let scheduledPayload = null;
const res = await handleAccountCredentialAction(
{ action: 'switch', email: 'target@example.com', activeEmail: 'current@example.com' },
{
platform: 'win32',
resolveCredential: async (cred) => ({
email: cred.token.refresh_token.includes('active-host')
? 'current@example.com'
: 'target@example.com',
credential: cred,
}),
store: async (req) => {
if (req.action === 'read') {
const hit = savedEntries.get(req.email);
return hit ? { credential: hit } : { error: 'notFound' };
}
if (req.action === 'readCurrent') {
return { credential: liveCurrent };
}
if (req.action === 'save') {
savedEntries.set(req.email, req.credential);
return { accounts: [...savedEntries.keys()], selectedEmail: '' };
}
if (req.action === 'scheduleSwitch') {
scheduledPayload = JSON.parse(req.credential);
return {
scheduled: true,
accounts: [...savedEntries.keys()],
selectedEmail: req.email,
};
}
return { error: 'storeFailed' };
},
}
);
assert.equal(res.restarting, true);
assert.ok(savedEntries.has('current@example.com'), 'Active host account must be auto-backed-up before switching away');
assert.ok(
Number.isSafeInteger(scheduledPayload?.aicode_scope_sign_out_attempted_at) &&
scheduledPayload.aicode_scope_sign_out_attempted_at > 0,
'Switched host credential must include 2.34 aicode_scope_sign_out_attempted_at guard'
);
const pools = await retrieveCredentialQuota('tok', async (url) => {
if (url.endsWith(':loadCodeAssist')) {
return {
ok: true,
json: async () => ({
paidTier: { id: 'g1-ultra-tier', name: 'Google AI Ultra' },
cloudaicompanionProject: 'p1',
}),
};
}
if (url.endsWith(':fetchAvailableModels')) {
return { ok: true, json: async () => ({ models: {} }) };
}
return {
ok: true,
json: async () => ({
groups: [{ displayName: 'Gemini Models', buckets: [{ window: 'weekly', remainingFraction: 0.85 }] }],
}),
};
});
assert.equal(pools.tierName, 'Google AI Ultra');
assert.equal(pools.tierInfo.tierMultiplier, '20x');
assert.equal(pools[0].weeklyRemainingPct, 85);
const litePools = await retrieveCredentialQuota('tok-5x', async (url) => {
if (url.endsWith(':loadCodeAssist')) {
return {
ok: true,
json: async () => ({
paidTier: { id: 'g1-ultra-lite-tier', name: 'Google AI Ultra' },
cloudaicompanionProject: 'p2',
}),
};
}
if (url.endsWith(':fetchAvailableModels')) {
return { ok: true, json: async () => ({ models: {} }) };
}
return {
ok: true,
json: async () => ({
groups: [{ displayName: 'Gemini Models', buckets: [{ window: 'weekly', remainingFraction: 0.91 }] }],
}),
};
});
assert.deepEqual(litePools.tierInfo, {
tierId: 'g1-ultra-lite-tier',
tierName: 'Google AI Ultra',
tierMultiplier: '5x',
});
});
test('enforces OAuth client_id allowlist, minimizes at-rest vault payload, and validates actionNonce on mutations', async () => {
const rt = '1//synthetic-refresh-token-for-allowlist-check';
assert.equal(
normalizeAccountCredential(
JSON.stringify({ client_id: 'evil-third-party.apps.googleusercontent.com', refresh_token: rt })
),
null,
'Must reject unknown third-party OAuth client_id'
);
assert.equal(
normalizeAccountCredential(
JSON.stringify({ type: 'service_account', refresh_token: rt })
),
null,
'Must reject non-user OAuth credential types'
);
const syntheticOfficialId = '1234567890-synthetic-test.apps.googleusercontent.com';
const validWithOfficialClient = normalizeAccountCredential(
JSON.stringify({
client_id: syntheticOfficialId,
client_secret: 'should-be-stripped',
access_token: 'ephemeral-access-token',
id_token: 'ephemeral-id-token',
refresh_token: rt,
}),
{ allowedClientIds: [syntheticOfficialId] }
);
assert.ok(validWithOfficialClient, 'Allowlisted Antigravity OAuth client_id must be accepted');
assert.equal(validWithOfficialClient.includes('should-be-stripped'), false);
// Verify PE .text/.rdata native OAuth client extraction & multi-path candidate discovery
const fakeId = '9876543210-unit-test-client.apps.googleusercontent.com';
const fakeSecret = 'GOCSPX-unit-test';
const peBuf = Buffer.alloc(1024);
peBuf.writeUInt16LE(0x5a4d, 0);
peBuf.writeUInt32LE(0x80, 60);
peBuf.writeUInt32LE(0x4550, 0x80);
peBuf.writeUInt16LE(0x8664, 0x84);
peBuf.writeUInt16LE(2, 0x86);
peBuf.writeUInt16LE(0, 0x94);
const secTable = 0x80 + 24;
peBuf.write('.text', secTable, 'ascii');
peBuf.writeUInt32LE(0x1000, secTable + 12);
peBuf.writeUInt32LE(0x100, secTable + 16);
peBuf.writeUInt32LE(0x200, secTable + 20);
peBuf.write('.rdata', secTable + 40, 'ascii');
peBuf.writeUInt32LE(0x2000, secTable + 52);
peBuf.writeUInt32LE(0x100, secTable + 56);
peBuf.writeUInt32LE(0x300, secTable + 60);
peBuf.write(fakeId + fakeSecret + 'trailing-go-str', 0x300, 'ascii');
const codeStart = 0x200;
Buffer.from([0x48, 0xc7, 0x40, 0x08]).copy(peBuf, codeStart);
peBuf.writeUInt32LE(fakeId.length, codeStart + 4);
Buffer.from([0x48, 0x8d, 0x0d]).copy(peBuf, codeStart + 8);
peBuf.writeInt32LE(0x2000 - (0x1000 + 11 + 4), codeStart + 11);
Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]).copy(peBuf, codeStart + 15);
peBuf.writeUInt32LE(fakeSecret.length, codeStart + 22);
Buffer.from([0x48, 0x8d, 0x0d]).copy(peBuf, codeStart + 26);
peBuf.writeInt32LE(0x2000 + fakeId.length - (0x1000 + 29 + 4), codeStart + 29);
assert.deepEqual(extractNativeOAuthClients(peBuf), [{ id: fakeId, secret: fakeSecret }]);
const discoveredCands = collectNativeOAuthBinaryCandidates({
env: {
USAGE_MONITOR_HOST_EXE: 'D:\\Custom\\Antigravity\\Antigravity.exe',
ANTIGRAVITY_GEMINI_DIR: 'D:\\CustomGemini',
},
homeDir: 'C:\\Users\\Test',
existsFn: null,
});
assert.ok(discoveredCands.some((p) => /D:\\Custom\\Antigravity\\resources\\bin\\language_server\.exe$/i.test(p)));
assert.ok(discoveredCands.some((p) => /D:\\CustomGemini\\bin\\agy\.exe$/i.test(p)));
const minStored = serializeVaultCredential(JSON.parse(validWithOfficialClient));
assert.equal(minStored.includes('ephemeral-access-token'), false);
assert.equal(minStored.includes('ephemeral-id-token'), false);
assert.deepEqual(JSON.parse(minStored), {
token: { refresh_token: rt, token_type: 'Bearer' },
auth_method: 'consumer',
});
const nonce = issueAccountActionNonce(1_700_000_000_000);
assert.equal(verifyAccountActionNonce(nonce, 1_700_000_000_000), true);
assert.equal(verifyAccountActionNonce(`${nonce}x`, 1_700_000_000_000), false);
assert.equal(verifyAccountActionNonce(nonce, 1_700_000_000_000 + 45 * 60_000), false);
const missingNonceRes = await executeAccountCredentialAction({
action: 'remove',
email: 'a@example.com',
});
const missingBody = JSON.parse(missingNonceRes.body);
assert.equal(missingBody.error, 'invalidActionNonce');
assert.equal(typeof missingBody.actionNonce, 'string');
});
test('secondary passphrase encrypts credentials with scrypt + AES-256-GCM, preserves cached list while locked, throttles brute force, and rotates/resets cleanly', { skip: process.platform !== 'win32' }, async (t) => {
const directory = await mkdtemp(fileURLToPath(new URL('../.account-sec-test-', import.meta.url)));
const vault = join(directory, 'sec-test.dpapi');
t.after(async () => {
clearAccountVaultRuntimeState();
await unlink(vault).catch((err) => {
if (err.code !== 'ENOENT') throw err;
});
await rmdir(directory);
});
clearAccountVaultRuntimeState();
const options = {
platform: 'win32',
resolveCredential: async (cred) => {
const rt = cred.token.refresh_token;
const email = rt.includes('alpha') ? 'alpha@example.com' : 'beta@example.com';
return {
email,
credential: {
token: {
access_token: `live-access-for-${email}`,
refresh_token: rt,
token_type: 'Bearer',
expiry: new Date(Date.now() + 3600_000).toISOString(),
},
auth_method: 'consumer',
id_token: 'live-jwt-id-token',
},
};
},
getQuota: async () => [{ poolKey: 'Gemini', remainingPct: 88, weeklyRemainingPct: 92 }],
store: (req) => {
if (req.action === 'scheduleSwitch') {
// Verify host receives live access_token while vault receives encrypted agv1: ciphertext
assert.equal(req.credential.includes('live-access-for-'), true);
assert.equal(String(req.vaultCredential || '').startsWith('agv1:'), true);
return Promise.resolve({
scheduled: true,
accounts: ['alpha@example.com', 'beta@example.com'],
selectedEmail: req.email,
security: { enabled: true, salt: req.expectedSecuritySalt },
});
}
return runWindowsCredentialStore({ ...req, vault, statusFile: '' });
},
};
await handleAccountCredentialAction(
{ action: 'save', credential: '1//alpha-refresh-token-1234567890123456' },
options
);
await handleAccountCredentialAction(
{ action: 'save', credential: '1//beta-refresh-token-1234567890123456' },
options
);
await handleAccountCredentialAction({ action: 'quota', email: 'alpha@example.com' }, options);
// Set secondary passphrase -> encrypts all saved entries inside DPAPI vault
const setRes = await handleAccountCredentialAction(
{ action: 'setPassword', newPassword: 'correct-horse-battery' },
options
);
assert.deepEqual(setRes.security, { enabled: true, unlocked: true });
const rawVaultAfterSet = await runWindowsCredentialStore({ action: 'readVault', vault });
assert.equal(rawVaultAfterSet.entries.length, 2);
for (const entry of rawVaultAfterSet.entries) {
assert.equal(entry.credential.startsWith('agv1:'), true);
assert.equal(entry.credential.includes('refresh-token'), false);
assert.equal(entry.credential.includes('live-access'), false);
}
// AAD binds ciphertext to email: swapping ciphertext onto another email must fail decryption
assert.throws(
() =>
decryptVaultEntryCredential(
rawVaultAfterSet.entries[0].credential,
Buffer.alloc(32, 1),
'beta@example.com'
),
/vaultDecryptFailed/
);
// Lock session -> emails & cached quotas remain readable, all mutations/decryptions blocked
const lockedList = await handleAccountCredentialAction({ action: 'lockVault' }, options);
assert.deepEqual(lockedList.security, { enabled: true, unlocked: false });
assert.deepEqual(lockedList.accounts, ['alpha@example.com', 'beta@example.com']);
assert.equal(lockedList.quotas['alpha@example.com'].pools[0].remainingPct, 88);
for (const blockedAction of [
{ action: 'switch', email: 'alpha@example.com' },
{ action: 'remove', email: 'beta@example.com' },
{ action: 'quota', email: 'alpha@example.com' },
{ action: 'save', credential: '1//alpha-refresh-token-1234567890123456' },
{ action: 'loginStart', language: 'zh-CN' },
]) {
const blocked = await handleAccountCredentialAction(blockedAction, options);
assert.equal(blocked.error, 'vaultLocked', `Action ${blockedAction.action} must reject while locked`);
}
// Wrong passphrase -> wrongPassword, then rate-limited on 5th consecutive failure
for (let i = 0; i < 4; i++) {
const bad = await handleAccountCredentialAction(
{ action: 'unlockVault', password: `wrong-pass-${i}` },
options
);
assert.equal(bad.error, 'wrongPassword');
}
const throttled = await handleAccountCredentialAction(
{ action: 'unlockVault', password: 'wrong-pass-5' },
options
);
assert.equal(throttled.error, 'passwordRateLimited');
assert.ok(throttled.retryAfterSec >= 1);
resetVaultUnlockFailures();
const unlockedRes = await handleAccountCredentialAction(
{ action: 'unlockVault', password: 'correct-horse-battery' },
options
);
assert.deepEqual(unlockedRes.security, { enabled: true, unlocked: true });
// Switch while unlocked keeps vault entry encrypted
const switched = await handleAccountCredentialAction(
{ action: 'switch', email: 'alpha@example.com' },
options
);
assert.equal(switched.restarting, true);
// Change passphrase -> old password rejected, new password works
const changed = await handleAccountCredentialAction(
{
action: 'changePassword',
currentPassword: 'correct-horse-battery',
newPassword: 'new-passphrase-9876',
},
options
);
assert.deepEqual(changed.security, { enabled: true, unlocked: true });
await handleAccountCredentialAction({ action: 'lockVault' }, options);
assert.equal(
(await handleAccountCredentialAction({ action: 'unlockVault', password: 'correct-horse-battery' }, options)).error,
'wrongPassword'
);
assert.deepEqual(
(await handleAccountCredentialAction({ action: 'unlockVault', password: 'new-passphrase-9876' }, options)).security,
{ enabled: true, unlocked: true }
);
// Disable passphrase requires valid current password
assert.equal(
(await handleAccountCredentialAction({ action: 'disablePassword', currentPassword: 'wrong-current' }, options)).error,
'wrongPassword'
);
const disabled = await handleAccountCredentialAction(
{ action: 'disablePassword', currentPassword: 'new-passphrase-9876', includeSecurity: true },
options
);
assert.deepEqual(disabled.security, { enabled: false, unlocked: true });
const rawAfterDisable = await runWindowsCredentialStore({ action: 'readVault', vault });
assert.equal(rawAfterDisable.entries[0].credential.startsWith('agv1:'), false);
assert.equal(rawAfterDisable.entries[0].credential.includes('live-access'), false);
// Reset vault clears entries only when confirmReset === 'RESET'
assert.equal(
(await handleAccountCredentialAction({ action: 'resetVault' }, options)).error,
'invalidCredential'
);
const resetRes = await handleAccountCredentialAction(
{ action: 'resetVault', confirmReset: 'RESET' },
options
);
assert.deepEqual(resetRes.accounts, []);
});
+13 -2
View File
@@ -2,7 +2,16 @@ import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import vm from 'node:vm';
import { createHash, randomUUID } from 'node:crypto';
import {
createCipheriv,
createDecipheriv,
createHash,
createHmac,
randomBytes,
randomUUID,
scrypt,
timingSafeEqual,
} from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import * as metrics from '../trajectory-metrics.mjs';
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
@@ -25,6 +34,8 @@ const BACKEND_MODULE_FILES = [
'../backend/fs-atomic.mjs',
'../backend/context-windows.mjs',
'../backend/account-oauth.mjs',
'../backend/account-login.mjs',
'../backend/account-vault-crypto.mjs',
'../backend/account-switch.mjs',
'../backend/http-helpers.mjs',
'../backend/settings-schema.mjs',
@@ -106,7 +117,7 @@ export function backendHarness({
}
};
const ctx={
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, createHash, randomUUID,
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, scrypt, timingSafeEqual,
...(clock ? { Date: class extends Date {
constructor(...args) { super(...(args.length ? args : [clock()])); }
static now() { return clock(); }
@@ -1123,7 +1123,7 @@ test('P0 audit fixes: main/bridge-daemon import isolation, standalone lsAddr, du
assert.doesNotMatch(renderBody, /\buiStore\.setState\b/);
});
test('P1 audit fixes: shared third-party pool & route single-source, pure frozen resolveScopedConversation, mock schema alignment, and dead SettingsAccountTab exclusion', async () => {
test('P1 audit fixes: shared third-party pool & route single-source, pure frozen resolveScopedConversation, mock schema alignment, and account preferences inclusion', async () => {
const { normalizeI18nLanguage } = await import('../src/i18n/index.js');
const { resolveSpecificQuotaSlotSummary } = await import('../src/registries/metricRegistry.js');
const { resolveScopedConversation, isEquivalentTelemetry } = await import(
@@ -1188,7 +1188,7 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen
assert.equal(scoped.aggregated.recentSteps.length, 2);
assert.equal(scoped.mainAgent.recentSteps.length, 1);
// 3. structurePreviewMock schema completeness & dead SettingsAccountTab exclusion from app.js
// 3. structurePreviewMock schema completeness & account preferences bundled for use
const mock = buildStructurePreviewTelemetry();
assert.equal(typeof mock.activeConversation.context.compactionUsedTokens, 'number');
assert.equal(mock.activeConversation.aggregated.agentId, 'all');
@@ -1196,8 +1196,8 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen
assert.equal(mock.quotas.meta.hasOfficialData, true);
const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8');
assert.equal(appJs.includes('SettingsAccountTab.js'), false);
assert.equal(appJs.includes('function renderQuotaRows('), false);
assert.equal(appJs.includes('SettingsAccountTab.js'), true);
assert.equal(appJs.includes('function renderQuotaRows('), true);
});
test('P2 audit fixes: standalone sqlite/proto-wire primitives, structured liveActivity/agent/media i18n, full en-US SVG charts, controlled LiveActivityWidget reuse, and shared Mock DOM', async () => {
@@ -2859,7 +2859,7 @@ test('P2 regressions: bundler regex-after-paren lexer, shared URI/prompt/atomic
assert.equal(latestQuery, '');
assert.equal(sBox.clearBtnEl.hasAttribute('hidden'), true);
// 4. Declarative settingsBackup round-trips all 30 portable keys + coupled legacy flags
// 4. Declarative settingsBackup round-trips all 31 portable keys + coupled legacy flags
const exported = buildExportableSettingsJson({
language: 'en-US',
modernUi: false,
@@ -2868,9 +2868,10 @@ test('P2 regressions: bundler regex-after-paren lexer, shared URI/prompt/atomic
windowMountMode: 'composer',
showStepFilterToolbar: true,
experimentalQuotaReservation: true,
accountQuotaRefreshMinutes: 180,
});
const parsedExport = JSON.parse(exported);
assert.equal(Object.keys(parsedExport.settings).length, 30);
assert.equal(Object.keys(parsedExport.settings).length, 31);
const reimported = parseImportedSettingsJson(exported);
assert.equal(reimported.ok, true);
assert.equal(reimported.patch.modernUi, false);
@@ -2883,4 +2884,5 @@ test('P2 regressions: bundler regex-after-paren lexer, shared URI/prompt/atomic
assert.equal(reimported.patch.enableWindowOverlay, true);
assert.equal(reimported.patch.showStepFilterToolbar, true);
assert.equal(reimported.patch.experimentalQuotaReservation, true);
assert.equal(reimported.patch.accountQuotaRefreshMinutes, 180);
});
+2 -2
View File
@@ -64,8 +64,8 @@ test('pack-release-zip ships only runtime-essential files, excludes dev bloat, a
assert.ok(existsSync(zipPath));
assert.ok(summary.zipBytes > 100 * 1024, 'ZIP should contain compiled assets and backend');
assert.ok(
summary.zipBytes < 750 * 1024,
`Runtime-only ZIP should stay compact (<750 KB), got ${(summary.zipBytes / 1024).toFixed(1)} KB`
summary.zipBytes < 900 * 1024,
`Runtime-only ZIP should stay compact (<900 KB), got ${(summary.zipBytes / 1024).toFixed(1)} KB`
);
// Extract via OS-native expander (same path used by plugin-updater.mjs, where extractDir already exists)
+57 -8
View File
@@ -720,6 +720,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
const mockSettings = { ...defaultMockSettings };
let cacheRebuildCalls = 0;
let selectedEmail = '';
let browserAccountAdded = false;
let browserLoginStarts = 0;
const accountRequests = [];
const mockWindow = {
@@ -752,12 +754,23 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
if (opts.method === 'POST') {
const update = JSON.parse(opts.body);
accountRequests.push(update);
if (update.action === 'loginStart') {
browserLoginStarts += 1;
if (browserLoginStarts > 1) {
browserAccountAdded = true;
return { ok: true, status: 200, json: async () => ({ supported: true, login: { id: 'browser-login', status: 'success', email: 'browser@example.com' } }) };
}
return { ok: true, status: 200, json: async () => ({ supported: true, login: { id: 'browser-login', status: 'waiting', url: 'https://accounts.google.com/o/oauth2/v2/auth?state=synthetic', opened: true } }) };
}
if (update.action === 'loginCancel') {
return { ok: true, status: 200, json: async () => ({ supported: true, login: { id: update.id, status: 'cancelled' } }) };
}
if (update.action === 'quota') {
return { ok: true, status: 200, json: async () => ({ email: update.email, pools: [{ poolKey: 'Gemini', remainingPct: 70 }] }) };
}
if (update.action === 'switch') selectedEmail = update.email;
}
return { ok: true, status: 200, json: async () => ({ supported: true, accounts: ['next@example.com'], selectedEmail }) };
return { ok: true, status: 200, json: async () => ({ supported: true, accounts: browserAccountAdded ? ['next@example.com', 'browser@example.com'] : ['next@example.com'], selectedEmail, restarting: opts.method === 'POST' && JSON.parse(opts.body).action === 'switch' }) };
}
if (urlStr.includes('/api/settings/reset') && String(opts.method || '').toUpperCase() === 'POST') {
for (const k of Object.keys(mockSettings)) delete mockSettings[k];
@@ -1437,7 +1450,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(selectRoot.classList.contains('is-open'), true, 'CustomSelect stays open via composedPath');
selectTrigger.dispatchEvent({ type: 'click', stopPropagation() {} });
// Verify modular 3-tab SettingsView (常规 / 结构 / 其他) with Account tab hidden
// Verify account preferences are reachable between Structure and Other.
const pillTabs = popoverEl.querySelectorAll('.pill-tab');
pillTabs[pillTabs.length - 1].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15));
@@ -1445,13 +1458,13 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
const allPanes = popoverEl.querySelectorAll('.view-pane');
const settingsRoot = popoverEl.querySelector('.settings-view-root');
const subNavBtns = settingsRoot.querySelector('.settings-subnav-bar').querySelectorAll('.seg-btn');
assert.deepEqual(subNavBtns.map((button) => button.textContent), ['常规', '结构', '其他']);
assert.deepEqual(subNavBtns.map((button) => button.textContent), ['常规', '结构', '账号', '其他']);
assert.match(
stylesCss,
/\.settings-subnav-bar\s+\.segmented\s*\{[^}]*grid-auto-flow:\s*column;[^}]*grid-auto-columns:\s*minmax\(0,\s*1fr\);/,
'Settings subnav uses auto-sized equal columns regardless of visible tab count'
);
const [generalPane, structurePane, otherPane] = settingsRoot.querySelectorAll('.settings-tab-stack');
const [generalPane, structurePane, accountPane, otherPane] = settingsRoot.querySelectorAll('.settings-tab-stack');
const thirdNavBar = settingsRoot.querySelector('.settings-thirdnav-bar');
assert.ok(thirdNavBar, '3rd-level structure menu bar mounted in SettingsView');
assert.equal(thirdNavBar.hasAttribute('hidden'), true, '3rd-level menu hidden when General tab is active');
@@ -1538,7 +1551,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(pillTabs[3].querySelector('.pill-tab-label').textContent, 'Settings');
assert.equal(subNavBtns[0].textContent, 'General');
assert.equal(subNavBtns[1].textContent, 'Structure');
assert.equal(subNavBtns[2].textContent, 'Other');
assert.equal(subNavBtns[2].textContent, 'Account');
assert.equal(subNavBtns[3].textContent, 'Other');
langBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 30));
assert.equal(mockSettings.language, 'auto');
@@ -2044,8 +2058,43 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
'Section reset restores monochrome speed classes in preview step table'
);
// --- 其他 (model format, context limits, cache rebuild, reset) ---
subNavBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 35));
assert.equal(accountPane.hasAttribute('hidden'), false);
assert.equal(accountPane.querySelector('.settings-account-identity').textContent, 'test@example.com');
assert.ok(accountPane.querySelectorAll('.settings-account-quota').some((el) => el.textContent === '5 小时 70%'));
assert.ok(accountRequests.some((item) => item.action === 'quota' && item.email === 'next@example.com'));
const googleLogin = accountPane.querySelector('.settings-account-login');
assert.equal(googleLogin.textContent, '使用 Google 登录');
googleLogin.dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 20));
assert.ok(accountRequests.some((item) => item.action === 'loginStart' && item.language === 'zh-CN'));
assert.ok(accountPane.querySelectorAll('.settings-action-desc').some((el) => el.textContent.includes('请在浏览器中选择 Google 账号')));
assert.equal(accountPane.querySelector('.settings-account-login-cancel').hasAttribute('hidden'), false);
assert.equal(accountPane.querySelector('a').getAttribute('href'), 'https://accounts.google.com/o/oauth2/v2/auth?state=synthetic');
accountPane.querySelector('.settings-account-login-cancel').dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 20));
assert.ok(accountRequests.some((item) => item.action === 'loginCancel' && item.id === 'browser-login'));
assert.equal(accountPane.querySelector('.settings-account-login-cancel').hasAttribute('hidden'), true);
assert.equal(googleLogin.hasAttribute('disabled'), false);
googleLogin.dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 20));
assert.ok(accountPane.querySelectorAll('.settings-account-identity').some((el) => el.textContent === 'browser@example.com'));
assert.ok(accountRequests.some((item) => item.action === 'quota' && item.email === 'browser@example.com'));
assert.ok(accountPane.querySelectorAll('.settings-action-desc').some((el) => el.textContent === '登录成功,账号已添加。'));
const switchButton = accountPane.querySelector('.settings-account-switch');
assert.equal(switchButton.textContent, '切换并重启');
switchButton.dispatchEvent({ type: 'click', stopPropagation() {} });
assert.equal(switchButton.textContent, '确认切换');
assert.equal(accountRequests.some((item) => item.action === 'switch'), false);
switchButton.dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 20));
assert.ok(accountRequests.some((item) => item.action === 'switch' && item.email === 'next@example.com'));
assert.equal(accountPane.querySelector('.settings-account-identity').textContent, 'test@example.com');
assert.ok(accountPane.querySelectorAll('.settings-action-desc').some((el) => el.textContent.includes('正在重启 Antigravity')));
// --- 其他 (model format, context limits, cache rebuild, reset) ---
subNavBtns[3].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15));
assert.equal(otherPane.hasAttribute('hidden'), false);
assert.equal(thirdNavBar.hasAttribute('hidden'), true, '3rd-level menu hidden when switching to Other tab');
@@ -2752,8 +2801,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
'Hover legend updates strictly in-place without DOM node replacement or appendChild'
);
assert.equal(createdForms.some((form) => form.className.includes('settings-account-form')), false);
assert.equal(fetchedUrls.some((url) => url.includes('/api/accounts')), false);
assert.equal(createdForms.some((form) => form.className.includes('settings-account-form')), true);
assert.equal(fetchedUrls.some((url) => url.includes('/api/accounts')), true);
// Verify in-place bridge port rotation preserves exact DOM host nodes without remount
fetchShouldFail = false;