@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/CHANGELOG.md +16 -0
- package/LICENSE +21 -0
- package/README.md +72 -2
- package/bin/asecret-mcp.js +4 -0
- package/bin/asecret.js +12 -0
- package/core/spec/0.2/messages.schema.json +751 -0
- package/core/src/agent-crypto.js +191 -0
- package/core/src/agent.js +237 -0
- package/core/src/assistant-instructions.js +64 -0
- package/core/src/authorization.js +266 -0
- package/core/src/credentials.js +149 -0
- package/core/src/host-login.js +110 -0
- package/core/src/mcp-tools.js +130 -0
- package/core/src/wire.js +76 -0
- package/package.json +68 -4
- package/skill/SKILL.md +66 -0
- package/src/agents.js +140 -0
- package/src/api.js +188 -0
- package/src/commands.js +864 -0
- package/src/config.js +76 -0
- package/src/core.d.ts +55 -0
- package/src/core.js +19 -0
- package/src/errors.js +11 -0
- package/src/main.js +520 -0
- package/src/mcp.js +107 -0
- package/src/output.js +93 -0
- package/src/server.js +242 -0
- package/src/storage.js +137 -0
package/core/src/wire.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import Ajv from 'ajv';
|
|
2
|
+
import addFormats from 'ajv-formats';
|
|
3
|
+
import schema from '../spec/0.2/messages.schema.json' with { type: 'json' };
|
|
4
|
+
|
|
5
|
+
export const detailTypes = Object.freeze([...schema.definitions.saveRequest.properties.detail_type.enum]);
|
|
6
|
+
export const orderStatuses = Object.freeze([
|
|
7
|
+
...schema.definitions.orderStatusConfirmed.properties.result.properties.order_status.enum,
|
|
8
|
+
]);
|
|
9
|
+
|
|
10
|
+
export function saveIntent(detailType) {
|
|
11
|
+
return detailType === 'payment_method'
|
|
12
|
+
? { operation: 'payments.save_method' }
|
|
13
|
+
: { operation: 'details.save', detail_type: detailType };
|
|
14
|
+
}
|
|
15
|
+
export function requestShape(operation) {
|
|
16
|
+
switch (operation) {
|
|
17
|
+
case 'details.request_setup':
|
|
18
|
+
return 'setupRequest';
|
|
19
|
+
case 'orders.get_status':
|
|
20
|
+
return 'orderStatusRequest';
|
|
21
|
+
case 'details.save':
|
|
22
|
+
return 'saveRequest';
|
|
23
|
+
case 'payments.save_method':
|
|
24
|
+
return 'paymentSetupRequest';
|
|
25
|
+
case 'orders.set_delivery_address':
|
|
26
|
+
return 'addressRequest';
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const ajv = new Ajv();
|
|
31
|
+
addFormats(ajv);
|
|
32
|
+
ajv.addSchema(schema, 'asecret-wire');
|
|
33
|
+
const validators = Object.fromEntries(
|
|
34
|
+
Object.keys(schema.definitions).map((name) => [name, ajv.getSchema('asecret-wire#/definitions/' + name)]),
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
export function conforms(shape, value) {
|
|
38
|
+
return validators[shape](value);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function check(shape, value) {
|
|
42
|
+
if (!conforms(shape, value)) throw new Error('Invalid aSecret message: ' + shape);
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function httpsURL(value, expectedOrigin) {
|
|
47
|
+
const url = new URL(value);
|
|
48
|
+
if (
|
|
49
|
+
url.protocol !== 'https:' ||
|
|
50
|
+
url.username ||
|
|
51
|
+
url.password ||
|
|
52
|
+
url.hash ||
|
|
53
|
+
(expectedOrigin && url.origin !== expectedOrigin)
|
|
54
|
+
) {
|
|
55
|
+
throw new Error('Invalid server URL');
|
|
56
|
+
}
|
|
57
|
+
return url;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function readJSON(response, maxBytes = 64 * 1024) {
|
|
61
|
+
if (response.headers.get('content-type')?.split(';')[0].trim() !== 'application/json') {
|
|
62
|
+
throw new Error('Server returned an unexpected content type');
|
|
63
|
+
}
|
|
64
|
+
const chunks = [];
|
|
65
|
+
let length = 0;
|
|
66
|
+
for await (const chunk of response.body ?? []) {
|
|
67
|
+
length += chunk.length;
|
|
68
|
+
if (length > maxBytes) throw new Error('Server response is too large');
|
|
69
|
+
chunks.push(chunk);
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
73
|
+
} catch {
|
|
74
|
+
throw new Error('Server returned invalid JSON');
|
|
75
|
+
}
|
|
76
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@asecret/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Agents use your secrets without seeing them: an agent's own secrets, encrypted, and asks to its person for a detail they keep. aSecret's command-line tools and local MCP server.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"asecret": "bin/asecret.js",
|
|
8
|
+
"asecret-mcp": "bin/asecret-mcp.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"src",
|
|
13
|
+
"core",
|
|
14
|
+
"skill",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE",
|
|
17
|
+
"CHANGELOG.md"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"test": "node --test test/*.test.js",
|
|
21
|
+
"check": "tsc -p .",
|
|
22
|
+
"lint": "biome lint .",
|
|
23
|
+
"gate": "npm run lint && npm run check && npm test",
|
|
24
|
+
"start": "node bin/asecret.js"
|
|
25
|
+
},
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=24"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"cli",
|
|
31
|
+
"encryption",
|
|
32
|
+
"secrets",
|
|
33
|
+
"api-keys",
|
|
34
|
+
"private-details",
|
|
35
|
+
"agents",
|
|
36
|
+
"ai-agents",
|
|
37
|
+
"agent-skills",
|
|
38
|
+
"skills",
|
|
39
|
+
"mcp",
|
|
40
|
+
"claude-code",
|
|
41
|
+
"codex",
|
|
42
|
+
"cursor",
|
|
43
|
+
"gemini-cli",
|
|
44
|
+
"openclaw"
|
|
45
|
+
],
|
|
46
|
+
"homepage": "https://asecret.sh",
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/asecret-org/cli.git"
|
|
50
|
+
},
|
|
51
|
+
"bugs": {
|
|
52
|
+
"url": "https://github.com/asecret-org/cli/issues"
|
|
53
|
+
},
|
|
54
|
+
"author": "aSecret, part of aGroup <contact@asecret.sh>",
|
|
55
|
+
"license": "MIT",
|
|
56
|
+
"dependencies": {
|
|
57
|
+
"@modelcontextprotocol/server": "^2.4.0",
|
|
58
|
+
"ajv": "^8.17.1",
|
|
59
|
+
"ajv-formats": "^3.0.1",
|
|
60
|
+
"zod": "^4.6.7"
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@biomejs/biome": "2.6.4",
|
|
64
|
+
"@types/node": "^22.10.0",
|
|
65
|
+
"typescript": "5.9.3"
|
|
66
|
+
},
|
|
67
|
+
"publishConfig": {
|
|
68
|
+
"access": "public"
|
|
69
|
+
}
|
|
70
|
+
}
|
package/skill/SKILL.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: asecret
|
|
3
|
+
description: "Agents use your secrets without seeing them: keep API keys and passwords encrypted, use one in a command without printing it, and ask your user for a private detail they keep, then learn only the outcome."
|
|
4
|
+
metadata:
|
|
5
|
+
version: "0.1.0"
|
|
6
|
+
homepage: "https://asecret.sh"
|
|
7
|
+
api_version: "v1"
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
# aSecret
|
|
11
|
+
|
|
12
|
+
Use aSecret when a task needs a secret, such as an API key, a token or a password, or one of your user's own private details. Every secret is encrypted on this machine before it leaves, and aSecret keeps only ciphertext. You use a secret by handing it to a command, never by reading it: a value you read ends up in your conversation, and from there in logs and transcripts. When a task needs your user's own detail, such as their address or membership number, you ask them, they decide in their browser, and you learn only the outcome.
|
|
13
|
+
|
|
14
|
+
aSecret is for secrets and details. For files and notes, use aFile (afile.sh, the `afile` skill).
|
|
15
|
+
|
|
16
|
+
## Connect once
|
|
17
|
+
|
|
18
|
+
Install the CLI with `npm install -g @asecret/cli`, then run `asecret connect`. It registers this agent with no account and creates its key on this machine. Run `asecret key --export --out <file>` and tell your user where the file is. Without the key, your secrets can't be read again. Keep the key, the token and the export out of logs, messages and shared transcripts.
|
|
19
|
+
|
|
20
|
+
## Keep a secret
|
|
21
|
+
|
|
22
|
+
A value goes in only through standard input, never on the command line or in chat:
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
printf %s "$OPENAI_API_KEY" | asecret save OPENAI_API_KEY
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Name a secret the way an environment variable is named. Saving the same name again keeps a new version, and the one before stays for 30 days. A secret can be up to 64 KiB.
|
|
29
|
+
|
|
30
|
+
When your user wants to give you a secret, ask them to run `asecret save NAME` in a terminal on this machine themselves. It asks for the value without showing it. Never ask them to paste a value into chat. If they paste one anyway, don't repeat it, and suggest they replace it at its provider and save the new one themselves.
|
|
31
|
+
|
|
32
|
+
## Use a secret
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
asecret run --secret OPENAI_API_KEY -- python agent.py
|
|
36
|
+
asecret run --secret GITHUB_TOKEN --secret NPM_TOKEN -- ./release.sh
|
|
37
|
+
asecret list
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`run` decrypts each `--secret` and sets it, under its own name, in that command's environment alone, and prints nothing about it. `list` shows names only. Never print or paste a value: don't run `asecret get` unless your user asks to see a value themselves, and never echo a secret, log it, or write it into a file, a message or a command line. Watch the command you run too: one that prints its environment would print the secret. Run `asecret delete NAME --yes` only when your user asks.
|
|
41
|
+
|
|
42
|
+
## Link your user
|
|
43
|
+
|
|
44
|
+
When your user wants to see what you keep, or be able to recover it, run `asecret link` and show them the printed address and code unchanged. They open it signed in to asecret.sh, check the code and approve this agent there. The command waits until they decide; if it stops first, the code still works for 15 minutes. Once linked, they see your secrets by name, never their values, and can delete them, pause you or unlink you. If they turn on agent recovery there, you give them your key, sealed so only they can open it, and they can reveal and recover your secrets too. `asecret me` shows whether you are linked and whether recovery is on. Run `asecret unlink --yes` only when your user asks.
|
|
45
|
+
|
|
46
|
+
## Ask your user for a detail
|
|
47
|
+
|
|
48
|
+
Once linked, you can ask your user for one of their own details: `postal_address`, `email`, `phone`, `membership`, `secure_note`, `api_key`, `password`, `id_number` or `document`. `asecret ask setup` asks them to set up several at once.
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
asecret ask postal_address
|
|
52
|
+
asecret ask setup
|
|
53
|
+
asecret asks
|
|
54
|
+
asecret check <ask> --wait
|
|
55
|
+
asecret cancel <ask>
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Show the printed review link unchanged and say why the task needs the detail. They open it signed in to asecret.sh, choose or add the detail in their browser, and answer. You learn only that it's saved or ready, never the detail. Wait for `confirmed` before you continue the task. A declined, expired or canceled ask ends that step: tell your user and leave it pending. An ask waits 15 minutes, and while your user has paused you, you can't ask. A saved detail gives you no permission to send it, sign in to an account or make a purchase. Before linking, `asecret ask <type>` prints a public save page instead, which isn't tracked.
|
|
59
|
+
|
|
60
|
+
Payment methods, website forms and deliveries to merchants (`asecret ask payment_method`, `asecret ask form`, `asecret ask address --to <recipient> --order <id>`) need your user's own aSecret server, one they run themselves. Link to it with `asecret link --server <origin>`; asks then go there.
|
|
61
|
+
|
|
62
|
+
## Setup
|
|
63
|
+
|
|
64
|
+
`asecret add` installs this skill for the agents on this machine. `asecret mcp` runs a local MCP server over stdio (`claude mcp add asecret -- asecret mcp`), with `list_secrets`, which gives names only, and the tools that ask your user. No tool returns a value. `asecret mcp --print --host claude` prints a settings entry instead. Use `--json` when you need the exact fields. Set `ASECRET_CONFIG_DIR` for a separate agent on the same machine, `ASECRET_API_URL` for another aSecret server, or `ASECRET_TOKEN` to use an existing token.
|
|
65
|
+
|
|
66
|
+
[CLI](https://github.com/asecret-org/cli) · [Protocol](https://github.com/asecret-org/protocol) · [aFile](https://afile.sh)
|
package/src/agents.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Where each agent reads skills from, and adding or removing the aSecret
|
|
2
|
+
// skill there. The folders follow the open skills ecosystem, so a copy added
|
|
3
|
+
// here sits exactly where `npx skills add` would put it.
|
|
4
|
+
|
|
5
|
+
import { existsSync } from "node:fs";
|
|
6
|
+
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
|
|
9
|
+
export const SKILL = "asecret";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @typedef {{ id: string, name: string, project: string, global: string, installed: boolean }} Agent
|
|
13
|
+
* @param {{ home: string, env: NodeJS.ProcessEnv }} where
|
|
14
|
+
* @returns {Agent[]}
|
|
15
|
+
*/
|
|
16
|
+
export function agents({ home, env }) {
|
|
17
|
+
const config = env.XDG_CONFIG_HOME?.trim() || join(home, ".config");
|
|
18
|
+
const claude = env.CLAUDE_CONFIG_DIR?.trim() || join(home, ".claude");
|
|
19
|
+
const codex = env.CODEX_HOME?.trim() || join(home, ".codex");
|
|
20
|
+
const hermes = env.HERMES_HOME?.trim() || join(home, ".hermes");
|
|
21
|
+
const claw = [".openclaw", ".clawdbot", ".moltbot"].map((dir) => join(home, dir)).find((dir) => existsSync(dir));
|
|
22
|
+
/** @type {[string, string, string, string, string | false][]} id, name, project folder, global folder, what shows it is installed */
|
|
23
|
+
const table = [
|
|
24
|
+
["claude-code", "Claude Code", ".claude/skills", join(claude, "skills"), claude],
|
|
25
|
+
["codex", "Codex", ".agents/skills", join(codex, "skills"), codex],
|
|
26
|
+
["cursor", "Cursor", ".agents/skills", join(home, ".cursor/skills"), join(home, ".cursor")],
|
|
27
|
+
["gemini-cli", "Gemini CLI", ".agents/skills", join(home, ".gemini/skills"), join(home, ".gemini")],
|
|
28
|
+
["github-copilot", "GitHub Copilot", ".agents/skills", join(home, ".copilot/skills"), join(home, ".copilot")],
|
|
29
|
+
["opencode", "OpenCode", ".agents/skills", join(config, "opencode/skills"), join(config, "opencode")],
|
|
30
|
+
["openclaw", "OpenClaw", "skills", join(claw ?? join(home, ".openclaw"), "skills"), claw ?? false],
|
|
31
|
+
["hermes-agent", "Hermes Agent", ".hermes/skills", join(hermes, "skills"), hermes],
|
|
32
|
+
["amp", "Amp", ".agents/skills", join(config, "agents/skills"), join(config, "amp")],
|
|
33
|
+
["cline", "Cline", ".agents/skills", join(home, ".agents/skills"), join(home, ".cline")],
|
|
34
|
+
["goose", "Goose", ".goose/skills", join(config, "goose/skills"), join(config, "goose")],
|
|
35
|
+
["junie", "Junie", ".junie/skills", join(home, ".junie/skills"), join(home, ".junie")],
|
|
36
|
+
["kiro-cli", "Kiro CLI", ".kiro/skills", join(home, ".kiro/skills"), join(home, ".kiro")],
|
|
37
|
+
["roo", "Roo Code", ".roo/skills", join(home, ".roo/skills"), join(home, ".roo")],
|
|
38
|
+
["trae", "Trae", ".trae/skills", join(home, ".trae/skills"), join(home, ".trae")],
|
|
39
|
+
["warp", "Warp", ".agents/skills", join(home, ".agents/skills"), join(home, ".warp")],
|
|
40
|
+
["windsurf", "Windsurf", ".windsurf/skills", join(home, ".codeium/windsurf/skills"), join(home, ".codeium/windsurf")],
|
|
41
|
+
["universal", "Any agent that reads .agents/skills", ".agents/skills", join(config, "agents/skills"), false],
|
|
42
|
+
];
|
|
43
|
+
return table.map(([id, name, project, global, marker]) => ({
|
|
44
|
+
id,
|
|
45
|
+
name,
|
|
46
|
+
project,
|
|
47
|
+
global,
|
|
48
|
+
installed: marker ? existsSync(marker) : false,
|
|
49
|
+
}));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The agents to add the skill for: those named with --agent, or every agent
|
|
54
|
+
* found on this machine, or the shared .agents folder when none is found.
|
|
55
|
+
* @param {Agent[]} all
|
|
56
|
+
* @param {string[]} requested
|
|
57
|
+
*/
|
|
58
|
+
export function chooseAgents(all, requested) {
|
|
59
|
+
if (requested.includes("*")) return all;
|
|
60
|
+
if (requested.length) {
|
|
61
|
+
const unknown = requested.filter((id) => !all.some((agent) => agent.id === id));
|
|
62
|
+
if (unknown.length) {
|
|
63
|
+
throw new Error(`Unknown agent: ${unknown.join(", ")}. Known agents: ${all.map((a) => a.id).join(", ")}`);
|
|
64
|
+
}
|
|
65
|
+
return all.filter((agent) => requested.includes(agent.id));
|
|
66
|
+
}
|
|
67
|
+
const found = all.filter((agent) => agent.installed);
|
|
68
|
+
return found.length ? found : all.filter((agent) => agent.id === "universal");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Each skill folder once, with every agent that reads it.
|
|
73
|
+
* @param {Agent[]} chosen
|
|
74
|
+
* @param {{ global: boolean, cwd: string }} scope
|
|
75
|
+
*/
|
|
76
|
+
export function targets(chosen, { global, cwd }) {
|
|
77
|
+
/** @type {Map<string, string[]>} */
|
|
78
|
+
const byDir = new Map();
|
|
79
|
+
for (const agent of chosen) {
|
|
80
|
+
const dir = join(global ? agent.global : join(cwd, agent.project), SKILL);
|
|
81
|
+
byDir.set(dir, [...(byDir.get(dir) ?? []), agent.name]);
|
|
82
|
+
}
|
|
83
|
+
return [...byDir].map(([dir, names]) => ({ dir, names }));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The `name:` in a SKILL.md's frontmatter. @param {string} text */
|
|
87
|
+
export function skillName(text) {
|
|
88
|
+
const front = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
89
|
+
return front?.[1].match(/^name:\s*["']?([^"'\r\n]+?)["']?\s*$/m)?.[1] ?? null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The `version:` in a SKILL.md's metadata. @param {string} text */
|
|
93
|
+
export function skillVersion(text) {
|
|
94
|
+
const front = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
95
|
+
return front?.[1].match(/^\s+version:\s*["']?([^"'\r\n]+?)["']?\s*$/m)?.[1] ?? null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What is in a skill folder now: nothing, our skill, or somebody else's. @param {string} dir */
|
|
99
|
+
export async function occupant(dir) {
|
|
100
|
+
let text;
|
|
101
|
+
try {
|
|
102
|
+
text = await readFile(join(dir, "SKILL.md"), "utf8");
|
|
103
|
+
} catch {
|
|
104
|
+
return existsSync(dir) ? { kind: /** @type {const} */ ("other"), version: null } : { kind: /** @type {const} */ ("none"), version: null };
|
|
105
|
+
}
|
|
106
|
+
const name = skillName(text);
|
|
107
|
+
return name === SKILL
|
|
108
|
+
? { kind: /** @type {const} */ ("ours"), version: skillVersion(text) }
|
|
109
|
+
: { kind: /** @type {const} */ ("other"), version: null };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** @param {string} dir @param {Record<string, string>} files */
|
|
113
|
+
export async function writeSkill(dir, files) {
|
|
114
|
+
await mkdir(dir, { recursive: true });
|
|
115
|
+
for (const [name, text] of Object.entries(files)) await writeFile(join(dir, name), text);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** @param {string} dir */
|
|
119
|
+
export async function removeSkill(dir) {
|
|
120
|
+
await rm(dir, { recursive: true, force: true });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The skill as aSecret publishes it now.
|
|
125
|
+
* @param {string} web
|
|
126
|
+
* @param {{ fetch: typeof fetch, userAgent: string }} io
|
|
127
|
+
*/
|
|
128
|
+
export async function downloadSkill(web, { fetch: send, userAgent }) {
|
|
129
|
+
const root = web.replace(/\/+$/, "");
|
|
130
|
+
/** @type {Record<string, string>} */
|
|
131
|
+
const files = {};
|
|
132
|
+
// aSecret's skill is one file; aMessage's also carries a heartbeat.
|
|
133
|
+
const response = await send(`${root}/skill.md`, { headers: { "User-Agent": userAgent, Accept: "text/markdown" } });
|
|
134
|
+
if (!response.ok) throw new Error(`Could not download ${root}/skill.md (${response.status}).`);
|
|
135
|
+
files["SKILL.md"] = await response.text();
|
|
136
|
+
if (skillName(files["SKILL.md"]) !== SKILL) {
|
|
137
|
+
throw new Error(`${root}/skill.md is not the aSecret skill. Nothing was written.`);
|
|
138
|
+
}
|
|
139
|
+
return { files, version: skillVersion(files["SKILL.md"]) };
|
|
140
|
+
}
|
package/src/api.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { frameItem, ITEM_TYPE } from "./core.js";
|
|
3
|
+
// The aSecret API for an agent's secrets, as described in spec/0.2/agent-secrets.md.
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_API = "https://api.asecret.sh";
|
|
6
|
+
export const DEFAULT_WEB = "https://asecret.sh";
|
|
7
|
+
|
|
8
|
+
/** What each refusal means, in the words the CLI uses when the API gives no detail. */
|
|
9
|
+
const MEANING = /** @type {Record<string, string>} */ ({
|
|
10
|
+
invalid_request: "aSecret could not use that request.",
|
|
11
|
+
invalid_token: "aSecret did not accept this agent's token.",
|
|
12
|
+
not_found: "Nothing with that id belongs to this agent.",
|
|
13
|
+
precondition_required: "aSecret needs the secret's current ETag for this change.",
|
|
14
|
+
precondition_failed: "The secret changed since it was read.",
|
|
15
|
+
idempotency_conflict: "That --key was already used for a different write.",
|
|
16
|
+
item_too_large: "A secret can be up to 64 KiB.",
|
|
17
|
+
quota_exceeded: "This agent's secrets fill its space at aSecret.",
|
|
18
|
+
invalid_grant: "That server link is not live at this server.",
|
|
19
|
+
not_linked: "This agent is not linked to a person yet.",
|
|
20
|
+
recovery_off: "This agent's person hasn't turned on agent recovery.",
|
|
21
|
+
rate_limited: "Too many requests for now.",
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
/** What to do next, for the refusals that have one. */
|
|
25
|
+
const NEXT = /** @type {Record<string, string>} */ ({
|
|
26
|
+
precondition_failed: "It changed while this ran. Run the command again.",
|
|
27
|
+
quota_exceeded: "Delete secrets you no longer need: asecret list",
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
/** A refusal from the API, carrying its problem details. */
|
|
31
|
+
export class ApiError extends Error {
|
|
32
|
+
/**
|
|
33
|
+
* @param {number} status
|
|
34
|
+
* @param {any} problem
|
|
35
|
+
* @param {string | null} retryAfter
|
|
36
|
+
*/
|
|
37
|
+
constructor(status, problem, retryAfter) {
|
|
38
|
+
const code = problem?.code ?? problem?.error ?? null;
|
|
39
|
+
super(problem?.detail || problem?.title || MEANING[code] || `The API answered ${status}`);
|
|
40
|
+
this.status = status;
|
|
41
|
+
this.problem = problem;
|
|
42
|
+
this.code = code;
|
|
43
|
+
/** What the API says to do next, printed under the message. */
|
|
44
|
+
this.next = typeof problem?.next === "string" ? problem.next : (NEXT[code] ?? null);
|
|
45
|
+
this.retryAfter = retryAfter;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** An authenticated call with no token to send. */
|
|
50
|
+
export class NotConnected extends Error {
|
|
51
|
+
constructor() {
|
|
52
|
+
super("This agent is not connected to aSecret yet.");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Bytes as the base64url the API takes. @param {Uint8Array} bytes */
|
|
57
|
+
export const base64url = (bytes) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64url");
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @typedef {{ base: string, token?: string | null, userAgent: string, fetch?: typeof fetch }} ClientOptions
|
|
61
|
+
* @typedef {{ body?: unknown, upload?: { fields: Record<string, unknown>, content: Uint8Array }, query?: Record<string, string | number | undefined | null>, auth?: "required" | "optional", headers?: Record<string, string>, withTag?: boolean, raw?: boolean, origin?: string }} RequestOptions
|
|
62
|
+
*/
|
|
63
|
+
|
|
64
|
+
/** @param {ClientOptions} options */
|
|
65
|
+
export function createClient({ base, token = null, userAgent, fetch: send = globalThis.fetch }) {
|
|
66
|
+
const root = base.replace(/\/+$/, "");
|
|
67
|
+
// Whether the API's last answer said this agent's person wants its key (asecret-escrow: wanted).
|
|
68
|
+
let escrowWanted = false;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @param {string} method
|
|
72
|
+
* @param {string} path
|
|
73
|
+
* @param {RequestOptions} [options]
|
|
74
|
+
* @returns {Promise<any>}
|
|
75
|
+
*/
|
|
76
|
+
async function request(method, path, { body, upload, query, auth, headers: extra = {}, withTag = false, raw = false, origin } = {}) {
|
|
77
|
+
const url = new URL((origin ?? root) + path);
|
|
78
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
79
|
+
if (value !== undefined && value !== null && value !== "") url.searchParams.set(key, String(value));
|
|
80
|
+
}
|
|
81
|
+
/** @type {Record<string, string>} */
|
|
82
|
+
const headers = {
|
|
83
|
+
Accept: raw ? "application/octet-stream" : "application/json",
|
|
84
|
+
"User-Agent": userAgent,
|
|
85
|
+
"asecret-version": "0.2",
|
|
86
|
+
...extra,
|
|
87
|
+
};
|
|
88
|
+
if (auth === "required" && !token) throw new NotConnected();
|
|
89
|
+
if (auth && token) headers.Authorization = `Bearer ${token}`;
|
|
90
|
+
/** @type {BodyInit | undefined} */
|
|
91
|
+
let payload;
|
|
92
|
+
if (upload) {
|
|
93
|
+
// Sealed bytes travel as they are, after their JSON fields, so servers need not decode them.
|
|
94
|
+
headers["Content-Type"] = ITEM_TYPE;
|
|
95
|
+
payload = /** @type {BodyInit} */ (/** @type {unknown} */ (frameItem(upload.fields, upload.content)));
|
|
96
|
+
} else if (body !== undefined) {
|
|
97
|
+
headers["Content-Type"] = "application/json";
|
|
98
|
+
payload = JSON.stringify(body);
|
|
99
|
+
}
|
|
100
|
+
const response = await send(url, { method, headers, body: payload, redirect: "error" });
|
|
101
|
+
if (!response.ok) {
|
|
102
|
+
const text = await response.text();
|
|
103
|
+
let problem = null;
|
|
104
|
+
try {
|
|
105
|
+
problem = text ? JSON.parse(text) : null;
|
|
106
|
+
} catch {
|
|
107
|
+
problem = { detail: text.slice(0, 500) };
|
|
108
|
+
}
|
|
109
|
+
throw new ApiError(response.status, problem, response.headers.get("retry-after"));
|
|
110
|
+
}
|
|
111
|
+
if (auth && token && !origin) escrowWanted = response.headers.get("asecret-escrow") === "wanted";
|
|
112
|
+
if (raw) return new Uint8Array(await response.arrayBuffer());
|
|
113
|
+
const text = await response.text();
|
|
114
|
+
const data = text ? JSON.parse(text) : null;
|
|
115
|
+
return withTag ? { data, etag: response.headers.get("etag") } : data;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const id = (/** @type {string} */ value) => encodeURIComponent(value);
|
|
119
|
+
|
|
120
|
+
/** @param {string} path @param {unknown} body @param {string} [key] */
|
|
121
|
+
const post = (path, body, key = randomUUID()) =>
|
|
122
|
+
request("POST", path, {
|
|
123
|
+
body,
|
|
124
|
+
auth: "required",
|
|
125
|
+
headers: { "Idempotency-Key": key },
|
|
126
|
+
});
|
|
127
|
+
/** @param {string} path @param {Record<string, unknown>} fields @param {Uint8Array} content @param {string} [key] */
|
|
128
|
+
const postUpload = (path, fields, content, key = randomUUID()) =>
|
|
129
|
+
request("POST", path, { upload: { fields, content }, auth: "required", headers: { "Idempotency-Key": key } });
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
/** The API asked for this agent's key for its person (PUT /v1/me/escrow), on its last answer. */
|
|
133
|
+
get escrowWanted() {
|
|
134
|
+
return escrowWanted;
|
|
135
|
+
},
|
|
136
|
+
async register() {
|
|
137
|
+
const { agent, token } = await request("POST", "/v1/agents", { body: {} });
|
|
138
|
+
return { ...agent, token };
|
|
139
|
+
},
|
|
140
|
+
discovery: () => request("GET", "/.well-known/asecret"),
|
|
141
|
+
me: () => request("GET", "/v1/me", { auth: "required" }),
|
|
142
|
+
/** A new token; the old one works until the new one is first used. */
|
|
143
|
+
rotateToken: () => request("POST", "/v1/me/token", { auth: "required" }),
|
|
144
|
+
/** Delete this agent with every secret it has. */
|
|
145
|
+
deleteAgent: () => request("DELETE", "/v1/me", { auth: "required" }),
|
|
146
|
+
/** @param {string} [cursor] @param {number} [limit] */
|
|
147
|
+
items: (cursor, limit) => request("GET", "/v1/items", { query: { cursor, limit }, auth: "required" }),
|
|
148
|
+
/** @param {string} item */
|
|
149
|
+
item: (item) => request("GET", `/v1/items/${id(item)}`, { auth: "required" }),
|
|
150
|
+
/** @param {string} item */
|
|
151
|
+
versions: (item) => request("GET", `/v1/items/${id(item)}/versions`, { auth: "required" }),
|
|
152
|
+
/** @param {string} item @param {number} [version] */
|
|
153
|
+
content: (item, version) =>
|
|
154
|
+
request("GET", `/v1/items/${id(item)}/content`, { query: { version }, auth: "required", raw: true }),
|
|
155
|
+
/** @param {Record<string, unknown>} fields @param {Uint8Array} content @param {string} [key] */
|
|
156
|
+
createItem: (fields, content, key) => postUpload("/v1/items", fields, content, key),
|
|
157
|
+
/** New fields, and new sealed bytes when the contents change. @param {string} item @param {Record<string, unknown>} fields @param {Uint8Array | undefined} content @param {string} etag */
|
|
158
|
+
updateItem: (item, fields, content, etag) =>
|
|
159
|
+
request("PUT", `/v1/items/${id(item)}`, {
|
|
160
|
+
...(content ? { upload: { fields, content } } : { body: fields }),
|
|
161
|
+
headers: { "If-Match": etag },
|
|
162
|
+
auth: "required",
|
|
163
|
+
}),
|
|
164
|
+
/** @param {string} item @param {string} etag */
|
|
165
|
+
deleteItem: (item, etag) =>
|
|
166
|
+
request("DELETE", `/v1/items/${id(item)}`, { headers: { "If-Match": etag }, auth: "required" }),
|
|
167
|
+
/** @param {string} accessToken */
|
|
168
|
+
linkPerson: (accessToken) => request("POST", "/v1/me/link", { body: { access_token: accessToken }, auth: "required" }),
|
|
169
|
+
/** @param {string} escrow */
|
|
170
|
+
setEscrow: (escrow) => request("PUT", "/v1/me/escrow", { body: { escrow }, auth: "required" }),
|
|
171
|
+
/** A code for this agent's person to approve at asecret.sh, replacing one still waiting. */
|
|
172
|
+
linkCode: () => request("POST", "/v1/me/link-code", { auth: "required" }),
|
|
173
|
+
/** This agent's latest link code: waiting, approved, declined or expired. */
|
|
174
|
+
linkCodeState: () => request("GET", "/v1/me/link-code", { auth: "required" }),
|
|
175
|
+
unlinkPerson: () => request("DELETE", "/v1/me/link", { auth: "required" }),
|
|
176
|
+
/**
|
|
177
|
+
* Ask the linked person (POST /v1/requests): save a detail, or set up aSecret. The same key
|
|
178
|
+
* brings back the same ask. @param {Record<string, unknown>} body @param {string} key
|
|
179
|
+
*/
|
|
180
|
+
ask: (body, key) => post("/v1/requests", body, key),
|
|
181
|
+
/** Where an ask stands. @param {string} ask */
|
|
182
|
+
askStatus: (ask) => request("GET", `/v1/requests/${id(ask)}`, { auth: "required" }),
|
|
183
|
+
/** Stop an ask that still waits. @param {string} ask */
|
|
184
|
+
cancelAsk: (ask) => request("POST", `/v1/requests/${id(ask)}/cancel`, { auth: "required" }),
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** @typedef {ReturnType<typeof createClient>} Client */
|