@mylasecurity/gate 0.0.0-stage → 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 +62 -2
- package/bin/gate.mjs +945 -0
- package/package.json +21 -4
package/README.md
CHANGED
|
@@ -1,3 +1,63 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mylasecurity/gate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
One command to put the Myla Gate in front of a coding agent. It fetches a one-time claim, **merges**
|
|
4
|
+
its hooks into your per-user settings file (never replaces the file), **backs up first**, writes
|
|
5
|
+
atomically, and prints exactly what it changed — so a non-developer never has to find a hidden folder
|
|
6
|
+
or merge JSON by hand.
|
|
7
|
+
|
|
8
|
+
```
|
|
9
|
+
npx @mylasecurity/gate install <claim-code>
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Commands
|
|
13
|
+
|
|
14
|
+
| Command | What it does |
|
|
15
|
+
| --- | --- |
|
|
16
|
+
| `install <code>` | The whole job: fetch → validate → back up → merge → write → report. |
|
|
17
|
+
| `install <code> --dry-run` | Fetch, validate, print exactly what *would* be written and where. Writes nothing. The config is printed with the credential **masked**. |
|
|
18
|
+
| `doctor` | Read the settings file and say whether a Myla hook is installed, which host it points at, and whether you still need to restart. No network, no writes. |
|
|
19
|
+
| `uninstall` | Remove **only** Myla's hook entries, keep everything else, back up first. |
|
|
20
|
+
|
|
21
|
+
### Flags
|
|
22
|
+
|
|
23
|
+
- `--client claude-code\|cursor\|codex` — which agent (default `claude-code`).
|
|
24
|
+
- `--origin <url>` — which Myla deployment (default the production host). Needed to install against a
|
|
25
|
+
staging or local deployment.
|
|
26
|
+
- `--dry-run` — `install`/`uninstall`: don't write, just show.
|
|
27
|
+
|
|
28
|
+
## Guarantees
|
|
29
|
+
|
|
30
|
+
- **It never prints the credential.** Not in `--dry-run`, not in an error, not in `doctor`. The mask is
|
|
31
|
+
the install sheet's own `CONFIG_TOKEN_MASK`, reused — there is no second masker.
|
|
32
|
+
- **It never drops a hook you wrote.** A hook entry is removed only when every URL inside it points at
|
|
33
|
+
the Myla origin. Your own hooks, and hooks pointing anywhere else, are kept.
|
|
34
|
+
- **It never clobbers a malformed file.** If the settings file isn't valid JSON, it stops, names the
|
|
35
|
+
line, and changes nothing — no write, no backup.
|
|
36
|
+
- **A reinstall is idempotent.** A prior Myla block is replaced, not duplicated.
|
|
37
|
+
|
|
38
|
+
## Running it before it's published
|
|
39
|
+
|
|
40
|
+
This package is **not published to npm** (that's the owner's call, a separate step). Until it is, run it
|
|
41
|
+
from the repo. It has no dependencies.
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
# From the repo root — same tsx the rest of the repo's scripts use:
|
|
45
|
+
npx tsx packages/gate-cli/src/cli.ts install <claim-code>
|
|
46
|
+
npx tsx packages/gate-cli/src/cli.ts install <claim-code> --dry-run
|
|
47
|
+
npx tsx packages/gate-cli/src/cli.ts doctor
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Or build the standalone, dependency-free bin and run that:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
cd packages/gate-cli && npm run build # esbuild → bin/gate.mjs (a single file, no node_modules)
|
|
54
|
+
node packages/gate-cli/bin/gate.mjs doctor
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`bin/gate.mjs` is a build artifact (git-ignored); regenerate it with `npm run build`. The source in
|
|
58
|
+
`src/` is the single source of truth, and the tests run against the source, not the bundle.
|
|
59
|
+
|
|
60
|
+
## Tests
|
|
61
|
+
|
|
62
|
+
Fixture-driven, offline, no real credential: `scripts/security-gate-cli-test.ts`, wired as
|
|
63
|
+
`npm run check:gate-cli` and picked up by `npm run check:all`.
|
package/bin/gate.mjs
ADDED
|
@@ -0,0 +1,945 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// ../../src/lib/security/gate/claim-ttl.ts
|
|
4
|
+
var CLAIM_TTL_MS = 60 * 60 * 1e3;
|
|
5
|
+
var CLAIM_TTL_LABEL = (() => {
|
|
6
|
+
const h = CLAIM_TTL_MS / 36e5;
|
|
7
|
+
if (h === 1) return "one hour";
|
|
8
|
+
if (Number.isInteger(h)) return `${h} hours`;
|
|
9
|
+
return `${CLAIM_TTL_MS / 6e4} minutes`;
|
|
10
|
+
})();
|
|
11
|
+
|
|
12
|
+
// ../../src/components/security/gate/hookInstall.ts
|
|
13
|
+
var CONFIG_TOKEN_MASK = "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 \u2039hidden \u2014 tap Reveal\u203A";
|
|
14
|
+
function maskConfigToken(config, token) {
|
|
15
|
+
return token ? config.replaceAll(token, CONFIG_TOKEN_MASK) : config;
|
|
16
|
+
}
|
|
17
|
+
var INSTALL_WAITING_CAUSES = [
|
|
18
|
+
{ lead: "Not restarted.", rest: "Hooks are read once, when the agent starts." },
|
|
19
|
+
{ lead: "Wrong folder.", rest: "The file is in a project instead of your home folder." },
|
|
20
|
+
{ lead: "Masked copy.", rest: "The config was selected from the screen instead of copied with the button, so the token is a row of dots." },
|
|
21
|
+
// AD105 — the agent-install path can fail a fourth way: the one-time claim link lapsed before the
|
|
22
|
+
// agent fetched it.
|
|
23
|
+
{ lead: "Link expired.", rest: `The one-time install link lasts ${CLAIM_TTL_LABEL} \u2014 issue a new one.` }
|
|
24
|
+
];
|
|
25
|
+
function hookConfigShape(config) {
|
|
26
|
+
let usesShell = false;
|
|
27
|
+
try {
|
|
28
|
+
const walk = (v) => {
|
|
29
|
+
if (Array.isArray(v)) {
|
|
30
|
+
v.forEach(walk);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (v && typeof v === "object") {
|
|
34
|
+
const o = v;
|
|
35
|
+
if (typeof o.command === "string" || o.type === "command") usesShell = true;
|
|
36
|
+
Object.values(o).forEach(walk);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
walk(JSON.parse(config));
|
|
40
|
+
} catch {
|
|
41
|
+
usesShell = /"type"\s*:\s*"command"/.test(config) || /"command"\s*:/.test(config);
|
|
42
|
+
}
|
|
43
|
+
const hosts = Array.from(new Set(Array.from(config.matchAll(/https?:\/\/([^\s"'/\\]+)/g), (m) => m[1])));
|
|
44
|
+
return { usesShell, hosts };
|
|
45
|
+
}
|
|
46
|
+
var CLAUDE_CODE_WATCHED_TOOLS = ["Bash", "Write", "Edit"];
|
|
47
|
+
var CLAUDE_CODE_EXACT_MATCHER = CLAUDE_CODE_WATCHED_TOOLS.join("|");
|
|
48
|
+
var CLAUDE_CODE_MCP_MATCHER = "mcp__.*";
|
|
49
|
+
function watchTokens(client) {
|
|
50
|
+
if (client === "cursor") return ["beforeShellExecution", "beforeMCPExecution", "beforeReadFile"];
|
|
51
|
+
if (client === "codex") return ["*"];
|
|
52
|
+
return [...CLAUDE_CODE_WATCHED_TOOLS, CLAUDE_CODE_MCP_MATCHER, "Read", "WebFetch", "WebSearch"];
|
|
53
|
+
}
|
|
54
|
+
function fnv1a(s) {
|
|
55
|
+
let h = 2166136261;
|
|
56
|
+
for (let i = 0; i < s.length; i++) {
|
|
57
|
+
h ^= s.charCodeAt(i);
|
|
58
|
+
h = Math.imul(h, 16777619);
|
|
59
|
+
}
|
|
60
|
+
return (h >>> 0).toString(16).padStart(8, "0");
|
|
61
|
+
}
|
|
62
|
+
function hookVersion(client) {
|
|
63
|
+
return fnv1a(`${client}
|
|
64
|
+
${watchTokens(client).join("|")}
|
|
65
|
+
${hookConfigJson(client, "ORIGIN", "TOKEN", "VERSION")}`);
|
|
66
|
+
}
|
|
67
|
+
var curl = (origin, token, path5, fallback, version) => `curl -sS -f --max-time 10 -X POST ${origin}${path5} -H "Authorization: Bearer ${token}" -H "Content-Type: application/json" -H "X-Myla-Hook-Version: ${version}" --data-binary @- || printf '${fallback}'`;
|
|
68
|
+
var CURSOR_ALLOW = '{"permission":"allow"}';
|
|
69
|
+
var CODEX_ALLOW = "{}";
|
|
70
|
+
function hookConfigJson(client, origin, token, version) {
|
|
71
|
+
if (client === "cursor") {
|
|
72
|
+
const shell = curl(origin, token, "/api/security/gate/hook/cursor", CURSOR_ALLOW, version);
|
|
73
|
+
const read = curl(origin, token, "/api/security/gate/hook/cursor/report", CURSOR_ALLOW, version);
|
|
74
|
+
return JSON.stringify({
|
|
75
|
+
version: 1,
|
|
76
|
+
hooks: {
|
|
77
|
+
beforeShellExecution: [{ command: shell }],
|
|
78
|
+
beforeMCPExecution: [{ command: shell }],
|
|
79
|
+
beforeReadFile: [{ command: read }]
|
|
80
|
+
}
|
|
81
|
+
}, null, 2);
|
|
82
|
+
}
|
|
83
|
+
if (client === "codex") {
|
|
84
|
+
const pre = curl(origin, token, "/api/security/gate/hook/codex", CODEX_ALLOW, version);
|
|
85
|
+
const post = curl(origin, token, "/api/security/gate/hook/codex/report", CODEX_ALLOW, version);
|
|
86
|
+
return JSON.stringify({
|
|
87
|
+
hooks: {
|
|
88
|
+
PreToolUse: [{ matcher: ".*", hooks: [{ type: "command", command: pre }] }],
|
|
89
|
+
PostToolUse: [{ matcher: ".*", hooks: [{ type: "command", command: post }] }]
|
|
90
|
+
}
|
|
91
|
+
}, null, 2);
|
|
92
|
+
}
|
|
93
|
+
const httpHook = (path5, timeout) => [{
|
|
94
|
+
type: "http",
|
|
95
|
+
url: `${origin}${path5}`,
|
|
96
|
+
timeout,
|
|
97
|
+
headers: { Authorization: `Bearer ${token}`, "X-Myla-Hook-Version": version }
|
|
98
|
+
}];
|
|
99
|
+
const preHook = httpHook("/api/security/gate/hook/claude-code", 10);
|
|
100
|
+
return JSON.stringify({
|
|
101
|
+
hooks: {
|
|
102
|
+
PreToolUse: [
|
|
103
|
+
{ matcher: CLAUDE_CODE_EXACT_MATCHER, hooks: preHook },
|
|
104
|
+
{ matcher: CLAUDE_CODE_MCP_MATCHER, hooks: preHook }
|
|
105
|
+
],
|
|
106
|
+
PostToolUse: [{ matcher: "Read|WebFetch|WebSearch", hooks: httpHook("/api/security/gate/hook/claude-code/report", 5) }]
|
|
107
|
+
}
|
|
108
|
+
}, null, 2);
|
|
109
|
+
}
|
|
110
|
+
function hookInstall(client, origin, token) {
|
|
111
|
+
const config = hookConfigJson(client, origin, token, hookVersion(client));
|
|
112
|
+
if (client === "cursor") {
|
|
113
|
+
return {
|
|
114
|
+
label: "Cursor",
|
|
115
|
+
perUserPath: "~/.cursor/hooks.json",
|
|
116
|
+
merge: false,
|
|
117
|
+
usesShellCommand: true,
|
|
118
|
+
config,
|
|
119
|
+
enterprise: "Enforce it for everyone (can\u2019t be switched off) via the MDM path: /Library/Application Support/Cursor/hooks.json (macOS), /etc/cursor/hooks.json (Linux), or C:\\ProgramData\\Cursor\\hooks.json (Windows).",
|
|
120
|
+
notes: [
|
|
121
|
+
"Windows is not yet supported for Cursor. The fail-open fallback is a POSIX shell line (|| printf \u2026), and Cursor runs hooks through PowerShell on Windows, where it does not apply \u2014 so a Myla outage could BLOCK Cursor there. Install on macOS or Linux for now; Windows support is tracked.",
|
|
122
|
+
"Cursor sees shell commands, MCP tool calls, and file reads (reported before the read runs, so a read Myla records may not have completed). It does not see Cursor\u2019s web search or web fetches \u2014 provenance from the web isn\u2019t captured on Cursor."
|
|
123
|
+
]
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
if (client === "codex") {
|
|
127
|
+
return {
|
|
128
|
+
label: "Codex",
|
|
129
|
+
perUserPath: "~/.codex/hooks.json",
|
|
130
|
+
merge: false,
|
|
131
|
+
usesShellCommand: true,
|
|
132
|
+
config,
|
|
133
|
+
enterprise: "Enforce it for everyone (can\u2019t be switched off) via a managed hooks directory with allow_managed_hooks_only in requirements.toml.",
|
|
134
|
+
notes: [
|
|
135
|
+
"REQUIRED: Codex ignores these hooks until you trust them \u2014 run /hooks in Codex and approve, or nothing is gated. You must do this AGAIN after every reissue or config change: Codex keys trust to a hash of the hook command, so a new token or version silently turns the hook off until you re-run /hooks.",
|
|
136
|
+
"No live event has been seen from Codex yet, so it stays unconfirmed until one arrives (the agents card shows \u201Cnever contacted the Gate\u201D until then). The .* matcher itself is confirmed correct against Codex\u2019s source.",
|
|
137
|
+
"Codex sees shell commands (and apply_patch); its web search is hosted and never reaches the hook, and some shell interception is incomplete \u2014 so provenance of what Codex read is not captured."
|
|
138
|
+
]
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
label: "Claude Code",
|
|
143
|
+
perUserPath: "~/.claude/settings.json",
|
|
144
|
+
merge: true,
|
|
145
|
+
usesShellCommand: false,
|
|
146
|
+
config,
|
|
147
|
+
enterprise: "Enforce it for everyone (can\u2019t be switched off) via managed settings deployed by your MDM: /Library/Application Support/ClaudeCode/managed-settings.json (macOS), /etc/claude-code/managed-settings.json (Linux), or C:\\ProgramData\\ClaudeCode\\managed-settings.json (Windows).",
|
|
148
|
+
notes: [
|
|
149
|
+
"Claude Code reports file reads and web fetches/searches after they happen, so Myla sees what each session read."
|
|
150
|
+
]
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// src/shared.ts
|
|
155
|
+
var HOOK_CLIENTS = ["claude-code", "cursor", "codex"];
|
|
156
|
+
|
|
157
|
+
// src/constants.ts
|
|
158
|
+
var DEFAULT_ORIGIN = (process.env.NEXT_PUBLIC_APP_ORIGIN || "https://mylasecurity.app").replace(/\/+$/, "");
|
|
159
|
+
var MIN_NODE_MAJOR = 18;
|
|
160
|
+
var MYLA_HOOK_PATH = "/api/security/gate/hook";
|
|
161
|
+
|
|
162
|
+
// src/install.ts
|
|
163
|
+
import fs3 from "node:fs";
|
|
164
|
+
import path3 from "node:path";
|
|
165
|
+
import os2 from "node:os";
|
|
166
|
+
|
|
167
|
+
// src/paths.ts
|
|
168
|
+
import os from "node:os";
|
|
169
|
+
import path from "node:path";
|
|
170
|
+
import fs from "node:fs";
|
|
171
|
+
function resolveUserPath(perUserPath) {
|
|
172
|
+
const segments = perUserPath.replace(/\\/g, "/").split("/").filter((s) => s.length > 0);
|
|
173
|
+
if (segments[0] === "~") return path.join(os.homedir(), ...segments.slice(1));
|
|
174
|
+
return path.normalize(perUserPath);
|
|
175
|
+
}
|
|
176
|
+
function nextBackupPath(file) {
|
|
177
|
+
let candidate = `${file}.bak`;
|
|
178
|
+
let n = 2;
|
|
179
|
+
while (fs.existsSync(candidate)) {
|
|
180
|
+
candidate = `${file}.bak.${n}`;
|
|
181
|
+
n++;
|
|
182
|
+
}
|
|
183
|
+
return candidate;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// src/validate.ts
|
|
187
|
+
function originHostOf(origin) {
|
|
188
|
+
try {
|
|
189
|
+
return new URL(origin).host;
|
|
190
|
+
} catch {
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function validateClaim(body, client, origin) {
|
|
195
|
+
const host = originHostOf(origin);
|
|
196
|
+
if (!host) return { ok: false, reason: `the origin ${JSON.stringify(origin)} is not a valid URL.` };
|
|
197
|
+
let parsed;
|
|
198
|
+
try {
|
|
199
|
+
parsed = JSON.parse(body);
|
|
200
|
+
} catch {
|
|
201
|
+
return { ok: false, reason: "the server did not return valid JSON." };
|
|
202
|
+
}
|
|
203
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
204
|
+
return { ok: false, reason: "the response is not a JSON object." };
|
|
205
|
+
}
|
|
206
|
+
const obj = parsed;
|
|
207
|
+
const referenceKeys = Object.keys(JSON.parse(hookInstall(client, origin, "PLACEHOLDER").config));
|
|
208
|
+
const unexpected = Object.keys(obj).filter((k) => !referenceKeys.includes(k));
|
|
209
|
+
if (unexpected.length > 0) {
|
|
210
|
+
return { ok: false, reason: `it has unexpected top-level key(s): ${unexpected.join(", ")}.` };
|
|
211
|
+
}
|
|
212
|
+
if (!obj.hooks || typeof obj.hooks !== "object" || Array.isArray(obj.hooks)) {
|
|
213
|
+
return { ok: false, reason: 'it has no "hooks" object.' };
|
|
214
|
+
}
|
|
215
|
+
const shape = hookConfigShape(body);
|
|
216
|
+
if (shape.hosts.length === 0) {
|
|
217
|
+
return { ok: false, reason: "none of the hooks point at a host." };
|
|
218
|
+
}
|
|
219
|
+
const foreign = shape.hosts.filter((h) => h !== host);
|
|
220
|
+
if (foreign.length > 0) {
|
|
221
|
+
return { ok: false, reason: `a hook points at an unexpected host (${foreign.join(", ")}), not ${host}.` };
|
|
222
|
+
}
|
|
223
|
+
if (client === "claude-code" && shape.usesShell) {
|
|
224
|
+
return { ok: false, reason: "it contains a shell command, which a Claude Code config never does." };
|
|
225
|
+
}
|
|
226
|
+
const m = body.match(/Bearer\s+([^\s"'\\]+)/);
|
|
227
|
+
const token = m ? m[1] : "";
|
|
228
|
+
return { ok: true, config: obj, token };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// src/merge.ts
|
|
232
|
+
var SettingsParseError = class extends Error {
|
|
233
|
+
constructor(where, message) {
|
|
234
|
+
super(message);
|
|
235
|
+
this.where = where;
|
|
236
|
+
this.name = "SettingsParseError";
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
function stripBom(s) {
|
|
240
|
+
return s.replace(/^/, "");
|
|
241
|
+
}
|
|
242
|
+
function isPlainObject(v) {
|
|
243
|
+
return !!v && typeof v === "object" && !Array.isArray(v);
|
|
244
|
+
}
|
|
245
|
+
var HOST_RE = /https?:\/\/([^\s"'/\\]+)/g;
|
|
246
|
+
function collectHosts(value, out = /* @__PURE__ */ new Set()) {
|
|
247
|
+
if (typeof value === "string") {
|
|
248
|
+
for (const m of value.matchAll(HOST_RE)) out.add(m[1]);
|
|
249
|
+
} else if (Array.isArray(value)) {
|
|
250
|
+
for (const v of value) collectHosts(v, out);
|
|
251
|
+
} else if (value && typeof value === "object") {
|
|
252
|
+
for (const v of Object.values(value)) collectHosts(v, out);
|
|
253
|
+
}
|
|
254
|
+
return out;
|
|
255
|
+
}
|
|
256
|
+
function isOurEntry(entry, originHost) {
|
|
257
|
+
const hosts = collectHosts(entry);
|
|
258
|
+
return hosts.size > 0 && [...hosts].every((h) => h === originHost);
|
|
259
|
+
}
|
|
260
|
+
function detectIndent(raw) {
|
|
261
|
+
const m = /\n([ \t]+)"/.exec(stripBom(raw));
|
|
262
|
+
if (!m) return 2;
|
|
263
|
+
return m[1].includes(" ") ? " " : m[1].length;
|
|
264
|
+
}
|
|
265
|
+
function hadTrailingNewline(raw) {
|
|
266
|
+
return /\n[ \t]*$/.test(raw);
|
|
267
|
+
}
|
|
268
|
+
function lineAt(text, index) {
|
|
269
|
+
return text.slice(0, Math.max(0, index)).split("\n").length;
|
|
270
|
+
}
|
|
271
|
+
function locateJsonError(text, message) {
|
|
272
|
+
const lineCol = /line (\d+)/i.exec(message);
|
|
273
|
+
if (lineCol) return `line ${lineCol[1]}`;
|
|
274
|
+
const pos = /position (\d+)/i.exec(message);
|
|
275
|
+
if (pos) return `line ${lineAt(text, Number(pos[1]))}`;
|
|
276
|
+
const marker = " is not valid JSON";
|
|
277
|
+
const mi = message.indexOf(marker);
|
|
278
|
+
if (mi > 0) {
|
|
279
|
+
let frag = message.slice(0, mi).trim().replace(/\.\.\.$/, "").replace(/"$/, "");
|
|
280
|
+
frag = frag.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
|
|
281
|
+
for (const len of [40, 24, 12, 6, 3]) {
|
|
282
|
+
const tail = frag.slice(-len);
|
|
283
|
+
if (tail.includes("...")) continue;
|
|
284
|
+
const idx = text.indexOf(tail);
|
|
285
|
+
if (idx >= 0) return `line ${lineAt(text, idx + tail.length)}`;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return "an unreadable spot";
|
|
289
|
+
}
|
|
290
|
+
function parseSettings(raw) {
|
|
291
|
+
const text = stripBom(raw);
|
|
292
|
+
let parsed;
|
|
293
|
+
try {
|
|
294
|
+
parsed = JSON.parse(text);
|
|
295
|
+
} catch (e) {
|
|
296
|
+
const message = e.message;
|
|
297
|
+
throw new SettingsParseError(locateJsonError(text, message), message);
|
|
298
|
+
}
|
|
299
|
+
if (!isPlainObject(parsed)) {
|
|
300
|
+
throw new SettingsParseError("the top level", "the file is valid JSON but not an object");
|
|
301
|
+
}
|
|
302
|
+
return parsed;
|
|
303
|
+
}
|
|
304
|
+
function mergeSettings(opts) {
|
|
305
|
+
const { existingRaw, fetchedConfig, originHost } = opts;
|
|
306
|
+
const present = existingRaw !== null && stripBom(existingRaw).trim() !== "";
|
|
307
|
+
if (!present) {
|
|
308
|
+
return {
|
|
309
|
+
text: JSON.stringify(fetchedConfig, null, 2) + "\n",
|
|
310
|
+
createdFile: true,
|
|
311
|
+
keptSettings: 0,
|
|
312
|
+
keptUserHooks: 0,
|
|
313
|
+
replacedMylaHooks: 0
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
const existing = parseSettings(existingRaw);
|
|
317
|
+
const indent = detectIndent(existingRaw);
|
|
318
|
+
const result = { ...existing };
|
|
319
|
+
for (const k of Object.keys(fetchedConfig)) {
|
|
320
|
+
if (k !== "hooks" && !(k in result)) result[k] = fetchedConfig[k];
|
|
321
|
+
}
|
|
322
|
+
const existingHooks = isPlainObject(existing.hooks) ? existing.hooks : {};
|
|
323
|
+
const fetchedHooks = isPlainObject(fetchedConfig.hooks) ? fetchedConfig.hooks : {};
|
|
324
|
+
const mergedHooks = {};
|
|
325
|
+
let keptUserHooks = 0;
|
|
326
|
+
let replacedMylaHooks = 0;
|
|
327
|
+
const events = /* @__PURE__ */ new Set([...Object.keys(existingHooks), ...Object.keys(fetchedHooks)]);
|
|
328
|
+
for (const ev of events) {
|
|
329
|
+
const existingArr = Array.isArray(existingHooks[ev]) ? existingHooks[ev] : [];
|
|
330
|
+
const keptUser = existingArr.filter((entry) => {
|
|
331
|
+
const ours = isOurEntry(entry, originHost);
|
|
332
|
+
if (ours) replacedMylaHooks++;
|
|
333
|
+
return !ours;
|
|
334
|
+
});
|
|
335
|
+
keptUserHooks += keptUser.length;
|
|
336
|
+
const fetchedArr = Array.isArray(fetchedHooks[ev]) ? fetchedHooks[ev] : [];
|
|
337
|
+
const merged = [...keptUser, ...fetchedArr];
|
|
338
|
+
if (merged.length > 0) mergedHooks[ev] = merged;
|
|
339
|
+
}
|
|
340
|
+
result.hooks = mergedHooks;
|
|
341
|
+
const keptSettings = Object.keys(existing).filter((k) => k !== "hooks").length;
|
|
342
|
+
const text = JSON.stringify(result, null, indent) + (hadTrailingNewline(existingRaw) ? "\n" : "");
|
|
343
|
+
return { text, createdFile: false, keptSettings, keptUserHooks, replacedMylaHooks };
|
|
344
|
+
}
|
|
345
|
+
function removeMylaHooks(opts) {
|
|
346
|
+
const { existingRaw, mylaHookPath } = opts;
|
|
347
|
+
const existing = parseSettings(existingRaw);
|
|
348
|
+
const indent = detectIndent(existingRaw);
|
|
349
|
+
const isMyla = (entry) => JSON.stringify(entry).includes(mylaHookPath);
|
|
350
|
+
if (!isPlainObject(existing.hooks)) return null;
|
|
351
|
+
const hooks = existing.hooks;
|
|
352
|
+
let removed = 0;
|
|
353
|
+
const nextHooks = {};
|
|
354
|
+
for (const ev of Object.keys(hooks)) {
|
|
355
|
+
const arr = Array.isArray(hooks[ev]) ? hooks[ev] : hooks[ev];
|
|
356
|
+
if (!Array.isArray(arr)) {
|
|
357
|
+
nextHooks[ev] = arr;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
const kept = arr.filter((entry) => {
|
|
361
|
+
const myla = isMyla(entry);
|
|
362
|
+
if (myla) removed++;
|
|
363
|
+
return !myla;
|
|
364
|
+
});
|
|
365
|
+
if (kept.length > 0) nextHooks[ev] = kept;
|
|
366
|
+
}
|
|
367
|
+
if (removed === 0) return null;
|
|
368
|
+
const result = { ...existing };
|
|
369
|
+
if (Object.keys(nextHooks).length > 0) result.hooks = nextHooks;
|
|
370
|
+
else delete result.hooks;
|
|
371
|
+
const text = JSON.stringify(result, null, indent) + (hadTrailingNewline(existingRaw) ? "\n" : "");
|
|
372
|
+
return { text, removed };
|
|
373
|
+
}
|
|
374
|
+
function findMylaHooks(raw, mylaHookPath) {
|
|
375
|
+
let existing;
|
|
376
|
+
try {
|
|
377
|
+
existing = parseSettings(raw);
|
|
378
|
+
} catch {
|
|
379
|
+
return { count: 0, hosts: [] };
|
|
380
|
+
}
|
|
381
|
+
if (!isPlainObject(existing.hooks)) return { count: 0, hosts: [] };
|
|
382
|
+
let count = 0;
|
|
383
|
+
const hosts = /* @__PURE__ */ new Set();
|
|
384
|
+
for (const ev of Object.keys(existing.hooks)) {
|
|
385
|
+
const arr = existing.hooks[ev];
|
|
386
|
+
if (!Array.isArray(arr)) continue;
|
|
387
|
+
for (const entry of arr) {
|
|
388
|
+
if (JSON.stringify(entry).includes(mylaHookPath)) {
|
|
389
|
+
count++;
|
|
390
|
+
for (const h of collectHosts(entry)) hosts.add(h);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return { count, hosts: [...hosts] };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// src/output.ts
|
|
398
|
+
function masking(io, token) {
|
|
399
|
+
const m = (s) => maskConfigToken(s, token);
|
|
400
|
+
return { out: (s) => io.out(m(s)), err: (s) => io.err(m(s)) };
|
|
401
|
+
}
|
|
402
|
+
var COL = 38;
|
|
403
|
+
function row(mark, label, value) {
|
|
404
|
+
return ` ${mark} ${label}`.padEnd(COL) + value;
|
|
405
|
+
}
|
|
406
|
+
var WATCHES = {
|
|
407
|
+
"claude-code": [
|
|
408
|
+
" Myla will now see: Bash commands, file writes, file edits,",
|
|
409
|
+
" and MCP tool calls your agent makes."
|
|
410
|
+
],
|
|
411
|
+
cursor: [
|
|
412
|
+
" Myla will now see: shell commands, MCP tool calls, and file",
|
|
413
|
+
" reads your agent makes."
|
|
414
|
+
],
|
|
415
|
+
codex: [
|
|
416
|
+
" Myla will now see: shell commands (and apply_patch) your",
|
|
417
|
+
" agent makes."
|
|
418
|
+
]
|
|
419
|
+
};
|
|
420
|
+
function keptLine(merge) {
|
|
421
|
+
if (merge.createdFile) return "new settings file";
|
|
422
|
+
if (merge.keptSettings === 0) return "your settings were kept";
|
|
423
|
+
const n = merge.keptSettings;
|
|
424
|
+
return `your ${n} existing setting${n === 1 ? "" : "s"} kept`;
|
|
425
|
+
}
|
|
426
|
+
function printInstalled(io, args) {
|
|
427
|
+
const { label, client, file, backupPath, merge } = args;
|
|
428
|
+
io.out("");
|
|
429
|
+
io.out(` Myla Gate \xB7 ${label}`);
|
|
430
|
+
io.out("");
|
|
431
|
+
if (merge.createdFile) {
|
|
432
|
+
io.out(row("\u2713", `Created your ${label} settings`, file));
|
|
433
|
+
} else {
|
|
434
|
+
io.out(row("\u2713", `Found your ${label} settings`, file));
|
|
435
|
+
if (backupPath) io.out(row("\u2713", "Saved a backup first", backupPath));
|
|
436
|
+
}
|
|
437
|
+
io.out(row("\u2713", `Added Myla\u2019s hooks`, keptLine(merge)));
|
|
438
|
+
if (merge.keptUserHooks > 0) {
|
|
439
|
+
io.out(row("\u2713", "Kept your own hooks", `${merge.keptUserHooks} left in place`));
|
|
440
|
+
}
|
|
441
|
+
io.out("");
|
|
442
|
+
for (const line of WATCHES[client] ?? WATCHES["claude-code"]) io.out(line);
|
|
443
|
+
io.out("");
|
|
444
|
+
io.out(" Observe mode \u2014 it records what it would decide. It does not");
|
|
445
|
+
io.out(" stop anything yet.");
|
|
446
|
+
io.out("");
|
|
447
|
+
io.out(` Next: quit ${label} completely and reopen it.`);
|
|
448
|
+
io.out(" Closing the window isn\u2019t enough \u2014 hooks are read once, at startup.");
|
|
449
|
+
io.out("");
|
|
450
|
+
io.out(` Written to ${file}`);
|
|
451
|
+
io.out(" Nothing else on your machine was changed.");
|
|
452
|
+
io.out("");
|
|
453
|
+
}
|
|
454
|
+
function printDryRun(io, args) {
|
|
455
|
+
const { label, file, willCreate, mergedText } = args;
|
|
456
|
+
io.out("");
|
|
457
|
+
io.out(` Myla Gate \xB7 ${label} \xB7 dry run`);
|
|
458
|
+
io.out("");
|
|
459
|
+
io.out(` This is what WOULD be written to ${file}`);
|
|
460
|
+
io.out(willCreate ? " (the file does not exist yet \u2014 it would be created):" : " (merged into your existing settings):");
|
|
461
|
+
io.out("");
|
|
462
|
+
for (const line of mergedText.replace(/\n$/, "").split("\n")) io.out(` ${line}`);
|
|
463
|
+
io.out("");
|
|
464
|
+
io.out(" Nothing was written. Re-run without --dry-run to install.");
|
|
465
|
+
io.out("");
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// src/scan.ts
|
|
469
|
+
import fs2 from "node:fs";
|
|
470
|
+
import path2 from "node:path";
|
|
471
|
+
function clientLayout(client) {
|
|
472
|
+
if (client === "cursor") return { folder: ".cursor", files: ["hooks.json"], managed: ["/Library/Application Support/Cursor/hooks.json", "/etc/cursor/hooks.json", "C:\\ProgramData\\Cursor\\hooks.json"] };
|
|
473
|
+
if (client === "codex") return { folder: ".codex", files: ["hooks.json"], managed: [] };
|
|
474
|
+
return {
|
|
475
|
+
folder: ".claude",
|
|
476
|
+
files: ["settings.json", "settings.local.json"],
|
|
477
|
+
managed: ["/Library/Application Support/ClaudeCode/managed-settings.json", "/etc/claude-code/managed-settings.json", "C:\\ProgramData\\ClaudeCode\\managed-settings.json"]
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
function ancestors(cwd) {
|
|
481
|
+
const out = [];
|
|
482
|
+
let dir = path2.resolve(cwd);
|
|
483
|
+
for (; ; ) {
|
|
484
|
+
out.push(dir);
|
|
485
|
+
const parent = path2.dirname(dir);
|
|
486
|
+
if (parent === dir) break;
|
|
487
|
+
dir = parent;
|
|
488
|
+
}
|
|
489
|
+
return out;
|
|
490
|
+
}
|
|
491
|
+
function scanForOtherMylaHooks(opts) {
|
|
492
|
+
const { client, cwd, perUserAbsolute } = opts;
|
|
493
|
+
const layout = clientLayout(client);
|
|
494
|
+
const perUser = path2.resolve(perUserAbsolute);
|
|
495
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
496
|
+
for (const dir of ancestors(cwd)) {
|
|
497
|
+
for (const f of layout.files) candidates.add(path2.resolve(dir, layout.folder, f));
|
|
498
|
+
}
|
|
499
|
+
for (const m of layout.managed) candidates.add(m);
|
|
500
|
+
const found = [];
|
|
501
|
+
for (const file of candidates) {
|
|
502
|
+
if (path2.resolve(file) === perUser) continue;
|
|
503
|
+
let raw;
|
|
504
|
+
try {
|
|
505
|
+
if (!fs2.existsSync(file)) continue;
|
|
506
|
+
raw = fs2.readFileSync(file, "utf8");
|
|
507
|
+
} catch {
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
const { count, hosts } = findMylaHooks(raw, MYLA_HOOK_PATH);
|
|
511
|
+
if (count > 0) found.push({ path: file, count, hosts });
|
|
512
|
+
}
|
|
513
|
+
return found;
|
|
514
|
+
}
|
|
515
|
+
function describeOtherConfigs(found) {
|
|
516
|
+
if (found.length === 0) return [];
|
|
517
|
+
const lines = [""];
|
|
518
|
+
lines.push(` \u26A0 You have ${found.length === 1 ? "another Myla config" : `${found.length} other Myla configs`} on this machine, outside your per-user file:`);
|
|
519
|
+
for (const f of found) {
|
|
520
|
+
const host = f.hosts.length ? f.hosts.join(", ") : "an unreadable host";
|
|
521
|
+
lines.push(` \u2022 ${f.path}`);
|
|
522
|
+
lines.push(` points at ${host} \u2014 this is a different install and may use a different agent's token.`);
|
|
523
|
+
}
|
|
524
|
+
lines.push(" Claude Code reads these too, so this one keeps firing even after you reinstall the per-user one.");
|
|
525
|
+
lines.push(" Nothing here was changed \u2014 open or delete the file(s) above yourself if they shouldn\u2019t be running.");
|
|
526
|
+
return lines;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// src/install.ts
|
|
530
|
+
var realFetch = async (url) => {
|
|
531
|
+
const res = await fetch(url, { headers: { accept: "application/json" } });
|
|
532
|
+
const body = await res.text();
|
|
533
|
+
return { status: res.status, body };
|
|
534
|
+
};
|
|
535
|
+
async function runInstall(io, opts) {
|
|
536
|
+
const { code, client, origin, dryRun } = opts;
|
|
537
|
+
const fetchClaim = opts.fetchClaim ?? realFetch;
|
|
538
|
+
const inst = hookInstall(client, origin, "PLACEHOLDER");
|
|
539
|
+
const file = opts.filePathOverride ?? resolveUserPath(inst.perUserPath);
|
|
540
|
+
const url = `${origin.replace(/\/+$/, "")}/api/security/gate/claim/${encodeURIComponent(code)}?client=${client}`;
|
|
541
|
+
let res;
|
|
542
|
+
try {
|
|
543
|
+
res = await fetchClaim(url);
|
|
544
|
+
} catch (e) {
|
|
545
|
+
io.err(`Couldn\u2019t reach ${origin} to fetch the install link (${e.message}). Check your connection and the --origin, then try again. Nothing was written.`);
|
|
546
|
+
return 1;
|
|
547
|
+
}
|
|
548
|
+
if (res.status === 410) {
|
|
549
|
+
io.err("This install link has lapsed \u2014 one-time links don\u2019t last forever. That\u2019s expected, not something you did wrong: issue a new agent (or reissue this one) in Myla for a fresh link, then run the new command. Nothing was written.");
|
|
550
|
+
return 1;
|
|
551
|
+
}
|
|
552
|
+
if (res.status === 400) {
|
|
553
|
+
io.err(`The server didn\u2019t accept the request for client "${client}". Nothing was written.`);
|
|
554
|
+
return 1;
|
|
555
|
+
}
|
|
556
|
+
if (res.status !== 200) {
|
|
557
|
+
io.err(`The install link returned HTTP ${res.status}. Nothing was written.`);
|
|
558
|
+
return 1;
|
|
559
|
+
}
|
|
560
|
+
const v = validateClaim(res.body, client, origin);
|
|
561
|
+
if (!v.ok) {
|
|
562
|
+
io.err(`The install link returned something unexpected \u2014 ${v.reason} For safety nothing was written. If this keeps happening, reissue the link in Myla.`);
|
|
563
|
+
return 1;
|
|
564
|
+
}
|
|
565
|
+
const mio = masking(io, v.token);
|
|
566
|
+
let existingRaw = null;
|
|
567
|
+
try {
|
|
568
|
+
existingRaw = fs3.existsSync(file) ? fs3.readFileSync(file, "utf8") : null;
|
|
569
|
+
} catch (e) {
|
|
570
|
+
mio.err(`Couldn\u2019t read ${file} (${e.message}). Nothing was written.`);
|
|
571
|
+
return 1;
|
|
572
|
+
}
|
|
573
|
+
let merge;
|
|
574
|
+
try {
|
|
575
|
+
merge = mergeSettings({ existingRaw, fetchedConfig: v.config, originHost: new URL(origin).host });
|
|
576
|
+
} catch (e) {
|
|
577
|
+
if (e instanceof SettingsParseError) {
|
|
578
|
+
mio.err(`Your ${inst.label} settings file isn\u2019t valid JSON \u2014 the problem is around ${e.where}. It was left exactly as it is; nothing was written and no backup was made. Fix that spot and run this again.`);
|
|
579
|
+
return 1;
|
|
580
|
+
}
|
|
581
|
+
throw e;
|
|
582
|
+
}
|
|
583
|
+
if (dryRun) {
|
|
584
|
+
printDryRun(mio, { label: inst.label, file, willCreate: merge.createdFile, mergedText: merge.text });
|
|
585
|
+
return 0;
|
|
586
|
+
}
|
|
587
|
+
if (existingRaw !== null) {
|
|
588
|
+
try {
|
|
589
|
+
fs3.accessSync(file, fs3.constants.W_OK);
|
|
590
|
+
} catch {
|
|
591
|
+
mio.err(`${file} is read-only, so it was left untouched. Make it writable (chmod +w) and run this again, or install by hand. Nothing was written.`);
|
|
592
|
+
return 1;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
let backupPath;
|
|
596
|
+
if (existingRaw !== null) {
|
|
597
|
+
backupPath = nextBackupPath(file);
|
|
598
|
+
try {
|
|
599
|
+
fs3.copyFileSync(file, backupPath);
|
|
600
|
+
} catch (e) {
|
|
601
|
+
mio.err(`Couldn\u2019t write a backup next to ${file} (${e.message}), so nothing was changed. The original is exactly as it was.`);
|
|
602
|
+
return 1;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
const dir = path3.dirname(file);
|
|
606
|
+
try {
|
|
607
|
+
fs3.mkdirSync(dir, { recursive: true });
|
|
608
|
+
} catch (e) {
|
|
609
|
+
mio.err(`Couldn\u2019t create the folder ${dir} (${e.message}). Nothing was written.`);
|
|
610
|
+
return 1;
|
|
611
|
+
}
|
|
612
|
+
const tmp = path3.join(dir, `.gate-install-${process.pid}-${Date.now()}.tmp`);
|
|
613
|
+
try {
|
|
614
|
+
fs3.writeFileSync(tmp, merge.text, { encoding: "utf8", mode: 384 });
|
|
615
|
+
fs3.renameSync(tmp, file);
|
|
616
|
+
} catch (e) {
|
|
617
|
+
try {
|
|
618
|
+
if (fs3.existsSync(tmp)) fs3.unlinkSync(tmp);
|
|
619
|
+
} catch {
|
|
620
|
+
}
|
|
621
|
+
mio.err(`Couldn\u2019t write ${file} (${e.message}). Your original file is unchanged${backupPath ? ` and a backup is at ${backupPath}` : ""}. Nothing was lost.`);
|
|
622
|
+
return 1;
|
|
623
|
+
}
|
|
624
|
+
printInstalled(mio, { label: inst.label, client, file, backupPath, merge });
|
|
625
|
+
const others = scanForOtherMylaHooks({ client, cwd: opts.cwd ?? process.cwd(), perUserAbsolute: file });
|
|
626
|
+
for (const line of describeOtherConfigs(others)) mio.out(line);
|
|
627
|
+
return 0;
|
|
628
|
+
}
|
|
629
|
+
function homeShorten(file) {
|
|
630
|
+
const home = os2.homedir();
|
|
631
|
+
return file.startsWith(home) ? "~" + file.slice(home.length) : file;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// src/doctor.ts
|
|
635
|
+
import fs4 from "node:fs";
|
|
636
|
+
var realVerify = async (url, token) => {
|
|
637
|
+
const res = await fetch(url, {
|
|
638
|
+
method: "POST",
|
|
639
|
+
headers: { Authorization: `Bearer ${token}`, "content-type": "application/json" }
|
|
640
|
+
});
|
|
641
|
+
return { status: res.status, body: await res.text() };
|
|
642
|
+
};
|
|
643
|
+
var TOKEN_RE = /^[A-Za-z0-9_-]{32,128}$/;
|
|
644
|
+
async function runDoctor(io, opts) {
|
|
645
|
+
const inst = hookInstall(opts.client, opts.origin, "PLACEHOLDER");
|
|
646
|
+
const file = opts.filePathOverride ?? resolveUserPath(inst.perUserPath);
|
|
647
|
+
const shown = homeShorten(file);
|
|
648
|
+
const verifyFetch = opts.verifyFetch ?? realVerify;
|
|
649
|
+
io.out("");
|
|
650
|
+
io.out(` Myla Gate \xB7 ${inst.label} \xB7 doctor`);
|
|
651
|
+
io.out("");
|
|
652
|
+
if (!fs4.existsSync(file)) {
|
|
653
|
+
io.out(row2("\u2022", "Settings file", `${shown} \u2014 not found`));
|
|
654
|
+
io.out("");
|
|
655
|
+
io.out(` No ${inst.label} settings file exists yet, so no Myla hook is installed.`);
|
|
656
|
+
io.out(" Run the install command to create it.");
|
|
657
|
+
io.out("");
|
|
658
|
+
return 0;
|
|
659
|
+
}
|
|
660
|
+
let raw;
|
|
661
|
+
try {
|
|
662
|
+
raw = fs4.readFileSync(file, "utf8");
|
|
663
|
+
} catch (e) {
|
|
664
|
+
io.err(` Couldn\u2019t read ${shown} (${e.message}).`);
|
|
665
|
+
return 1;
|
|
666
|
+
}
|
|
667
|
+
const { count, hosts } = findMylaHooks(raw, MYLA_HOOK_PATH);
|
|
668
|
+
io.out(row2("\u2022", "Settings file", shown));
|
|
669
|
+
if (count === 0) {
|
|
670
|
+
io.out(row2("\u2022", "Myla hook", "not installed"));
|
|
671
|
+
io.out("");
|
|
672
|
+
io.out(" The file exists but has no Myla hook. Run the install command to add it.");
|
|
673
|
+
io.out("");
|
|
674
|
+
return 0;
|
|
675
|
+
}
|
|
676
|
+
io.out(row2("\u2713", "Myla hook", `installed (${count} ${count === 1 ? "entry" : "entries"})`));
|
|
677
|
+
io.out(row2("\u2022", "Points at", hosts.length ? hosts.join(", ") : "an unreadable host"));
|
|
678
|
+
const others = scanForOtherMylaHooks({ client: opts.client, cwd: opts.cwd ?? process.cwd(), perUserAbsolute: file });
|
|
679
|
+
for (const line of describeOtherConfigs(others)) io.out(line);
|
|
680
|
+
const m = raw.match(/Bearer\s+([^\s"'\\]+)/);
|
|
681
|
+
const token = m ? m[1] : "";
|
|
682
|
+
if (!token || !TOKEN_RE.test(token)) {
|
|
683
|
+
io.out(row2("\u2717", "Gate check", "the token in this config is not a real token"));
|
|
684
|
+
io.out("");
|
|
685
|
+
io.out(" The hook is here, but the credential in it isn\u2019t a usable token \u2014 most often the masked");
|
|
686
|
+
io.out(" preview (the row of dots) was copied off the screen instead of the real one. Re-run the");
|
|
687
|
+
io.out(" install command (it writes the real token), or use COPY CONFIG on the install sheet.");
|
|
688
|
+
io.out("");
|
|
689
|
+
return 1;
|
|
690
|
+
}
|
|
691
|
+
const verifyUrl = `${opts.origin.replace(/\/+$/, "")}/api/security/gate/verify`;
|
|
692
|
+
let res;
|
|
693
|
+
try {
|
|
694
|
+
res = await verifyFetch(verifyUrl, token);
|
|
695
|
+
} catch (e) {
|
|
696
|
+
io.out(row2("\u2022", "Gate check", "couldn\u2019t reach the Gate"));
|
|
697
|
+
io.out("");
|
|
698
|
+
io.out(` The hook is written, but I couldn\u2019t reach ${opts.origin} to confirm it (${e.message}).`);
|
|
699
|
+
io.out(" Check your connection and the --origin, then run doctor again.");
|
|
700
|
+
io.out("");
|
|
701
|
+
return 1;
|
|
702
|
+
}
|
|
703
|
+
let d;
|
|
704
|
+
try {
|
|
705
|
+
d = JSON.parse(res.body);
|
|
706
|
+
} catch {
|
|
707
|
+
d = null;
|
|
708
|
+
}
|
|
709
|
+
if (res.status !== 200 || !d) {
|
|
710
|
+
io.out(row2("\u2022", "Gate check", "couldn\u2019t check"));
|
|
711
|
+
io.out("");
|
|
712
|
+
io.out(` The Gate answered unexpectedly (HTTP ${res.status}). The hook is written; try doctor again in a moment.`);
|
|
713
|
+
io.out("");
|
|
714
|
+
return 1;
|
|
715
|
+
}
|
|
716
|
+
if (d.recognized === true) {
|
|
717
|
+
io.out(row2("\u2713", "Gate check", d.agent?.name ? `recognised as \u201C${d.agent.name}\u201D` : "recognised"));
|
|
718
|
+
if (d.gateEnabled === false) {
|
|
719
|
+
io.out(row2("\u2022", "Gate status", "switched off on this deployment"));
|
|
720
|
+
}
|
|
721
|
+
io.out("");
|
|
722
|
+
if (typeof d.lastSeenAt === "string") {
|
|
723
|
+
io.out(" Recognised, and the Gate has heard from this agent \u2014 you\u2019re being watched.");
|
|
724
|
+
} else if (d.lastSeenAt === null) {
|
|
725
|
+
io.out(" The token is recognised, but no call has reached the Gate yet. Fully quit and reopen");
|
|
726
|
+
io.out(` ${inst.label} (closing the window isn\u2019t enough \u2014 hooks load at startup), then use it once.`);
|
|
727
|
+
} else {
|
|
728
|
+
io.out(" The token is recognised. (Couldn\u2019t read recent activity just now.)");
|
|
729
|
+
}
|
|
730
|
+
io.out("");
|
|
731
|
+
return 0;
|
|
732
|
+
}
|
|
733
|
+
if (d.recognized === false) {
|
|
734
|
+
io.out(row2("\u2717", "Gate check", "NOT recognised"));
|
|
735
|
+
io.out("");
|
|
736
|
+
io.out(" The hook is installed and calls to the Gate return 200 \u2014 but the Gate does NOT recognise");
|
|
737
|
+
io.out(" this token, so nothing is being recorded. The usual cause is that the agent was reissued");
|
|
738
|
+
io.out(" or revoked, which rotates the token and leaves this config pointing at a dead one.");
|
|
739
|
+
io.out(" Reissue the agent in Myla if needed, then re-run the install command to write the new token.");
|
|
740
|
+
io.out("");
|
|
741
|
+
return 1;
|
|
742
|
+
}
|
|
743
|
+
io.out(row2("\u2022", "Gate check", "couldn\u2019t check"));
|
|
744
|
+
io.out("");
|
|
745
|
+
io.out(" Couldn\u2019t confirm the token just now \u2014 that\u2019s a Myla hiccup, not a sign your setup is wrong.");
|
|
746
|
+
io.out(" Try doctor again in a moment.");
|
|
747
|
+
io.out("");
|
|
748
|
+
return 0;
|
|
749
|
+
}
|
|
750
|
+
var COL2 = 38;
|
|
751
|
+
function row2(mark, label, value) {
|
|
752
|
+
return ` ${mark} ${label}`.padEnd(COL2) + value;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// src/uninstall.ts
|
|
756
|
+
import fs5 from "node:fs";
|
|
757
|
+
import path4 from "node:path";
|
|
758
|
+
function runUninstall(io, opts) {
|
|
759
|
+
const inst = hookInstall(opts.client, opts.origin, "PLACEHOLDER");
|
|
760
|
+
const file = opts.filePathOverride ?? resolveUserPath(inst.perUserPath);
|
|
761
|
+
const shown = homeShorten(file);
|
|
762
|
+
if (!fs5.existsSync(file)) {
|
|
763
|
+
io.out(`No ${inst.label} settings file at ${shown}, so there\u2019s no Myla hook to remove. Nothing was changed.`);
|
|
764
|
+
return 0;
|
|
765
|
+
}
|
|
766
|
+
let raw;
|
|
767
|
+
try {
|
|
768
|
+
raw = fs5.readFileSync(file, "utf8");
|
|
769
|
+
} catch (e) {
|
|
770
|
+
io.err(`Couldn\u2019t read ${shown} (${e.message}). Nothing was changed.`);
|
|
771
|
+
return 1;
|
|
772
|
+
}
|
|
773
|
+
let result;
|
|
774
|
+
try {
|
|
775
|
+
result = removeMylaHooks({ existingRaw: raw, mylaHookPath: MYLA_HOOK_PATH });
|
|
776
|
+
} catch (e) {
|
|
777
|
+
if (e instanceof SettingsParseError) {
|
|
778
|
+
io.err(`Your ${inst.label} settings file isn\u2019t valid JSON \u2014 the problem is around ${e.where}. It was left exactly as it is; nothing was removed. Fix that spot first.`);
|
|
779
|
+
return 1;
|
|
780
|
+
}
|
|
781
|
+
throw e;
|
|
782
|
+
}
|
|
783
|
+
if (!result) {
|
|
784
|
+
io.out(`No Myla hook found in ${shown}. Nothing was changed.`);
|
|
785
|
+
return 0;
|
|
786
|
+
}
|
|
787
|
+
if (opts.dryRun) {
|
|
788
|
+
io.out(`Would remove ${result.removed} Myla hook ${result.removed === 1 ? "entry" : "entries"} from ${shown} and keep everything else. Nothing was written (dry run).`);
|
|
789
|
+
return 0;
|
|
790
|
+
}
|
|
791
|
+
if (existingWritableRefused(io, file, shown)) return 1;
|
|
792
|
+
const backupPath = nextBackupPath(file);
|
|
793
|
+
try {
|
|
794
|
+
fs5.copyFileSync(file, backupPath);
|
|
795
|
+
} catch (e) {
|
|
796
|
+
io.err(`Couldn\u2019t write a backup next to ${shown} (${e.message}), so nothing was changed.`);
|
|
797
|
+
return 1;
|
|
798
|
+
}
|
|
799
|
+
const tmp = path4.join(path4.dirname(file), `.gate-uninstall-${process.pid}-${Date.now()}.tmp`);
|
|
800
|
+
try {
|
|
801
|
+
fs5.writeFileSync(tmp, result.text, { encoding: "utf8", mode: 384 });
|
|
802
|
+
fs5.renameSync(tmp, file);
|
|
803
|
+
} catch (e) {
|
|
804
|
+
try {
|
|
805
|
+
if (fs5.existsSync(tmp)) fs5.unlinkSync(tmp);
|
|
806
|
+
} catch {
|
|
807
|
+
}
|
|
808
|
+
io.err(`Couldn\u2019t write ${shown} (${e.message}). Your original file is unchanged and a backup is at ${homeShorten(backupPath)}.`);
|
|
809
|
+
return 1;
|
|
810
|
+
}
|
|
811
|
+
io.out(`Removed ${result.removed} Myla hook ${result.removed === 1 ? "entry" : "entries"} from ${shown}; everything else is kept. Backup saved to ${homeShorten(backupPath)}.`);
|
|
812
|
+
io.out(`Quit ${inst.label} completely and reopen it for the change to take effect.`);
|
|
813
|
+
return 0;
|
|
814
|
+
}
|
|
815
|
+
function existingWritableRefused(io, file, shown) {
|
|
816
|
+
try {
|
|
817
|
+
fs5.accessSync(file, fs5.constants.W_OK);
|
|
818
|
+
return false;
|
|
819
|
+
} catch {
|
|
820
|
+
io.err(`${shown} is read-only, so it was left untouched. Make it writable (chmod +w) and run this again. Nothing was changed.`);
|
|
821
|
+
return true;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// src/cli.ts
|
|
826
|
+
var realIo = {
|
|
827
|
+
out: (s) => process.stdout.write(s + "\n"),
|
|
828
|
+
err: (s) => process.stderr.write(s + "\n")
|
|
829
|
+
};
|
|
830
|
+
function parseArgs(argv) {
|
|
831
|
+
const out = {
|
|
832
|
+
command: "",
|
|
833
|
+
positionals: [],
|
|
834
|
+
client: "claude-code",
|
|
835
|
+
origin: DEFAULT_ORIGIN,
|
|
836
|
+
dryRun: false,
|
|
837
|
+
help: false
|
|
838
|
+
};
|
|
839
|
+
let clientSeen;
|
|
840
|
+
for (let i = 0; i < argv.length; i++) {
|
|
841
|
+
const a = argv[i];
|
|
842
|
+
if (a === "--help" || a === "-h") {
|
|
843
|
+
out.help = true;
|
|
844
|
+
continue;
|
|
845
|
+
}
|
|
846
|
+
if (a === "--dry-run") {
|
|
847
|
+
out.dryRun = true;
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
if (a === "--client" || a.startsWith("--client=")) {
|
|
851
|
+
const val = a.includes("=") ? a.slice("--client=".length) : argv[++i];
|
|
852
|
+
clientSeen = val;
|
|
853
|
+
continue;
|
|
854
|
+
}
|
|
855
|
+
if (a === "--origin" || a.startsWith("--origin=")) {
|
|
856
|
+
const val = a.includes("=") ? a.slice("--origin=".length) : argv[++i];
|
|
857
|
+
if (val) out.origin = val.replace(/\/+$/, "");
|
|
858
|
+
continue;
|
|
859
|
+
}
|
|
860
|
+
if (a.startsWith("-")) {
|
|
861
|
+
out.error = `Unknown flag: ${a}`;
|
|
862
|
+
continue;
|
|
863
|
+
}
|
|
864
|
+
if (!out.command) out.command = a;
|
|
865
|
+
else out.positionals.push(a);
|
|
866
|
+
}
|
|
867
|
+
if (clientSeen !== void 0) {
|
|
868
|
+
if (!HOOK_CLIENTS.includes(clientSeen)) {
|
|
869
|
+
out.error = `--client must be one of ${HOOK_CLIENTS.join(", ")} (got "${clientSeen}")`;
|
|
870
|
+
} else {
|
|
871
|
+
out.client = clientSeen;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return out;
|
|
875
|
+
}
|
|
876
|
+
var HELP = `Myla Gate installer
|
|
877
|
+
|
|
878
|
+
Puts the Myla Gate in front of your coding agent by merging its hooks into your
|
|
879
|
+
per-user settings file. It backs up first, prints exactly what it changed, and
|
|
880
|
+
touches nothing else.
|
|
881
|
+
|
|
882
|
+
Usage
|
|
883
|
+
npx @mylasecurity/gate install <claim-code> Install (the whole job)
|
|
884
|
+
npx @mylasecurity/gate install <claim-code> --dry-run Show what would be written, write nothing
|
|
885
|
+
npx @mylasecurity/gate doctor Is a Myla hook installed? (no network, no writes)
|
|
886
|
+
npx @mylasecurity/gate uninstall Remove only Myla's hooks, back up first
|
|
887
|
+
|
|
888
|
+
Options
|
|
889
|
+
--client claude-code|cursor|codex Which agent (default: claude-code)
|
|
890
|
+
--origin <url> Which Myla deployment (default: the production host)
|
|
891
|
+
--dry-run install/uninstall: don't write, just show
|
|
892
|
+
-h, --help This help
|
|
893
|
+
|
|
894
|
+
The claim code comes from Myla when you add an agent. One-time links expire; if yours
|
|
895
|
+
has lapsed, reissuing is free \u2014 just get a fresh command.`;
|
|
896
|
+
async function main(argv, io = realIo) {
|
|
897
|
+
const nodeMajor = Number(process.versions.node.split(".")[0]);
|
|
898
|
+
if (Number.isFinite(nodeMajor) && nodeMajor < MIN_NODE_MAJOR) {
|
|
899
|
+
io.err(`This installer needs Node ${MIN_NODE_MAJOR} or newer (it uses the built-in fetch). You\u2019re on Node ${process.versions.node}. Install a newer Node and run it again.`);
|
|
900
|
+
return 1;
|
|
901
|
+
}
|
|
902
|
+
const p = parseArgs(argv);
|
|
903
|
+
if (p.help || p.command === "" || p.command === "help") {
|
|
904
|
+
io.out(HELP);
|
|
905
|
+
return p.error ? 1 : 0;
|
|
906
|
+
}
|
|
907
|
+
if (p.error) {
|
|
908
|
+
io.err(p.error);
|
|
909
|
+
return 1;
|
|
910
|
+
}
|
|
911
|
+
switch (p.command) {
|
|
912
|
+
case "install": {
|
|
913
|
+
const code = p.positionals[0];
|
|
914
|
+
if (!code) {
|
|
915
|
+
io.err("Usage: npx @mylasecurity/gate install <claim-code> (the code comes from Myla when you add an agent)");
|
|
916
|
+
return 1;
|
|
917
|
+
}
|
|
918
|
+
return runInstall(io, { code, client: p.client, origin: p.origin, dryRun: p.dryRun });
|
|
919
|
+
}
|
|
920
|
+
case "doctor":
|
|
921
|
+
return runDoctor(io, { client: p.client, origin: p.origin });
|
|
922
|
+
case "uninstall":
|
|
923
|
+
return runUninstall(io, { client: p.client, origin: p.origin, dryRun: p.dryRun });
|
|
924
|
+
default:
|
|
925
|
+
io.err(`Unknown command "${p.command}". Run with --help to see the commands.`);
|
|
926
|
+
return 1;
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
var isDirectRun = (() => {
|
|
930
|
+
const invoked = process.argv[1] ?? "";
|
|
931
|
+
return /gate(\.mjs|\.ts|\.js)?$/.test(invoked) || invoked.endsWith("cli.ts");
|
|
932
|
+
})();
|
|
933
|
+
if (isDirectRun) {
|
|
934
|
+
main(process.argv.slice(2)).then((code) => {
|
|
935
|
+
process.exitCode = code;
|
|
936
|
+
}).catch((err) => {
|
|
937
|
+
process.stderr.write(`Unexpected error: ${err.message}
|
|
938
|
+
`);
|
|
939
|
+
process.exitCode = 1;
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
export {
|
|
943
|
+
main,
|
|
944
|
+
parseArgs
|
|
945
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mylasecurity/gate",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "One command to put the Myla Gate in front of your coding agent — fetches a one-time claim, merges the hooks into your per-user settings, backs up first, prints exactly what it changed.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"gate": "bin/gate.mjs"
|
|
9
|
+
},
|
|
10
|
+
"engines": {
|
|
11
|
+
"node": ">=18"
|
|
12
|
+
},
|
|
13
|
+
"scripts": {
|
|
14
|
+
"build": "npx --yes esbuild src/cli.ts --bundle --platform=node --format=esm --target=node18 --tsconfig=../../tsconfig.json --banner:js=\"#!/usr/bin/env node\" --outfile=bin/gate.mjs",
|
|
15
|
+
"prepublishOnly": "npm run build"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"bin/gate.mjs"
|
|
19
|
+
],
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
}
|
|
23
|
+
}
|