@mylasecurity/gate 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +62 -2
  2. package/bin/gate.mjs +808 -0
  3. package/package.json +21 -4
package/README.md CHANGED
@@ -1,3 +1,63 @@
1
- # Temporary Holding Version
1
+ # @mylasecurity/gate
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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,808 @@
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, path4, fallback, version) => `curl -sS -f --max-time 10 -X POST ${origin}${path4} -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 = (path4, timeout) => [{
94
+ type: "http",
95
+ url: `${origin}${path4}`,
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 fs2 from "node:fs";
164
+ import path2 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/install.ts
469
+ var realFetch = async (url) => {
470
+ const res = await fetch(url, { headers: { accept: "application/json" } });
471
+ const body = await res.text();
472
+ return { status: res.status, body };
473
+ };
474
+ async function runInstall(io, opts) {
475
+ const { code, client, origin, dryRun } = opts;
476
+ const fetchClaim = opts.fetchClaim ?? realFetch;
477
+ const inst = hookInstall(client, origin, "PLACEHOLDER");
478
+ const file = opts.filePathOverride ?? resolveUserPath(inst.perUserPath);
479
+ const url = `${origin.replace(/\/+$/, "")}/api/security/gate/claim/${encodeURIComponent(code)}?client=${client}`;
480
+ let res;
481
+ try {
482
+ res = await fetchClaim(url);
483
+ } catch (e) {
484
+ 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.`);
485
+ return 1;
486
+ }
487
+ if (res.status === 410) {
488
+ 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.");
489
+ return 1;
490
+ }
491
+ if (res.status === 400) {
492
+ io.err(`The server didn\u2019t accept the request for client "${client}". Nothing was written.`);
493
+ return 1;
494
+ }
495
+ if (res.status !== 200) {
496
+ io.err(`The install link returned HTTP ${res.status}. Nothing was written.`);
497
+ return 1;
498
+ }
499
+ const v = validateClaim(res.body, client, origin);
500
+ if (!v.ok) {
501
+ 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.`);
502
+ return 1;
503
+ }
504
+ const mio = masking(io, v.token);
505
+ let existingRaw = null;
506
+ try {
507
+ existingRaw = fs2.existsSync(file) ? fs2.readFileSync(file, "utf8") : null;
508
+ } catch (e) {
509
+ mio.err(`Couldn\u2019t read ${file} (${e.message}). Nothing was written.`);
510
+ return 1;
511
+ }
512
+ let merge;
513
+ try {
514
+ merge = mergeSettings({ existingRaw, fetchedConfig: v.config, originHost: new URL(origin).host });
515
+ } catch (e) {
516
+ if (e instanceof SettingsParseError) {
517
+ 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.`);
518
+ return 1;
519
+ }
520
+ throw e;
521
+ }
522
+ if (dryRun) {
523
+ printDryRun(mio, { label: inst.label, file, willCreate: merge.createdFile, mergedText: merge.text });
524
+ return 0;
525
+ }
526
+ if (existingRaw !== null) {
527
+ try {
528
+ fs2.accessSync(file, fs2.constants.W_OK);
529
+ } catch {
530
+ 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.`);
531
+ return 1;
532
+ }
533
+ }
534
+ let backupPath;
535
+ if (existingRaw !== null) {
536
+ backupPath = nextBackupPath(file);
537
+ try {
538
+ fs2.copyFileSync(file, backupPath);
539
+ } catch (e) {
540
+ mio.err(`Couldn\u2019t write a backup next to ${file} (${e.message}), so nothing was changed. The original is exactly as it was.`);
541
+ return 1;
542
+ }
543
+ }
544
+ const dir = path2.dirname(file);
545
+ try {
546
+ fs2.mkdirSync(dir, { recursive: true });
547
+ } catch (e) {
548
+ mio.err(`Couldn\u2019t create the folder ${dir} (${e.message}). Nothing was written.`);
549
+ return 1;
550
+ }
551
+ const tmp = path2.join(dir, `.gate-install-${process.pid}-${Date.now()}.tmp`);
552
+ try {
553
+ fs2.writeFileSync(tmp, merge.text, { encoding: "utf8", mode: 384 });
554
+ fs2.renameSync(tmp, file);
555
+ } catch (e) {
556
+ try {
557
+ if (fs2.existsSync(tmp)) fs2.unlinkSync(tmp);
558
+ } catch {
559
+ }
560
+ mio.err(`Couldn\u2019t write ${file} (${e.message}). Your original file is unchanged${backupPath ? ` and a backup is at ${backupPath}` : ""}. Nothing was lost.`);
561
+ return 1;
562
+ }
563
+ printInstalled(mio, { label: inst.label, client, file, backupPath, merge });
564
+ return 0;
565
+ }
566
+ function homeShorten(file) {
567
+ const home = os2.homedir();
568
+ return file.startsWith(home) ? "~" + file.slice(home.length) : file;
569
+ }
570
+
571
+ // src/doctor.ts
572
+ import fs3 from "node:fs";
573
+ function runDoctor(io, opts) {
574
+ const inst = hookInstall(opts.client, opts.origin, "PLACEHOLDER");
575
+ const file = opts.filePathOverride ?? resolveUserPath(inst.perUserPath);
576
+ const shown = homeShorten(file);
577
+ io.out("");
578
+ io.out(` Myla Gate \xB7 ${inst.label} \xB7 doctor`);
579
+ io.out("");
580
+ if (!fs3.existsSync(file)) {
581
+ io.out(row2("\u2022", "Settings file", `${shown} \u2014 not found`));
582
+ io.out("");
583
+ io.out(` No ${inst.label} settings file exists yet, so no Myla hook is installed.`);
584
+ io.out(" Run the install command to create it.");
585
+ io.out("");
586
+ return 0;
587
+ }
588
+ let raw;
589
+ try {
590
+ raw = fs3.readFileSync(file, "utf8");
591
+ } catch (e) {
592
+ io.err(` Couldn\u2019t read ${shown} (${e.message}).`);
593
+ return 1;
594
+ }
595
+ const { count, hosts } = findMylaHooks(raw, MYLA_HOOK_PATH);
596
+ io.out(row2("\u2022", "Settings file", shown));
597
+ if (count === 0) {
598
+ io.out(row2("\u2022", "Myla hook", "not installed"));
599
+ io.out("");
600
+ io.out(" The file exists but has no Myla hook. Run the install command to add it.");
601
+ io.out("");
602
+ return 0;
603
+ }
604
+ io.out(row2("\u2713", "Myla hook", `installed (${count} ${count === 1 ? "entry" : "entries"})`));
605
+ io.out(row2("\u2022", "Points at", hosts.length ? hosts.join(", ") : "an unreadable host"));
606
+ io.out("");
607
+ io.out(` The hook is written into your settings. If you haven\u2019t fully quit and reopened`);
608
+ io.out(` ${inst.label} since installing, do that now \u2014 hooks are read once, at startup.`);
609
+ io.out(" Whether a call has actually reached the Gate shows on the agent\u2019s row in Myla.");
610
+ io.out("");
611
+ return 0;
612
+ }
613
+ var COL2 = 38;
614
+ function row2(mark, label, value) {
615
+ return ` ${mark} ${label}`.padEnd(COL2) + value;
616
+ }
617
+
618
+ // src/uninstall.ts
619
+ import fs4 from "node:fs";
620
+ import path3 from "node:path";
621
+ function runUninstall(io, opts) {
622
+ const inst = hookInstall(opts.client, opts.origin, "PLACEHOLDER");
623
+ const file = opts.filePathOverride ?? resolveUserPath(inst.perUserPath);
624
+ const shown = homeShorten(file);
625
+ if (!fs4.existsSync(file)) {
626
+ io.out(`No ${inst.label} settings file at ${shown}, so there\u2019s no Myla hook to remove. Nothing was changed.`);
627
+ return 0;
628
+ }
629
+ let raw;
630
+ try {
631
+ raw = fs4.readFileSync(file, "utf8");
632
+ } catch (e) {
633
+ io.err(`Couldn\u2019t read ${shown} (${e.message}). Nothing was changed.`);
634
+ return 1;
635
+ }
636
+ let result;
637
+ try {
638
+ result = removeMylaHooks({ existingRaw: raw, mylaHookPath: MYLA_HOOK_PATH });
639
+ } catch (e) {
640
+ if (e instanceof SettingsParseError) {
641
+ 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.`);
642
+ return 1;
643
+ }
644
+ throw e;
645
+ }
646
+ if (!result) {
647
+ io.out(`No Myla hook found in ${shown}. Nothing was changed.`);
648
+ return 0;
649
+ }
650
+ if (opts.dryRun) {
651
+ io.out(`Would remove ${result.removed} Myla hook ${result.removed === 1 ? "entry" : "entries"} from ${shown} and keep everything else. Nothing was written (dry run).`);
652
+ return 0;
653
+ }
654
+ if (existingWritableRefused(io, file, shown)) return 1;
655
+ const backupPath = nextBackupPath(file);
656
+ try {
657
+ fs4.copyFileSync(file, backupPath);
658
+ } catch (e) {
659
+ io.err(`Couldn\u2019t write a backup next to ${shown} (${e.message}), so nothing was changed.`);
660
+ return 1;
661
+ }
662
+ const tmp = path3.join(path3.dirname(file), `.gate-uninstall-${process.pid}-${Date.now()}.tmp`);
663
+ try {
664
+ fs4.writeFileSync(tmp, result.text, { encoding: "utf8", mode: 384 });
665
+ fs4.renameSync(tmp, file);
666
+ } catch (e) {
667
+ try {
668
+ if (fs4.existsSync(tmp)) fs4.unlinkSync(tmp);
669
+ } catch {
670
+ }
671
+ io.err(`Couldn\u2019t write ${shown} (${e.message}). Your original file is unchanged and a backup is at ${homeShorten(backupPath)}.`);
672
+ return 1;
673
+ }
674
+ io.out(`Removed ${result.removed} Myla hook ${result.removed === 1 ? "entry" : "entries"} from ${shown}; everything else is kept. Backup saved to ${homeShorten(backupPath)}.`);
675
+ io.out(`Quit ${inst.label} completely and reopen it for the change to take effect.`);
676
+ return 0;
677
+ }
678
+ function existingWritableRefused(io, file, shown) {
679
+ try {
680
+ fs4.accessSync(file, fs4.constants.W_OK);
681
+ return false;
682
+ } catch {
683
+ io.err(`${shown} is read-only, so it was left untouched. Make it writable (chmod +w) and run this again. Nothing was changed.`);
684
+ return true;
685
+ }
686
+ }
687
+
688
+ // src/cli.ts
689
+ var realIo = {
690
+ out: (s) => process.stdout.write(s + "\n"),
691
+ err: (s) => process.stderr.write(s + "\n")
692
+ };
693
+ function parseArgs(argv) {
694
+ const out = {
695
+ command: "",
696
+ positionals: [],
697
+ client: "claude-code",
698
+ origin: DEFAULT_ORIGIN,
699
+ dryRun: false,
700
+ help: false
701
+ };
702
+ let clientSeen;
703
+ for (let i = 0; i < argv.length; i++) {
704
+ const a = argv[i];
705
+ if (a === "--help" || a === "-h") {
706
+ out.help = true;
707
+ continue;
708
+ }
709
+ if (a === "--dry-run") {
710
+ out.dryRun = true;
711
+ continue;
712
+ }
713
+ if (a === "--client" || a.startsWith("--client=")) {
714
+ const val = a.includes("=") ? a.slice("--client=".length) : argv[++i];
715
+ clientSeen = val;
716
+ continue;
717
+ }
718
+ if (a === "--origin" || a.startsWith("--origin=")) {
719
+ const val = a.includes("=") ? a.slice("--origin=".length) : argv[++i];
720
+ if (val) out.origin = val.replace(/\/+$/, "");
721
+ continue;
722
+ }
723
+ if (a.startsWith("-")) {
724
+ out.error = `Unknown flag: ${a}`;
725
+ continue;
726
+ }
727
+ if (!out.command) out.command = a;
728
+ else out.positionals.push(a);
729
+ }
730
+ if (clientSeen !== void 0) {
731
+ if (!HOOK_CLIENTS.includes(clientSeen)) {
732
+ out.error = `--client must be one of ${HOOK_CLIENTS.join(", ")} (got "${clientSeen}")`;
733
+ } else {
734
+ out.client = clientSeen;
735
+ }
736
+ }
737
+ return out;
738
+ }
739
+ var HELP = `Myla Gate installer
740
+
741
+ Puts the Myla Gate in front of your coding agent by merging its hooks into your
742
+ per-user settings file. It backs up first, prints exactly what it changed, and
743
+ touches nothing else.
744
+
745
+ Usage
746
+ npx @mylasecurity/gate install <claim-code> Install (the whole job)
747
+ npx @mylasecurity/gate install <claim-code> --dry-run Show what would be written, write nothing
748
+ npx @mylasecurity/gate doctor Is a Myla hook installed? (no network, no writes)
749
+ npx @mylasecurity/gate uninstall Remove only Myla's hooks, back up first
750
+
751
+ Options
752
+ --client claude-code|cursor|codex Which agent (default: claude-code)
753
+ --origin <url> Which Myla deployment (default: the production host)
754
+ --dry-run install/uninstall: don't write, just show
755
+ -h, --help This help
756
+
757
+ The claim code comes from Myla when you add an agent. One-time links expire; if yours
758
+ has lapsed, reissuing is free \u2014 just get a fresh command.`;
759
+ async function main(argv, io = realIo) {
760
+ const nodeMajor = Number(process.versions.node.split(".")[0]);
761
+ if (Number.isFinite(nodeMajor) && nodeMajor < MIN_NODE_MAJOR) {
762
+ 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.`);
763
+ return 1;
764
+ }
765
+ const p = parseArgs(argv);
766
+ if (p.help || p.command === "" || p.command === "help") {
767
+ io.out(HELP);
768
+ return p.error ? 1 : 0;
769
+ }
770
+ if (p.error) {
771
+ io.err(p.error);
772
+ return 1;
773
+ }
774
+ switch (p.command) {
775
+ case "install": {
776
+ const code = p.positionals[0];
777
+ if (!code) {
778
+ io.err("Usage: npx @mylasecurity/gate install <claim-code> (the code comes from Myla when you add an agent)");
779
+ return 1;
780
+ }
781
+ return runInstall(io, { code, client: p.client, origin: p.origin, dryRun: p.dryRun });
782
+ }
783
+ case "doctor":
784
+ return runDoctor(io, { client: p.client, origin: p.origin });
785
+ case "uninstall":
786
+ return runUninstall(io, { client: p.client, origin: p.origin, dryRun: p.dryRun });
787
+ default:
788
+ io.err(`Unknown command "${p.command}". Run with --help to see the commands.`);
789
+ return 1;
790
+ }
791
+ }
792
+ var isDirectRun = (() => {
793
+ const invoked = process.argv[1] ?? "";
794
+ return /gate(\.mjs|\.ts|\.js)?$/.test(invoked) || invoked.endsWith("cli.ts");
795
+ })();
796
+ if (isDirectRun) {
797
+ main(process.argv.slice(2)).then((code) => {
798
+ process.exitCode = code;
799
+ }).catch((err) => {
800
+ process.stderr.write(`Unexpected error: ${err.message}
801
+ `);
802
+ process.exitCode = 1;
803
+ });
804
+ }
805
+ export {
806
+ main,
807
+ parseArgs
808
+ };
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@mylasecurity/gate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.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
+ }