turno-cli 0.4.0 → 0.5.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.
@@ -1,118 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { JSON_FLAG, bool, parseFlags } from "../args.js";
3
- import { Exit } from "../exit.js";
4
- import { fail } from "../io.js";
5
- import { emit, jsonOutput } from "../output.js";
6
- import { style } from "../style.js";
7
- /** `turno browser live|pause|resume <id> --json`. */
8
- export const LIVE_JSON = jsonOutput([
9
- "identity",
10
- "pid",
11
- "port",
12
- "started",
13
- "paused",
14
- "waiting",
15
- "busy",
16
- "wait",
17
- "browser",
18
- "engine",
19
- "view",
20
- "showing",
21
- "pinned",
22
- "hidden",
23
- "viewers",
24
- "tabs",
25
- ]);
26
- const openInBrowser = async (url, io) => {
27
- const { openInvocation } = await import("./open.js");
28
- const inv = openInvocation(undefined, url, io.env);
29
- await new Promise((resolve, reject) => {
30
- const child = spawn(inv.command, inv.args, { stdio: "ignore", env: io.env, detached: true });
31
- child.on("error", reject);
32
- child.on("spawn", () => {
33
- child.unref();
34
- resolve();
35
- });
36
- });
37
- };
38
- function needIdentity(mod, id, sub, io) {
39
- if (!id)
40
- return fail(`browser ${sub} needs an identity id (for example: turno browser ${sub} school)`);
41
- mod.assertIdentityId(id);
42
- if (!mod.identityExists(id, io.env))
43
- return fail(`identity "${id}" does not exist (turno identity add browser:${id})`);
44
- return id;
45
- }
46
- /** `120000` as "2m", `90000` as "90s". */
47
- function seconds(ms) {
48
- return ms >= 60_000 && ms % 60_000 === 0 ? `${ms / 60_000}m` : `${Math.round(ms / 1000)}s`;
49
- }
50
- /** Why there is no live view to talk to: off, or no server running now. */
51
- function notServing(mod, id, io) {
52
- const on = mod.checkIdentitySettings(id, io.env).settings?.live?.enabled === true;
53
- return fail(on
54
- ? `no turno-browser-mcp serves "${id}" right now. The live view starts with the server (an agent session that uses browser-${id} starts it).`
55
- : `the live view is off for "${id}" (the default). Turn it on with turno browser set ${id} --live true; it starts with the next turno-browser-mcp for this identity.`);
56
- }
57
- function describe(status, io) {
58
- const s = style(io);
59
- const state = status.paused
60
- ? `paused for ${seconds(Math.max(0, Date.now() - Date.parse(status.paused.since)))} (${status.paused.by})${status.waiting ? `, ${status.waiting} call${status.waiting === 1 ? "" : "s"} waiting` : ""}`
61
- : status.busy
62
- ? "the agent is working"
63
- : "the agent is idle";
64
- io.out(`${s.bold(status.identity)} ${state}`);
65
- io.out(s.muted(` browser ${status.browser ? `running (${status.engine})` : "not running"}; a paused call waits up to ${seconds(status.wait)}`));
66
- if (!status.view.available && status.view.reason)
67
- io.out(s.note("info", status.view.reason, 2));
68
- for (const t of status.tabs)
69
- io.out(` ${t.id === status.showing ? "*" : " "} ${t.title || "(no title)"} ${s.muted(t.url)}${t.session ? s.muted(` [${t.session}]`) : ""}`);
70
- }
71
- const LIVE_FLAGS = { "no-open": { type: "boolean" }, ...JSON_FLAG };
72
- export async function live(mod, args, io, open = openInBrowser) {
73
- const p = parseFlags(args, LIVE_FLAGS, 1);
74
- const id = needIdentity(mod, p.positionals[0], "live", io);
75
- const status = await mod.liveStatus(id, io.env);
76
- if (!status)
77
- return notServing(mod, id, io);
78
- if (bool(p, "json")) {
79
- emit(io, p, LIVE_JSON, status);
80
- return Exit.ok;
81
- }
82
- describe(status, io);
83
- if (!status.view.available || bool(p, "no-open"))
84
- return Exit.ok;
85
- await open(await mod.liveLink(id, io.env), io);
86
- io.err(style(io).muted(`opened the live view of "${id}" in your browser (the link works once; run this again for a new one)`));
87
- return Exit.ok;
88
- }
89
- export async function pause(mod, args, io) {
90
- const p = parseFlags(args, JSON_FLAG, 1);
91
- const id = needIdentity(mod, p.positionals[0], "pause", io);
92
- if (!(await mod.liveStatus(id, io.env)))
93
- return notServing(mod, id, io);
94
- const status = await mod.livePause(id, io.env);
95
- if (bool(p, "json")) {
96
- emit(io, p, LIVE_JSON, status);
97
- return Exit.ok;
98
- }
99
- io.out(`paused "${id}": the agent's next call waits up to ${seconds(status.wait)} for you. Act in the browser${status.view.available ? ` or the live view (turno browser live ${id})` : ""}, then: turno browser resume ${id}`);
100
- return Exit.ok;
101
- }
102
- export async function resume(mod, args, io) {
103
- const p = parseFlags(args, JSON_FLAG, 1);
104
- const id = needIdentity(mod, p.positionals[0], "resume", io);
105
- const before = await mod.liveStatus(id, io.env);
106
- if (!before)
107
- return notServing(mod, id, io);
108
- const status = await mod.liveResume(id, io.env);
109
- if (bool(p, "json")) {
110
- emit(io, p, LIVE_JSON, status);
111
- return Exit.ok;
112
- }
113
- io.out(before?.paused
114
- ? `resumed "${id}": the agent's waiting calls go on, and each is told what changed.`
115
- : `"${id}" was not paused.`);
116
- return Exit.ok;
117
- }
118
- //# sourceMappingURL=browser-live.js.map
@@ -1,102 +0,0 @@
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
@@ -1,193 +0,0 @@
1
- import { DRY_RUN, JSON_FLAG, bool, flagsOf, parseFlags, str } from "../args.js";
2
- import { group } from "../group.js";
3
- import { nextStep } from "../hints.js";
4
- import { fail, needsAnswer, noInputReason } from "../io.js";
5
- import { emit, jsonOutput } from "../output.js";
6
- import { readHidden, readStdinText, readVisible, stdinIsTty } from "../secret-input.js";
7
- import { OPTIONAL, notInstalled } from "../optional.js";
8
- /**
9
- * `turno browser vault`: the credential vault of a browser identity. Values go
10
- * from a hidden prompt or stdin straight to turno-browser, which keeps them in the secret store;
11
- * nothing here prints, logs or passes one as an argument.
12
- */
13
- /** `turno browser vault list --json`. */
14
- const VAULT_JSON = jsonOutput(["identity", "submit", "sites"]);
15
- export const terminalInput = {
16
- isTty: stdinIsTty,
17
- hidden: readHidden,
18
- visible: readVisible,
19
- stdin: readStdinText,
20
- };
21
- const ADD_FLAGS = {
22
- url: { type: "string", multiple: true },
23
- username: { type: "string" },
24
- totp: { type: "boolean" },
25
- ...DRY_RUN,
26
- };
27
- function ids(mod, io, args, count, usage) {
28
- const words = args.slice(0, count);
29
- if (words.length < count || words.some((w) => !w))
30
- return fail(`usage: turno browser vault ${usage}`);
31
- try {
32
- mod.assertIdentityId(words[0]);
33
- }
34
- catch (err) {
35
- return fail(err.message);
36
- }
37
- if (!mod.identityExists(words[0], io.env))
38
- return fail(`browser identity "${words[0]}" does not exist (turno browser add ${words[0]})`);
39
- return words;
40
- }
41
- async function add(mod, args, io, input) {
42
- const p = parseFlags(args, ADD_FLAGS, 2);
43
- const [id, site] = ids(mod, io, p.positionals, 2, "add <identity> <site> --url <sign-in page> [--username <name>] [--totp]");
44
- const urls = p.values.url ?? [];
45
- if (!urls.length)
46
- return fail("give the sign-in page with --url (for example --url https://github.com/login)");
47
- const withTotp = bool(p, "totp");
48
- if (bool(p, "dry-run")) {
49
- io.out(`(dry run) would store a username, a password${withTotp ? " and a TOTP secret" : ""} for ${site} in browser identity "${id}"`);
50
- return 0;
51
- }
52
- let username = str(p, "username");
53
- let password;
54
- let totp;
55
- if (input.isTty()) {
56
- // Hidden prompts wait for a person: never with --no-input or inside an agent session.
57
- if (noInputReason(io.env))
58
- needsAnswer("browser vault add", "the password on stdin (and --username)");
59
- username ??= await input.visible(`Username for ${site}: `);
60
- password = await input.hidden(`Password for ${site} (input hidden): `);
61
- if (withTotp)
62
- totp = await input.hidden("TOTP secret or otpauth:// URI (input hidden): ");
63
- }
64
- else {
65
- if (!username)
66
- return fail("give --username when the password comes on stdin");
67
- const lines = (await input.stdin()).split(/\r?\n/);
68
- password = lines[0] ?? "";
69
- if (withTotp)
70
- totp = lines[1]?.trim() || undefined;
71
- if (withTotp && !totp)
72
- return fail("--totp reads the TOTP secret from the second line of stdin, and it is empty");
73
- }
74
- if (!password)
75
- return fail("the password is empty; nothing was stored");
76
- const entry = await mod.vaultAdd(id, site, { urls, username: username ?? "", password, ...(totp ? { totp } : {}) }, { env: io.env });
77
- io.out(`stored the credentials of ${entry.site} for browser identity "${id}" (username, password${entry.totp ? ", TOTP secret" : ""}) in the secret store`);
78
- io.out(`origins: ${entry.origins.join(", ")}`);
79
- nextStep(io, `an agent on browser-${id} signs in with the browser_login tool (site "${entry.site}") on that sign-in page`);
80
- return 0;
81
- }
82
- async function list(mod, args, io) {
83
- const p = parseFlags(args, JSON_FLAG, 1);
84
- const [id] = ids(mod, io, p.positionals, 1, "list <identity> [--json]");
85
- const info = await mod.vaultList(id, { env: io.env });
86
- if (bool(p, "json")) {
87
- emit(io, p, VAULT_JSON, info);
88
- return 0;
89
- }
90
- io.out(`browser identity "${id}": ${info.submit === "auto" ? "browser_login submits the form itself" : "browser_login fills, the agent clicks sign in"} (turno browser vault submit ${id} auto|confirm)`);
91
- if (!info.sites.length) {
92
- io.out(`No credentials yet. Add some with \`turno browser vault add ${id} <site> --url <sign-in page>\`.`);
93
- return 0;
94
- }
95
- const width = Math.max(...info.sites.map((s) => s.site.length));
96
- for (const s of info.sites) {
97
- const state = s.stored ? "" : " MISSING from the secret store";
98
- io.out(`${s.site.padEnd(width)} ${s.totp ? "password+totp" : "password "} ${s.origins.join(", ")}${state}`);
99
- }
100
- return info.sites.every((s) => s.stored) ? 0 : 1;
101
- }
102
- async function remove(mod, args, io) {
103
- const p = parseFlags(args, DRY_RUN, 2);
104
- const [id, site] = ids(mod, io, p.positionals, 2, "remove <identity> <site> [--dry-run]");
105
- if (bool(p, "dry-run")) {
106
- io.out(`(dry run) would delete the credentials of ${site} from browser identity "${id}"`);
107
- return 0;
108
- }
109
- if (!(await mod.vaultRemove(id, site, { env: io.env }))) {
110
- io.out(`browser identity "${id}" has no credentials for ${site}`);
111
- return 1;
112
- }
113
- io.out(`removed the credentials of ${site} from browser identity "${id}"`);
114
- return 0;
115
- }
116
- function submit(mod, args, io) {
117
- const p = parseFlags(args, DRY_RUN, 2);
118
- const [id, mode] = ids(mod, io, p.positionals, 2, "submit <identity> <confirm|auto>");
119
- if (mode !== "confirm" && mode !== "auto")
120
- return fail(`submit takes "confirm" (the agent clicks sign in) or "auto" (browser_login submits), not "${mode}"`);
121
- if (bool(p, "dry-run")) {
122
- io.out(`(dry run) would set browser_login of "${id}" to ${mode}`);
123
- return 0;
124
- }
125
- mod.vaultSetSubmit(id, mode, { env: io.env });
126
- io.out(mode === "auto"
127
- ? `browser_login now submits the sign-in form itself for "${id}"`
128
- : `browser_login now only fills the form for "${id}"; the agent clicks sign in`);
129
- return 0;
130
- }
131
- const FOOTER = `The vault keeps a username, a password and optionally a TOTP secret per site for one
132
- browser identity, only in the secret store (the macOS Keychain or the Linux Secret Service).
133
- The browser_login tool fills them into the site's sign-in page without the agent seeing them,
134
- and only on the origins given with --url. In a terminal the password and the TOTP secret are
135
- asked with hidden prompts; from a pipe, the first line of stdin is the password and, with
136
- --totp, the second line is the TOTP secret (base32, or the otpauth:// URI of the QR code).`;
137
- /** The `browser vault` group; `load` is the browser group's loader. */
138
- export function vaultCommand(deps, input = terminalInput) {
139
- const withModule = (run) => async (args, io) => {
140
- const mod = await deps.load(io);
141
- if (!mod)
142
- return fail(notInstalled(OPTIONAL.browser));
143
- try {
144
- return await run(mod, args, io);
145
- }
146
- catch (err) {
147
- const name = err.name;
148
- if (name === "VaultError" || name === "IdentityError" || name === "TotpError")
149
- return fail(err.message);
150
- throw err;
151
- }
152
- };
153
- const subs = {
154
- add: {
155
- summary: "store a site's username, password and optional TOTP secret (asked hidden, or on stdin)",
156
- synopsis: "<identity> <site> --url <sign-in page> [--url <url>]... [--username <name>] [--totp] [--dry-run]",
157
- flags: flagsOf(ADD_FLAGS),
158
- run: withModule((mod, args, io) => add(mod, args, io, input)),
159
- },
160
- list: {
161
- summary: "the sites in an identity's vault (never the values)",
162
- synopsis: "<identity> [--json]",
163
- flags: ["--json"],
164
- json: VAULT_JSON,
165
- run: withModule(list),
166
- },
167
- remove: {
168
- summary: "delete a site's credentials",
169
- synopsis: "<identity> <site> [--dry-run]",
170
- flags: ["--dry-run"],
171
- run: withModule(remove),
172
- },
173
- rm: { summary: "same as remove", hidden: true, run: withModule(remove) },
174
- submit: {
175
- summary: "let browser_login submit the form (auto) or leave the click to the agent (confirm, default)",
176
- synopsis: "<identity> <confirm|auto> [--dry-run]",
177
- flags: ["--dry-run"],
178
- run: withModule(submit),
179
- },
180
- };
181
- return group("browser vault", "credentials browser_login fills without showing them", subs, {
182
- footer: FOOTER,
183
- examples: [
184
- "turno browser vault add work github --url https://github.com/login --username alice --totp",
185
- "printf '%s\\n' \"$PASSWORD\" | turno browser vault add work mail --url https://mail.example.com --username alice@example.com",
186
- "turno browser vault list work",
187
- "turno browser vault list work --json",
188
- "turno browser vault submit work auto",
189
- "turno browser vault remove work github --dry-run",
190
- ],
191
- });
192
- }
193
- //# sourceMappingURL=browser-vault.js.map