@asecret/cli 0.0.0-stage → 0.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/src/main.js ADDED
@@ -0,0 +1,520 @@
1
+ // Reading the command line, building what every command needs, and saying
2
+ // what went wrong when something does.
3
+
4
+ import { spawn } from "node:child_process";
5
+ import { readFileSync } from "node:fs";
6
+ import { readFile } from "node:fs/promises";
7
+ import { constants, homedir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { parseArgs } from "node:util";
10
+ import { ApiError, createClient, DEFAULT_API, DEFAULT_WEB, NotConnected } from "./api.js";
11
+ import { commands, UsageError } from "./commands.js";
12
+ import { configDir, credentialsFile, forgetCredentials, loadCredentials, saveCredentials, setting } from "./config.js";
13
+ import { ServerError } from "./core.js";
14
+ import { NotLinked } from "./errors.js";
15
+ import { clean, palette } from "./output.js";
16
+ import { keyFingerprint, newKeys, shareKeys } from "./storage.js";
17
+
18
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
19
+
20
+ const ALIASES = /** @type {Record<string, string>} */ ({
21
+ login: "connect",
22
+ whoami: "me",
23
+ install: "add",
24
+ uninstall: "remove",
25
+ secret: "save",
26
+ secrets: "list",
27
+ ls: "list",
28
+ rm: "delete",
29
+ });
30
+
31
+ const GLOBAL = {
32
+ json: { type: /** @type {const} */ ("boolean"), help: "Print the API's JSON, for scripts and agents" },
33
+ yes: { type: /** @type {const} */ ("boolean"), short: "y", help: "Answer yes to every prompt" },
34
+ api: { type: /** @type {const} */ ("string"), hint: "url", help: `Use another aSecret API (default ${DEFAULT_API})` },
35
+ help: { type: /** @type {const} */ ("boolean"), short: "h", help: "Show help" },
36
+ };
37
+
38
+ /** Stopped at a prompt. */
39
+ class Cancelled extends Error {}
40
+
41
+ /** How each agent appears to a person when it links, unless --name says otherwise. */
42
+ const AGENT_NAMES = /** @type {Record<string, string>} */ ({
43
+ "claude-code": "Claude Code", codex: "Codex", cursor: "Cursor", "gemini-cli": "Gemini CLI", antigravity: "Antigravity",
44
+ augment: "Augment", opencode: "OpenCode", replit: "Replit Agent", "github-copilot": "GitHub Copilot",
45
+ });
46
+
47
+ /**
48
+ * The agent running this CLI, if one is, from the variables agents set.
49
+ * It leads the User-Agent so aSecret can see which agents turn up.
50
+ * @param {NodeJS.ProcessEnv} env
51
+ */
52
+ export function detectAgent(env) {
53
+ const named = env.AI_AGENT?.trim();
54
+ if (named) return named.replace(/[^A-Za-z0-9._-]+/g, "-").slice(0, 40) || null;
55
+ if (env.CURSOR_TRACE_ID || env.CURSOR_AGENT) return "cursor";
56
+ if (env.GEMINI_CLI) return "gemini-cli";
57
+ if (env.CODEX_SANDBOX || env.CODEX_CI || env.CODEX_THREAD_ID) return "codex";
58
+ if (env.ANTIGRAVITY_AGENT) return "antigravity";
59
+ if (env.AUGMENT_AGENT) return "augment";
60
+ if (env.OPENCODE_CLIENT) return "opencode";
61
+ if (env.CLAUDECODE || env.CLAUDE_CODE) return "claude-code";
62
+ if (env.REPL_ID) return "replit";
63
+ if (env.COPILOT_MODEL || env.COPILOT_ALLOW_ALL) return "github-copilot";
64
+ return null;
65
+ }
66
+
67
+ /** @param {NodeJS.ProcessEnv} env */
68
+ export function userAgent(env) {
69
+ if (setting(env, "USER_AGENT")) return setting(env, "USER_AGENT");
70
+ const own = `asecret-cli/${VERSION} (+https://github.com/asecret-org/cli)`;
71
+ const agent = detectAgent(env);
72
+ return agent ? `${agent} ${own}` : own;
73
+ }
74
+
75
+ /**
76
+ * @typedef {{
77
+ * env?: NodeJS.ProcessEnv,
78
+ * cwd?: string,
79
+ * home?: string,
80
+ * fetch?: typeof fetch,
81
+ * stdin?: NodeJS.ReadableStream & { isTTY?: boolean, setRawMode?: (on: boolean) => void },
82
+ * stdout?: NodeJS.WritableStream & { isTTY?: boolean, columns?: number },
83
+ * stderr?: NodeJS.WritableStream & { isTTY?: boolean },
84
+ * spawn?: (command: string, args: string[], env: Record<string, string>) => Promise<number>,
85
+ * }} IO
86
+ */
87
+
88
+ /**
89
+ * @param {string[]} argv
90
+ * @param {IO} [io]
91
+ * @returns {Promise<number>} the exit code
92
+ */
93
+ export async function main(argv, io = {}) {
94
+ const env = io.env ?? process.env;
95
+ const stdout = io.stdout ?? process.stdout;
96
+ const stderr = io.stderr ?? process.stderr;
97
+ const stdin = io.stdin ?? process.stdin;
98
+ const color = !env.NO_COLOR && (!!env.FORCE_COLOR || !!stdout.isTTY);
99
+ const c = palette(color);
100
+ const write = (/** @type {NodeJS.WritableStream} */ stream, /** @type {string} */ text) => stream.write(`${text}\n`);
101
+
102
+ const { name, rest } = splitCommand(argv);
103
+ if (!name) {
104
+ if (rest.includes("--version") || rest.includes("-v")) {
105
+ write(stdout, VERSION);
106
+ return 0;
107
+ }
108
+ write(rest.length && !rest.some((arg) => arg === "-h" || arg === "--help") ? stderr : stdout, mainHelp(c));
109
+ return rest.length && !rest.some((arg) => arg === "-h" || arg === "--help") ? 2 : 0;
110
+ }
111
+ if (name === "help") {
112
+ const topic = rest[0] && (commands[rest[0]] ? rest[0] : ALIASES[rest[0]]);
113
+ write(stdout, topic ? commandHelp(topic, c) : mainHelp(c));
114
+ return 0;
115
+ }
116
+ const commandName = commands[name] ? name : ALIASES[name];
117
+ if (!commandName) {
118
+ const near = nearest(name, [...Object.keys(commands), ...Object.keys(ALIASES)]);
119
+ write(stderr, `${c.red(`Unknown command "${clean(name)}".`)}${near ? ` Did you mean ${c.bold(near)}?` : ""}`);
120
+ write(stderr, c.dim("See every command with: asecret --help"));
121
+ return 2;
122
+ }
123
+ const command = commands[commandName];
124
+
125
+ /** @type {{ values: Record<string, any>, positionals: string[] }} */
126
+ let parsed;
127
+ try {
128
+ const options = { ...GLOBAL, ...command.options };
129
+ parsed = parseArgs({ args: rest, options, allowPositionals: true, strict: true });
130
+ } catch (error) {
131
+ write(stderr, c.red(/** @type {Error} */ (error).message.replace(/\. To specify a positional.*$/s, ".")));
132
+ write(stderr, c.dim(`See: asecret ${commandName} --help`));
133
+ return 2;
134
+ }
135
+ const { values: opts, positionals: args } = parsed;
136
+ if (opts.help) {
137
+ write(stdout, commandHelp(commandName, c));
138
+ return 0;
139
+ }
140
+
141
+ const home = io.home ?? homedir();
142
+ const api = (opts.api || setting(env, "API_URL") || DEFAULT_API).replace(/\/+$/, "");
143
+ const dir = configDir(env, home);
144
+ const file = credentialsFile(env, home);
145
+ const send = io.fetch ?? globalThis.fetch;
146
+ const agentName = userAgent(env);
147
+ const interactive = !!stdin.isTTY && !!stdout.isTTY;
148
+ /** @type {import("./api.js").Client | null} */
149
+ let client = null;
150
+ let token = /** @type {string | null} */ (null);
151
+ let tokenSource = /** @type {string | null} */ (null);
152
+ const tilde = (/** @type {string} */ path) => (path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path);
153
+
154
+ const credentials = async () => {
155
+ const saved = await loadCredentials(file, api);
156
+ const fromEnv = setting(env, "TOKEN");
157
+ if (fromEnv) return { ...(saved?.token === fromEnv ? saved : {}), keys: saved?.keys, server: saved?.server, token: fromEnv, agent_id: saved?.token === fromEnv ? saved.agent_id : null, source: "ASECRET_TOKEN" };
158
+ return saved ? { ...saved, source: tilde(file) } : null;
159
+ };
160
+
161
+ /** @param {any} stored */
162
+ const remember = async (stored) => {
163
+ await saveCredentials(file, api, stored);
164
+ token = stored.token;
165
+ tokenSource = tilde(file);
166
+ client = null;
167
+ };
168
+
169
+ /** @type {Context} */
170
+ const ctx = {
171
+ env,
172
+ cwd: io.cwd ?? process.cwd(),
173
+ home,
174
+ fetch: send,
175
+ api,
176
+ configDir: dir,
177
+ asksFile: join(dir, "asks.json"),
178
+ web: setting(env, "WEB_URL").replace(/\/+$/, "") || (api === DEFAULT_API ? DEFAULT_WEB : null),
179
+ skillWeb: setting(env, "WEB_URL").replace(/\/+$/, "") || DEFAULT_WEB,
180
+ json: !!opts.json,
181
+ interactive,
182
+ stdinIsTTY: !!stdin.isTTY,
183
+ stdoutIsTTY: !!stdout.isTTY,
184
+ pollMs: Number(setting(env, "POLL_MS")) || 3000,
185
+ c,
186
+ width: Math.min(Math.max(stdout.columns || 80, 40), 100),
187
+ userAgent: agentName,
188
+ agentName: AGENT_NAMES[detectAgent(env) ?? ""] ?? "My agent",
189
+ get tokenSource() {
190
+ return tokenSource;
191
+ },
192
+ tilde,
193
+ out: (line = "") => write(stdout, line),
194
+ say: (line) => write(ctx.json ? stderr : stdout, line),
195
+ hint: (line) => write(ctx.json ? stderr : stdout, c.dim(line)),
196
+ warn: (line) => write(stderr, c.yellow(line)),
197
+ printJson: (value) => write(stdout, JSON.stringify(value, null, 2)),
198
+ writeBytes: (bytes) => stdout.write(bytes),
199
+ async readStdin() {
200
+ return new TextDecoder().decode(await ctx.readStdinBytes());
201
+ },
202
+ async readStdinBytes() {
203
+ /** @type {Buffer[]} */
204
+ const chunks = [];
205
+ for await (const chunk of stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
206
+ const all = Buffer.concat(chunks);
207
+ return new Uint8Array(all.buffer, all.byteOffset, all.byteLength);
208
+ },
209
+ async askHidden(question) {
210
+ if (!stdin.isTTY) return ctx.readStdin();
211
+ stderr.write(question);
212
+ stdin.setRawMode?.(true);
213
+ let value = "";
214
+ try {
215
+ for await (const chunk of stdin) {
216
+ for (const char of String(chunk)) {
217
+ if (char === "\r" || char === "\n") return value;
218
+ if (char === "\u0003") throw new Cancelled("Nothing changed.");
219
+ if (char === "\u007f") value = value.slice(0, -1);
220
+ else value += char;
221
+ }
222
+ }
223
+ return value;
224
+ } finally {
225
+ stdin.setRawMode?.(false);
226
+ stderr.write("\n");
227
+ }
228
+ },
229
+ async confirm(question, preferYes) {
230
+ if (opts.yes) return;
231
+ if (!interactive) throw new UsageError("Add --yes to do this without a prompt.");
232
+ const { createInterface } = await import("node:readline/promises");
233
+ const prompt = createInterface({ input: stdin, output: stderr });
234
+ // Input that ends before an answer is a no, never a hang.
235
+ const closed = new Promise((resolve) => prompt.once("close", () => resolve("n")));
236
+ const answer = String(await Promise.race([prompt.question(`${question} ${preferYes ? "[Y/n]" : "[y/N]"} `), closed])).trim().toLowerCase();
237
+ prompt.close();
238
+ const yes = answer ? answer === "y" || answer === "yes" : preferYes;
239
+ if (!yes) throw new Cancelled("Nothing changed.");
240
+ },
241
+ spawn:
242
+ io.spawn ??
243
+ ((commandLine, args, extra) =>
244
+ new Promise((resolve, reject) => {
245
+ const child = spawn(commandLine, args, { stdio: "inherit", env: { ...process.env, ...extra } });
246
+ child.on("error", (error) => reject(new Error(`Could not run ${commandLine}: ${error.message}`)));
247
+ child.on("exit", (code, signal) => resolve(code ?? (signal ? 128 + (constants.signals[signal] ?? 1) : 1)));
248
+ })),
249
+ credentials,
250
+ async connect({ primary = false } = {}) {
251
+ const keys = newKeys();
252
+ const result = await createClient({ base: api, userAgent: agentName, fetch: send }).register();
253
+ await remember({ agent_id: result.agent_id, token: result.token, keys, connected_at: new Date().toISOString() });
254
+ const say = primary && !ctx.json ? ctx.out : (/** @type {string} */ line) => write(stderr, line);
255
+ say(c.green(`Connected this agent to aSecret. Agent ${clean(result.agent_id)}.`));
256
+ say(c.dim(`The token and key are saved in ${tilde(file)}, readable only by you.`));
257
+ say(c.dim("Without the key its secrets can't be read again. Keep a copy: asecret key --export --out <file>"));
258
+ return result;
259
+ },
260
+ async restore(path) {
261
+ let saved;
262
+ try {
263
+ saved = JSON.parse(await readFile(path, "utf8"));
264
+ } catch {
265
+ throw new UsageError(`${clean(path)} is not an exported aSecret key.`);
266
+ }
267
+ if (saved?.format !== "asecret-agent-key/1" || !saved.token || !saved.keys?.agent) throw new UsageError(`${clean(path)} is not an exported aSecret key.`);
268
+ if (saved.api !== api) throw new UsageError(`This key belongs to ${clean(saved.api)}. Restore it with --api ${clean(saved.api)}.`);
269
+ const me = await createClient({ base: api, token: saved.token, userAgent: agentName, fetch: send }).me();
270
+ if (me.agent_id !== saved.agent_id) throw new Error("The token in that file belongs to another agent. Nothing changed.");
271
+ await remember({ agent_id: saved.agent_id, token: saved.token, keys: saved.keys, server: saved.server, connected_at: new Date().toISOString() });
272
+ if (!ctx.json) {
273
+ ctx.out(c.green(`Restored agent ${clean(saved.agent_id)} on this machine.`));
274
+ ctx.out(c.dim(`Key ${await keyFingerprint(saved.keys.agent)}, saved in ${tilde(file)}.`));
275
+ }
276
+ return saved;
277
+ },
278
+ async saveServer(origin) {
279
+ const saved = await loadCredentials(file, api);
280
+ if (!saved) return;
281
+ await saveCredentials(file, api, { ...saved, server: origin });
282
+ },
283
+ async forget() {
284
+ return forgetCredentials(file, api);
285
+ },
286
+ async rotateToken() {
287
+ if (setting(env, "TOKEN")) throw new UsageError("This agent's token comes from ASECRET_TOKEN. Unset it to rotate the saved token.");
288
+ const saved = await loadCredentials(file, api);
289
+ if (!saved) throw new NotConnected();
290
+ const { token: next } = await createClient({ base: api, token: saved.token, userAgent: agentName, fetch: send }).rotateToken();
291
+ // On disk first: if the next call fails, the new token is kept and the old one still works.
292
+ await saveCredentials(file, api, { ...saved, token: next });
293
+ // Its first use retires the old token.
294
+ await createClient({ base: api, token: next, userAgent: agentName, fetch: send }).me();
295
+ token = next;
296
+ client = null;
297
+ return { agent_id: saved.agent_id, source: tilde(file) };
298
+ },
299
+ async client({ connect = false, required = false } = {}) {
300
+ if (client) return client;
301
+ if (!token) {
302
+ const found = await credentials();
303
+ if (found) {
304
+ token = found.token;
305
+ tokenSource = found.source;
306
+ }
307
+ }
308
+ if (!token && connect) await ctx.connect();
309
+ if (!token && required) throw new NotConnected();
310
+ client = createClient({ base: api, token, userAgent: agentName, fetch: send });
311
+ return client;
312
+ },
313
+ };
314
+
315
+ // The person turned on agent recovery after this agent linked, and the API said so on one of
316
+ // this run's answers: send them this agent's keys now, once. It never fails the command; a
317
+ // problem is only mentioned, on stderr so piped output stays clean, and the next run tries again.
318
+ async function shareKeysQuietly() {
319
+ if (!client?.escrowWanted) return;
320
+ try {
321
+ const saved = await credentials();
322
+ if (saved?.keys?.agent) await shareKeys(client, saved, await client.me());
323
+ } catch (/** @type {any} */ error) {
324
+ write(stderr, c.dim(`Couldn't give your person this agent's key for recovery yet (${clean(error.message).replace(/\.$/, "")}). It tries again on the next command.`));
325
+ }
326
+ }
327
+
328
+ try {
329
+ const code = await command.run(ctx, args, opts);
330
+ await shareKeysQuietly();
331
+ return typeof code === "number" ? code : 0;
332
+ } catch (error) {
333
+ return report(ctx, stderr, error, commandName);
334
+ }
335
+ }
336
+
337
+ /**
338
+ * @typedef {{
339
+ * env: NodeJS.ProcessEnv, cwd: string, home: string, fetch: typeof fetch,
340
+ * api: string, configDir: string, asksFile: string, web: string | null, skillWeb: string,
341
+ * json: boolean, interactive: boolean, stdinIsTTY: boolean, stdoutIsTTY: boolean, pollMs: number,
342
+ * c: import("./output.js").Palette, width: number, userAgent: string, agentName: string,
343
+ * readonly tokenSource: string | null,
344
+ * tilde: (path: string) => string,
345
+ * out: (line?: string) => void, say: (line: string) => void, hint: (line: string) => void, warn: (line: string) => void,
346
+ * printJson: (value: unknown) => void, writeBytes: (bytes: Uint8Array) => void,
347
+ * readStdin: () => Promise<string>, readStdinBytes: () => Promise<Uint8Array>, askHidden: (question: string) => Promise<string>,
348
+ * confirm: (question: string, preferYes: boolean) => Promise<void>,
349
+ * spawn: (command: string, args: string[], env: Record<string, string>) => Promise<number>,
350
+ * credentials: () => Promise<any>,
351
+ * connect: (options?: { primary?: boolean }) => Promise<any>,
352
+ * restore: (path: string) => Promise<any>,
353
+ * saveServer: (origin: string | undefined) => Promise<void>,
354
+ * forget: () => Promise<boolean>,
355
+ * rotateToken: () => Promise<{ agent_id: string, source: string }>,
356
+ * client: (options?: { connect?: boolean, required?: boolean }) => Promise<import("./api.js").Client>,
357
+ * }} Context
358
+ */
359
+
360
+ /** The command name and everything else, letting global flags come first. @param {string[]} argv */
361
+ function splitCommand(argv) {
362
+ for (let i = 0; i < argv.length; i++) {
363
+ const arg = argv[i];
364
+ if (arg === "--api") {
365
+ i++;
366
+ continue;
367
+ }
368
+ if (arg === "--") return { name: argv[i + 1] ?? null, rest: [...argv.slice(0, i), ...argv.slice(i + 2)] };
369
+ if (!arg.startsWith("-")) return { name: arg, rest: [...argv.slice(0, i), ...argv.slice(i + 1)] };
370
+ }
371
+ return { name: null, rest: argv };
372
+ }
373
+
374
+ /** @param {Context} ctx @param {NodeJS.WritableStream} stderr @param {unknown} error @param {string} command */
375
+ function report(ctx, stderr, error, command) {
376
+ const { c } = ctx;
377
+ const say = (/** @type {string} */ line) => stderr.write(`${line}\n`);
378
+ if (error instanceof Cancelled) {
379
+ say(error.message);
380
+ return 1;
381
+ }
382
+ if (error instanceof UsageError) {
383
+ say(c.red(error.message));
384
+ say(c.dim(`See: asecret ${command} --help`));
385
+ return 2;
386
+ }
387
+ if (error instanceof NotConnected) {
388
+ say(c.red(error.message));
389
+ say("Run asecret connect, or save a secret with asecret save, which connects on the way.");
390
+ return 1;
391
+ }
392
+ if (error instanceof NotLinked) {
393
+ say(c.red(error.message));
394
+ say("Link your person with: asecret link");
395
+ return 1;
396
+ }
397
+ if (error instanceof ServerError) {
398
+ if (ctx.json) ctx.printJson({ error: { status: error.status, code: error.code } });
399
+ say(`${c.red(serverMessage(error))} ${c.dim(`(${error.status} ${error.code})`)}`);
400
+ if (error.status === 401) say("Link again with: asecret link");
401
+ return 1;
402
+ }
403
+ if (error instanceof ApiError) {
404
+ if (ctx.json) ctx.printJson({ error: { status: error.status, ...(error.problem ?? {}) } });
405
+ const label = [error.status, error.code].filter(Boolean).join(" ");
406
+ say(`${c.red(clean(error.message))} ${c.dim(`(${label})`)}`);
407
+ // What the API says to do next, except for a token it refused: the CLI says that its own way.
408
+ if (error.next && error.status !== 401) say(clean(error.next));
409
+ if (error.status === 401) {
410
+ say(`aSecret did not accept the token from ${ctx.tokenSource ?? "this machine"}. If it was revoked, the person this agent is linked to can check in aSecret.`);
411
+ say(c.dim("Connecting again would make a separate agent with empty storage, so it is not a fix."));
412
+ }
413
+ if (error.retryAfter) {
414
+ const seconds = Number(error.retryAfter);
415
+ say(c.dim(Number.isFinite(seconds) ? `Try again in ${seconds} seconds.` : `Try again after ${clean(error.retryAfter)}.`));
416
+ }
417
+ return 1;
418
+ }
419
+ const failure = /** @type {Error & { cause?: { code?: string, hostname?: string } }} */ (error);
420
+ if (failure?.name === "TypeError" && /fetch failed/i.test(failure.message)) {
421
+ const where = failure.cause?.hostname ? `https://${failure.cause.hostname}` : ctx.api;
422
+ say(c.red(`Could not reach ${where}${failure.cause?.code ? ` (${failure.cause.code})` : ""}. Check the connection, then try again.`));
423
+ return 1;
424
+ }
425
+ say(c.red(failure?.message ?? String(error)));
426
+ if (setting(ctx.env, "DEBUG") && failure?.stack) say(c.dim(failure.stack));
427
+ return 1;
428
+ }
429
+
430
+ /** What a refusal from the person's aSecret server means. @param {ServerError} error */
431
+ function serverMessage(error) {
432
+ return (
433
+ /** @type {Record<string, string>} */ ({
434
+ invalid_token: "Your person's aSecret server no longer accepts this agent's link.",
435
+ access_paused: "Your person has paused this agent's asks.",
436
+ insufficient_scope: "This link can't make that ask.",
437
+ not_found: "Your person's aSecret server has no ask with that id for this agent.",
438
+ unsupported_recipient: "Your person's aSecret server does not deliver to that recipient. See them with: asecret recipients",
439
+ unsupported_operation: "Your person's aSecret server does not offer that.",
440
+ idempotency_conflict: "That --key was already used for a different ask.",
441
+ rate_limited: "Too many asks for now. Try again in a minute.",
442
+ })[error.code] ?? "Your person's aSecret server refused that."
443
+ );
444
+ }
445
+
446
+ /** @param {string} word @param {string[]} candidates */
447
+ function nearest(word, candidates) {
448
+ /** @param {string} a @param {string} b */
449
+ const distance = (a, b) => {
450
+ const row = Array.from({ length: b.length + 1 }, (_, j) => j);
451
+ for (let i = 1; i <= a.length; i++) {
452
+ let previous = row[0];
453
+ row[0] = i;
454
+ for (let j = 1; j <= b.length; j++) {
455
+ const kept = row[j];
456
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
457
+ previous = kept;
458
+ }
459
+ }
460
+ return row[b.length];
461
+ };
462
+ const best = candidates.map((name) => ({ name, d: distance(word, name) })).sort((x, y) => x.d - y.d)[0];
463
+ return best && best.d <= 2 ? best.name : null;
464
+ }
465
+
466
+ /** @param {Record<string, { short?: string, hint?: string, help: string, hidden?: boolean }>} options */
467
+ function optionLines(options) {
468
+ const rows = Object.entries(options).filter(([, o]) => !o.hidden).map(([name, o]) => [
469
+ `${o.short ? `-${o.short}, ` : ""}--${name}${o.hint ? ` <${o.hint}>` : ""}`,
470
+ o.help,
471
+ ]);
472
+ const width = Math.max(...rows.map(([left]) => left.length)) + 2;
473
+ return rows.map(([left, right]) => ` ${left.padEnd(width)}${right}`);
474
+ }
475
+
476
+ /** @param {import("./output.js").Palette} c */
477
+ function mainHelp(c) {
478
+ const groups = /** @type {Record<string, string[][]>} */ ({});
479
+ for (const command of Object.values(commands)) {
480
+ groups[command.group] ??= [];
481
+ groups[command.group].push([command.usage, command.summary]);
482
+ }
483
+ const width = Math.max(...Object.values(commands).map((command) => command.usage.length)) + 3;
484
+ const lines = [
485
+ `${c.bold("aSecret")} keeps your AI agent's secrets, encrypted, and lets it use them without seeing them.`,
486
+ "Once linked, it can also ask your person for a detail they keep, and your person decides.",
487
+ "",
488
+ `${c.bold("Usage")} asecret <command> [options]`,
489
+ ];
490
+ for (const [group, rows] of Object.entries(groups)) {
491
+ lines.push("", c.bold(group));
492
+ for (const [usage, summary] of rows) lines.push(` ${usage.padEnd(width)}${summary}`);
493
+ }
494
+ lines.push(
495
+ "",
496
+ c.bold("Options"),
497
+ ...optionLines({ ...GLOBAL, version: { short: "v", help: "Show the version" } }),
498
+ "",
499
+ c.bold("Examples"),
500
+ " asecret connect",
501
+ ' printf %s "$OPENAI_API_KEY" | asecret save OPENAI_API_KEY',
502
+ " asecret list",
503
+ " asecret run --secret OPENAI_API_KEY -- python agent.py",
504
+ " asecret link",
505
+ " asecret ask postal_address",
506
+ " asecret add",
507
+ "",
508
+ c.dim("https://asecret.sh · https://github.com/asecret-org/cli"),
509
+ );
510
+ return lines.join("\n");
511
+ }
512
+
513
+ /** @param {string} name @param {import("./output.js").Palette} c */
514
+ function commandHelp(name, c) {
515
+ const command = commands[name];
516
+ const lines = [`${c.bold("Usage")} asecret ${command.usage} [options]`, "", `${command.summary}.`];
517
+ if (command.about?.length) lines.push("", ...command.about);
518
+ lines.push("", c.bold("Options"), ...optionLines({ ...(command.options ?? {}), ...GLOBAL }));
519
+ return lines.join("\n");
520
+ }
package/src/mcp.js ADDED
@@ -0,0 +1,107 @@
1
+ // asecret-mcp: a local MCP server for this agent, using the same token and key as the CLI. It lists
2
+ // the agent's secrets by name and never returns a value: an agent must not read a secret into its
3
+ // conversation, so it uses one through `asecret run`. Asks to the agent's person are offered too once
4
+ // it is linked: at asecret.sh, or to their own aSecret server.
5
+
6
+ import { homedir } from "node:os";
7
+ import { McpServer } from "@modelcontextprotocol/server";
8
+ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
9
+ import * as z from "zod/v4";
10
+ import { ApiError, createClient, DEFAULT_API } from "./api.js";
11
+ import { configDir, credentialsFile, loadCredentials, setting } from "./config.js";
12
+ import * as core from "./core.js";
13
+ import { userAgent, VERSION } from "./main.js";
14
+ import { UsageError } from "./errors.js";
15
+ import * as storage from "./storage.js";
16
+ import * as person from "./server.js";
17
+
18
+ /** @param {unknown} value */
19
+ const reply = (value) => ({ content: [{ type: /** @type {const} */ ("text"), text: typeof value === "string" ? value : JSON.stringify(value) }] });
20
+ /** @param {string} message */
21
+ const refuse = (message) => ({ isError: true, content: [{ type: /** @type {const} */ ("text"), text: JSON.stringify({ error: message }) }] });
22
+
23
+ /** @param {{ env?: NodeJS.ProcessEnv, home?: string, fetch?: typeof fetch }} [io] */
24
+ export function storageServer({ env = process.env, home = homedir(), fetch: send = globalThis.fetch } = {}) {
25
+ const api = (setting(env, "API_URL") || DEFAULT_API).replace(/\/+$/, "");
26
+ const dir = configDir(env, home);
27
+ const agent = userAgent(env);
28
+ const mcp = new McpServer({ name: "asecret", version: VERSION });
29
+
30
+ async function session() {
31
+ const saved = await loadCredentials(credentialsFile(env, home), api);
32
+ const token = setting(env, "TOKEN") || saved?.token;
33
+ if (!token || !saved?.keys) throw new Error("This agent is not connected on this machine. Run asecret connect in a terminal first.");
34
+ return { client: createClient({ base: api, token, userAgent: agent, fetch: send }), keys: storage.keysOf(saved), saved };
35
+ }
36
+
37
+ /** @param {(s: Awaited<ReturnType<typeof session>>) => Promise<any>} work */
38
+ const run = async (work) => {
39
+ try {
40
+ return await work(await session());
41
+ } catch (error) {
42
+ return refuse(/** @type {Error} */ (error).message);
43
+ }
44
+ };
45
+
46
+ mcp.registerTool(
47
+ "list_secrets",
48
+ {
49
+ description:
50
+ "List the names of the secrets this agent keeps in aSecret. No tool returns a value: to use one, run a command with it in its environment, `asecret run --secret NAME -- <command>`, so the value never enters the conversation.",
51
+ inputSchema: z.strictObject({}),
52
+ annotations: { readOnlyHint: true },
53
+ },
54
+ () =>
55
+ run(async ({ client, keys }) => {
56
+ const names = (await storage.secrets(client, keys)).map((entry) => entry.meta?.name);
57
+ return reply({ names, use: "asecret run --secret NAME -- <command>" });
58
+ }),
59
+ );
60
+
61
+ // Asks to the person's aSecret server, through the same tools the server's MCP adapter offers.
62
+ async function linked() {
63
+ const saved = await loadCredentials(credentialsFile(env, home), api);
64
+ const origin = saved?.server ?? new URL(api).origin;
65
+ return { origin, file: person.linkFile(dir, origin) };
66
+ }
67
+ /** @param {(server: any) => Promise<any>} action */
68
+ async function use(action) {
69
+ try {
70
+ // Linked by code on asecret.sh: asks go through the storage API, with this agent's token.
71
+ const saved = await loadCredentials(credentialsFile(env, home), api);
72
+ if (!saved?.server) {
73
+ const { client } = await session();
74
+ const profiles = (await client.discovery())?.profiles ?? [];
75
+ if (profiles.includes("person-link") && profiles.includes("agent-http")) {
76
+ if (!(await client.me()).linked) return refuse("Link this agent to your person first: asecret link");
77
+ return reply(await action(person.hostedServer(client)));
78
+ }
79
+ }
80
+ const { origin, file } = await linked();
81
+ const { server } = await person.session(origin, file, send);
82
+ return reply(await action(server));
83
+ } catch (error) {
84
+ if (error instanceof ApiError || error instanceof UsageError) return refuse(error.message);
85
+ const code = error instanceof core.ServerError ? error.code : "connection_required";
86
+ return refuse(code === "connection_required" ? "Link this agent to your person's aSecret server first: asecret link" : code);
87
+ }
88
+ }
89
+ /** @param {(origin: string, options: any) => Promise<any>} lookup */
90
+ const publicLink = (lookup) => async () => {
91
+ try {
92
+ return reply(await lookup((await linked()).origin, { fetcher: send }));
93
+ } catch (error) {
94
+ return refuse(/** @type {Error} */ (error).message);
95
+ }
96
+ };
97
+ core.registerServerTools(mcp, use, {
98
+ directory: publicLink(core.getPublicDirectory),
99
+ formLink: publicLink(core.privateWebsiteFormLink),
100
+ setupLink: publicLink(core.privateOwnerSetupLink),
101
+ });
102
+ return mcp;
103
+ }
104
+
105
+ export async function serve() {
106
+ await storageServer().connect(new StdioServerTransport());
107
+ }