agy-bar 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +148 -54
- package/README.zh-CN.md +144 -50
- package/bin/agy-bar.mjs +603 -6
- package/llms.txt +47 -0
- package/package.json +3 -2
- package/skills/agy-bar/SKILL.md +11 -4
- package/src/account-import.mjs +435 -0
- package/src/account-quota.mjs +466 -0
- package/src/account-store.mjs +1140 -0
- package/src/agent-state.mjs +2 -1
- package/src/ansi.mjs +7 -0
- package/src/config.mjs +24 -0
- package/src/fs-atomic.mjs +16 -5
- package/src/handoff.mjs +424 -0
- package/src/installer.mjs +16 -0
- package/src/keyring.mjs +604 -0
- package/src/proxy.mjs +189 -48
- package/src/quota-sync.mjs +100 -20
- package/src/render.mjs +11 -3
- package/src/statusline.mjs +55 -8
- package/src/step-timing.mjs +52 -3
- package/src/telemetry.mjs +4 -0
- package/src/title.mjs +18 -3
|
@@ -0,0 +1,1140 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync } from 'node:crypto';
|
|
2
|
+
import {
|
|
3
|
+
closeSync,
|
|
4
|
+
existsSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
openSync,
|
|
7
|
+
readFileSync,
|
|
8
|
+
rmSync,
|
|
9
|
+
statSync,
|
|
10
|
+
writeSync,
|
|
11
|
+
} from 'node:fs';
|
|
12
|
+
import { homedir, hostname } from 'node:os';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { configDir } from './config.mjs';
|
|
15
|
+
import { writeFileAtomic } from './fs-atomic.mjs';
|
|
16
|
+
import {
|
|
17
|
+
clearActiveAgyCredential,
|
|
18
|
+
createKeyringBackend,
|
|
19
|
+
readActiveAgyCredential,
|
|
20
|
+
VAULT_KEYRING_SERVICE,
|
|
21
|
+
writeActiveAgyCredential,
|
|
22
|
+
} from './keyring.mjs';
|
|
23
|
+
import { hashAccountIdentifier } from './quota-sync.mjs';
|
|
24
|
+
|
|
25
|
+
export const ALIAS_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,31}$/;
|
|
26
|
+
export const VAULT_STORAGE_MODES = Object.freeze(['auto', 'keychain', 'file']);
|
|
27
|
+
const LOCK_STALE_MS = 30_000;
|
|
28
|
+
const LOCK_TIMEOUT_MS = 5_000;
|
|
29
|
+
const LOCK_RETRY_MS = 25;
|
|
30
|
+
const WAIT_ARRAY = new Int32Array(new SharedArrayBuffer(4));
|
|
31
|
+
|
|
32
|
+
function sleepSync(ms) {
|
|
33
|
+
Atomics.wait(WAIT_ARRAY, 0, 0, ms);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function accountsDir(baseDir = configDir(homedir())) {
|
|
37
|
+
return join(baseDir, 'accounts');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function accountIndexPath(baseDir = configDir(homedir())) {
|
|
41
|
+
return join(accountsDir(baseDir), 'index.json');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function accountStatePath(baseDir = configDir(homedir())) {
|
|
45
|
+
return join(accountsDir(baseDir), 'state.json');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function accountVaultFilePath(baseDir = configDir(homedir())) {
|
|
49
|
+
return join(accountsDir(baseDir), 'vault.json');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function accountLockPath(baseDir = configDir(homedir())) {
|
|
53
|
+
return join(accountsDir(baseDir), '.lock');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function sha256Short(value) {
|
|
57
|
+
if (typeof value !== 'string' || !value) return null;
|
|
58
|
+
return createHash('sha256').update(value).digest('hex').slice(0, 16);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function maskEmail(email) {
|
|
62
|
+
const cleaned = typeof email === 'string' ? email.trim() : '';
|
|
63
|
+
const at = cleaned.indexOf('@');
|
|
64
|
+
if (at <= 0 || at === cleaned.length - 1) return null;
|
|
65
|
+
const local = cleaned.slice(0, at);
|
|
66
|
+
const domain = cleaned.slice(at + 1);
|
|
67
|
+
if (local.length <= 1) return `***@${domain}`;
|
|
68
|
+
if (local.length === 2) return `${local[0]}***@${domain}`;
|
|
69
|
+
return `${local.slice(0, 2)}***@${domain}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function decodeJwtClaimsUnsafe(jwt) {
|
|
73
|
+
if (typeof jwt !== 'string') return null;
|
|
74
|
+
const parts = jwt.trim().split('.');
|
|
75
|
+
if (parts.length < 2 || !parts[1]) return null;
|
|
76
|
+
try {
|
|
77
|
+
const json = Buffer.from(parts[1], 'base64url').toString('utf8');
|
|
78
|
+
const parsed = JSON.parse(json);
|
|
79
|
+
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
80
|
+
} catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function decodeGoKeyringValue(raw) {
|
|
86
|
+
const str = String(raw ?? '').trim();
|
|
87
|
+
const prefix = 'go-keyring-base64:';
|
|
88
|
+
if (str.startsWith(prefix)) {
|
|
89
|
+
try {
|
|
90
|
+
return Buffer.from(str.slice(prefix.length), 'base64').toString('utf8').trim();
|
|
91
|
+
} catch {
|
|
92
|
+
return str;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return str;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function parseAgyTokenPayload(raw) {
|
|
99
|
+
const originalRaw = String(raw ?? '').trim();
|
|
100
|
+
const str = decodeGoKeyringValue(originalRaw);
|
|
101
|
+
if (!str) {
|
|
102
|
+
throw new Error('Credential payload is empty.');
|
|
103
|
+
}
|
|
104
|
+
let parsed;
|
|
105
|
+
try {
|
|
106
|
+
parsed = JSON.parse(str);
|
|
107
|
+
} catch {
|
|
108
|
+
throw new Error('Credential payload is not valid JSON.');
|
|
109
|
+
}
|
|
110
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
111
|
+
throw new Error('Credential payload must be a JSON object.');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const tokenObj = parsed.token && typeof parsed.token === 'object' ? parsed.token : parsed;
|
|
115
|
+
const accessToken = typeof tokenObj.access_token === 'string' && tokenObj.access_token.trim() ? tokenObj.access_token.trim() : null;
|
|
116
|
+
const refreshToken = typeof tokenObj.refresh_token === 'string' && tokenObj.refresh_token.trim() ? tokenObj.refresh_token.trim() : null;
|
|
117
|
+
const idToken =
|
|
118
|
+
(typeof parsed.id_token === 'string' && parsed.id_token.trim()) ||
|
|
119
|
+
(typeof tokenObj.id_token === 'string' && tokenObj.id_token.trim()) ||
|
|
120
|
+
null;
|
|
121
|
+
|
|
122
|
+
if (!accessToken && !refreshToken && !idToken) {
|
|
123
|
+
throw new Error('Credential JSON does not contain access_token, refresh_token, or id_token.');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const claims = idToken ? decodeJwtClaimsUnsafe(idToken) : null;
|
|
127
|
+
const rawEmail =
|
|
128
|
+
(typeof claims?.email === 'string' && claims.email.trim()) ||
|
|
129
|
+
(typeof parsed.email === 'string' && parsed.email.trim()) ||
|
|
130
|
+
null;
|
|
131
|
+
const rawSub = (typeof claims?.sub === 'string' && claims.sub.trim()) || null;
|
|
132
|
+
const rawExpiry = typeof tokenObj.expiry === 'string' ? tokenObj.expiry : null;
|
|
133
|
+
const expiryMs = rawExpiry && Number.isFinite(Date.parse(rawExpiry)) ? Date.parse(rawExpiry) : null;
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
raw: originalRaw,
|
|
137
|
+
authMethod: typeof parsed.auth_method === 'string' ? parsed.auth_method : 'oauth',
|
|
138
|
+
hasRefreshToken: Boolean(refreshToken),
|
|
139
|
+
accessTokenHash: sha256Short(accessToken),
|
|
140
|
+
refreshTokenHash: sha256Short(refreshToken),
|
|
141
|
+
subHash: sha256Short(rawSub),
|
|
142
|
+
emailHash: rawEmail ? hashAccountIdentifier(rawEmail) : null,
|
|
143
|
+
maskedEmail: rawEmail ? maskEmail(rawEmail) : null,
|
|
144
|
+
expiry: rawExpiry,
|
|
145
|
+
expiryMs,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function validateAlias(alias) {
|
|
150
|
+
const cleaned = String(alias ?? '').trim();
|
|
151
|
+
if (!ALIAS_REGEX.test(cleaned)) {
|
|
152
|
+
throw new Error(
|
|
153
|
+
`Invalid account alias "${alias}". Use 1-32 alphanumeric characters, ".", "_", or "-" (starting with a letter or digit).`,
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
return cleaned;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function isPidAlive(pid) {
|
|
160
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
161
|
+
try {
|
|
162
|
+
process.kill(pid, 0);
|
|
163
|
+
return true;
|
|
164
|
+
} catch (err) {
|
|
165
|
+
return err?.code === 'EPERM';
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function withAccountLock(fn, { baseDir = configDir(homedir()), timeoutMs = LOCK_TIMEOUT_MS } = {}) {
|
|
170
|
+
const dir = accountsDir(baseDir);
|
|
171
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
172
|
+
const lockPath = accountLockPath(baseDir);
|
|
173
|
+
const deadline = Date.now() + timeoutMs;
|
|
174
|
+
const token = `${process.pid}:${Date.now()}:${randomBytes(4).toString('hex')}`;
|
|
175
|
+
let acquired = false;
|
|
176
|
+
|
|
177
|
+
while (!acquired) {
|
|
178
|
+
try {
|
|
179
|
+
const fd = openSync(lockPath, 'wx', 0o600);
|
|
180
|
+
try {
|
|
181
|
+
writeSync(fd, JSON.stringify({ pid: process.pid, host: hostname(), token, createdAt: Date.now() }) + '\n');
|
|
182
|
+
} finally {
|
|
183
|
+
closeSync(fd);
|
|
184
|
+
}
|
|
185
|
+
acquired = true;
|
|
186
|
+
} catch (err) {
|
|
187
|
+
if (err?.code !== 'EEXIST') throw err;
|
|
188
|
+
|
|
189
|
+
// Inspect lock for staleness (dead PID or expired TTL).
|
|
190
|
+
let stale = false;
|
|
191
|
+
try {
|
|
192
|
+
const raw = readFileSync(lockPath, 'utf8');
|
|
193
|
+
const info = JSON.parse(raw);
|
|
194
|
+
const age = Date.now() - Number(info?.createdAt || 0);
|
|
195
|
+
if (age > LOCK_STALE_MS) {
|
|
196
|
+
stale = true;
|
|
197
|
+
} else if (info?.host === hostname() && Number.isInteger(info?.pid) && !isPidAlive(info.pid)) {
|
|
198
|
+
stale = true;
|
|
199
|
+
}
|
|
200
|
+
} catch {
|
|
201
|
+
try {
|
|
202
|
+
const st = statSync(lockPath);
|
|
203
|
+
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) stale = true;
|
|
204
|
+
} catch {
|
|
205
|
+
// Lock vanished concurrently; retry immediately.
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (stale) {
|
|
211
|
+
try {
|
|
212
|
+
rmSync(lockPath, { force: true });
|
|
213
|
+
} catch {
|
|
214
|
+
// Ignore race.
|
|
215
|
+
}
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (Date.now() >= deadline) {
|
|
220
|
+
throw new Error(`Timed out waiting for agy-bar account lock (${lockPath}). Another account operation may be running.`);
|
|
221
|
+
}
|
|
222
|
+
sleepSync(LOCK_RETRY_MS);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
try {
|
|
227
|
+
return fn();
|
|
228
|
+
} finally {
|
|
229
|
+
try {
|
|
230
|
+
const current = readFileSync(lockPath, 'utf8');
|
|
231
|
+
if (current.includes(token)) {
|
|
232
|
+
rmSync(lockPath, { force: true });
|
|
233
|
+
}
|
|
234
|
+
} catch {
|
|
235
|
+
// Ignore cleanup errors.
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function readAccountIndex({ baseDir = configDir(homedir()) } = {}) {
|
|
241
|
+
const filePath = accountIndexPath(baseDir);
|
|
242
|
+
if (!existsSync(filePath)) {
|
|
243
|
+
return { version: 1, accounts: [] };
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
|
|
247
|
+
if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.accounts)) {
|
|
248
|
+
return { version: 1, accounts: [] };
|
|
249
|
+
}
|
|
250
|
+
return { version: 1, accounts: parsed.accounts.filter((a) => a && typeof a === 'object' && typeof a.id === 'string') };
|
|
251
|
+
} catch {
|
|
252
|
+
return { version: 1, accounts: [] };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function writeAccountIndex(index, { baseDir = configDir(homedir()) } = {}) {
|
|
257
|
+
writeFileAtomic(accountIndexPath(baseDir), JSON.stringify({ version: 1, accounts: index.accounts }, null, 2) + '\n', {
|
|
258
|
+
mode: 0o600,
|
|
259
|
+
dirMode: 0o700,
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function readActiveAccountState({ baseDir = configDir(homedir()) } = {}) {
|
|
264
|
+
const filePath = accountStatePath(baseDir);
|
|
265
|
+
if (!existsSync(filePath)) return null;
|
|
266
|
+
try {
|
|
267
|
+
const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
|
|
268
|
+
if (!parsed || typeof parsed !== 'object') return null;
|
|
269
|
+
return {
|
|
270
|
+
activeAccountId: typeof parsed.activeAccountId === 'string' ? parsed.activeAccountId : null,
|
|
271
|
+
activeQuotaKey: typeof parsed.activeQuotaKey === 'string' ? parsed.activeQuotaKey : null,
|
|
272
|
+
lastSwitchAt: typeof parsed.lastSwitchAt === 'number' ? parsed.lastSwitchAt : null,
|
|
273
|
+
updatedAt: typeof parsed.updatedAt === 'number' ? parsed.updatedAt : null,
|
|
274
|
+
};
|
|
275
|
+
} catch {
|
|
276
|
+
return null;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function writeActiveAccountState(state, { baseDir = configDir(homedir()) } = {}) {
|
|
281
|
+
writeFileAtomic(accountStatePath(baseDir), JSON.stringify({ version: 1, ...state }, null, 2) + '\n', {
|
|
282
|
+
mode: 0o600,
|
|
283
|
+
dirMode: 0o700,
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function readFileVault(baseDir) {
|
|
288
|
+
const filePath = accountVaultFilePath(baseDir);
|
|
289
|
+
if (!existsSync(filePath)) return { version: 1, secrets: {} };
|
|
290
|
+
try {
|
|
291
|
+
const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
|
|
292
|
+
if (!parsed || typeof parsed !== 'object' || !parsed.secrets || typeof parsed.secrets !== 'object') {
|
|
293
|
+
return { version: 1, secrets: {} };
|
|
294
|
+
}
|
|
295
|
+
return { version: 1, secrets: { ...parsed.secrets } };
|
|
296
|
+
} catch {
|
|
297
|
+
return { version: 1, secrets: {} };
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function writeFileVault(vault, baseDir) {
|
|
302
|
+
writeFileAtomic(accountVaultFilePath(baseDir), JSON.stringify({ version: 1, secrets: vault.secrets }, null, 2) + '\n', {
|
|
303
|
+
mode: 0o600,
|
|
304
|
+
dirMode: 0o700,
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function writeVaultSecret(slotId, rawSecret, { storage = 'auto', baseDir, keyring }) {
|
|
309
|
+
if (!VAULT_STORAGE_MODES.includes(storage)) {
|
|
310
|
+
throw new Error(`Invalid storage mode "${storage}". Choose one of: ${VAULT_STORAGE_MODES.join(', ')}`);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (storage !== 'file' && keyring?.isAvailable?.()) {
|
|
314
|
+
try {
|
|
315
|
+
keyring.set(VAULT_KEYRING_SERVICE, slotId, rawSecret, { sharedAcl: false });
|
|
316
|
+
// Remove any stale copy in file vault if migrating from file -> keychain.
|
|
317
|
+
const vaultPath = accountVaultFilePath(baseDir);
|
|
318
|
+
if (existsSync(vaultPath)) {
|
|
319
|
+
const vault = readFileVault(baseDir);
|
|
320
|
+
if (Object.hasOwn(vault.secrets, slotId)) {
|
|
321
|
+
delete vault.secrets[slotId];
|
|
322
|
+
writeFileVault(vault, baseDir);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return 'keychain';
|
|
326
|
+
} catch (err) {
|
|
327
|
+
if (storage === 'keychain' || err?.code !== 'KEYRING_UNAVAILABLE') {
|
|
328
|
+
throw err;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
} else if (storage === 'keychain') {
|
|
332
|
+
throw new Error('OS keyring is not available in this environment. Use "--storage file" or default auto fallback.');
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const vault = readFileVault(baseDir);
|
|
336
|
+
vault.secrets[slotId] = rawSecret;
|
|
337
|
+
writeFileVault(vault, baseDir);
|
|
338
|
+
return 'file';
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function readVaultSecret(slot, { baseDir, keyring }) {
|
|
342
|
+
if (slot.storageBackend === 'keychain' && keyring?.isAvailable?.()) {
|
|
343
|
+
try {
|
|
344
|
+
const secret = keyring.get(VAULT_KEYRING_SERVICE, slot.id);
|
|
345
|
+
if (typeof secret === 'string' && secret.trim()) return secret.trim();
|
|
346
|
+
} catch (err) {
|
|
347
|
+
if (err?.code !== 'KEYRING_UNAVAILABLE') throw err;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const vault = readFileVault(baseDir);
|
|
352
|
+
const fromFile = vault.secrets[slot.id];
|
|
353
|
+
if (typeof fromFile === 'string' && fromFile.trim()) return fromFile.trim();
|
|
354
|
+
|
|
355
|
+
// Last-chance check in keychain if metadata was stale.
|
|
356
|
+
if (slot.storageBackend !== 'keychain' && keyring?.isAvailable?.()) {
|
|
357
|
+
try {
|
|
358
|
+
const secret = keyring.get(VAULT_KEYRING_SERVICE, slot.id);
|
|
359
|
+
if (typeof secret === 'string' && secret.trim()) return secret.trim();
|
|
360
|
+
} catch {
|
|
361
|
+
// Ignore fallback miss.
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function deleteVaultSecret(slot, { baseDir, keyring }) {
|
|
369
|
+
if (keyring?.isAvailable?.()) {
|
|
370
|
+
try {
|
|
371
|
+
keyring.delete(VAULT_KEYRING_SERVICE, slot.id);
|
|
372
|
+
} catch {
|
|
373
|
+
// Ignore if absent or unavailable.
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
const vaultPath = accountVaultFilePath(baseDir);
|
|
377
|
+
if (existsSync(vaultPath)) {
|
|
378
|
+
const vault = readFileVault(baseDir);
|
|
379
|
+
if (Object.hasOwn(vault.secrets, slot.id)) {
|
|
380
|
+
delete vault.secrets[slot.id];
|
|
381
|
+
writeFileVault(vault, baseDir);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export function matchSlotForToken(accounts, tokenInfo) {
|
|
387
|
+
if (!Array.isArray(accounts) || !tokenInfo) return null;
|
|
388
|
+
if (tokenInfo.refreshTokenHash) {
|
|
389
|
+
const byRefresh = accounts.find((a) => a.refreshTokenHash && a.refreshTokenHash === tokenInfo.refreshTokenHash);
|
|
390
|
+
if (byRefresh) return byRefresh;
|
|
391
|
+
}
|
|
392
|
+
if (tokenInfo.subHash) {
|
|
393
|
+
const bySub = accounts.find((a) => a.subHash && a.subHash === tokenInfo.subHash);
|
|
394
|
+
if (bySub) return bySub;
|
|
395
|
+
}
|
|
396
|
+
if (tokenInfo.emailHash) {
|
|
397
|
+
const byEmail = accounts.find((a) => a.emailHash && a.emailHash === tokenInfo.emailHash);
|
|
398
|
+
if (byEmail) return byEmail;
|
|
399
|
+
}
|
|
400
|
+
if (tokenInfo.accessTokenHash) {
|
|
401
|
+
const byAccess = accounts.find((a) => a.accessTokenHash && a.accessTokenHash === tokenInfo.accessTokenHash);
|
|
402
|
+
if (byAccess) return byAccess;
|
|
403
|
+
}
|
|
404
|
+
return null;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export function resolveAccountTarget(accounts, target) {
|
|
408
|
+
const query = String(target ?? '').trim();
|
|
409
|
+
if (!query) return null;
|
|
410
|
+
const lower = query.toLowerCase();
|
|
411
|
+
const exactAlias = accounts.find((a) => a.alias.toLowerCase() === lower);
|
|
412
|
+
if (exactAlias) return exactAlias;
|
|
413
|
+
const exactId = accounts.find((a) => a.id.toLowerCase() === lower);
|
|
414
|
+
if (exactId) return exactId;
|
|
415
|
+
const prefixMatches = accounts.filter((a) => a.id.toLowerCase().startsWith(lower));
|
|
416
|
+
if (prefixMatches.length === 1) return prefixMatches[0];
|
|
417
|
+
return null;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function generateDefaultAlias(accounts) {
|
|
421
|
+
const used = new Set(accounts.map((a) => a.alias.toLowerCase()));
|
|
422
|
+
if (!used.has('primary')) return 'primary';
|
|
423
|
+
for (let i = 1; i <= 999; i++) {
|
|
424
|
+
const candidate = `acct-${i}`;
|
|
425
|
+
if (!used.has(candidate)) return candidate;
|
|
426
|
+
}
|
|
427
|
+
return `acct-${randomBytes(3).toString('hex')}`;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function createSlotId() {
|
|
431
|
+
return `acct-${randomBytes(6).toString('hex')}`;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function upsertSlotRecord(index, { existing, alias, tokenInfo, storageBackend, tier = null, maskedEmail = null, emailHash = null, now }) {
|
|
435
|
+
const id = existing?.id || createSlotId();
|
|
436
|
+
const resolvedEmailHash = tokenInfo.emailHash || emailHash || existing?.emailHash || null;
|
|
437
|
+
const quotaKey = resolvedEmailHash || existing?.quotaKey || id;
|
|
438
|
+
const record = {
|
|
439
|
+
id,
|
|
440
|
+
alias,
|
|
441
|
+
maskedEmail: tokenInfo.maskedEmail || maskedEmail || existing?.maskedEmail || null,
|
|
442
|
+
emailHash: resolvedEmailHash,
|
|
443
|
+
subHash: tokenInfo.subHash || existing?.subHash || null,
|
|
444
|
+
quotaKey,
|
|
445
|
+
tier: tier || existing?.tier || null,
|
|
446
|
+
authMethod: tokenInfo.authMethod || existing?.authMethod || 'oauth',
|
|
447
|
+
hasRefreshToken: tokenInfo.hasRefreshToken,
|
|
448
|
+
refreshTokenHash: tokenInfo.refreshTokenHash || existing?.refreshTokenHash || null,
|
|
449
|
+
accessTokenHash: tokenInfo.accessTokenHash || existing?.accessTokenHash || null,
|
|
450
|
+
expiry: tokenInfo.expiry || existing?.expiry || null,
|
|
451
|
+
storageBackend,
|
|
452
|
+
createdAt: existing?.createdAt || now,
|
|
453
|
+
lastUsedAt: now,
|
|
454
|
+
lastRefreshedAt: now,
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
if (existing) {
|
|
458
|
+
const idx = index.accounts.findIndex((a) => a.id === existing.id);
|
|
459
|
+
if (idx >= 0) index.accounts[idx] = record;
|
|
460
|
+
else index.accounts.push(record);
|
|
461
|
+
} else {
|
|
462
|
+
index.accounts.push(record);
|
|
463
|
+
}
|
|
464
|
+
return record;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
export function upsertImportedAccounts(
|
|
468
|
+
candidates = [],
|
|
469
|
+
{
|
|
470
|
+
force = false,
|
|
471
|
+
storage = 'auto',
|
|
472
|
+
home = homedir(),
|
|
473
|
+
baseDir = configDir(homedir()),
|
|
474
|
+
keyring = createKeyringBackend(),
|
|
475
|
+
now = Date.now(),
|
|
476
|
+
} = {},
|
|
477
|
+
) {
|
|
478
|
+
return withAccountLock(
|
|
479
|
+
() => {
|
|
480
|
+
const index = readAccountIndex({ baseDir });
|
|
481
|
+
const imported = [];
|
|
482
|
+
const updated = [];
|
|
483
|
+
const skipped = [];
|
|
484
|
+
|
|
485
|
+
for (const item of candidates) {
|
|
486
|
+
if (!item?.rawSecret) {
|
|
487
|
+
skipped.push({ alias: item?.alias || null, maskedEmail: item?.maskedEmail || null, reason: 'missing credential' });
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
let tokenInfo;
|
|
491
|
+
try {
|
|
492
|
+
tokenInfo = parseAgyTokenPayload(item.rawSecret);
|
|
493
|
+
} catch (err) {
|
|
494
|
+
skipped.push({ alias: item?.alias || null, maskedEmail: item?.maskedEmail || null, reason: err.message });
|
|
495
|
+
continue;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const effectiveEmailHash = tokenInfo.emailHash || item.emailHash || null;
|
|
499
|
+
const matchInfo = { ...tokenInfo, emailHash: effectiveEmailHash };
|
|
500
|
+
const existing = matchSlotForToken(index.accounts, matchInfo);
|
|
501
|
+
|
|
502
|
+
let desiredAlias =
|
|
503
|
+
item.alias && ALIAS_REGEX.test(String(item.alias))
|
|
504
|
+
? String(item.alias)
|
|
505
|
+
: generateDefaultAlias(index.accounts);
|
|
506
|
+
|
|
507
|
+
const collision = index.accounts.find((a) => a.alias.toLowerCase() === desiredAlias.toLowerCase());
|
|
508
|
+
if (collision && (!existing || collision.id !== existing.id)) {
|
|
509
|
+
if (force) {
|
|
510
|
+
deleteVaultSecret(collision, { baseDir, keyring });
|
|
511
|
+
index.accounts = index.accounts.filter((a) => a.id !== collision.id);
|
|
512
|
+
} else {
|
|
513
|
+
let suffix = 2;
|
|
514
|
+
const stem = desiredAlias.slice(0, 28);
|
|
515
|
+
while (index.accounts.some((a) => a.alias.toLowerCase() === `${stem}-${suffix}`.toLowerCase())) {
|
|
516
|
+
suffix += 1;
|
|
517
|
+
}
|
|
518
|
+
desiredAlias = `${stem}-${suffix}`.slice(0, 32);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const slotId = existing?.id || createSlotId();
|
|
523
|
+
const actualStorage = writeVaultSecret(slotId, tokenInfo.raw, { storage, baseDir, keyring });
|
|
524
|
+
const saved = upsertSlotRecord(index, {
|
|
525
|
+
existing: existing ? { ...existing, id: slotId } : { id: slotId, createdAt: item.createdAt || now },
|
|
526
|
+
alias: existing && !force ? existing.alias : desiredAlias,
|
|
527
|
+
tokenInfo,
|
|
528
|
+
storageBackend: actualStorage,
|
|
529
|
+
tier: item.tier || null,
|
|
530
|
+
maskedEmail: item.maskedEmail || null,
|
|
531
|
+
emailHash: effectiveEmailHash,
|
|
532
|
+
now: item.lastUsedAt || now,
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
const entry = {
|
|
536
|
+
id: saved.id,
|
|
537
|
+
alias: saved.alias,
|
|
538
|
+
maskedEmail: saved.maskedEmail,
|
|
539
|
+
quotaKey: saved.quotaKey,
|
|
540
|
+
tier: saved.tier,
|
|
541
|
+
storageBackend: saved.storageBackend,
|
|
542
|
+
quotaBuckets: item.quotaBuckets || null,
|
|
543
|
+
};
|
|
544
|
+
if (existing) updated.push(entry);
|
|
545
|
+
else imported.push(entry);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// If no active account is tracked yet, passively link whichever slot matches current agy login.
|
|
549
|
+
let detectedActiveAlias = null;
|
|
550
|
+
const existingState = readActiveAccountState({ baseDir });
|
|
551
|
+
if (!existingState?.activeAccountId && index.accounts.length > 0) {
|
|
552
|
+
try {
|
|
553
|
+
const activeCred = readActiveAgyCredential({ home, keyring });
|
|
554
|
+
if (activeCred?.raw) {
|
|
555
|
+
const activeInfo = parseAgyTokenPayload(activeCred.raw);
|
|
556
|
+
const matchedActive = matchSlotForToken(index.accounts, activeInfo);
|
|
557
|
+
if (matchedActive) {
|
|
558
|
+
matchedActive.lastUsedAt = now;
|
|
559
|
+
writeActiveAccountState(
|
|
560
|
+
{
|
|
561
|
+
activeAccountId: matchedActive.id,
|
|
562
|
+
activeQuotaKey: matchedActive.quotaKey,
|
|
563
|
+
lastSwitchAt: now,
|
|
564
|
+
updatedAt: now,
|
|
565
|
+
},
|
|
566
|
+
{ baseDir },
|
|
567
|
+
);
|
|
568
|
+
detectedActiveAlias = matchedActive.alias;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
} catch {
|
|
572
|
+
// Never fail import if active credential cannot be read.
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
writeAccountIndex(index, { baseDir });
|
|
577
|
+
return {
|
|
578
|
+
imported,
|
|
579
|
+
updated,
|
|
580
|
+
skipped,
|
|
581
|
+
detectedActiveAlias,
|
|
582
|
+
total: index.accounts.length,
|
|
583
|
+
};
|
|
584
|
+
},
|
|
585
|
+
{ baseDir },
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
export function saveCurrentAccount({
|
|
590
|
+
alias = null,
|
|
591
|
+
force = false,
|
|
592
|
+
storage = 'auto',
|
|
593
|
+
baseDir = configDir(homedir()),
|
|
594
|
+
home = homedir(),
|
|
595
|
+
keyring = createKeyringBackend(),
|
|
596
|
+
now = Date.now(),
|
|
597
|
+
} = {}) {
|
|
598
|
+
return withAccountLock(
|
|
599
|
+
() => {
|
|
600
|
+
const activeCred = readActiveAgyCredential({ home, keyring });
|
|
601
|
+
if (!activeCred) {
|
|
602
|
+
throw new Error('No active Antigravity CLI login found. Sign in with "agy" first, then run "agy-bar account save [alias]".');
|
|
603
|
+
}
|
|
604
|
+
const tokenInfo = parseAgyTokenPayload(activeCred.raw);
|
|
605
|
+
const index = readAccountIndex({ baseDir });
|
|
606
|
+
const matched = matchSlotForToken(index.accounts, tokenInfo);
|
|
607
|
+
|
|
608
|
+
let chosenAlias;
|
|
609
|
+
if (alias !== null && alias !== undefined && String(alias).trim() !== '') {
|
|
610
|
+
chosenAlias = validateAlias(alias);
|
|
611
|
+
} else if (matched) {
|
|
612
|
+
chosenAlias = matched.alias;
|
|
613
|
+
} else {
|
|
614
|
+
chosenAlias = generateDefaultAlias(index.accounts);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
const aliasOwner = index.accounts.find((a) => a.alias.toLowerCase() === chosenAlias.toLowerCase());
|
|
618
|
+
let targetExisting = matched;
|
|
619
|
+
|
|
620
|
+
if (aliasOwner && (!matched || aliasOwner.id !== matched.id)) {
|
|
621
|
+
if (!force) {
|
|
622
|
+
throw new Error(
|
|
623
|
+
`Alias "${chosenAlias}" is already assigned to another account (${aliasOwner.maskedEmail || aliasOwner.id}). Choose a different alias or pass --force to replace it.`,
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
// Replacing aliasOwner with this credential; remove old aliasOwner slot if matched already had another slot.
|
|
627
|
+
if (matched && matched.id !== aliasOwner.id) {
|
|
628
|
+
deleteVaultSecret(aliasOwner, { baseDir, keyring });
|
|
629
|
+
index.accounts = index.accounts.filter((a) => a.id !== aliasOwner.id);
|
|
630
|
+
} else {
|
|
631
|
+
targetExisting = aliasOwner;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
const slotId = targetExisting?.id || createSlotId();
|
|
636
|
+
const chosenStorage = storage === 'auto' && targetExisting?.storageBackend === 'file' && !keyring?.isAvailable?.()
|
|
637
|
+
? 'file'
|
|
638
|
+
: storage;
|
|
639
|
+
const actualStorage = writeVaultSecret(slotId, tokenInfo.raw, { storage: chosenStorage, baseDir, keyring });
|
|
640
|
+
const saved = upsertSlotRecord(index, {
|
|
641
|
+
existing: targetExisting ? { ...targetExisting, id: slotId } : { id: slotId },
|
|
642
|
+
alias: chosenAlias,
|
|
643
|
+
tokenInfo,
|
|
644
|
+
storageBackend: actualStorage,
|
|
645
|
+
now,
|
|
646
|
+
});
|
|
647
|
+
writeAccountIndex(index, { baseDir });
|
|
648
|
+
writeActiveAccountState(
|
|
649
|
+
{
|
|
650
|
+
activeAccountId: saved.id,
|
|
651
|
+
activeQuotaKey: saved.quotaKey,
|
|
652
|
+
lastSwitchAt: readActiveAccountState({ baseDir })?.lastSwitchAt ?? now,
|
|
653
|
+
updatedAt: now,
|
|
654
|
+
},
|
|
655
|
+
{ baseDir },
|
|
656
|
+
);
|
|
657
|
+
|
|
658
|
+
return {
|
|
659
|
+
action: matched ? 'updated' : aliasOwner ? 'replaced' : 'saved',
|
|
660
|
+
account: saved,
|
|
661
|
+
source: activeCred.source,
|
|
662
|
+
};
|
|
663
|
+
},
|
|
664
|
+
{ baseDir },
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function writebackOutgoingSlot(index, state, outgoingRaw, { baseDir, keyring, now }) {
|
|
669
|
+
if (!outgoingRaw) return { wroteBack: false, slot: null };
|
|
670
|
+
let outgoingInfo;
|
|
671
|
+
try {
|
|
672
|
+
outgoingInfo = parseAgyTokenPayload(outgoingRaw);
|
|
673
|
+
} catch {
|
|
674
|
+
return { wroteBack: false, slot: null };
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
let outgoingSlot = matchSlotForToken(index.accounts, outgoingInfo);
|
|
678
|
+
if (!outgoingSlot && state?.activeAccountId) {
|
|
679
|
+
const byState = index.accounts.find((a) => a.id === state.activeAccountId);
|
|
680
|
+
// Only trust state fallback if emailHash / subHash don't actively contradict it.
|
|
681
|
+
if (
|
|
682
|
+
byState &&
|
|
683
|
+
(!outgoingInfo.emailHash || !byState.emailHash || outgoingInfo.emailHash === byState.emailHash) &&
|
|
684
|
+
(!outgoingInfo.subHash || !byState.subHash || outgoingInfo.subHash === byState.subHash)
|
|
685
|
+
) {
|
|
686
|
+
outgoingSlot = byState;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
if (!outgoingSlot) return { wroteBack: false, slot: null };
|
|
691
|
+
|
|
692
|
+
const tokenChanged =
|
|
693
|
+
outgoingInfo.accessTokenHash !== outgoingSlot.accessTokenHash ||
|
|
694
|
+
outgoingInfo.refreshTokenHash !== outgoingSlot.refreshTokenHash;
|
|
695
|
+
|
|
696
|
+
if (!tokenChanged) return { wroteBack: false, slot: outgoingSlot };
|
|
697
|
+
|
|
698
|
+
const preferredStorage = outgoingSlot.storageBackend === 'file' ? 'file' : 'auto';
|
|
699
|
+
const actualStorage = writeVaultSecret(outgoingSlot.id, outgoingInfo.raw, {
|
|
700
|
+
storage: preferredStorage,
|
|
701
|
+
baseDir,
|
|
702
|
+
keyring,
|
|
703
|
+
});
|
|
704
|
+
const idx = index.accounts.findIndex((a) => a.id === outgoingSlot.id);
|
|
705
|
+
if (idx >= 0) {
|
|
706
|
+
index.accounts[idx] = {
|
|
707
|
+
...outgoingSlot,
|
|
708
|
+
accessTokenHash: outgoingInfo.accessTokenHash || outgoingSlot.accessTokenHash,
|
|
709
|
+
refreshTokenHash: outgoingInfo.refreshTokenHash || outgoingSlot.refreshTokenHash,
|
|
710
|
+
expiry: outgoingInfo.expiry || outgoingSlot.expiry,
|
|
711
|
+
maskedEmail: outgoingInfo.maskedEmail || outgoingSlot.maskedEmail,
|
|
712
|
+
emailHash: outgoingInfo.emailHash || outgoingSlot.emailHash,
|
|
713
|
+
subHash: outgoingInfo.subHash || outgoingSlot.subHash,
|
|
714
|
+
quotaKey: outgoingInfo.emailHash || outgoingSlot.emailHash || outgoingSlot.quotaKey,
|
|
715
|
+
storageBackend: actualStorage,
|
|
716
|
+
lastRefreshedAt: now,
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
return { wroteBack: true, slot: index.accounts[idx] || outgoingSlot };
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
export function switchToAccount(
|
|
723
|
+
target,
|
|
724
|
+
{
|
|
725
|
+
baseDir = configDir(homedir()),
|
|
726
|
+
home = homedir(),
|
|
727
|
+
keyring = createKeyringBackend(),
|
|
728
|
+
now = Date.now(),
|
|
729
|
+
} = {},
|
|
730
|
+
) {
|
|
731
|
+
return withAccountLock(
|
|
732
|
+
() => {
|
|
733
|
+
const index = readAccountIndex({ baseDir });
|
|
734
|
+
if (index.accounts.length === 0) {
|
|
735
|
+
throw new Error('No saved accounts yet. Run "agy-bar account save [alias]" to save your current login first.');
|
|
736
|
+
}
|
|
737
|
+
const targetSlot = resolveAccountTarget(index.accounts, target);
|
|
738
|
+
if (!targetSlot) {
|
|
739
|
+
const names = index.accounts.map((a) => a.alias).join(', ');
|
|
740
|
+
throw new Error(`Account "${target}" not found. Saved accounts: ${names}`);
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
const targetSecret = readVaultSecret(targetSlot, { baseDir, keyring });
|
|
744
|
+
if (!targetSecret) {
|
|
745
|
+
throw new Error(
|
|
746
|
+
`Stored credential for "${targetSlot.alias}" is missing from ${targetSlot.storageBackend} storage. Re-capture it with "agy-bar account add ${targetSlot.alias}".`,
|
|
747
|
+
);
|
|
748
|
+
}
|
|
749
|
+
const targetInfo = parseAgyTokenPayload(targetSecret);
|
|
750
|
+
|
|
751
|
+
const state = readActiveAccountState({ baseDir });
|
|
752
|
+
let outgoing = null;
|
|
753
|
+
try {
|
|
754
|
+
outgoing = readActiveAgyCredential({ home, keyring });
|
|
755
|
+
} catch {
|
|
756
|
+
outgoing = null;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// Preserve any hourly access_token refresh on the outgoing account before swapping.
|
|
760
|
+
const writeback = writebackOutgoingSlot(index, state, outgoing?.raw || null, { baseDir, keyring, now });
|
|
761
|
+
|
|
762
|
+
try {
|
|
763
|
+
writeActiveAgyCredential(targetInfo.raw, { home, keyring });
|
|
764
|
+
} catch (err) {
|
|
765
|
+
// Atomic rollback to outgoing credential if write failed halfway.
|
|
766
|
+
if (outgoing?.raw) {
|
|
767
|
+
try {
|
|
768
|
+
writeActiveAgyCredential(outgoing.raw, { home, keyring });
|
|
769
|
+
} catch {
|
|
770
|
+
// Best-effort rollback.
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
throw new Error(`Failed to activate account "${targetSlot.alias}": ${err.message}`);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const targetIdx = index.accounts.findIndex((a) => a.id === targetSlot.id);
|
|
777
|
+
if (targetIdx >= 0) {
|
|
778
|
+
index.accounts[targetIdx] = {
|
|
779
|
+
...index.accounts[targetIdx],
|
|
780
|
+
lastUsedAt: now,
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
writeAccountIndex(index, { baseDir });
|
|
784
|
+
writeActiveAccountState(
|
|
785
|
+
{
|
|
786
|
+
activeAccountId: targetSlot.id,
|
|
787
|
+
activeQuotaKey: targetSlot.quotaKey,
|
|
788
|
+
lastSwitchAt: now,
|
|
789
|
+
updatedAt: now,
|
|
790
|
+
},
|
|
791
|
+
{ baseDir },
|
|
792
|
+
);
|
|
793
|
+
|
|
794
|
+
return {
|
|
795
|
+
switched: true,
|
|
796
|
+
fromAlias: writeback.slot?.alias || null,
|
|
797
|
+
wroteBackOutgoing: writeback.wroteBack,
|
|
798
|
+
account: index.accounts[targetIdx] || targetSlot,
|
|
799
|
+
};
|
|
800
|
+
},
|
|
801
|
+
{ baseDir },
|
|
802
|
+
);
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
export function syncActiveAccountBeforeLaunch({
|
|
806
|
+
baseDir = configDir(homedir()),
|
|
807
|
+
home = homedir(),
|
|
808
|
+
keyring = createKeyringBackend(),
|
|
809
|
+
now = Date.now(),
|
|
810
|
+
} = {}) {
|
|
811
|
+
// Fast zero-touch path for users who have never configured multi-account.
|
|
812
|
+
const state = readActiveAccountState({ baseDir });
|
|
813
|
+
if (!state?.activeAccountId) {
|
|
814
|
+
return { active: false, synced: false, reason: 'unused' };
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
return withAccountLock(
|
|
818
|
+
() => {
|
|
819
|
+
const freshState = readActiveAccountState({ baseDir });
|
|
820
|
+
if (!freshState?.activeAccountId) {
|
|
821
|
+
return { active: false, synced: false, reason: 'unused' };
|
|
822
|
+
}
|
|
823
|
+
const index = readAccountIndex({ baseDir });
|
|
824
|
+
const desired = index.accounts.find((a) => a.id === freshState.activeAccountId);
|
|
825
|
+
if (!desired) {
|
|
826
|
+
return { active: false, synced: false, reason: 'missing-slot' };
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
let current = null;
|
|
830
|
+
try {
|
|
831
|
+
current = readActiveAgyCredential({ home, keyring });
|
|
832
|
+
} catch {
|
|
833
|
+
return { active: true, synced: false, reason: 'read-error', alias: desired.alias };
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
if (!current?.raw) {
|
|
837
|
+
const desiredSecret = readVaultSecret(desired, { baseDir, keyring });
|
|
838
|
+
if (!desiredSecret) {
|
|
839
|
+
return { active: true, synced: false, reason: 'missing-secret', alias: desired.alias };
|
|
840
|
+
}
|
|
841
|
+
writeActiveAgyCredential(desiredSecret, { home, keyring });
|
|
842
|
+
return { active: true, synced: true, restoredEmpty: true, alias: desired.alias };
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
let currentInfo;
|
|
846
|
+
try {
|
|
847
|
+
currentInfo = parseAgyTokenPayload(current.raw);
|
|
848
|
+
} catch {
|
|
849
|
+
return { active: true, synced: false, reason: 'unparseable-active', alias: desired.alias };
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
const matched = matchSlotForToken(index.accounts, currentInfo);
|
|
853
|
+
if (!matched) {
|
|
854
|
+
// User signed into a brand-new untracked account directly via `agy`; never clobber it.
|
|
855
|
+
return { active: true, synced: false, reason: 'untracked-login', alias: desired.alias };
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
if (matched.id === desired.id) {
|
|
859
|
+
// Same account: silently save refreshed access_token if hourly refresh occurred.
|
|
860
|
+
const wb = writebackOutgoingSlot(index, freshState, current.raw, { baseDir, keyring, now });
|
|
861
|
+
if (wb.wroteBack) {
|
|
862
|
+
writeAccountIndex(index, { baseDir });
|
|
863
|
+
}
|
|
864
|
+
return { active: true, synced: false, refreshedWriteback: wb.wroteBack, alias: desired.alias };
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// Drift detected: an older terminal refreshed `matched` and overwrote active credentials!
|
|
868
|
+
// 1) Save the refreshed token back to `matched` so zero refresh state is lost.
|
|
869
|
+
writebackOutgoingSlot(index, { activeAccountId: matched.id }, current.raw, { baseDir, keyring, now });
|
|
870
|
+
// 2) Restore `desired` into active credentials.
|
|
871
|
+
const desiredSecret = readVaultSecret(desired, { baseDir, keyring });
|
|
872
|
+
if (!desiredSecret) {
|
|
873
|
+
writeAccountIndex(index, { baseDir });
|
|
874
|
+
return { active: true, synced: false, reason: 'missing-desired-secret', alias: desired.alias };
|
|
875
|
+
}
|
|
876
|
+
writeActiveAgyCredential(desiredSecret, { home, keyring });
|
|
877
|
+
writeAccountIndex(index, { baseDir });
|
|
878
|
+
return {
|
|
879
|
+
active: true,
|
|
880
|
+
synced: true,
|
|
881
|
+
repairedFrom: matched.alias,
|
|
882
|
+
alias: desired.alias,
|
|
883
|
+
};
|
|
884
|
+
},
|
|
885
|
+
{ baseDir },
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
export function renameAccount(oldTarget, newAlias, { baseDir = configDir(homedir()), now = Date.now() } = {}) {
|
|
890
|
+
const validNew = validateAlias(newAlias);
|
|
891
|
+
return withAccountLock(
|
|
892
|
+
() => {
|
|
893
|
+
const index = readAccountIndex({ baseDir });
|
|
894
|
+
const slot = resolveAccountTarget(index.accounts, oldTarget);
|
|
895
|
+
if (!slot) {
|
|
896
|
+
throw new Error(`Account "${oldTarget}" not found.`);
|
|
897
|
+
}
|
|
898
|
+
const collision = index.accounts.find((a) => a.id !== slot.id && a.alias.toLowerCase() === validNew.toLowerCase());
|
|
899
|
+
if (collision) {
|
|
900
|
+
throw new Error(`Alias "${validNew}" is already in use.`);
|
|
901
|
+
}
|
|
902
|
+
const oldAlias = slot.alias;
|
|
903
|
+
slot.alias = validNew;
|
|
904
|
+
slot.updatedAt = now;
|
|
905
|
+
writeAccountIndex(index, { baseDir });
|
|
906
|
+
return { oldAlias, newAlias: validNew, account: slot };
|
|
907
|
+
},
|
|
908
|
+
{ baseDir },
|
|
909
|
+
);
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
export function removeAccount(
|
|
913
|
+
target,
|
|
914
|
+
{
|
|
915
|
+
baseDir = configDir(homedir()),
|
|
916
|
+
keyring = createKeyringBackend(),
|
|
917
|
+
now = Date.now(),
|
|
918
|
+
} = {},
|
|
919
|
+
) {
|
|
920
|
+
return withAccountLock(
|
|
921
|
+
() => {
|
|
922
|
+
const index = readAccountIndex({ baseDir });
|
|
923
|
+
const slot = resolveAccountTarget(index.accounts, target);
|
|
924
|
+
if (!slot) {
|
|
925
|
+
throw new Error(`Account "${target}" not found.`);
|
|
926
|
+
}
|
|
927
|
+
deleteVaultSecret(slot, { baseDir, keyring });
|
|
928
|
+
index.accounts = index.accounts.filter((a) => a.id !== slot.id);
|
|
929
|
+
writeAccountIndex(index, { baseDir });
|
|
930
|
+
|
|
931
|
+
const state = readActiveAccountState({ baseDir });
|
|
932
|
+
if (state?.activeAccountId === slot.id) {
|
|
933
|
+
writeActiveAccountState(
|
|
934
|
+
{
|
|
935
|
+
activeAccountId: null,
|
|
936
|
+
activeQuotaKey: null,
|
|
937
|
+
lastSwitchAt: state.lastSwitchAt,
|
|
938
|
+
updatedAt: now,
|
|
939
|
+
},
|
|
940
|
+
{ baseDir },
|
|
941
|
+
);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
return { removed: true, account: slot, remaining: index.accounts.length };
|
|
945
|
+
},
|
|
946
|
+
{ baseDir },
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
export function prepareForNewAccountLogin({
|
|
951
|
+
baseDir = configDir(homedir()),
|
|
952
|
+
home = homedir(),
|
|
953
|
+
keyring = createKeyringBackend(),
|
|
954
|
+
now = Date.now(),
|
|
955
|
+
} = {}) {
|
|
956
|
+
return withAccountLock(
|
|
957
|
+
() => {
|
|
958
|
+
const current = readActiveAgyCredential({ home, keyring });
|
|
959
|
+
let preserved = null;
|
|
960
|
+
if (current?.raw) {
|
|
961
|
+
try {
|
|
962
|
+
const info = parseAgyTokenPayload(current.raw);
|
|
963
|
+
const index = readAccountIndex({ baseDir });
|
|
964
|
+
const existing = matchSlotForToken(index.accounts, info);
|
|
965
|
+
const alias = existing ? existing.alias : generateDefaultAlias(index.accounts);
|
|
966
|
+
const slotId = existing?.id || createSlotId();
|
|
967
|
+
const actualStorage = writeVaultSecret(slotId, info.raw, { storage: 'auto', baseDir, keyring });
|
|
968
|
+
const saved = upsertSlotRecord(index, {
|
|
969
|
+
existing: existing ? { ...existing, id: slotId } : { id: slotId },
|
|
970
|
+
alias,
|
|
971
|
+
tokenInfo: info,
|
|
972
|
+
storageBackend: actualStorage,
|
|
973
|
+
now,
|
|
974
|
+
});
|
|
975
|
+
writeAccountIndex(index, { baseDir });
|
|
976
|
+
preserved = { alias: saved.alias, id: saved.id, raw: current.raw, existedBefore: Boolean(existing) };
|
|
977
|
+
} catch {
|
|
978
|
+
preserved = { alias: null, id: null, raw: current.raw, existedBefore: false };
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
clearActiveAgyCredential({ home, keyring });
|
|
982
|
+
return { preserved };
|
|
983
|
+
},
|
|
984
|
+
{ baseDir },
|
|
985
|
+
);
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
export function restorePreservedLogin(preserved, { home = homedir(), keyring = createKeyringBackend() } = {}) {
|
|
989
|
+
if (!preserved?.raw) return false;
|
|
990
|
+
writeActiveAgyCredential(preserved.raw, { home, keyring });
|
|
991
|
+
return true;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
export function exportEncryptedBackup({
|
|
995
|
+
passphrase,
|
|
996
|
+
baseDir = configDir(homedir()),
|
|
997
|
+
keyring = createKeyringBackend(),
|
|
998
|
+
now = Date.now(),
|
|
999
|
+
} = {}) {
|
|
1000
|
+
const pass = String(passphrase ?? '');
|
|
1001
|
+
if (pass.length < 4) {
|
|
1002
|
+
throw new Error('Backup passphrase must be at least 4 characters long.');
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
return withAccountLock(
|
|
1006
|
+
() => {
|
|
1007
|
+
const index = readAccountIndex({ baseDir });
|
|
1008
|
+
if (index.accounts.length === 0) {
|
|
1009
|
+
throw new Error('No saved accounts to back up.');
|
|
1010
|
+
}
|
|
1011
|
+
const entries = [];
|
|
1012
|
+
for (const slot of index.accounts) {
|
|
1013
|
+
const rawSecret = readVaultSecret(slot, { baseDir, keyring });
|
|
1014
|
+
if (!rawSecret) continue;
|
|
1015
|
+
entries.push({
|
|
1016
|
+
alias: slot.alias,
|
|
1017
|
+
maskedEmail: slot.maskedEmail || null,
|
|
1018
|
+
emailHash: slot.emailHash || null,
|
|
1019
|
+
quotaKey: slot.quotaKey || null,
|
|
1020
|
+
createdAt: slot.createdAt || now,
|
|
1021
|
+
lastUsedAt: slot.lastUsedAt || now,
|
|
1022
|
+
rawSecret,
|
|
1023
|
+
});
|
|
1024
|
+
}
|
|
1025
|
+
if (entries.length === 0) {
|
|
1026
|
+
throw new Error('No readable account credentials found in vault.');
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
const salt = randomBytes(16);
|
|
1030
|
+
const iv = randomBytes(12);
|
|
1031
|
+
const key = scryptSync(pass, salt, 32, { N: 16384, r: 8, p: 1 });
|
|
1032
|
+
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
|
1033
|
+
const plaintext = JSON.stringify({ version: 1, exportedAt: new Date(now).toISOString(), entries });
|
|
1034
|
+
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
|
1035
|
+
const tag = cipher.getAuthTag();
|
|
1036
|
+
|
|
1037
|
+
return {
|
|
1038
|
+
format: 'agy-bar-vault-backup',
|
|
1039
|
+
version: 1,
|
|
1040
|
+
kdf: 'scrypt',
|
|
1041
|
+
cipher: 'aes-256-gcm',
|
|
1042
|
+
count: entries.length,
|
|
1043
|
+
exportedAt: new Date(now).toISOString(),
|
|
1044
|
+
salt: salt.toString('base64'),
|
|
1045
|
+
iv: iv.toString('base64'),
|
|
1046
|
+
tag: tag.toString('base64'),
|
|
1047
|
+
ciphertext: ciphertext.toString('base64'),
|
|
1048
|
+
};
|
|
1049
|
+
},
|
|
1050
|
+
{ baseDir },
|
|
1051
|
+
);
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
export function importEncryptedBackup(
|
|
1055
|
+
envelope,
|
|
1056
|
+
{
|
|
1057
|
+
passphrase,
|
|
1058
|
+
force = false,
|
|
1059
|
+
storage = 'auto',
|
|
1060
|
+
baseDir = configDir(homedir()),
|
|
1061
|
+
keyring = createKeyringBackend(),
|
|
1062
|
+
now = Date.now(),
|
|
1063
|
+
} = {},
|
|
1064
|
+
) {
|
|
1065
|
+
if (!envelope || typeof envelope !== 'object' || envelope.format !== 'agy-bar-vault-backup') {
|
|
1066
|
+
throw new Error('Invalid backup file format (expected agy-bar-vault-backup).');
|
|
1067
|
+
}
|
|
1068
|
+
const pass = String(passphrase ?? '');
|
|
1069
|
+
if (!pass) {
|
|
1070
|
+
throw new Error('Passphrase is required to decrypt backup.');
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
let decrypted;
|
|
1074
|
+
try {
|
|
1075
|
+
const salt = Buffer.from(String(envelope.salt || ''), 'base64');
|
|
1076
|
+
const iv = Buffer.from(String(envelope.iv || ''), 'base64');
|
|
1077
|
+
const tag = Buffer.from(String(envelope.tag || ''), 'base64');
|
|
1078
|
+
const ciphertext = Buffer.from(String(envelope.ciphertext || ''), 'base64');
|
|
1079
|
+
const key = scryptSync(pass, salt, 32, { N: 16384, r: 8, p: 1 });
|
|
1080
|
+
const decipher = createDecipheriv('aes-256-gcm', key, iv);
|
|
1081
|
+
decipher.setAuthTag(tag);
|
|
1082
|
+
const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
|
|
1083
|
+
decrypted = JSON.parse(plain);
|
|
1084
|
+
} catch {
|
|
1085
|
+
throw new Error('Failed to decrypt backup: invalid passphrase or corrupted file.');
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
if (!Array.isArray(decrypted?.entries)) {
|
|
1089
|
+
throw new Error('Backup payload is missing account entries.');
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
return withAccountLock(
|
|
1093
|
+
() => {
|
|
1094
|
+
const index = readAccountIndex({ baseDir });
|
|
1095
|
+
const imported = [];
|
|
1096
|
+
const updated = [];
|
|
1097
|
+
|
|
1098
|
+
for (const item of decrypted.entries) {
|
|
1099
|
+
if (!item?.rawSecret) continue;
|
|
1100
|
+
const tokenInfo = parseAgyTokenPayload(item.rawSecret);
|
|
1101
|
+
const existing = matchSlotForToken(index.accounts, tokenInfo);
|
|
1102
|
+
let desiredAlias = ALIAS_REGEX.test(String(item.alias || '')) ? String(item.alias) : generateDefaultAlias(index.accounts);
|
|
1103
|
+
|
|
1104
|
+
const collision = index.accounts.find((a) => a.alias.toLowerCase() === desiredAlias.toLowerCase());
|
|
1105
|
+
if (collision && (!existing || collision.id !== existing.id)) {
|
|
1106
|
+
if (force) {
|
|
1107
|
+
deleteVaultSecret(collision, { baseDir, keyring });
|
|
1108
|
+
index.accounts = index.accounts.filter((a) => a.id !== collision.id);
|
|
1109
|
+
} else {
|
|
1110
|
+
let suffix = 2;
|
|
1111
|
+
while (index.accounts.some((a) => a.alias.toLowerCase() === `${desiredAlias}-${suffix}`.toLowerCase())) {
|
|
1112
|
+
suffix += 1;
|
|
1113
|
+
}
|
|
1114
|
+
desiredAlias = `${desiredAlias}-${suffix}`.slice(0, 32);
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
const slotId = existing?.id || createSlotId();
|
|
1119
|
+
const actualStorage = writeVaultSecret(slotId, tokenInfo.raw, { storage, baseDir, keyring });
|
|
1120
|
+
const saved = upsertSlotRecord(index, {
|
|
1121
|
+
existing: existing ? { ...existing, id: slotId } : { id: slotId, createdAt: item.createdAt || now },
|
|
1122
|
+
alias: existing && !force ? existing.alias : desiredAlias,
|
|
1123
|
+
tokenInfo,
|
|
1124
|
+
storageBackend: actualStorage,
|
|
1125
|
+
now,
|
|
1126
|
+
});
|
|
1127
|
+
if (existing) updated.push(saved.alias);
|
|
1128
|
+
else imported.push(saved.alias);
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
writeAccountIndex(index, { baseDir });
|
|
1132
|
+
return {
|
|
1133
|
+
imported,
|
|
1134
|
+
updated,
|
|
1135
|
+
total: index.accounts.length,
|
|
1136
|
+
};
|
|
1137
|
+
},
|
|
1138
|
+
{ baseDir },
|
|
1139
|
+
);
|
|
1140
|
+
}
|