turno-cli 0.2.0 → 0.3.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 (112) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.md +127 -39
  3. package/dist/accounts/audit.js +27 -15
  4. package/dist/accounts/builtin.js +35 -7
  5. package/dist/accounts/delegate.js +30 -7
  6. package/dist/accounts/policy.js +4 -2
  7. package/dist/accounts/registry.js +3 -1
  8. package/dist/agents/adapter.js +22 -0
  9. package/dist/agents/claude.js +54 -3
  10. package/dist/agents/codex.js +94 -6
  11. package/dist/agents/copilot.js +19 -2
  12. package/dist/agents/cursor.js +19 -2
  13. package/dist/agents/index.js +1 -1
  14. package/dist/agents/snippets.js +37 -10
  15. package/dist/cli/args.js +32 -15
  16. package/dist/cli/commands/accounts.js +29 -7
  17. package/dist/cli/commands/auto.js +50 -12
  18. package/dist/cli/commands/browser-identity.js +514 -0
  19. package/dist/cli/commands/browser-session.js +102 -0
  20. package/dist/cli/commands/browser-vault.js +193 -0
  21. package/dist/cli/commands/browser.js +159 -59
  22. package/dist/cli/commands/complete.js +13 -3
  23. package/dist/cli/commands/completion.js +4 -0
  24. package/dist/cli/commands/config.js +90 -13
  25. package/dist/cli/commands/demo.js +36 -7
  26. package/dist/cli/commands/doctor.js +170 -36
  27. package/dist/cli/commands/identity.js +99 -12
  28. package/dist/cli/commands/init.js +42 -10
  29. package/dist/cli/commands/limit.js +65 -9
  30. package/dist/cli/commands/mcp-call.js +240 -0
  31. package/dist/cli/commands/mcp-oauth.js +33 -6
  32. package/dist/cli/commands/mcp-observe.js +128 -23
  33. package/dist/cli/commands/mcp-share.js +201 -0
  34. package/dist/cli/commands/mcp.js +203 -42
  35. package/dist/cli/commands/mcpd.js +76 -12
  36. package/dist/cli/commands/open.js +26 -3
  37. package/dist/cli/commands/profile.js +212 -30
  38. package/dist/cli/commands/resolve.js +8 -1
  39. package/dist/cli/commands/run.js +24 -4
  40. package/dist/cli/commands/secret.js +23 -38
  41. package/dist/cli/commands/session.js +16 -5
  42. package/dist/cli/commands/sessions.js +7 -1
  43. package/dist/cli/commands/setup.js +83 -11
  44. package/dist/cli/commands/status.js +67 -15
  45. package/dist/cli/commands/statusline.js +7 -2
  46. package/dist/cli/commands/ui.js +17 -5
  47. package/dist/cli/commands/undo.js +39 -7
  48. package/dist/cli/commands/uninstall.js +24 -5
  49. package/dist/cli/commands/upgrade.js +113 -76
  50. package/dist/cli/commands/usage.js +11 -10
  51. package/dist/cli/commands/version.js +20 -8
  52. package/dist/cli/commands/which.js +5 -3
  53. package/dist/cli/diagnostics.js +184 -0
  54. package/dist/cli/exit.js +65 -0
  55. package/dist/cli/group.js +20 -8
  56. package/dist/cli/help.js +6 -1
  57. package/dist/cli/hints.js +30 -0
  58. package/dist/cli/io.js +24 -8
  59. package/dist/cli/launch.js +31 -2
  60. package/dist/cli/launchers.js +25 -10
  61. package/dist/cli/main.js +52 -18
  62. package/dist/cli/optional.js +144 -0
  63. package/dist/cli/output.js +123 -0
  64. package/dist/cli/picker.js +17 -5
  65. package/dist/cli/registry.js +20 -2
  66. package/dist/cli/safe.js +87 -0
  67. package/dist/cli/secret-input.js +63 -0
  68. package/dist/cli/security.js +31 -9
  69. package/dist/cli/style.js +35 -5
  70. package/dist/cli/topics.js +142 -0
  71. package/dist/core/config.js +39 -3
  72. package/dist/core/fsutil.js +2 -10
  73. package/dist/core/journal.js +19 -11
  74. package/dist/core/manifest.js +28 -1
  75. package/dist/core/paths.js +6 -112
  76. package/dist/core/profiles.js +28 -8
  77. package/dist/core/resolve.js +13 -3
  78. package/dist/core/secrets.js +4 -154
  79. package/dist/core/state-file.js +107 -0
  80. package/dist/core/update.js +14 -11
  81. package/dist/core/version.js +57 -10
  82. package/dist/demo/server.js +10 -2
  83. package/dist/mcpd/cache.js +6 -7
  84. package/dist/mcpd/calllog.js +10 -9
  85. package/dist/mcpd/client-names.js +8 -13
  86. package/dist/mcpd/connectors.js +42 -3
  87. package/dist/mcpd/daemon.js +29 -8
  88. package/dist/mcpd/folder-sets.js +5 -2
  89. package/dist/mcpd/gateway.js +57 -29
  90. package/dist/mcpd/health.js +69 -25
  91. package/dist/mcpd/importer.js +106 -9
  92. package/dist/mcpd/instances.js +59 -31
  93. package/dist/mcpd/jsonrpc.js +3 -1
  94. package/dist/mcpd/middleware.js +144 -0
  95. package/dist/mcpd/modern.js +57 -19
  96. package/dist/mcpd/oauth.js +71 -17
  97. package/dist/mcpd/peerpid.js +15 -3
  98. package/dist/mcpd/pressure.js +4 -1
  99. package/dist/mcpd/rss.js +34 -19
  100. package/dist/mcpd/service.js +28 -4
  101. package/dist/mcpd/share.js +217 -0
  102. package/dist/mcpd/state.js +16 -16
  103. package/dist/mcpd/sync.js +22 -12
  104. package/dist/mcpd/systemd.js +4 -1
  105. package/dist/mcpd/tokens.js +4 -8
  106. package/dist/mcpd/upstream.js +12 -5
  107. package/dist/statusline/cost.js +17 -4
  108. package/dist/statusline/input.js +15 -3
  109. package/dist/ui/fonts.js +1 -1
  110. package/dist/ui/settings.js +6 -1
  111. package/npm-shrinkwrap.json +12 -3
  112. package/package.json +7 -6
@@ -0,0 +1,514 @@
1
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { tildify } from "../../core/paths.js";
5
+ import { JSON_FLAG, bool, parseFlags, str } from "../args.js";
6
+ import { Exit } from "../exit.js";
7
+ import { fail } from "../io.js";
8
+ import { emit, jsonOutput } from "../output.js";
9
+ import { style } from "../style.js";
10
+ /** `turno browser show --json` and `turno identity show browser:<id> --json`. */
11
+ export const SHOW_JSON = jsonOutput(["id", "dir", "settingsFile", "settings", "problems", "inUse", "holder", "health"]);
12
+ /** `turno browser set --json` and `turno identity set browser:<id> --json`: what changed, or would. */
13
+ export const SET_JSON = jsonOutput(["id", "settingsFile", "dryRun", "changes", "settings"]);
14
+ /** `turno browser doctor --json`: the shape of `turno doctor --json`. */
15
+ export const DOCTOR_JSON = jsonOutput(["ok", "counts", "checks", "fixed"]);
16
+ /** `turno browser reputation --json`: one element per identity. */
17
+ export const REPUTATION_JSON = jsonOutput(["id", "file", "total", "sites"]);
18
+ /** Flags that write identity.json, shared by `add` and `set`. An empty value removes the key. */
19
+ export const SETTINGS_FLAGS = {
20
+ timezone: { type: "string" },
21
+ locale: { type: "string" },
22
+ languages: { type: "string" },
23
+ region: { type: "string" },
24
+ "health-url": { type: "string" },
25
+ "health-text": { type: "string" },
26
+ "health-selector": { type: "string" },
27
+ "no-health": { type: "boolean" },
28
+ // How the host runs this identity's Chrome (format 2 of identity.json): the tab governor,
29
+ // background throttling, settle, resource blocking and cache.
30
+ "tabs-max": { type: "string" },
31
+ "tabs-popups": { type: "string" },
32
+ "tabs-park": { type: "string" },
33
+ "tabs-close": { type: "string" },
34
+ "no-tabs": { type: "boolean" },
35
+ "background-throttling": { type: "string" },
36
+ settle: { type: "string" },
37
+ "block-trackers": { type: "string" },
38
+ "block-types": { type: "string" },
39
+ "block-patterns": { type: "string" },
40
+ "no-block": { type: "boolean" },
41
+ cache: { type: "boolean" },
42
+ "cache-max-size": { type: "string" },
43
+ "no-cache": { type: "boolean" },
44
+ };
45
+ /** The identity.json key behind each tuning flag, so the package's messages name the flag. */
46
+ const KEY_FLAGS = [
47
+ ["tabs.max", "--tabs-max"],
48
+ ["tabs.popups", "--tabs-popups"],
49
+ ["tabs.park", "--tabs-park"],
50
+ ["tabs.close", "--tabs-close"],
51
+ ["backgroundThrottling", "--background-throttling"],
52
+ ["settle", "--settle"],
53
+ ["block.trackers", "--block-trackers"],
54
+ ["block.types", "--block-types"],
55
+ ["block.patterns", "--block-patterns"],
56
+ ["cache.maxSize", "--cache-max-size"],
57
+ ];
58
+ const TABS_MAX_PROBLEM = "--tabs-max must be a whole number from 0 (no cap) to 100";
59
+ /**
60
+ * A rejected identity.json with each problem of a tuning key told as its flag: the package
61
+ * says `identity "school": settle must be ...`, the command line says `--settle must be ...`.
62
+ * Other messages stay as the package wrote them.
63
+ */
64
+ function flagMessage(message) {
65
+ const problems = message.replace(/^identity "[^"]*": /, "").split("; ");
66
+ const told = problems.map((p) => {
67
+ const hit = KEY_FLAGS.find(([key]) => p.startsWith(`${key} `));
68
+ return hit ? `${hit[1]}${p.slice(hit[0].length)}` : undefined;
69
+ });
70
+ return told.every((t) => t !== undefined) ? told.join("; ") : message;
71
+ }
72
+ /** A true or false flag value; also on/off and yes/no. */
73
+ function booleanValue(flag, v) {
74
+ const word = v.toLowerCase();
75
+ if (["true", "on", "yes"].includes(word))
76
+ return true;
77
+ if (["false", "off", "no"].includes(word))
78
+ return false;
79
+ return fail(`${flag} must be true or false (an empty value removes it)`);
80
+ }
81
+ const list = (v) => v
82
+ .split(",")
83
+ .map((x) => x.trim())
84
+ .filter(Boolean);
85
+ /**
86
+ * A group of identity.json (tabs, block, cache) after the flags: `parts` set or (with null)
87
+ * remove its keys, the rest of `base` stays. Null when nothing is left, so the key goes.
88
+ */
89
+ function mergeGroup(base, parts) {
90
+ const next = { ...base };
91
+ for (const [k, v] of Object.entries(parts)) {
92
+ if (v === undefined)
93
+ continue;
94
+ if (v === null)
95
+ delete next[k];
96
+ else
97
+ next[k] = v;
98
+ }
99
+ return Object.keys(next).length ? next : null;
100
+ }
101
+ export const SETTINGS_FLAG_NAMES = Object.keys(SETTINGS_FLAGS).map((f) => `--${f}`);
102
+ /** The identity.json change the flags ask for; `current` fills the parts of health not given. */
103
+ export function settingsPatch(p, current) {
104
+ const patch = {};
105
+ const value = (name) => {
106
+ const v = str(p, name);
107
+ return v === undefined ? undefined : v.trim() === "" ? null : v.trim();
108
+ };
109
+ for (const key of ["timezone", "locale", "region"]) {
110
+ const v = value(key);
111
+ if (v !== undefined)
112
+ patch[key] = v;
113
+ }
114
+ const langs = value("languages");
115
+ if (langs !== undefined)
116
+ patch.languages =
117
+ langs === null
118
+ ? null
119
+ : langs
120
+ .split(",")
121
+ .map((l) => l.trim())
122
+ .filter(Boolean);
123
+ const url = value("health-url");
124
+ const text = value("health-text");
125
+ const selector = value("health-selector");
126
+ if (bool(p, "no-health")) {
127
+ if (url !== undefined || text !== undefined || selector !== undefined)
128
+ fail("--no-health does not go with the other --health flags");
129
+ patch.health = null;
130
+ }
131
+ else if (url !== undefined || text !== undefined || selector !== undefined) {
132
+ const base = current?.health;
133
+ const health = { url: url ?? base?.url ?? "" };
134
+ const t = text === undefined ? base?.text : (text ?? undefined);
135
+ const s = selector === undefined ? base?.selector : (selector ?? undefined);
136
+ if (t)
137
+ health.text = t;
138
+ if (s)
139
+ health.selector = s;
140
+ if (!health.url)
141
+ fail("a health check needs --health-url (a page only a signed-in user sees)");
142
+ if (!health.text && !health.selector)
143
+ fail("a health check needs --health-text or --health-selector (what that page shows when signed in)");
144
+ patch.health = health;
145
+ }
146
+ tuningPatch(p, value, patch, current);
147
+ return patch;
148
+ }
149
+ /** The format 2 keys of the patch: tabs, backgroundThrottling, settle, block and cache. */
150
+ function tuningPatch(p, value, patch, current) {
151
+ const tabs = {
152
+ max: value("tabs-max"),
153
+ popups: value("tabs-popups"),
154
+ park: value("tabs-park"),
155
+ close: value("tabs-close"),
156
+ };
157
+ if (bool(p, "no-tabs")) {
158
+ if (Object.values(tabs).some((v) => v !== undefined))
159
+ fail("--no-tabs does not go with the other --tabs flags");
160
+ patch.tabs = null;
161
+ }
162
+ else if (Object.values(tabs).some((v) => v !== undefined)) {
163
+ let max;
164
+ if (typeof tabs.max === "string") {
165
+ if (!/^\d+$/.test(tabs.max))
166
+ fail(TABS_MAX_PROBLEM);
167
+ max = Number(tabs.max);
168
+ }
169
+ else
170
+ max = tabs.max;
171
+ patch.tabs = mergeGroup(current?.tabs, { ...tabs, max });
172
+ }
173
+ const throttling = value("background-throttling");
174
+ if (throttling !== undefined)
175
+ patch.backgroundThrottling = throttling === null ? null : booleanValue("--background-throttling", throttling);
176
+ const settle = value("settle");
177
+ if (settle !== undefined)
178
+ patch.settle = settle;
179
+ const trackers = value("block-trackers");
180
+ const types = value("block-types");
181
+ const patterns = value("block-patterns");
182
+ if (bool(p, "no-block")) {
183
+ if (trackers !== undefined || types !== undefined || patterns !== undefined)
184
+ fail("--no-block does not go with the other --block flags");
185
+ patch.block = null;
186
+ }
187
+ else if (trackers !== undefined || types !== undefined || patterns !== undefined) {
188
+ patch.block = mergeGroup(current?.block, {
189
+ trackers: typeof trackers === "string" ? booleanValue("--block-trackers", trackers) : trackers,
190
+ types: typeof types === "string" ? list(types) : types,
191
+ patterns: typeof patterns === "string" ? list(patterns) : patterns,
192
+ });
193
+ }
194
+ const maxSize = value("cache-max-size");
195
+ if (bool(p, "no-cache")) {
196
+ if (bool(p, "cache") || maxSize !== undefined)
197
+ fail("--no-cache does not go with --cache or --cache-max-size");
198
+ patch.cache = null;
199
+ }
200
+ else if (bool(p, "cache") || maxSize !== undefined) {
201
+ // The cache stays on when its size is removed: {} is on with the default size.
202
+ patch.cache = mergeGroup(current?.cache, { maxSize }) ?? {};
203
+ }
204
+ }
205
+ export function hasSettings(patch) {
206
+ return Object.keys(patch).length > 0;
207
+ }
208
+ function describeHealth(h) {
209
+ return [h.url, h.text ? `shows "${h.text}"` : "", h.selector ? `has ${h.selector}` : ""].filter(Boolean).join(" ");
210
+ }
211
+ function describeTabs(t) {
212
+ const parts = [];
213
+ if (t.max !== undefined)
214
+ parts.push(t.max === 0 ? "no cap on open tabs" : `at most ${t.max} open`);
215
+ if (t.popups)
216
+ parts.push(t.popups === "keep" ? "popups kept" : "popups closed");
217
+ if (t.park !== undefined)
218
+ parts.push(t.park === "0" ? "never parked" : `parked after ${t.park}`);
219
+ if (t.close !== undefined)
220
+ parts.push(t.close === "0" ? "never closed when unused" : `closed after ${t.close}`);
221
+ return parts.join(", ");
222
+ }
223
+ function describeBlock(b) {
224
+ const n = b.patterns?.length ?? 0;
225
+ return [b.trackers ? "trackers" : "", ...(b.types ?? []), n ? `${n} pattern${n === 1 ? "" : "s"}` : ""]
226
+ .filter(Boolean)
227
+ .join(", ");
228
+ }
229
+ export function show(m, id, args, io) {
230
+ const p = parseFlags(args, JSON_FLAG, 1);
231
+ if (!m.identityExists(id, io.env))
232
+ return fail(`identity "${id}" does not exist (turno identity add browser:${id})`);
233
+ const { path, settings, problems } = m.checkIdentitySettings(id, io.env);
234
+ const holder = m.inUseBy(id, io.env);
235
+ const health = m.readHealth(id, io.env);
236
+ if (bool(p, "json")) {
237
+ emit(io, p, SHOW_JSON, {
238
+ id: `browser:${id}`,
239
+ dir: tildify(m.identityDir(id, io.env), io.env),
240
+ settingsFile: tildify(path, io.env),
241
+ settings: settings ?? null,
242
+ problems,
243
+ inUse: holder !== undefined,
244
+ holder: holder ?? null,
245
+ health: health ?? null,
246
+ });
247
+ return Exit.ok;
248
+ }
249
+ const s = style(io);
250
+ const rows = [
251
+ ["profile", tildify(m.identityDir(id, io.env), io.env)],
252
+ [
253
+ "settings",
254
+ `${tildify(path, io.env)}${settings || problems.length ? "" : s.muted(" (none: Chrome's own time zone and languages)")}`,
255
+ ],
256
+ ];
257
+ if (settings) {
258
+ rows.push(["time zone", settings.timezone ?? s.muted("(the system's)")]);
259
+ if (settings.locale)
260
+ rows.push(["locale", settings.locale]);
261
+ rows.push([
262
+ "languages",
263
+ settings.languages?.join(", ") ?? s.muted(settings.locale ? "(from the locale)" : "(Chrome's)"),
264
+ ]);
265
+ if (settings.region)
266
+ rows.push(["region", settings.region]);
267
+ rows.push(["health check", settings.health ? describeHealth(settings.health) : s.muted("(none)")]);
268
+ if (settings.tabs)
269
+ rows.push(["tabs", `${describeTabs(settings.tabs)}${s.muted(" (the rest as default)")}`]);
270
+ if (settings.backgroundThrottling !== undefined)
271
+ rows.push([
272
+ "throttling",
273
+ settings.backgroundThrottling ? "background tabs throttled" : "every tab at full speed",
274
+ ]);
275
+ if (settings.settle !== undefined)
276
+ rows.push(["settle", settings.settle]);
277
+ if (settings.block)
278
+ rows.push(["blocking", describeBlock(settings.block) || s.muted("(nothing)")]);
279
+ if (settings.cache)
280
+ rows.push(["cache", `on, up to ${settings.cache.maxSize ?? "100MB"}`]);
281
+ if (settings.keychain === "system")
282
+ rows.push(["cookie key", "the system keychain (identity.json keychain)"]);
283
+ rows.push(["created", settings.created]);
284
+ rows.push(["updated", settings.updated]);
285
+ }
286
+ if (health) {
287
+ const state = health.status === "ok"
288
+ ? s.ok("signed in")
289
+ : health.status === "needs_auth"
290
+ ? s.err("NEEDS_AUTH")
291
+ : s.warn("check failed");
292
+ rows.push(["last check", `${state} ${s.muted(`${health.checkedAt}${health.detail ? `: ${health.detail}` : ""}`)}`]);
293
+ }
294
+ rows.push([
295
+ "state",
296
+ holder ? s.warn(holder.replace(/^browser identity "[^"]+" is /, "").replace(/\. .*$/, "")) : s.ok("free"),
297
+ ]);
298
+ io.out(s.bold(`browser:${id}`));
299
+ const width = Math.max(...rows.map(([k]) => k.length));
300
+ for (const [k, v] of rows)
301
+ io.out(s.kv(k, v, width));
302
+ for (const problem of problems)
303
+ io.out(s.note("err", `identity.json ${problem}`));
304
+ if (health?.status === "needs_auth")
305
+ io.out(s.note("info", `sign in again: turno browser login ${id}`));
306
+ return Exit.ok;
307
+ }
308
+ const SET_FLAGS = { ...SETTINGS_FLAGS, "dry-run": { type: "boolean" }, ...JSON_FLAG };
309
+ /** The arguments of `set` after the identity, for the usage line. */
310
+ export const SET_SYNOPSIS = "[--timezone <zone>] [--locale <tag>] [--languages <tag,...>] [--region <CC>] [--health-url <url>] [--health-text <text>] [--health-selector <css>] [--no-health] " +
311
+ "[--tabs-max <n>] [--tabs-popups close|keep] [--tabs-park <duration>] [--tabs-close <duration>] [--no-tabs] [--background-throttling true|false] [--settle <duration>] " +
312
+ "[--block-trackers true|false] [--block-types image,media,font] [--block-patterns <host|glob>,...] [--no-block] [--cache] [--cache-max-size <size>] [--no-cache] [--dry-run] [--json]";
313
+ /** More help for `set`: what each tuning flag writes to identity.json. */
314
+ export const SET_DETAILS = `Each flag writes one key of identity.json; an empty value (--settle "") removes it, and
315
+ --no-health, --no-tabs, --no-block and --no-cache remove a whole group. A flag of a group
316
+ changes only its part: the rest of that group stays.
317
+
318
+ How the host runs this identity's Chrome (read at every Chrome start):
319
+ --tabs-max <n> most tabs open at once, 0 for no cap (default 8)
320
+ --tabs-popups close|keep close popups the agent did not open (default close)
321
+ --tabs-park <duration> park an unused tab on about:blank, "0" never (default 5m)
322
+ --tabs-close <duration> close an unused tab, "0" never (default 15m)
323
+ --background-throttling <bool> let Chrome slow tabs that are not in front (default false)
324
+ --settle <duration> wait after each action for the work it started, "0" to "10s"
325
+ --block-trackers <bool> block a built-in list of ad and analytics hosts
326
+ --block-types <list> block image, media and font requests (never the page itself)
327
+ --block-patterns <list> block host names (and subdomains) or URL globs with *
328
+ --cache keep images, fonts, styles and scripts on disk (100MB)
329
+ --cache-max-size <size> the cache's size, "1MB" to "10GB"; turns the cache on
330
+
331
+ Blocking without the cache turns Chrome's own HTTP cache off: use them together.`;
332
+ /** The flags of `set`, for completion. */
333
+ export const SET_FLAG_NAMES = ["--dry-run", "--json", ...SETTINGS_FLAG_NAMES];
334
+ /**
335
+ * The package's own validation, run on a copy: identity.json is copied to a throwaway data
336
+ * folder and the patch written there, so `--dry-run` refuses exactly what the write would and
337
+ * shows the file it would leave, without touching the real one.
338
+ */
339
+ function rehearse(m, id, patch, env) {
340
+ const dir = mkdtempSync(join(env.TMPDIR || tmpdir(), "turno-identity-"));
341
+ try {
342
+ const copy = { ...env, TURNO_DATA_DIR: dir };
343
+ const from = m.identitySettingsPath(id, env);
344
+ const to = m.identitySettingsPath(id, copy);
345
+ mkdirSync(dirname(to), { recursive: true, mode: 0o700 });
346
+ if (existsSync(from))
347
+ copyFileSync(from, to);
348
+ return m.writeIdentitySettings(id, patch, copy);
349
+ }
350
+ finally {
351
+ rmSync(dir, { recursive: true, force: true });
352
+ }
353
+ }
354
+ export function set(m, id, args, io) {
355
+ const p = parseFlags(args, SET_FLAGS, 1);
356
+ if (!m.identityExists(id, io.env))
357
+ return fail(`identity "${id}" does not exist (turno identity add browser:${id})`);
358
+ const patch = settingsPatch(p, m.checkIdentitySettings(id, io.env).settings);
359
+ if (!hasSettings(patch))
360
+ return fail(`nothing to set: pass ${SETTINGS_FLAG_NAMES.join(", ")} (an empty value removes one)`);
361
+ const dryRun = bool(p, "dry-run");
362
+ let settings;
363
+ try {
364
+ settings = dryRun ? rehearse(m, id, patch, io.env) : m.writeIdentitySettings(id, patch, io.env);
365
+ }
366
+ catch (err) {
367
+ if (err.name === "IdentityError")
368
+ return fail(flagMessage(err.message));
369
+ throw err;
370
+ }
371
+ if (bool(p, "json")) {
372
+ emit(io, p, SET_JSON, {
373
+ id: `browser:${id}`,
374
+ settingsFile: tildify(m.identitySettingsPath(id, io.env), io.env),
375
+ dryRun,
376
+ changes: patch,
377
+ settings,
378
+ });
379
+ return Exit.ok;
380
+ }
381
+ if (dryRun) {
382
+ io.out(`(dry run) would update identity.json of "${id}": ${JSON.stringify(patch)}`);
383
+ return Exit.ok;
384
+ }
385
+ io.out(`updated identity.json of "${id}"; the next Chrome start of browser-${id} uses it\n`);
386
+ return show(m, id, [], io);
387
+ }
388
+ const DOCTOR_FLAGS = { fix: { type: "boolean" }, "no-launch": { type: "boolean" }, ...JSON_FLAG };
389
+ const SECTIONS = [
390
+ ["Chrome", (a) => a === "chrome"],
391
+ ["System", (a) => a === "system"],
392
+ ["Identities", (a) => a === "identities" || a.startsWith("identity ")],
393
+ ];
394
+ export async function doctor(m, args, io) {
395
+ const p = parseFlags(args, DOCTOR_FLAGS, 0);
396
+ const json = bool(p, "json");
397
+ const report = await m.runDoctor({ env: io.env, fix: bool(p, "fix"), launch: !bool(p, "no-launch") });
398
+ const failed = report.checks.some((c) => c.level === "fail");
399
+ const exit = failed ? Exit.failure : Exit.ok;
400
+ const status = (c) => (c.level === "info" ? "skip" : c.level);
401
+ const n = (l) => report.checks.filter((c) => c.level === l).length;
402
+ if (json) {
403
+ emit(io, p, DOCTOR_JSON, {
404
+ ok: !failed,
405
+ counts: { ok: n("ok"), warn: n("warn"), fail: n("fail"), skip: n("info") },
406
+ fixed: report.fixed,
407
+ checks: report.checks.map((c) => ({
408
+ area: c.area,
409
+ status: status(c),
410
+ text: c.text,
411
+ fix: c.level === "ok" ? null : (c.fix ?? null),
412
+ auto: Boolean(c.auto) && (c.level === "warn" || c.level === "fail"),
413
+ manual: c.level === "ok" ? null : (c.manual ?? null),
414
+ })),
415
+ });
416
+ return exit;
417
+ }
418
+ const s = style(io);
419
+ for (const f of report.fixed)
420
+ io.out(s.check("ok", `fixed: ${f}`));
421
+ if (report.fixed.length)
422
+ io.out("");
423
+ const ICON = { ok: "ok", warn: "warn", fail: "err", info: "skip" };
424
+ let first = true;
425
+ for (const [title, has] of SECTIONS) {
426
+ const rows = report.checks.filter((c) => has(c.area));
427
+ if (!rows.length)
428
+ continue;
429
+ if (!first)
430
+ io.out("");
431
+ first = false;
432
+ io.out(s.header(title));
433
+ let area = "";
434
+ for (const c of rows) {
435
+ if (c.area.startsWith("identity ") && c.area !== area)
436
+ io.out(` ${s.bold(`browser:${c.area.slice("identity ".length)}`)}`);
437
+ area = c.area;
438
+ const indent = c.area.startsWith("identity ") ? 4 : 2;
439
+ const text = c.level === "fail" ? s.err(c.text) : c.level === "info" ? s.muted(c.text) : c.text;
440
+ io.out(s.note(ICON[c.level], text, indent));
441
+ if (c.level === "ok")
442
+ continue;
443
+ const under = " ".repeat(indent + 2);
444
+ const label = c.level === "info" ? "optional:" : "fix:";
445
+ if (c.fix)
446
+ io.out(s.wrap(`${under}${s.muted(label)} `, `${c.level === "info" ? s.muted(c.fix) : s.bold(c.fix)}${c.auto ? s.muted(" (runs with --fix)") : ""}`));
447
+ else if (c.manual)
448
+ io.out(s.wrap(`${under}${s.muted("manual:")} `, c.manual));
449
+ }
450
+ }
451
+ io.out("");
452
+ io.out([
453
+ `${n("ok")} ok`,
454
+ n("warn") ? `${n("warn")} warning${n("warn") === 1 ? "" : "s"}` : "",
455
+ n("fail") ? `${n("fail")} failure${n("fail") === 1 ? "" : "s"}` : "",
456
+ ]
457
+ .filter(Boolean)
458
+ .join(", "));
459
+ return exit;
460
+ }
461
+ export function reputation(m, args, io, checkId) {
462
+ const p = parseFlags(args, JSON_FLAG, 1);
463
+ const id = p.positionals[0] === undefined ? undefined : checkId(p.positionals[0].replace(/^browser:/, ""));
464
+ let report;
465
+ try {
466
+ report = m.reputationReport(io.env, id ? [id] : undefined);
467
+ }
468
+ catch (err) {
469
+ return fail(err.message);
470
+ }
471
+ if (bool(p, "json")) {
472
+ emit(io, p, REPUTATION_JSON, report.identities.map((i) => ({
473
+ id: `browser:${i.id}`,
474
+ file: tildify(i.file, io.env),
475
+ total: i.total,
476
+ sites: i.sites,
477
+ })));
478
+ return Exit.ok;
479
+ }
480
+ const s = style(io);
481
+ if (!report.identities.length) {
482
+ io.out("No browser identities yet. Create one with `turno identity add browser:<id>`.");
483
+ return Exit.ok;
484
+ }
485
+ const TREND = { up: s.warn("up"), down: s.ok("down"), flat: s.muted("flat") };
486
+ for (const [i, ident] of report.identities.entries()) {
487
+ if (i)
488
+ io.out("");
489
+ io.out(s.header(`browser:${ident.id}`));
490
+ if (!ident.sites.length) {
491
+ io.out(` ${s.muted("no challenges recorded")}`);
492
+ continue;
493
+ }
494
+ const head = ["site", "total", "captcha", "verify", "block", "7d", "prev 7d", "trend", "last seen"].map((h) => s.muted(h));
495
+ const rows = ident.sites.map((x) => [
496
+ x.site,
497
+ String(x.total),
498
+ String(x.captcha),
499
+ String(x.verify),
500
+ String(x.block),
501
+ String(x.last7d),
502
+ String(x.prev7d),
503
+ TREND[x.trend],
504
+ x.lastSeen,
505
+ ]);
506
+ const right = { align: "right" };
507
+ for (const l of s.table([head, ...rows], {
508
+ columns: [{}, right, right, right, right, right, right, {}, { drop: 1 }],
509
+ }))
510
+ io.out(l);
511
+ }
512
+ return Exit.ok;
513
+ }
514
+ //# sourceMappingURL=browser-identity.js.map
@@ -0,0 +1,102 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { tildify } from "../../core/paths.js";
4
+ import { DRY_RUN, bool, parseFlags, str } from "../args.js";
5
+ import { fail, needsAnswer, noInputReason } from "../io.js";
6
+ import { terminalInput } from "./browser-vault.js";
7
+ /**
8
+ * `turno browser export` and `turno browser import`: an identity's signed-in session
9
+ * (cookies, localStorage, IndexedDB) as one file encrypted under a passphrase, with an expiry
10
+ * inside. The passphrase comes from a hidden prompt (asked twice on export) or the first line
11
+ * of stdin, never from a flag.
12
+ */
13
+ const EXPORT_FLAGS = {
14
+ out: { type: "string", short: "o" },
15
+ expires: { type: "string" },
16
+ force: { type: "boolean" },
17
+ };
18
+ const IMPORT_FLAGS = { as: { type: "string" }, yes: { type: "boolean", short: "y" }, ...DRY_RUN };
19
+ const DAY = 24 * 3600_000;
20
+ /** `7d`, `36h`: how long an export can be imported. */
21
+ export function parseExpiry(text) {
22
+ const m = /^(\d+)\s*(d|h)$/.exec(text.trim());
23
+ const ms = m ? Number(m[1]) * (m[2] === "d" ? DAY : 3600_000) : Number.NaN;
24
+ if (!(ms > 0 && ms <= 90 * DAY))
25
+ return fail(`--expires takes hours or days up to 90d, like 7d or 12h, not "${text}"`);
26
+ return ms;
27
+ }
28
+ async function passphrase(io, input, confirm) {
29
+ if (input.isTty()) {
30
+ if (noInputReason(io.env))
31
+ needsAnswer(confirm ? "browser export" : "browser import", "the passphrase on stdin");
32
+ const first = await input.hidden("Passphrase (input hidden): ");
33
+ if (confirm && (await input.hidden("Passphrase again: ")) !== first)
34
+ return fail("the passphrases differ; nothing was written");
35
+ return first;
36
+ }
37
+ return (await input.stdin()).split(/\r?\n/)[0] ?? "";
38
+ }
39
+ export async function exportSession(mod, args, io, input = terminalInput) {
40
+ const p = parseFlags(args, EXPORT_FLAGS, 1);
41
+ const id = p.positionals[0];
42
+ if (!id)
43
+ return fail("usage: turno browser export <id> --out <file> [--expires 7d] [--force]");
44
+ mod.assertIdentityId(id);
45
+ if (!mod.identityExists(id, io.env))
46
+ return fail(`browser identity "${id}" does not exist`);
47
+ const out = str(p, "out");
48
+ if (!out)
49
+ return fail("give the file to write with --out (for example --out school.session)");
50
+ const expiresInMs = parseExpiry(str(p, "expires") ?? "7d");
51
+ const file = resolve(out);
52
+ const secret = await passphrase(io, input, true);
53
+ const { sealed, summary } = await mod.exportSession(id, { passphrase: secret, expiresInMs, env: io.env });
54
+ try {
55
+ writeFileSync(file, sealed, { mode: 0o600, flag: bool(p, "force") ? "w" : "wx" });
56
+ }
57
+ catch (err) {
58
+ if (err.code === "EEXIST")
59
+ return fail(`${tildify(file, io.env)} exists; pass --force to replace it`);
60
+ throw err;
61
+ }
62
+ io.out(`exported the session of "${id}" (${summary.cookies} cookies, storage of ${summary.origins} sites) to ${tildify(file, io.env)}`);
63
+ io.out(`it can be imported until ${summary.expiresAt}; it holds no vault credentials`);
64
+ return 0;
65
+ }
66
+ export async function importSession(mod, args, io, deps, input = terminalInput) {
67
+ const p = parseFlags(args, IMPORT_FLAGS, 1);
68
+ const path = p.positionals[0];
69
+ if (!path)
70
+ return fail("usage: turno browser import <file> [--as <id>] [--yes] [--dry-run]");
71
+ let text;
72
+ try {
73
+ text = readFileSync(resolve(path), "utf8");
74
+ }
75
+ catch {
76
+ return fail(`cannot read ${path}`);
77
+ }
78
+ const as = str(p, "as");
79
+ if (as)
80
+ mod.assertIdentityId(as);
81
+ const secret = await passphrase(io, input, false);
82
+ const { summary } = await mod.readSessionExport(text, secret);
83
+ const id = as ?? summary.identity;
84
+ const exists = mod.identityExists(id, io.env);
85
+ const what = `${summary.cookies} cookies and the storage of ${summary.origins} sites, exported from "${summary.identity}" on ${summary.createdAt}`;
86
+ if (bool(p, "dry-run")) {
87
+ io.out(`(dry run) would ${exists ? "replace the session of" : "create"} browser identity "${id}" with ${what}`);
88
+ return 0;
89
+ }
90
+ if (exists && !bool(p, "yes")) {
91
+ if (!deps.interactive(io))
92
+ needsAnswer("browser import into an existing identity");
93
+ if (!(await deps.confirm(`Replace the cookies and site storage of "${id}"? Its current sign-ins are lost. [y/N] `, io))) {
94
+ io.out("nothing imported");
95
+ return 1;
96
+ }
97
+ }
98
+ const done = await mod.importSession(text, { passphrase: secret, ...(as ? { as } : {}), env: io.env });
99
+ io.out(`${done.created ? "created" : "replaced the session of"} browser identity "${done.identity}" with ${what}`);
100
+ return 0;
101
+ }
102
+ //# sourceMappingURL=browser-session.js.map