myrmo-mcp 0.28.0 → 0.28.2

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.
@@ -0,0 +1,280 @@
1
+ // Generated from clients/typescript/packages/myrmo/src/redact.ts by clients/typescript/scripts/sync-plugin-redact.mjs.
2
+ // Do not edit: change the SDK, build it and run that script. The SDK's tests check that this copy is current.
3
+ // Client-side redaction: the same detectors the colony runs, applied before anything leaves the
4
+ // machine. Keep in sync with server/src/redact.rs and clients/python/src/myrmo/redact.py: all
5
+ // three must reproduce protocol/redact.v1.vectors.json exactly.
6
+ //
7
+ // Rules run in order, most specific first. A rule's replacement never matches a later rule (it
8
+ // starts with `<`, which no value pattern accepts), so redacting twice changes nothing.
9
+ const full = (kind) => `<redacted:${kind}>`;
10
+ const r = (kind, source, flags, replace) => ({
11
+ kind,
12
+ pattern: new RegExp(source, `g${flags}`),
13
+ replace,
14
+ });
15
+ const fixed = (kind) => () => full(kind);
16
+ // Values that are references or placeholders, not secrets. The test is narrow on purpose: a
17
+ // password may contain `(`, `$` or `/`, and leaking one costs far more than keeping a code
18
+ // fragment, so only unmistakable references are kept: `$DB_PASSWORD`, `${{ secrets.X }}`,
19
+ // `os.getenv(`, `get_secret()`, `None`, `****`, a URL, a path.
20
+ const LITERALS = new Set([
21
+ "none", "null", "nil", "true", "false", "undefined", "required", "optional", "string", "str",
22
+ "int", "integer", "bool", "boolean", "empty", "redacted", "password", "secret", "token",
23
+ ]);
24
+ const ENV_REFERENCE = /^(?:\$\{?[A-Z_][A-Z0-9_]*\}?|%[A-Za-z_][A-Za-z0-9_]*%)$/;
25
+ const CODE_REFERENCE = /^[A-Za-z_][\w.]*(?:\(\)|[(\[])$/;
26
+ function isReference(value) {
27
+ const lower = value.toLowerCase();
28
+ return (ENV_REFERENCE.test(value) ||
29
+ CODE_REFERENCE.test(value) ||
30
+ ["${", "{{", "[", "{"].some((p) => value.startsWith(p)) ||
31
+ ["http://", "https://", "./", "../", "~/"].some((p) => lower.startsWith(p)) ||
32
+ (value.startsWith("/") && value.slice(1).includes("/")) ||
33
+ LITERALS.has(lower) ||
34
+ [...value].every((c) => "*xX.#-_".includes(c)));
35
+ }
36
+ function luhn(digits) {
37
+ let total = 0;
38
+ [...digits].reverse().forEach((ch, i) => {
39
+ let n = Number(ch);
40
+ if (i % 2 === 1) {
41
+ n *= 2;
42
+ if (n > 9)
43
+ n -= 9;
44
+ }
45
+ total += n;
46
+ });
47
+ return total % 10 === 0;
48
+ }
49
+ const ip = ([m]) => {
50
+ const valid = m.split(".").every((octet) => Number(octet) <= 255);
51
+ const harmless = m === "127.0.0.1" || m === "0.0.0.0" || m === "255.255.255.255";
52
+ return valid && !harmless ? full("ip") : null;
53
+ };
54
+ const card = ([m]) => {
55
+ const digits = m.replace(/[^0-9]/g, "");
56
+ return digits.length >= 13 && digits.length <= 19 && luhn(digits) ? full("card") : null;
57
+ };
58
+ /** `name = value` becomes `name = <redacted:kind>` unless the value is a reference. */
59
+ const keepPrefix = (kind, valueGroup) => (m) => isReference(m[valueGroup]) ? null : m.slice(1, valueGroup).join("") + full(kind);
60
+ // Configuration values that name an organisation or a person: `edc.ui.organization=Acme`, `"owner": "Ana"`,
61
+ // `LABEL maintainer=...`. The key decides, never the value, because a name looks like any other word. A key
62
+ // matches only when its last part is one of these words, so `org.eclipse.edc:dcp-core` (a Maven coordinate) and
63
+ // `--org-id` are left alone. A product or connector `*.title` is included: it is usually the owner's brand.
64
+ const ORG_KEY = String.raw `(?:(?:[A-Za-z0-9_.\-]{0,64}[._\-])?(?:(?:organi[sz]ations?|org|compan(?:y|ies)|tenants?|customers?|owners?|authors?|` +
65
+ String.raw `contacts?|maintainers?|publishers?|vendors?|employers?)(?:[_.\-]?(?:name|title))?|` +
66
+ String.raw `(?:client|display|full|legal|trade|business|brand)[_.\-]?name)|` +
67
+ String.raw `(?:[A-Za-z0-9_.\-]{0,64}[._\-])?(?:connector|product|portal|brand|app|ui|site)[._\-](?:[A-Za-z0-9_.\-]{0,64}[._\-])?title)`;
68
+ /** Values that are not a name: placeholders, types and generic words. */
69
+ const ORG_KEEP = new Set([
70
+ "default", "unknown", "example", "test", "testing", "user", "users", "admin", "administrator", "root", "me",
71
+ "self", "system", "anonymous", "n/a", "na", "tbd", "todo", "unset", "any", "object", "dict", "list", "set",
72
+ "array", "map", "number", "float", "date", "datetime", "name", "author", "owner", "org", "organization",
73
+ "company", "customer", "tenant",
74
+ ]);
75
+ /** A type annotation such as `Optional[str]`, not a name. */
76
+ const ORG_TYPE = /^[A-Za-z_][A-Za-z0-9_.]*\[[A-Za-z0-9_., \[\]]*\]$/;
77
+ /**
78
+ * The key of a rule anchored to the start of a line cannot begin with `-`, or the `-Dkey=value` of a command would
79
+ * take the rest of the command with it.
80
+ */
81
+ const ORG_KEY_LINE = ORG_KEY.replace(String.raw `[A-Za-z0-9_.\-]{0,64}[._\-]`, String.raw `[A-Za-z0-9_][A-Za-z0-9_.\-]{0,63}[._\-]`);
82
+ function orgKept(value, inline) {
83
+ const lower = value.toLowerCase();
84
+ return (isReference(value) ||
85
+ value.startsWith("<") ||
86
+ !/\p{L}/u.test(value) ||
87
+ ORG_TYPE.test(value) ||
88
+ ORG_KEEP.has(lower) ||
89
+ ["your", "example", "sample", "my-", "my_"].some((p) => lower.startsWith(p)) ||
90
+ (inline && [...value].some((c) => "${}[]()*\\".includes(c))));
91
+ }
92
+ /** Replaces the value group with `<redacted:org>`, keeping every group before and after it. */
93
+ const orgValue = (valueGroup, inline) => (m) => orgKept(m[valueGroup], inline)
94
+ ? null
95
+ : m.slice(1).map((group, i) => (i + 1 === valueGroup ? full("org") : group)).join("");
96
+ const SCHEMES = ["bearer", "basic", "token", "digest", "negotiate", "ntlm", "hawk"];
97
+ const authorization = (m) => {
98
+ const [, prefix, scheme, value] = m;
99
+ if (!scheme && SCHEMES.includes(value.toLowerCase()))
100
+ return null; // `Bearer <redacted:token>`: already gone
101
+ if (isReference(value))
102
+ return null;
103
+ return prefix + scheme + full("auth_header");
104
+ };
105
+ const NAMES_STRONG = "password|passwd|pwd|passphrase|secret|api[_-]?key|apikey|access[_-]?key|private[_-]?key|" +
106
+ "signing[_-]?key|encryption[_-]?key|access[_-]?token|auth[_-]?token";
107
+ const NAMES_WEAK = "token|credentials?|session[_-]?id|sessionid|csrf|xsrf";
108
+ const CLI_NAMES = "password|passwd|pwd|pass|passphrase|secret|token|api[_-]?key|access[_-]?key|auth[_-]?token|" +
109
+ "client[_-]?secret|private[_-]?key";
110
+ // `"$PWD:/src"` and `$PATH:/opt/bin` expand a shell variable and go on with more text: the name gives no value.
111
+ // `$TOKEN=value` is still redacted, since what follows the `=` may well be a secret.
112
+ const expandsVariable = (name) => name.startsWith("$") && name.trimEnd().endsWith(":");
113
+ const assignment = (m) => (expandsVariable(m[1]) || isReference(m[3]) ? null : m[1] + m[2] + full("secret"));
114
+ /** Replaces the value group with `<redacted:secret>`, keeping every group before and after it. */
115
+ const valueOnly = (valueGroup) => (m) => isReference(m[valueGroup])
116
+ ? null
117
+ : m.slice(1).map((group, i) => (i + 1 === valueGroup ? full("secret") : group)).join("");
118
+ // A `.pgpass` line, `host:port:database:user:` before the password. The host has a letter or a dot (or is `*`) and
119
+ // the port has four or five digits (or is `*`), so a timestamp, an IPv6 address or a log such as `a:b:c:d:e` is left
120
+ // alone. A colon inside a field is escaped as `\:`.
121
+ const PGPASS_FIELD = String.raw `(?:\\.|[^:\s\\'\x22<>])+`;
122
+ const PGPASS = String.raw `(?:\*|[0-9_\-]*[A-Za-z.][A-Za-z0-9_.\-]*):(?:[0-9]{4,5}|\*):` + PGPASS_FIELD + ":" + PGPASS_FIELD + ":";
123
+ // The MySQL and MariaDB clients take the password glued to `-p`: `mysql -uroot -pSECRET`. `-p 3306`, `mkdir -p`
124
+ // and `ssh -p 22` are other commands or have a space.
125
+ const MYSQL = String.raw `(?:mysql(?:dump|admin|import|check|show|pump|slap|binlog|sh)?|mariadb(?:-?dump|-admin|-import|-check|-show)?)`;
126
+ const RULES = [
127
+ // Private keys, whole or cut off by a truncated log.
128
+ r("private_key", String.raw `-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----`, "", fixed("private_key")),
129
+ r("private_key", String.raw `-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----(?:(?:\\n|\r?\n)[A-Za-z0-9+/=]{16,})*`, "", fixed("private_key")),
130
+ // An age secret key: `AGE-SECRET-KEY-1` and Bech32 in upper case.
131
+ r("private_key", String.raw `\bAGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{40,}`, "", fixed("private_key")),
132
+ // Password hashes: bcrypt, argon2, crypt(3).
133
+ r("password_hash", String.raw `\$(?:2[abxy]\$[0-9]{2}\$[./A-Za-z0-9]{53}|argon2(?:id|i|d)\$[^\s'\x22<>]{20,}|[156y]\$[./A-Za-z0-9]{1,16}\$[./A-Za-z0-9]{20,})`, "", fixed("password_hash")),
134
+ // Provider tokens.
135
+ r("api_key", String.raw `\bsk-ant-[A-Za-z0-9_\-]{20,}`, "", fixed("api_key")),
136
+ r("api_key", String.raw `\bsk-(?:proj-|svcacct-)?[A-Za-z0-9_\-]{20,}`, "", fixed("api_key")),
137
+ r("api_key", String.raw `\bgh[pousr]_[A-Za-z0-9]{30,}|\bgithub_pat_[A-Za-z0-9_]{22,}`, "", fixed("api_key")),
138
+ r("api_key", String.raw `\bglpat-[A-Za-z0-9_\-]{20,}`, "", fixed("api_key")),
139
+ r("api_key", String.raw `\bxox[abprs]-[A-Za-z0-9\-]{10,}|\bxapp-[A-Za-z0-9\-]{10,}`, "", fixed("api_key")),
140
+ r("api_key", String.raw `\bAIza[0-9A-Za-z_\-]{35}`, "", fixed("api_key")),
141
+ r("api_key", String.raw `\b[rs]k_(?:live|test)_[A-Za-z0-9]{20,}`, "", fixed("api_key")),
142
+ r("api_key", String.raw `\bmyk_[0-9a-f]{64}\b`, "", fixed("api_key")),
143
+ r("api_key", String.raw `\bnpm_[A-Za-z0-9]{36}\b`, "", fixed("api_key")),
144
+ r("api_key", String.raw `\bhf_[A-Za-z0-9]{30,}`, "", fixed("api_key")),
145
+ r("api_key", String.raw `\bSG\.[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}`, "", fixed("api_key")),
146
+ r("api_key", String.raw `\bpypi-AgEIcHlwaS5vcmc[A-Za-z0-9_\-]{40,}`, "", fixed("api_key")),
147
+ r("api_key", String.raw `\bya29\.[A-Za-z0-9_\-]{20,}`, "", fixed("api_key")),
148
+ r("api_key", String.raw `\b(?:dckr_pat_|dop_v1_|gsk_|xai-|r8_|lin_api_|pplx-|shp(?:at|ca|pa|ss)_|whsec_|sq0(?:atp|csp)-|glptt-|glrt-|GOCSPX-)[A-Za-z0-9_\-]{16,}`, "", fixed("api_key")),
149
+ r("api_key", String.raw `\b(?:dapi|SK)[0-9a-f]{32}\b|\bkey-[0-9a-f]{32}\b`, "", fixed("api_key")),
150
+ r("api_key", String.raw `\b(?:secret_[A-Za-z0-9]{43}|ntn_[A-Za-z0-9]{36,})\b`, "", fixed("api_key")),
151
+ // HashiCorp Vault service, batch and recovery tokens; Doppler service, personal, service account and CLI tokens;
152
+ // Pulumi access tokens.
153
+ r("api_key", String.raw `\bhv[sbr]\.[A-Za-z0-9_\-]{24,}`, "", fixed("api_key")),
154
+ r("api_key", String.raw `\bdp\.(?:st|pt|sa|ct)\.(?:[A-Za-z0-9_\-]{1,64}\.)?[A-Za-z0-9]{30,}`, "", fixed("api_key")),
155
+ r("api_key", String.raw `\bpul-[0-9a-f]{40}\b`, "", fixed("api_key")),
156
+ r("api_key", String.raw `\b((?:account|sharedaccess)key\s*=)[A-Za-z0-9+/=]{20,}`, "i", (m) => m[1] + full("api_key")),
157
+ r("aws_access_key", String.raw `\b(?:AKIA|ASIA)[0-9A-Z]{16}\b`, "", fixed("aws_access_key")),
158
+ r("aws_access_key", String.raw `(aws_secret_access_key\s*[=:]\s*['\x22]?)[A-Za-z0-9/+=]{40}`, "i", (m) => m[1] + full("aws_access_key")),
159
+ r("webhook", String.raw `https://hooks\.slack\.com/services/[A-Za-z0-9/]{20,}|https://(?:discord(?:app)?\.com)/api/webhooks/[0-9]+/[A-Za-z0-9_\-]+|https://[a-z0-9.\-]*webhook\.office\.com/[^\s'\x22<>]+`, "i", fixed("webhook")),
160
+ r("jwt", String.raw `\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}`, "", fixed("jwt")),
161
+ r("token", String.raw `\b(bearer\s+)[A-Za-z0-9\-._~+/]{16,}=*`, "i", (m) => m[1] + full("token")),
162
+ // Headers.
163
+ r("auth_header", String.raw `\b((?:proxy-)?authorization['\x22]?[ \t]*[:=][ \t]*['\x22]?)((?:[A-Za-z][A-Za-z0-9_\-]*[ \t]+)?)([^\s'\x22,;<>]{6,})`, "i", authorization),
164
+ r("auth_header", String.raw `\b((?:x-api-key|x-auth-token|x-access-token|x-amz-security-token|x-csrf-token|x-xsrf-token|x-goog-api-key|x-gitlab-token|x-github-token|private-token|api-key|apikey)['\x22]?[ \t]*[:=][ \t]*['\x22]?)([^\s'\x22,;<>]{4,})`, "i", keepPrefix("auth_header", 2)),
165
+ r("cookie", String.raw `\b((?:set-)?cookie['\x22]?[ \t]*:[ \t]*['\x22]?)([^\r\n'\x22<>]{6,})`, "i", (m) => m[1] + full("cookie")),
166
+ // Credentials inside URLs.
167
+ r("connection_string", String.raw `\b([a-z][a-z0-9+.\-]{0,30}:\/\/)[^:/\s@<>]+:[^@\s/<>]+@`, "i", (m) => `${m[1]}${full("connection_string")}@`),
168
+ r("connection_string", String.raw `\b([a-z][a-z0-9+.\-]{0,30}:\/\/)[A-Za-z0-9_\-.~%]{20,}@`, "i", (m) => `${m[1]}${full("connection_string")}@`),
169
+ r("url_secret", String.raw `([?&;](?:access_token|refresh_token|id_token|token|api[_-]?key|apikey|secret|client_secret|password|passwd|pwd|sig|signature|x-amz-signature|x-amz-security-token|x-amz-credential|private_token|sessionid|jwt)=)([^&\s'\x22<>#]{4,})`, "i", keepPrefix("url_secret", 2)),
170
+ // Credentials files and commands whose password has no `name =` in front of it: Docker's `config.json` (`"auth"`
171
+ // is base64 of user:password), npm's legacy `_auth=`, `mysql -pSECRET`, `sshpass -p SECRET`, a `.netrc` entry, and
172
+ // a `.pgpass` line on its own or written to `.pgpass`.
173
+ r("password_assignment", String.raw `(\\?\x22(?:auth|identitytoken|registrytoken)\\?\x22[ \t]*:[ \t]*\\?\x22)([A-Za-z0-9+/=_.\-]{8,})(\\?\x22)`, "i", valueOnly(2)),
174
+ r("password_assignment", String.raw `((?:^|[^A-Za-z0-9_])_auth[ \t]*=[ \t]*)(['\x22]?)([^\s'\x22,;<>]{4,})`, "", assignment),
175
+ r("password_assignment", String.raw `((?:^|[\s;&|(/])` + MYSQL + String.raw `(?:[ \t]+[^\s;&|]+)*?[ \t]+-p)(['\x22]?)([^\s'\x22<>]+)`, "", assignment),
176
+ r("password_assignment", String.raw `((?:^|[\s;&|(/])sshpass(?:[ \t]+-v)*[ \t]+-p[ \t]*)(['\x22]?)([^\s'\x22<>]+)`, "", assignment),
177
+ r("password_assignment", String.raw `((?:^|\s)(?:machine[ \t]+[^\s]+|default)(?:\s+(?:login|account)[ \t]+[^\s]+)+\s+password[ \t]+)(['\x22]?)([^\s'\x22<>]+)`, "", assignment),
178
+ r("password_assignment", String.raw `(^[ \t]*` + PGPASS + ")(" + PGPASS_FIELD + String.raw `)([ \t]*\r?$)`, "m", valueOnly(2)),
179
+ r("password_assignment", String.raw `((?:^|[\s'\x22])` + PGPASS + ")(" + PGPASS_FIELD + String.raw `)([ \t]*['\x22]?[ \t]*>{1,2}[ \t]*[^\s]*\.pgpass)`, "", valueOnly(2)),
180
+ // `name = value`, in code, config, JSON, env files and command lines.
181
+ r("password_assignment", String.raw `(\$?\b[\w.\-]{0,64}(?:${NAMES_STRONG})[\w.\-]{0,64}['\x22]?[ \t]*[=:][ \t]*)(['\x22]?)([^\s'\x22,;<>]{4,})`, "i", assignment),
182
+ r("password_assignment", String.raw `(\$?\b[\w.\-]{0,64}(?:${NAMES_WEAK})[\w.\-]{0,64}['\x22]?[ \t]*[=:][ \t]*)(['\x22]?)([^\s'\x22,;<>]{12,})`, "i", assignment),
183
+ r("password_assignment", String.raw `((?:^|\s)--?(?:${CLI_NAMES})(?:=|[ \t]+))(['\x22]?)([^\s'\x22<>\-][^\s'\x22<>]{2,})`, "i", assignment),
184
+ // Personal data.
185
+ r("email", String.raw `\b[A-Za-z0-9._%+\-]{1,64}@[A-Za-z0-9.\-]{1,255}\.[A-Za-z]{2,}\b`, "", ([m]) => (m.startsWith("git@") ? null : full("email"))),
186
+ r("ip", String.raw `\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b`, "", ip),
187
+ r("ipv6", String.raw `\b(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}\b|\b(?:[0-9A-Fa-f]{1,4}:){1,5}:(?:[0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4}\b`, "", fixed("ipv6")),
188
+ r("mac", String.raw `\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b`, "", fixed("mac")),
189
+ r("hostname", String.raw `(:\/\/|@)(?:[A-Za-z0-9\-]{1,63}\.){1,10}(?:internal|corp|intranet|lan|localdomain|home\.arpa|local)\b`, "i", (m) => m[1] + full("hostname")),
190
+ // An internal host name on its own, for example in a DNS error. It must end the name: `jdk.internal.misc`
191
+ // and `com.acme.corp.Service` are Java packages, not hosts. `.local` is left out: it is also a file
192
+ // suffix (`.env.local`), so it is only redacted inside URLs. The rule is listed twice because a match
193
+ // consumes the character after it, which would hide a second host separated by a single space.
194
+ r("hostname", String.raw `(^|[^A-Za-z0-9.\-_])(?:[A-Za-z0-9\-]{1,63}\.){1,10}(?:internal|corp|intranet|lan|localdomain|home\.arpa)($|[^A-Za-z0-9.\-_]|\.\s)`, "i", (m) => m[1] + full("hostname") + m[2]),
195
+ r("hostname", String.raw `(^|[^A-Za-z0-9.\-_])(?:[A-Za-z0-9\-]{1,63}\.){1,10}(?:internal|corp|intranet|lan|localdomain|home\.arpa)($|[^A-Za-z0-9.\-_]|\.\s)`, "i", (m) => m[1] + full("hostname") + m[2]),
196
+ r("phone", String.raw `\+[0-9]{1,3}[\s.\-]?\(?[0-9]{2,4}\)?[\s.\-]?[0-9]{3,4}[\s.\-]?[0-9]{3,4}\b`, "", fixed("phone")),
197
+ r("card", String.raw `\b[3-6](?:[ \-]?[0-9]){12,18}\b`, "", card),
198
+ r("home_path", String.raw `(\/home\/|\/Users\/)[^/\s'\x22<>]+`, "", (m) => `${m[1]}<user>`),
199
+ r("home_path", String.raw `([a-z]:\\Users\\)[^\\\s'\x22<>]+`, "i", (m) => `${m[1]}<user>`),
200
+ // The org rules come last: they match on the key, so every more specific kind has already had its turn.
201
+ r("org", String.raw `(^|[^A-Za-z0-9_.\-])(` + ORG_KEY + String.raw `['\x22]?[ \t]*[=:][ \t]*)(['\x22])([^'\x22\r\n]{2,120})(['\x22])`, "i", orgValue(4, false)),
202
+ r("org", String.raw `(^[ \t]*(?:-[ \t]+)?` + ORG_KEY_LINE + String.raw `['\x22]?[ \t]*[=:][ \t]*)([^\s'\x22<>][^\r\n]*?)([ \t]*\r?$)`, "im", orgValue(2, false)),
203
+ r("org", String.raw `(^|[^A-Za-z0-9_.\-])(` + ORG_KEY + String.raw `['\x22]?[ \t]*[=:][ \t]*)([^\s'\x22<>,;]{2,80})`, "i", orgValue(3, true)),
204
+ ];
205
+ const NETWORK_KINDS = new Set(["ip", "ipv6", "mac", "hostname"]);
206
+ export function redactText(input, report = {}, policy = {}) {
207
+ let text = input;
208
+ for (const rule of RULES) {
209
+ if (policy.keepNetwork && NETWORK_KINDS.has(rule.kind))
210
+ continue;
211
+ rule.pattern.lastIndex = 0;
212
+ if (!rule.pattern.test(text))
213
+ continue;
214
+ rule.pattern.lastIndex = 0;
215
+ let hits = 0;
216
+ text = text.replace(rule.pattern, (...args) => {
217
+ // args: match, group 1..n, offset, whole string (the patterns have no named groups).
218
+ const groups = args.slice(0, -2).map((g) => g ?? "");
219
+ const replacement = rule.replace(groups);
220
+ if (replacement === null)
221
+ return groups[0];
222
+ hits++;
223
+ return replacement;
224
+ });
225
+ if (hits)
226
+ report[rule.kind] = (report[rule.kind] ?? 0) + hits;
227
+ }
228
+ return text;
229
+ }
230
+ /** Deep copy of `value` with every string redacted. */
231
+ export function redactValue(value, report = {}, policy = {}) {
232
+ if (typeof value === "string")
233
+ return redactText(value, report, policy);
234
+ if (Array.isArray(value))
235
+ return value.map((v) => redactValue(v, report, policy));
236
+ if (value && typeof value === "object") {
237
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redactValue(v, report, policy)]));
238
+ }
239
+ return value;
240
+ }
241
+ /**
242
+ * Runs of capitalised words that look like a name (`Acme Data Systems`), for a person to check before approving a
243
+ * publication. This does not redact anything: a name looks like any other word, so the colony cannot remove one by
244
+ * itself. A run at the start of a sentence loses its first word, which is capitalised anyway.
245
+ */
246
+ export function possibleNames(value, limit = 10) {
247
+ const found = new Set();
248
+ const capitalised = (w) => w.length >= 2 && w[0] !== w[0].toLowerCase();
249
+ const scan = (text) => {
250
+ let run = [];
251
+ const flush = () => {
252
+ if (run.length && /(?:^|[.!?:]\s+|\n\s*)$/.test(text.slice(0, run[0].index)))
253
+ run = run.slice(1);
254
+ if (run.length >= 2)
255
+ found.add(text.slice(run[0].index, run[run.length - 1].end));
256
+ run = [];
257
+ };
258
+ for (const m of text.matchAll(/\p{L}+/gu)) {
259
+ const word = { index: m.index ?? 0, end: (m.index ?? 0) + m[0].length };
260
+ if (!capitalised(m[0])) {
261
+ flush();
262
+ continue;
263
+ }
264
+ if (run.length && !(text[run[run.length - 1].end] === " " && run[run.length - 1].end + 1 === word.index))
265
+ flush();
266
+ run.push(word);
267
+ }
268
+ flush();
269
+ };
270
+ const walk = (v) => {
271
+ if (typeof v === "string")
272
+ scan(v);
273
+ else if (Array.isArray(v))
274
+ v.forEach(walk);
275
+ else if (v && typeof v === "object")
276
+ Object.values(v).forEach(walk);
277
+ };
278
+ walk(value);
279
+ return [...found].slice(0, limit);
280
+ }
@@ -0,0 +1,118 @@
1
+ // Where the hooks keep what they remember about a session (state.mjs): the last error lines, the trails shown, the
2
+ // prompts looked up. It is this person's only: a folder of their own ($XDG_RUNTIME_DIR/myrmo, else ~/.myrmo/state),
3
+ // created readable by them alone and refused when it belongs to someone else or is open to others; files written under
4
+ // a fresh name with mode 0600 and moved into place, never through a link; and what is read back is checked again, since
5
+ // it goes into the agent's context. MYRMO_HOOK_STATE_DIR chooses another folder (tests).
6
+
7
+ import { chmodSync, closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { randomBytes } from "node:crypto";
11
+
12
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
+ const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
14
+ const posix = (platform) => platform !== "win32" && typeof process.getuid === "function";
15
+
16
+ /** The hooks' state folder for this person. */
17
+ export function stateDir(env = process.env, platform = process.platform) {
18
+ const chosen = env.MYRMO_HOOK_STATE_DIR?.trim();
19
+ if (chosen) return chosen;
20
+ const runtime = platform !== "win32" ? env.XDG_RUNTIME_DIR?.trim() : "";
21
+ return runtime ? join(runtime, "myrmo") : join(homedir(), ".myrmo", "state");
22
+ }
23
+
24
+ /**
25
+ * The folder, made for this person only; null when it cannot be trusted: a link, not a folder, someone else's, or one
26
+ * of theirs that others can write to and that cannot be closed.
27
+ */
28
+ export function ensureDir(dir, platform = process.platform) {
29
+ try {
30
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
31
+ const st = lstatSync(dir);
32
+ if (st.isSymbolicLink() || !st.isDirectory()) return null;
33
+ if (posix(platform)) {
34
+ if (st.uid !== process.getuid()) return null;
35
+ if ((st.mode & 0o077) !== 0) {
36
+ chmodSync(dir, 0o700);
37
+ if ((lstatSync(dir).mode & 0o077) !== 0) return null;
38
+ }
39
+ }
40
+ return dir;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * A session's state file, or null when no folder can be trusted. $XDG_RUNTIME_DIR that cannot be used (gone, someone
48
+ * else's) falls back to ~/.myrmo/state; a folder chosen with MYRMO_HOOK_STATE_DIR does not.
49
+ */
50
+ export function stateFile(name, { env = process.env, platform = process.platform, prefix = "" } = {}) {
51
+ const first = stateDir(env, platform);
52
+ const home = join(homedir(), ".myrmo", "state");
53
+ const dir = ensureDir(first, platform) ?? (env.MYRMO_HOOK_STATE_DIR?.trim() || first === home ? null : ensureDir(home, platform));
54
+ if (!dir) return null;
55
+ const safe = String(name ?? "default").replace(/[^A-Za-z0-9_-]/g, "").slice(0, 64) || "default";
56
+ return join(dir, `${prefix}${safe}.json`);
57
+ }
58
+
59
+ const ids = (value, max) => (Array.isArray(value) ? value.filter((id) => typeof id === "string" && UUID.test(id)).map((id) => id.toLowerCase()).slice(-max) : []);
60
+ const line = (value) => (typeof value === "string" ? value.slice(0, 2000) : "");
61
+
62
+ /** What was read back, as the hooks expect it: trail ids that are UUIDs, lines that are text of bounded length. */
63
+ export function cleanState(raw) {
64
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
65
+ const state = { ...raw };
66
+ for (const key of ["found", "brief"]) {
67
+ if (state[key] == null) continue;
68
+ if (typeof state[key] !== "object" || Array.isArray(state[key])) {
69
+ state[key] = null;
70
+ continue;
71
+ }
72
+ state[key] = { ...state[key], ids: ids(state[key].ids, 5) };
73
+ if ("task" in state[key]) state[key].task = line(state[key].task);
74
+ if (!state[key].ids.length) state[key] = null;
75
+ }
76
+ if ("briefSeen" in state) state.briefSeen = ids(state.briefSeen, 50);
77
+ for (const key of ["nomatch", "failed", "problem"]) {
78
+ if (state[key] == null) continue;
79
+ if (typeof state[key] !== "object" || Array.isArray(state[key])) state[key] = null;
80
+ else if ("line" in state[key]) state[key] = { ...state[key], line: line(state[key].line) };
81
+ }
82
+ return state;
83
+ }
84
+
85
+ /** The state in `file`, or {} when there is none or it cannot be trusted (a link, someone else's). */
86
+ export function readState(file, platform = process.platform) {
87
+ if (!file) return {};
88
+ let fd;
89
+ try {
90
+ fd = openSync(file, constants.O_RDONLY | NOFOLLOW);
91
+ const st = fstatSync(fd);
92
+ if (!st.isFile() || (posix(platform) && st.uid !== process.getuid())) return {};
93
+ return cleanState(JSON.parse(readFileSync(fd, "utf8")));
94
+ } catch {
95
+ return {};
96
+ } finally {
97
+ if (fd !== undefined) closeSync(fd);
98
+ }
99
+ }
100
+
101
+ /** Write `state` to `file`: a new file of this person's only (0600), then moved over the old one. */
102
+ export function writeState(file, state) {
103
+ if (!file) return false;
104
+ const tmp = `${file}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
105
+ let fd;
106
+ try {
107
+ fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NOFOLLOW, 0o600);
108
+ writeSync(fd, JSON.stringify(state));
109
+ closeSync(fd);
110
+ fd = undefined;
111
+ renameSync(tmp, file);
112
+ return true;
113
+ } catch {
114
+ if (fd !== undefined) closeSync(fd);
115
+ rmSync(tmp, { force: true });
116
+ return false;
117
+ }
118
+ }
@@ -0,0 +1,15 @@
1
+ /** Where the hosted server listens without --host: this machine only. A container passes --host 0.0.0.0. */
2
+ export declare const DEFAULT_HTTP_HOST = "127.0.0.1";
3
+ /** The colony the hosted server talks to: MYRMO_URL, else the public one. Never the one saved in the settings file. */
4
+ export declare function hostedColonyUrl(env?: NodeJS.ProcessEnv): string;
5
+ /**
6
+ * The access key for one request: the caller's Bearer token, or none. Never MYRMO_API_KEY nor a saved key, which belong
7
+ * to whoever runs the server, not to whoever calls it. An empty string tells the SDK not to look for one elsewhere.
8
+ */
9
+ export declare function callerKey(authorization: string | undefined): string;
10
+ /**
11
+ * The Host headers /mcp answers (DNS rebinding protection), or null for no check. MYRMO_MCP_ALLOWED_HOSTS is a
12
+ * comma-separated list (`myrmo.dev`, `mcp.example.internal:8443`); `*` turns the check off, for a proxy that checks the
13
+ * host itself. Unset: this machine's loopback names on the port it listens on.
14
+ */
15
+ export declare function allowedHosts(port: number, value?: string | undefined): string[] | null;
@@ -0,0 +1,34 @@
1
+ // What the hosted server (`myrmo-mcp --http`) trusts. It answers whoever can reach its port, so it takes nothing from
2
+ // the machine it runs on that would let a caller act as someone else: no access key from the environment or the
3
+ // settings file (only the caller's own `Authorization: Bearer`), and no colony from the settings file. It listens on
4
+ // loopback unless told otherwise, and answers /mcp only for the Host names it is meant to serve, so that a web page
5
+ // cannot reach it through DNS rebinding.
6
+ /** The public colony, where the hosted server goes when MYRMO_URL names no other. */
7
+ const PUBLIC_COLONY = "https://myrmo.dev";
8
+ /** Where the hosted server listens without --host: this machine only. A container passes --host 0.0.0.0. */
9
+ export const DEFAULT_HTTP_HOST = "127.0.0.1";
10
+ /** The colony the hosted server talks to: MYRMO_URL, else the public one. Never the one saved in the settings file. */
11
+ export function hostedColonyUrl(env = process.env) {
12
+ return env.MYRMO_URL?.trim() || PUBLIC_COLONY;
13
+ }
14
+ /**
15
+ * The access key for one request: the caller's Bearer token, or none. Never MYRMO_API_KEY nor a saved key, which belong
16
+ * to whoever runs the server, not to whoever calls it. An empty string tells the SDK not to look for one elsewhere.
17
+ */
18
+ export function callerKey(authorization) {
19
+ const m = /^Bearer\s+(\S+)\s*$/i.exec(authorization ?? "");
20
+ return m ? m[1] : "";
21
+ }
22
+ /**
23
+ * The Host headers /mcp answers (DNS rebinding protection), or null for no check. MYRMO_MCP_ALLOWED_HOSTS is a
24
+ * comma-separated list (`myrmo.dev`, `mcp.example.internal:8443`); `*` turns the check off, for a proxy that checks the
25
+ * host itself. Unset: this machine's loopback names on the port it listens on.
26
+ */
27
+ export function allowedHosts(port, value = process.env.MYRMO_MCP_ALLOWED_HOSTS) {
28
+ const listed = (value ?? "").split(",").map((h) => h.trim().toLowerCase()).filter(Boolean);
29
+ if (listed.includes("*"))
30
+ return null;
31
+ if (listed.length)
32
+ return listed;
33
+ return ["localhost", "127.0.0.1", "[::1]"].flatMap((h) => [`${h}:${port}`, h]);
34
+ }
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // myrmo-mcp: run the Myrmo MCP server.
3
3
  //
4
4
  // npx -y myrmo-mcp stdio, for one developer (redaction happens on this machine)
5
- // myrmo-mcp --http --port 3333 Streamable HTTP, stateless, for hosting next to a colony
5
+ // myrmo-mcp --http --port 3333 Streamable HTTP, stateless, for hosting next to a colony (loopback unless --host)
6
6
  import { createHash } from "node:crypto";
7
7
  import { createServer as createHttpServer } from "node:http";
8
8
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -11,6 +11,7 @@ import { Colony, configPath, minFailedAttempts as resolveMinFailedAttempts, publ
11
11
  import * as sdk from "myrmo";
12
12
  import { parseInitArgs, runInit } from "./init.js";
13
13
  import { createServer, privateMode, VERSION } from "./server.js";
14
+ import { allowedHosts, callerKey, DEFAULT_HTTP_HOST, hostedColonyUrl } from "./hosting.js";
14
15
  import { clean, readDeclared, rememberDeclared } from "./profile.js";
15
16
  const args = process.argv.slice(2);
16
17
  const flag = (name) => args.includes(name);
@@ -36,7 +37,7 @@ if (flag("--version")) {
36
37
  const USAGE = `myrmo-mcp ${VERSION}: the Myrmo MCP server and its commands.
37
38
 
38
39
  myrmo-mcp run the MCP server on stdio (what an agent's client launches)
39
- myrmo-mcp --http [--port N] run it over Streamable HTTP, stateless
40
+ myrmo-mcp --http [--port N] [--host H] run it over Streamable HTTP, stateless (default host 127.0.0.1)
40
41
  myrmo-mcp init [options] set this machine's agents up (add --url, --key or --key-file, --private for a team colony)
41
42
  myrmo-mcp doctor check that this machine can use the colony, and say what to fix
42
43
  myrmo-mcp config [setting value] show or change a setting (publish, hook, ...)
@@ -53,7 +54,8 @@ const INIT_USAGE = `myrmo-mcp init [options]: set up the agents on this machine
53
54
  --client <id>[,<id>] only these: claude-code, cursor, windsurf, gemini, antigravity, claude-desktop,
54
55
  vscode, opencode, codex
55
56
  --url <colony> your organisation's colony instead of the public one
56
- --key <key> | --key-file <f> its access key (the file may be the invitation message)
57
+ --key-file <f> | --key - its access key, from a file (the invitation message works) or standard input;
58
+ --key <key> works too, but stays in the shell's history
57
59
  --publish auto|ask|off how agents publish to that colony (otherwise you are asked the first time)
58
60
  --private only for a colony older than protocol 1.7 (newer ones say what they are)
59
61
  --agents-md [file] also write the usage rules into this repository's AGENTS.md
@@ -274,7 +276,7 @@ if (args[0] === "init") {
274
276
  process.exit(0);
275
277
  }
276
278
  if (flag("--http")) {
277
- await serveHttp(Number(option("--port", process.env.PORT ?? "3333")), option("--host", "0.0.0.0"));
279
+ await serveHttp(Number(option("--port", process.env.PORT ?? "3333")), option("--host", DEFAULT_HTTP_HOST));
278
280
  }
279
281
  else {
280
282
  // What the colony says it is decides private mode (protocol 1.7). Known from an earlier start, it is used at once and
@@ -348,6 +350,8 @@ function sendJson(res, status, body) {
348
350
  res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
349
351
  }
350
352
  async function serveHttp(port, host) {
353
+ const hosts = allowedHosts(port);
354
+ const url = hostedColonyUrl();
351
355
  const http = createHttpServer(async (req, res) => {
352
356
  const path = (req.url ?? "/").split("?")[0];
353
357
  if (path === "/healthz")
@@ -369,17 +373,25 @@ async function serveHttp(port, host) {
369
373
  const agent = req.headers["x-myrmo-agent"];
370
374
  if (typeof agent === "string")
371
375
  headers["x-myrmo-agent"] = agent;
372
- const auth = req.headers.authorization;
373
376
  const colony = new Colony({
377
+ url,
374
378
  headers,
375
- apiKey: auth?.startsWith("Bearer ") ? auth.slice(7) : undefined,
379
+ // The caller's own key or none: never MYRMO_API_KEY or a key saved on this machine, which anyone who can reach
380
+ // this port would otherwise use.
381
+ apiKey: callerKey(req.headers.authorization),
376
382
  publish: "off",
377
383
  cacheTtlMs: 0,
378
384
  // The hosted server has no identity of its own: it forwards the header of whoever is calling.
379
385
  agentId: false,
380
386
  });
381
387
  const server = createServer({ colony, publishMode: "off", minFailedAttempts, fillLocalEnvironment: false, hosted: true });
382
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
388
+ // A web page can make a browser send requests to this port under a name it controls (DNS rebinding): only the
389
+ // Host names this server is meant for are answered (MYRMO_MCP_ALLOWED_HOSTS).
390
+ const transport = new StreamableHTTPServerTransport({
391
+ sessionIdGenerator: undefined,
392
+ enableJsonResponse: true,
393
+ ...(hosts ? { enableDnsRebindingProtection: true, allowedHosts: hosts } : {}),
394
+ });
383
395
  res.on("close", () => {
384
396
  void transport.close();
385
397
  void server.close();
@@ -396,5 +408,5 @@ async function serveHttp(port, host) {
396
408
  }
397
409
  });
398
410
  http.keepAliveTimeout = 65_000;
399
- http.listen(port, host, () => console.error(`myrmo-mcp ${VERSION} listening on http://${host}:${port}/mcp`));
411
+ http.listen(port, host, () => console.error(`myrmo-mcp ${VERSION} listening on http://${host}:${port}/mcp for ${url}; Host names answered: ${hosts ? hosts.join(", ") : "any (MYRMO_MCP_ALLOWED_HOSTS=*)"}`));
400
412
  }
package/dist/init.d.ts CHANGED
@@ -10,7 +10,7 @@ export interface Entry {
10
10
  command: string;
11
11
  args: string[];
12
12
  }
13
- export declare function serverEntry(platform?: NodeJS.Platform): Entry;
13
+ export declare function serverEntry(platform?: NodeJS.Platform, version?: string): Entry;
14
14
  /** How a client writes one MCP server in its JSON settings: under which key, and in which shape. */
15
15
  export interface Shape {
16
16
  key: string;
@@ -51,6 +51,7 @@ export interface InitOptions {
51
51
  private?: boolean;
52
52
  url?: string;
53
53
  key?: string;
54
+ keySource?: "argument" | "file" | "stdin";
54
55
  publish?: PublishMode;
55
56
  hooksSource?: string;
56
57
  env?: NodeJS.ProcessEnv;
@@ -85,11 +86,21 @@ export declare function mergeHooks(current: string | undefined, command: string)
85
86
  text: string;
86
87
  changed: boolean;
87
88
  } | null;
89
+ /**
90
+ * Point this machine at another colony: saves it in the settings file (with its key, private mode and publish choice,
91
+ * which apply only to that colony), and for Antigravity installs the hook that looks errors up there.
92
+ */
93
+ /** The scripts the hooks are made of, copied together (scripts/copy-hooks.mjs puts them in dist/hooks). */
94
+ export declare const HOOK_SCRIPTS: string[];
95
+ /** This machine or a private network: where plain http does not carry a key across the internet. */
96
+ export declare function nearbyHost(hostname: string): boolean;
97
+ /** What to tell the person about how their key is handled, one line each. */
98
+ export declare function keyWarnings(opts: Pick<InitOptions, "url" | "key" | "keySource">): string[];
88
99
  /** A colony key anywhere in a text (the invitation message works as it is), or a text holding only the key. */
89
100
  export declare function keyIn(text: string): string | undefined;
90
101
  export declare function runInit(opts: InitOptions): {
91
102
  configured: string[];
92
103
  skipped: string[];
93
104
  };
94
- export declare function parseInitArgs(args: string[]): InitOptions | string;
105
+ export declare function parseInitArgs(args: string[], readStdin?: () => string): InitOptions | string;
95
106
  export {};