turno-cli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/CHANGELOG.md +293 -0
  2. package/README.md +143 -75
  3. package/dist/accounts/audit.js +137 -7
  4. package/dist/accounts/builtin.js +68 -21
  5. package/dist/accounts/delegate.js +176 -35
  6. package/dist/accounts/policy.js +77 -0
  7. package/dist/accounts/registry.js +37 -21
  8. package/dist/agents/adapter.js +7 -0
  9. package/dist/agents/claude.js +195 -0
  10. package/dist/agents/codex.js +98 -0
  11. package/dist/agents/copilot.js +39 -0
  12. package/dist/agents/cursor.js +41 -0
  13. package/dist/agents/index.js +26 -86
  14. package/dist/agents/snippets.js +7 -4
  15. package/dist/cli/args.js +19 -4
  16. package/dist/cli/commands/accounts.js +96 -51
  17. package/dist/cli/commands/auto.js +82 -32
  18. package/dist/cli/commands/browser.js +216 -135
  19. package/dist/cli/commands/complete.js +2 -1
  20. package/dist/cli/commands/completion.js +4 -2
  21. package/dist/cli/commands/config.js +103 -18
  22. package/dist/cli/commands/demo.js +292 -0
  23. package/dist/cli/commands/doctor.js +387 -119
  24. package/dist/cli/commands/handoff.js +33 -22
  25. package/dist/cli/commands/identity.js +101 -50
  26. package/dist/cli/commands/init.js +616 -0
  27. package/dist/cli/commands/limit.js +25 -13
  28. package/dist/cli/commands/mcp-oauth.js +194 -0
  29. package/dist/cli/commands/mcp-observe.js +434 -0
  30. package/dist/cli/commands/mcp.js +653 -185
  31. package/dist/cli/commands/mcpd.js +323 -75
  32. package/dist/cli/commands/migrate.js +6 -4
  33. package/dist/cli/commands/open.js +92 -27
  34. package/dist/cli/commands/profile.js +205 -69
  35. package/dist/cli/commands/resolve.js +6 -2
  36. package/dist/cli/commands/run.js +15 -5
  37. package/dist/cli/commands/secret.js +61 -42
  38. package/dist/cli/commands/session.js +2 -2
  39. package/dist/cli/commands/sessions.js +42 -12
  40. package/dist/cli/commands/setup.js +136 -158
  41. package/dist/cli/commands/status.js +172 -41
  42. package/dist/cli/commands/statusline.js +305 -113
  43. package/dist/cli/commands/ui.js +64 -66
  44. package/dist/cli/commands/undo.js +161 -18
  45. package/dist/cli/commands/uninstall.js +462 -0
  46. package/dist/cli/commands/upgrade.js +75 -19
  47. package/dist/cli/commands/usage.js +117 -44
  48. package/dist/cli/commands/version.js +7 -5
  49. package/dist/cli/commands/which.js +7 -24
  50. package/dist/cli/compile-cache.js +32 -0
  51. package/dist/cli/group.js +10 -10
  52. package/dist/cli/help.js +57 -0
  53. package/dist/cli/highlight.js +236 -0
  54. package/dist/cli/io.js +170 -1
  55. package/dist/cli/launch.js +21 -37
  56. package/dist/cli/launchers.js +145 -94
  57. package/dist/cli/main.js +163 -27
  58. package/dist/cli/picker.js +447 -0
  59. package/dist/cli/registry.js +42 -5
  60. package/dist/cli/security.js +539 -0
  61. package/dist/cli/style.js +281 -0
  62. package/dist/core/config.js +145 -23
  63. package/dist/core/exhausted.js +6 -8
  64. package/dist/core/fsutil.js +47 -0
  65. package/dist/core/journal.js +281 -11
  66. package/dist/core/manifest.js +126 -6
  67. package/dist/core/paths.js +114 -7
  68. package/dist/core/profiles.js +139 -9
  69. package/dist/core/resolve.js +129 -23
  70. package/dist/core/secrets.js +215 -20
  71. package/dist/core/sessions.js +13 -20
  72. package/dist/core/update.js +18 -8
  73. package/dist/core/version.js +6 -0
  74. package/dist/demo/server.js +34 -0
  75. package/dist/mcpd/cache.js +18 -4
  76. package/dist/mcpd/calllog.js +253 -0
  77. package/dist/mcpd/client-names.js +51 -0
  78. package/dist/mcpd/connectors.js +148 -17
  79. package/dist/mcpd/daemon.js +452 -116
  80. package/dist/mcpd/folder-sets.js +39 -0
  81. package/dist/mcpd/gateway.js +441 -47
  82. package/dist/mcpd/health.js +269 -0
  83. package/dist/mcpd/importer.js +356 -36
  84. package/dist/mcpd/instances.js +425 -65
  85. package/dist/mcpd/jsonrpc.js +8 -0
  86. package/dist/mcpd/launchd.js +65 -48
  87. package/dist/mcpd/modern.js +648 -0
  88. package/dist/mcpd/oauth.js +791 -0
  89. package/dist/mcpd/peerpid.js +122 -6
  90. package/dist/mcpd/pressure.js +85 -0
  91. package/dist/mcpd/rss.js +151 -0
  92. package/dist/mcpd/service.js +167 -0
  93. package/dist/mcpd/state.js +183 -0
  94. package/dist/mcpd/sync.js +55 -80
  95. package/dist/mcpd/systemd.js +80 -0
  96. package/dist/mcpd/tokens.js +89 -0
  97. package/dist/mcpd/upstream.js +154 -44
  98. package/dist/statusline/cost.js +154 -44
  99. package/dist/statusline/input.js +66 -0
  100. package/dist/statusline/render.js +9 -3
  101. package/dist/ui/fonts.js +8 -3
  102. package/dist/ui/settings.js +27 -15
  103. package/npm-shrinkwrap.json +1093 -0
  104. package/package.json +9 -9
  105. package/dist/cli/commands/available.js +0 -18
@@ -0,0 +1,539 @@
1
+ import { chmodSync, existsSync, lstatSync, readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { parse as parseToml } from "smol-toml";
4
+ import { verifyAudit } from "../accounts/audit.js";
5
+ import { SCAN_ORDER, adapter, mcpFileFor } from "../agents/index.js";
6
+ import { loadConfig } from "../core/config.js";
7
+ import { loadManifest } from "../core/manifest.js";
8
+ import { paths, privateRoots, tildify } from "../core/paths.js";
9
+ import { agentOf, listProfiles } from "../core/profiles.js";
10
+ import { secretStore } from "../core/secrets.js";
11
+ import { profileTokenFile, tokenProfile } from "../mcpd/tokens.js";
12
+ import { isObject } from "../core/fsutil.js";
13
+ /**
14
+ * `turno doctor --security` (ADR 0027): who can read turno's files, who holds the mcpd port,
15
+ * literal secrets left in configs and backups, MCP servers that run whatever version is newest,
16
+ * the age of the gateway token, and the audit log's hash chain. Every check only reads, except
17
+ * the permissions fix, which narrows modes under turno's own folders.
18
+ */
19
+ const DAY_MS = 24 * 60 * 60 * 1000;
20
+ /** A gateway token older than this gets a rotation hint. */
21
+ export const TOKEN_MAX_AGE_DAYS = 90;
22
+ /** Paths listed in one finding before "and N more". */
23
+ const SHOWN = 5;
24
+ /** Entries walked under turno's folders before giving up (a runaway tree is a finding of its own). */
25
+ const WALK_LIMIT = 20_000;
26
+ const check = (c) => ({ area: "security", ...c });
27
+ function listPaths(files, env) {
28
+ const shown = files.slice(0, SHOWN).map((f) => tildify(f, env));
29
+ return `${shown.join(", ")}${files.length > SHOWN ? ` and ${files.length - SHOWN} more` : ""}`;
30
+ }
31
+ // ---- secret store
32
+ function secretStoreCheck(env) {
33
+ const store = secretStore(env);
34
+ if (store)
35
+ return check({ level: "ok", text: `secret store: ${secretStoreLabel(env)}` });
36
+ let usesKeychain = false;
37
+ try {
38
+ usesKeychain = existsSync(paths(env).mcpFile) && readFileSync(paths(env).mcpFile, "utf8").includes("keychain:");
39
+ }
40
+ catch {
41
+ /* unreadable: reported elsewhere */
42
+ }
43
+ return check({
44
+ level: usesKeychain ? "fail" : "info",
45
+ text: `secret store: none found (no security or secret-tool on PATH)${usesKeychain ? "; mcp.toml has keychain: references that cannot resolve" : ""}`,
46
+ manual: usesKeychain
47
+ ? "install secret-tool (libsecret), or write env:NAME in place of each keychain: reference in mcp.toml"
48
+ : "use env:NAME references in mcp.toml",
49
+ });
50
+ }
51
+ /** "macOS Keychain (security)" or "Secret Service (secret-tool)", or "none", for doctor and status. */
52
+ export function secretStoreLabel(env) {
53
+ const store = secretStore(env);
54
+ if (!store)
55
+ return "none";
56
+ return store.kind === "keychain" ? "macOS Keychain (security)" : "Secret Service (secret-tool)";
57
+ }
58
+ /** Subtrees whose contents other programs own (npm installs, Chrome profiles): only their folder is checked. */
59
+ function opaqueDirs(env) {
60
+ const p = paths(env);
61
+ return new Set([p.serversDir, p.chromeProfilesDir, p.browserDir]);
62
+ }
63
+ /**
64
+ * Folders and files under turno's config, state and data roots that group or others can read or
65
+ * write, or that belong to another user. Symbolic links are not followed.
66
+ */
67
+ export function scanPermissions(env) {
68
+ const uid = process.getuid?.();
69
+ const opaque = opaqueDirs(env);
70
+ const wide = [];
71
+ const foreign = [];
72
+ let seen = 0;
73
+ const visit = (path) => {
74
+ if (++seen > WALK_LIMIT)
75
+ return false;
76
+ let st;
77
+ try {
78
+ st = lstatSync(path);
79
+ }
80
+ catch {
81
+ return true;
82
+ }
83
+ if (st.isSymbolicLink())
84
+ return true;
85
+ const f = { path, mode: st.mode & 0o777, dir: st.isDirectory(), uid: st.uid };
86
+ if (uid !== undefined && st.uid !== uid)
87
+ foreign.push(f);
88
+ else if (f.mode & 0o077)
89
+ wide.push(f);
90
+ if (!f.dir || opaque.has(path) || basename(path) === "node_modules")
91
+ return true;
92
+ let names;
93
+ try {
94
+ names = readdirSync(path);
95
+ }
96
+ catch {
97
+ return true;
98
+ }
99
+ for (const name of names)
100
+ if (!visit(join(path, name)))
101
+ return false;
102
+ return true;
103
+ };
104
+ let truncated = false;
105
+ for (const root of new Set(privateRoots(env))) {
106
+ if (!existsSync(root))
107
+ continue;
108
+ if (!visit(root)) {
109
+ truncated = true;
110
+ break;
111
+ }
112
+ }
113
+ return { wide, foreign, truncated };
114
+ }
115
+ /** Remove group and other bits from every finding this user owns. Returns how many changed. */
116
+ export function narrowPermissions(findings) {
117
+ let n = 0;
118
+ for (const f of findings) {
119
+ try {
120
+ chmodSync(f.path, f.mode & 0o700);
121
+ n++;
122
+ }
123
+ catch {
124
+ /* gone or not ours: the next doctor run shows it again */
125
+ }
126
+ }
127
+ return n;
128
+ }
129
+ function permissionChecks(env) {
130
+ const { wide, foreign, truncated } = scanPermissions(env);
131
+ const out = [];
132
+ const roots = privateRoots(env).filter((r) => existsSync(r));
133
+ if (!roots.length)
134
+ return [check({ level: "info", text: "permissions: turno has no folders yet" })];
135
+ if (!wide.length && !foreign.length)
136
+ out.push(check({ level: "ok", text: `permissions: only you can read turno's folders (${roots.map((r) => tildify(r, env)).join(", ")})` }));
137
+ if (wide.length) {
138
+ const writable = wide.filter((f) => f.mode & 0o022);
139
+ out.push(check({
140
+ level: writable.length ? "fail" : "warn",
141
+ text: `permissions: ${wide.length} item${wide.length === 1 ? "" : "s"} under turno's folders ${writable.length ? "can be changed" : "can be read"} by other users: ${listPaths((writable.length ? writable : wide).map((f) => f.path), env)}`,
142
+ fix: {
143
+ label: "turno doctor --security --fix",
144
+ run: (io) => {
145
+ const n = narrowPermissions(scanPermissions(io.env).wide);
146
+ io.out(`narrowed ${n} item${n === 1 ? "" : "s"} to owner only`);
147
+ },
148
+ },
149
+ }));
150
+ }
151
+ if (foreign.length) {
152
+ out.push(check({
153
+ level: "warn",
154
+ text: `permissions: ${foreign.length} item${foreign.length === 1 ? "" : "s"} under turno's folders belong to another user (a sudo run?): ${listPaths(foreign.map((f) => f.path), env)}`,
155
+ manual: `give them back to your user: sudo chown -R "$(id -un)" <path> for each one listed`,
156
+ }));
157
+ }
158
+ if (truncated)
159
+ out.push(check({ level: "info", text: `permissions: stopped after ${WALK_LIMIT} entries; the rest was not checked` }));
160
+ return out;
161
+ }
162
+ // ---- mcpd port owner
163
+ async function portCheck(env) {
164
+ const { answersAsMcpd, mcpdPort, readToken } = await import("../mcpd/state.js");
165
+ const { describeOwner, portOwner } = await import("../mcpd/peerpid.js");
166
+ const port = mcpdPort(env);
167
+ const owner = await portOwner(port, { env });
168
+ const uid = process.getuid?.();
169
+ if (!owner)
170
+ return check({ level: "info", text: `mcpd port ${port}: nothing listens there (mcpd is not running)` });
171
+ if (owner.uid !== undefined && uid !== undefined && owner.uid !== uid) {
172
+ return check({
173
+ level: "fail",
174
+ text: `mcpd port ${port}: held by ${describeOwner(owner)}, another user, so sessions would send it the gateway token`,
175
+ manual: "stop it or move mcpd (turno config set mcpd.port <port>, then turno mcp sync), then turno mcp token rotate",
176
+ });
177
+ }
178
+ const ours = await answersAsMcpd(port, readToken(env, () => { }));
179
+ if (ours)
180
+ return check({ level: "ok", text: `mcpd port ${port}: held by mcpd${ours.pid ? ` (pid ${ours.pid})` : ""} under your user` });
181
+ return check({
182
+ level: "warn",
183
+ text: `mcpd port ${port}: held by ${describeOwner(owner)}, which does not answer as mcpd, so sessions would send it the gateway token`,
184
+ manual: "stop that process, or move mcpd: turno config set mcpd.port <port>, then turno mcp sync",
185
+ });
186
+ }
187
+ /** Entries turno wrote: their token is the gateway's, checked by the token age instead. */
188
+ function isGatewayEntry(e) {
189
+ const headers = { ...(isObject(e.headers) ? e.headers : {}), ...(isObject(e.http_headers) ? e.http_headers : {}) };
190
+ if (Object.keys(headers).some((h) => h.toLowerCase() === "x-turno-profile"))
191
+ return true;
192
+ return e.bearer_token_env_var === "TURNO_MCPD_TOKEN";
193
+ }
194
+ /** Where an MCP entry holds a literal secret: `env.KEY`, `headers.Authorization`, `args`, `url`. */
195
+ export async function entrySecrets(e) {
196
+ if (isGatewayEntry(e))
197
+ return [];
198
+ const { argSecrets, isSecretValue, urlSecrets } = await import("../mcpd/importer.js");
199
+ const out = [];
200
+ for (const table of ["env", "headers", "http_headers"]) {
201
+ const t = e[table];
202
+ if (!isObject(t))
203
+ continue;
204
+ for (const [k, v] of Object.entries(t))
205
+ if (typeof v === "string" && isSecretValue(k, v))
206
+ out.push(`${table}.${k}`);
207
+ }
208
+ if (Array.isArray(e.args) && argSecrets(e.args.map(String)).length)
209
+ out.push("args");
210
+ if (typeof e.url === "string" && urlSecrets(e.url).length)
211
+ out.push("url");
212
+ return out;
213
+ }
214
+ /** The server maps of an agent config: `mcpServers` (and Claude Code's per-project ones) or Codex's `mcp_servers`. */
215
+ function serverMaps(doc) {
216
+ const maps = [];
217
+ const add = (v) => {
218
+ if (isObject(v))
219
+ maps.push(Object.fromEntries(Object.entries(v).filter(([, e]) => isObject(e))));
220
+ };
221
+ add(doc.mcpServers);
222
+ add(doc.mcp_servers);
223
+ if (isObject(doc.projects))
224
+ for (const proj of Object.values(doc.projects))
225
+ if (isObject(proj))
226
+ add(proj.mcpServers);
227
+ return maps;
228
+ }
229
+ function readDoc(file) {
230
+ let text;
231
+ try {
232
+ text = readFileSync(file, "utf8");
233
+ }
234
+ catch {
235
+ return undefined;
236
+ }
237
+ try {
238
+ const v = /\.toml$/.test(file) ? parseToml(text) : JSON.parse(text);
239
+ return isObject(v) ? v : undefined;
240
+ }
241
+ catch {
242
+ return undefined;
243
+ }
244
+ }
245
+ /** `server.where` for every literal secret in an agent config (JSON or TOML). */
246
+ export async function configSecrets(file) {
247
+ const doc = readDoc(file);
248
+ if (!doc)
249
+ return [];
250
+ const out = [];
251
+ for (const map of serverMaps(doc))
252
+ for (const [name, e] of Object.entries(map))
253
+ for (const w of await entrySecrets(e))
254
+ out.push(`${name}.${w}`);
255
+ return [...new Set(out)];
256
+ }
257
+ /** `server.where` for every literal secret in mcp.toml, variants included. */
258
+ async function manifestSecrets(file) {
259
+ const doc = readDoc(file);
260
+ if (!doc || !isObject(doc.server))
261
+ return [];
262
+ const out = [];
263
+ for (const [name, def] of Object.entries(doc.server)) {
264
+ if (!isObject(def))
265
+ continue;
266
+ for (const w of await entrySecrets(def))
267
+ out.push(`${name}.${w}`);
268
+ if (isObject(def.variants)) {
269
+ for (const [variant, v] of Object.entries(def.variants))
270
+ if (isObject(v))
271
+ for (const w of await entrySecrets(v))
272
+ out.push(`${name}.variants.${variant}.${w}`);
273
+ }
274
+ }
275
+ return out;
276
+ }
277
+ /** The agent config files on this machine that can hold MCP servers: hubs and every profile's. */
278
+ function agentConfigFiles(env, config) {
279
+ const files = new Set(SCAN_ORDER.map((id) => adapter(id).mcp.hubFile(env)));
280
+ if (config) {
281
+ for (const name of listProfiles(config, env))
282
+ files.add(mcpFileFor(name, agentOf(name, config), env));
283
+ }
284
+ return [...files].filter((f) => existsSync(f));
285
+ }
286
+ async function secretChecks(env, config) {
287
+ const p = paths(env);
288
+ const out = [];
289
+ const inManifest = existsSync(p.mcpFile) ? await manifestSecrets(p.mcpFile) : [];
290
+ if (inManifest.length) {
291
+ out.push(check({
292
+ level: "warn",
293
+ text: `literal secrets in ${tildify(p.mcpFile, env)}: ${inManifest.join(", ")}`,
294
+ manual: "store each with turno secret set <name> and write keychain:<name> in its place (args and URLs cannot hold references; see docs/mcp.md)",
295
+ }));
296
+ }
297
+ let clean = 0;
298
+ for (const file of agentConfigFiles(env, config)) {
299
+ const found = await configSecrets(file);
300
+ if (!found.length) {
301
+ clean++;
302
+ continue;
303
+ }
304
+ out.push(check({
305
+ level: "warn",
306
+ text: `literal secrets in ${tildify(file, env)}: ${found.join(", ")}`,
307
+ hint: "turno mcp import --write --move-secrets && turno mcp sync",
308
+ }));
309
+ }
310
+ if (!out.length)
311
+ out.push(check({ level: "ok", text: `no literal secrets in mcp.toml or ${clean} agent config${clean === 1 ? "" : "s"}` }));
312
+ out.push(...(await backupChecks(env)));
313
+ return out;
314
+ }
315
+ /** Backups (journal copies) of configs that held literal secrets when they were taken. */
316
+ async function backupChecks(env) {
317
+ const dir = paths(env).backupsDir;
318
+ let stamps;
319
+ try {
320
+ stamps = readdirSync(dir).sort();
321
+ }
322
+ catch {
323
+ return [];
324
+ }
325
+ const holding = [];
326
+ for (const stamp of stamps) {
327
+ const files = join(dir, stamp, "files");
328
+ let names;
329
+ try {
330
+ names = readdirSync(files);
331
+ }
332
+ catch {
333
+ continue;
334
+ }
335
+ for (const name of names) {
336
+ const file = join(files, name);
337
+ try {
338
+ if (!statSync(file).isFile() || statSync(file).size > 16 * 1024 * 1024)
339
+ continue;
340
+ }
341
+ catch {
342
+ continue;
343
+ }
344
+ if (/\.(json|toml)$/.test(name) && ((await configSecrets(file)).length || (await manifestSecrets(file)).length)) {
345
+ holding.push(stamp);
346
+ break;
347
+ }
348
+ }
349
+ }
350
+ if (!holding.length)
351
+ return [];
352
+ return [
353
+ check({
354
+ level: "warn",
355
+ text: `${holding.length} backup${holding.length === 1 ? "" : "s"} in ${tildify(dir, env)} hold configs with literal secrets (oldest ${holding[0]}); backups are pruned after 30 days`,
356
+ hint: "turno undo --prune --older-than 1d",
357
+ }),
358
+ ];
359
+ }
360
+ // ---- versions
361
+ const EXACT = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
362
+ /** Whether an npm spec names one exact version: `pkg@1.2.3`, `@scope/pkg@1.2.3`. */
363
+ export function isExactNpmSpec(spec) {
364
+ const at = spec.lastIndexOf("@");
365
+ return at > 0 && EXACT.test(spec.slice(at + 1));
366
+ }
367
+ /** Whether a uvx/pipx spec names one exact version: `pkg==1.2.3` or `pkg@1.2.3`. */
368
+ function isExactPySpec(spec) {
369
+ const m = /(?:==|@)([^=@]+)$/.exec(spec);
370
+ return Boolean(m && /^\d+(?:\.\d+)*\S*$/.test(m[1]));
371
+ }
372
+ /** The package a runner command fetches at start (npx, bunx, pnpm dlx, uvx), if it is one. */
373
+ async function fetchedPackage(command, args) {
374
+ const bin = basename(command);
375
+ const { parseNpx } = await import("../mcpd/importer.js");
376
+ if (bin === "npx" || bin === "bunx") {
377
+ const { pkg } = parseNpx(args);
378
+ return pkg ? { runner: bin, spec: pkg, exact: isExactNpmSpec(pkg) } : undefined;
379
+ }
380
+ if (bin === "pnpm" && args[0] === "dlx") {
381
+ const pkg = args.slice(1).find((a) => !a.startsWith("-"));
382
+ return pkg ? { runner: "pnpm dlx", spec: pkg, exact: isExactNpmSpec(pkg) } : undefined;
383
+ }
384
+ if (bin === "uvx") {
385
+ const from = args.indexOf("--from");
386
+ const pkg = from >= 0 ? args[from + 1] : args.find((a) => !a.startsWith("-"));
387
+ return pkg ? { runner: bin, spec: pkg, exact: isExactPySpec(pkg) } : undefined;
388
+ }
389
+ return undefined;
390
+ }
391
+ async function versionChecks(env) {
392
+ let manifest;
393
+ try {
394
+ manifest = loadManifest(env);
395
+ }
396
+ catch {
397
+ return []; // a broken mcp.toml is reported by turno doctor
398
+ }
399
+ const serversDir = paths(env).serversDir;
400
+ const loose = [];
401
+ /** Loose servers that `turno mcp install` can pin (an npm package); the others need an edit. */
402
+ const pinnable = [];
403
+ const runtime = [];
404
+ let stdio = 0;
405
+ for (const s of Object.values(manifest.servers)) {
406
+ if (s.kind !== "stdio" || s.builtin)
407
+ continue;
408
+ stdio++;
409
+ if (s.package) {
410
+ if (!isExactNpmSpec(s.package)) {
411
+ loose.push(`${s.name} (package ${s.package})`);
412
+ pinnable.push(s.name);
413
+ }
414
+ else if (!existsSync(join(serversDir, s.name, "node_modules", ".bin", s.command)))
415
+ runtime.push(s.name);
416
+ continue;
417
+ }
418
+ for (const launch of [{ command: s.command, args: s.args }, ...Object.values(s.variants).map((v) => ({ command: v.command ?? s.command, args: v.args ?? s.args }))]) {
419
+ const f = await fetchedPackage(launch.command, launch.args);
420
+ if (f && !f.exact) {
421
+ loose.push(`${s.name} (${f.runner} ${f.spec} fetches the newest version at each start)`);
422
+ break;
423
+ }
424
+ }
425
+ }
426
+ const out = [];
427
+ if (loose.length) {
428
+ const all = pinnable.length === loose.length;
429
+ out.push(check({
430
+ level: "warn",
431
+ text: `MCP servers without an exact version: ${loose.join("; ")}`,
432
+ ...(all
433
+ ? { hint: `turno mcp install ${pinnable.join(" ")}` }
434
+ : { manual: `write an exact version (pkg@1.2.3) in each command in mcp.toml${pinnable.length ? `; turno mcp install ${pinnable.join(" ")} pins the npm packages` : ""}` }),
435
+ }));
436
+ }
437
+ if (runtime.length)
438
+ out.push(check({ level: "info", text: `pinned but not installed, so npx downloads them at each start: ${runtime.join(", ")}`, hint: "turno mcp install" }));
439
+ if (!loose.length && stdio)
440
+ out.push(check({ level: "ok", text: `every stdio MCP server runs an exact version or a fixed command (${stdio})` }));
441
+ return out;
442
+ }
443
+ // ---- gateway token
444
+ function tokenAgeCheck(env, now = Date.now()) {
445
+ const file = paths(env).mcpdToken;
446
+ let mtime;
447
+ let master;
448
+ try {
449
+ mtime = statSync(file).mtimeMs;
450
+ master = readFileSync(file, "utf8").trim();
451
+ }
452
+ catch {
453
+ return [];
454
+ }
455
+ // Profile tokens (ADR 0023) derive from the master token, so they share its age; a token file
456
+ // that does not match it was written before a rotation and no longer opens mcpd.
457
+ const dir = dirname(profileTokenFile("x", env));
458
+ let names = [];
459
+ try {
460
+ names = readdirSync(dir).filter((f) => f.endsWith(".token"));
461
+ }
462
+ catch {
463
+ /* no profile token files */
464
+ }
465
+ const stale = [];
466
+ for (const f of names) {
467
+ let text = "";
468
+ try {
469
+ text = readFileSync(join(dir, f), "utf8").trim();
470
+ }
471
+ catch {
472
+ /* unreadable: counted as stale */
473
+ }
474
+ if (tokenProfile(master, text) !== f.slice(0, -".token".length))
475
+ stale.push(join(dir, f));
476
+ }
477
+ const fresh = names.length - stale.length;
478
+ const derived = fresh ? ` (${fresh} profile token${fresh === 1 ? "" : "s"} derived from it)` : "";
479
+ const days = Math.floor((now - mtime) / DAY_MS);
480
+ const out = [];
481
+ if (days > TOKEN_MAX_AGE_DAYS) {
482
+ out.push(check({
483
+ level: "warn",
484
+ text: `the mcpd token is ${days} days old (more than ${TOKEN_MAX_AGE_DAYS})${derived}`,
485
+ hint: "turno mcp token rotate && turno mcp sync",
486
+ }));
487
+ }
488
+ else
489
+ out.push(check({ level: "ok", text: `the mcpd token is ${days} day${days === 1 ? "" : "s"} old${derived}` }));
490
+ if (stale.length) {
491
+ const one = stale.length === 1;
492
+ out.push(check({
493
+ level: "warn",
494
+ text: `${stale.length} profile token file${one ? " predates" : "s predate"} the mcpd token, so ${one ? "its agent" : "their agents"} cannot reach mcpd (${listPaths(stale, env)})`,
495
+ hint: "turno mcp sync",
496
+ }));
497
+ }
498
+ return out;
499
+ }
500
+ // ---- audit log
501
+ function auditCheck(env) {
502
+ let v;
503
+ try {
504
+ v = verifyAudit(env);
505
+ }
506
+ catch (err) {
507
+ return check({ level: "warn", text: `audit log: cannot read it: ${err.message}`, manual: `check the owner and mode of ${tildify(paths(env).auditLog, env)} (yours, 600)` });
508
+ }
509
+ if (v.lines === 0)
510
+ return undefined;
511
+ if (!v.ok) {
512
+ return check({
513
+ level: "fail",
514
+ text: `audit log: line ${v.line}: ${v.reason}`,
515
+ manual: `find out who changed ${tildify(paths(env).auditLog, env)} after it was written; turno identity log --verify shows the line`,
516
+ });
517
+ }
518
+ return check({ level: "ok", text: `audit log: hash chain intact (${v.lines} line${v.lines === 1 ? "" : "s"}${v.legacy ? `, ${v.legacy} before the chain` : ""})` });
519
+ }
520
+ /** Every security check, in the order `turno doctor --security` prints them. */
521
+ export async function securityChecks(env) {
522
+ let config;
523
+ try {
524
+ config = loadConfig(env);
525
+ }
526
+ catch {
527
+ config = undefined;
528
+ }
529
+ const out = [secretStoreCheck(env), ...permissionChecks(env)];
530
+ out.push(await portCheck(env));
531
+ out.push(...(await secretChecks(env, config)));
532
+ out.push(...(await versionChecks(env)));
533
+ out.push(...tokenAgeCheck(env));
534
+ const audit = auditCheck(env);
535
+ if (audit)
536
+ out.push(audit);
537
+ return out;
538
+ }
539
+ //# sourceMappingURL=security.js.map