@mylasecurity/gate 0.2.1 → 0.3.1
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 +63 -41
- package/bin/gate.mjs +1906 -31
- package/package.json +15 -3
package/bin/gate.mjs
CHANGED
|
@@ -64,7 +64,7 @@ function hookVersion(client) {
|
|
|
64
64
|
${watchTokens(client).join("|")}
|
|
65
65
|
${hookConfigJson(client, "ORIGIN", "TOKEN", "VERSION")}`);
|
|
66
66
|
}
|
|
67
|
-
var curl = (origin, token,
|
|
67
|
+
var curl = (origin, token, path11, fallback, version) => `curl -sS -f --max-time 10 -X POST ${origin}${path11} -H "Authorization: Bearer ${token}" -H "Content-Type: application/json" -H "X-Myla-Hook-Version: ${version}" --data-binary @- || printf '${fallback}'`;
|
|
68
68
|
var CURSOR_ALLOW = '{"permission":"allow"}';
|
|
69
69
|
var CODEX_ALLOW = "{}";
|
|
70
70
|
function hookConfigJson(client, origin, token, version) {
|
|
@@ -90,9 +90,9 @@ function hookConfigJson(client, origin, token, version) {
|
|
|
90
90
|
}
|
|
91
91
|
}, null, 2);
|
|
92
92
|
}
|
|
93
|
-
const httpHook = (
|
|
93
|
+
const httpHook = (path11, timeout) => [{
|
|
94
94
|
type: "http",
|
|
95
|
-
url: `${origin}${
|
|
95
|
+
url: `${origin}${path11}`,
|
|
96
96
|
timeout,
|
|
97
97
|
headers: { Authorization: `Bearer ${token}`, "X-Myla-Hook-Version": version }
|
|
98
98
|
}];
|
|
@@ -158,6 +158,7 @@ var HOOK_CLIENTS = ["claude-code", "cursor", "codex"];
|
|
|
158
158
|
var DEFAULT_ORIGIN = (process.env.NEXT_PUBLIC_APP_ORIGIN || "https://mylasecurity.app").replace(/\/+$/, "");
|
|
159
159
|
var MIN_NODE_MAJOR = 18;
|
|
160
160
|
var MYLA_HOOK_PATH = "/api/security/gate/hook";
|
|
161
|
+
var MYLA_LOCAL_MARKER = ".myla/decider.mjs";
|
|
161
162
|
|
|
162
163
|
// src/install.ts
|
|
163
164
|
import fs3 from "node:fs";
|
|
@@ -191,6 +192,28 @@ function originHostOf(origin) {
|
|
|
191
192
|
return null;
|
|
192
193
|
}
|
|
193
194
|
}
|
|
195
|
+
function readClaimToken(body, origin) {
|
|
196
|
+
const host = originHostOf(origin);
|
|
197
|
+
if (!host) return { ok: false, reason: `the origin ${JSON.stringify(origin)} is not a valid URL.` };
|
|
198
|
+
let parsed;
|
|
199
|
+
try {
|
|
200
|
+
parsed = JSON.parse(body);
|
|
201
|
+
} catch {
|
|
202
|
+
return { ok: false, reason: "the server did not return valid JSON." };
|
|
203
|
+
}
|
|
204
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
205
|
+
return { ok: false, reason: "the response is not a JSON object." };
|
|
206
|
+
}
|
|
207
|
+
const obj = parsed;
|
|
208
|
+
if (obj.hooks) return validateClaim(body, "claude-code", origin);
|
|
209
|
+
const unexpected = Object.keys(obj).filter((k) => k !== "token" && k !== "origin");
|
|
210
|
+
if (unexpected.length > 0) return { ok: false, reason: `it has unexpected top-level key(s): ${unexpected.join(", ")}.` };
|
|
211
|
+
if (typeof obj.token !== "string" || obj.token.length < 16) return { ok: false, reason: "it carries no credential." };
|
|
212
|
+
const bodyHost = typeof obj.origin === "string" ? originHostOf(obj.origin) : null;
|
|
213
|
+
if (!bodyHost) return { ok: false, reason: "it names no origin for the credential." };
|
|
214
|
+
if (bodyHost !== host) return { ok: false, reason: `it names an unexpected host (${bodyHost}), not ${host}.` };
|
|
215
|
+
return { ok: true, config: obj, token: obj.token };
|
|
216
|
+
}
|
|
194
217
|
function validateClaim(body, client, origin) {
|
|
195
218
|
const host = originHostOf(origin);
|
|
196
219
|
if (!host) return { ok: false, reason: `the origin ${JSON.stringify(origin)} is not a valid URL.` };
|
|
@@ -243,17 +266,18 @@ function isPlainObject(v) {
|
|
|
243
266
|
return !!v && typeof v === "object" && !Array.isArray(v);
|
|
244
267
|
}
|
|
245
268
|
var HOST_RE = /https?:\/\/([^\s"'/\\]+)/g;
|
|
246
|
-
function collectHosts(value,
|
|
269
|
+
function collectHosts(value, out3 = /* @__PURE__ */ new Set()) {
|
|
247
270
|
if (typeof value === "string") {
|
|
248
|
-
for (const m of value.matchAll(HOST_RE))
|
|
271
|
+
for (const m of value.matchAll(HOST_RE)) out3.add(m[1]);
|
|
249
272
|
} else if (Array.isArray(value)) {
|
|
250
|
-
for (const v of value) collectHosts(v,
|
|
273
|
+
for (const v of value) collectHosts(v, out3);
|
|
251
274
|
} else if (value && typeof value === "object") {
|
|
252
|
-
for (const v of Object.values(value)) collectHosts(v,
|
|
275
|
+
for (const v of Object.values(value)) collectHosts(v, out3);
|
|
253
276
|
}
|
|
254
|
-
return
|
|
277
|
+
return out3;
|
|
255
278
|
}
|
|
256
279
|
function isOurEntry(entry, originHost) {
|
|
280
|
+
if (isMylaEntry(entry, MYLA_HOOK_PATH)) return true;
|
|
257
281
|
const hosts = collectHosts(entry);
|
|
258
282
|
return hosts.size > 0 && [...hosts].every((h) => h === originHost);
|
|
259
283
|
}
|
|
@@ -346,7 +370,7 @@ function removeMylaHooks(opts) {
|
|
|
346
370
|
const { existingRaw, mylaHookPath } = opts;
|
|
347
371
|
const existing = parseSettings(existingRaw);
|
|
348
372
|
const indent = detectIndent(existingRaw);
|
|
349
|
-
const isMyla = (entry) =>
|
|
373
|
+
const isMyla = (entry) => isMylaEntry(entry, mylaHookPath);
|
|
350
374
|
if (!isPlainObject(existing.hooks)) return null;
|
|
351
375
|
const hooks = existing.hooks;
|
|
352
376
|
let removed = 0;
|
|
@@ -371,27 +395,33 @@ function removeMylaHooks(opts) {
|
|
|
371
395
|
const text = JSON.stringify(result, null, indent) + (hadTrailingNewline(existingRaw) ? "\n" : "");
|
|
372
396
|
return { text, removed };
|
|
373
397
|
}
|
|
398
|
+
function isMylaEntry(entry, mylaHookPath) {
|
|
399
|
+
const s = JSON.stringify(entry);
|
|
400
|
+
return s.includes(mylaHookPath) || s.includes(MYLA_LOCAL_MARKER);
|
|
401
|
+
}
|
|
374
402
|
function findMylaHooks(raw, mylaHookPath) {
|
|
375
403
|
let existing;
|
|
376
404
|
try {
|
|
377
405
|
existing = parseSettings(raw);
|
|
378
406
|
} catch {
|
|
379
|
-
return { count: 0, hosts: [] };
|
|
407
|
+
return { count: 0, hosts: [], local: 0 };
|
|
380
408
|
}
|
|
381
|
-
if (!isPlainObject(existing.hooks)) return { count: 0, hosts: [] };
|
|
409
|
+
if (!isPlainObject(existing.hooks)) return { count: 0, hosts: [], local: 0 };
|
|
382
410
|
let count = 0;
|
|
411
|
+
let local = 0;
|
|
383
412
|
const hosts = /* @__PURE__ */ new Set();
|
|
384
413
|
for (const ev of Object.keys(existing.hooks)) {
|
|
385
414
|
const arr = existing.hooks[ev];
|
|
386
415
|
if (!Array.isArray(arr)) continue;
|
|
387
416
|
for (const entry of arr) {
|
|
388
|
-
if (
|
|
417
|
+
if (isMylaEntry(entry, mylaHookPath)) {
|
|
389
418
|
count++;
|
|
419
|
+
if (JSON.stringify(entry).includes(MYLA_LOCAL_MARKER)) local++;
|
|
390
420
|
for (const h of collectHosts(entry)) hosts.add(h);
|
|
391
421
|
}
|
|
392
422
|
}
|
|
393
423
|
}
|
|
394
|
-
return { count, hosts: [...hosts] };
|
|
424
|
+
return { count, hosts: [...hosts], local };
|
|
395
425
|
}
|
|
396
426
|
|
|
397
427
|
// src/output.ts
|
|
@@ -478,15 +508,15 @@ function clientLayout(client) {
|
|
|
478
508
|
};
|
|
479
509
|
}
|
|
480
510
|
function ancestors(cwd) {
|
|
481
|
-
const
|
|
511
|
+
const out3 = [];
|
|
482
512
|
let dir = path2.resolve(cwd);
|
|
483
513
|
for (; ; ) {
|
|
484
|
-
|
|
514
|
+
out3.push(dir);
|
|
485
515
|
const parent = path2.dirname(dir);
|
|
486
516
|
if (parent === dir) break;
|
|
487
517
|
dir = parent;
|
|
488
518
|
}
|
|
489
|
-
return
|
|
519
|
+
return out3;
|
|
490
520
|
}
|
|
491
521
|
function scanForOtherMylaHooks(opts) {
|
|
492
522
|
const { client, cwd, perUserAbsolute } = opts;
|
|
@@ -633,6 +663,8 @@ function homeShorten(file) {
|
|
|
633
663
|
|
|
634
664
|
// src/doctor.ts
|
|
635
665
|
import fs4 from "node:fs";
|
|
666
|
+
import os3 from "node:os";
|
|
667
|
+
import path4 from "node:path";
|
|
636
668
|
var realVerify = async (url, token) => {
|
|
637
669
|
const res = await fetch(url, {
|
|
638
670
|
method: "POST",
|
|
@@ -641,6 +673,29 @@ var realVerify = async (url, token) => {
|
|
|
641
673
|
return { status: res.status, body: await res.text() };
|
|
642
674
|
};
|
|
643
675
|
var TOKEN_RE = /^[A-Za-z0-9_-]{32,128}$/;
|
|
676
|
+
function localBundleState() {
|
|
677
|
+
const dir = path4.join(os3.homedir(), ".myla");
|
|
678
|
+
let segment = 0;
|
|
679
|
+
try {
|
|
680
|
+
const seg = JSON.parse(fs4.readFileSync(path4.join(dir, "offline-segment.json"), "utf8"));
|
|
681
|
+
segment = Array.isArray(seg.entries) ? seg.entries.length : 0;
|
|
682
|
+
} catch {
|
|
683
|
+
}
|
|
684
|
+
try {
|
|
685
|
+
const b = JSON.parse(fs4.readFileSync(path4.join(dir, "bundle.json"), "utf8"));
|
|
686
|
+
const age = Date.now() - Date.parse(b.issued_at ?? "");
|
|
687
|
+
if (!Number.isFinite(age)) return { mark: "!", text: "unreadable \u2014 run `sync`", segment };
|
|
688
|
+
const hours2 = Math.floor(age / 36e5);
|
|
689
|
+
const stale = age > (b.ttl_ms ?? 864e5);
|
|
690
|
+
return {
|
|
691
|
+
mark: stale ? "!" : "\u2713",
|
|
692
|
+
text: stale ? `${hours2}h old \u2014 past their life, decisions are marked stale. Run \`sync\`` : hours2 < 1 ? "fresh (under an hour old)" : `${hours2}h old`,
|
|
693
|
+
segment
|
|
694
|
+
};
|
|
695
|
+
} catch {
|
|
696
|
+
return { mark: "!", text: "none on this machine \u2014 run `sync` before you need them", segment };
|
|
697
|
+
}
|
|
698
|
+
}
|
|
644
699
|
async function runDoctor(io, opts) {
|
|
645
700
|
const inst = hookInstall(opts.client, opts.origin, "PLACEHOLDER");
|
|
646
701
|
const file = opts.filePathOverride ?? resolveUserPath(inst.perUserPath);
|
|
@@ -664,7 +719,7 @@ async function runDoctor(io, opts) {
|
|
|
664
719
|
io.err(` Couldn\u2019t read ${shown} (${e.message}).`);
|
|
665
720
|
return 1;
|
|
666
721
|
}
|
|
667
|
-
const { count, hosts } = findMylaHooks(raw, MYLA_HOOK_PATH);
|
|
722
|
+
const { count, hosts, local } = findMylaHooks(raw, MYLA_HOOK_PATH);
|
|
668
723
|
io.out(row2("\u2022", "Settings file", shown));
|
|
669
724
|
if (count === 0) {
|
|
670
725
|
io.out(row2("\u2022", "Myla hook", "not installed"));
|
|
@@ -675,6 +730,12 @@ async function runDoctor(io, opts) {
|
|
|
675
730
|
}
|
|
676
731
|
io.out(row2("\u2713", "Myla hook", `installed (${count} ${count === 1 ? "entry" : "entries"})`));
|
|
677
732
|
io.out(row2("\u2022", "Points at", hosts.length ? hosts.join(", ") : "an unreadable host"));
|
|
733
|
+
if (local > 0) {
|
|
734
|
+
io.out(row2("\u2713", "Local mode", `on \u2014 ${local} of those ${local === 1 ? "hook decides" : "hooks decide"} on this machine`));
|
|
735
|
+
const b = localBundleState();
|
|
736
|
+
io.out(row2(b.mark, "Rules on disk", b.text));
|
|
737
|
+
if (b.segment > 0) io.out(row2("\u2022", "Waiting to hand over", `${b.segment} decision${b.segment === 1 ? "" : "s"} made offline \u2014 run \`sync\``));
|
|
738
|
+
}
|
|
678
739
|
const others = scanForOtherMylaHooks({ client: opts.client, cwd: opts.cwd ?? process.cwd(), perUserAbsolute: file });
|
|
679
740
|
for (const line of describeOtherConfigs(others)) io.out(line);
|
|
680
741
|
const m = raw.match(/Bearer\s+([^\s"'\\]+)/);
|
|
@@ -754,7 +815,7 @@ function row2(mark, label, value) {
|
|
|
754
815
|
|
|
755
816
|
// src/uninstall.ts
|
|
756
817
|
import fs5 from "node:fs";
|
|
757
|
-
import
|
|
818
|
+
import path5 from "node:path";
|
|
758
819
|
function runUninstall(io, opts) {
|
|
759
820
|
const inst = hookInstall(opts.client, opts.origin, "PLACEHOLDER");
|
|
760
821
|
const file = opts.filePathOverride ?? resolveUserPath(inst.perUserPath);
|
|
@@ -796,7 +857,7 @@ function runUninstall(io, opts) {
|
|
|
796
857
|
io.err(`Couldn\u2019t write a backup next to ${shown} (${e.message}), so nothing was changed.`);
|
|
797
858
|
return 1;
|
|
798
859
|
}
|
|
799
|
-
const tmp =
|
|
860
|
+
const tmp = path5.join(path5.dirname(file), `.gate-uninstall-${process.pid}-${Date.now()}.tmp`);
|
|
800
861
|
try {
|
|
801
862
|
fs5.writeFileSync(tmp, result.text, { encoding: "utf8", mode: 384 });
|
|
802
863
|
fs5.renameSync(tmp, file);
|
|
@@ -822,31 +883,1747 @@ function existingWritableRefused(io, file, shown) {
|
|
|
822
883
|
}
|
|
823
884
|
}
|
|
824
885
|
|
|
886
|
+
// ../../src/lib/security/gate/hooks/claude-code.ts
|
|
887
|
+
import { posix as pathPosix } from "node:path";
|
|
888
|
+
|
|
889
|
+
// ../../src/lib/security/gate/request.ts
|
|
890
|
+
var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
891
|
+
var strArr = (v, max) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && x.length <= 64).slice(0, max) : [];
|
|
892
|
+
function parseGateRequest(body) {
|
|
893
|
+
if (!isObj(body)) return null;
|
|
894
|
+
const tool = typeof body.tool === "string" && /^[a-z0-9_.-]{1,64}$/i.test(body.tool) ? body.tool : null;
|
|
895
|
+
if (!tool || !isObj(body.args)) return null;
|
|
896
|
+
const sha = typeof body.toolDescriptionSha256 === "string" && /^[0-9a-f]{64}$/i.test(body.toolDescriptionSha256) ? body.toolDescriptionSha256 : null;
|
|
897
|
+
const sc = isObj(body.sessionContext) ? body.sessionContext : {};
|
|
898
|
+
const sources = (Array.isArray(sc.sources) ? sc.sources : []).slice(0, 20).filter(isObj).map((s) => ({
|
|
899
|
+
// Only an explicit 'internal' is trusted as internal; anything else is external (fail closed).
|
|
900
|
+
kind: s.kind === "internal" ? "internal" : "external",
|
|
901
|
+
label: typeof s.label === "string" ? s.label.slice(0, 200) : void 0,
|
|
902
|
+
from: typeof s.from === "string" ? s.from.slice(0, 200) : void 0,
|
|
903
|
+
text: typeof s.text === "string" ? s.text.slice(0, 2e4) : void 0,
|
|
904
|
+
dataClasses: strArr(s.dataClasses, 20)
|
|
905
|
+
}));
|
|
906
|
+
return {
|
|
907
|
+
tool,
|
|
908
|
+
args: body.args,
|
|
909
|
+
toolDescriptionSha256: sha,
|
|
910
|
+
sessionContext: { task: typeof sc.task === "string" ? sc.task.slice(0, 2e3) : void 0, sources, dataClasses: strArr(sc.dataClasses, 20) }
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
// ../../src/lib/security/gate/hooks/dependency-dirs.ts
|
|
915
|
+
var DEP_DIRS = /* @__PURE__ */ new Set(["node_modules", "vendor", ".venv", "Pods", "target"]);
|
|
916
|
+
function inDependencyDir(rel) {
|
|
917
|
+
return rel.split("/").some((seg) => DEP_DIRS.has(seg));
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// ../../src/lib/security/gate/hooks/claude-code.ts
|
|
921
|
+
var isObj2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
922
|
+
var str = (v, max) => typeof v === "string" ? v.slice(0, max) : void 0;
|
|
923
|
+
function hostnameOf(u) {
|
|
924
|
+
if (typeof u !== "string") return null;
|
|
925
|
+
try {
|
|
926
|
+
return new URL(u).hostname.slice(0, 253) || null;
|
|
927
|
+
} catch {
|
|
928
|
+
return null;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
var ASK_DENY_REASON = "A person needs to approve this. It\u2019s waiting in Myla \u2014 approve it there and run this again.";
|
|
932
|
+
function out(decision, reasonForModel, systemMessage) {
|
|
933
|
+
return {
|
|
934
|
+
hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: decision, permissionDecisionReason: reasonForModel },
|
|
935
|
+
...systemMessage ? { systemMessage } : {}
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
var claudeCodeAdapter = {
|
|
939
|
+
parse(body) {
|
|
940
|
+
if (!isObj2(body)) return null;
|
|
941
|
+
const req = parseGateRequest({
|
|
942
|
+
tool: body.tool_name,
|
|
943
|
+
args: isObj2(body.tool_input) ? body.tool_input : {},
|
|
944
|
+
sessionContext: { sources: [] }
|
|
945
|
+
});
|
|
946
|
+
if (!req) return null;
|
|
947
|
+
return {
|
|
948
|
+
req,
|
|
949
|
+
source: { client: "claude-code", ...str(body.session_id, 120) ? { session_id: str(body.session_id, 120) } : {}, ...str(body.cwd, 300) ? { cwd: str(body.cwd, 300) } : {} }
|
|
950
|
+
};
|
|
951
|
+
},
|
|
952
|
+
render(outcome, observeOnly) {
|
|
953
|
+
const verdict = outcome.result.verdict;
|
|
954
|
+
const reason = outcome.result.reasons[0] ?? "Blocked by Myla Gate.";
|
|
955
|
+
if (observeOnly) {
|
|
956
|
+
const note = verdict === "allow" ? "" : verdict === "ask" ? "Myla would have asked a person to approve this \u2014 observing only, not blocking." : "Myla would have blocked this \u2014 observing only, not blocking.";
|
|
957
|
+
return out("allow", "", note);
|
|
958
|
+
}
|
|
959
|
+
if (verdict === "allow") return out("allow", "", "");
|
|
960
|
+
if (verdict === "ask") return out("deny", ASK_DENY_REASON, ASK_DENY_REASON);
|
|
961
|
+
return out("deny", reason, reason);
|
|
962
|
+
},
|
|
963
|
+
parseReport(body) {
|
|
964
|
+
if (!isObj2(body)) return null;
|
|
965
|
+
const sessionId = str(body.session_id, 120);
|
|
966
|
+
if (!sessionId) return null;
|
|
967
|
+
const tool = typeof body.tool_name === "string" ? body.tool_name : null;
|
|
968
|
+
const input = isObj2(body.tool_input) ? body.tool_input : {};
|
|
969
|
+
let source = null;
|
|
970
|
+
if (tool === "WebFetch") {
|
|
971
|
+
const host = hostnameOf(input.url);
|
|
972
|
+
if (host) source = { kind: "external", label: host };
|
|
973
|
+
} else if (tool === "WebSearch") {
|
|
974
|
+
source = { kind: "external", label: "web search" };
|
|
975
|
+
} else if (tool === "Read") {
|
|
976
|
+
const fp = typeof input.file_path === "string" ? input.file_path : null;
|
|
977
|
+
const cwd = str(body.cwd, 1e3);
|
|
978
|
+
if (fp && cwd) {
|
|
979
|
+
const rel = pathPosix.relative(cwd, fp);
|
|
980
|
+
if (rel && (rel.startsWith("..") || pathPosix.isAbsolute(rel) || inDependencyDir(rel))) source = { kind: "external", label: rel.slice(0, 300) };
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
return { sessionId, source };
|
|
984
|
+
},
|
|
985
|
+
// Claude Code's read is PostToolUse — observational, gates nothing — so an empty object is the right
|
|
986
|
+
// acknowledgement. (Cursor differs: see cursor.ts, where the read hook is a permission hook.)
|
|
987
|
+
reportAck() {
|
|
988
|
+
return {};
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
|
|
992
|
+
// ../../src/lib/security/gate/hooks/cursor.ts
|
|
993
|
+
import { posix as pathPosix2 } from "node:path";
|
|
994
|
+
var isObj3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
995
|
+
var str2 = (v, max) => typeof v === "string" ? v.slice(0, max) : void 0;
|
|
996
|
+
var sessionKey = (body) => str2(body.conversation_id, 120) ?? str2(body.session_id, 120);
|
|
997
|
+
function parseMcpInput(v) {
|
|
998
|
+
if (isObj3(v)) return v;
|
|
999
|
+
if (typeof v === "string") {
|
|
1000
|
+
try {
|
|
1001
|
+
const p = JSON.parse(v);
|
|
1002
|
+
return isObj3(p) ? p : {};
|
|
1003
|
+
} catch {
|
|
1004
|
+
return {};
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
return {};
|
|
1008
|
+
}
|
|
1009
|
+
var ALLOW = { permission: "allow" };
|
|
1010
|
+
var deny = (message) => ({ permission: "deny", user_message: message, agent_message: message });
|
|
1011
|
+
var cursorAdapter = {
|
|
1012
|
+
parse(body) {
|
|
1013
|
+
if (!isObj3(body)) return null;
|
|
1014
|
+
let tool, args;
|
|
1015
|
+
if (typeof body.tool_name === "string") {
|
|
1016
|
+
tool = body.tool_name;
|
|
1017
|
+
args = parseMcpInput(body.tool_input);
|
|
1018
|
+
} else if (typeof body.command === "string") {
|
|
1019
|
+
tool = "Bash";
|
|
1020
|
+
args = { command: body.command };
|
|
1021
|
+
} else {
|
|
1022
|
+
return null;
|
|
1023
|
+
}
|
|
1024
|
+
const req = parseGateRequest({ tool, args, sessionContext: { sources: [] } });
|
|
1025
|
+
if (!req) return null;
|
|
1026
|
+
const sid = sessionKey(body);
|
|
1027
|
+
return {
|
|
1028
|
+
req,
|
|
1029
|
+
source: { client: "cursor", ...sid ? { session_id: sid } : {}, ...str2(body.cwd, 300) ? { cwd: str2(body.cwd, 300) } : {} }
|
|
1030
|
+
};
|
|
1031
|
+
},
|
|
1032
|
+
render(outcome, observeOnly) {
|
|
1033
|
+
const verdict = outcome.result.verdict;
|
|
1034
|
+
const reason = outcome.result.reasons[0] ?? "Blocked by Myla Gate.";
|
|
1035
|
+
if (observeOnly) return ALLOW;
|
|
1036
|
+
if (verdict === "allow") return ALLOW;
|
|
1037
|
+
if (verdict === "ask") return deny(ASK_DENY_REASON);
|
|
1038
|
+
return deny(reason);
|
|
1039
|
+
},
|
|
1040
|
+
// What a Cursor read hook (beforeReadFile) expects back. It is a PERMISSION hook, so `{}` would be a
|
|
1041
|
+
// schema mismatch and BLOCK the read (AD42 §2d) — it must get a valid permission, and in observe mode
|
|
1042
|
+
// that is always allow.
|
|
1043
|
+
reportAck() {
|
|
1044
|
+
return ALLOW;
|
|
1045
|
+
},
|
|
1046
|
+
parseReport(body) {
|
|
1047
|
+
if (!isObj3(body)) return null;
|
|
1048
|
+
const sessionId = sessionKey(body);
|
|
1049
|
+
if (!sessionId) return null;
|
|
1050
|
+
const fp = typeof body.file_path === "string" ? body.file_path : null;
|
|
1051
|
+
const cwd = str2(body.cwd, 1e3);
|
|
1052
|
+
let source = null;
|
|
1053
|
+
if (fp && cwd) {
|
|
1054
|
+
const rel = pathPosix2.relative(cwd, fp);
|
|
1055
|
+
if (rel && (rel.startsWith("..") || pathPosix2.isAbsolute(rel) || inDependencyDir(rel))) source = { kind: "external", label: rel.slice(0, 300) };
|
|
1056
|
+
}
|
|
1057
|
+
return { sessionId, source };
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
|
|
1061
|
+
// ../../src/lib/security/gate/hooks/codex.ts
|
|
1062
|
+
var isObj4 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
1063
|
+
var str3 = (v, max) => typeof v === "string" ? v.slice(0, max) : void 0;
|
|
1064
|
+
function out2(decision, reasonForModel, systemMessage) {
|
|
1065
|
+
return {
|
|
1066
|
+
hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: decision, permissionDecisionReason: reasonForModel },
|
|
1067
|
+
...systemMessage ? { systemMessage } : {}
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
var codexAdapter = {
|
|
1071
|
+
parse(body) {
|
|
1072
|
+
if (!isObj4(body)) return null;
|
|
1073
|
+
const req = parseGateRequest({
|
|
1074
|
+
tool: body.tool_name,
|
|
1075
|
+
args: isObj4(body.tool_input) ? body.tool_input : {},
|
|
1076
|
+
sessionContext: { sources: [] }
|
|
1077
|
+
// join happens at evaluate time (AD36), keyed on session_id
|
|
1078
|
+
});
|
|
1079
|
+
if (!req) return null;
|
|
1080
|
+
return {
|
|
1081
|
+
req,
|
|
1082
|
+
source: {
|
|
1083
|
+
client: "codex",
|
|
1084
|
+
...str3(body.session_id, 120) ? { session_id: str3(body.session_id, 120) } : {},
|
|
1085
|
+
...str3(body.cwd, 300) ? { cwd: str3(body.cwd, 300) } : {},
|
|
1086
|
+
...str3(body.model, 120) ? { model: str3(body.model, 120) } : {}
|
|
1087
|
+
// Codex sends this; Claude Code does not
|
|
1088
|
+
}
|
|
1089
|
+
};
|
|
1090
|
+
},
|
|
1091
|
+
render(outcome, observeOnly) {
|
|
1092
|
+
const verdict = outcome.result.verdict;
|
|
1093
|
+
const reason = outcome.result.reasons[0] ?? "Blocked by Myla Gate.";
|
|
1094
|
+
if (observeOnly) return {};
|
|
1095
|
+
if (verdict === "allow") return {};
|
|
1096
|
+
if (verdict === "ask") return out2("deny", ASK_DENY_REASON, ASK_DENY_REASON);
|
|
1097
|
+
return out2("deny", reason, reason);
|
|
1098
|
+
},
|
|
1099
|
+
parseReport(body) {
|
|
1100
|
+
if (!isObj4(body)) return null;
|
|
1101
|
+
const sessionId = str3(body.session_id, 120);
|
|
1102
|
+
if (!sessionId) return null;
|
|
1103
|
+
return { sessionId, source: null };
|
|
1104
|
+
},
|
|
1105
|
+
// Codex's read is PostToolUse — observational, gates nothing — so an empty object, like Claude Code.
|
|
1106
|
+
reportAck() {
|
|
1107
|
+
return {};
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
|
|
1111
|
+
// ../../src/lib/security/gate/hooks/types.ts
|
|
1112
|
+
var isUnsupported = (a) => "unsupported" in a;
|
|
1113
|
+
|
|
1114
|
+
// ../../src/lib/security/gate/hooks/index.ts
|
|
1115
|
+
var HOOK_ADAPTERS = {
|
|
1116
|
+
"claude-code": claudeCodeAdapter,
|
|
1117
|
+
"cursor": cursorAdapter,
|
|
1118
|
+
"codex": codexAdapter
|
|
1119
|
+
};
|
|
1120
|
+
function isHookClient(c) {
|
|
1121
|
+
return c === "claude-code" || c === "codex" || c === "cursor";
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
// src/offline.ts
|
|
1125
|
+
import { createHash } from "node:crypto";
|
|
1126
|
+
import fs6 from "node:fs";
|
|
1127
|
+
import path6 from "node:path";
|
|
1128
|
+
import os4 from "node:os";
|
|
1129
|
+
|
|
1130
|
+
// ../../src/lib/security/gate/bundle.ts
|
|
1131
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
1132
|
+
var BUNDLE_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
1133
|
+
function canonical(value) {
|
|
1134
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
1135
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
1136
|
+
const obj = value;
|
|
1137
|
+
const keys = Object.keys(obj).filter((k) => obj[k] !== void 0).sort();
|
|
1138
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonical(obj[k])}`).join(",")}}`;
|
|
1139
|
+
}
|
|
1140
|
+
function verifyBundle(bundle, token) {
|
|
1141
|
+
const { sig, ...body } = bundle;
|
|
1142
|
+
if (typeof sig !== "string" || sig.length !== 64) return false;
|
|
1143
|
+
const want = createHmac("sha256", token).update(canonical(body)).digest("hex");
|
|
1144
|
+
try {
|
|
1145
|
+
return timingSafeEqual(Buffer.from(want, "hex"), Buffer.from(sig, "hex"));
|
|
1146
|
+
} catch {
|
|
1147
|
+
return false;
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
function bundleAgeMs(bundle, now = Date.now()) {
|
|
1151
|
+
const issued = Date.parse(bundle.issued_at);
|
|
1152
|
+
return Number.isFinite(issued) ? Math.max(0, now - issued) : Number.POSITIVE_INFINITY;
|
|
1153
|
+
}
|
|
1154
|
+
function bundleStale(bundle, now = Date.now()) {
|
|
1155
|
+
return bundleAgeMs(bundle, now) > bundle.ttl_ms;
|
|
1156
|
+
}
|
|
1157
|
+
function entryHash(prev, entry) {
|
|
1158
|
+
return createHmac("sha256", prev).update(canonical(entry)).digest("hex");
|
|
1159
|
+
}
|
|
1160
|
+
function verifySegment(seed, entries) {
|
|
1161
|
+
let prev = seed;
|
|
1162
|
+
for (let i = 0; i < entries.length; i++) {
|
|
1163
|
+
const e = entries[i];
|
|
1164
|
+
if (e.seq !== i + 1) return { ok: false, at: i, why: `out of sequence (seq ${e.seq}, expected ${i + 1})` };
|
|
1165
|
+
const { hash, ...rest } = e;
|
|
1166
|
+
if (entryHash(prev, rest) !== hash) return { ok: false, at: i, why: "hash does not match the entry" };
|
|
1167
|
+
prev = hash;
|
|
1168
|
+
}
|
|
1169
|
+
return { ok: true };
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
// ../../src/lib/security/gate/tripwire.ts
|
|
1173
|
+
function sensitiveWritePath(path11) {
|
|
1174
|
+
const p = path11.replace(/\\/g, "/");
|
|
1175
|
+
const segs = p.split("/").filter(Boolean);
|
|
1176
|
+
const base = segs[segs.length - 1] ?? "";
|
|
1177
|
+
if (/^\.env(\..+)?$/i.test(base)) return ".env";
|
|
1178
|
+
if (base === ".git/config" || segs.includes(".git") && base === "config") return ".git/config";
|
|
1179
|
+
if (segs.includes(".ssh")) return ".ssh/";
|
|
1180
|
+
if (segs.includes(".github") && segs.includes("workflows")) return ".github/workflows/";
|
|
1181
|
+
if (/^Dockerfile(\..+)?$/i.test(base)) return "Dockerfile";
|
|
1182
|
+
if (base === ".gitlab-ci.yml" || base === "Jenkinsfile" || segs.includes(".circleci") || base === "azure-pipelines.yml" || base === ".travis.yml") return "CI config";
|
|
1183
|
+
return null;
|
|
1184
|
+
}
|
|
1185
|
+
function redirectTargets(command) {
|
|
1186
|
+
const targets = [];
|
|
1187
|
+
const redir = /(?:>>?\s*|\btee\b\s+(?:-a\s+)?)(['"]?)([^\s'"|&;<>]+)\1/g;
|
|
1188
|
+
for (const m of command.matchAll(redir)) if (m[2]) targets.push(m[2]);
|
|
1189
|
+
return targets;
|
|
1190
|
+
}
|
|
1191
|
+
function bashConsequence(command) {
|
|
1192
|
+
const c = command.toLowerCase();
|
|
1193
|
+
if (/\b(curl|wget)\b[^|]*\|\s*(sudo\s+)?(sh|bash|zsh|python[0-9.]*|node|perl|ruby)\b/.test(c))
|
|
1194
|
+
return { kind: "bash_pipe_to_shell", phrase: "pipes a download straight into a shell" };
|
|
1195
|
+
if (/\bgit\s+push\b/.test(c)) return { kind: "bash_push", phrase: "pushes commits to a remote" };
|
|
1196
|
+
if (/\b(npm|yarn|pnpm)\s+publish\b/.test(c)) return { kind: "bash_publish", phrase: "publishes a package" };
|
|
1197
|
+
if (/(>>?|\btee\b|\bcp\b|\bmv\b|\bchmod\b)[^\n]*(~\/\.ssh|\$home\/\.ssh|\/\.ssh\/)/.test(c))
|
|
1198
|
+
return { kind: "bash_writes_ssh", phrase: "writes into ~/.ssh" };
|
|
1199
|
+
for (const target of redirectTargets(command)) {
|
|
1200
|
+
const hit = sensitiveWritePath(target);
|
|
1201
|
+
if (hit) return { kind: "bash_writes_sensitive_file", phrase: `writes to a credentials or CI file (${hit}) via a shell redirect` };
|
|
1202
|
+
}
|
|
1203
|
+
const longBody = /(--data\b|--data-\w+\b|--form\b|--upload-file\b|--post-\w+\b|--body-\w+\b|--request\s+(post|put)\b|@[^\s'"]+)/i.test(command);
|
|
1204
|
+
const shortBody = /(?:^|\s)-[dFT]\b/.test(command) || /(?:^|\s)-X\s+(POST|PUT|post|put)\b/.test(command);
|
|
1205
|
+
if (/\b(curl|wget)\b/.test(c) && (longBody || shortBody))
|
|
1206
|
+
return { kind: "bash_egress", phrase: "sends data off the machine" };
|
|
1207
|
+
return null;
|
|
1208
|
+
}
|
|
1209
|
+
function consequentialTripwire(tool, args) {
|
|
1210
|
+
if (tool === "Bash") {
|
|
1211
|
+
const command = typeof args.command === "string" ? args.command : "";
|
|
1212
|
+
return command ? bashConsequence(command) : null;
|
|
1213
|
+
}
|
|
1214
|
+
if (tool === "Write" || tool === "Edit") {
|
|
1215
|
+
const path11 = typeof args.file_path === "string" ? args.file_path : "";
|
|
1216
|
+
const hit = path11 ? sensitiveWritePath(path11) : null;
|
|
1217
|
+
return hit ? { kind: "write_sensitive_file", phrase: `writes to a credentials or CI file (${hit})` } : null;
|
|
1218
|
+
}
|
|
1219
|
+
return null;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// ../../src/lib/security/gate/mcp.ts
|
|
1223
|
+
var PREFIX = "mcp__";
|
|
1224
|
+
function parseMcpTool(name) {
|
|
1225
|
+
if (typeof name !== "string" || !name.startsWith(PREFIX)) return null;
|
|
1226
|
+
const rest = name.slice(PREFIX.length);
|
|
1227
|
+
const sep = rest.indexOf("__");
|
|
1228
|
+
if (sep <= 0) return null;
|
|
1229
|
+
const server = rest.slice(0, sep);
|
|
1230
|
+
const tool = rest.slice(sep + 2);
|
|
1231
|
+
if (!server || !tool) return null;
|
|
1232
|
+
return { server, tool };
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
// ../../src/lib/security/gate/shell-egress.ts
|
|
1236
|
+
var NOT_EGRESS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1", "ip6-localhost", "broadcasthost"]);
|
|
1237
|
+
var isNotEgress = (h) => NOT_EGRESS.has(h) || h.endsWith(".localhost") || h.endsWith(".local") || h.startsWith("127.") || h.startsWith("192.168.") || h.startsWith("10.");
|
|
1238
|
+
var LOOKS_LIKE_HOST = /^(?:[a-z0-9-]+\.)+[a-z]{2,}$|^\d{1,3}(?:\.\d{1,3}){3}$/;
|
|
1239
|
+
var URL_RE = /\b(?:https?|ftps?|ssh|git|wss?):\/\/([^\s"'`<>\\|)]+)/gi;
|
|
1240
|
+
var SCP_RE = /\b[a-z0-9._-]+@([a-z0-9.-]+\.[a-z]{2,})(?=:)/gi;
|
|
1241
|
+
function cleanHost(raw) {
|
|
1242
|
+
let h = raw.trim().toLowerCase();
|
|
1243
|
+
h = h.split("/")[0].split("?")[0].split("#")[0];
|
|
1244
|
+
const at = h.lastIndexOf("@");
|
|
1245
|
+
if (at >= 0) h = h.slice(at + 1);
|
|
1246
|
+
if (h.startsWith("[")) {
|
|
1247
|
+
const end = h.indexOf("]");
|
|
1248
|
+
h = end > 0 ? h.slice(1, end) : h.slice(1);
|
|
1249
|
+
} else {
|
|
1250
|
+
h = h.split(":")[0];
|
|
1251
|
+
}
|
|
1252
|
+
h = h.replace(/[.,;)\]}'"]+$/, "");
|
|
1253
|
+
if (!h || !LOOKS_LIKE_HOST.test(h)) return null;
|
|
1254
|
+
return h;
|
|
1255
|
+
}
|
|
1256
|
+
function hostsInCommand(command) {
|
|
1257
|
+
if (typeof command !== "string" || command.length === 0) return [];
|
|
1258
|
+
const text = command.slice(0, 8e3);
|
|
1259
|
+
const out3 = [];
|
|
1260
|
+
const add = (raw) => {
|
|
1261
|
+
const h = cleanHost(raw);
|
|
1262
|
+
if (h && !isNotEgress(h) && !out3.includes(h)) out3.push(h);
|
|
1263
|
+
};
|
|
1264
|
+
for (const m of text.matchAll(URL_RE)) add(m[1]);
|
|
1265
|
+
for (const m of text.matchAll(SCP_RE)) add(m[1]);
|
|
1266
|
+
return out3;
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
// ../../src/lib/security/gate/policy.ts
|
|
1270
|
+
var OUTBOUND_TOOLS = /* @__PURE__ */ new Set(["email.send", "http.post", "http.request", "slack.post", "webhook.send", "file.share"]);
|
|
1271
|
+
var ACTION_CLASSES = {
|
|
1272
|
+
// ── read: observes, changes nothing ──────────────────────────────────────
|
|
1273
|
+
"db.query": ["read"],
|
|
1274
|
+
"db.read": ["read"],
|
|
1275
|
+
"file.read": ["read"],
|
|
1276
|
+
"http.get": ["read"],
|
|
1277
|
+
"logs.read": ["read"],
|
|
1278
|
+
"search.query": ["read"],
|
|
1279
|
+
"email.read": ["read"],
|
|
1280
|
+
"calendar.read": ["read"],
|
|
1281
|
+
"repo.read": ["read"],
|
|
1282
|
+
"issue.read": ["read"],
|
|
1283
|
+
"metrics.read": ["read"],
|
|
1284
|
+
// ── write: changes something a person can put back ───────────────────────
|
|
1285
|
+
"db.insert": ["write"],
|
|
1286
|
+
"db.update": ["write"],
|
|
1287
|
+
"file.write": ["write"],
|
|
1288
|
+
"issue.create": ["write"],
|
|
1289
|
+
"issue.comment": ["write"],
|
|
1290
|
+
"ticket.update": ["write"],
|
|
1291
|
+
"calendar.create": ["write"],
|
|
1292
|
+
"pr.create": ["write"],
|
|
1293
|
+
"branch.create": ["write"],
|
|
1294
|
+
// ── irreversible: no undo, or undo needs someone senior and a backup ─────
|
|
1295
|
+
"db.delete": ["irreversible"],
|
|
1296
|
+
"db.drop": ["irreversible"],
|
|
1297
|
+
"db.truncate": ["irreversible"],
|
|
1298
|
+
"file.delete": ["irreversible"],
|
|
1299
|
+
"bucket.delete": ["irreversible"],
|
|
1300
|
+
"user.revoke": ["irreversible"],
|
|
1301
|
+
"user.delete": ["irreversible"],
|
|
1302
|
+
"access.revoke": ["irreversible"],
|
|
1303
|
+
"repo.force_push": ["irreversible"],
|
|
1304
|
+
"repo.delete": ["irreversible"],
|
|
1305
|
+
"release.delete": ["irreversible"],
|
|
1306
|
+
"key.rotate": ["irreversible"],
|
|
1307
|
+
"agent.revoke": ["irreversible"],
|
|
1308
|
+
// ── costly: moves money or commits spend ─────────────────────────────────
|
|
1309
|
+
"payments.refund": ["costly"],
|
|
1310
|
+
"payments.charge": ["costly"],
|
|
1311
|
+
"payments.transfer": ["costly"],
|
|
1312
|
+
"payments.payout": ["costly"],
|
|
1313
|
+
"subscription.cancel": ["costly", "irreversible"],
|
|
1314
|
+
"invoice.void": ["costly", "irreversible"],
|
|
1315
|
+
"infra.provision": ["costly"],
|
|
1316
|
+
// ── public: someone outside the company sees it ──────────────────────────
|
|
1317
|
+
// The six OUTBOUND_TOOLS are classified too, for completeness of the map — but see
|
|
1318
|
+
// UNTRUSTED_ACTION below: the outbound rules already govern them, so a class here does not
|
|
1319
|
+
// make a second rule fire on the same call.
|
|
1320
|
+
"email.send": ["public"],
|
|
1321
|
+
"slack.post": ["public"],
|
|
1322
|
+
"webhook.send": ["public"],
|
|
1323
|
+
"http.post": ["public"],
|
|
1324
|
+
"http.request": ["public"],
|
|
1325
|
+
"file.share": ["public"],
|
|
1326
|
+
"tweet.post": ["public"],
|
|
1327
|
+
"page.publish": ["public"],
|
|
1328
|
+
"repo.publish": ["public"],
|
|
1329
|
+
"deploy.production": ["public", "irreversible"]
|
|
1330
|
+
};
|
|
1331
|
+
function actionClasses(tool, classifications = []) {
|
|
1332
|
+
const authored = ACTION_CLASSES[tool];
|
|
1333
|
+
if (authored) return authored;
|
|
1334
|
+
const mcp = parseMcpTool(tool);
|
|
1335
|
+
if (mcp) {
|
|
1336
|
+
const hit = classifications.find((c) => c.server === mcp.server);
|
|
1337
|
+
if (hit) return hit.classes;
|
|
1338
|
+
}
|
|
1339
|
+
return [];
|
|
1340
|
+
}
|
|
1341
|
+
var CONSEQUENTIAL = ["irreversible", "costly", "public"];
|
|
1342
|
+
var CLASS_PHRASE = {
|
|
1343
|
+
irreversible: "cannot be undone",
|
|
1344
|
+
costly: "moves money",
|
|
1345
|
+
public: "is visible outside the company"
|
|
1346
|
+
};
|
|
1347
|
+
var SENSITIVE_CLASSES = /* @__PURE__ */ new Set(["customer_list", "secrets", "credentials", "pii_bulk", "financials"]);
|
|
1348
|
+
var CLASS_LABEL = {
|
|
1349
|
+
customer_list: "the customer list",
|
|
1350
|
+
secrets: "secrets",
|
|
1351
|
+
credentials: "credentials",
|
|
1352
|
+
pii_bulk: "bulk personal data",
|
|
1353
|
+
financials: "financial records"
|
|
1354
|
+
};
|
|
1355
|
+
var asList = (v) => typeof v === "string" ? [v] : Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
|
|
1356
|
+
function destinations(args) {
|
|
1357
|
+
const recipients = [...asList(args.to), ...asList(args.cc), ...asList(args.bcc), ...asList(args.recipients)].map((r) => r.trim().toLowerCase());
|
|
1358
|
+
const urls = [...asList(args.url), ...asList(args.webhook)];
|
|
1359
|
+
const domains = recipients.map((r) => {
|
|
1360
|
+
const m = r.match(/^[^@\s]+@([a-z0-9.-]+\.[a-z]{2,})$/);
|
|
1361
|
+
return m ? m[1] : null;
|
|
1362
|
+
});
|
|
1363
|
+
for (const u of urls) {
|
|
1364
|
+
try {
|
|
1365
|
+
domains.push(new URL(u).hostname.toLowerCase());
|
|
1366
|
+
} catch {
|
|
1367
|
+
domains.push(null);
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
return { recipients, domains };
|
|
1371
|
+
}
|
|
1372
|
+
function domainAllowed(domain, allowlist) {
|
|
1373
|
+
return allowlist.some((a) => {
|
|
1374
|
+
const d = a.trim().toLowerCase();
|
|
1375
|
+
return domain === d || domain.endsWith(`.${d}`);
|
|
1376
|
+
});
|
|
1377
|
+
}
|
|
1378
|
+
function outgoingClasses(args) {
|
|
1379
|
+
const out3 = new Set(asList(args.data_classes));
|
|
1380
|
+
if (Array.isArray(args.attachments)) {
|
|
1381
|
+
for (const a of args.attachments) {
|
|
1382
|
+
if (a && typeof a === "object" && typeof a.data_class === "string") out3.add(a.data_class);
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
return Array.from(out3);
|
|
1386
|
+
}
|
|
1387
|
+
function evaluatePolicy(input) {
|
|
1388
|
+
const { agent, tool, args, sessionContext: ctx } = input;
|
|
1389
|
+
const hard = [];
|
|
1390
|
+
const soft = [];
|
|
1391
|
+
let ask = null;
|
|
1392
|
+
let pauseAgent = false;
|
|
1393
|
+
const classes = actionClasses(tool, input.classifications ?? []);
|
|
1394
|
+
if (agent.status === "quarantined") hard.push(["QUARANTINED", `${agent.name} is quarantined: a person has deliberately stopped it, so every action it attempts is denied. This is a policy decision, not a technical fault or a temporary outage \u2014 a different route or tool will be denied too. Stop now and tell the person who runs you; do not try to work around it.`]);
|
|
1395
|
+
else if (agent.status === "paused") hard.push(["PAUSED", `${agent.name} is paused until someone reviews it.`]);
|
|
1396
|
+
if (!agent.allowed_tools.includes(tool)) hard.push(["NOT_ALLOWED", `${agent.name} isn't allowed to use ${tool}.`]);
|
|
1397
|
+
const pin = input.pins.find((p) => p.tool_name === tool && p.description_sha256);
|
|
1398
|
+
if (pin) {
|
|
1399
|
+
const seen = (input.toolDescriptionSha256 ?? "").toLowerCase();
|
|
1400
|
+
if (seen !== pin.description_sha256.toLowerCase()) {
|
|
1401
|
+
hard.push(["TOOL_PIN", seen ? `The instructions for ${tool} changed since they were approved \u2014 ${agent.name} is paused.` : `Couldn't verify the instructions for ${tool} against the approved version \u2014 ${agent.name} is paused.`]);
|
|
1402
|
+
pauseAgent = true;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
const outboundBuiltin = OUTBOUND_TOOLS.has(tool);
|
|
1406
|
+
const classifiedPublicMcp = parseMcpTool(tool) !== null && classes.includes("public");
|
|
1407
|
+
const wayOut = outboundBuiltin || classifiedPublicMcp;
|
|
1408
|
+
const dest = destinations(args);
|
|
1409
|
+
if (outboundBuiltin) {
|
|
1410
|
+
if (dest.domains.length === 0 || dest.domains.some((d) => d === null)) {
|
|
1411
|
+
hard.push(["EGRESS", "The destination of this outbound action could not be verified."]);
|
|
1412
|
+
} else {
|
|
1413
|
+
const bad = Array.from(new Set(dest.domains.filter((d) => !domainAllowed(d, agent.egress_allowlist))));
|
|
1414
|
+
if (bad.length) hard.push(["EGRESS", `${bad.join(", ")} ${bad.length === 1 ? "is" : "are"} not on ${agent.name}'s list of allowed destinations.`]);
|
|
1415
|
+
}
|
|
1416
|
+
} else if (typeof args.command === "string" && agent.egress_allowlist.length > 0) {
|
|
1417
|
+
const hosts = hostsInCommand(args.command);
|
|
1418
|
+
const bad = hosts.filter((h) => !domainAllowed(h, agent.egress_allowlist));
|
|
1419
|
+
if (bad.length) {
|
|
1420
|
+
hard.push(["EGRESS", `This command appears to reach ${bad.join(", ")}, which ${bad.length === 1 ? "is" : "are"} not on ${agent.name}'s list of allowed destinations.`]);
|
|
1421
|
+
}
|
|
1422
|
+
} else if (classifiedPublicMcp) {
|
|
1423
|
+
const named = Array.from(new Set(dest.domains.filter((d) => d !== null)));
|
|
1424
|
+
const bad = named.filter((d) => !domainAllowed(d, agent.egress_allowlist));
|
|
1425
|
+
if (bad.length) hard.push(["EGRESS", `${bad.join(", ")} ${bad.length === 1 ? "is" : "are"} not on ${agent.name}'s list of allowed destinations.`]);
|
|
1426
|
+
}
|
|
1427
|
+
const carried = outgoingClasses(args);
|
|
1428
|
+
let decisionRef;
|
|
1429
|
+
if (outboundBuiltin && dest.recipients.length > 0 && carried.length > 0) {
|
|
1430
|
+
const active = input.grants.filter((g) => g.active && g.tool === tool);
|
|
1431
|
+
const byDecision = /* @__PURE__ */ new Map();
|
|
1432
|
+
for (const g of active) byDecision.set(g.decision_id, [...byDecision.get(g.decision_id) ?? [], g]);
|
|
1433
|
+
for (const [decisionId, gs] of Array.from(byDecision)) {
|
|
1434
|
+
const ok = dest.recipients.every((r) => carried.every((c) => gs.some((g) => g.recipient.toLowerCase() === r && g.data_class === c)));
|
|
1435
|
+
if (ok) {
|
|
1436
|
+
decisionRef = decisionId;
|
|
1437
|
+
break;
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
const touchedPrivate = ctx.dataClasses.some((c) => SENSITIVE_CLASSES.has(c)) || ctx.sources.some((s) => (s.dataClasses ?? []).some((c) => SENSITIVE_CLASSES.has(c)));
|
|
1442
|
+
const ingestedExternal = ctx.sources.some((s) => s.kind === "external");
|
|
1443
|
+
if (wayOut && touchedPrivate && ingestedExternal) {
|
|
1444
|
+
soft.push(["ASI01", "Possible goal hijack: this session read private data and untrusted outside content, and is now sending data out."]);
|
|
1445
|
+
soft.push(["TRIFECTA", 'Private data + untrusted input + a way out \u2014 the "lethal trifecta".']);
|
|
1446
|
+
}
|
|
1447
|
+
const leaving = carried.filter((c) => SENSITIVE_CLASSES.has(c));
|
|
1448
|
+
if (wayOut && leaving.length) {
|
|
1449
|
+
soft.push(["DATA_CLASS", `Sensitive data (${leaving.map((c) => CLASS_LABEL[c] ?? c).join(", ")}) would leave the company.`]);
|
|
1450
|
+
}
|
|
1451
|
+
if (outboundBuiltin && ingestedExternal && !touchedPrivate) {
|
|
1452
|
+
ask = ["UNTRUSTED_INPUT", "The agent read untrusted outside content before sending \u2014 a person should OK this."];
|
|
1453
|
+
}
|
|
1454
|
+
if (!outboundBuiltin && ingestedExternal) {
|
|
1455
|
+
const hit = CONSEQUENTIAL.filter((c) => classes.includes(c));
|
|
1456
|
+
if (hit.length) {
|
|
1457
|
+
ask = [
|
|
1458
|
+
"UNTRUSTED_ACTION",
|
|
1459
|
+
`The agent read untrusted outside content, and ${tool} ${hit.map((c) => CLASS_PHRASE[c]).join(" and ")} \u2014 a person should OK this.`
|
|
1460
|
+
];
|
|
1461
|
+
} else {
|
|
1462
|
+
const trip = consequentialTripwire(tool, args);
|
|
1463
|
+
if (trip) {
|
|
1464
|
+
ask = [
|
|
1465
|
+
"UNTRUSTED_ACTION",
|
|
1466
|
+
`The agent read untrusted outside content, and ${tool} ${trip.phrase} \u2014 a person should OK this (tripwire, not a guarantee).`
|
|
1467
|
+
];
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
const gap = {};
|
|
1472
|
+
if (classes.length === 0) gap.unclassifiedTool = tool;
|
|
1473
|
+
if (classifiedPublicMcp) gap.noDestinationRule = tool;
|
|
1474
|
+
if (hard.length) {
|
|
1475
|
+
const all = [...hard, ...soft];
|
|
1476
|
+
return { verdict: "block", rules: all.map((r) => r[0]), reasons: all.map((r) => r[1]), pauseAgent, ...gap };
|
|
1477
|
+
}
|
|
1478
|
+
if (decisionRef) {
|
|
1479
|
+
return {
|
|
1480
|
+
verdict: "allow",
|
|
1481
|
+
rules: ["DECISION_MATCH"],
|
|
1482
|
+
decisionRef,
|
|
1483
|
+
pauseAgent,
|
|
1484
|
+
...gap,
|
|
1485
|
+
reasons: ["Matches an approved decision for exactly this recipient and content."]
|
|
1486
|
+
};
|
|
1487
|
+
}
|
|
1488
|
+
if (soft.length) return { verdict: "block", rules: soft.map((r) => r[0]), reasons: soft.map((r) => r[1]), pauseAgent, ...gap };
|
|
1489
|
+
if (ask) return { verdict: "ask", rules: [ask[0]], reasons: [ask[1]], pauseAgent, ...gap };
|
|
1490
|
+
return { verdict: "allow", rules: [], reasons: ["Within this agent's allowed tools and destinations."], pauseAgent, ...gap };
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
// src/offline.ts
|
|
1494
|
+
var MYLA_DIR = path6.join(os4.homedir(), ".myla");
|
|
1495
|
+
function keyFor(token) {
|
|
1496
|
+
return createHash("sha256").update(token).digest("hex").slice(0, 12);
|
|
1497
|
+
}
|
|
1498
|
+
function bundleName(token) {
|
|
1499
|
+
return `bundle-${keyFor(token)}.json`;
|
|
1500
|
+
}
|
|
1501
|
+
function segmentName(token) {
|
|
1502
|
+
return `segment-${keyFor(token)}.json`;
|
|
1503
|
+
}
|
|
1504
|
+
function bundleFile(token) {
|
|
1505
|
+
return path6.join(MYLA_DIR, bundleName(token));
|
|
1506
|
+
}
|
|
1507
|
+
function segmentFile(token) {
|
|
1508
|
+
return path6.join(MYLA_DIR, segmentName(token));
|
|
1509
|
+
}
|
|
1510
|
+
var LEGACY_BUNDLE = path6.join(MYLA_DIR, "bundle.json");
|
|
1511
|
+
var LEGACY_SEGMENT = path6.join(MYLA_DIR, "offline-segment.json");
|
|
1512
|
+
var SESSION_DIR = path6.join(MYLA_DIR, "sessions");
|
|
1513
|
+
var ONLINE_TIMEOUT_MS = 1200;
|
|
1514
|
+
function readJson(file) {
|
|
1515
|
+
try {
|
|
1516
|
+
return JSON.parse(fs6.readFileSync(file, "utf8"));
|
|
1517
|
+
} catch {
|
|
1518
|
+
return null;
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
function writeJson(file, value) {
|
|
1522
|
+
fs6.mkdirSync(path6.dirname(file), { recursive: true });
|
|
1523
|
+
const tmp = `${file}.tmp`;
|
|
1524
|
+
fs6.writeFileSync(tmp, JSON.stringify(value), { mode: 384 });
|
|
1525
|
+
fs6.renameSync(tmp, file);
|
|
1526
|
+
}
|
|
1527
|
+
function sessionFile(sessionId) {
|
|
1528
|
+
const safe = sessionId.replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 120);
|
|
1529
|
+
return path6.join(SESSION_DIR, `${safe}.json`);
|
|
1530
|
+
}
|
|
1531
|
+
function rememberSources(sessionId, sources) {
|
|
1532
|
+
if (!sessionId) return sources;
|
|
1533
|
+
const file = sessionFile(sessionId);
|
|
1534
|
+
const held = readJson(file)?.sources ?? [];
|
|
1535
|
+
const seen = new Set(held.map((s) => `${s.kind}:${s.label}`));
|
|
1536
|
+
const merged = [...held];
|
|
1537
|
+
for (const s of sources) {
|
|
1538
|
+
const key = `${s.kind}:${s.label}`;
|
|
1539
|
+
if (!seen.has(key)) {
|
|
1540
|
+
seen.add(key);
|
|
1541
|
+
merged.push(s);
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
const capped = merged.slice(-200);
|
|
1545
|
+
try {
|
|
1546
|
+
writeJson(file, { sources: capped, at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
1547
|
+
} catch {
|
|
1548
|
+
}
|
|
1549
|
+
return capped;
|
|
1550
|
+
}
|
|
1551
|
+
function loadBundle(token, now = Date.now()) {
|
|
1552
|
+
const bundle = readJson(bundleFile(token)) ?? readJson(LEGACY_BUNDLE);
|
|
1553
|
+
if (!bundle || !verifyBundle(bundle, token)) return null;
|
|
1554
|
+
return { bundle, stale: bundleStale(bundle, now) };
|
|
1555
|
+
}
|
|
1556
|
+
async function fetchBundle(origin, token) {
|
|
1557
|
+
try {
|
|
1558
|
+
const res = await fetch(`${origin}/api/security/gate/bundle`, {
|
|
1559
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
1560
|
+
signal: AbortSignal.timeout(8e3)
|
|
1561
|
+
});
|
|
1562
|
+
if (!res.ok) return null;
|
|
1563
|
+
const bundle = await res.json();
|
|
1564
|
+
if (!verifyBundle(bundle, token)) return null;
|
|
1565
|
+
writeJson(bundleFile(token), bundle);
|
|
1566
|
+
return bundle;
|
|
1567
|
+
} catch {
|
|
1568
|
+
return null;
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
function appendSegment(token, seed, entry) {
|
|
1572
|
+
const held = readJson(segmentFile(token)) ?? readJson(LEGACY_SEGMENT);
|
|
1573
|
+
const segment = held && held.chain_seed === seed ? held : { chain_seed: seed, entries: [] };
|
|
1574
|
+
const prev = segment.entries.length ? segment.entries[segment.entries.length - 1].hash : seed;
|
|
1575
|
+
const seq = segment.entries.length + 1;
|
|
1576
|
+
const body = { ...entry, seq };
|
|
1577
|
+
const full = { ...body, hash: entryHash(prev, body) };
|
|
1578
|
+
segment.entries.push(full);
|
|
1579
|
+
try {
|
|
1580
|
+
writeJson(segmentFile(token), segment);
|
|
1581
|
+
} catch {
|
|
1582
|
+
}
|
|
1583
|
+
return full;
|
|
1584
|
+
}
|
|
1585
|
+
async function syncSegment(origin, token) {
|
|
1586
|
+
const segment = readJson(segmentFile(token)) ?? readJson(LEGACY_SEGMENT);
|
|
1587
|
+
if (!segment || segment.entries.length === 0) return { written: 0, verified: true };
|
|
1588
|
+
try {
|
|
1589
|
+
const res = await fetch(`${origin}/api/security/gate/offline-sync`, {
|
|
1590
|
+
method: "POST",
|
|
1591
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
|
1592
|
+
body: JSON.stringify(segment),
|
|
1593
|
+
signal: AbortSignal.timeout(15e3)
|
|
1594
|
+
});
|
|
1595
|
+
if (!res.ok) return null;
|
|
1596
|
+
const out3 = await res.json();
|
|
1597
|
+
if (out3.verified !== true || typeof out3.written !== "number") return null;
|
|
1598
|
+
try {
|
|
1599
|
+
fs6.rmSync(segmentFile(token), { force: true });
|
|
1600
|
+
} catch {
|
|
1601
|
+
}
|
|
1602
|
+
try {
|
|
1603
|
+
fs6.rmSync(LEGACY_SEGMENT, { force: true });
|
|
1604
|
+
} catch {
|
|
1605
|
+
}
|
|
1606
|
+
return { written: out3.written, verified: true };
|
|
1607
|
+
} catch {
|
|
1608
|
+
return null;
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
function decideLocally(token, ev, now = Date.now()) {
|
|
1612
|
+
const loaded = loadBundle(token, now);
|
|
1613
|
+
if (!loaded) return null;
|
|
1614
|
+
const { bundle, stale } = loaded;
|
|
1615
|
+
const sessionId = ev.session_id ?? null;
|
|
1616
|
+
const incoming = ev.sessionContext?.sources ?? [];
|
|
1617
|
+
const sources = rememberSources(sessionId, incoming);
|
|
1618
|
+
const sessionContext = {
|
|
1619
|
+
...ev.sessionContext,
|
|
1620
|
+
sources,
|
|
1621
|
+
dataClasses: ev.sessionContext?.dataClasses ?? []
|
|
1622
|
+
};
|
|
1623
|
+
const result = evaluatePolicy({
|
|
1624
|
+
agent: bundle.agent,
|
|
1625
|
+
tool: ev.tool,
|
|
1626
|
+
args: ev.args ?? {},
|
|
1627
|
+
toolDescriptionSha256: ev.toolDescriptionSha256 ?? null,
|
|
1628
|
+
sessionContext,
|
|
1629
|
+
pins: bundle.pins,
|
|
1630
|
+
grants: bundle.grants,
|
|
1631
|
+
classifications: bundle.classifications
|
|
1632
|
+
});
|
|
1633
|
+
const entry = appendSegment(token, bundle.chain_seed, {
|
|
1634
|
+
at: new Date(now).toISOString(),
|
|
1635
|
+
agent_id: bundle.agent.id,
|
|
1636
|
+
tool: ev.tool,
|
|
1637
|
+
verdict: result.verdict,
|
|
1638
|
+
reasons: result.reasons,
|
|
1639
|
+
rules: result.rules,
|
|
1640
|
+
stale,
|
|
1641
|
+
session_id: sessionId
|
|
1642
|
+
});
|
|
1643
|
+
return {
|
|
1644
|
+
verdict: result.verdict,
|
|
1645
|
+
reasons: [...new Set(result.reasons)],
|
|
1646
|
+
rules: [...new Set(result.rules)],
|
|
1647
|
+
where: "local",
|
|
1648
|
+
stale,
|
|
1649
|
+
decided: entry.seq > 0
|
|
1650
|
+
};
|
|
1651
|
+
}
|
|
1652
|
+
function installDecider() {
|
|
1653
|
+
const self = process.argv[1];
|
|
1654
|
+
if (!self) return null;
|
|
1655
|
+
try {
|
|
1656
|
+
if (!fs6.statSync(self).isFile()) return null;
|
|
1657
|
+
} catch {
|
|
1658
|
+
return null;
|
|
1659
|
+
}
|
|
1660
|
+
const target = path6.join(MYLA_DIR, "decider.mjs");
|
|
1661
|
+
try {
|
|
1662
|
+
fs6.mkdirSync(MYLA_DIR, { recursive: true });
|
|
1663
|
+
fs6.copyFileSync(path6.resolve(self), target);
|
|
1664
|
+
fs6.chmodSync(target, 448);
|
|
1665
|
+
return target;
|
|
1666
|
+
} catch {
|
|
1667
|
+
return null;
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
function tokenFromInstalledConfig(client) {
|
|
1671
|
+
const fromHook = tokenFromHookConfig(client);
|
|
1672
|
+
if (fromHook) return fromHook;
|
|
1673
|
+
try {
|
|
1674
|
+
const creds = JSON.parse(fs6.readFileSync(path6.join(MYLA_DIR, "credentials.json"), "utf8"));
|
|
1675
|
+
if (typeof creds.token === "string" && creds.token.length >= 16) return creds.token;
|
|
1676
|
+
} catch {
|
|
1677
|
+
}
|
|
1678
|
+
return null;
|
|
1679
|
+
}
|
|
1680
|
+
function tokenFromHookConfig(client) {
|
|
1681
|
+
try {
|
|
1682
|
+
const inst = hookInstall(client, "https://mylasecurity.app", "x");
|
|
1683
|
+
const file = resolveUserPath(inst.perUserPath);
|
|
1684
|
+
const raw = fs6.readFileSync(file, "utf8");
|
|
1685
|
+
const m = raw.match(/Bearer\s+([^\s"'\\]+)/);
|
|
1686
|
+
return m && m[1] && m[1] !== "x" ? m[1] : null;
|
|
1687
|
+
} catch {
|
|
1688
|
+
return null;
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
// src/log.ts
|
|
1693
|
+
import fs7 from "node:fs";
|
|
1694
|
+
import path7 from "node:path";
|
|
1695
|
+
function readJson2(file) {
|
|
1696
|
+
try {
|
|
1697
|
+
return JSON.parse(fs7.readFileSync(file, "utf8"));
|
|
1698
|
+
} catch {
|
|
1699
|
+
return null;
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
function localView(token, now = Date.now()) {
|
|
1703
|
+
const signed = readJson2(bundleFile(token)) ?? readJson2(path7.join(MYLA_DIR, "bundle.json"));
|
|
1704
|
+
const segment = readJson2(segmentFile(token)) ?? readJson2(path7.join(MYLA_DIR, "offline-segment.json"));
|
|
1705
|
+
const entries = Array.isArray(segment?.entries) ? segment.entries : [];
|
|
1706
|
+
let rules = null;
|
|
1707
|
+
if (signed && typeof signed.issued_at === "string") {
|
|
1708
|
+
const verified = verifyBundle(signed, token);
|
|
1709
|
+
const issued = Date.parse(signed.issued_at);
|
|
1710
|
+
rules = {
|
|
1711
|
+
agent: signed.agent?.name ?? "this agent",
|
|
1712
|
+
mode: signed.gate_mode ?? "observe",
|
|
1713
|
+
allowed: Array.isArray(signed.agent?.allowed_tools) ? signed.agent.allowed_tools : [],
|
|
1714
|
+
destinations: Array.isArray(signed.agent?.egress_allowlist) ? signed.agent.egress_allowlist : [],
|
|
1715
|
+
issuedAt: signed.issued_at,
|
|
1716
|
+
ageMs: Number.isFinite(issued) ? now - issued : 0,
|
|
1717
|
+
stale: bundleStale(signed, now),
|
|
1718
|
+
verified
|
|
1719
|
+
};
|
|
1720
|
+
}
|
|
1721
|
+
return {
|
|
1722
|
+
rules,
|
|
1723
|
+
decisions: entries,
|
|
1724
|
+
chain: segment ? verifySegment(segment.chain_seed, entries) : null
|
|
1725
|
+
};
|
|
1726
|
+
}
|
|
1727
|
+
function hours(ms) {
|
|
1728
|
+
const m = Math.floor(ms / 6e4);
|
|
1729
|
+
if (m < 1) return "just now";
|
|
1730
|
+
if (m < 60) return `${m} min ago`;
|
|
1731
|
+
const h = Math.floor(m / 60);
|
|
1732
|
+
if (h < 24) return `${h} h ago`;
|
|
1733
|
+
const d = Math.floor(h / 24);
|
|
1734
|
+
return d === 1 ? "yesterday" : `${d} days ago`;
|
|
1735
|
+
}
|
|
1736
|
+
var COL3 = 30;
|
|
1737
|
+
var row3 = (label, value) => ` ${label}`.padEnd(COL3) + value;
|
|
1738
|
+
function renderLog(v, now = Date.now()) {
|
|
1739
|
+
const out3 = ["", " Myla \xB7 what this machine knows", ""];
|
|
1740
|
+
if (!v.rules) {
|
|
1741
|
+
out3.push(row3("\u2022 Rules on this machine", "none"));
|
|
1742
|
+
out3.push("");
|
|
1743
|
+
out3.push(" Nothing has been taken down to this machine, so nothing here can decide for itself.");
|
|
1744
|
+
out3.push(" Next time you are online: npx @mylasecurity/gate sync");
|
|
1745
|
+
out3.push("");
|
|
1746
|
+
return out3;
|
|
1747
|
+
}
|
|
1748
|
+
if (!v.rules.verified) {
|
|
1749
|
+
out3.push(row3("\u2717 Rules on this machine", "present, but they do NOT verify"));
|
|
1750
|
+
out3.push("");
|
|
1751
|
+
out3.push(" The file has been changed since Myla signed it, so nothing on this machine is using it.");
|
|
1752
|
+
out3.push(" Calls are going through unchecked until you run: npx @mylasecurity/gate sync");
|
|
1753
|
+
out3.push("");
|
|
1754
|
+
return out3;
|
|
1755
|
+
}
|
|
1756
|
+
out3.push(row3("\u2713 Rules on this machine", `${v.rules.agent}, taken ${hours(v.rules.ageMs)}`));
|
|
1757
|
+
out3.push(row3(v.rules.stale ? "! Age" : "\u2022 Age", v.rules.stale ? "past their life, so decisions are marked stale" : "within their life"));
|
|
1758
|
+
out3.push(row3("\u2022 Mode", v.rules.mode === "enforce" ? "enforce: a call it blocks is refused" : `${v.rules.mode}: it records, and refuses nothing`));
|
|
1759
|
+
out3.push(row3("\u2022 May use", v.rules.allowed.length ? v.rules.allowed.join(", ") : "nothing has been allowed"));
|
|
1760
|
+
if (v.rules.destinations.length) out3.push(row3("\u2022 May reach", v.rules.destinations.join(", ")));
|
|
1761
|
+
out3.push("");
|
|
1762
|
+
if (v.decisions.length === 0) {
|
|
1763
|
+
out3.push(row3("\u2022 Decided here", "nothing since the last hand-over"));
|
|
1764
|
+
out3.push("");
|
|
1765
|
+
return out3;
|
|
1766
|
+
}
|
|
1767
|
+
const blocks = v.decisions.filter((d) => d.verdict === "block").length;
|
|
1768
|
+
const asks = v.decisions.filter((d) => d.verdict === "ask").length;
|
|
1769
|
+
const allows = v.decisions.length - blocks - asks;
|
|
1770
|
+
out3.push(row3("\u2022 Decided here", `${v.decisions.length} waiting to hand over \xB7 ${blocks} blocked, ${asks} asked, ${allows} allowed`));
|
|
1771
|
+
out3.push(row3(v.chain?.ok ? "\u2713 Record" : "\u2717 Record", v.chain?.ok ? "the chain verifies" : `the chain breaks at entry ${v.chain && !v.chain.ok ? v.chain.at : "?"}, ${v.chain && !v.chain.ok ? v.chain.why : "unknown"}`));
|
|
1772
|
+
out3.push("");
|
|
1773
|
+
for (const d of [...v.decisions].reverse().slice(0, 20)) {
|
|
1774
|
+
const when = hours(now - Date.parse(d.at));
|
|
1775
|
+
const mark = d.verdict === "block" ? "[BLOCK]" : d.verdict === "ask" ? "[ASK] " : "[ALLOW]";
|
|
1776
|
+
out3.push(` ${mark} ${d.tool}${d.stale ? " \xB7 stale rules" : ""} \xB7 ${when}`);
|
|
1777
|
+
if (d.reasons[0]) out3.push(` ${d.reasons[0]}`);
|
|
1778
|
+
}
|
|
1779
|
+
if (v.decisions.length > 20) out3.push(` \u2026 and ${v.decisions.length - 20} more`);
|
|
1780
|
+
out3.push("");
|
|
1781
|
+
out3.push(" Next time you are online: npx @mylasecurity/gate sync");
|
|
1782
|
+
out3.push("");
|
|
1783
|
+
return out3;
|
|
1784
|
+
}
|
|
1785
|
+
var esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
1786
|
+
function renderHtml(v, now = Date.now()) {
|
|
1787
|
+
const head = `<!doctype html><html lang="en"><head><meta charset="utf-8">
|
|
1788
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1789
|
+
<!--
|
|
1790
|
+
AD171 - this page is LIVE. The decider rewrites it after every decision it makes alone, and the
|
|
1791
|
+
page reloads itself, so a tab left open is a working Myla with no network at all: the thing
|
|
1792
|
+
somebody actually means by "it kept working". A meta refresh rather than a script, because the
|
|
1793
|
+
page stays scriptless and has to open from a file on a machine that may block scripts in local
|
|
1794
|
+
pages entirely.
|
|
1795
|
+
-->
|
|
1796
|
+
<meta http-equiv="refresh" content="10">
|
|
1797
|
+
<title>Myla \xB7 on this machine</title>
|
|
1798
|
+
<style>
|
|
1799
|
+
:root { color-scheme: light dark; --ink:#16181D; --muted:#4A4D55; --bg:#F4F4F5; --card:#fff; --line:#E4E4E7; --accent:#2447C9; --danger:#B42318; --warn:#B8731F; }
|
|
1800
|
+
@media (prefers-color-scheme: dark) { :root { --ink:#F0F0F2; --muted:#9A9AA2; --bg:#15161A; --card:#1C1E24; --line:#2A2D35; --accent:#6E8CF8; --danger:#F97066; --warn:#E7A33E; } }
|
|
1801
|
+
* { box-sizing: border-box; }
|
|
1802
|
+
body { margin:0; padding:28px 18px 56px; background:var(--bg); color:var(--ink); font:15px/1.55 ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif; }
|
|
1803
|
+
.wrap { max-width:720px; margin:0 auto; }
|
|
1804
|
+
h1 { font-size:20px; margin:0 0 2px; }
|
|
1805
|
+
.sub { font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace; color:var(--muted); margin:0 0 20px; }
|
|
1806
|
+
.card { background:var(--card); border:1px solid var(--line); border-radius:12px; padding:14px 15px; margin-bottom:12px; }
|
|
1807
|
+
.k { font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace; letter-spacing:.09em; text-transform:uppercase; color:var(--muted); margin:0 0 6px; }
|
|
1808
|
+
.row { display:flex; gap:12px; padding:5px 0; border-top:1px solid var(--line); font-size:13.5px; }
|
|
1809
|
+
.row:first-of-type { border-top:0; }
|
|
1810
|
+
.row b { flex:0 0 130px; font-weight:600; color:var(--muted); font-size:12.5px; }
|
|
1811
|
+
.tag { font:10px/1 ui-monospace,SFMono-Regular,Menlo,monospace; font-weight:700; letter-spacing:.07em; padding:3px 5px; border-radius:4px; }
|
|
1812
|
+
.block { color:var(--danger); border:1px solid var(--danger); }
|
|
1813
|
+
.ask { color:var(--warn); border:1px solid var(--warn); }
|
|
1814
|
+
.allow { color:var(--muted); border:1px solid var(--line); }
|
|
1815
|
+
.d { display:flex; gap:9px; align-items:baseline; padding:8px 0; border-top:1px solid var(--line); }
|
|
1816
|
+
.d p { margin:2px 0 0; font-size:12.5px; color:var(--muted); }
|
|
1817
|
+
.when { margin-left:auto; font:11px/1 ui-monospace,monospace; color:var(--muted); white-space:nowrap; }
|
|
1818
|
+
.bad { color:var(--danger); }
|
|
1819
|
+
footer { font:12px/1.6 ui-monospace,monospace; color:var(--muted); margin-top:18px; }
|
|
1820
|
+
</style></head><body><div class="wrap">
|
|
1821
|
+
<h1>What this machine knows</h1>
|
|
1822
|
+
<p class="sub">read from ~/.myla \xB7 no network was used to build this page \xB7 as of ${new Date(now).toLocaleTimeString()}</p>`;
|
|
1823
|
+
if (!v.rules) {
|
|
1824
|
+
return `${head}<div class="card"><p class="k">Rules on this machine</p><p>None. Nothing has been taken down here, so nothing on this machine can decide for itself.</p></div>
|
|
1825
|
+
<footer>Next time you are online: npx @mylasecurity/gate sync</footer></div></body></html>`;
|
|
1826
|
+
}
|
|
1827
|
+
if (!v.rules.verified) {
|
|
1828
|
+
return `${head}<div class="card"><p class="k bad">Rules on this machine</p><p class="bad">Present, but they do not verify.</p>
|
|
1829
|
+
<p>The file has been changed since Myla signed it, so nothing on this machine is using it. Calls are going through unchecked.</p></div>
|
|
1830
|
+
<footer>Next time you are online: npx @mylasecurity/gate sync</footer></div></body></html>`;
|
|
1831
|
+
}
|
|
1832
|
+
const r = v.rules;
|
|
1833
|
+
const rules = `<div class="card"><p class="k">Rules on this machine</p>
|
|
1834
|
+
<div class="row"><b>Agent</b><span>${esc(r.agent)}</span></div>
|
|
1835
|
+
<div class="row"><b>Taken</b><span>${hours(r.ageMs)}${r.stale ? ' \xB7 <span class="bad">past their life, so decisions are marked stale</span>' : ""}</span></div>
|
|
1836
|
+
<div class="row"><b>Mode</b><span>${esc(r.mode)}${r.mode === "enforce" ? ": a call it blocks is refused" : ": it records, and refuses nothing"}</span></div>
|
|
1837
|
+
<div class="row"><b>May use</b><span>${r.allowed.length ? esc(r.allowed.join(", ")) : "nothing has been allowed"}</span></div>
|
|
1838
|
+
${r.destinations.length ? `<div class="row"><b>May reach</b><span>${esc(r.destinations.join(", "))}</span></div>` : ""}
|
|
1839
|
+
</div>`;
|
|
1840
|
+
const chainLine = v.chain?.ok ? "The chain verifies." : v.chain ? `<span class="bad">The chain breaks at entry ${v.chain.at}, ${esc(v.chain.why)}.</span>` : "";
|
|
1841
|
+
const list = v.decisions.length === 0 ? '<div class="card"><p class="k">Decided here</p><p>Nothing since the last hand-over.</p></div>' : `<div class="card"><p class="k">Decided here \xB7 ${v.decisions.length} waiting to hand over</p>
|
|
1842
|
+
<p style="margin:0 0 6px;font-size:12.5px;color:var(--muted)">${chainLine}</p>
|
|
1843
|
+
${[...v.decisions].reverse().map((d) => {
|
|
1844
|
+
const cls = d.verdict === "block" ? "block" : d.verdict === "ask" ? "ask" : "allow";
|
|
1845
|
+
return `<div class="d"><span class="tag ${cls}">${d.verdict.toUpperCase()}</span>
|
|
1846
|
+
<div><strong>${esc(d.tool)}</strong>${d.stale ? ' <span class="bad">\xB7 stale rules</span>' : ""}${d.reasons[0] ? `<p>${esc(d.reasons[0])}</p>` : ""}</div>
|
|
1847
|
+
<span class="when">${hours(now - Date.parse(d.at))}</span></div>`;
|
|
1848
|
+
}).join("")}</div>`;
|
|
1849
|
+
return `${head}${rules}${list}<footer>Next time you are online: npx @mylasecurity/gate sync</footer></div></body></html>`;
|
|
1850
|
+
}
|
|
1851
|
+
function refreshLocalPage(token, now = Date.now()) {
|
|
1852
|
+
try {
|
|
1853
|
+
fs7.mkdirSync(MYLA_DIR, { recursive: true });
|
|
1854
|
+
fs7.writeFileSync(path7.join(MYLA_DIR, "on-this-machine.html"), renderHtml(localView(token, now), now), { mode: 384 });
|
|
1855
|
+
} catch {
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
function runLog(io, opts) {
|
|
1859
|
+
const v = localView(opts.token, opts.now);
|
|
1860
|
+
if (!opts.html) {
|
|
1861
|
+
for (const line of renderLog(v, opts.now)) io.out(line);
|
|
1862
|
+
return 0;
|
|
1863
|
+
}
|
|
1864
|
+
const file = path7.join(MYLA_DIR, "on-this-machine.html");
|
|
1865
|
+
try {
|
|
1866
|
+
fs7.mkdirSync(MYLA_DIR, { recursive: true });
|
|
1867
|
+
fs7.writeFileSync(file, renderHtml(v, opts.now), { mode: 384 });
|
|
1868
|
+
} catch (e) {
|
|
1869
|
+
io.err(`Could not write ${file}: ${e instanceof Error ? e.message : String(e)}`);
|
|
1870
|
+
return 1;
|
|
1871
|
+
}
|
|
1872
|
+
io.out(`Wrote ${file}`);
|
|
1873
|
+
io.out("Open it in a browser. It needs no network.");
|
|
1874
|
+
return 0;
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
// src/notice.ts
|
|
1878
|
+
import { spawn } from "node:child_process";
|
|
1879
|
+
import fs8 from "node:fs";
|
|
1880
|
+
import path8 from "node:path";
|
|
1881
|
+
var NOTICE_FILE = path8.join(MYLA_DIR, "notice.json");
|
|
1882
|
+
var NOTICE_WINDOW_MS = 6e4;
|
|
1883
|
+
function safeForNotice(s, max = 48) {
|
|
1884
|
+
const cleaned = s.replace(/[^A-Za-z0-9 ._-]/g, "").trim();
|
|
1885
|
+
return cleaned.length > max ? cleaned.slice(0, max) : cleaned;
|
|
1886
|
+
}
|
|
1887
|
+
function dueForNotice(now = Date.now()) {
|
|
1888
|
+
let last = 0;
|
|
1889
|
+
try {
|
|
1890
|
+
last = JSON.parse(fs8.readFileSync(NOTICE_FILE, "utf8")).at ?? 0;
|
|
1891
|
+
} catch {
|
|
1892
|
+
}
|
|
1893
|
+
if (now - last < NOTICE_WINDOW_MS) return false;
|
|
1894
|
+
try {
|
|
1895
|
+
fs8.mkdirSync(MYLA_DIR, { recursive: true });
|
|
1896
|
+
fs8.writeFileSync(NOTICE_FILE, JSON.stringify({ at: now }));
|
|
1897
|
+
} catch {
|
|
1898
|
+
}
|
|
1899
|
+
return true;
|
|
1900
|
+
}
|
|
1901
|
+
function noticeCommand(platform, title, body) {
|
|
1902
|
+
const t = safeForNotice(title, 32);
|
|
1903
|
+
const b = safeForNotice(body, 96);
|
|
1904
|
+
if (platform === "darwin") {
|
|
1905
|
+
return { bin: "osascript", args: ["-e", `display notification "${b}" with title "${t}"`] };
|
|
1906
|
+
}
|
|
1907
|
+
if (platform === "linux") {
|
|
1908
|
+
return { bin: "notify-send", args: ["--app-name=Myla", t, b] };
|
|
1909
|
+
}
|
|
1910
|
+
return null;
|
|
1911
|
+
}
|
|
1912
|
+
function noticeBlocked(tool, opts = {}) {
|
|
1913
|
+
const platform = opts.platform ?? process.platform;
|
|
1914
|
+
const cmd = noticeCommand(platform, "Myla", `Blocked ${safeForNotice(tool)} on this machine. Myla was unreachable.`);
|
|
1915
|
+
if (!cmd) return "unsupported";
|
|
1916
|
+
if (!dueForNotice(opts.now)) return "rate-limited";
|
|
1917
|
+
try {
|
|
1918
|
+
const child = (opts.spawnImpl ?? spawn)(cmd.bin, cmd.args, { detached: true, stdio: "ignore" });
|
|
1919
|
+
child.on?.("error", () => {
|
|
1920
|
+
});
|
|
1921
|
+
child.unref?.();
|
|
1922
|
+
} catch {
|
|
1923
|
+
}
|
|
1924
|
+
return "sent";
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
// src/decide.ts
|
|
1928
|
+
function readStdin() {
|
|
1929
|
+
return new Promise((resolve) => {
|
|
1930
|
+
let data = "";
|
|
1931
|
+
process.stdin.setEncoding("utf8");
|
|
1932
|
+
process.stdin.on("data", (chunk) => {
|
|
1933
|
+
data += chunk;
|
|
1934
|
+
});
|
|
1935
|
+
process.stdin.on("end", () => resolve(data));
|
|
1936
|
+
process.stdin.on("error", () => resolve(""));
|
|
1937
|
+
});
|
|
1938
|
+
}
|
|
1939
|
+
async function runDecide(opts, io) {
|
|
1940
|
+
const client = opts.client;
|
|
1941
|
+
if (!isHookClient(client)) {
|
|
1942
|
+
io.err(`Unknown client: ${client}`);
|
|
1943
|
+
return 2;
|
|
1944
|
+
}
|
|
1945
|
+
const adapter = HOOK_ADAPTERS[client];
|
|
1946
|
+
if (isUnsupported(adapter)) {
|
|
1947
|
+
io.err(adapter.unsupported);
|
|
1948
|
+
return 2;
|
|
1949
|
+
}
|
|
1950
|
+
let body;
|
|
1951
|
+
try {
|
|
1952
|
+
body = JSON.parse(opts.stdin);
|
|
1953
|
+
} catch {
|
|
1954
|
+
body = null;
|
|
1955
|
+
}
|
|
1956
|
+
const parsed = body === null ? null : adapter.parse(body);
|
|
1957
|
+
if (!parsed) {
|
|
1958
|
+
io.out(JSON.stringify(adapter.render({ result: allowResult(), ledgerId: 0, notified: 0 }, true)));
|
|
1959
|
+
return 0;
|
|
1960
|
+
}
|
|
1961
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
1962
|
+
try {
|
|
1963
|
+
const res = await doFetch(`${opts.origin}/api/security/gate/hook/${client}`, {
|
|
1964
|
+
method: "POST",
|
|
1965
|
+
headers: { Authorization: `Bearer ${opts.token}`, "Content-Type": "application/json" },
|
|
1966
|
+
body: opts.stdin,
|
|
1967
|
+
signal: AbortSignal.timeout(ONLINE_TIMEOUT_MS)
|
|
1968
|
+
});
|
|
1969
|
+
if (res.ok) {
|
|
1970
|
+
const answer = await res.text();
|
|
1971
|
+
io.out(answer);
|
|
1972
|
+
void syncSegment(opts.origin, opts.token);
|
|
1973
|
+
void fetchBundle(opts.origin, opts.token);
|
|
1974
|
+
return 0;
|
|
1975
|
+
}
|
|
1976
|
+
} catch {
|
|
1977
|
+
}
|
|
1978
|
+
const local = decideLocally(opts.token, {
|
|
1979
|
+
tool: parsed.req.tool,
|
|
1980
|
+
args: parsed.req.args,
|
|
1981
|
+
session_id: parsed.source?.session_id ?? null,
|
|
1982
|
+
toolDescriptionSha256: parsed.req.toolDescriptionSha256 ?? null,
|
|
1983
|
+
sessionContext: parsed.req.sessionContext
|
|
1984
|
+
}, opts.now);
|
|
1985
|
+
if (!local) {
|
|
1986
|
+
io.err("Myla: no local policy bundle, so this call was not evaluated. Run: npx @mylasecurity/gate sync");
|
|
1987
|
+
io.out(JSON.stringify(adapter.render({ result: allowResult(), ledgerId: 0, notified: 0 }, true)));
|
|
1988
|
+
return 0;
|
|
1989
|
+
}
|
|
1990
|
+
const bundle = loadBundle(opts.token, opts.now);
|
|
1991
|
+
const observeOnly = bundle?.bundle.gate_mode !== "enforce";
|
|
1992
|
+
const result = {
|
|
1993
|
+
verdict: local.verdict,
|
|
1994
|
+
reasons: local.reasons,
|
|
1995
|
+
// The IDS, not the sentences. These were the same array for an afternoon, which put
|
|
1996
|
+
// "Claude Code isn't allowed to use Bash." in a field every consumer reads as a rule id.
|
|
1997
|
+
rules: local.rules,
|
|
1998
|
+
pauseAgent: false
|
|
1999
|
+
};
|
|
2000
|
+
io.out(JSON.stringify(adapter.render({ result, ledgerId: 0, notified: 0 }, observeOnly)));
|
|
2001
|
+
refreshLocalPage(opts.token, opts.now);
|
|
2002
|
+
if (local.verdict === "block" && !observeOnly) noticeBlocked(parsed.req.tool, { now: opts.now });
|
|
2003
|
+
if (local.verdict !== "allow" && !observeOnly) {
|
|
2004
|
+
io.err(`Myla decided this on your machine${local.stale ? " (rules are past their refresh window)" : ""}: ${local.verdict} \u2014 ${local.reasons.join(", ")}`);
|
|
2005
|
+
}
|
|
2006
|
+
return 0;
|
|
2007
|
+
}
|
|
2008
|
+
function allowResult() {
|
|
2009
|
+
return { verdict: "allow", reasons: [], rules: [], pauseAgent: false };
|
|
2010
|
+
}
|
|
2011
|
+
async function runSync(origin, token, io) {
|
|
2012
|
+
const synced = await syncSegment(origin, token);
|
|
2013
|
+
if (!synced) {
|
|
2014
|
+
io.err("Could not reach Myla, so nothing was handed over. The record is still on this machine.");
|
|
2015
|
+
return 1;
|
|
2016
|
+
}
|
|
2017
|
+
const bundle = await fetchBundle(origin, token);
|
|
2018
|
+
io.out(synced.written > 0 ? `Handed over ${synced.written} decision${synced.written === 1 ? "" : "s"} made offline${synced.verified ? "" : " (the local chain was broken, and they are recorded as unverified)"}.` : "Nothing was decided offline since the last sync.");
|
|
2019
|
+
io.out(bundle ? "Rules refreshed." : "Could not refresh the rules; the ones on this machine stay in force until they expire.");
|
|
2020
|
+
return 0;
|
|
2021
|
+
}
|
|
2022
|
+
|
|
2023
|
+
// src/offline-mode.ts
|
|
2024
|
+
import fs9 from "node:fs";
|
|
2025
|
+
import path9 from "node:path";
|
|
2026
|
+
var CREDENTIALS_FILE = path9.join(MYLA_DIR, "credentials.json");
|
|
2027
|
+
var DECIDER_FILE = path9.join(MYLA_DIR, "decider.mjs");
|
|
2028
|
+
function decideCommand(client, origin, decider = DECIDER_FILE) {
|
|
2029
|
+
const originFlag = origin && origin !== "https://mylasecurity.app" ? ` --origin ${origin}` : "";
|
|
2030
|
+
return `node ${decider} decide --client ${client}${originFlag}`;
|
|
2031
|
+
}
|
|
2032
|
+
function offlineHookConfig(client, origin, token, decider = DECIDER_FILE) {
|
|
2033
|
+
const shipped = JSON.parse(hookInstall(client, origin, token).config);
|
|
2034
|
+
const cmd = { type: "command", command: decideCommand(client, origin, decider) };
|
|
2035
|
+
const hooks = shipped.hooks ?? shipped;
|
|
2036
|
+
const decisions = client === "cursor" ? ["beforeShellExecution", "beforeMCPExecution"] : ["PreToolUse"];
|
|
2037
|
+
for (const key of decisions) {
|
|
2038
|
+
const groups = hooks[key];
|
|
2039
|
+
if (!Array.isArray(groups)) continue;
|
|
2040
|
+
hooks[key] = groups.map((g) => {
|
|
2041
|
+
const group = g;
|
|
2042
|
+
if (Array.isArray(group.hooks)) return { ...group, hooks: group.hooks.map(() => ({ ...cmd })) };
|
|
2043
|
+
return { ...group, ...{ command: cmd.command } };
|
|
2044
|
+
});
|
|
2045
|
+
}
|
|
2046
|
+
return shipped;
|
|
2047
|
+
}
|
|
2048
|
+
function runOffline(io, opts) {
|
|
2049
|
+
const inst = hookInstall(opts.client, opts.origin, "x");
|
|
2050
|
+
const file = resolveUserPath(inst.perUserPath);
|
|
2051
|
+
if (!opts.on) {
|
|
2052
|
+
io.out("To go back to the hosted Gate, reinstall it: npx @mylasecurity/gate install <claim-code>");
|
|
2053
|
+
io.out("That rewrites the hook to call Myla directly, and local mode stops being used.");
|
|
2054
|
+
io.out(`Your offline records stay in ${MYLA_DIR} until they sync.`);
|
|
2055
|
+
return 0;
|
|
2056
|
+
}
|
|
2057
|
+
const token = tokenFromInstalledConfig(opts.client);
|
|
2058
|
+
if (!token) {
|
|
2059
|
+
io.err(`No Myla hook found in ${inst.perUserPath}. Install the Gate first: npx @mylasecurity/gate install <claim-code>`);
|
|
2060
|
+
return 1;
|
|
2061
|
+
}
|
|
2062
|
+
const existing = fs9.existsSync(file) ? fs9.readFileSync(file, "utf8") : null;
|
|
2063
|
+
let merged;
|
|
2064
|
+
try {
|
|
2065
|
+
merged = mergeSettings({ existingRaw: existing, fetchedConfig: offlineHookConfig(opts.client, opts.origin, token), originHost: "mylasecurity.app" });
|
|
2066
|
+
} catch (e) {
|
|
2067
|
+
io.err(`Could not read ${inst.perUserPath}: ${e instanceof Error ? e.message : String(e)}. Nothing was changed.`);
|
|
2068
|
+
return 1;
|
|
2069
|
+
}
|
|
2070
|
+
io.out("Local mode puts the Gate on this machine:");
|
|
2071
|
+
io.out(" \u2022 Myla is still asked first, with a short timeout. Her answer wins when she is reachable.");
|
|
2072
|
+
io.out(" \u2022 When she is NOT reachable, the rules on this machine decide instead of the call going through unchecked.");
|
|
2073
|
+
io.out(" \u2022 What was decided offline is recorded here and handed over on the next sync.");
|
|
2074
|
+
io.out("");
|
|
2075
|
+
io.out(opts.client === "claude-code" ? " The cost, plainly: today your hook is an HTTP call and nothing runs on your machine. Local mode runs a command on every tool call instead. That is the trade." : " Your hook already runs a command on every tool call, so this swaps one command for another.");
|
|
2076
|
+
io.out("");
|
|
2077
|
+
if (opts.dryRun) {
|
|
2078
|
+
io.out(`Would write ${inst.perUserPath} (a backup first), with the hook pointing at:`);
|
|
2079
|
+
io.out(` ${decideCommand(opts.client, opts.origin)}`);
|
|
2080
|
+
io.out(" Your report hooks would be left exactly as they are: a report is not a decision.");
|
|
2081
|
+
io.out(`Would copy the decider to ${DECIDER_FILE} and store its credential at ${CREDENTIALS_FILE} (owner-read only).`);
|
|
2082
|
+
io.out("Nothing was written.");
|
|
2083
|
+
return 0;
|
|
2084
|
+
}
|
|
2085
|
+
if (!installDecider()) {
|
|
2086
|
+
io.err("Could not work out which file I am running from, so I will not point your hook at a guess. Nothing was changed.");
|
|
2087
|
+
return 1;
|
|
2088
|
+
}
|
|
2089
|
+
if (existing !== null) {
|
|
2090
|
+
const backup = nextBackupPath(file);
|
|
2091
|
+
fs9.copyFileSync(file, backup);
|
|
2092
|
+
io.out(`Backed up \u2192 ${backup}`);
|
|
2093
|
+
}
|
|
2094
|
+
fs9.mkdirSync(path9.dirname(file), { recursive: true });
|
|
2095
|
+
fs9.writeFileSync(file, merged.text);
|
|
2096
|
+
io.out(`Wrote ${inst.perUserPath}`);
|
|
2097
|
+
fs9.mkdirSync(MYLA_DIR, { recursive: true });
|
|
2098
|
+
fs9.writeFileSync(CREDENTIALS_FILE, JSON.stringify({ token, origin: opts.origin, client: opts.client }), { mode: 384 });
|
|
2099
|
+
io.out(`Stored the credential at ${CREDENTIALS_FILE} (owner-read only)`);
|
|
2100
|
+
io.out(`Installed the decider at ${DECIDER_FILE}`);
|
|
2101
|
+
io.out("");
|
|
2102
|
+
io.out(`Now run: node ${DECIDER_FILE} sync \u2014 to take the rules down to this machine.`);
|
|
2103
|
+
io.out(`Then quit ${inst.label} completely and open it again: hooks load at startup.`);
|
|
2104
|
+
return 0;
|
|
2105
|
+
}
|
|
2106
|
+
|
|
2107
|
+
// src/ask.ts
|
|
2108
|
+
var ASK_EXIT = { allow: 0, unevaluated: 1, ask: 2, block: 3 };
|
|
2109
|
+
function exitFor(a) {
|
|
2110
|
+
if (!a.decided) return ASK_EXIT.unevaluated;
|
|
2111
|
+
return a.verdict === "block" ? ASK_EXIT.block : a.verdict === "ask" ? ASK_EXIT.ask : ASK_EXIT.allow;
|
|
2112
|
+
}
|
|
2113
|
+
function parseAsk(raw) {
|
|
2114
|
+
let body;
|
|
2115
|
+
try {
|
|
2116
|
+
body = JSON.parse(raw);
|
|
2117
|
+
} catch {
|
|
2118
|
+
return null;
|
|
2119
|
+
}
|
|
2120
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return null;
|
|
2121
|
+
const o = body;
|
|
2122
|
+
if (typeof o.tool !== "string" || !o.tool.trim()) return null;
|
|
2123
|
+
if (!o.args || typeof o.args !== "object" || Array.isArray(o.args)) return null;
|
|
2124
|
+
return {
|
|
2125
|
+
tool: o.tool,
|
|
2126
|
+
args: o.args,
|
|
2127
|
+
session_id: typeof o.session_id === "string" ? o.session_id : null,
|
|
2128
|
+
toolDescriptionSha256: typeof o.toolDescriptionSha256 === "string" ? o.toolDescriptionSha256 : null,
|
|
2129
|
+
sessionContext: o.sessionContext && typeof o.sessionContext === "object" && !Array.isArray(o.sessionContext) ? o.sessionContext : void 0
|
|
2130
|
+
};
|
|
2131
|
+
}
|
|
2132
|
+
async function resolveVerdict(opts, req) {
|
|
2133
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
2134
|
+
try {
|
|
2135
|
+
const res = await doFetch(`${opts.origin}/api/security/gate/evaluate`, {
|
|
2136
|
+
method: "POST",
|
|
2137
|
+
headers: { Authorization: `Bearer ${opts.token}`, "Content-Type": "application/json" },
|
|
2138
|
+
body: JSON.stringify({ tool: req.tool, args: req.args, ...req.sessionContext ? { sessionContext: req.sessionContext } : {} }),
|
|
2139
|
+
signal: AbortSignal.timeout(ONLINE_TIMEOUT_MS)
|
|
2140
|
+
});
|
|
2141
|
+
if (res.ok) {
|
|
2142
|
+
const served = await res.json();
|
|
2143
|
+
const verdict = served.verdict === "block" || served.verdict === "ask" ? served.verdict : "allow";
|
|
2144
|
+
void syncSegment(opts.origin, opts.token);
|
|
2145
|
+
void fetchBundle(opts.origin, opts.token);
|
|
2146
|
+
return {
|
|
2147
|
+
verdict,
|
|
2148
|
+
reasons: Array.isArray(served.reasons) ? served.reasons.filter((x) => typeof x === "string") : [],
|
|
2149
|
+
rules: Array.isArray(served.rules) ? served.rules.filter((x) => typeof x === "string") : [],
|
|
2150
|
+
where: "server",
|
|
2151
|
+
stale: false,
|
|
2152
|
+
decided: true
|
|
2153
|
+
};
|
|
2154
|
+
}
|
|
2155
|
+
} catch {
|
|
2156
|
+
}
|
|
2157
|
+
const local = decideLocally(opts.token, {
|
|
2158
|
+
tool: req.tool,
|
|
2159
|
+
args: req.args,
|
|
2160
|
+
session_id: req.session_id ?? null,
|
|
2161
|
+
toolDescriptionSha256: req.toolDescriptionSha256 ?? null
|
|
2162
|
+
}, opts.now);
|
|
2163
|
+
if (!local) return null;
|
|
2164
|
+
return { verdict: local.verdict, reasons: local.reasons, rules: local.rules, where: "local", stale: local.stale, decided: true };
|
|
2165
|
+
}
|
|
2166
|
+
async function runAsk(opts, io) {
|
|
2167
|
+
const req = parseAsk(opts.stdin);
|
|
2168
|
+
if (!req) {
|
|
2169
|
+
const answer2 = {
|
|
2170
|
+
verdict: "allow",
|
|
2171
|
+
reasons: ["The Gate could not read this request."],
|
|
2172
|
+
rules: ["BAD_REQUEST"],
|
|
2173
|
+
where: "none",
|
|
2174
|
+
stale: false,
|
|
2175
|
+
decided: false
|
|
2176
|
+
};
|
|
2177
|
+
io.out(JSON.stringify(answer2));
|
|
2178
|
+
io.err('Myla: send one JSON object on stdin with at least {"tool": "...", "args": {...}}.');
|
|
2179
|
+
return ASK_EXIT.unevaluated;
|
|
2180
|
+
}
|
|
2181
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
2182
|
+
try {
|
|
2183
|
+
const res = await doFetch(`${opts.origin}/api/security/gate/evaluate`, {
|
|
2184
|
+
method: "POST",
|
|
2185
|
+
headers: { Authorization: `Bearer ${opts.token}`, "Content-Type": "application/json" },
|
|
2186
|
+
body: JSON.stringify({ tool: req.tool, args: req.args, ...req.sessionContext ? { sessionContext: req.sessionContext } : {} }),
|
|
2187
|
+
signal: AbortSignal.timeout(ONLINE_TIMEOUT_MS)
|
|
2188
|
+
});
|
|
2189
|
+
if (res.ok) {
|
|
2190
|
+
const served = await res.json();
|
|
2191
|
+
const verdict = served.verdict === "block" || served.verdict === "ask" ? served.verdict : "allow";
|
|
2192
|
+
const answer2 = {
|
|
2193
|
+
verdict,
|
|
2194
|
+
reasons: Array.isArray(served.reasons) ? served.reasons.filter((x) => typeof x === "string") : [],
|
|
2195
|
+
rules: Array.isArray(served.rules) ? served.rules.filter((x) => typeof x === "string") : [],
|
|
2196
|
+
where: "server",
|
|
2197
|
+
stale: false,
|
|
2198
|
+
decided: true
|
|
2199
|
+
};
|
|
2200
|
+
io.out(JSON.stringify(answer2));
|
|
2201
|
+
void syncSegment(opts.origin, opts.token);
|
|
2202
|
+
void fetchBundle(opts.origin, opts.token);
|
|
2203
|
+
return exitFor(answer2);
|
|
2204
|
+
}
|
|
2205
|
+
} catch {
|
|
2206
|
+
}
|
|
2207
|
+
const local = decideLocally(opts.token, {
|
|
2208
|
+
tool: req.tool,
|
|
2209
|
+
args: req.args,
|
|
2210
|
+
session_id: req.session_id ?? null,
|
|
2211
|
+
toolDescriptionSha256: req.toolDescriptionSha256 ?? null
|
|
2212
|
+
}, opts.now);
|
|
2213
|
+
if (!local) {
|
|
2214
|
+
const answer2 = {
|
|
2215
|
+
verdict: "allow",
|
|
2216
|
+
reasons: ["This machine has no rules for this agent, so the call was not evaluated."],
|
|
2217
|
+
rules: ["GATE_NOT_EVALUATED"],
|
|
2218
|
+
where: "none",
|
|
2219
|
+
stale: false,
|
|
2220
|
+
decided: false
|
|
2221
|
+
};
|
|
2222
|
+
io.out(JSON.stringify(answer2));
|
|
2223
|
+
io.err("Myla: no local policy bundle, so this call was not evaluated. Run: npx @mylasecurity/gate sync");
|
|
2224
|
+
return ASK_EXIT.unevaluated;
|
|
2225
|
+
}
|
|
2226
|
+
const answer = {
|
|
2227
|
+
verdict: local.verdict,
|
|
2228
|
+
reasons: local.reasons,
|
|
2229
|
+
rules: local.rules,
|
|
2230
|
+
where: "local",
|
|
2231
|
+
stale: local.stale,
|
|
2232
|
+
decided: true
|
|
2233
|
+
};
|
|
2234
|
+
io.out(JSON.stringify(answer));
|
|
2235
|
+
refreshLocalPage(opts.token, opts.now);
|
|
2236
|
+
if (local.verdict === "block") noticeBlocked(req.tool, { now: opts.now });
|
|
2237
|
+
if (local.verdict !== "allow") {
|
|
2238
|
+
io.err(`Myla decided this on your machine${local.stale ? " (rules are past their refresh window)" : ""}: ${local.verdict}, ${local.reasons.join(", ")}`);
|
|
2239
|
+
}
|
|
2240
|
+
return exitFor(answer);
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2243
|
+
// src/mcp.ts
|
|
2244
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
2245
|
+
function gateToolId(server, tool) {
|
|
2246
|
+
return `mcp__${server}__${tool}`;
|
|
2247
|
+
}
|
|
2248
|
+
function refusalMessage(id, reasons) {
|
|
2249
|
+
const text = reasons.length ? `${reasons.join(" ")} This is a policy decision made by the person who runs this machine, not a fault, and another tool or another route will be refused too. Stop and tell them.` : "Myla refused this call.";
|
|
2250
|
+
return JSON.stringify({
|
|
2251
|
+
jsonrpc: "2.0",
|
|
2252
|
+
id,
|
|
2253
|
+
result: { isError: true, content: [{ type: "text", text }] }
|
|
2254
|
+
});
|
|
2255
|
+
}
|
|
2256
|
+
function takeLines(buffer) {
|
|
2257
|
+
const parts = buffer.split("\n");
|
|
2258
|
+
const rest = parts.pop() ?? "";
|
|
2259
|
+
return { lines: parts.filter((l) => l.trim() !== ""), rest };
|
|
2260
|
+
}
|
|
2261
|
+
function toolCallIn(line) {
|
|
2262
|
+
let msg;
|
|
2263
|
+
try {
|
|
2264
|
+
msg = JSON.parse(line);
|
|
2265
|
+
} catch {
|
|
2266
|
+
return null;
|
|
2267
|
+
}
|
|
2268
|
+
if (msg.method !== "tools/call") return null;
|
|
2269
|
+
const name = typeof msg.params?.name === "string" ? msg.params.name : null;
|
|
2270
|
+
if (!name) return null;
|
|
2271
|
+
const args = msg.params?.arguments && typeof msg.params.arguments === "object" && !Array.isArray(msg.params.arguments) ? msg.params.arguments : {};
|
|
2272
|
+
return { id: msg.id ?? null, name, args };
|
|
2273
|
+
}
|
|
2274
|
+
async function runMcp(opts, io) {
|
|
2275
|
+
const child = (opts.spawnImpl ?? spawn2)(opts.command, opts.args, {
|
|
2276
|
+
stdio: ["pipe", "pipe", "inherit"]
|
|
2277
|
+
});
|
|
2278
|
+
const inStream = opts.streams?.stdin ?? process.stdin;
|
|
2279
|
+
const outStream = opts.streams?.stdout ?? process.stdout;
|
|
2280
|
+
child.stdout.pipe(outStream, { end: false });
|
|
2281
|
+
let buffer = "";
|
|
2282
|
+
let chain = Promise.resolve();
|
|
2283
|
+
let denied = 0;
|
|
2284
|
+
const handle = async (line) => {
|
|
2285
|
+
const call = toolCallIn(line);
|
|
2286
|
+
if (!call) {
|
|
2287
|
+
child.stdin.write(line + "\n");
|
|
2288
|
+
return;
|
|
2289
|
+
}
|
|
2290
|
+
const tool = gateToolId(opts.server, call.name);
|
|
2291
|
+
const answer = await resolveVerdict({ ...opts, stdin: "" }, { tool, args: call.args });
|
|
2292
|
+
if (!answer) {
|
|
2293
|
+
io.err(`Myla: no rules on this machine, so ${tool} was not evaluated. Run: npx @mylasecurity/gate sync`);
|
|
2294
|
+
child.stdin.write(line + "\n");
|
|
2295
|
+
return;
|
|
2296
|
+
}
|
|
2297
|
+
if (answer.verdict === "allow") {
|
|
2298
|
+
child.stdin.write(line + "\n");
|
|
2299
|
+
return;
|
|
2300
|
+
}
|
|
2301
|
+
const mode = loadBundle(opts.token, opts.now)?.bundle.gate_mode;
|
|
2302
|
+
if (mode !== "enforce") {
|
|
2303
|
+
io.err(`Myla would have refused ${tool} (${answer.reasons.join(" ")}), and did not: this agent is watching, not enforcing.`);
|
|
2304
|
+
child.stdin.write(line + "\n");
|
|
2305
|
+
return;
|
|
2306
|
+
}
|
|
2307
|
+
denied += 1;
|
|
2308
|
+
outStream.write(refusalMessage(call.id, answer.reasons) + "\n");
|
|
2309
|
+
io.err(`Myla ${answer.where === "local" ? "decided this on your machine" : "refused this"}: ${tool}, ${answer.reasons.join(" ")}`);
|
|
2310
|
+
if (answer.where === "local") {
|
|
2311
|
+
refreshLocalPage(opts.token, opts.now);
|
|
2312
|
+
noticeBlocked(call.name, { now: opts.now });
|
|
2313
|
+
}
|
|
2314
|
+
};
|
|
2315
|
+
inStream.on("data", (chunk) => {
|
|
2316
|
+
buffer += String(chunk);
|
|
2317
|
+
const { lines, rest } = takeLines(buffer);
|
|
2318
|
+
buffer = rest;
|
|
2319
|
+
for (const line of lines) chain = chain.then(() => handle(line)).catch(() => {
|
|
2320
|
+
});
|
|
2321
|
+
});
|
|
2322
|
+
inStream.on("end", () => {
|
|
2323
|
+
void chain.then(() => child.stdin.end());
|
|
2324
|
+
});
|
|
2325
|
+
return new Promise((resolve) => {
|
|
2326
|
+
child.on("error", (e) => {
|
|
2327
|
+
io.err(`Myla: could not start the MCP server (${opts.command}): ${e.message}`);
|
|
2328
|
+
resolve(1);
|
|
2329
|
+
});
|
|
2330
|
+
child.on("close", (code) => {
|
|
2331
|
+
if (denied > 0) io.err(`Myla refused ${denied} call${denied === 1 ? "" : "s"} on this server.`);
|
|
2332
|
+
resolve(code ?? 0);
|
|
2333
|
+
});
|
|
2334
|
+
});
|
|
2335
|
+
}
|
|
2336
|
+
|
|
2337
|
+
// src/mcp-install.ts
|
|
2338
|
+
import fs10 from "node:fs";
|
|
2339
|
+
import os5 from "node:os";
|
|
2340
|
+
import path10 from "node:path";
|
|
2341
|
+
var DECIDER = path10.join(MYLA_DIR, "decider.mjs");
|
|
2342
|
+
var MCP_CREDENTIALS = path10.join(MYLA_DIR, "mcp-credentials.json");
|
|
2343
|
+
function readMcpToken(file = MCP_CREDENTIALS) {
|
|
2344
|
+
try {
|
|
2345
|
+
const c = JSON.parse(fs10.readFileSync(file, "utf8"));
|
|
2346
|
+
return typeof c.token === "string" && c.token.length >= 16 ? c.token : null;
|
|
2347
|
+
} catch {
|
|
2348
|
+
return null;
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
2351
|
+
function mcpConfigPaths(home = os5.homedir(), platform = process.platform) {
|
|
2352
|
+
const mac = platform === "darwin";
|
|
2353
|
+
return [
|
|
2354
|
+
{ label: "Claude Desktop", file: mac ? path10.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json") : path10.join(home, ".config", "Claude", "claude_desktop_config.json") },
|
|
2355
|
+
{ label: "Claude Code", file: path10.join(home, ".claude.json") },
|
|
2356
|
+
{ label: "Cursor", file: path10.join(home, ".cursor", "mcp.json") }
|
|
2357
|
+
];
|
|
2358
|
+
}
|
|
2359
|
+
function isWrapped(entry) {
|
|
2360
|
+
if (typeof entry.command !== "string") return false;
|
|
2361
|
+
if (entry.command !== "node" && !entry.command.endsWith("/node") && !entry.command.endsWith("\\node.exe")) return false;
|
|
2362
|
+
const args = Array.isArray(entry.args) ? entry.args.filter((a) => typeof a === "string") : [];
|
|
2363
|
+
return args.length > 5 && args[0].endsWith(".mjs") && args[1] === "mcp" && args[2] === "--server" && args.indexOf("--") === 4;
|
|
2364
|
+
}
|
|
2365
|
+
function wrap(name, entry, decider = DECIDER) {
|
|
2366
|
+
if (isWrapped(entry)) return null;
|
|
2367
|
+
if (typeof entry.command !== "string" || !entry.command) return null;
|
|
2368
|
+
const args = Array.isArray(entry.args) ? entry.args.filter((a) => typeof a === "string") : [];
|
|
2369
|
+
return { ...entry, command: "node", args: [decider, "mcp", "--server", name, "--", entry.command, ...args] };
|
|
2370
|
+
}
|
|
2371
|
+
function unwrap(entry) {
|
|
2372
|
+
if (!isWrapped(entry)) return null;
|
|
2373
|
+
const args = Array.isArray(entry.args) ? entry.args.filter((a) => typeof a === "string") : [];
|
|
2374
|
+
const i = args.indexOf("--");
|
|
2375
|
+
if (i < 0 || i === args.length - 1) return null;
|
|
2376
|
+
return { ...entry, command: args[i + 1], args: args.slice(i + 2) };
|
|
2377
|
+
}
|
|
2378
|
+
function mcpStatus(home, platform) {
|
|
2379
|
+
return mcpConfigPaths(home, platform).map(({ label, file }) => {
|
|
2380
|
+
let doc;
|
|
2381
|
+
try {
|
|
2382
|
+
doc = JSON.parse(fs10.readFileSync(file, "utf8"));
|
|
2383
|
+
} catch {
|
|
2384
|
+
return { label, file, present: false, gated: [], bare: [] };
|
|
2385
|
+
}
|
|
2386
|
+
const servers = doc.mcpServers;
|
|
2387
|
+
if (!servers || typeof servers !== "object") return { label, file, present: true, gated: [], bare: [] };
|
|
2388
|
+
const gated = [];
|
|
2389
|
+
const bare = [];
|
|
2390
|
+
for (const [name, entry] of Object.entries(servers)) {
|
|
2391
|
+
if (!entry || typeof entry !== "object") continue;
|
|
2392
|
+
(isWrapped(entry) ? gated : bare).push(name);
|
|
2393
|
+
}
|
|
2394
|
+
return { label, file, present: true, gated, bare };
|
|
2395
|
+
});
|
|
2396
|
+
}
|
|
2397
|
+
function renderMcpStatus(files, hasCredential) {
|
|
2398
|
+
const out3 = [];
|
|
2399
|
+
const seen = files.filter((f) => f.present);
|
|
2400
|
+
if (seen.length === 0) {
|
|
2401
|
+
out3.push("No MCP configuration found on this machine, in any of:");
|
|
2402
|
+
for (const f of files) out3.push(` ${f.file}`);
|
|
2403
|
+
out3.push("Configure an MCP server in the app first, then run: npx @mylasecurity/gate mcp install <claim-code>");
|
|
2404
|
+
return out3;
|
|
2405
|
+
}
|
|
2406
|
+
for (const f of seen) {
|
|
2407
|
+
const bits = [];
|
|
2408
|
+
if (f.gated.length) bits.push(`${f.gated.length} behind the Gate (${f.gated.join(", ")})`);
|
|
2409
|
+
if (f.bare.length) bits.push(`${f.bare.length} not gated (${f.bare.join(", ")})`);
|
|
2410
|
+
out3.push(`${f.label}: ${bits.length ? bits.join("; ") : "no MCP servers configured"}`);
|
|
2411
|
+
out3.push(` ${f.file}`);
|
|
2412
|
+
}
|
|
2413
|
+
const total = seen.reduce((n, f) => n + f.gated.length, 0);
|
|
2414
|
+
const bare = seen.reduce((n, f) => n + f.bare.length, 0);
|
|
2415
|
+
if (total > 0 && !hasCredential) {
|
|
2416
|
+
out3.push("A server is wrapped but there is no credential on this machine, so the proxy cannot ask Myla. Run: npx @mylasecurity/gate mcp install <claim-code>");
|
|
2417
|
+
}
|
|
2418
|
+
if (bare > 0) out3.push(`Put the rest behind the Gate with: npx @mylasecurity/gate mcp install${total > 0 ? "" : " <claim-code>"}`);
|
|
2419
|
+
if (total > 0) out3.push("A call to a gated server is judged before it runs. Quit and reopen the app after any change \u2014 MCP servers start with it.");
|
|
2420
|
+
return out3;
|
|
2421
|
+
}
|
|
2422
|
+
function editFile(file, label, how) {
|
|
2423
|
+
let raw;
|
|
2424
|
+
try {
|
|
2425
|
+
raw = fs10.readFileSync(file, "utf8");
|
|
2426
|
+
} catch {
|
|
2427
|
+
return null;
|
|
2428
|
+
}
|
|
2429
|
+
let doc;
|
|
2430
|
+
try {
|
|
2431
|
+
doc = JSON.parse(raw);
|
|
2432
|
+
} catch {
|
|
2433
|
+
return { label, file, changed: [], skipped: ["could not read this file as JSON, so nothing was touched"] };
|
|
2434
|
+
}
|
|
2435
|
+
const servers = doc.mcpServers;
|
|
2436
|
+
if (!servers || typeof servers !== "object") return null;
|
|
2437
|
+
const changed = [];
|
|
2438
|
+
const skipped = [];
|
|
2439
|
+
for (const [name, entry] of Object.entries(servers)) {
|
|
2440
|
+
if (!entry || typeof entry !== "object") continue;
|
|
2441
|
+
const next = how(name, entry);
|
|
2442
|
+
if (next) {
|
|
2443
|
+
servers[name] = next;
|
|
2444
|
+
changed.push(name);
|
|
2445
|
+
} else skipped.push(name);
|
|
2446
|
+
}
|
|
2447
|
+
if (changed.length === 0) return { label, file, changed, skipped };
|
|
2448
|
+
const indentMatch = /\n(\s+)"/.exec(raw);
|
|
2449
|
+
const indent = indentMatch ? indentMatch[1].includes(" ") ? " " : indentMatch[1].length : 2;
|
|
2450
|
+
fs10.copyFileSync(file, nextBackupPath(file));
|
|
2451
|
+
fs10.writeFileSync(file, JSON.stringify(doc, null, indent) + (raw.endsWith("\n") ? "\n" : ""));
|
|
2452
|
+
return { label, file, changed, skipped };
|
|
2453
|
+
}
|
|
2454
|
+
async function claimMcpAgent(opts) {
|
|
2455
|
+
const origin = (opts.origin ?? "https://mylasecurity.app").replace(/\/+$/, "");
|
|
2456
|
+
const url = `${origin}/api/security/gate/claim/${encodeURIComponent(opts.code)}?client=mcp`;
|
|
2457
|
+
let res;
|
|
2458
|
+
try {
|
|
2459
|
+
res = opts.fetchClaim ? await opts.fetchClaim(url) : await fetch(url).then(async (r) => ({ status: r.status, body: await r.text() }));
|
|
2460
|
+
} catch (e) {
|
|
2461
|
+
return `Couldn't reach ${origin} to fetch the install link (${e.message}). Nothing was changed.`;
|
|
2462
|
+
}
|
|
2463
|
+
if (res.status === 400) {
|
|
2464
|
+
const legacy = `${origin}/api/security/gate/claim/${encodeURIComponent(opts.code)}?client=claude-code`;
|
|
2465
|
+
try {
|
|
2466
|
+
res = opts.fetchClaim ? await opts.fetchClaim(legacy) : await fetch(legacy).then(async (r) => ({ status: r.status, body: await r.text() }));
|
|
2467
|
+
} catch (e) {
|
|
2468
|
+
return `Couldn't reach ${origin} to fetch the install link (${e.message}). Nothing was changed.`;
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
if (res.status === 410) return "This install link has lapsed. Reissue it in Myla and run this again. Nothing was changed.";
|
|
2472
|
+
if (res.status !== 200) return `The install link returned HTTP ${res.status}. Nothing was changed.`;
|
|
2473
|
+
const v = readClaimToken(res.body, origin);
|
|
2474
|
+
if (!v.ok) return `The install link returned something unexpected, ${v.reason} Nothing was changed.`;
|
|
2475
|
+
try {
|
|
2476
|
+
fs10.mkdirSync(MYLA_DIR, { recursive: true });
|
|
2477
|
+
fs10.writeFileSync(MCP_CREDENTIALS, JSON.stringify({ token: v.token, origin }), { mode: 384 });
|
|
2478
|
+
} catch (e) {
|
|
2479
|
+
return `Could not store the credential at ${MCP_CREDENTIALS} (${e.message}). Nothing was changed.`;
|
|
2480
|
+
}
|
|
2481
|
+
return null;
|
|
2482
|
+
}
|
|
2483
|
+
async function runMcpInstall(io, opts) {
|
|
2484
|
+
if (opts.on && !opts.dryRun) {
|
|
2485
|
+
if (opts.code) {
|
|
2486
|
+
const err = await claimMcpAgent(opts);
|
|
2487
|
+
if (err) {
|
|
2488
|
+
io.err(err);
|
|
2489
|
+
return 1;
|
|
2490
|
+
}
|
|
2491
|
+
io.out(`Stored this surface's credential at ${MCP_CREDENTIALS} (owner-read only)`);
|
|
2492
|
+
} else if (!readMcpToken()) {
|
|
2493
|
+
io.err("MCP needs its own agent, so its calls are judged by its own rules and recorded as itself.");
|
|
2494
|
+
io.err('In Myla, add an agent (call it something like "claude-desktop"), then run:');
|
|
2495
|
+
io.err(" npx @mylasecurity/gate mcp install <the code it gives you>");
|
|
2496
|
+
return 1;
|
|
2497
|
+
}
|
|
2498
|
+
}
|
|
2499
|
+
if (opts.on && !opts.dryRun) {
|
|
2500
|
+
const token = readMcpToken();
|
|
2501
|
+
if (token) {
|
|
2502
|
+
const got = await fetchBundle((opts.origin ?? "https://mylasecurity.app").replace(/\/+$/, ""), token);
|
|
2503
|
+
io.out(got ? "Took this agent's rules down to this machine." : "Could not fetch its rules just now, so the proxy will let calls through and say so until it can.");
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
if (!opts.dryRun && !installDecider()) {
|
|
2507
|
+
io.err("Could not work out which file I am running from, so I will not point your MCP config at a guess. Nothing was changed.");
|
|
2508
|
+
return 1;
|
|
2509
|
+
}
|
|
2510
|
+
const results = [];
|
|
2511
|
+
for (const { label, file } of mcpConfigPaths(opts.home, opts.platform)) {
|
|
2512
|
+
if (!fs10.existsSync(file)) continue;
|
|
2513
|
+
if (opts.dryRun) {
|
|
2514
|
+
let doc = {};
|
|
2515
|
+
try {
|
|
2516
|
+
doc = JSON.parse(fs10.readFileSync(file, "utf8"));
|
|
2517
|
+
} catch {
|
|
2518
|
+
}
|
|
2519
|
+
const names = Object.entries(doc.mcpServers ?? {}).filter(([n, e]) => (opts.on ? wrap(n, e) : unwrap(e)) !== null).map(([n]) => n);
|
|
2520
|
+
if (names.length) results.push({ label, file, changed: names, skipped: [] });
|
|
2521
|
+
continue;
|
|
2522
|
+
}
|
|
2523
|
+
const r = editFile(file, label, (name, e) => opts.on ? wrap(name, e) : unwrap(e));
|
|
2524
|
+
if (r) results.push(r);
|
|
2525
|
+
}
|
|
2526
|
+
const touched = results.filter((r) => r.changed.length > 0);
|
|
2527
|
+
if (touched.length === 0) {
|
|
2528
|
+
io.out(opts.on ? "Found no MCP servers to put behind the Gate. Either none are configured, or they are already behind it." : "Found no Myla-wrapped MCP servers to put back.");
|
|
2529
|
+
return 0;
|
|
2530
|
+
}
|
|
2531
|
+
for (const r of touched) {
|
|
2532
|
+
io.out(`${opts.dryRun ? "Would change" : "Changed"} ${r.label}: ${r.changed.join(", ")}`);
|
|
2533
|
+
io.out(` ${r.file}`);
|
|
2534
|
+
}
|
|
2535
|
+
io.out("");
|
|
2536
|
+
if (opts.dryRun) {
|
|
2537
|
+
io.out("Nothing was written.");
|
|
2538
|
+
return 0;
|
|
2539
|
+
}
|
|
2540
|
+
io.out(opts.on ? "Every tool call from those servers now asks the Gate first. A backup of each file was made before it was changed." : "Those servers now run directly again, exactly as they did before.");
|
|
2541
|
+
io.out("Quit the app completely and open it again: MCP servers start with it.");
|
|
2542
|
+
return 0;
|
|
2543
|
+
}
|
|
2544
|
+
|
|
2545
|
+
// src/serve.ts
|
|
2546
|
+
import http from "node:http";
|
|
2547
|
+
var DEFAULT_PORT = 7177;
|
|
2548
|
+
function runServe(io, opts) {
|
|
2549
|
+
const port = opts.port ?? DEFAULT_PORT;
|
|
2550
|
+
const host = opts.host ?? "127.0.0.1";
|
|
2551
|
+
return new Promise((resolve) => {
|
|
2552
|
+
const server = http.createServer((req, res) => {
|
|
2553
|
+
if (req.method !== "GET" || req.url !== "/" && req.url !== "/index.html") {
|
|
2554
|
+
res.writeHead(404, { "content-type": "text/plain" });
|
|
2555
|
+
res.end("Not found\n");
|
|
2556
|
+
return;
|
|
2557
|
+
}
|
|
2558
|
+
const html = renderHtml(localView(opts.token), Date.now());
|
|
2559
|
+
res.writeHead(200, {
|
|
2560
|
+
"content-type": "text/html; charset=utf-8",
|
|
2561
|
+
"cache-control": "no-store",
|
|
2562
|
+
// It renders only what it generated, but a page that shows what an agent tried to do should
|
|
2563
|
+
// not be one frame or one injected script away from being useful to somebody else.
|
|
2564
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
|
|
2565
|
+
"x-content-type-options": "nosniff",
|
|
2566
|
+
"referrer-policy": "no-referrer"
|
|
2567
|
+
});
|
|
2568
|
+
res.end(html);
|
|
2569
|
+
});
|
|
2570
|
+
server.on("error", (e) => {
|
|
2571
|
+
io.err(e.code === "EADDRINUSE" ? `Port ${port} is already in use. Something else is on it, or Myla is already serving: open http://${host}:${port}` : `Could not start the local page: ${e.message}`);
|
|
2572
|
+
resolve(1);
|
|
2573
|
+
});
|
|
2574
|
+
server.listen(port, host, () => {
|
|
2575
|
+
io.out(`Myla is serving on http://${host}:${port}`);
|
|
2576
|
+
io.out("It reads only ~/.myla, it needs no network, and it listens on this machine alone.");
|
|
2577
|
+
io.out("Leave it open. It refreshes itself as decisions are made. Ctrl+C to stop.");
|
|
2578
|
+
});
|
|
2579
|
+
const stop = () => {
|
|
2580
|
+
server.close(() => resolve(0));
|
|
2581
|
+
};
|
|
2582
|
+
process.on("SIGINT", stop);
|
|
2583
|
+
process.on("SIGTERM", stop);
|
|
2584
|
+
});
|
|
2585
|
+
}
|
|
2586
|
+
|
|
825
2587
|
// src/cli.ts
|
|
2588
|
+
import { fileURLToPath } from "node:url";
|
|
2589
|
+
import { realpathSync } from "node:fs";
|
|
826
2590
|
var realIo = {
|
|
827
2591
|
out: (s) => process.stdout.write(s + "\n"),
|
|
828
2592
|
err: (s) => process.stderr.write(s + "\n")
|
|
829
2593
|
};
|
|
830
2594
|
function parseArgs(argv) {
|
|
831
|
-
const
|
|
2595
|
+
const out3 = {
|
|
832
2596
|
command: "",
|
|
833
2597
|
positionals: [],
|
|
834
2598
|
client: "claude-code",
|
|
835
2599
|
origin: DEFAULT_ORIGIN,
|
|
836
2600
|
dryRun: false,
|
|
2601
|
+
html: false,
|
|
837
2602
|
help: false
|
|
838
2603
|
};
|
|
839
2604
|
let clientSeen;
|
|
840
2605
|
for (let i = 0; i < argv.length; i++) {
|
|
841
2606
|
const a = argv[i];
|
|
842
2607
|
if (a === "--help" || a === "-h") {
|
|
843
|
-
|
|
2608
|
+
out3.help = true;
|
|
844
2609
|
continue;
|
|
845
2610
|
}
|
|
846
2611
|
if (a === "--dry-run") {
|
|
847
|
-
|
|
2612
|
+
out3.dryRun = true;
|
|
2613
|
+
continue;
|
|
2614
|
+
}
|
|
2615
|
+
if (a === "--html") {
|
|
2616
|
+
out3.html = true;
|
|
2617
|
+
continue;
|
|
2618
|
+
}
|
|
2619
|
+
if (a === "--server" || a.startsWith("--server=")) {
|
|
2620
|
+
out3.server = a.includes("=") ? a.slice("--server=".length) : argv[++i];
|
|
848
2621
|
continue;
|
|
849
2622
|
}
|
|
2623
|
+
if (a === "--") {
|
|
2624
|
+
out3.rest = argv.slice(i + 1);
|
|
2625
|
+
break;
|
|
2626
|
+
}
|
|
850
2627
|
if (a === "--client" || a.startsWith("--client=")) {
|
|
851
2628
|
const val = a.includes("=") ? a.slice("--client=".length) : argv[++i];
|
|
852
2629
|
clientSeen = val;
|
|
@@ -854,24 +2631,24 @@ function parseArgs(argv) {
|
|
|
854
2631
|
}
|
|
855
2632
|
if (a === "--origin" || a.startsWith("--origin=")) {
|
|
856
2633
|
const val = a.includes("=") ? a.slice("--origin=".length) : argv[++i];
|
|
857
|
-
if (val)
|
|
2634
|
+
if (val) out3.origin = val.replace(/\/+$/, "");
|
|
858
2635
|
continue;
|
|
859
2636
|
}
|
|
860
2637
|
if (a.startsWith("-")) {
|
|
861
|
-
|
|
2638
|
+
out3.error = `Unknown flag: ${a}`;
|
|
862
2639
|
continue;
|
|
863
2640
|
}
|
|
864
|
-
if (!
|
|
865
|
-
else
|
|
2641
|
+
if (!out3.command) out3.command = a;
|
|
2642
|
+
else out3.positionals.push(a);
|
|
866
2643
|
}
|
|
867
2644
|
if (clientSeen !== void 0) {
|
|
868
2645
|
if (!HOOK_CLIENTS.includes(clientSeen)) {
|
|
869
|
-
|
|
2646
|
+
out3.error = `--client must be one of ${HOOK_CLIENTS.join(", ")} (got "${clientSeen}")`;
|
|
870
2647
|
} else {
|
|
871
|
-
|
|
2648
|
+
out3.client = clientSeen;
|
|
872
2649
|
}
|
|
873
2650
|
}
|
|
874
|
-
return
|
|
2651
|
+
return out3;
|
|
875
2652
|
}
|
|
876
2653
|
var HELP = `Myla Gate installer
|
|
877
2654
|
|
|
@@ -884,6 +2661,18 @@ Usage
|
|
|
884
2661
|
npx @mylasecurity/gate install <claim-code> --dry-run Show what would be written, write nothing
|
|
885
2662
|
npx @mylasecurity/gate doctor Check the hook is installed AND the Gate recognises the token (read-only)
|
|
886
2663
|
npx @mylasecurity/gate uninstall Remove only Myla's hooks, back up first
|
|
2664
|
+
npx @mylasecurity/gate decide Decide ONE tool call (reads the event on stdin). Asks Myla first; decides here if Myla is unreachable
|
|
2665
|
+
npx @mylasecurity/gate mcp What is behind the Gate on this machine, and what is not
|
|
2666
|
+
npx @mylasecurity/gate mcp install <claim-code> Put every MCP server on this machine behind the Gate, as its own agent
|
|
2667
|
+
npx @mylasecurity/gate mcp uninstall Put them back exactly as they were
|
|
2668
|
+
npx @mylasecurity/gate mcp --server <name> -- <cmd> The proxy itself: what an MCP client launches
|
|
2669
|
+
npx @mylasecurity/gate serve Myla as a page on this machine, live, at 127.0.0.1. No network
|
|
2670
|
+
npx @mylasecurity/gate log What this machine decided, and the rules it used \u2014 reads only ~/.myla, works with no network
|
|
2671
|
+
npx @mylasecurity/gate log --html The same as a self-contained page you can open offline
|
|
2672
|
+
npx @mylasecurity/gate ask Ask about ONE call from any agent: {"tool","args"} on stdin, a verdict on stdout
|
|
2673
|
+
npx @mylasecurity/gate sync Hand over anything decided offline, and take a fresh copy of the rules
|
|
2674
|
+
npx @mylasecurity/gate offline on Put the Gate on this machine, so it still decides when Myla is unreachable
|
|
2675
|
+
npx @mylasecurity/gate offline off How to go back to the hosted Gate
|
|
887
2676
|
|
|
888
2677
|
Options
|
|
889
2678
|
--client claude-code|cursor|codex Which agent (default: claude-code)
|
|
@@ -917,6 +2706,86 @@ async function main(argv, io = realIo) {
|
|
|
917
2706
|
}
|
|
918
2707
|
return runInstall(io, { code, client: p.client, origin: p.origin, dryRun: p.dryRun });
|
|
919
2708
|
}
|
|
2709
|
+
case "decide": {
|
|
2710
|
+
const token = tokenFromInstalledConfig(p.client);
|
|
2711
|
+
if (!token) {
|
|
2712
|
+
io.err("No Myla hook config on this machine, so there is nothing to decide with.");
|
|
2713
|
+
return 1;
|
|
2714
|
+
}
|
|
2715
|
+
return runDecide({ client: p.client, origin: p.origin, token, stdin: await readStdin() }, io);
|
|
2716
|
+
}
|
|
2717
|
+
case "ask": {
|
|
2718
|
+
const token = tokenFromInstalledConfig(p.client);
|
|
2719
|
+
if (!token) {
|
|
2720
|
+
io.err("No Myla hook config on this machine. Install the Gate first: npx @mylasecurity/gate install <claim-code>");
|
|
2721
|
+
return 1;
|
|
2722
|
+
}
|
|
2723
|
+
return runAsk({ origin: p.origin, token, stdin: await readStdin() }, io);
|
|
2724
|
+
}
|
|
2725
|
+
case "mcp": {
|
|
2726
|
+
const sub = p.positionals[0];
|
|
2727
|
+
if (sub === "install" || sub === "uninstall") {
|
|
2728
|
+
return runMcpInstall(io, {
|
|
2729
|
+
on: sub === "install",
|
|
2730
|
+
dryRun: p.dryRun,
|
|
2731
|
+
code: p.positionals[1],
|
|
2732
|
+
origin: p.origin
|
|
2733
|
+
});
|
|
2734
|
+
}
|
|
2735
|
+
const rest = p.rest ?? [];
|
|
2736
|
+
if (!p.server && rest.length === 0 && !sub) {
|
|
2737
|
+
for (const line of renderMcpStatus(mcpStatus(), readMcpToken() !== null)) io.out(line);
|
|
2738
|
+
return 0;
|
|
2739
|
+
}
|
|
2740
|
+
if (!p.server || rest.length === 0) {
|
|
2741
|
+
io.err("Usage: npx @mylasecurity/gate mcp --server <name> -- <command to run the MCP server>");
|
|
2742
|
+
io.err("Or, to see what is behind the Gate on this machine: npx @mylasecurity/gate mcp");
|
|
2743
|
+
return 1;
|
|
2744
|
+
}
|
|
2745
|
+
const token = readMcpToken();
|
|
2746
|
+
if (!token) {
|
|
2747
|
+
io.err("No MCP credential on this machine. Run: npx @mylasecurity/gate mcp install <claim-code>");
|
|
2748
|
+
return 1;
|
|
2749
|
+
}
|
|
2750
|
+
return runMcp({ server: p.server, command: rest[0], args: rest.slice(1), origin: p.origin, token }, io);
|
|
2751
|
+
}
|
|
2752
|
+
case "serve": {
|
|
2753
|
+
const token = tokenFromInstalledConfig(p.client);
|
|
2754
|
+
if (!token) {
|
|
2755
|
+
io.err("No Myla hook config on this machine. Install the Gate first: npx @mylasecurity/gate install <claim-code>");
|
|
2756
|
+
return 1;
|
|
2757
|
+
}
|
|
2758
|
+
const port = p.positionals[0] ? Number(p.positionals[0]) : DEFAULT_PORT;
|
|
2759
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
2760
|
+
io.err(`Not a port: ${p.positionals[0]}`);
|
|
2761
|
+
return 1;
|
|
2762
|
+
}
|
|
2763
|
+
return runServe(io, { token, port });
|
|
2764
|
+
}
|
|
2765
|
+
case "log": {
|
|
2766
|
+
const token = tokenFromInstalledConfig(p.client);
|
|
2767
|
+
if (!token) {
|
|
2768
|
+
io.err("No Myla hook config on this machine. Install the Gate first: npx @mylasecurity/gate install <claim-code>");
|
|
2769
|
+
return 1;
|
|
2770
|
+
}
|
|
2771
|
+
return runLog(io, { token, html: p.html });
|
|
2772
|
+
}
|
|
2773
|
+
case "sync": {
|
|
2774
|
+
const token = tokenFromInstalledConfig(p.client);
|
|
2775
|
+
if (!token) {
|
|
2776
|
+
io.err("No Myla hook config on this machine. Install the Gate first: npx @mylasecurity/gate install <claim-code>");
|
|
2777
|
+
return 1;
|
|
2778
|
+
}
|
|
2779
|
+
return runSync(p.origin, token, io);
|
|
2780
|
+
}
|
|
2781
|
+
case "offline": {
|
|
2782
|
+
const which = p.positionals[0];
|
|
2783
|
+
if (which !== "on" && which !== "off") {
|
|
2784
|
+
io.err("Usage: npx @mylasecurity/gate offline on (or: offline off)");
|
|
2785
|
+
return 1;
|
|
2786
|
+
}
|
|
2787
|
+
return runOffline(io, { on: which === "on", client: p.client, origin: p.origin, dryRun: p.dryRun });
|
|
2788
|
+
}
|
|
920
2789
|
case "doctor":
|
|
921
2790
|
return runDoctor(io, { client: p.client, origin: p.origin });
|
|
922
2791
|
case "uninstall":
|
|
@@ -927,8 +2796,14 @@ async function main(argv, io = realIo) {
|
|
|
927
2796
|
}
|
|
928
2797
|
}
|
|
929
2798
|
var isDirectRun = (() => {
|
|
930
|
-
|
|
931
|
-
|
|
2799
|
+
if (true) return true;
|
|
2800
|
+
const invoked = process.argv[1];
|
|
2801
|
+
if (!invoked) return false;
|
|
2802
|
+
try {
|
|
2803
|
+
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(invoked);
|
|
2804
|
+
} catch {
|
|
2805
|
+
return false;
|
|
2806
|
+
}
|
|
932
2807
|
})();
|
|
933
2808
|
if (isDirectRun) {
|
|
934
2809
|
main(process.argv.slice(2)).then((code) => {
|