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
package/src/keyring.mjs
ADDED
|
@@ -0,0 +1,604 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { writeFileAtomic } from './fs-atomic.mjs';
|
|
6
|
+
|
|
7
|
+
export const AGY_KEYRING_SERVICE = 'gemini';
|
|
8
|
+
export const AGY_KEYRING_ACCOUNT = 'antigravity';
|
|
9
|
+
export const VAULT_KEYRING_SERVICE = 'agy-bar-account';
|
|
10
|
+
export const AGY_FALLBACK_TOKEN_FILENAME = 'jetski-standalone-oauth-token';
|
|
11
|
+
|
|
12
|
+
const SAFE_IDENT_RE = /^[a-zA-Z0-9._:@/-]{1,128}$/;
|
|
13
|
+
|
|
14
|
+
export function agyFallbackTokenPath(home = homedir()) {
|
|
15
|
+
return join(home, '.gemini', AGY_FALLBACK_TOKEN_FILENAME);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function assertSafeCredentialIdentifier(value, label = 'identifier') {
|
|
19
|
+
const s = String(value ?? '').trim();
|
|
20
|
+
if (!SAFE_IDENT_RE.test(s)) {
|
|
21
|
+
throw new Error(`Invalid keyring ${label}: must match ${SAFE_IDENT_RE.source}`);
|
|
22
|
+
}
|
|
23
|
+
return s;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function decodeSecurityHexIfNeeded(raw) {
|
|
27
|
+
const str = String(raw ?? '').replace(/\r?\n$/, '');
|
|
28
|
+
if (!str) return '';
|
|
29
|
+
if (str.length >= 2 && str.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(str)) {
|
|
30
|
+
try {
|
|
31
|
+
const decoded = Buffer.from(str, 'hex').toString('utf8');
|
|
32
|
+
// Only treat as hex-encoded if the decoded text looks like valid UTF-8 JSON or printable text
|
|
33
|
+
// (macOS `security -w` hex-encodes passwords containing newlines or non-ASCII bytes).
|
|
34
|
+
const trimmed = decoded.trim();
|
|
35
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
36
|
+
JSON.parse(trimmed);
|
|
37
|
+
return decoded;
|
|
38
|
+
}
|
|
39
|
+
if (!decoded.includes('\uFFFD') && /^[\t\r\n\x20-\x7e]+$/.test(decoded)) {
|
|
40
|
+
return decoded;
|
|
41
|
+
}
|
|
42
|
+
} catch {
|
|
43
|
+
// Keep original string if it was genuinely a hex token.
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return str;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function buildMacAddGenericPasswordLine({ service, account, secret, update = false, sharedAcl = false }) {
|
|
50
|
+
const safeService = assertSafeCredentialIdentifier(service, 'service');
|
|
51
|
+
const safeAccount = assertSafeCredentialIdentifier(account, 'account');
|
|
52
|
+
const hex = Buffer.from(String(secret ?? ''), 'utf8').toString('hex');
|
|
53
|
+
const parts = ['add-generic-password'];
|
|
54
|
+
if (update) {
|
|
55
|
+
parts.push('-U');
|
|
56
|
+
} else if (sharedAcl) {
|
|
57
|
+
// Only pass -A on initial creation for shared active AGY slots so agy can read it without
|
|
58
|
+
// prompting; updates (-U) intentionally omit -A to preserve existing Keychain ACLs.
|
|
59
|
+
parts.push('-A');
|
|
60
|
+
}
|
|
61
|
+
parts.push('-a', safeAccount, '-s', safeService, '-X', hex);
|
|
62
|
+
return `${parts.join(' ')}\n`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function buildWindowsCredScript() {
|
|
66
|
+
return [
|
|
67
|
+
'$ErrorActionPreference = "Stop"',
|
|
68
|
+
'$rawIn = [Console]::In.ReadToEnd()',
|
|
69
|
+
'if (-not $rawIn) { throw "Missing stdin JSON payload" }',
|
|
70
|
+
'$req = $rawIn | ConvertFrom-Json',
|
|
71
|
+
'$code = @"',
|
|
72
|
+
'using System;',
|
|
73
|
+
'using System.Runtime.InteropServices;',
|
|
74
|
+
'using System.Runtime.InteropServices.ComTypes;',
|
|
75
|
+
'public static class AgyBarWinCred {',
|
|
76
|
+
' public const uint CRED_TYPE_GENERIC = 1;',
|
|
77
|
+
' public const uint CRED_PERSIST_LOCAL_MACHINE = 2;',
|
|
78
|
+
' [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]',
|
|
79
|
+
' public struct CREDENTIAL {',
|
|
80
|
+
' public uint Flags;',
|
|
81
|
+
' public uint Type;',
|
|
82
|
+
' public string TargetName;',
|
|
83
|
+
' public string Comment;',
|
|
84
|
+
' public FILETIME LastWritten;',
|
|
85
|
+
' public uint CredentialBlobSize;',
|
|
86
|
+
' public IntPtr CredentialBlob;',
|
|
87
|
+
' public uint Persist;',
|
|
88
|
+
' public uint AttributeCount;',
|
|
89
|
+
' public IntPtr Attributes;',
|
|
90
|
+
' public string TargetAlias;',
|
|
91
|
+
' public string UserName;',
|
|
92
|
+
' }',
|
|
93
|
+
' [DllImport("advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]',
|
|
94
|
+
' public static extern bool CredRead(string target, uint type, uint flags, out IntPtr credPtr);',
|
|
95
|
+
' [DllImport("advapi32.dll", EntryPoint = "CredWriteW", CharSet = CharSet.Unicode, SetLastError = true)]',
|
|
96
|
+
' public static extern bool CredWrite([In] ref CREDENTIAL cred, uint flags);',
|
|
97
|
+
' [DllImport("advapi32.dll", EntryPoint = "CredDeleteW", CharSet = CharSet.Unicode, SetLastError = true)]',
|
|
98
|
+
' public static extern bool CredDelete(string target, uint type, uint flags);',
|
|
99
|
+
' [DllImport("advapi32.dll", EntryPoint = "CredFree")]',
|
|
100
|
+
' public static extern void CredFree(IntPtr buffer);',
|
|
101
|
+
' public static byte[] ReadBytes(string target, out int err) {',
|
|
102
|
+
' err = 0;',
|
|
103
|
+
' IntPtr ptr;',
|
|
104
|
+
' if (!CredRead(target, CRED_TYPE_GENERIC, 0, out ptr)) {',
|
|
105
|
+
' err = Marshal.GetLastWin32Error();',
|
|
106
|
+
' return null;',
|
|
107
|
+
' }',
|
|
108
|
+
' try {',
|
|
109
|
+
' var cred = (CREDENTIAL)Marshal.PtrToStructure(ptr, typeof(CREDENTIAL));',
|
|
110
|
+
' if (cred.CredentialBlobSize == 0 || cred.CredentialBlob == IntPtr.Zero) return new byte[0];',
|
|
111
|
+
' var bytes = new byte[cred.CredentialBlobSize];',
|
|
112
|
+
' Marshal.Copy(cred.CredentialBlob, bytes, 0, (int)cred.CredentialBlobSize);',
|
|
113
|
+
' return bytes;',
|
|
114
|
+
' } finally {',
|
|
115
|
+
' CredFree(ptr);',
|
|
116
|
+
' }',
|
|
117
|
+
' }',
|
|
118
|
+
' public static int WriteBytes(string target, string userName, byte[] blob) {',
|
|
119
|
+
' IntPtr ptr = Marshal.AllocCoTaskMem(blob.Length);',
|
|
120
|
+
' try {',
|
|
121
|
+
' if (blob.Length > 0) Marshal.Copy(blob, 0, ptr, blob.Length);',
|
|
122
|
+
' var cred = new CREDENTIAL {',
|
|
123
|
+
' Type = CRED_TYPE_GENERIC,',
|
|
124
|
+
' TargetName = target,',
|
|
125
|
+
' UserName = userName,',
|
|
126
|
+
' CredentialBlobSize = (uint)blob.Length,',
|
|
127
|
+
' CredentialBlob = ptr,',
|
|
128
|
+
' Persist = CRED_PERSIST_LOCAL_MACHINE',
|
|
129
|
+
' };',
|
|
130
|
+
' if (!CredWrite(ref cred, 0)) return Marshal.GetLastWin32Error();',
|
|
131
|
+
' return 0;',
|
|
132
|
+
' } finally {',
|
|
133
|
+
' Marshal.FreeCoTaskMem(ptr);',
|
|
134
|
+
' }',
|
|
135
|
+
' }',
|
|
136
|
+
' public static int DeleteTarget(string target) {',
|
|
137
|
+
' if (!CredDelete(target, CRED_TYPE_GENERIC, 0)) return Marshal.GetLastWin32Error();',
|
|
138
|
+
' return 0;',
|
|
139
|
+
' }',
|
|
140
|
+
'}',
|
|
141
|
+
'"@',
|
|
142
|
+
'if (-not ("AgyBarWinCred" -as [type])) { Add-Type -TypeDefinition $code }',
|
|
143
|
+
'$target = [string]$req.target',
|
|
144
|
+
'$op = [string]$req.op',
|
|
145
|
+
'if ($op -eq "get" -or $op -eq "exists") {',
|
|
146
|
+
' [int]$err = 0',
|
|
147
|
+
' $bytes = [AgyBarWinCred]::ReadBytes($target, [ref]$err)',
|
|
148
|
+
' if ($null -eq $bytes) {',
|
|
149
|
+
' if ($err -eq 1168) { @{ ok = $true; found = $false } | ConvertTo-Json -Compress; exit 0 }',
|
|
150
|
+
' @{ ok = $false; code = $err } | ConvertTo-Json -Compress; exit 1',
|
|
151
|
+
' }',
|
|
152
|
+
' if ($op -eq "exists") { @{ ok = $true; found = $true } | ConvertTo-Json -Compress; exit 0 }',
|
|
153
|
+
' $b64 = [Convert]::ToBase64String($bytes)',
|
|
154
|
+
' @{ ok = $true; found = $true; secretB64 = $b64 } | ConvertTo-Json -Compress',
|
|
155
|
+
'} elseif ($op -eq "set") {',
|
|
156
|
+
' $bytes = [Convert]::FromBase64String([string]$req.secretB64)',
|
|
157
|
+
' $user = if ($req.user) { [string]$req.user } else { $target }',
|
|
158
|
+
' $err = [AgyBarWinCred]::WriteBytes($target, $user, $bytes)',
|
|
159
|
+
' if ($err -ne 0) { @{ ok = $false; code = $err } | ConvertTo-Json -Compress; exit 1 }',
|
|
160
|
+
' @{ ok = $true } | ConvertTo-Json -Compress',
|
|
161
|
+
'} elseif ($op -eq "delete") {',
|
|
162
|
+
' $err = [AgyBarWinCred]::DeleteTarget($target)',
|
|
163
|
+
' if ($err -eq 1168) { @{ ok = $true; deleted = $false } | ConvertTo-Json -Compress; exit 0 }',
|
|
164
|
+
' if ($err -ne 0) { @{ ok = $false; code = $err } | ConvertTo-Json -Compress; exit 1 }',
|
|
165
|
+
' @{ ok = $true; deleted = $true } | ConvertTo-Json -Compress',
|
|
166
|
+
'} else {',
|
|
167
|
+
' @{ ok = $false; error = "unknown op" } | ConvertTo-Json -Compress; exit 2',
|
|
168
|
+
'}',
|
|
169
|
+
].join('\n');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function decodeWindowsSecretBuffer(buf) {
|
|
173
|
+
if (!buf || buf.length === 0) return '';
|
|
174
|
+
// Detect UTF-16LE encoded ASCII/JSON (e.g. "{\0\"\0...") and decode gracefully; otherwise UTF-8.
|
|
175
|
+
if (buf.length >= 4 && buf.length % 2 === 0 && buf[1] === 0 && buf[3] === 0) {
|
|
176
|
+
return buf.toString('utf16le').replace(/\0+$/, '');
|
|
177
|
+
}
|
|
178
|
+
return buf.toString('utf8');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function defaultExec(cmd, args, options = {}) {
|
|
182
|
+
const res = spawnSync(cmd, args, {
|
|
183
|
+
encoding: 'utf8',
|
|
184
|
+
windowsHide: true,
|
|
185
|
+
timeout: options.timeout ?? 8000,
|
|
186
|
+
input: options.input,
|
|
187
|
+
env: options.env,
|
|
188
|
+
stdio: options.stdio ?? ['pipe', 'pipe', 'pipe'],
|
|
189
|
+
});
|
|
190
|
+
return {
|
|
191
|
+
status: typeof res.status === 'number' ? res.status : res.error ? 1 : 0,
|
|
192
|
+
stdout: typeof res.stdout === 'string' ? res.stdout : '',
|
|
193
|
+
stderr: typeof res.stderr === 'string' ? res.stderr : '',
|
|
194
|
+
error: res.error || null,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function isMacNotFound(res) {
|
|
199
|
+
return (
|
|
200
|
+
res.status === 44 ||
|
|
201
|
+
/could not be found in the keychain/i.test(res.stderr) ||
|
|
202
|
+
/errSecItemNotFound/i.test(res.stderr)
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function createMacKeyring({ execFn = defaultExec, env = process.env } = {}) {
|
|
207
|
+
const bin = '/usr/bin/security';
|
|
208
|
+
|
|
209
|
+
const exists = (service, account) => {
|
|
210
|
+
const s = assertSafeCredentialIdentifier(service, 'service');
|
|
211
|
+
const a = assertSafeCredentialIdentifier(account, 'account');
|
|
212
|
+
const res = execFn(bin, ['find-generic-password', '-s', s, '-a', a], {
|
|
213
|
+
env,
|
|
214
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
215
|
+
timeout: 5000,
|
|
216
|
+
});
|
|
217
|
+
if (res.error?.code === 'ENOENT') return false;
|
|
218
|
+
if (res.status === 0) return true;
|
|
219
|
+
if (isMacNotFound(res)) return false;
|
|
220
|
+
throw new Error(`macOS Keychain lookup failed (code ${res.status}): ${res.stderr.trim() || 'unknown error'}`);
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
const get = (service, account) => {
|
|
224
|
+
const s = assertSafeCredentialIdentifier(service, 'service');
|
|
225
|
+
const a = assertSafeCredentialIdentifier(account, 'account');
|
|
226
|
+
const res = execFn(bin, ['find-generic-password', '-s', s, '-a', a, '-w'], { env, timeout: 8000 });
|
|
227
|
+
if (res.error) {
|
|
228
|
+
throw new Error(`macOS Keychain unavailable: ${res.error.message}`);
|
|
229
|
+
}
|
|
230
|
+
if (res.status === 0) {
|
|
231
|
+
return decodeSecurityHexIfNeeded(res.stdout);
|
|
232
|
+
}
|
|
233
|
+
if (isMacNotFound(res)) return null;
|
|
234
|
+
throw new Error(`macOS Keychain read failed (code ${res.status}): ${res.stderr.trim() || 'access denied or locked'}`);
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const set = (service, account, secret, { sharedAcl = false } = {}) => {
|
|
238
|
+
const alreadyExists = exists(service, account);
|
|
239
|
+
const stdinCmd = buildMacAddGenericPasswordLine({
|
|
240
|
+
service,
|
|
241
|
+
account,
|
|
242
|
+
secret,
|
|
243
|
+
update: alreadyExists,
|
|
244
|
+
sharedAcl,
|
|
245
|
+
});
|
|
246
|
+
const res = execFn(bin, ['-i'], { input: stdinCmd, env, timeout: 8000 });
|
|
247
|
+
if (res.error) {
|
|
248
|
+
throw new Error(`macOS Keychain unavailable: ${res.error.message}`);
|
|
249
|
+
}
|
|
250
|
+
const errText = res.stderr.trim();
|
|
251
|
+
if (res.status !== 0 || /security:\s+SecKeychain|execution error|User interaction is not allowed|denied/i.test(errText)) {
|
|
252
|
+
throw new Error(`macOS Keychain write failed: ${errText || `exit ${res.status}`}`);
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
const del = (service, account) => {
|
|
257
|
+
const s = assertSafeCredentialIdentifier(service, 'service');
|
|
258
|
+
const a = assertSafeCredentialIdentifier(account, 'account');
|
|
259
|
+
const res = execFn(bin, ['delete-generic-password', '-s', s, '-a', a], { env, timeout: 5000 });
|
|
260
|
+
if (res.error) {
|
|
261
|
+
throw new Error(`macOS Keychain unavailable: ${res.error.message}`);
|
|
262
|
+
}
|
|
263
|
+
if (res.status === 0) return true;
|
|
264
|
+
if (isMacNotFound(res)) return false;
|
|
265
|
+
throw new Error(`macOS Keychain delete failed (code ${res.status}): ${res.stderr.trim() || 'unknown error'}`);
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
const probe = () => {
|
|
269
|
+
if (execFn !== defaultExec) return true;
|
|
270
|
+
return existsSync(bin);
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
return {
|
|
274
|
+
kind: 'macos-keychain',
|
|
275
|
+
label: 'macOS Keychain',
|
|
276
|
+
isAvailable: probe,
|
|
277
|
+
exists,
|
|
278
|
+
get,
|
|
279
|
+
set,
|
|
280
|
+
delete: del,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function isLinuxSecretServiceUnavailable(res) {
|
|
285
|
+
if (res.error?.code === 'ENOENT') return true;
|
|
286
|
+
const err = `${res.stderr} ${res.error?.message || ''}`;
|
|
287
|
+
return /Cannot autolaunch D-Bus|org\.freedesktop\.secrets|No such interface|Failed to execute child process|GDBus\.Error|Could not connect|session bus/i.test(
|
|
288
|
+
err,
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function createLinuxKeyring({ execFn = defaultExec, env = process.env } = {}) {
|
|
293
|
+
let cachedAvailable = null;
|
|
294
|
+
|
|
295
|
+
const isAvailable = () => {
|
|
296
|
+
if (cachedAvailable !== null) return cachedAvailable;
|
|
297
|
+
const res = execFn('secret-tool', ['--version'], { env, timeout: 3000 });
|
|
298
|
+
if (res.error?.code === 'ENOENT') {
|
|
299
|
+
cachedAvailable = false;
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
// Headless SSH sessions without D-Bus session bus cannot reach Secret Service.
|
|
303
|
+
if (!env?.DBUS_SESSION_BUS_ADDRESS && !env?.DISPLAY && !env?.WAYLAND_DISPLAY) {
|
|
304
|
+
const probe = execFn('secret-tool', ['lookup', 'service', 'agy-bar-probe', 'username', 'probe'], {
|
|
305
|
+
env,
|
|
306
|
+
timeout: 3000,
|
|
307
|
+
});
|
|
308
|
+
if (isLinuxSecretServiceUnavailable(probe)) {
|
|
309
|
+
cachedAvailable = false;
|
|
310
|
+
return false;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
cachedAvailable = true;
|
|
314
|
+
return true;
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
const get = (service, account) => {
|
|
318
|
+
const s = assertSafeCredentialIdentifier(service, 'service');
|
|
319
|
+
const a = assertSafeCredentialIdentifier(account, 'account');
|
|
320
|
+
const res = execFn('secret-tool', ['lookup', 'service', s, 'username', a], { env, timeout: 5000 });
|
|
321
|
+
if (isLinuxSecretServiceUnavailable(res)) {
|
|
322
|
+
cachedAvailable = false;
|
|
323
|
+
const err = new Error('Linux Secret Service (secret-tool / D-Bus) is unavailable');
|
|
324
|
+
err.code = 'KEYRING_UNAVAILABLE';
|
|
325
|
+
throw err;
|
|
326
|
+
}
|
|
327
|
+
if (res.status === 0) {
|
|
328
|
+
return res.stdout.replace(/\r?\n$/, '');
|
|
329
|
+
}
|
|
330
|
+
if (res.status === 1 && !res.stderr.trim()) {
|
|
331
|
+
return null;
|
|
332
|
+
}
|
|
333
|
+
throw new Error(`Linux secret-tool read failed (code ${res.status}): ${res.stderr.trim() || 'unknown error'}`);
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
const set = (service, account, secret) => {
|
|
337
|
+
const s = assertSafeCredentialIdentifier(service, 'service');
|
|
338
|
+
const a = assertSafeCredentialIdentifier(account, 'account');
|
|
339
|
+
const label = s === AGY_KEYRING_SERVICE ? 'Antigravity CLI' : `agy-bar (${a})`;
|
|
340
|
+
const res = execFn('secret-tool', ['store', `--label=${label}`, 'service', s, 'username', a], {
|
|
341
|
+
input: String(secret ?? ''),
|
|
342
|
+
env,
|
|
343
|
+
timeout: 8000,
|
|
344
|
+
});
|
|
345
|
+
if (isLinuxSecretServiceUnavailable(res)) {
|
|
346
|
+
cachedAvailable = false;
|
|
347
|
+
const err = new Error('Linux Secret Service (secret-tool / D-Bus) is unavailable');
|
|
348
|
+
err.code = 'KEYRING_UNAVAILABLE';
|
|
349
|
+
throw err;
|
|
350
|
+
}
|
|
351
|
+
if (res.status !== 0) {
|
|
352
|
+
throw new Error(`Linux secret-tool write failed (code ${res.status}): ${res.stderr.trim() || 'unknown error'}`);
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
const del = (service, account) => {
|
|
357
|
+
const s = assertSafeCredentialIdentifier(service, 'service');
|
|
358
|
+
const a = assertSafeCredentialIdentifier(account, 'account');
|
|
359
|
+
const res = execFn('secret-tool', ['clear', 'service', s, 'username', a], { env, timeout: 5000 });
|
|
360
|
+
if (isLinuxSecretServiceUnavailable(res)) {
|
|
361
|
+
cachedAvailable = false;
|
|
362
|
+
const err = new Error('Linux Secret Service (secret-tool / D-Bus) is unavailable');
|
|
363
|
+
err.code = 'KEYRING_UNAVAILABLE';
|
|
364
|
+
throw err;
|
|
365
|
+
}
|
|
366
|
+
if (res.status === 0) return true;
|
|
367
|
+
if (res.status === 1 && !res.stderr.trim()) return false;
|
|
368
|
+
throw new Error(`Linux secret-tool delete failed (code ${res.status}): ${res.stderr.trim() || 'unknown error'}`);
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
const exists = (service, account) => get(service, account) !== null;
|
|
372
|
+
|
|
373
|
+
return {
|
|
374
|
+
kind: 'linux-secret-service',
|
|
375
|
+
label: 'Linux Secret Service (secret-tool)',
|
|
376
|
+
isAvailable,
|
|
377
|
+
exists,
|
|
378
|
+
get,
|
|
379
|
+
set,
|
|
380
|
+
delete: del,
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function createWindowsKeyring({ execFn = defaultExec, env = process.env } = {}) {
|
|
385
|
+
const encodedScript = Buffer.from(buildWindowsCredScript(), 'utf16le').toString('base64');
|
|
386
|
+
const psArgs = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encodedScript];
|
|
387
|
+
let cachedAvailable = null;
|
|
388
|
+
|
|
389
|
+
const invoke = (payload) => {
|
|
390
|
+
const res = execFn('powershell.exe', psArgs, {
|
|
391
|
+
input: JSON.stringify(payload),
|
|
392
|
+
env,
|
|
393
|
+
timeout: 12_000,
|
|
394
|
+
});
|
|
395
|
+
if (res.error?.code === 'ENOENT') {
|
|
396
|
+
cachedAvailable = false;
|
|
397
|
+
const err = new Error('Windows PowerShell is unavailable for Credential Manager access');
|
|
398
|
+
err.code = 'KEYRING_UNAVAILABLE';
|
|
399
|
+
throw err;
|
|
400
|
+
}
|
|
401
|
+
const line = res.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || '';
|
|
402
|
+
let parsed = null;
|
|
403
|
+
try {
|
|
404
|
+
parsed = line ? JSON.parse(line) : null;
|
|
405
|
+
} catch {
|
|
406
|
+
parsed = null;
|
|
407
|
+
}
|
|
408
|
+
if (parsed && parsed.ok === true) {
|
|
409
|
+
cachedAvailable = true;
|
|
410
|
+
return parsed;
|
|
411
|
+
}
|
|
412
|
+
const detail = parsed?.code
|
|
413
|
+
? `Win32 error ${parsed.code}`
|
|
414
|
+
: parsed?.error || res.stderr.trim() || `exit ${res.status}`;
|
|
415
|
+
throw new Error(`Windows Credential Manager ${payload.op} failed: ${detail}`);
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
const targetOf = (service, account) => {
|
|
419
|
+
const s = assertSafeCredentialIdentifier(service, 'service');
|
|
420
|
+
const a = assertSafeCredentialIdentifier(account, 'account');
|
|
421
|
+
return `${s}:${a}`;
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
const isAvailable = () => {
|
|
425
|
+
if (cachedAvailable !== null) return cachedAvailable;
|
|
426
|
+
if (execFn !== defaultExec) return true;
|
|
427
|
+
const probe = execFn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '1'], { env, timeout: 4000 });
|
|
428
|
+
cachedAvailable = !probe.error && probe.status === 0;
|
|
429
|
+
return cachedAvailable;
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
return {
|
|
433
|
+
kind: 'windows-credman',
|
|
434
|
+
label: 'Windows Credential Manager',
|
|
435
|
+
isAvailable,
|
|
436
|
+
exists(service, account) {
|
|
437
|
+
const out = invoke({ op: 'exists', target: targetOf(service, account) });
|
|
438
|
+
return Boolean(out.found);
|
|
439
|
+
},
|
|
440
|
+
get(service, account) {
|
|
441
|
+
const out = invoke({ op: 'get', target: targetOf(service, account) });
|
|
442
|
+
if (!out.found) return null;
|
|
443
|
+
return decodeWindowsSecretBuffer(Buffer.from(String(out.secretB64 || ''), 'base64'));
|
|
444
|
+
},
|
|
445
|
+
set(service, account, secret) {
|
|
446
|
+
const a = assertSafeCredentialIdentifier(account, 'account');
|
|
447
|
+
invoke({
|
|
448
|
+
op: 'set',
|
|
449
|
+
target: targetOf(service, account),
|
|
450
|
+
user: a,
|
|
451
|
+
secretB64: Buffer.from(String(secret ?? ''), 'utf8').toString('base64'),
|
|
452
|
+
});
|
|
453
|
+
},
|
|
454
|
+
delete(service, account) {
|
|
455
|
+
const out = invoke({ op: 'delete', target: targetOf(service, account) });
|
|
456
|
+
return Boolean(out.deleted);
|
|
457
|
+
},
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
export function createMemoryKeyring(initial = {}, { available = true, kind = 'memory' } = {}) {
|
|
462
|
+
const store = new Map();
|
|
463
|
+
for (const [key, value] of Object.entries(initial)) {
|
|
464
|
+
if (typeof value === 'string') store.set(key, value);
|
|
465
|
+
}
|
|
466
|
+
const keyOf = (service, account) => `${service}\0${account}`;
|
|
467
|
+
const ops = [];
|
|
468
|
+
return {
|
|
469
|
+
kind,
|
|
470
|
+
label: `In-memory (${kind})`,
|
|
471
|
+
ops,
|
|
472
|
+
isAvailable: () => available,
|
|
473
|
+
exists(service, account) {
|
|
474
|
+
if (!available) {
|
|
475
|
+
const err = new Error('Keyring unavailable');
|
|
476
|
+
err.code = 'KEYRING_UNAVAILABLE';
|
|
477
|
+
throw err;
|
|
478
|
+
}
|
|
479
|
+
return store.has(keyOf(service, account));
|
|
480
|
+
},
|
|
481
|
+
get(service, account) {
|
|
482
|
+
if (!available) {
|
|
483
|
+
const err = new Error('Keyring unavailable');
|
|
484
|
+
err.code = 'KEYRING_UNAVAILABLE';
|
|
485
|
+
throw err;
|
|
486
|
+
}
|
|
487
|
+
return store.has(keyOf(service, account)) ? store.get(keyOf(service, account)) : null;
|
|
488
|
+
},
|
|
489
|
+
set(service, account, secret, opts = {}) {
|
|
490
|
+
if (!available) {
|
|
491
|
+
const err = new Error('Keyring unavailable');
|
|
492
|
+
err.code = 'KEYRING_UNAVAILABLE';
|
|
493
|
+
throw err;
|
|
494
|
+
}
|
|
495
|
+
ops.push({ op: 'set', service, account, sharedAcl: Boolean(opts.sharedAcl) });
|
|
496
|
+
store.set(keyOf(service, account), String(secret ?? ''));
|
|
497
|
+
},
|
|
498
|
+
delete(service, account) {
|
|
499
|
+
if (!available) {
|
|
500
|
+
const err = new Error('Keyring unavailable');
|
|
501
|
+
err.code = 'KEYRING_UNAVAILABLE';
|
|
502
|
+
throw err;
|
|
503
|
+
}
|
|
504
|
+
ops.push({ op: 'delete', service, account });
|
|
505
|
+
return store.delete(keyOf(service, account));
|
|
506
|
+
},
|
|
507
|
+
dumpKeys() {
|
|
508
|
+
return [...store.keys()];
|
|
509
|
+
},
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
export function createKeyringBackend({ platform = process.platform, env = process.env, execFn = defaultExec } = {}) {
|
|
514
|
+
if (platform === 'darwin') return createMacKeyring({ execFn, env });
|
|
515
|
+
if (platform === 'win32') return createWindowsKeyring({ execFn, env });
|
|
516
|
+
if (platform === 'linux') return createLinuxKeyring({ execFn, env });
|
|
517
|
+
return createMemoryKeyring({}, { available: false, kind: `unsupported-${platform}` });
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
export function readActiveAgyCredential({ home = homedir(), keyring = createKeyringBackend() } = {}) {
|
|
521
|
+
let keyringError = null;
|
|
522
|
+
if (keyring?.isAvailable?.()) {
|
|
523
|
+
try {
|
|
524
|
+
const fromKeyring = keyring.get(AGY_KEYRING_SERVICE, AGY_KEYRING_ACCOUNT);
|
|
525
|
+
if (typeof fromKeyring === 'string' && fromKeyring.trim()) {
|
|
526
|
+
return { raw: fromKeyring.trim(), source: 'keyring', keyringKind: keyring.kind };
|
|
527
|
+
}
|
|
528
|
+
} catch (err) {
|
|
529
|
+
keyringError = err;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const fallbackPath = agyFallbackTokenPath(home);
|
|
534
|
+
if (existsSync(fallbackPath)) {
|
|
535
|
+
try {
|
|
536
|
+
const fromFile = readFileSync(fallbackPath, 'utf8').trim();
|
|
537
|
+
if (fromFile) {
|
|
538
|
+
return { raw: fromFile, source: 'file', filePath: fallbackPath, keyringKind: keyring?.kind || 'none' };
|
|
539
|
+
}
|
|
540
|
+
} catch {
|
|
541
|
+
// Ignore unreadable fallback file if keyring error is more informative.
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
if (keyringError && keyringError.code !== 'KEYRING_UNAVAILABLE') {
|
|
546
|
+
throw keyringError;
|
|
547
|
+
}
|
|
548
|
+
return null;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
export function writeActiveAgyCredential(rawSecret, { home = homedir(), keyring = createKeyringBackend() } = {}) {
|
|
552
|
+
const payload = String(rawSecret ?? '').trim();
|
|
553
|
+
if (!payload) {
|
|
554
|
+
throw new Error('Refusing to write an empty Antigravity credential.');
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
let wroteKeyring = false;
|
|
558
|
+
let keyringWarning = null;
|
|
559
|
+
if (keyring?.isAvailable?.()) {
|
|
560
|
+
try {
|
|
561
|
+
keyring.set(AGY_KEYRING_SERVICE, AGY_KEYRING_ACCOUNT, payload, { sharedAcl: true });
|
|
562
|
+
wroteKeyring = true;
|
|
563
|
+
} catch (err) {
|
|
564
|
+
if (err?.code === 'KEYRING_UNAVAILABLE') {
|
|
565
|
+
keyringWarning = err.message;
|
|
566
|
+
} else {
|
|
567
|
+
throw err;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
const fallbackPath = agyFallbackTokenPath(home);
|
|
573
|
+
writeFileAtomic(fallbackPath, `${payload}\n`, { mode: 0o600, dirMode: 0o700 });
|
|
574
|
+
|
|
575
|
+
return {
|
|
576
|
+
wroteKeyring,
|
|
577
|
+
wroteFile: true,
|
|
578
|
+
filePath: fallbackPath,
|
|
579
|
+
keyringKind: keyring?.kind || 'none',
|
|
580
|
+
keyringWarning,
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
export function clearActiveAgyCredential({ home = homedir(), keyring = createKeyringBackend() } = {}) {
|
|
585
|
+
let clearedKeyring = false;
|
|
586
|
+
if (keyring?.isAvailable?.()) {
|
|
587
|
+
try {
|
|
588
|
+
clearedKeyring = Boolean(keyring.delete(AGY_KEYRING_SERVICE, AGY_KEYRING_ACCOUNT));
|
|
589
|
+
} catch (err) {
|
|
590
|
+
if (err?.code !== 'KEYRING_UNAVAILABLE') {
|
|
591
|
+
throw err;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const fallbackPath = agyFallbackTokenPath(home);
|
|
597
|
+
let clearedFile = false;
|
|
598
|
+
if (existsSync(fallbackPath)) {
|
|
599
|
+
rmSync(fallbackPath, { force: true });
|
|
600
|
+
clearedFile = true;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
return { clearedKeyring, clearedFile };
|
|
604
|
+
}
|