hardened-mcp 0.0.1 → 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/README.md +67 -4
- package/bin/hmcp.js +20 -0
- package/dist/classify.d.ts +42 -0
- package/dist/classify.js +77 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +445 -0
- package/dist/grants.d.ts +49 -0
- package/dist/grants.js +138 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/render.d.ts +30 -0
- package/dist/render.js +86 -0
- package/dist/store.d.ts +16 -0
- package/dist/store.js +25 -0
- package/dist/version.d.ts +10 -0
- package/dist/version.js +11 -0
- package/package.json +41 -4
package/README.md
CHANGED
|
@@ -1,6 +1,69 @@
|
|
|
1
1
|
# hardened-mcp
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
[hardened-mcp](https://github.com/aoutix/hardened-mcp) puts a safety check
|
|
4
|
+
between your AI app (Claude, Cursor, VS Code and others) and the MCP servers
|
|
5
|
+
that give it tools. Reading runs straight away. Changing or deleting something
|
|
6
|
+
can wait for your OK, and what you don't want can be blocked. Every call is
|
|
7
|
+
written down.
|
|
8
|
+
|
|
9
|
+
## Start here
|
|
10
|
+
|
|
11
|
+
You need Node.js 22.19 or newer. Then run:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npx hardened-mcp
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
That opens the hardened-mcp console in your browser, already signed in, on a
|
|
18
|
+
short guide. It takes about five minutes:
|
|
19
|
+
|
|
20
|
+
1. **Welcome**: what MCP servers are, and what the toolbox does.
|
|
21
|
+
2. **Check your computer**: finds what servers need (Node.js, uv, Docker,
|
|
22
|
+
Python, Git), with install steps for anything missing.
|
|
23
|
+
3. **Add your first server**: pick a ready-made one such as **Files on this
|
|
24
|
+
computer** or GitHub, search the public list, or paste a server's setup
|
|
25
|
+
instructions. **Test it** shows every tool before you save anything.
|
|
26
|
+
4. **Connect your AI app**: one click, then restart that app once.
|
|
27
|
+
5. **Try it**: a first thing to ask your AI.
|
|
28
|
+
6. **Choose how careful to be**: **Protect me now** (changes wait for your
|
|
29
|
+
OK), or **Watch first** (everything runs and is written down, and you turn
|
|
30
|
+
protection on later).
|
|
31
|
+
7. **You're set**.
|
|
32
|
+
|
|
33
|
+
Your AI apps keep working when the console is closed. You only need it to
|
|
34
|
+
approve things and to sign in to services. Run `npx hardened-mcp` again whenever you
|
|
35
|
+
want it back. The guide is always at `/start`.
|
|
36
|
+
|
|
37
|
+
Servers written in Python need a small program called uv. If you don't have it,
|
|
38
|
+
the guide shows you how to install it (on a Mac, one line to paste into
|
|
39
|
+
Terminal).
|
|
40
|
+
|
|
41
|
+
## Commands
|
|
42
|
+
|
|
43
|
+
`npx hardened-mcp` with no command is `npx hardened-mcp start`. Once installed
|
|
44
|
+
(`npm install -g hardened-mcp`), the same commands also answer to the shorter `hmcp`.
|
|
45
|
+
The rest are for the terminal, and
|
|
46
|
+
work whether or not your AI app can ask you itself:
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
hmcp start # open the console (the default)
|
|
50
|
+
hmcp pending # calls waiting for your decision
|
|
51
|
+
hmcp approve <id> # let one through, bound to its exact arguments
|
|
52
|
+
hmcp deny <id>
|
|
53
|
+
hmcp approvals # what has been decided
|
|
54
|
+
hmcp grant ... # see and withdraw pre-approvals
|
|
55
|
+
hmcp audit tail # every decision, allowed or refused
|
|
56
|
+
hmcp audit verify # check the activity log has not been edited
|
|
57
|
+
hmcp policy [file] # what a policy actually says, defaults included
|
|
58
|
+
hmcp --version
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Full documentation is in the
|
|
62
|
+
[repository README](https://github.com/aoutix/hardened-mcp#readme).
|
|
63
|
+
|
|
64
|
+
## License
|
|
65
|
+
|
|
66
|
+
Free to use, including at work, and you may change it for your own use. You may not sell it,
|
|
67
|
+
publish it, share copies of it, or offer it to others as a service. The terms are the
|
|
68
|
+
[PolyForm Internal Use License 1.0.0](https://polyformproject.org/licenses/internal-use/1.0.0)
|
|
69
|
+
with an added permission for personal use; see `LICENSE`. © 2026 Aditya Das
|
package/bin/hmcp.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/*
|
|
3
|
+
* The entry point npm links as `hmcp`.
|
|
4
|
+
*
|
|
5
|
+
* It is this file, and not dist/cli.js, because npm links a command when it
|
|
6
|
+
* installs and only if the file is already there. dist/ does not exist in a
|
|
7
|
+
* fresh clone until the build has run, so pointing the command at it meant the
|
|
8
|
+
* command was never linked, and `npx hardened-mcp` went looking on the registry.
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
|
|
13
|
+
const cli = new URL("../dist/cli.js", import.meta.url);
|
|
14
|
+
|
|
15
|
+
if (!existsSync(fileURLToPath(cli))) {
|
|
16
|
+
process.stderr.write("hmcp has not been built yet. From the repository root, run:\n\n npm run build\n\n");
|
|
17
|
+
process.exit(1);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
await import(cli.href);
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type ApprovalRow, type ApprovalStore, type Effect } from "hmcp-core";
|
|
2
|
+
/**
|
|
3
|
+
* `hmcp approve <id> --classify <effect>`.
|
|
4
|
+
*
|
|
5
|
+
* Its own module because `cli.ts` parses `process.argv` as soon as it is
|
|
6
|
+
* imported, so nothing in it can be exercised without running the program.
|
|
7
|
+
*
|
|
8
|
+
* `hmcp` is pointed at an approvals database, not at a gateway, so it has to
|
|
9
|
+
* find the policy file for the call it is approving. The gateway that held
|
|
10
|
+
* the call publishes the config it was started from; this follows that to the
|
|
11
|
+
* `policy:` file beside it. It reads two keys out of that config and nothing
|
|
12
|
+
* else, so this package does not have to depend on the gateway's.
|
|
13
|
+
*/
|
|
14
|
+
export declare class ClassifyError extends Error {
|
|
15
|
+
}
|
|
16
|
+
export interface ClassifyOnApprove {
|
|
17
|
+
readonly store: ApprovalStore;
|
|
18
|
+
readonly row: ApprovalRow;
|
|
19
|
+
readonly effect: Effect;
|
|
20
|
+
readonly actor: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The policy file of the gateway a row belongs to, and whether it may be
|
|
24
|
+
* written. `fallback` is what to tell the operator to do instead when it
|
|
25
|
+
* cannot be found.
|
|
26
|
+
*/
|
|
27
|
+
export declare function policyFor(store: ApprovalStore, row: {
|
|
28
|
+
readonly component: string;
|
|
29
|
+
readonly tool?: string;
|
|
30
|
+
}, fallback?: string): {
|
|
31
|
+
policyPath: string;
|
|
32
|
+
writesAllowed: boolean;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Writes the rule. Does not decide the approval: the caller does that next,
|
|
36
|
+
* so a classification that cannot be written stops before anything changes.
|
|
37
|
+
*/
|
|
38
|
+
export declare function classifyOnApprove(options: ClassifyOnApprove): {
|
|
39
|
+
ruleId: string;
|
|
40
|
+
decision: "allow" | "approve";
|
|
41
|
+
policyPath: string;
|
|
42
|
+
};
|
package/dist/classify.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { parse as parseYaml } from "yaml";
|
|
4
|
+
import { AuditLog, classifyHeldTool, expandPath, loadPolicy } from "hmcp-core";
|
|
5
|
+
/**
|
|
6
|
+
* `hmcp approve <id> --classify <effect>`.
|
|
7
|
+
*
|
|
8
|
+
* Its own module because `cli.ts` parses `process.argv` as soon as it is
|
|
9
|
+
* imported, so nothing in it can be exercised without running the program.
|
|
10
|
+
*
|
|
11
|
+
* `hmcp` is pointed at an approvals database, not at a gateway, so it has to
|
|
12
|
+
* find the policy file for the call it is approving. The gateway that held
|
|
13
|
+
* the call publishes the config it was started from; this follows that to the
|
|
14
|
+
* `policy:` file beside it. It reads two keys out of that config and nothing
|
|
15
|
+
* else, so this package does not have to depend on the gateway's.
|
|
16
|
+
*/
|
|
17
|
+
export class ClassifyError extends Error {
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The policy file of the gateway a row belongs to, and whether it may be
|
|
21
|
+
* written. `fallback` is what to tell the operator to do instead when it
|
|
22
|
+
* cannot be found.
|
|
23
|
+
*/
|
|
24
|
+
export function policyFor(store, row, fallback = `Classify it with the gateway's own command instead: hmcp-gateway rule ${row.tool ?? "<tool>"}`) {
|
|
25
|
+
const state = store.runtimeState(row.component);
|
|
26
|
+
if (!state || !state.policy_path) {
|
|
27
|
+
throw new ClassifyError(`no gateway has recorded where the config for "${row.component}" is, so the policy to write cannot be found. ` +
|
|
28
|
+
fallback);
|
|
29
|
+
}
|
|
30
|
+
const configPath = expandPath(state.policy_path);
|
|
31
|
+
if (!existsSync(configPath)) {
|
|
32
|
+
throw new ClassifyError(`the gateway config recorded for "${row.component}" is not at ${configPath}. ${fallback}`);
|
|
33
|
+
}
|
|
34
|
+
const config = parseYaml(readFileSync(configPath, "utf8"));
|
|
35
|
+
if (typeof config?.policy !== "string") {
|
|
36
|
+
throw new ClassifyError(`the policy for "${row.component}" is inline in ${configPath}, which is not edited from here. ` +
|
|
37
|
+
fallback);
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
policyPath: expandPath(config.policy, dirname(configPath)),
|
|
41
|
+
writesAllowed: config.policy_writes !== false
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Writes the rule. Does not decide the approval: the caller does that next,
|
|
46
|
+
* so a classification that cannot be written stops before anything changes.
|
|
47
|
+
*/
|
|
48
|
+
export function classifyOnApprove(options) {
|
|
49
|
+
const { store, row, effect, actor } = options;
|
|
50
|
+
const { policyPath, writesAllowed } = policyFor(store, row);
|
|
51
|
+
const policy = loadPolicy(policyPath);
|
|
52
|
+
/*
|
|
53
|
+
* What calls get from now on follows the posture rather than being asked
|
|
54
|
+
* for: a read runs, anything that mutates keeps waiting for a person. That
|
|
55
|
+
* is what the gateway would have done had the tool been classified from the
|
|
56
|
+
* start, so saying what the tool *is* does not also become a way of
|
|
57
|
+
* granting it more than the policy grants its kind.
|
|
58
|
+
*/
|
|
59
|
+
const decision = effect === "read" && policy.defaults.mode !== "locked" ? "allow" : "approve";
|
|
60
|
+
try {
|
|
61
|
+
const { ruleId } = classifyHeldTool({
|
|
62
|
+
policyPath,
|
|
63
|
+
row,
|
|
64
|
+
effect,
|
|
65
|
+
decision,
|
|
66
|
+
actor,
|
|
67
|
+
writesAllowed,
|
|
68
|
+
audit: new AuditLog({ config: policy.audit, component: row.component, actor, cwd: dirname(policyPath) }),
|
|
69
|
+
tenant: row.tenant || null,
|
|
70
|
+
via: "hmcp approve"
|
|
71
|
+
});
|
|
72
|
+
return { ruleId, decision, policyPath };
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
throw new ClassifyError(err.message);
|
|
76
|
+
}
|
|
77
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { Command } from "commander";
|
|
5
|
+
import { StoreNotFound, storeAt } from "./store.js";
|
|
6
|
+
import { NotADatabase } from "hmcp-core";
|
|
7
|
+
import { describePending, scopeLabel, describeAuditRecord } from "./render.js";
|
|
8
|
+
import { escapeForDisplay } from "hmcp-scanner";
|
|
9
|
+
import { parse as parseYaml } from "yaml";
|
|
10
|
+
import { ApprovalStore, defaultPolicy, expandPath, loadPolicy, parsePolicy, PolicyError, queryAuditLog, verifyAuditLog, EffectSchema, REMEMBER_DEFAULT_TTL_SECONDS, REMEMBER_DEFAULT_USES } from "hmcp-core";
|
|
11
|
+
import { VERSION } from "./version.js";
|
|
12
|
+
import { ClassifyError, classifyOnApprove } from "./classify.js";
|
|
13
|
+
import { GrantCommandError, describeGrant, listGrants, parseDuration, rememberOnApprove, revokeGrant } from "./grants.js";
|
|
14
|
+
const program = new Command();
|
|
15
|
+
program
|
|
16
|
+
.name("hardened-mcp")
|
|
17
|
+
.description("Start the hardened-mcp console (the default, with its setup guide), review approvals and verify the audit trail.")
|
|
18
|
+
.version(VERSION);
|
|
19
|
+
/* ---------------------------------------------------------------------- start */
|
|
20
|
+
/*
|
|
21
|
+
* `hmcp` on its own starts the console and opens it in the browser: the one
|
|
22
|
+
* command a new user is told to run. Every other subcommand is unchanged.
|
|
23
|
+
* Loaded on demand so `hmcp pending` does not pay for the console's imports.
|
|
24
|
+
*/
|
|
25
|
+
program
|
|
26
|
+
.command("start", { isDefault: true })
|
|
27
|
+
.description("Open the hardened-mcp console in your browser (the default when no command is given).")
|
|
28
|
+
.option("-p, --port <number>", "port to listen on (default 7777, or the next free one)")
|
|
29
|
+
.option("-r, --registry <file>", "server registry")
|
|
30
|
+
.option("--no-open", "do not open the browser")
|
|
31
|
+
.action(async (options) => {
|
|
32
|
+
const web = await import("hmcp-web");
|
|
33
|
+
try {
|
|
34
|
+
await web.startConsole({
|
|
35
|
+
...(options.port !== undefined ? { port: Number(options.port), strictPort: true } : {}),
|
|
36
|
+
...(options.registry ? { registryPath: options.registry } : {}),
|
|
37
|
+
open: options.open
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
if (err instanceof web.StartError) {
|
|
42
|
+
process.stderr.write(`\nerror: ${err.message}\n`);
|
|
43
|
+
process.exit(1);
|
|
44
|
+
}
|
|
45
|
+
throw err;
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
/* ------------------------------------------------------------------ approvals */
|
|
49
|
+
program
|
|
50
|
+
.command("pending")
|
|
51
|
+
.description("List tool calls waiting for a human decision.")
|
|
52
|
+
.option("-p, --policy <file>", "policy file, to locate the approval store")
|
|
53
|
+
.option("--store <file>", "approval store path")
|
|
54
|
+
.option("--json", "emit JSON", false)
|
|
55
|
+
.action((options) => {
|
|
56
|
+
run(() => {
|
|
57
|
+
const store = openStore(options);
|
|
58
|
+
try {
|
|
59
|
+
const rows = store.listPendingAll();
|
|
60
|
+
if (options.json) {
|
|
61
|
+
log(JSON.stringify(rows, null, 2));
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (rows.length === 0) {
|
|
65
|
+
log("Nothing is waiting for approval.");
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
log(`${rows.length} call(s) waiting:`);
|
|
69
|
+
for (const row of rows)
|
|
70
|
+
log("\n" + describePending(row));
|
|
71
|
+
log("");
|
|
72
|
+
log(`Approve with: hmcp approve <id>`);
|
|
73
|
+
log(`Refuse with: hmcp deny <id>`);
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
store.close();
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
program
|
|
81
|
+
.command("approve")
|
|
82
|
+
.description("Release one pending call. The grant is bound to the exact arguments shown.")
|
|
83
|
+
.argument("<id>", "approval id, as shown by `hmcp pending`")
|
|
84
|
+
.option("-p, --policy <file>", "policy file, to locate the approval store")
|
|
85
|
+
.option("--store <file>", "approval store path")
|
|
86
|
+
.option("-m, --note <text>", "note recorded with the decision", "")
|
|
87
|
+
.option("--classify <effect>", "also say what the tool does (read | write | destructive), for a call held because nothing classified it")
|
|
88
|
+
.option("--remember [duration]", "also allow calls like this one without asking, for this long (10m, 1h, 8h, 2d; default 1h)")
|
|
89
|
+
.option("--uses <count>", "with --remember, how many calls it releases (default 20)")
|
|
90
|
+
.action((id, options) => decideOne(id, "granted", options));
|
|
91
|
+
program
|
|
92
|
+
.command("deny")
|
|
93
|
+
.description("Refuse one pending call.")
|
|
94
|
+
.argument("<id>", "approval id, as shown by `hmcp pending`")
|
|
95
|
+
.option("-p, --policy <file>", "policy file, to locate the approval store")
|
|
96
|
+
.option("--store <file>", "approval store path")
|
|
97
|
+
.option("-m, --note <text>", "note recorded with the decision", "")
|
|
98
|
+
.action((id, options) => decideOne(id, "denied", options));
|
|
99
|
+
program
|
|
100
|
+
.command("approvals")
|
|
101
|
+
.description("Show recent approval history, decided or not.")
|
|
102
|
+
.option("-p, --policy <file>", "policy file, to locate the approval store")
|
|
103
|
+
.option("--store <file>", "approval store path")
|
|
104
|
+
.option("-n, --limit <count>", "how many to show", "20")
|
|
105
|
+
.action((options) => {
|
|
106
|
+
run(() => {
|
|
107
|
+
const store = openStore(options);
|
|
108
|
+
try {
|
|
109
|
+
const rows = store.listAll(Number(options.limit));
|
|
110
|
+
if (rows.length === 0) {
|
|
111
|
+
log("No approval requests have been recorded.");
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
for (const row of rows) {
|
|
115
|
+
const decided = row.decided_at ? new Date(row.decided_at).toISOString() : "-";
|
|
116
|
+
log(`${row.id} ${row.state.padEnd(8)} ${scopeLabel(row).padEnd(30)} ${row.tool.padEnd(28)} ` +
|
|
117
|
+
`${(row.effect ?? "?").padEnd(12)} by ${(row.decided_by ?? "-").padEnd(14)} ${decided}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
store.close();
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
});
|
|
125
|
+
function decideOne(id, state, options) {
|
|
126
|
+
run(() => {
|
|
127
|
+
const store = openStore(options);
|
|
128
|
+
try {
|
|
129
|
+
const existing = store.getAny(id);
|
|
130
|
+
if (!existing)
|
|
131
|
+
throw new CliError(`no approval request with id "${id}". Run "hmcp pending" to see what is open.`);
|
|
132
|
+
if (existing.state !== "pending") {
|
|
133
|
+
throw new CliError(`approval "${id}" is already ${existing.state}, so it cannot be decided again. ` +
|
|
134
|
+
`If the agent needs to retry, it must make a fresh request.`);
|
|
135
|
+
}
|
|
136
|
+
log(describePending(existing));
|
|
137
|
+
log("");
|
|
138
|
+
/*
|
|
139
|
+
* Before the approval, so that a classification which cannot be written
|
|
140
|
+
* stops here with nothing changed, rather than leaving the call released
|
|
141
|
+
* and the tool still unknown.
|
|
142
|
+
*/
|
|
143
|
+
const classify = options["classify"];
|
|
144
|
+
if (classify !== undefined) {
|
|
145
|
+
if (state !== "granted")
|
|
146
|
+
throw new CliError("--classify goes with approve, not deny.");
|
|
147
|
+
const effect = EffectSchema.safeParse(classify);
|
|
148
|
+
if (!effect.success) {
|
|
149
|
+
throw new CliError(`--classify must be read, write or destructive, not ${JSON.stringify(classify)}.`);
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
const done = classifyOnApprove({ store, row: existing, effect: effect.data, actor: actor() });
|
|
153
|
+
log(`Classified ${existing.tool} as ${effect.data} (rule "${done.ruleId}" in ${done.policyPath}). ` +
|
|
154
|
+
(done.decision === "allow"
|
|
155
|
+
? "Calls to it now run without asking."
|
|
156
|
+
: "It is no longer unknown; calls to it still wait for a person, as this policy has every write do."));
|
|
157
|
+
}
|
|
158
|
+
catch (err) {
|
|
159
|
+
if (err instanceof ClassifyError)
|
|
160
|
+
throw new CliError(`${err.message}\nNothing was approved.`);
|
|
161
|
+
throw err;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/*
|
|
165
|
+
* Also before the approval, for the same reason: a grant that cannot be
|
|
166
|
+
* written must not leave the call released and the question unanswered.
|
|
167
|
+
*/
|
|
168
|
+
const remember = options["remember"];
|
|
169
|
+
if (remember !== undefined && remember !== false) {
|
|
170
|
+
if (state !== "granted")
|
|
171
|
+
throw new CliError("--remember goes with approve, not deny.");
|
|
172
|
+
try {
|
|
173
|
+
const ttlSeconds = remember === true ? REMEMBER_DEFAULT_TTL_SECONDS : parseDuration(remember);
|
|
174
|
+
const uses = options["uses"];
|
|
175
|
+
const maxUses = uses === undefined ? REMEMBER_DEFAULT_USES : Number(uses);
|
|
176
|
+
if (!Number.isInteger(maxUses) || maxUses <= 0) {
|
|
177
|
+
throw new GrantCommandError(`--uses must be a whole number of calls, not ${JSON.stringify(uses)}.`);
|
|
178
|
+
}
|
|
179
|
+
// The row as it is now, in case --classify has just given the tool an effect.
|
|
180
|
+
const grant = rememberOnApprove({ store, row: store.getAny(id) ?? existing, ttlSeconds, maxUses, actor: actor() });
|
|
181
|
+
log("Remembered. Calls like this one now run without asking:");
|
|
182
|
+
for (const line of describeGrant(grant))
|
|
183
|
+
log(line);
|
|
184
|
+
log(` Withdraw it at any time with: hmcp grant revoke ${grant.id}`);
|
|
185
|
+
log("");
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
if (err instanceof GrantCommandError)
|
|
189
|
+
throw new CliError(`${err.message}\nNothing was approved.`);
|
|
190
|
+
throw err;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const row = store.decideAny(id, state, actor(), options["note"] ?? "");
|
|
194
|
+
if (!row)
|
|
195
|
+
throw new CliError(`approval "${id}" could not be decided; it may have just expired.`);
|
|
196
|
+
log(state === "granted"
|
|
197
|
+
? `Granted. The agent may now retry this call with identical arguments; the grant is single-use where ` +
|
|
198
|
+
`policy says so, and it expires at ${new Date(row.expires_at).toISOString()}.`
|
|
199
|
+
: `Refused. The agent cannot run this call.`);
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
store.close();
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
/* --------------------------------------------------------------------- grants */
|
|
207
|
+
const grant = program
|
|
208
|
+
.command("grant")
|
|
209
|
+
.description("See and withdraw standing grants: pre-approvals that release calls without asking.");
|
|
210
|
+
grant
|
|
211
|
+
.command("list")
|
|
212
|
+
.description("Show the standing grants that are live.")
|
|
213
|
+
.option("-p, --policy <file>", "policy file, to locate the approval store")
|
|
214
|
+
.option("--store <file>", "approval store path")
|
|
215
|
+
.option("--all", "include expired, used-up and revoked ones", false)
|
|
216
|
+
.option("--json", "emit JSON", false)
|
|
217
|
+
.action((options) => {
|
|
218
|
+
run(() => {
|
|
219
|
+
const store = openStore(options);
|
|
220
|
+
try {
|
|
221
|
+
const rows = listGrants(store, { all: options.all });
|
|
222
|
+
if (options.json) {
|
|
223
|
+
log(JSON.stringify(rows, null, 2));
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
if (rows.length === 0) {
|
|
227
|
+
log(options.all ? "No standing grants have been recorded." : "No standing grants are live.");
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
log(`${rows.length} standing grant(s)${options.all ? "" : " live"}:`);
|
|
231
|
+
for (const row of rows) {
|
|
232
|
+
log("");
|
|
233
|
+
for (const line of describeGrant(row))
|
|
234
|
+
log(line);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
finally {
|
|
238
|
+
store.close();
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
grant
|
|
243
|
+
.command("revoke")
|
|
244
|
+
.description("Withdraw one standing grant, so the calls it covered ask again.")
|
|
245
|
+
.argument("<id>", "grant id, as shown by `hmcp grant list`")
|
|
246
|
+
.option("-p, --policy <file>", "policy file, to locate the approval store")
|
|
247
|
+
.option("--store <file>", "approval store path")
|
|
248
|
+
.action((id, options) => {
|
|
249
|
+
run(() => {
|
|
250
|
+
const store = openStore(options);
|
|
251
|
+
try {
|
|
252
|
+
const revoked = revokeGrant({ store, id, actor: actor() });
|
|
253
|
+
log(`Revoked ${revoked.id} (${revoked.tool_match}) after ${revoked.uses} use(s). Calls it covered ask again.`);
|
|
254
|
+
if (revoked.warning)
|
|
255
|
+
log(revoked.warning);
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
if (err instanceof GrantCommandError)
|
|
259
|
+
throw new CliError(err.message);
|
|
260
|
+
throw err;
|
|
261
|
+
}
|
|
262
|
+
finally {
|
|
263
|
+
store.close();
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
/* ---------------------------------------------------------------------- audit */
|
|
268
|
+
const audit = program.command("audit").description("Inspect the audit trail.");
|
|
269
|
+
audit
|
|
270
|
+
.command("verify")
|
|
271
|
+
.description("Check the hash chain for edited, removed or reordered records.")
|
|
272
|
+
.option("-p, --policy <file>", "policy file, to locate the log")
|
|
273
|
+
.option("-f, --file <file>", "audit log path")
|
|
274
|
+
.option("--expect-head <hash>", "a head hash recorded earlier, elsewhere: fails if it is no longer in this log")
|
|
275
|
+
.action((options) => {
|
|
276
|
+
run(() => {
|
|
277
|
+
const path = auditPath(options);
|
|
278
|
+
const expectHead = options.expectHead;
|
|
279
|
+
const result = verifyAuditLog(path, { ...(expectHead ? { expectHead } : {}) });
|
|
280
|
+
if (result.ok) {
|
|
281
|
+
log(`${path}: ${result.count} record(s), chain intact.`);
|
|
282
|
+
if (result.head)
|
|
283
|
+
log(`head: ${result.head}`);
|
|
284
|
+
if (expectHead !== undefined) {
|
|
285
|
+
log(`The head recorded earlier is still in this log, at record ${result.headPosition}, ` +
|
|
286
|
+
`with ${result.count - (result.headPosition ?? 0) - 1} record(s) after it.`);
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
/*
|
|
290
|
+
* Said every time, because the chain's one blind spot is the end of
|
|
291
|
+
* the file and the only fix is a value kept somewhere else. Nobody
|
|
292
|
+
* records a head they were never told to.
|
|
293
|
+
*/
|
|
294
|
+
log("");
|
|
295
|
+
log("A chain cannot detect the end of the log being cut off: what remains still verifies.");
|
|
296
|
+
log("Keep this head somewhere the log's owner does not control, then check it with:");
|
|
297
|
+
log(` hmcp audit verify -f ${path} --expect-head ${result.head ?? "<hash>"}`);
|
|
298
|
+
}
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
log(`${path}: ${result.count} record(s), ${result.problems.length} problem(s).`);
|
|
302
|
+
log("");
|
|
303
|
+
for (const problem of result.problems)
|
|
304
|
+
log(` line ${problem.line}: ${problem.message}`);
|
|
305
|
+
log("");
|
|
306
|
+
log("A chain break means the log was altered after it was written. Treat it as an incident.");
|
|
307
|
+
process.exitCode = 1;
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
audit
|
|
311
|
+
.command("tail")
|
|
312
|
+
.description("Show the most recent decisions.")
|
|
313
|
+
.option("-p, --policy <file>", "policy file, to locate the log")
|
|
314
|
+
.option("-f, --file <file>", "audit log path")
|
|
315
|
+
.option("-n, --limit <count>", "how many to show", "20")
|
|
316
|
+
.option("--denied", "only show calls that were refused, held for approval, or failed", false)
|
|
317
|
+
.option("--json", "emit JSON", false)
|
|
318
|
+
.action((options) => {
|
|
319
|
+
run(() => {
|
|
320
|
+
const path = auditPath(options);
|
|
321
|
+
const limit = Number(options.limit);
|
|
322
|
+
// Bounded and newest-first, then reversed to keep this command's existing
|
|
323
|
+
// oldest-first output. The previous read parsed the whole log and threw on
|
|
324
|
+
// a single torn line, which could hide every record around it.
|
|
325
|
+
const page = queryAuditLog(path, { limit, ...(options.denied ? { noteworthy: true } : {}) });
|
|
326
|
+
const records = [...page.records].reverse();
|
|
327
|
+
if (options.json) {
|
|
328
|
+
log(JSON.stringify(records, null, 2));
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (records.length === 0) {
|
|
332
|
+
log(`${path}: nothing recorded yet.`);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
for (const r of records)
|
|
336
|
+
for (const line of describeAuditRecord(r))
|
|
337
|
+
log(line);
|
|
338
|
+
});
|
|
339
|
+
});
|
|
340
|
+
/* ---------------------------------------------------------------------- policy */
|
|
341
|
+
program
|
|
342
|
+
.command("policy")
|
|
343
|
+
.description("Validate a policy file and print the effective settings, defaults included.")
|
|
344
|
+
.argument("[file]", "policy file", "policy.yaml")
|
|
345
|
+
.action((file) => {
|
|
346
|
+
run(() => {
|
|
347
|
+
const policy = loadPolicy(file);
|
|
348
|
+
log(`${resolve(file)} is valid.`);
|
|
349
|
+
log("");
|
|
350
|
+
log(`enforcement: ${policy.enforcement}` +
|
|
351
|
+
(policy.enforcement === "observe" ? " -- NOT ENFORCED: every call runs and is only recorded" : ""));
|
|
352
|
+
log(`posture: ${policy.defaults.mode} (unclassified tools: ${policy.defaults.on_unclassified})`);
|
|
353
|
+
log(`rules: ${policy.rules.length}`);
|
|
354
|
+
for (const rule of policy.rules) {
|
|
355
|
+
log(` ${rule.id.padEnd(26)} ${rule.match.padEnd(22)} ${rule.decision}${rule.effect ? ` as ${rule.effect}` : ""}`);
|
|
356
|
+
/*
|
|
357
|
+
* The bounds, on their own line. Without them the listing says a rule
|
|
358
|
+
* "allows" a tool, which for a bounded rule is only half of it: the
|
|
359
|
+
* call runs while the arguments are inside the bounds, and outside
|
|
360
|
+
* them it is refused or held. The effective settings are the whole
|
|
361
|
+
* point of this command.
|
|
362
|
+
*/
|
|
363
|
+
const paths = Object.keys(rule.args ?? {});
|
|
364
|
+
if (paths.length > 0 || rule.unknown_args !== "allow") {
|
|
365
|
+
const parts = [
|
|
366
|
+
paths.length > 0 ? `bounds ${paths.join(", ")}` : "no bounds",
|
|
367
|
+
`outside -> ${rule.on_violation}`,
|
|
368
|
+
`unknown args -> ${rule.unknown_args}`
|
|
369
|
+
];
|
|
370
|
+
log(` ${" ".repeat(26)} ${parts.join("; ")}`);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
log(`tenant: ${policy.tenant ? `${policy.tenant.field} from ${policy.tenant.source.kind}` : "not configured"}`);
|
|
374
|
+
log(`egress allow: ${policy.egress.allow.length > 0 ? policy.egress.allow.join(", ") : "(nothing)"}`);
|
|
375
|
+
log(`egress methods: ${policy.egress.methods.join(", ")}`);
|
|
376
|
+
log(`body cap: ${policy.egress.max_body_bytes} bytes`);
|
|
377
|
+
log(`private IPs: ${policy.egress.block_private_ips ? "blocked" : "ALLOWED"}`);
|
|
378
|
+
log(`approvals: ${policy.approvals.mode}, ttl ${policy.approvals.ttl_seconds}s, single-use ${policy.approvals.single_use}`);
|
|
379
|
+
log(`audit: ${policy.audit.enabled ? expandPath(policy.audit.path) : "DISABLED"}${policy.audit.hash_chain ? " (hash-chained)" : ""}`);
|
|
380
|
+
log(`tool budget: ${policy.tool_budget}`);
|
|
381
|
+
/*
|
|
382
|
+
* This command's promise is the effective settings, defaults included.
|
|
383
|
+
* A setting that decides what reaches the model, printed nowhere, is a
|
|
384
|
+
* default nobody chose.
|
|
385
|
+
*/
|
|
386
|
+
log(`tool changes: ${policy.on_tool_change}` +
|
|
387
|
+
(policy.on_tool_change === "warn" ? " (reported, and the tool is still served)" : " (withheld until accepted)"));
|
|
388
|
+
log(`results: injected text -> ${policy.results.on_injection}, secrets -> ${policy.results.on_secret}`);
|
|
389
|
+
});
|
|
390
|
+
});
|
|
391
|
+
/* ---------------------------------------------------------------------- shared */
|
|
392
|
+
function resolvePolicy(options) {
|
|
393
|
+
const path = options["policy"];
|
|
394
|
+
if (path)
|
|
395
|
+
return loadPolicy(path);
|
|
396
|
+
if (existsSync("policy.yaml"))
|
|
397
|
+
return parsePolicy(parseYaml(readFileSync("policy.yaml", "utf8")), "policy.yaml");
|
|
398
|
+
return defaultPolicy();
|
|
399
|
+
}
|
|
400
|
+
function openStore(options) {
|
|
401
|
+
const override = options["store"];
|
|
402
|
+
return storeAt(override ?? resolvePolicy(options).approvals.store_path, override !== undefined);
|
|
403
|
+
}
|
|
404
|
+
function auditPath(options) {
|
|
405
|
+
const override = options["file"];
|
|
406
|
+
return expandPath(override ?? resolvePolicy(options).audit.path);
|
|
407
|
+
}
|
|
408
|
+
function actor() {
|
|
409
|
+
return process.env["HMCP_ACTOR"] ?? process.env["USER"] ?? "unknown";
|
|
410
|
+
}
|
|
411
|
+
class CliError extends Error {
|
|
412
|
+
}
|
|
413
|
+
/*
|
|
414
|
+
* Every line this command prints passes through here, and some of it is text a
|
|
415
|
+
* server we do not control chose: a tool name, an upstream's own description,
|
|
416
|
+
* an actor from a token. A control sequence in any of those rewrites the
|
|
417
|
+
* terminal -- `ESC[2J ESC[1;1H` clears the screen and homes the cursor, so an
|
|
418
|
+
* upstream could print a clean-looking report over the real one. JSON escapes
|
|
419
|
+
* these on the way to disk, so the log file is safe to `cat`; it is parsing it
|
|
420
|
+
* back and printing it that is not.
|
|
421
|
+
*
|
|
422
|
+
* Done at the one place everything funnels through rather than at each call
|
|
423
|
+
* site, because a new line of output should not be able to reintroduce this by
|
|
424
|
+
* forgetting. Nothing here prints colour, so there is no legitimate escape to
|
|
425
|
+
* preserve.
|
|
426
|
+
*/
|
|
427
|
+
function log(message) {
|
|
428
|
+
process.stdout.write(`${escapeForDisplay(message)}\n`);
|
|
429
|
+
}
|
|
430
|
+
function run(fn) {
|
|
431
|
+
try {
|
|
432
|
+
fn();
|
|
433
|
+
}
|
|
434
|
+
catch (err) {
|
|
435
|
+
if (err instanceof CliError ||
|
|
436
|
+
err instanceof PolicyError ||
|
|
437
|
+
err instanceof StoreNotFound ||
|
|
438
|
+
err instanceof NotADatabase) {
|
|
439
|
+
process.stderr.write(`\nerror: ${err.message}\n`);
|
|
440
|
+
process.exit(1);
|
|
441
|
+
}
|
|
442
|
+
throw err;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
await program.parseAsync(process.argv);
|
package/dist/grants.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type ApprovalRow, type ApprovalStore, type StandingGrantRow } from "hmcp-core";
|
|
2
|
+
/**
|
|
3
|
+
* Standing grants from the terminal: making one while approving a call
|
|
4
|
+
* (`hmcp approve <id> --remember`), and seeing and withdrawing them
|
|
5
|
+
* (`hmcp grant list`, `hmcp grant revoke`).
|
|
6
|
+
*
|
|
7
|
+
* Its own module because `cli.ts` parses `process.argv` as soon as it is
|
|
8
|
+
* imported. A grant made from a terminal has to be visible and reversible
|
|
9
|
+
* from one, which is why the last two exist: before them a standing grant
|
|
10
|
+
* could only be seen or withdrawn in the console.
|
|
11
|
+
*/
|
|
12
|
+
export declare class GrantCommandError extends Error {
|
|
13
|
+
}
|
|
14
|
+
/** `10m`, `1h`, `8h`, `2d`, `90s`, or a bare number of seconds. */
|
|
15
|
+
export declare function parseDuration(text: string): number;
|
|
16
|
+
export interface RememberOnApprove {
|
|
17
|
+
readonly store: ApprovalStore;
|
|
18
|
+
readonly row: ApprovalRow;
|
|
19
|
+
readonly ttlSeconds: number;
|
|
20
|
+
readonly maxUses: number | null;
|
|
21
|
+
readonly actor: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Creates the grant. Does not decide the approval: the caller does that
|
|
25
|
+
* next, so a grant that cannot be written stops before anything changes.
|
|
26
|
+
*
|
|
27
|
+
* The rules for what may be remembered live in core, shared with the
|
|
28
|
+
* console; this only finds the policy and the log from a terminal.
|
|
29
|
+
*/
|
|
30
|
+
export declare function rememberOnApprove(options: RememberOnApprove): StandingGrantRow;
|
|
31
|
+
/** Every grant in the file, newest first. Live ones only unless asked for all. */
|
|
32
|
+
export declare function listGrants(store: ApprovalStore, options?: {
|
|
33
|
+
all?: boolean;
|
|
34
|
+
}): StandingGrantRow[];
|
|
35
|
+
/**
|
|
36
|
+
* Withdraws one grant, wherever in the file it is.
|
|
37
|
+
*
|
|
38
|
+
* Revoking only ever tightens, so it is kept even when the audit record
|
|
39
|
+
* cannot be written; the failure is reported instead of undoing the fix.
|
|
40
|
+
*/
|
|
41
|
+
export declare function revokeGrant(options: {
|
|
42
|
+
readonly store: ApprovalStore;
|
|
43
|
+
readonly id: string;
|
|
44
|
+
readonly actor: string;
|
|
45
|
+
}): StandingGrantRow & {
|
|
46
|
+
warning?: string;
|
|
47
|
+
};
|
|
48
|
+
/** One grant, as lines for a listing. */
|
|
49
|
+
export declare function describeGrant(grant: StandingGrantRow, now?: number): string[];
|
package/dist/grants.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { dirname } from "node:path";
|
|
2
|
+
import { AuditLog, RememberError, hasLooseListItems, isOlderRemembered, loadPolicy, rememberOnApprove as rememberShared } from "hmcp-core";
|
|
3
|
+
import { ClassifyError, policyFor } from "./classify.js";
|
|
4
|
+
/**
|
|
5
|
+
* Standing grants from the terminal: making one while approving a call
|
|
6
|
+
* (`hmcp approve <id> --remember`), and seeing and withdrawing them
|
|
7
|
+
* (`hmcp grant list`, `hmcp grant revoke`).
|
|
8
|
+
*
|
|
9
|
+
* Its own module because `cli.ts` parses `process.argv` as soon as it is
|
|
10
|
+
* imported. A grant made from a terminal has to be visible and reversible
|
|
11
|
+
* from one, which is why the last two exist: before them a standing grant
|
|
12
|
+
* could only be seen or withdrawn in the console.
|
|
13
|
+
*/
|
|
14
|
+
export class GrantCommandError extends Error {
|
|
15
|
+
}
|
|
16
|
+
/** `10m`, `1h`, `8h`, `2d`, `90s`, or a bare number of seconds. */
|
|
17
|
+
export function parseDuration(text) {
|
|
18
|
+
const match = /^(\d+)([smhd])?$/.exec(text.trim());
|
|
19
|
+
const seconds = match ? Number(match[1]) * { s: 1, m: 60, h: 3600, d: 86400 }[match[2] ?? "s"] : 0;
|
|
20
|
+
if (!match || seconds <= 0) {
|
|
21
|
+
throw new GrantCommandError(`"${text}" is not a length of time. Write it like 10m, 1h, 8h or 2d.`);
|
|
22
|
+
}
|
|
23
|
+
return seconds;
|
|
24
|
+
}
|
|
25
|
+
const INSTEAD = "Approve this call on its own, or write the pre-approval in the console.";
|
|
26
|
+
/** The audit log of the gateway a row belongs to, written under the operator's name. */
|
|
27
|
+
function auditFor(store, component, actor) {
|
|
28
|
+
const { policyPath } = policyFor(store, { component }, INSTEAD);
|
|
29
|
+
const policy = loadPolicy(policyPath);
|
|
30
|
+
return {
|
|
31
|
+
policyPath,
|
|
32
|
+
audit: new AuditLog({ config: policy.audit, component, actor, cwd: dirname(policyPath) })
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Creates the grant. Does not decide the approval: the caller does that
|
|
37
|
+
* next, so a grant that cannot be written stops before anything changes.
|
|
38
|
+
*
|
|
39
|
+
* The rules for what may be remembered live in core, shared with the
|
|
40
|
+
* console; this only finds the policy and the log from a terminal.
|
|
41
|
+
*/
|
|
42
|
+
export function rememberOnApprove(options) {
|
|
43
|
+
const { store, row, actor } = options;
|
|
44
|
+
try {
|
|
45
|
+
const { audit, policyPath } = auditFor(store, row.component, actor);
|
|
46
|
+
return rememberShared({
|
|
47
|
+
scoped: store.scoped({ component: row.component, tenant: row.tenant }),
|
|
48
|
+
audit,
|
|
49
|
+
row,
|
|
50
|
+
policy: loadPolicy(policyPath),
|
|
51
|
+
ttlSeconds: options.ttlSeconds,
|
|
52
|
+
maxUses: options.maxUses,
|
|
53
|
+
actor,
|
|
54
|
+
via: "hmcp approve"
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
if (err instanceof RememberError || err instanceof ClassifyError)
|
|
59
|
+
throw new GrantCommandError(err.message);
|
|
60
|
+
throw err;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** Every grant in the file, newest first. Live ones only unless asked for all. */
|
|
64
|
+
export function listGrants(store, options = {}) {
|
|
65
|
+
const rows = [];
|
|
66
|
+
for (const scope of store.listScopes()) {
|
|
67
|
+
rows.push(...store.scoped(scope).listGrants({ activeOnly: !options.all, limit: 1000 }));
|
|
68
|
+
}
|
|
69
|
+
return rows.sort((a, b) => b.created_at - a.created_at);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Withdraws one grant, wherever in the file it is.
|
|
73
|
+
*
|
|
74
|
+
* Revoking only ever tightens, so it is kept even when the audit record
|
|
75
|
+
* cannot be written; the failure is reported instead of undoing the fix.
|
|
76
|
+
*/
|
|
77
|
+
export function revokeGrant(options) {
|
|
78
|
+
const { store, id, actor } = options;
|
|
79
|
+
for (const scope of store.listScopes()) {
|
|
80
|
+
const scoped = store.scoped(scope);
|
|
81
|
+
const existing = scoped.getGrant(id);
|
|
82
|
+
if (!existing)
|
|
83
|
+
continue;
|
|
84
|
+
const revoked = scoped.revokeGrant(id, actor);
|
|
85
|
+
if (!revoked)
|
|
86
|
+
throw new GrantCommandError(`standing grant ${id} is already ${existing.state}.`);
|
|
87
|
+
try {
|
|
88
|
+
auditFor(store, revoked.component, actor).audit.appendStrict({
|
|
89
|
+
tool: revoked.tool_match,
|
|
90
|
+
decision: "deny",
|
|
91
|
+
tenant: revoked.tenant || null,
|
|
92
|
+
rule_id: "standing_grant.revoke",
|
|
93
|
+
reason: `standing grant ${revoked.id} revoked by ${actor} via hmcp grant revoke after ${revoked.uses} use(s)`,
|
|
94
|
+
outcome: "completed",
|
|
95
|
+
grant_id: revoked.id
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
return { ...revoked, warning: `the grant was revoked but the audit record failed: ${err.message}` };
|
|
100
|
+
}
|
|
101
|
+
return revoked;
|
|
102
|
+
}
|
|
103
|
+
throw new GrantCommandError(`no standing grant with id "${id}". Run "hmcp grant list" to see what is live.`);
|
|
104
|
+
}
|
|
105
|
+
/** One grant, as lines for a listing. */
|
|
106
|
+
export function describeGrant(grant, now = Date.now()) {
|
|
107
|
+
const left = Math.max(0, grant.expires_at - now);
|
|
108
|
+
const remaining = left >= 5_400_000 ? `${Math.round(left / 3_600_000)}h` : left >= 90_000 ? `${Math.round(left / 60_000)}m` : `${Math.round(left / 1000)}s`;
|
|
109
|
+
const uses = grant.max_uses === null ? `${grant.uses} used, no cap` : `${grant.uses} of ${grant.max_uses} used`;
|
|
110
|
+
const older = isOlderRemembered(grant);
|
|
111
|
+
let bounds = older ? "none named: only a call with no arguments at all" : "none: any arguments";
|
|
112
|
+
try {
|
|
113
|
+
const constraints = JSON.parse(grant.constraints);
|
|
114
|
+
const parts = Object.entries(constraints).map(([path, c]) => `${path} ${JSON.stringify(c)}`);
|
|
115
|
+
if (parts.length > 0)
|
|
116
|
+
bounds = older ? `only these arguments: ${parts.join("; ")}` : parts.join("; ");
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
bounds = "unreadable, so this grant matches nothing";
|
|
120
|
+
}
|
|
121
|
+
const loose = hasLooseListItems(grant);
|
|
122
|
+
const state = loose && grant.state === "active"
|
|
123
|
+
? "active, needs approving again: made by an older version, which did not keep list items together, it releases nothing"
|
|
124
|
+
: older && grant.state === "active"
|
|
125
|
+
? "active, needs approving again: made by an older version, it releases only what it names"
|
|
126
|
+
: grant.state;
|
|
127
|
+
return [
|
|
128
|
+
` id: ${grant.id} (${state})`,
|
|
129
|
+
` scope: ${grant.component || "(none)"}${grant.tenant ? `/${grant.tenant}` : ""}`,
|
|
130
|
+
` tool: ${grant.tool_match}${grant.effect ? ` (${grant.effect})` : ""}`,
|
|
131
|
+
` bounds: ${bounds}`,
|
|
132
|
+
` calls: ${uses}`,
|
|
133
|
+
grant.state === "active"
|
|
134
|
+
? ` expires: in ${remaining} (${new Date(grant.expires_at).toISOString()})`
|
|
135
|
+
: ` expired: ${new Date(grant.expires_at).toISOString()}`,
|
|
136
|
+
` made by: ${grant.created_by}: ${grant.reason}`
|
|
137
|
+
];
|
|
138
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.js
ADDED
package/dist/render.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type ApprovalRow, type AuditRecord } from "hmcp-core";
|
|
2
|
+
/**
|
|
3
|
+
* Rendering a parked approval for a human.
|
|
4
|
+
*
|
|
5
|
+
* Its own module because `cli.ts` parses `process.argv` as soon as it is
|
|
6
|
+
* imported, so nothing in it can be exercised without running the program.
|
|
7
|
+
* What a reviewer is shown before they release a destructive call is worth
|
|
8
|
+
* testing directly.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Which server and customer a row belongs to, for an operator reading a file
|
|
12
|
+
* that holds several of both.
|
|
13
|
+
*
|
|
14
|
+
* A row written before scoping existed carries neither, and says so rather
|
|
15
|
+
* than being quietly attributed to whoever is looking.
|
|
16
|
+
*/
|
|
17
|
+
export declare function scopeLabel(row: {
|
|
18
|
+
component: string;
|
|
19
|
+
tenant: string;
|
|
20
|
+
}): string;
|
|
21
|
+
export declare function describePending(row: ApprovalRow): string;
|
|
22
|
+
/**
|
|
23
|
+
* One audit record, as lines for a listing.
|
|
24
|
+
*
|
|
25
|
+
* A record written in observe mode carries the decision policy *would* have
|
|
26
|
+
* made and the outcome that actually happened, so "deny / completed" is not a
|
|
27
|
+
* contradiction there: the call ran and enforcement would have refused it.
|
|
28
|
+
* Printed as it stands that reads as a bug, so it is spelled out.
|
|
29
|
+
*/
|
|
30
|
+
export declare function describeAuditRecord(r: AuditRecord): string[];
|
package/dist/render.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { approvalViolations } from "hmcp-core";
|
|
2
|
+
/**
|
|
3
|
+
* Rendering a parked approval for a human.
|
|
4
|
+
*
|
|
5
|
+
* Its own module because `cli.ts` parses `process.argv` as soon as it is
|
|
6
|
+
* imported, so nothing in it can be exercised without running the program.
|
|
7
|
+
* What a reviewer is shown before they release a destructive call is worth
|
|
8
|
+
* testing directly.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Which server and customer a row belongs to, for an operator reading a file
|
|
12
|
+
* that holds several of both.
|
|
13
|
+
*
|
|
14
|
+
* A row written before scoping existed carries neither, and says so rather
|
|
15
|
+
* than being quietly attributed to whoever is looking.
|
|
16
|
+
*/
|
|
17
|
+
export function scopeLabel(row) {
|
|
18
|
+
if (!row.component && !row.tenant)
|
|
19
|
+
return "(unscoped, pre-upgrade)";
|
|
20
|
+
const tenant = row.tenant ? `/${row.tenant}` : "";
|
|
21
|
+
return `${row.component || "(none)"}${tenant}`;
|
|
22
|
+
}
|
|
23
|
+
export function describePending(row) {
|
|
24
|
+
let args = row.args_redacted;
|
|
25
|
+
try {
|
|
26
|
+
args = JSON.stringify(JSON.parse(row.args_redacted), null, 2);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
/* leave as stored */
|
|
30
|
+
}
|
|
31
|
+
const violations = approvalViolations(row);
|
|
32
|
+
return [
|
|
33
|
+
` id: ${row.id}`,
|
|
34
|
+
` scope: ${scopeLabel(row)}`,
|
|
35
|
+
` tool: ${row.tool} (${row.effect ?? "unclassified"})`,
|
|
36
|
+
` asked by: ${row.actor} session ${row.session.slice(0, 8)}`,
|
|
37
|
+
` because: ${row.reason}`,
|
|
38
|
+
` expires: ${new Date(row.expires_at).toISOString()}`,
|
|
39
|
+
/*
|
|
40
|
+
* Which bound was exceeded, and by how much. The arguments below are
|
|
41
|
+
* redacted, truncated past 100 array elements and collapsed past depth
|
|
42
|
+
* 12, so for a call held by an argument bound this can be the only place
|
|
43
|
+
* the value being decided on is visible at all — and approving a binding
|
|
44
|
+
* over a value the reviewer was never shown is the worst version of this.
|
|
45
|
+
*/
|
|
46
|
+
...(violations.length > 0
|
|
47
|
+
? [` outside: ${violations.join("\n ")}`]
|
|
48
|
+
: []),
|
|
49
|
+
` arguments (secrets redacted):`,
|
|
50
|
+
args
|
|
51
|
+
.split("\n")
|
|
52
|
+
.map((l) => ` ${l}`)
|
|
53
|
+
.join("\n")
|
|
54
|
+
].join("\n");
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* One audit record, as lines for a listing.
|
|
58
|
+
*
|
|
59
|
+
* A record written in observe mode carries the decision policy *would* have
|
|
60
|
+
* made and the outcome that actually happened, so "deny / completed" is not a
|
|
61
|
+
* contradiction there: the call ran and enforcement would have refused it.
|
|
62
|
+
* Printed as it stands that reads as a bug, so it is spelled out.
|
|
63
|
+
*/
|
|
64
|
+
export function describeAuditRecord(r) {
|
|
65
|
+
const indent = " ".repeat(26);
|
|
66
|
+
if (r.observe) {
|
|
67
|
+
const ran = r.outcome === "error" ? "ran and failed" : "ran";
|
|
68
|
+
const lines = [
|
|
69
|
+
`${r.ts} observe ${`would ${r.decision}`.padEnd(16)} ${r.tool.padEnd(30)} ` +
|
|
70
|
+
`${(r.effect ?? "-").padEnd(12)} ${r.rule_id}`
|
|
71
|
+
];
|
|
72
|
+
if (r.decision !== "allow" || r.outcome !== "completed") {
|
|
73
|
+
lines.push(`${indent}not enforced: the call ${ran}. ${r.outcome === "error" ? (r.error ?? "") : r.reason}`.trimEnd());
|
|
74
|
+
}
|
|
75
|
+
return lines;
|
|
76
|
+
}
|
|
77
|
+
const lines = [
|
|
78
|
+
`${r.ts} ${r.decision.padEnd(7)} ${r.outcome.padEnd(16)} ${r.tool.padEnd(30)} ` +
|
|
79
|
+
`${(r.effect ?? "-").padEnd(12)} ${r.rule_id}`
|
|
80
|
+
];
|
|
81
|
+
// An error explains the outcome better than the rule that permitted it.
|
|
82
|
+
const detail = r.outcome === "error" ? r.error || r.reason : r.reason || r.error;
|
|
83
|
+
if (r.decision !== "allow" || r.outcome !== "completed")
|
|
84
|
+
lines.push(`${indent}${detail ?? ""}`);
|
|
85
|
+
return lines;
|
|
86
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ApprovalStore } from "hmcp-core";
|
|
2
|
+
/** A problem to report as a message, not as a stack trace. */
|
|
3
|
+
export declare class StoreNotFound extends Error {
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Opens an approvals database.
|
|
7
|
+
*
|
|
8
|
+
* `explicit` is the difference between a path somebody typed and a path a
|
|
9
|
+
* policy supplied. Opening a database creates it, which is right for a
|
|
10
|
+
* gateway starting for the first time and wrong for a reviewer who has
|
|
11
|
+
* mistyped `--store`: the typo became an empty database, and the answer came
|
|
12
|
+
* back "Nothing is waiting for approval". That reads as all clear and means
|
|
13
|
+
* "I looked in the wrong place", from the one command somebody runs before
|
|
14
|
+
* deciding nothing needs their attention.
|
|
15
|
+
*/
|
|
16
|
+
export declare function storeAt(path: string, explicit: boolean): ApprovalStore;
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { ApprovalStore, expandPath } from "hmcp-core";
|
|
3
|
+
/** A problem to report as a message, not as a stack trace. */
|
|
4
|
+
export class StoreNotFound extends Error {
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Opens an approvals database.
|
|
8
|
+
*
|
|
9
|
+
* `explicit` is the difference between a path somebody typed and a path a
|
|
10
|
+
* policy supplied. Opening a database creates it, which is right for a
|
|
11
|
+
* gateway starting for the first time and wrong for a reviewer who has
|
|
12
|
+
* mistyped `--store`: the typo became an empty database, and the answer came
|
|
13
|
+
* back "Nothing is waiting for approval". That reads as all clear and means
|
|
14
|
+
* "I looked in the wrong place", from the one command somebody runs before
|
|
15
|
+
* deciding nothing needs their attention.
|
|
16
|
+
*/
|
|
17
|
+
export function storeAt(path, explicit) {
|
|
18
|
+
const full = expandPath(path);
|
|
19
|
+
if (explicit && !existsSync(full)) {
|
|
20
|
+
throw new StoreNotFound(`no approvals database at ${full}. Nothing was created, because a path given on the command ` +
|
|
21
|
+
`line that does not exist is more likely a typo than a new store -- and an empty store ` +
|
|
22
|
+
`answers every question with "nothing".`);
|
|
23
|
+
}
|
|
24
|
+
return new ApprovalStore(full);
|
|
25
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This package's version, read from its own `package.json`.
|
|
3
|
+
*
|
|
4
|
+
* It used to be typed out wherever it was needed, which is five places that
|
|
5
|
+
* each go on saying 0.1.0 after the first release that is not 0.1.0.
|
|
6
|
+
* `package.json` sits one level above both `src/` and `dist/`, and npm always
|
|
7
|
+
* ships it, so the same relative path works from a checkout and from an
|
|
8
|
+
* installed package.
|
|
9
|
+
*/
|
|
10
|
+
export declare const VERSION: string;
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
/**
|
|
3
|
+
* This package's version, read from its own `package.json`.
|
|
4
|
+
*
|
|
5
|
+
* It used to be typed out wherever it was needed, which is five places that
|
|
6
|
+
* each go on saying 0.1.0 after the first release that is not 0.1.0.
|
|
7
|
+
* `package.json` sits one level above both `src/` and `dist/`, and npm always
|
|
8
|
+
* ships it, so the same relative path works from a checkout and from an
|
|
9
|
+
* installed package.
|
|
10
|
+
*/
|
|
11
|
+
export const VERSION = createRequire(import.meta.url)("../package.json").version;
|
package/package.json
CHANGED
|
@@ -1,10 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hardened-mcp",
|
|
3
|
-
"version": "0.0
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Command line for hardened-mcp: start the console, approvals, audit verification and policy inspection.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"author": "Aditya Das",
|
|
7
|
-
"repository": {
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/aoutix/hardened-mcp.git",
|
|
10
|
+
"directory": "packages/cli"
|
|
11
|
+
},
|
|
8
12
|
"homepage": "https://github.com/aoutix/hardened-mcp#readme",
|
|
9
|
-
"
|
|
13
|
+
"keywords": [
|
|
14
|
+
"mcp",
|
|
15
|
+
"model-context-protocol",
|
|
16
|
+
"security",
|
|
17
|
+
"policy",
|
|
18
|
+
"gateway",
|
|
19
|
+
"audit"
|
|
20
|
+
],
|
|
21
|
+
"type": "module",
|
|
22
|
+
"bin": {
|
|
23
|
+
"hardened-mcp": "bin/hmcp.js",
|
|
24
|
+
"hmcp": "bin/hmcp.js"
|
|
25
|
+
},
|
|
26
|
+
"main": "./dist/index.js",
|
|
27
|
+
"files": [
|
|
28
|
+
"bin",
|
|
29
|
+
"dist",
|
|
30
|
+
"!dist/**/*.map",
|
|
31
|
+
"README.md",
|
|
32
|
+
"LICENSE"
|
|
33
|
+
],
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "public"
|
|
36
|
+
},
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=22.19.0"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"hmcp-core": "0.1.0",
|
|
42
|
+
"hmcp-scanner": "0.1.0",
|
|
43
|
+
"hmcp-web": "0.1.0",
|
|
44
|
+
"commander": "^15.0.0",
|
|
45
|
+
"yaml": "^2.7.0"
|
|
46
|
+
}
|
|
10
47
|
}
|