@dennisonbertram/agent-drive 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +10 -2
- package/dist/SKILL.md +118 -0
- package/dist/backup-targets.d.ts +24 -0
- package/dist/backup-targets.js +104 -0
- package/dist/backup-targets.js.map +1 -0
- package/dist/backup.d.ts +16 -0
- package/dist/backup.js +151 -0
- package/dist/backup.js.map +1 -0
- package/dist/capture-codex.d.ts +5 -0
- package/dist/capture-codex.js +40 -0
- package/dist/capture-codex.js.map +1 -0
- package/dist/capture-spool.d.ts +58 -0
- package/dist/capture-spool.js +299 -0
- package/dist/capture-spool.js.map +1 -0
- package/dist/capture.d.ts +66 -0
- package/dist/capture.js +536 -0
- package/dist/capture.js.map +1 -0
- package/dist/check.d.ts +17 -0
- package/dist/check.js +119 -0
- package/dist/check.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +584 -0
- package/dist/cli.js.map +1 -0
- package/dist/client.d.ts +259 -0
- package/dist/client.js +456 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +41 -0
- package/dist/config.js +220 -0
- package/dist/config.js.map +1 -0
- package/dist/credentials.d.ts +108 -0
- package/dist/credentials.js +336 -0
- package/dist/credentials.js.map +1 -0
- package/dist/crypto-format.d.ts +8 -0
- package/dist/crypto-format.js +96 -0
- package/dist/crypto-format.js.map +1 -0
- package/dist/crypto.d.ts +20 -0
- package/dist/crypto.js +124 -0
- package/dist/crypto.js.map +1 -0
- package/dist/device.d.ts +33 -0
- package/dist/device.js +229 -0
- package/dist/device.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp.d.ts +7 -0
- package/dist/mcp.js +348 -0
- package/dist/mcp.js.map +1 -0
- package/dist/safe-write.d.ts +9 -0
- package/dist/safe-write.js +34 -0
- package/dist/safe-write.js.map +1 -0
- package/dist/seal.d.ts +12 -0
- package/dist/seal.js +49 -0
- package/dist/seal.js.map +1 -0
- package/dist/skill.d.ts +4 -0
- package/dist/skill.js +42 -0
- package/dist/skill.js.map +1 -0
- package/dist/sync.d.ts +13 -0
- package/dist/sync.js +301 -0
- package/dist/sync.js.map +1 -0
- package/dist/trace-inbox.d.ts +26 -0
- package/dist/trace-inbox.js +126 -0
- package/dist/trace-inbox.js.map +1 -0
- package/dist/trace-path.d.ts +10 -0
- package/dist/trace-path.js +18 -0
- package/dist/trace-path.js.map +1 -0
- package/package.json +61 -4
package/dist/config.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { chmod, mkdir, open, readFile, rename, rm, rmdir } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { hostname, homedir } from 'node:os';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { decodeDriveKey } from './crypto.js';
|
|
6
|
+
import { loadConfig } from './credentials.js';
|
|
7
|
+
export const DEFAULT_API_URL = 'https://agentdrive.xyz/api';
|
|
8
|
+
export async function resolveLoginApiUrl(flag) {
|
|
9
|
+
return flag ?? process.env.AGENT_DRIVE_API_URL ?? (await readConfig()).apiUrl ?? DEFAULT_API_URL;
|
|
10
|
+
}
|
|
11
|
+
/** The --drive flag, else the only drive key saved for this API origin, else an error naming the choices. */
|
|
12
|
+
export function resolveDriveId(flag, config, apiUrl) {
|
|
13
|
+
if (flag)
|
|
14
|
+
return flag;
|
|
15
|
+
const origin = originOf(apiUrl);
|
|
16
|
+
const ids = Object.keys(config.driveKeys ?? {}).filter((id) => config.driveKeyOrigins?.[id] === origin);
|
|
17
|
+
if (ids.length === 1)
|
|
18
|
+
return ids[0];
|
|
19
|
+
throw new Error(`A --drive ID is required. ${ids.length ? `Configured drives for this API: ${ids.join(', ')}.` : 'No drive key is configured for this API.'}`);
|
|
20
|
+
}
|
|
21
|
+
export function configPath() {
|
|
22
|
+
return process.env.AGENT_DRIVE_CONFIG ?? join(homedir(), '.config', 'agent-drive', 'config.json');
|
|
23
|
+
}
|
|
24
|
+
export async function readConfig() {
|
|
25
|
+
let serialized;
|
|
26
|
+
try {
|
|
27
|
+
serialized = await readFile(configPath(), 'utf8');
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {
|
|
31
|
+
return {};
|
|
32
|
+
}
|
|
33
|
+
throw new Error('Unable to read Agent Drive configuration.');
|
|
34
|
+
}
|
|
35
|
+
let value;
|
|
36
|
+
try {
|
|
37
|
+
value = JSON.parse(serialized);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new Error('Agent Drive configuration is malformed; refusing to overwrite it.');
|
|
41
|
+
}
|
|
42
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
43
|
+
throw new Error('Agent Drive configuration is malformed; refusing to overwrite it.');
|
|
44
|
+
}
|
|
45
|
+
const record = value;
|
|
46
|
+
if ((record.apiUrl !== undefined && typeof record.apiUrl !== 'string') ||
|
|
47
|
+
(record.apiKey !== undefined && typeof record.apiKey !== 'string') ||
|
|
48
|
+
(record.driveKeys !== undefined &&
|
|
49
|
+
(!record.driveKeys ||
|
|
50
|
+
typeof record.driveKeys !== 'object' ||
|
|
51
|
+
Array.isArray(record.driveKeys) ||
|
|
52
|
+
Object.values(record.driveKeys).some((key) => typeof key !== 'string'))) ||
|
|
53
|
+
(record.driveKeyOrigins !== undefined &&
|
|
54
|
+
(!record.driveKeyOrigins ||
|
|
55
|
+
typeof record.driveKeyOrigins !== 'object' ||
|
|
56
|
+
Array.isArray(record.driveKeyOrigins) ||
|
|
57
|
+
Object.values(record.driveKeyOrigins).some((origin) => typeof origin !== 'string'))) ||
|
|
58
|
+
(record.keyBackup !== undefined &&
|
|
59
|
+
(!record.keyBackup ||
|
|
60
|
+
typeof record.keyBackup !== 'object' ||
|
|
61
|
+
Array.isArray(record.keyBackup))) ||
|
|
62
|
+
(record.pendingExport != null &&
|
|
63
|
+
(typeof record.pendingExport !== 'object' ||
|
|
64
|
+
typeof record.pendingExport.apiKeyHash !== 'string' ||
|
|
65
|
+
!Array.isArray(record.pendingExport.driveIds)))) {
|
|
66
|
+
throw new Error('Agent Drive configuration is malformed; refusing to overwrite it.');
|
|
67
|
+
}
|
|
68
|
+
// One-time migration: a key saved before origins were recorded belongs to the saved apiUrl's
|
|
69
|
+
// origin. It is persisted by the next writeConfig, which merges what readConfig returns.
|
|
70
|
+
const legacyOrigin = typeof record.apiUrl === 'string' ? originOf(record.apiUrl) : undefined;
|
|
71
|
+
const keys = (record.driveKeys ?? {});
|
|
72
|
+
const origins = { ...record.driveKeyOrigins };
|
|
73
|
+
if (legacyOrigin)
|
|
74
|
+
for (const id of Object.keys(keys))
|
|
75
|
+
if (origins[id] === undefined)
|
|
76
|
+
origins[id] = legacyOrigin;
|
|
77
|
+
return {
|
|
78
|
+
...(typeof record.apiUrl === 'string' ? { apiUrl: record.apiUrl } : {}),
|
|
79
|
+
...(typeof record.apiKey === 'string' ? { apiKey: record.apiKey } : {}),
|
|
80
|
+
...(record.driveKeys !== undefined
|
|
81
|
+
? { driveKeys: { ...record.driveKeys } }
|
|
82
|
+
: {}),
|
|
83
|
+
...(Object.keys(origins).length || record.driveKeyOrigins !== undefined
|
|
84
|
+
? { driveKeyOrigins: origins }
|
|
85
|
+
: {}),
|
|
86
|
+
...(record.keyBackup !== undefined
|
|
87
|
+
? { keyBackup: { ...record.keyBackup } }
|
|
88
|
+
: {}),
|
|
89
|
+
...(record.pendingExport != null
|
|
90
|
+
? { pendingExport: record.pendingExport }
|
|
91
|
+
: {}),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function originOf(url) {
|
|
95
|
+
try {
|
|
96
|
+
return new URL(url).origin;
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
export async function writeConfig(config) {
|
|
103
|
+
const path = configPath();
|
|
104
|
+
const directory = dirname(path);
|
|
105
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
106
|
+
const lockPath = `${path}.lock`;
|
|
107
|
+
const timeoutAt = Date.now() + 10_000;
|
|
108
|
+
while (true) {
|
|
109
|
+
try {
|
|
110
|
+
await mkdir(lockPath, { mode: 0o700 });
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
if (!isCode(error, 'EEXIST')) {
|
|
115
|
+
throw new Error(`Unable to acquire configuration lock at ${lockPath}.`);
|
|
116
|
+
}
|
|
117
|
+
if (Date.now() >= timeoutAt) {
|
|
118
|
+
throw new Error(`Timed out waiting for configuration lock at ${lockPath}. If no Agent Drive command is running, remove the stale lock directory manually.`);
|
|
119
|
+
}
|
|
120
|
+
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
124
|
+
let temporaryCreated = false;
|
|
125
|
+
let backupsCleared = false;
|
|
126
|
+
try {
|
|
127
|
+
const current = await readConfig();
|
|
128
|
+
// A new API key invalidates every exported bundle, so earlier backup records are stale.
|
|
129
|
+
const keyChanged = config.apiKey !== undefined && config.apiKey !== current.apiKey;
|
|
130
|
+
backupsCleared = keyChanged && Object.keys(current.keyBackup ?? {}).length > 0;
|
|
131
|
+
const previousBackup = keyChanged ? undefined : current.keyBackup;
|
|
132
|
+
const mergedDriveKeys = { ...current.driveKeys, ...config.driveKeys };
|
|
133
|
+
const merged = {
|
|
134
|
+
...current,
|
|
135
|
+
...Object.fromEntries(Object.entries(config).filter(([, value]) => value !== undefined)),
|
|
136
|
+
...(current.driveKeys || config.driveKeys ? { driveKeys: mergedDriveKeys } : {}),
|
|
137
|
+
...(current.driveKeyOrigins || config.driveKeyOrigins
|
|
138
|
+
? { driveKeyOrigins: { ...current.driveKeyOrigins, ...config.driveKeyOrigins } }
|
|
139
|
+
: {}),
|
|
140
|
+
...(previousBackup || config.keyBackup
|
|
141
|
+
? { keyBackup: { ...previousBackup, ...config.keyBackup } }
|
|
142
|
+
: {}),
|
|
143
|
+
};
|
|
144
|
+
if (keyChanged && !config.keyBackup)
|
|
145
|
+
delete merged.keyBackup;
|
|
146
|
+
if (merged.pendingExport === null)
|
|
147
|
+
delete merged.pendingExport;
|
|
148
|
+
const handle = await open(temporary, 'wx', 0o600);
|
|
149
|
+
temporaryCreated = true;
|
|
150
|
+
try {
|
|
151
|
+
await handle.chmod(0o600);
|
|
152
|
+
await handle.writeFile(`${JSON.stringify(merged, null, 2)}\n`, 'utf8');
|
|
153
|
+
await handle.sync();
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
await handle.close();
|
|
157
|
+
}
|
|
158
|
+
await rename(temporary, path);
|
|
159
|
+
await chmod(path, 0o600);
|
|
160
|
+
}
|
|
161
|
+
finally {
|
|
162
|
+
try {
|
|
163
|
+
if (temporaryCreated)
|
|
164
|
+
await rm(temporary, { force: true });
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
try {
|
|
168
|
+
await rmdir(lockPath);
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
if (!isCode(error, 'ENOENT')) {
|
|
172
|
+
throw new Error(`Unable to release configuration lock at ${lockPath}.`);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return { backupsCleared };
|
|
178
|
+
}
|
|
179
|
+
function isCode(error, code) {
|
|
180
|
+
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
|
|
181
|
+
}
|
|
182
|
+
export function machineName() {
|
|
183
|
+
return process.env.AGENT_DRIVE_MACHINE ?? hostname();
|
|
184
|
+
}
|
|
185
|
+
/** A saved key is trusted for an origin only if it was saved for it and decodes to 32 bytes. */
|
|
186
|
+
export function keysForOrigin(config, origin) {
|
|
187
|
+
return Object.fromEntries(Object.entries(config.driveKeys ?? {}).filter(([id, key]) => config.driveKeyOrigins?.[id] === origin && isValidDriveKey(key)));
|
|
188
|
+
}
|
|
189
|
+
export function isValidDriveKey(key) {
|
|
190
|
+
try {
|
|
191
|
+
decodeDriveKey(key);
|
|
192
|
+
return true;
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
export function driveKeyEnvironmentName(driveId) {
|
|
199
|
+
return `AGENT_DRIVE_KEY_${driveId.toUpperCase().replace(/[^A-Z0-9]/gu, '_')}`;
|
|
200
|
+
}
|
|
201
|
+
export async function resolveConnection() {
|
|
202
|
+
const saved = await loadConfig();
|
|
203
|
+
const apiUrl = process.env.AGENT_DRIVE_API_URL || saved.apiUrl || DEFAULT_API_URL;
|
|
204
|
+
const apiKey = process.env.AGENT_DRIVE_API_KEY || saved.apiKey;
|
|
205
|
+
if (!apiUrl || !apiKey) {
|
|
206
|
+
throw new Error('API configuration is missing. Run `agent-drive login` or set AGENT_DRIVE_API_URL and AGENT_DRIVE_API_KEY.');
|
|
207
|
+
}
|
|
208
|
+
return { apiUrl, apiKey, config: saved };
|
|
209
|
+
}
|
|
210
|
+
export async function resolveDriveKey(driveId, keyFile, config) {
|
|
211
|
+
const fromDriveEnvironment = process.env[driveKeyEnvironmentName(driveId)];
|
|
212
|
+
if (fromDriveEnvironment)
|
|
213
|
+
return fromDriveEnvironment.trim();
|
|
214
|
+
if (process.env.AGENT_DRIVE_KEY)
|
|
215
|
+
return process.env.AGENT_DRIVE_KEY.trim();
|
|
216
|
+
if (keyFile)
|
|
217
|
+
return (await readFile(keyFile, 'utf8')).trim();
|
|
218
|
+
return config?.driveKeys?.[driveId];
|
|
219
|
+
}
|
|
220
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"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AAM,UAAU,EAAE,CAAC;IACjC,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,KAAK,CAAC,MAAM,IAAI,eAAe,CAAC;IAClF,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,KAAK,CAAC,MAAM,CAAC;IAC/D,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CACb,2GAA2G,CAC5G,CAAC;IACJ,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AAC3C,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,OAAe,EACf,OAAgB,EAChB,MAAyB;IAEzB,MAAM,oBAAoB,GAAG,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC,CAAC;IAC3E,IAAI,oBAAoB;QAAE,OAAO,oBAAoB,CAAC,IAAI,EAAE,CAAC;IAC7D,IAAI,OAAO,CAAC,GAAG,CAAC,eAAe;QAAE,OAAO,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,EAAE,CAAC;IAC3E,IAAI,OAAO;QAAE,OAAO,CAAC,MAAM,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAC7D,OAAO,MAAM,EAAE,SAAS,EAAE,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC"}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { type AgentDriveClient } from './client.js';
|
|
2
|
+
import { type TargetDeps } from './backup-targets.js';
|
|
3
|
+
import { type AgentDriveConfig } from './config.js';
|
|
4
|
+
export declare const BUNDLE_PREFIX = "adcred1.";
|
|
5
|
+
export type Bundle = {
|
|
6
|
+
v: 1;
|
|
7
|
+
apiUrl: string;
|
|
8
|
+
apiKey: string;
|
|
9
|
+
driveKeys: Record<string, string>;
|
|
10
|
+
driveKeyOrigins: Record<string, string>;
|
|
11
|
+
};
|
|
12
|
+
export declare const BACKUP_HINT = "Back up this agent's credentials before this machine or sandbox goes away: `agent-drive credentials export --to 1password` (1Password), `agent-drive credentials export --to clipboard` (copy, paste it into Apple Passwords or another password manager, then run `agent-drive credentials confirm`), or `agent-drive credentials export --to <a file outside the sandbox, on a path that survives it>`. Until then `agent-drive check` will not pass.";
|
|
13
|
+
export declare function encodeBundle(bundle: Bundle): string;
|
|
14
|
+
/** A bundle holding only the named drives' keys (all of them when `driveIds` is omitted). */
|
|
15
|
+
export declare function buildBundle(source: Pick<Bundle, 'apiUrl' | 'apiKey'> & Partial<Pick<Bundle, 'driveKeys' | 'driveKeyOrigins'>>, driveIds?: string[]): string;
|
|
16
|
+
export declare function decodeBundle(text: string): Bundle;
|
|
17
|
+
/** The AGENT_DRIVE_CREDENTIALS bundle, if set. Errors never include its content. */
|
|
18
|
+
export declare function envBundle(): Bundle | undefined;
|
|
19
|
+
/**
|
|
20
|
+
* The saved config with the environment bundle merged in memory. Saved values win over the
|
|
21
|
+
* bundle (a later login is newer than a stored backup); bundle drives count as backed up.
|
|
22
|
+
* Never write the result back: writeConfig re-reads the file itself.
|
|
23
|
+
*/
|
|
24
|
+
export declare function loadConfig(): Promise<AgentDriveConfig>;
|
|
25
|
+
export declare function unbackedUp(config: AgentDriveConfig, driveIds: string[]): string[];
|
|
26
|
+
type Io = {
|
|
27
|
+
isTTY: boolean;
|
|
28
|
+
write: (text: string) => Promise<void>;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Mints a new agent's key through a `delegate` key and prints a bundle holding only that key and
|
|
32
|
+
* the chosen drive's key. The caller's own key and saved config are never part of it or changed.
|
|
33
|
+
*/
|
|
34
|
+
export declare function issueCredentials(options: {
|
|
35
|
+
name: string;
|
|
36
|
+
drive?: string;
|
|
37
|
+
scopes?: string[];
|
|
38
|
+
writePaths?: string[];
|
|
39
|
+
label?: string;
|
|
40
|
+
machine?: string;
|
|
41
|
+
to?: string;
|
|
42
|
+
force?: boolean;
|
|
43
|
+
stdout?: boolean;
|
|
44
|
+
}, io: Io, createKey: AgentDriveClient['createKey']): Promise<{
|
|
45
|
+
agentName: string;
|
|
46
|
+
keyId: string;
|
|
47
|
+
scopes: string[];
|
|
48
|
+
writePaths: string[];
|
|
49
|
+
}>;
|
|
50
|
+
/**
|
|
51
|
+
* Writes a bundle to a 0600 file (recorded as a backup) or to a non-TTY stdout. A stdout export
|
|
52
|
+
* is not recorded: pipe it to a secret store, then run `agent-drive credentials confirm`.
|
|
53
|
+
*/
|
|
54
|
+
export declare function exportCredentials(options: {
|
|
55
|
+
to?: string;
|
|
56
|
+
force?: boolean;
|
|
57
|
+
stdout?: boolean;
|
|
58
|
+
vault?: string;
|
|
59
|
+
keepClipboard?: boolean;
|
|
60
|
+
}, io: Io, deps?: TargetDeps): Promise<{
|
|
61
|
+
method: "stdout";
|
|
62
|
+
target: undefined;
|
|
63
|
+
clearing: undefined;
|
|
64
|
+
driveIds: string[];
|
|
65
|
+
apiUrl: string;
|
|
66
|
+
apiKey: string;
|
|
67
|
+
} | {
|
|
68
|
+
method: "file";
|
|
69
|
+
target: undefined;
|
|
70
|
+
clearing: undefined;
|
|
71
|
+
driveIds: string[];
|
|
72
|
+
apiUrl: string;
|
|
73
|
+
apiKey: string;
|
|
74
|
+
} | {
|
|
75
|
+
target: "1password";
|
|
76
|
+
method: "stdout";
|
|
77
|
+
clearing: undefined;
|
|
78
|
+
driveIds: string[];
|
|
79
|
+
apiUrl: string;
|
|
80
|
+
apiKey: string;
|
|
81
|
+
} | {
|
|
82
|
+
target: "clipboard";
|
|
83
|
+
clearing: import("./backup-targets.js").ClearResult;
|
|
84
|
+
method: "stdout";
|
|
85
|
+
driveIds: string[];
|
|
86
|
+
apiUrl: string;
|
|
87
|
+
apiKey: string;
|
|
88
|
+
}>;
|
|
89
|
+
/**
|
|
90
|
+
* Records that the last export was stored (`credentials confirm`). Only drives named by a
|
|
91
|
+
* pending export made with the current API key are recorded, and the marker is then cleared.
|
|
92
|
+
*/
|
|
93
|
+
export declare function confirmCredentials(method?: 'stdout' | 'file'): Promise<{
|
|
94
|
+
method: "stdout" | "file";
|
|
95
|
+
driveIds: string[];
|
|
96
|
+
apiUrl: string;
|
|
97
|
+
apiKey: string;
|
|
98
|
+
}>;
|
|
99
|
+
/** Merges a bundle into the saved config; imported keys count as backed up. */
|
|
100
|
+
export declare function importCredentials(text: string, method: 'file' | 'stdout'): Promise<string[]>;
|
|
101
|
+
/** Tells the service a key was backed up (never the key). A failure is only a warning. */
|
|
102
|
+
export declare function reportKeyBackup(apiUrl: string, apiKey: string, driveIds: string[], method: 'file' | 'stdout' | 'env', deps?: {
|
|
103
|
+
fetch?: typeof fetch;
|
|
104
|
+
warn?: (message: string) => void;
|
|
105
|
+
}): Promise<void>;
|
|
106
|
+
/** Reports bundle drives (once per process) whose effective key is the bundle's key for this origin. */
|
|
107
|
+
export declare function reportEnvBackups(apiUrl: string, apiKey: string, deps?: Parameters<typeof reportKeyBackup>[4]): Promise<void>;
|
|
108
|
+
export {};
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { lstat } from 'node:fs/promises';
|
|
3
|
+
import { validateUrl } from './client.js';
|
|
4
|
+
import { decodeDriveKey } from './crypto.js';
|
|
5
|
+
import { writeFileSafely } from './safe-write.js';
|
|
6
|
+
import { copyToClipboard, exportTo1Password, parseTarget, realTargetDeps, } from './backup-targets.js';
|
|
7
|
+
import { readConfig, resolveDriveKey, resolveDriveId, writeConfig, DEFAULT_API_URL, } from './config.js';
|
|
8
|
+
export const BUNDLE_PREFIX = 'adcred1.';
|
|
9
|
+
export const BACKUP_HINT = "Back up this agent's credentials before this machine or sandbox goes away: `agent-drive credentials export --to 1password` (1Password), `agent-drive credentials export --to clipboard` (copy, paste it into Apple Passwords or another password manager, then run `agent-drive credentials confirm`), or `agent-drive credentials export --to <a file outside the sandbox, on a path that survives it>`. Until then `agent-drive check` will not pass.";
|
|
10
|
+
export function encodeBundle(bundle) {
|
|
11
|
+
return BUNDLE_PREFIX + Buffer.from(JSON.stringify(bundle)).toString('base64url');
|
|
12
|
+
}
|
|
13
|
+
/** A bundle holding only the named drives' keys (all of them when `driveIds` is omitted). */
|
|
14
|
+
export function buildBundle(source, driveIds) {
|
|
15
|
+
const driveKeys = source.driveKeys ?? {};
|
|
16
|
+
const origins = source.driveKeyOrigins ?? {};
|
|
17
|
+
const ids = driveIds ?? Object.keys(driveKeys);
|
|
18
|
+
return encodeBundle({
|
|
19
|
+
v: 1,
|
|
20
|
+
apiUrl: source.apiUrl,
|
|
21
|
+
apiKey: source.apiKey,
|
|
22
|
+
driveKeys: Object.fromEntries(ids.filter((id) => driveKeys[id]).map((id) => [id, driveKeys[id]])),
|
|
23
|
+
driveKeyOrigins: Object.fromEntries(ids.filter((id) => origins[id]).map((id) => [id, origins[id]])),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
|
|
27
|
+
const isStringMap = (v) => Boolean(v) &&
|
|
28
|
+
typeof v === 'object' &&
|
|
29
|
+
!Array.isArray(v) &&
|
|
30
|
+
Object.values(v).every((x) => typeof x === 'string');
|
|
31
|
+
export function decodeBundle(text) {
|
|
32
|
+
const bad = () => new Error('Not a valid Agent Drive credentials bundle.');
|
|
33
|
+
const trimmed = text.trim();
|
|
34
|
+
if (!trimmed.startsWith(BUNDLE_PREFIX))
|
|
35
|
+
throw bad();
|
|
36
|
+
let value;
|
|
37
|
+
try {
|
|
38
|
+
value = JSON.parse(Buffer.from(trimmed.slice(BUNDLE_PREFIX.length), 'base64url').toString('utf8'));
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw bad();
|
|
42
|
+
}
|
|
43
|
+
if (!value ||
|
|
44
|
+
value.v !== 1 ||
|
|
45
|
+
typeof value.apiUrl !== 'string' ||
|
|
46
|
+
typeof value.apiKey !== 'string' ||
|
|
47
|
+
!isStringMap(value.driveKeys) ||
|
|
48
|
+
!isStringMap(value.driveKeyOrigins))
|
|
49
|
+
throw bad();
|
|
50
|
+
// Reject the whole bundle on any invalid field.
|
|
51
|
+
try {
|
|
52
|
+
validateUrl(value.apiUrl, true);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
throw bad();
|
|
56
|
+
}
|
|
57
|
+
if (!value.apiKey || value.apiKey.length > 512)
|
|
58
|
+
throw bad();
|
|
59
|
+
for (const [id, key] of Object.entries(value.driveKeys)) {
|
|
60
|
+
if (!UUID.test(id))
|
|
61
|
+
throw bad();
|
|
62
|
+
try {
|
|
63
|
+
decodeDriveKey(key);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
throw bad();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
for (const id of Object.keys(value.driveKeyOrigins))
|
|
70
|
+
if (!UUID.test(id))
|
|
71
|
+
throw bad();
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
/** The AGENT_DRIVE_CREDENTIALS bundle, if set. Errors never include its content. */
|
|
75
|
+
export function envBundle() {
|
|
76
|
+
const raw = process.env.AGENT_DRIVE_CREDENTIALS?.trim();
|
|
77
|
+
if (!raw)
|
|
78
|
+
return undefined;
|
|
79
|
+
try {
|
|
80
|
+
return decodeBundle(raw);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
throw new Error('AGENT_DRIVE_CREDENTIALS is not a valid credentials bundle.');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The saved config with the environment bundle merged in memory. Saved values win over the
|
|
88
|
+
* bundle (a later login is newer than a stored backup); bundle drives count as backed up.
|
|
89
|
+
* Never write the result back: writeConfig re-reads the file itself.
|
|
90
|
+
*/
|
|
91
|
+
export async function loadConfig() {
|
|
92
|
+
const saved = await readConfig();
|
|
93
|
+
const bundle = envBundle();
|
|
94
|
+
if (!bundle)
|
|
95
|
+
return saved;
|
|
96
|
+
const at = new Date().toISOString();
|
|
97
|
+
const effectiveUrl = process.env.AGENT_DRIVE_API_URL || saved.apiUrl || bundle.apiUrl;
|
|
98
|
+
const effectiveOrigin = originOf(effectiveUrl);
|
|
99
|
+
// A bundle is a backup only of the connection it holds: same API key and origin.
|
|
100
|
+
const sameConnection = (process.env.AGENT_DRIVE_API_KEY || saved.apiKey || bundle.apiKey) === bundle.apiKey &&
|
|
101
|
+
originOf(bundle.apiUrl) === effectiveOrigin;
|
|
102
|
+
const driveKeys = { ...bundle.driveKeys, ...saved.driveKeys };
|
|
103
|
+
const keyBackup = { ...saved.keyBackup };
|
|
104
|
+
for (const id of Object.keys(bundle.driveKeys))
|
|
105
|
+
if (sameConnection &&
|
|
106
|
+
driveKeys[id] === bundle.driveKeys[id] &&
|
|
107
|
+
bundle.driveKeyOrigins[id] === effectiveOrigin)
|
|
108
|
+
keyBackup[id] = { at, method: 'env' };
|
|
109
|
+
return {
|
|
110
|
+
apiUrl: saved.apiUrl ?? bundle.apiUrl,
|
|
111
|
+
apiKey: saved.apiKey ?? bundle.apiKey,
|
|
112
|
+
driveKeys,
|
|
113
|
+
driveKeyOrigins: { ...bundle.driveKeyOrigins, ...saved.driveKeyOrigins },
|
|
114
|
+
keyBackup,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function originOf(url) {
|
|
118
|
+
try {
|
|
119
|
+
return new URL(url).origin;
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
export function unbackedUp(config, driveIds) {
|
|
126
|
+
return driveIds.filter((id) => !config.keyBackup?.[id]);
|
|
127
|
+
}
|
|
128
|
+
const pendingFor = (apiKey, driveIds) => ({
|
|
129
|
+
apiKeyHash: createHash('sha256').update(apiKey).digest('hex'),
|
|
130
|
+
driveIds,
|
|
131
|
+
});
|
|
132
|
+
async function writeBundleFile(path, bundle, force) {
|
|
133
|
+
try {
|
|
134
|
+
await writeFileSafely(path, `${bundle}\n`, { mode: 0o600, overwrite: Boolean(force) });
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
if (error.code === 'EEXIST')
|
|
138
|
+
throw new Error(`${path} already exists; pass --force to overwrite it.`);
|
|
139
|
+
if (error instanceof Error && /symlink/u.test(error.message))
|
|
140
|
+
throw error;
|
|
141
|
+
throw new Error(`Unable to write ${path}.`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Mints a new agent's key through a `delegate` key and prints a bundle holding only that key and
|
|
146
|
+
* the chosen drive's key. The caller's own key and saved config are never part of it or changed.
|
|
147
|
+
*/
|
|
148
|
+
export async function issueCredentials(options, io, createKey) {
|
|
149
|
+
if (Boolean(options.to) === Boolean(options.stdout))
|
|
150
|
+
throw new Error('Pass exactly one of --to <path> or --stdout.');
|
|
151
|
+
if (options.stdout && io.isTTY)
|
|
152
|
+
throw new Error('Refusing to print credentials to a terminal. Pipe them to a secret store: `agent-drive credentials issue --name <agent> --stdout | <your secret store>`, or use --to <path>.');
|
|
153
|
+
if (options.to && !options.force) {
|
|
154
|
+
// lstat: a dangling symlink counts as present. Only ENOENT means the path is free.
|
|
155
|
+
const present = await lstat(options.to).then(() => true, (error) => {
|
|
156
|
+
if (error.code === 'ENOENT')
|
|
157
|
+
return false;
|
|
158
|
+
throw error;
|
|
159
|
+
});
|
|
160
|
+
if (present)
|
|
161
|
+
throw new Error(`${options.to} already exists; pass --force to overwrite it.`);
|
|
162
|
+
}
|
|
163
|
+
const config = await loadConfig();
|
|
164
|
+
const apiUrl = process.env.AGENT_DRIVE_API_URL || config.apiUrl || DEFAULT_API_URL;
|
|
165
|
+
const drive = resolveDriveId(options.drive, config, apiUrl);
|
|
166
|
+
const driveKey = await resolveDriveKey(drive, undefined, config);
|
|
167
|
+
if (!driveKey)
|
|
168
|
+
throw new Error(`There is no drive key for ${drive} on this machine.`);
|
|
169
|
+
try {
|
|
170
|
+
decodeDriveKey(driveKey);
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
throw new Error(`The drive key for ${drive} on this machine is not a valid drive key.`);
|
|
174
|
+
}
|
|
175
|
+
const scopes = options.scopes?.length ? options.scopes : ['read', 'write'];
|
|
176
|
+
const writePaths = options.writePaths ?? [];
|
|
177
|
+
const label = options.label ?? `${options.name} (issued by ${options.machine ?? 'unknown'})`;
|
|
178
|
+
const key = await createKey(undefined, label, [drive], scopes, writePaths, options.name);
|
|
179
|
+
if (!key.token)
|
|
180
|
+
throw new Error('The service did not return a token.');
|
|
181
|
+
const bundle = buildBundle({
|
|
182
|
+
apiUrl,
|
|
183
|
+
apiKey: key.token,
|
|
184
|
+
driveKeys: { [drive]: driveKey },
|
|
185
|
+
driveKeyOrigins: { [drive]: config.driveKeyOrigins?.[drive] ?? new URL(apiUrl).origin },
|
|
186
|
+
}, [drive]);
|
|
187
|
+
const line = `AGENT_DRIVE_CREDENTIALS=${bundle}`;
|
|
188
|
+
if (options.to)
|
|
189
|
+
await writeBundleFile(options.to, line, options.force);
|
|
190
|
+
else
|
|
191
|
+
await io.write(`${line}\n`);
|
|
192
|
+
return { agentName: options.name, keyId: key.id, scopes, writePaths };
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Writes a bundle to a 0600 file (recorded as a backup) or to a non-TTY stdout. A stdout export
|
|
196
|
+
* is not recorded: pipe it to a secret store, then run `agent-drive credentials confirm`.
|
|
197
|
+
*/
|
|
198
|
+
export async function exportCredentials(options, io, deps = realTargetDeps) {
|
|
199
|
+
const target = parseTarget(options.to);
|
|
200
|
+
if (Boolean(options.to) === Boolean(options.stdout))
|
|
201
|
+
throw new Error('Pass exactly one of --to <path> or --stdout.');
|
|
202
|
+
if (options.stdout && io.isTTY)
|
|
203
|
+
throw new Error('Refusing to print credentials to a terminal. Pipe them to a secret store: `agent-drive credentials export --stdout | <your secret store> && agent-drive credentials confirm`, or use --to <path>.');
|
|
204
|
+
const config = await loadConfig();
|
|
205
|
+
const apiKey = process.env.AGENT_DRIVE_API_KEY || config.apiKey;
|
|
206
|
+
if (!apiKey)
|
|
207
|
+
throw new Error('There is no API key to back up. Run `agent-drive login` first.');
|
|
208
|
+
const driveKeys = config.driveKeys ?? {};
|
|
209
|
+
const ids = Object.keys(driveKeys);
|
|
210
|
+
if (!ids.length)
|
|
211
|
+
throw new Error('There are no drive keys on this machine to back up.');
|
|
212
|
+
const apiUrl = process.env.AGENT_DRIVE_API_URL || config.apiUrl || DEFAULT_API_URL;
|
|
213
|
+
const bundle = buildBundle({
|
|
214
|
+
apiUrl,
|
|
215
|
+
apiKey,
|
|
216
|
+
driveKeys,
|
|
217
|
+
driveKeyOrigins: config.driveKeyOrigins ?? {},
|
|
218
|
+
});
|
|
219
|
+
const done = (method) => ({
|
|
220
|
+
method,
|
|
221
|
+
target: undefined,
|
|
222
|
+
clearing: undefined,
|
|
223
|
+
driveIds: ids,
|
|
224
|
+
apiUrl,
|
|
225
|
+
apiKey,
|
|
226
|
+
});
|
|
227
|
+
if (target === '1password') {
|
|
228
|
+
await exportTo1Password(bundle, `Agent Drive – ${ids.join(', ')}`, options.vault, deps);
|
|
229
|
+
const at = new Date().toISOString();
|
|
230
|
+
await writeConfig({
|
|
231
|
+
keyBackup: Object.fromEntries(ids.map((id) => [id, { at, method: 'stdout' }])),
|
|
232
|
+
});
|
|
233
|
+
return { ...done('stdout'), target };
|
|
234
|
+
}
|
|
235
|
+
if (target === 'clipboard') {
|
|
236
|
+
// The clear timer starts at once and stays alive if the config write fails.
|
|
237
|
+
const clearing = await copyToClipboard(bundle, Boolean(options.keepClipboard), deps);
|
|
238
|
+
try {
|
|
239
|
+
// Not a backup yet: `credentials confirm` records it after the user saved it.
|
|
240
|
+
await writeConfig({ pendingExport: pendingFor(apiKey, ids) });
|
|
241
|
+
}
|
|
242
|
+
catch (error) {
|
|
243
|
+
await clearing;
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
return { ...done('stdout'), target, clearing };
|
|
247
|
+
}
|
|
248
|
+
if (options.to) {
|
|
249
|
+
await writeBundleFile(options.to, bundle, options.force);
|
|
250
|
+
const at = new Date().toISOString();
|
|
251
|
+
await writeConfig({
|
|
252
|
+
keyBackup: Object.fromEntries(ids.map((id) => [id, { at, method: 'file' }])),
|
|
253
|
+
});
|
|
254
|
+
return done('file');
|
|
255
|
+
}
|
|
256
|
+
await io.write(`${bundle}\n`);
|
|
257
|
+
await writeConfig({ pendingExport: pendingFor(apiKey, ids) });
|
|
258
|
+
return done('stdout');
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Records that the last export was stored (`credentials confirm`). Only drives named by a
|
|
262
|
+
* pending export made with the current API key are recorded, and the marker is then cleared.
|
|
263
|
+
*/
|
|
264
|
+
export async function confirmCredentials(method = 'stdout') {
|
|
265
|
+
const config = await loadConfig();
|
|
266
|
+
const apiKey = process.env.AGENT_DRIVE_API_KEY || config.apiKey;
|
|
267
|
+
const pending = config.pendingExport;
|
|
268
|
+
if (!apiKey || !pending || pending.apiKeyHash !== pendingFor(apiKey, []).apiKeyHash)
|
|
269
|
+
throw new Error('There is no matching credentials export to confirm. Run `agent-drive credentials export` first.');
|
|
270
|
+
const ids = pending.driveIds.filter((id) => config.driveKeys?.[id]);
|
|
271
|
+
const at = new Date().toISOString();
|
|
272
|
+
await writeConfig({
|
|
273
|
+
keyBackup: Object.fromEntries(ids.map((id) => [id, { at, method }])),
|
|
274
|
+
pendingExport: null,
|
|
275
|
+
});
|
|
276
|
+
const apiUrl = process.env.AGENT_DRIVE_API_URL || config.apiUrl || DEFAULT_API_URL;
|
|
277
|
+
return { method, driveIds: ids, apiUrl, apiKey };
|
|
278
|
+
}
|
|
279
|
+
/** Merges a bundle into the saved config; imported keys count as backed up. */
|
|
280
|
+
export async function importCredentials(text, method) {
|
|
281
|
+
const bundle = decodeBundle(text);
|
|
282
|
+
const at = new Date().toISOString();
|
|
283
|
+
await writeConfig({
|
|
284
|
+
apiUrl: bundle.apiUrl,
|
|
285
|
+
apiKey: bundle.apiKey,
|
|
286
|
+
driveKeys: bundle.driveKeys,
|
|
287
|
+
driveKeyOrigins: bundle.driveKeyOrigins,
|
|
288
|
+
keyBackup: Object.fromEntries(Object.keys(bundle.driveKeys).map((id) => [id, { at, method }])),
|
|
289
|
+
});
|
|
290
|
+
return Object.keys(bundle.driveKeys);
|
|
291
|
+
}
|
|
292
|
+
/** Tells the service a key was backed up (never the key). A failure is only a warning. */
|
|
293
|
+
export async function reportKeyBackup(apiUrl, apiKey, driveIds, method, deps = {}) {
|
|
294
|
+
const doFetch = deps.fetch ?? globalThis.fetch.bind(globalThis);
|
|
295
|
+
const warn = deps.warn ?? ((m) => process.stderr.write(`${m}\n`));
|
|
296
|
+
for (const id of driveIds) {
|
|
297
|
+
try {
|
|
298
|
+
// Same HTTPS/loopback rule as the client, checked before the token is attached.
|
|
299
|
+
const base = validateUrl(apiUrl, true).toString().replace(/\/+$/u, '');
|
|
300
|
+
const response = await doFetch(`${base}/v1/drives/${encodeURIComponent(id)}/key-backup`, {
|
|
301
|
+
method: 'POST',
|
|
302
|
+
redirect: 'error',
|
|
303
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },
|
|
304
|
+
body: JSON.stringify({ method }),
|
|
305
|
+
signal: AbortSignal.timeout(5000),
|
|
306
|
+
});
|
|
307
|
+
// 403: a read-only key may not report (the endpoint needs write). Expected, so no warning.
|
|
308
|
+
if (response.status === 403)
|
|
309
|
+
continue;
|
|
310
|
+
if (!response.ok)
|
|
311
|
+
throw new Error(String(response.status));
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
warn(`Warning: could not report the key backup for drive ${id} to Agent Drive.`);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
let reportedEnv = false;
|
|
319
|
+
/** Reports bundle drives (once per process) whose effective key is the bundle's key for this origin. */
|
|
320
|
+
export async function reportEnvBackups(apiUrl, apiKey, deps = {}) {
|
|
321
|
+
const bundle = envBundle();
|
|
322
|
+
if (!bundle || reportedEnv)
|
|
323
|
+
return;
|
|
324
|
+
reportedEnv = true;
|
|
325
|
+
if (bundle.apiKey !== apiKey || originOf(bundle.apiUrl) !== originOf(apiUrl))
|
|
326
|
+
return;
|
|
327
|
+
const config = await loadConfig();
|
|
328
|
+
const origin = originOf(apiUrl);
|
|
329
|
+
const ids = [];
|
|
330
|
+
for (const [id, key] of Object.entries(bundle.driveKeys))
|
|
331
|
+
if (bundle.driveKeyOrigins[id] === origin &&
|
|
332
|
+
(await resolveDriveKey(id, undefined, config)) === key)
|
|
333
|
+
ids.push(id);
|
|
334
|
+
await reportKeyBackup(apiUrl, apiKey, ids, 'env', deps);
|
|
335
|
+
}
|
|
336
|
+
//# sourceMappingURL=credentials.js.map
|