hmcp-gateway 0.1.0 → 0.2.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 +94 -0
- package/dist/adopt-cli.d.ts +5 -1
- package/dist/adopt-cli.js +45 -17
- package/dist/adopt-plan.js +116 -1
- package/dist/cli.js +124 -3
- package/dist/client-config.d.ts +65 -2
- package/dist/client-config.js +235 -24
- package/dist/connect-client.d.ts +3 -1
- package/dist/connect-client.js +55 -5
- package/dist/desktop-extensions.d.ts +53 -0
- package/dist/desktop-extensions.js +126 -0
- package/dist/gateway.d.ts +10 -0
- package/dist/gateway.js +21 -5
- package/dist/github-doors.d.ts +162 -0
- package/dist/github-doors.js +780 -0
- package/dist/guard-install.d.ts +109 -0
- package/dist/guard-install.js +396 -0
- package/dist/guard.d.ts +265 -0
- package/dist/guard.js +975 -0
- package/dist/import-client.d.ts +184 -0
- package/dist/import-client.js +578 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/toml-edit.d.ts +43 -0
- package/dist/toml-edit.js +363 -0
- package/package.json +4 -3
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turning the Claude Code guard on and off: our hook entries in a Claude Code
|
|
3
|
+
* settings file, and nothing else.
|
|
4
|
+
*
|
|
5
|
+
* A settings file holds a person's permissions, their environment, their own
|
|
6
|
+
* hooks and whatever else Claude Code grows next. So this never rewrites what
|
|
7
|
+
* it did not add: it reads the file, appends one matcher group to each of
|
|
8
|
+
* `hooks.PreToolUse`, `hooks.PostToolUse` and `hooks.PostToolUseFailure`, and
|
|
9
|
+
* writes everything else back as it was, keeping the file's mode. What it
|
|
10
|
+
* added is recorded under `~/.hmcp/`, and uninstalling removes that: the
|
|
11
|
+
* groups as recorded, or -- if someone has edited them since -- any hook that
|
|
12
|
+
* runs this guard with the recorded config. A hook of someone else's stays.
|
|
13
|
+
*/
|
|
14
|
+
export type GuardScope = "user" | "project";
|
|
15
|
+
export declare class GuardInstallError extends Error {
|
|
16
|
+
}
|
|
17
|
+
export interface GuardInstallOptions {
|
|
18
|
+
readonly scope: GuardScope;
|
|
19
|
+
/** The home folder. Passed in, never assumed, so a test cannot reach the real one. */
|
|
20
|
+
readonly home: string;
|
|
21
|
+
/** For `project`: the project folder whose `.claude/settings.local.json` is edited. */
|
|
22
|
+
readonly projectDir?: string;
|
|
23
|
+
/** The toolbox's gateway.yaml, or a policy.yaml. */
|
|
24
|
+
readonly configPath: string;
|
|
25
|
+
/** How long a held call waits for a person. Defaults to the policy's, or 120s. */
|
|
26
|
+
readonly waitSeconds?: number;
|
|
27
|
+
/** What the toolbox is called in Claude Code, when not `hmcp`. */
|
|
28
|
+
readonly entryName?: string;
|
|
29
|
+
/** Run this build on disk rather than the published version. Unset: as `adopt` decides. */
|
|
30
|
+
readonly local?: boolean;
|
|
31
|
+
/** This build's `cli.js`, for a local install. Unset: the one this code is running from. */
|
|
32
|
+
readonly cliPath?: string;
|
|
33
|
+
/** The version a published install pins. Unset: this package's own. */
|
|
34
|
+
readonly version?: string;
|
|
35
|
+
readonly dryRun?: boolean;
|
|
36
|
+
}
|
|
37
|
+
export interface GuardInstallResult {
|
|
38
|
+
readonly settingsPath: string;
|
|
39
|
+
/** False when exactly these hooks were already there. */
|
|
40
|
+
readonly changed: boolean;
|
|
41
|
+
readonly dryRun: boolean;
|
|
42
|
+
/** The settings file as it is, or would be, afterwards. */
|
|
43
|
+
readonly settings: Record<string, unknown>;
|
|
44
|
+
readonly configPath: string;
|
|
45
|
+
readonly waitSeconds: number;
|
|
46
|
+
/** Whether the policy only observes, which the person should be told: nothing is blocked. */
|
|
47
|
+
readonly observing: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Set for a project in git whose `.gitignore` does not cover the settings
|
|
50
|
+
* file: the hook names a path on this computer and is one person's choice,
|
|
51
|
+
* so it should not be committed for a team.
|
|
52
|
+
*/
|
|
53
|
+
readonly gitignoreWarning: string | null;
|
|
54
|
+
}
|
|
55
|
+
export interface GuardUninstallResult {
|
|
56
|
+
readonly settingsPath: string;
|
|
57
|
+
/** How many of our hooks were taken out. */
|
|
58
|
+
readonly removed: number;
|
|
59
|
+
readonly dryRun: boolean;
|
|
60
|
+
}
|
|
61
|
+
export interface GuardStatus {
|
|
62
|
+
readonly scope: GuardScope;
|
|
63
|
+
readonly settingsPath: string;
|
|
64
|
+
/** Our hooks are there, as installed or edited by hand. */
|
|
65
|
+
readonly installed: boolean;
|
|
66
|
+
/** Our command is there, but not the groups exactly as installed: someone has edited them. */
|
|
67
|
+
readonly changedByHand: boolean;
|
|
68
|
+
/** The config the installed hook checks calls against. */
|
|
69
|
+
readonly configPath: string | null;
|
|
70
|
+
readonly installedAt: string | null;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Where the guard's hooks go for a scope.
|
|
74
|
+
*
|
|
75
|
+
* A project's are in `settings.local.json`, which Claude Code keeps for one
|
|
76
|
+
* person's own settings, and not in `settings.json`, which a team commits: the
|
|
77
|
+
* hook names a config path on this computer, and whether to be guarded is the
|
|
78
|
+
* person's own choice.
|
|
79
|
+
*/
|
|
80
|
+
export declare function guardSettingsPath(scope: GuardScope, options: {
|
|
81
|
+
home: string;
|
|
82
|
+
projectDir?: string;
|
|
83
|
+
}): string;
|
|
84
|
+
export declare function guardRecordPath(home: string): string;
|
|
85
|
+
/**
|
|
86
|
+
* Adds the guard's hooks. Run again with the same choices, it changes nothing;
|
|
87
|
+
* with different ones (another config, another wait), it replaces the hooks
|
|
88
|
+
* it added before rather than stacking a second set.
|
|
89
|
+
*/
|
|
90
|
+
export declare function installGuard(options: GuardInstallOptions): GuardInstallResult;
|
|
91
|
+
/**
|
|
92
|
+
* Takes out the hooks `installGuard` recorded for this settings file.
|
|
93
|
+
*
|
|
94
|
+
* The record is kept when nothing could be found to remove -- the file was
|
|
95
|
+
* edited, or replaced -- so a later uninstall, after the hooks are back, can
|
|
96
|
+
* still find what is ours.
|
|
97
|
+
*/
|
|
98
|
+
export declare function uninstallGuard(options: {
|
|
99
|
+
readonly scope: GuardScope;
|
|
100
|
+
readonly home: string;
|
|
101
|
+
readonly projectDir?: string;
|
|
102
|
+
readonly dryRun?: boolean;
|
|
103
|
+
}): GuardUninstallResult;
|
|
104
|
+
/** Whether the guard is on for a scope: our hooks, as installed or edited since, in that settings file. */
|
|
105
|
+
export declare function guardStatus(options: {
|
|
106
|
+
readonly scope: GuardScope;
|
|
107
|
+
readonly home: string;
|
|
108
|
+
readonly projectDir?: string;
|
|
109
|
+
}): GuardStatus;
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, join, resolve, sep } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { sameJson, writeTextPreservingMode } from "./client-config.js";
|
|
5
|
+
import { clientCommand } from "./adopt-cli.js";
|
|
6
|
+
import { GUARD_DEFAULT_ENTRY, GUARD_TIMEOUT_MARGIN_SECONDS, guardWaitSeconds, openGuard } from "./guard.js";
|
|
7
|
+
import { VERSION } from "./version.js";
|
|
8
|
+
export class GuardInstallError extends Error {
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Where the guard's hooks go for a scope.
|
|
12
|
+
*
|
|
13
|
+
* A project's are in `settings.local.json`, which Claude Code keeps for one
|
|
14
|
+
* person's own settings, and not in `settings.json`, which a team commits: the
|
|
15
|
+
* hook names a config path on this computer, and whether to be guarded is the
|
|
16
|
+
* person's own choice.
|
|
17
|
+
*/
|
|
18
|
+
export function guardSettingsPath(scope, options) {
|
|
19
|
+
if (scope === "user")
|
|
20
|
+
return join(resolve(options.home), ".claude", "settings.json");
|
|
21
|
+
if (!options.projectDir || !isAbsolute(options.projectDir)) {
|
|
22
|
+
throw new GuardInstallError("a project install needs the project folder, as an absolute path");
|
|
23
|
+
}
|
|
24
|
+
return join(resolve(options.projectDir), ".claude", "settings.local.json");
|
|
25
|
+
}
|
|
26
|
+
/** The hook events the guard is installed for, and the record key each one's group is kept under. */
|
|
27
|
+
const EVENTS = [
|
|
28
|
+
["PreToolUse", "pre"],
|
|
29
|
+
["PostToolUse", "post"],
|
|
30
|
+
["PostToolUseFailure", "failure"]
|
|
31
|
+
];
|
|
32
|
+
/** The undo record: one entry per settings file, holding exactly the groups we added. */
|
|
33
|
+
const GroupSchema = z.record(z.string(), z.unknown());
|
|
34
|
+
const InstallRecordSchema = z
|
|
35
|
+
.object({
|
|
36
|
+
version: z.literal(1),
|
|
37
|
+
installs: z.array(z
|
|
38
|
+
.object({
|
|
39
|
+
settings_path: z.string(),
|
|
40
|
+
scope: z.enum(["user", "project"]),
|
|
41
|
+
config_path: z.string(),
|
|
42
|
+
installed_at: z.string(),
|
|
43
|
+
/** Whether the settings file existed before, so uninstalling can leave no empty file behind. */
|
|
44
|
+
created_file: z.boolean(),
|
|
45
|
+
/** Whether there was a "hooks" object before, so uninstalling does not leave an empty one. */
|
|
46
|
+
created_hooks: z.boolean(),
|
|
47
|
+
pre: GroupSchema,
|
|
48
|
+
post: GroupSchema,
|
|
49
|
+
failure: GroupSchema.optional()
|
|
50
|
+
})
|
|
51
|
+
.loose())
|
|
52
|
+
})
|
|
53
|
+
.loose();
|
|
54
|
+
export function guardRecordPath(home) {
|
|
55
|
+
return join(resolve(home), ".hmcp", "claude-code-guard.json");
|
|
56
|
+
}
|
|
57
|
+
function readRecord(home) {
|
|
58
|
+
const path = guardRecordPath(home);
|
|
59
|
+
if (!existsSync(path))
|
|
60
|
+
return { version: 1, installs: [] };
|
|
61
|
+
const parsed = InstallRecordSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
|
|
62
|
+
if (!parsed.success) {
|
|
63
|
+
throw new GuardInstallError(`${path} is not a record this version understands, so nothing was changed.`);
|
|
64
|
+
}
|
|
65
|
+
return parsed.data;
|
|
66
|
+
}
|
|
67
|
+
function writeRecord(home, record) {
|
|
68
|
+
const dir = join(resolve(home), ".hmcp");
|
|
69
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
70
|
+
const path = guardRecordPath(home);
|
|
71
|
+
writeTextPreservingMode(path, `${JSON.stringify(record, null, 2)}\n`);
|
|
72
|
+
chmodSync(path, 0o600);
|
|
73
|
+
}
|
|
74
|
+
/** The settings file, `{}` when there is none. Refuses, with nothing changed, a file it cannot safely edit. */
|
|
75
|
+
function readSettings(path) {
|
|
76
|
+
if (!existsSync(path))
|
|
77
|
+
return {};
|
|
78
|
+
let parsed;
|
|
79
|
+
try {
|
|
80
|
+
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
throw new GuardInstallError(`${path} is not valid JSON (${err.message}), so the guard's hooks cannot be added to it. ` +
|
|
84
|
+
`Nothing was changed. Fix that file and try again.`);
|
|
85
|
+
}
|
|
86
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
87
|
+
throw new GuardInstallError(`${path} does not hold a JSON object. Nothing was changed.`);
|
|
88
|
+
}
|
|
89
|
+
const hooks = parsed["hooks"];
|
|
90
|
+
if (hooks !== undefined && (typeof hooks !== "object" || hooks === null || Array.isArray(hooks))) {
|
|
91
|
+
throw new GuardInstallError(`"hooks" in ${path} is not an object. Nothing was changed.`);
|
|
92
|
+
}
|
|
93
|
+
for (const [event] of EVENTS) {
|
|
94
|
+
const list = hooks?.[event];
|
|
95
|
+
if (list !== undefined && !Array.isArray(list)) {
|
|
96
|
+
throw new GuardInstallError(`"hooks.${event}" in ${path} is not a list. Nothing was changed.`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return parsed;
|
|
100
|
+
}
|
|
101
|
+
/** Quoted for the shell Claude Code runs a hook command in. */
|
|
102
|
+
function shellQuote(text) {
|
|
103
|
+
return /^[A-Za-z0-9_@%+=:,./-]+$/.test(text) ? text : `'${text.replace(/'/g, `'\\''`)}'`;
|
|
104
|
+
}
|
|
105
|
+
/** The part of every hook command of ours that names its config: how a hand-edited one is still recognised. */
|
|
106
|
+
function commandMarker(configPath) {
|
|
107
|
+
return ` guard --config ${shellQuote(configPath)}`;
|
|
108
|
+
}
|
|
109
|
+
/** `a.b.c` > `x.y.z`, comparing the numbers; anything after them (a pre-release tag) is ignored. */
|
|
110
|
+
function versionAbove(version, than) {
|
|
111
|
+
const parts = (v) => v.split(/[.-]/).slice(0, 3).map((p) => Number.parseInt(p, 10) || 0);
|
|
112
|
+
const [a, b] = [parts(version), parts(than)];
|
|
113
|
+
for (let i = 0; i < 3; i++)
|
|
114
|
+
if (a[i] !== b[i])
|
|
115
|
+
return a[i] > b[i];
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
/** The first published version with the guard command in it is the one after this. */
|
|
119
|
+
const LAST_VERSION_WITHOUT_GUARD = "0.1.0";
|
|
120
|
+
/**
|
|
121
|
+
* The matcher groups this install adds, or a refusal for a command that would
|
|
122
|
+
* lock the person out.
|
|
123
|
+
*
|
|
124
|
+
* What runs is chosen the way `adopt` chooses it (`clientCommand`): the
|
|
125
|
+
* published version this command came from, or, from a source checkout, this
|
|
126
|
+
* build on disk. Two choices are refused, because with `onFailure: block` a
|
|
127
|
+
* hook that cannot run is every call refused:
|
|
128
|
+
*
|
|
129
|
+
* - a published version that has no guard command in it (0.1.0 does not);
|
|
130
|
+
* - anything under a `.claude/worktrees/` folder, which Claude Code deletes
|
|
131
|
+
* when the worktree is cleaned up -- taking the hook's program, or its
|
|
132
|
+
* config, with it.
|
|
133
|
+
*/
|
|
134
|
+
function ourGroups(options, configPath, waitSeconds) {
|
|
135
|
+
const version = options.version ?? VERSION;
|
|
136
|
+
// Local or not as `adopt` would decide it, first: a pinned version on its own would always mean "not local".
|
|
137
|
+
const local = options.local ?? clientCommand({}).local;
|
|
138
|
+
const launch = clientCommand({ local, pinVersion: version });
|
|
139
|
+
if (launch.local && options.cliPath)
|
|
140
|
+
launch.args = [options.cliPath];
|
|
141
|
+
if (!launch.local && !versionAbove(version, LAST_VERSION_WITHOUT_GUARD)) {
|
|
142
|
+
throw new GuardInstallError(`the published hmcp-gateway ${version} has no guard command, so a hook running it would refuse every tool ` +
|
|
143
|
+
`Claude Code uses. Install from a version newer than ${LAST_VERSION_WITHOUT_GUARD}, or from a copy on disk ` +
|
|
144
|
+
`(--local). Nothing was changed.`);
|
|
145
|
+
}
|
|
146
|
+
const worktree = `${sep}.claude${sep}worktrees${sep}`;
|
|
147
|
+
const inWorktree = [launch.command, ...launch.args, configPath].find((p) => p.includes(worktree) || p.includes("/.claude/worktrees/"));
|
|
148
|
+
if (inWorktree) {
|
|
149
|
+
throw new GuardInstallError(`${inWorktree} is inside a .claude/worktrees folder, which Claude Code deletes when it cleans the worktree up. ` +
|
|
150
|
+
`A hook pointing there would then refuse every tool Claude Code uses. Install from a checkout or a ` +
|
|
151
|
+
`published version that stays put, with a config outside that folder. Nothing was changed.`);
|
|
152
|
+
}
|
|
153
|
+
const where = options.scope === "user"
|
|
154
|
+
? " --scope user"
|
|
155
|
+
: ` --scope project --project-dir ${shellQuote(resolve(options.projectDir))}`;
|
|
156
|
+
const entryName = options.entryName ?? GUARD_DEFAULT_ENTRY;
|
|
157
|
+
const base = [launch.command, ...launch.args].map(shellQuote).join(" ") +
|
|
158
|
+
commandMarker(configPath) +
|
|
159
|
+
(entryName === GUARD_DEFAULT_ENTRY ? "" : ` --entry-name ${shellQuote(entryName)}`) +
|
|
160
|
+
where;
|
|
161
|
+
/*
|
|
162
|
+
* `onFailure: block` so a guard that crashes or runs out of time stops the
|
|
163
|
+
* call, the way the guard itself does for any error it can catch. The
|
|
164
|
+
* timeout leaves the wait room to finish and report.
|
|
165
|
+
*/
|
|
166
|
+
const hook = (command) => ({
|
|
167
|
+
type: "command",
|
|
168
|
+
command,
|
|
169
|
+
timeout: waitSeconds + GUARD_TIMEOUT_MARGIN_SECONDS,
|
|
170
|
+
onFailure: "block"
|
|
171
|
+
});
|
|
172
|
+
return {
|
|
173
|
+
pre: { matcher: "*", hooks: [hook(`${base} --wait ${waitSeconds}`)] },
|
|
174
|
+
post: { matcher: "*", hooks: [hook(`${base} --event post`)] },
|
|
175
|
+
failure: { matcher: "*", hooks: [hook(`${base} --event post`)] }
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function listOf(settings, event) {
|
|
179
|
+
return settings["hooks"]?.[event] ?? [];
|
|
180
|
+
}
|
|
181
|
+
function recordedGroup(entry, key) {
|
|
182
|
+
return entry[key];
|
|
183
|
+
}
|
|
184
|
+
/** Whether one hook in a group runs this guard with this config: ours, however it has been edited. */
|
|
185
|
+
function isOurHook(hook, configPath) {
|
|
186
|
+
const command = hook?.command;
|
|
187
|
+
return typeof command === "string" && command.includes(commandMarker(configPath));
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* The settings with our hooks taken out, and how many were.
|
|
191
|
+
*
|
|
192
|
+
* A group exactly as recorded goes whole. Otherwise, inside any group, a hook
|
|
193
|
+
* running this guard with the recorded config goes, the rest of the group
|
|
194
|
+
* stays, and a group left with no hooks goes. Empty containers we made go too.
|
|
195
|
+
*/
|
|
196
|
+
function withoutOurs(settings, entry) {
|
|
197
|
+
const hooks = { ...(settings["hooks"] ?? {}) };
|
|
198
|
+
let removed = 0;
|
|
199
|
+
for (const [event, key] of EVENTS) {
|
|
200
|
+
const list = listOf(settings, event);
|
|
201
|
+
const recorded = recordedGroup(entry, key);
|
|
202
|
+
const kept = [];
|
|
203
|
+
let changed = false;
|
|
204
|
+
for (const group of list) {
|
|
205
|
+
if (recorded && sameJson(group, recorded)) {
|
|
206
|
+
removed += Array.isArray(group["hooks"]) ? group["hooks"].length : 1;
|
|
207
|
+
changed = true;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const inner = group?.["hooks"];
|
|
211
|
+
if (Array.isArray(inner) && inner.some((h) => isOurHook(h, entry.config_path))) {
|
|
212
|
+
const rest = inner.filter((h) => !isOurHook(h, entry.config_path));
|
|
213
|
+
removed += inner.length - rest.length;
|
|
214
|
+
changed = true;
|
|
215
|
+
if (rest.length > 0)
|
|
216
|
+
kept.push({ ...group, hooks: rest });
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
kept.push(group);
|
|
220
|
+
}
|
|
221
|
+
if (!changed)
|
|
222
|
+
continue;
|
|
223
|
+
if (kept.length === 0)
|
|
224
|
+
delete hooks[event];
|
|
225
|
+
else
|
|
226
|
+
hooks[event] = kept;
|
|
227
|
+
}
|
|
228
|
+
const out = { ...settings };
|
|
229
|
+
if (settings["hooks"] !== undefined) {
|
|
230
|
+
if (Object.keys(hooks).length === 0 && entry.created_hooks && removed > 0)
|
|
231
|
+
delete out["hooks"];
|
|
232
|
+
else
|
|
233
|
+
out["hooks"] = hooks;
|
|
234
|
+
}
|
|
235
|
+
return { settings: out, removed };
|
|
236
|
+
}
|
|
237
|
+
function writeSettings(path, settings) {
|
|
238
|
+
writeTextPreservingMode(path, `${JSON.stringify(settings, null, 2)}\n`);
|
|
239
|
+
}
|
|
240
|
+
/** Lines of a `.gitignore` that keep `.claude/settings.local.json` out of git. Only this file is read. */
|
|
241
|
+
const IGNORES_LOCAL_SETTINGS = new Set([
|
|
242
|
+
".claude",
|
|
243
|
+
".claude/",
|
|
244
|
+
".claude/*",
|
|
245
|
+
".claude/**",
|
|
246
|
+
".claude/settings.local.json",
|
|
247
|
+
".claude/*.local.json",
|
|
248
|
+
"settings.local.json",
|
|
249
|
+
"*.local.json",
|
|
250
|
+
"**/settings.local.json",
|
|
251
|
+
"**/.claude",
|
|
252
|
+
"**/.claude/",
|
|
253
|
+
"**/.claude/settings.local.json"
|
|
254
|
+
]);
|
|
255
|
+
/** A plain warning when a git project's own `.gitignore` does not cover the settings file, else null. */
|
|
256
|
+
function gitignoreWarning(projectDir) {
|
|
257
|
+
if (!existsSync(join(projectDir, ".git")))
|
|
258
|
+
return null;
|
|
259
|
+
let lines = [];
|
|
260
|
+
try {
|
|
261
|
+
lines = readFileSync(join(projectDir, ".gitignore"), "utf8").split(/\r?\n/);
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
/* no .gitignore: nothing covers it */
|
|
265
|
+
}
|
|
266
|
+
const covered = lines
|
|
267
|
+
.map((l) => l.trim())
|
|
268
|
+
.filter((l) => l !== "" && !l.startsWith("#") && !l.startsWith("!"))
|
|
269
|
+
.some((l) => IGNORES_LOCAL_SETTINGS.has(l.replace(/^\//, "")));
|
|
270
|
+
return covered
|
|
271
|
+
? null
|
|
272
|
+
: `${join(projectDir, ".gitignore")} does not list .claude/settings.local.json. That file now names a path on ` +
|
|
273
|
+
`this computer; make sure it is not committed (add ".claude/settings.local.json" to .gitignore).`;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Adds the guard's hooks. Run again with the same choices, it changes nothing;
|
|
277
|
+
* with different ones (another config, another wait), it replaces the hooks
|
|
278
|
+
* it added before rather than stacking a second set.
|
|
279
|
+
*/
|
|
280
|
+
export function installGuard(options) {
|
|
281
|
+
const settingsPath = guardSettingsPath(options.scope, options);
|
|
282
|
+
const configPath = resolve(options.configPath);
|
|
283
|
+
// A hook pointing at a config that does not load would refuse every call Claude Code makes.
|
|
284
|
+
let opened;
|
|
285
|
+
try {
|
|
286
|
+
opened = openGuard(configPath);
|
|
287
|
+
}
|
|
288
|
+
catch (err) {
|
|
289
|
+
throw new GuardInstallError(`${configPath} could not be loaded (${err.message}). Nothing was changed.`);
|
|
290
|
+
}
|
|
291
|
+
const { policy } = opened;
|
|
292
|
+
opened.close();
|
|
293
|
+
const waitSeconds = options.waitSeconds ?? guardWaitSeconds(policy);
|
|
294
|
+
if (!Number.isInteger(waitSeconds) || waitSeconds < 0 || waitSeconds > 540) {
|
|
295
|
+
throw new GuardInstallError("the wait must be a whole number of seconds between 0 and 540. Nothing was changed.");
|
|
296
|
+
}
|
|
297
|
+
const existed = existsSync(settingsPath);
|
|
298
|
+
const original = readSettings(settingsPath);
|
|
299
|
+
const groups = ourGroups(options, configPath, waitSeconds);
|
|
300
|
+
const record = readRecord(options.home);
|
|
301
|
+
const previous = record.installs.find((i) => i.settings_path === settingsPath);
|
|
302
|
+
const settings = previous ? withoutOurs(original, previous).settings : original;
|
|
303
|
+
const hooks = { ...(settings["hooks"] ?? {}) };
|
|
304
|
+
for (const [event, key] of EVENTS)
|
|
305
|
+
hooks[event] = [...listOf(settings, event), groups[key]];
|
|
306
|
+
const next = { ...settings, hooks };
|
|
307
|
+
const changed = !existed || !sameJson(original, next);
|
|
308
|
+
const result = {
|
|
309
|
+
settingsPath,
|
|
310
|
+
changed,
|
|
311
|
+
dryRun: options.dryRun === true,
|
|
312
|
+
settings: next,
|
|
313
|
+
configPath,
|
|
314
|
+
waitSeconds,
|
|
315
|
+
observing: policy.enforcement === "observe",
|
|
316
|
+
gitignoreWarning: options.scope === "project" ? gitignoreWarning(resolve(options.projectDir)) : null
|
|
317
|
+
};
|
|
318
|
+
if (options.dryRun || !changed)
|
|
319
|
+
return result;
|
|
320
|
+
// The record first: a hook written with no record of it is one uninstall could never take out.
|
|
321
|
+
writeRecord(options.home, {
|
|
322
|
+
...record,
|
|
323
|
+
installs: [
|
|
324
|
+
...record.installs.filter((i) => i.settings_path !== settingsPath),
|
|
325
|
+
{
|
|
326
|
+
settings_path: settingsPath,
|
|
327
|
+
scope: options.scope,
|
|
328
|
+
config_path: configPath,
|
|
329
|
+
installed_at: new Date().toISOString(),
|
|
330
|
+
created_file: previous ? previous.created_file : !existed,
|
|
331
|
+
created_hooks: previous ? previous.created_hooks : original["hooks"] === undefined,
|
|
332
|
+
pre: groups["pre"],
|
|
333
|
+
post: groups["post"],
|
|
334
|
+
failure: groups["failure"]
|
|
335
|
+
}
|
|
336
|
+
]
|
|
337
|
+
});
|
|
338
|
+
writeSettings(settingsPath, next);
|
|
339
|
+
return result;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Takes out the hooks `installGuard` recorded for this settings file.
|
|
343
|
+
*
|
|
344
|
+
* The record is kept when nothing could be found to remove -- the file was
|
|
345
|
+
* edited, or replaced -- so a later uninstall, after the hooks are back, can
|
|
346
|
+
* still find what is ours.
|
|
347
|
+
*/
|
|
348
|
+
export function uninstallGuard(options) {
|
|
349
|
+
const settingsPath = guardSettingsPath(options.scope, options);
|
|
350
|
+
const record = readRecord(options.home);
|
|
351
|
+
const entry = record.installs.find((i) => i.settings_path === settingsPath);
|
|
352
|
+
if (!entry)
|
|
353
|
+
return { settingsPath, removed: 0, dryRun: options.dryRun === true };
|
|
354
|
+
const current = readSettings(settingsPath);
|
|
355
|
+
const { settings, removed } = withoutOurs(current, entry);
|
|
356
|
+
if (options.dryRun || removed === 0)
|
|
357
|
+
return { settingsPath, removed, dryRun: options.dryRun === true };
|
|
358
|
+
if (entry.created_file && Object.keys(settings).length === 0)
|
|
359
|
+
unlinkSync(settingsPath);
|
|
360
|
+
else
|
|
361
|
+
writeSettings(settingsPath, settings);
|
|
362
|
+
writeRecord(options.home, { ...record, installs: record.installs.filter((i) => i !== entry) });
|
|
363
|
+
return { settingsPath, removed, dryRun: false };
|
|
364
|
+
}
|
|
365
|
+
/** Whether the guard is on for a scope: our hooks, as installed or edited since, in that settings file. */
|
|
366
|
+
export function guardStatus(options) {
|
|
367
|
+
const settingsPath = guardSettingsPath(options.scope, options);
|
|
368
|
+
const entry = readRecord(options.home).installs.find((i) => i.settings_path === settingsPath);
|
|
369
|
+
let exact = false;
|
|
370
|
+
let ours = false;
|
|
371
|
+
if (entry && existsSync(settingsPath)) {
|
|
372
|
+
try {
|
|
373
|
+
const settings = readSettings(settingsPath);
|
|
374
|
+
exact = EVENTS.every(([event, key]) => {
|
|
375
|
+
const recorded = recordedGroup(entry, key);
|
|
376
|
+
return recorded === undefined || listOf(settings, event).some((g) => sameJson(g, recorded));
|
|
377
|
+
});
|
|
378
|
+
ours = EVENTS.some(([event]) => listOf(settings, event).some((g) => {
|
|
379
|
+
const inner = g?.["hooks"];
|
|
380
|
+
return Array.isArray(inner) && inner.some((h) => isOurHook(h, entry.config_path));
|
|
381
|
+
}));
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
exact = ours = false;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const installed = exact || ours;
|
|
388
|
+
return {
|
|
389
|
+
scope: options.scope,
|
|
390
|
+
settingsPath,
|
|
391
|
+
installed,
|
|
392
|
+
changedByHand: installed && !exact,
|
|
393
|
+
configPath: installed && entry ? entry.config_path : null,
|
|
394
|
+
installedAt: installed && entry ? entry.installed_at : null
|
|
395
|
+
};
|
|
396
|
+
}
|