@muhkoo/cli 0.15.0-alpha.14 → 0.15.0-alpha.15

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.
@@ -9,10 +9,11 @@
9
9
 
10
10
  import { lstat, readFile, stat, writeFile } from "node:fs/promises";
11
11
  import { basename, dirname, isAbsolute, resolve } from "node:path";
12
- import { openClient, explainWriteFailure } from "../lib/vfs.js";
12
+ import { openClient } from "../lib/vfs.js";
13
13
  import { mount as mountDir, importOnce, previewMount, heldBack, acceptIgnores, diskIgnoreTexts, assertMountable, mountTarget } from "../lib/mount.js";
14
14
  import { draftIgnores, ignoreFileProblem } from "../lib/ignore.js";
15
- import { loadConfig, saveConfig } from "../lib/config.js";
15
+ import { loadConfig, saveConfig, resolveBase } from "../lib/config.js";
16
+ import { devCall } from "../lib/http.js";
16
17
  import { table, json, ok, info, warn, die, writeText, prompt } from "../lib/ui.js";
17
18
 
18
19
  export const help = `muhkoo vfs — your encrypted filesystem
@@ -62,8 +63,17 @@ Usage:
62
63
  Ctrl-C or closing the terminal stops it after
63
64
  the current file; a second Ctrl-C quits now)
64
65
  muhkoo vfs sweep [--force] reclaim orphaned records
65
- muhkoo vfs use-app <domain> use an app, by the domain you use it at
66
- muhkoo vfs app show which app you are writing as
66
+ muhkoo vfs use-app <domain> no longer needed: your filesystem is billed
67
+ to your account (prints a notice)
68
+ muhkoo vfs app likewise
69
+ muhkoo vfs rehome [--dry-run] [--json] move files stored under an app to your account
70
+ (what older versions of the IDE and
71
+ Cloud Drive wrote); run it once. It
72
+ moves only what your own files point
73
+ at, skips what is already moved, and is
74
+ safe to repeat. --dry-run lists the
75
+ candidates and calls nothing. Exits 1
76
+ if any file failed, so a script can retry
67
77
 
68
78
  What gets synced is decided by .vcsignore if there is one. Otherwise git's
69
79
  rules apply: every .gitignore, each scoped to its own directory, and
@@ -100,13 +110,11 @@ does not read again. A pull leaves the disk 5% of its space free, at least
100
110
  your filesystem reports. Ignore files are held to these limits like any other
101
111
  file.
102
112
 
103
- Reading your files is free. WRITING stores bytes, which are metered to an
104
- app — so put, rm, cp, mv and restore need an app signed in first.
113
+ Your filesystem is billed to your account, not to an app: nothing to sign in
114
+ to first, and no app key. (\`vfs use-app\`, \`--app\` and \`--key\` are
115
+ accepted and ignored.)
105
116
 
106
117
  Options:
107
- --app <name> write as this app for one command
108
- --key <k> supply the app key yourself (apps that publish their public
109
- config at /.well-known/muhkoo.json need no key)
110
118
  --allow-delete propagate deletions (import: only to your filesystem). OFF by
111
119
  default: a delete removes the file's history too, so unlike an
112
120
  overwrite it cannot be undone. It trusts the remote side. A pass
@@ -122,6 +130,22 @@ Options:
122
130
  machine (it signs in for the one command if it must)
123
131
  --no-pair unlock for this command only; pair nothing to this machine`;
124
132
 
133
+ const NOT_NEEDED = "Not needed any more: your filesystem is billed to your account.";
134
+
135
+ /**
136
+ * The apps older versions of the IDE and Cloud Drive wrote files under, by id,
137
+ * per API base. A local base has none. Ids, not slugs: slugs are per account,
138
+ * these are the two shared apps.
139
+ */
140
+ export const IDE_APP_IDS = {
141
+ "https://api.muhkoo.dev": "36bfe1582aaf98e95157e8f80d519d10",
142
+ "https://api.staging.muhkoo.dev": "7dacbbf0634278f46bc8e6d3ade9199b",
143
+ };
144
+ export const CLOUD_DRIVE_APP_IDS = {
145
+ "https://api.muhkoo.dev": "53f8d3d5fb6faa9dcefa9df5aba1ae04",
146
+ "https://api.staging.muhkoo.dev": "999bed2ba01b168d4f70932777392da4",
147
+ };
148
+
125
149
  export default async function vfs(args) {
126
150
  const sub = args._[1];
127
151
  if (sub === undefined) return die("Missing subcommand. See `muhkoo vfs --help`.");
@@ -132,6 +156,11 @@ export default async function vfs(args) {
132
156
  // limiter long before it finishes.
133
157
  if (sub === "ignore") return ignoreCommand(args);
134
158
 
159
+ // The app key is gone: the filesystem is billed to your account. Say so for
160
+ // the old spellings, and ignore them — `use-app` and `app` never needed a
161
+ // session, so they do not open one.
162
+ if (sub === "use-app" || sub === "app") return info(NOT_NEEDED);
163
+
135
164
  // Where to sync is checked before the session opens, which can ask for a
136
165
  // password: `vfs mount /apps/x --path ./`, the two swapped, unlocked the
137
166
  // vault and then set about creating /apps at the top of this disk.
@@ -141,22 +170,22 @@ export default async function vfs(args) {
141
170
  if (problem) return die(pathError("import into", problem));
142
171
  }
143
172
 
173
+ if (args.key !== undefined || args.app !== undefined) {
174
+ info(NOT_NEEDED);
175
+ const { key: _key, app: _app, ...rest } = args;
176
+ args = rest;
177
+ }
178
+
144
179
  // A dry run writes nothing, and that includes ~/.muhkoo: unlocking would
145
180
  // otherwise pair a machine not paired yet (a device enrolled on the server,
146
181
  // its key saved) and reset a stale working directory. It unlocks for this
147
182
  // command only. A swallowed directory (`--dry-run <dir>`) still counts.
148
- const dryRun = (sub === "import" || sub === "push" || sub === "mount") && Boolean(args["dry-run"]);
183
+ const dryRun = (sub === "import" || sub === "push" || sub === "mount" || sub === "rehome") && Boolean(args["dry-run"]);
149
184
  const client = await openClient(dryRun ? { ...args, pair: false, readOnly: true } : args);
150
185
  const fs = client.vfs;
151
186
  const a = (n, dflt) => args._[n] ?? dflt;
152
187
 
153
- try {
154
- return await run();
155
- } catch (err) {
156
- const explained = explainWriteFailure(err, await loadConfig());
157
- if (explained) die(...explained);
158
- throw err;
159
- }
188
+ return await run();
160
189
 
161
190
  async function run() {
162
191
  switch (sub) {
@@ -278,27 +307,8 @@ export default async function vfs(args) {
278
307
  return ok(`Restored ${path} to version ${index} (${humanSize(stat.size)})`);
279
308
  }
280
309
 
281
- case "use-app": {
282
- const slug = args._[2];
283
- if (!slug) die("Missing app. Usage: muhkoo vfs use-app <slug> [--key <appKey>]");
284
- const saved = await useApp(slug, args.key);
285
- return ok(
286
- `Writing as "${saved.slug}". Reads never needed this; writes are now metered to that app.`,
287
- );
288
- }
289
-
290
- case "app": {
291
- const current = await loadConfig();
292
- const slug = current.vfsApp;
293
- if (args.json) return json({ app: slug ?? null, known: Object.keys(current.vfsApps ?? {}) });
294
- if (!slug) {
295
- return info(
296
- "Not writing as any app — reads work, writes will not.",
297
- "Sign one in with: muhkoo vfs use-app <slug> --key <appKey>",
298
- );
299
- }
300
- return info(`Writing as "${slug}".`);
301
- }
310
+ case "rehome":
311
+ return rehomeCommand(args, fs);
302
312
 
303
313
  case "import":
304
314
  case "push": {
@@ -654,65 +664,66 @@ function humanSize(bytes) {
654
664
  }
655
665
 
656
666
  /**
657
- * Point the CLI at an app, by the domain you use it at.
658
- *
659
- * A domain is how a USER knows an app — not a slug, and certainly not a key —
660
- * and this is meant to work for anyone who uses an app, not only whoever built
661
- * it. So the app publishes its own public config and we read it from there.
662
- *
663
- * It has to come from the app rather than the platform: key plaintexts are
664
- * never stored server-side (only `keyHashPrefix`), so no API can answer "what
665
- * is the key for this domain". A publishable key is public by design — it ships
666
- * in the app's own bundle — so the app serving it at a well-known path gives
667
- * away nothing that loading the app in a browser does not.
668
- *
669
- * A bare slug still works for an app you own and have a key for.
667
+ * `muhkoo vfs rehome`: move files an older app stored under its own billing to
668
+ * this account. Candidates are the built-in IDE and Cloud Drive ids for this
669
+ * base plus the ids of the apps named in `vfsApps` (resolved through the apps
670
+ * list). Moving what is not ours is the server's to refuse, so over-asking is
671
+ * harmless.
670
672
  */
671
- async function useApp(nameOrDomain, key) {
673
+ async function rehomeCommand(args, fs) {
672
674
  const cfg = await loadConfig();
673
- const known = cfg.vfsApps ?? {};
674
- const looksLikeDomain = nameOrDomain.includes(".");
675
-
676
- if (!key && !known[nameOrDomain] && looksLikeDomain) {
677
- key = await fetchPublicKey(nameOrDomain);
675
+ const baseUrl = String(await resolveBase(args, cfg)).replace(/\/+$/, "");
676
+ const ids = new Set([IDE_APP_IDS[baseUrl], CLOUD_DRIVE_APP_IDS[baseUrl]].filter(Boolean));
677
+
678
+ const slugs = Object.keys(cfg.vfsApps ?? {});
679
+ if (slugs.length) {
680
+ const token = args.token || process.env.MUHKOO_DEV_TOKEN || cfg.token;
681
+ const listed = await devCall({ baseUrl, token }, "GET", "/api/apps").catch(() => null);
682
+ const apps = listed?.ok ? (listed.body?.apps || listed.body || []) : null;
683
+ if (!Array.isArray(apps)) {
684
+ info("The CLI's own app list couldn't be read, so only the built-in candidates are used.");
685
+ } else {
686
+ for (const app of apps) if (!app.deletedAt && slugs.includes(app.slug) && app.appId) ids.add(app.appId);
687
+ }
678
688
  }
689
+ const fromAppIds = [...ids];
679
690
 
680
- if (!key && !known[nameOrDomain]) {
681
- die(
682
- `Could not work out the app key for "${nameOrDomain}".`,
683
- ...(looksLikeDomain
684
- ? [`That app does not publish ${WELL_KNOWN} yet. Pass it once with --key <appKey>.`]
685
- : [
686
- `Pass it once with --key <appKey>, or use the domain you access the app at.`,
687
- `App keys are shown when an app is created (muhkoo apps create).`,
688
- ]),
691
+ if (args["dry-run"]) {
692
+ const files = (await fs.walk("/")).length;
693
+ return info(
694
+ `${files} file${files === 1 ? "" : "s"} in your filesystem.`,
695
+ fromAppIds.length
696
+ ? `Would move anything stored under: ${fromAppIds.join(", ")}`
697
+ : "No candidate apps for this API base, so nothing would be moved.",
698
+ "Dry run: nothing was changed.",
689
699
  );
690
700
  }
691
- const next = key ? { ...known, [nameOrDomain]: key } : known;
692
- await saveConfig({ ...cfg, vfsApps: next, vfsApp: nameOrDomain });
693
- return { slug: nameOrDomain, key: next[nameOrDomain] };
694
- }
695
-
696
- const WELL_KNOWN = "/.well-known/muhkoo.json";
697
701
 
698
- /** Read an app's published public config. Returns the key, or null. */
699
- async function fetchPublicKey(domain) {
700
- const host = domain.replace(/^https?:\/\//, "").replace(/\/.*$/, "");
701
- const url = `https://${host}${WELL_KNOWN}`;
702
- try {
703
- const res = await fetch(url);
704
- if (!res.ok) return null;
705
- const body = await res.json();
706
- const key = body?.publishableKey ?? body?.key;
707
- // Only ever accept a PUBLISHABLE key from a public document. A site that
708
- // served a secret key here would be leaking it, and storing it because it
709
- // was offered would make us complicit in that.
710
- if (typeof key !== "string" || !/_pk_/.test(key)) return null;
711
- info(`Read ${host}'s public config (app ${body?.slug ?? body?.appId ?? "?"}).`);
712
- return key;
713
- } catch {
714
- return null;
702
+ let progressShown = false;
703
+ const result = await fs.rehome({
704
+ fromAppIds,
705
+ onProgress: args.json ? undefined : (done, total) => {
706
+ if (process.stderr.isTTY) {
707
+ process.stderr.write(`\r ${done}/${total}`);
708
+ progressShown = true;
709
+ }
710
+ },
711
+ });
712
+ // End the `\r n/m` line, so the summary does not print over it.
713
+ if (progressShown) process.stderr.write("\n");
714
+ if (args.json) {
715
+ json(result);
716
+ } else {
717
+ ok("Rehome finished.");
718
+ info(
719
+ ` moved: ${result.moved}`,
720
+ ` already moved: ${result.alreadyMoved}`,
721
+ ` not held: ${result.notHeld}`,
722
+ ` failed: ${result.failed}`,
723
+ );
715
724
  }
725
+ // `die`, not `process.exitCode`: the launcher exits 0 once a command returns.
726
+ if (result.failed > 0) return die(`${result.failed} file${result.failed === 1 ? "" : "s"} could not be moved. Run \`muhkoo vfs rehome\` again to retry.`);
716
727
  }
717
728
 
718
729
  /**
package/src/index.js CHANGED
@@ -8,7 +8,7 @@ import { readFile } from "node:fs/promises";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { dirname, join } from "node:path";
10
10
  import { parseArgs } from "./lib/args.js";
11
- import { c, die, info } from "./lib/ui.js";
11
+ import { c, die, info, setJsonMode } from "./lib/ui.js";
12
12
 
13
13
  const COMMANDS = {
14
14
  login: () => import("./commands/login.js"),
@@ -32,6 +32,7 @@ const COMMANDS = {
32
32
  functions: () => import("./commands/functions.js"),
33
33
  logs: () => import("./commands/logs.js"),
34
34
  eject: () => import("./commands/eject.js"),
35
+ mcp: () => import("./commands/mcp.js"),
35
36
  };
36
37
 
37
38
  const TOP_HELP = `${c.bold("muhkoo")} — command-line interface for the Muhkoo platform
@@ -63,13 +64,14 @@ Files
63
64
  vfs import|mount|ignore
64
65
  upload a project, keep a directory in sync, and
65
66
  choose what syncs
66
- vfs sweep|use-app|app reclaim records; pick the app writes are made as
67
+ vfs sweep|rehome reclaim records; move files an app stored to your account
68
+ vfs use-app|app no longer needed (filesystem storage is billed to you)
67
69
  vcs status|commit|log|show|diff|branch|switch|checkout|merge|restore
68
70
  version control over it
69
71
  kv ls [prefix] keys in your personal key/value store
70
72
 
71
73
  Hosting
72
- deploy deploy a built client to Muhkoo hosting (test env)
74
+ deploy deploy a built client to the test env (--prod: production)
73
75
  promote promote an app's test hosting → production
74
76
  hosting status|rollback|rm-release|unpublish
75
77
  domains ls|add|rm manage custom domains
@@ -77,6 +79,7 @@ Hosting
77
79
  Tools
78
80
  logs <appId> inspect an app's server-log Space
79
81
  eject <agentApp.ts> preview an agent's compiled prompt + tools
82
+ mcp run as an MCP server for Claude (stdio)
80
83
 
81
84
  Global options
82
85
  --base <env|url> prod (default) | staging | local | a literal URL
@@ -99,6 +102,7 @@ export async function run(argv) {
99
102
  const wantsHelp = argv.includes("--help") || argv.includes("-h");
100
103
  const args = parseArgs(argv.map((a) => (a === "-h" ? "--help" : a === "-v" ? "--version" : a)));
101
104
  const name = args._[0];
105
+ if (args.json) setJsonMode(true);
102
106
 
103
107
  if (wantsVersion) return info(await version());
104
108
  if (!name || name === "help") return info(...TOP_HELP.split("\n"));
package/src/lib/auth.js CHANGED
@@ -46,7 +46,7 @@ export async function loadClient() {
46
46
  }
47
47
 
48
48
  /**
49
- * Run a zero-knowledge login and return `{ token, commitment, username }`.
49
+ * Run a zero-knowledge login and return `{ token, commitment, username, seed }`.
50
50
  * Throws (via `die`) on failure.
51
51
  */
52
52
  export async function zkLogin({ baseUrl, username, password }) {
@@ -58,5 +58,10 @@ export async function zkLogin({ baseUrl, username, password }) {
58
58
  const user = await client.auth.zk.login(username, password);
59
59
  const token = client.auth.zk.token;
60
60
  if (!token) die("Login succeeded but no session token was issued.");
61
- return { token, commitment: user?.commitment, username: user?.username ?? username };
61
+ return {
62
+ token,
63
+ commitment: user?.commitment,
64
+ username: user?.username ?? username,
65
+ seed: client.auth.zk.seedBase64 ?? null,
66
+ };
62
67
  }
package/src/lib/bases.js CHANGED
@@ -15,6 +15,14 @@ export function resolveBaseUrl(value) {
15
15
  return BASES[value] || value;
16
16
  }
17
17
 
18
+ /** A plain name for an API base: "production", "staging", "local", or "custom". */
19
+ export function platformFor(baseUrl) {
20
+ if (baseUrl === BASES.prod) return "production";
21
+ if (baseUrl === BASES.staging) return "staging";
22
+ if (/^https?:\/\/(localhost|127\.0\.0\.1)(:|\/|$)/.test(baseUrl)) return "local";
23
+ return "custom";
24
+ }
25
+
18
26
  /** The public hosting host suffix for an API base (apps.* / apps.staging.*). */
19
27
  export function appsSuffixFor(baseUrl) {
20
28
  return baseUrl.includes("staging") ? "apps.staging.muhkoo.dev" : "apps.muhkoo.dev";
package/src/lib/ui.js CHANGED
@@ -62,21 +62,39 @@ export const c = {
62
62
  // Each argument is one line: a newline INSIDE an argument is escaped like
63
63
  // any other control character, so a message that runs to several lines
64
64
  // passes them as separate arguments.
65
+ //
66
+ // Under `--json` (see setJsonMode) stdout belongs to the one result object a
67
+ // program reads, so these progress lines go to stderr instead.
68
+ let jsonMode = false;
69
+
70
+ /** Turn JSON mode on for this process: progress → stderr, `die()` → `{"error"}` on stdout. */
71
+ export function setJsonMode(on) {
72
+ jsonMode = Boolean(on);
73
+ }
74
+ export function isJsonMode() {
75
+ return jsonMode;
76
+ }
77
+ const say = (text) => (jsonMode ? console.error(text) : console.log(text));
78
+
65
79
  export function info(...all) {
66
- console.log(lines(all));
80
+ say(lines(all));
67
81
  }
68
82
  export function ok(first, ...more) {
69
- console.log(lines([`${c.green("✓")} ${first}`, ...more]));
83
+ say(lines([`${c.green("✓")} ${first}`, ...more]));
70
84
  }
71
85
  export function warn(first, ...more) {
72
- console.log(lines([`${c.yellow("⚠")} ${first}`, ...more]));
86
+ say(lines([`${c.yellow("⚠")} ${first}`, ...more]));
73
87
  }
74
88
  export function step(first, ...more) {
75
- console.log(lines([`${c.dim("→")} ${first}`, ...more]));
89
+ say(lines([`${c.dim("→")} ${first}`, ...more]));
76
90
  }
77
91
 
78
- /** Print an error and exit non-zero. */
92
+ /** Print an error and exit non-zero. Under `--json`, as `{"error": "…"}` on stdout. */
79
93
  export function die(first, ...more) {
94
+ if (jsonMode) {
95
+ json({ error: [first, ...more].map((l) => printable(l).replace(MARKS, "")).join("\n") });
96
+ process.exit(1);
97
+ }
80
98
  console.error(lines(["", `${c.red("✗")} ${first}`, ...more, ""]));
81
99
  process.exit(1);
82
100
  }
@@ -132,8 +150,14 @@ export function table(headers, rows) {
132
150
  for (const r of body) console.log(out(line(r)));
133
151
  }
134
152
 
153
+ // Set by the MCP server's runner, where there is no one at stdin to answer:
154
+ // fail at once rather than wait for the tool's timeout.
155
+ const NOT_INTERACTIVE = "not signed in on this machine — use the login tool (or run `muhkoo login` in a terminal)";
156
+ const interactive = () => process.env.MUHKOO_NONINTERACTIVE !== "1";
157
+
135
158
  /** Prompt for a line of input on stdin. */
136
159
  export async function prompt(question) {
160
+ if (!interactive()) throw new Error(NOT_INTERACTIVE);
137
161
  const rl = (await import("node:readline/promises")).createInterface({
138
162
  input: process.stdin,
139
163
  output: process.stdout,
@@ -150,6 +174,7 @@ export async function prompt(question) {
150
174
  * non-TTY (piped) it just reads a line.
151
175
  */
152
176
  export function promptHidden(question) {
177
+ if (!interactive()) return Promise.reject(new Error(NOT_INTERACTIVE));
153
178
  const stdin = process.stdin;
154
179
  const stdout = process.stdout;
155
180
  if (!stdin.isTTY) return prompt(question);
package/src/lib/vfs.js CHANGED
@@ -31,6 +31,7 @@ import { die, info, step, prompt, promptHidden } from "./ui.js";
31
31
  */
32
32
  export async function openClient(args) {
33
33
  const { cfg, baseUrl, client } = await restoreSession(args);
34
+ requireFilesystemSdk(client);
34
35
 
35
36
  await unlock({ args, cfg, baseUrl, client });
36
37
 
@@ -47,6 +48,18 @@ export async function openClient(args) {
47
48
  return client;
48
49
  }
49
50
 
51
+ /**
52
+ * The VFS commands open a Client with no app key, which only an SDK that bills
53
+ * the filesystem to the signed-in account supports (`@muhkoo/connect`
54
+ * 0.15.0-alpha.15, the release that added `vfs.rehome`). An older SDK would
55
+ * fail on the first write with a confusing "API key required", so stop here.
56
+ */
57
+ function requireFilesystemSdk(client) {
58
+ if (typeof client?.vfs?.rehome !== "function") {
59
+ die("This CLI needs @muhkoo/connect 0.15.0-alpha.15 or newer — reinstall the CLI.");
60
+ }
61
+ }
62
+
50
63
  /**
51
64
  * A Client with the session restored and NOTHING unlocked, for commands that
52
65
  * only name things (`kv ls`) and never decrypt a value. Unlocking would ask for
@@ -63,15 +76,11 @@ async function restoreSession(args) {
63
76
  const token = args.token || process.env.MUHKOO_DEV_TOKEN || cfg.token;
64
77
  if (!token) die("Not signed in. Run `muhkoo login` first.");
65
78
 
66
- // Storing bytes is METERED, and the shard store attributes them to an app —
67
- // so a write needs an app key even though the filesystem is the user's own.
68
- // Reads do not, which is why ls and cat work with no app signed in at all.
69
- const apiKey = resolveAppKey(args, cfg);
70
-
79
+ // No app key: the filesystem is the signed-in user's own, and its storage is
80
+ // billed to their account. The session below is all a read or a write needs.
71
81
  const Client = await loadClient();
72
82
  const client = new Client({
73
83
  baseUrl,
74
- apiKey,
75
84
  // Hand the SDK the session we already hold instead of logging in again.
76
85
  sessionStore: {
77
86
  load: () => ({ token, username: cfg.username ?? "", commitment: cfg.commitment ?? "" }),
@@ -160,13 +169,41 @@ async function pairThisMachine({ args, cfg, baseUrl, client }) {
160
169
  return;
161
170
  }
162
171
 
172
+ const { factorId, label } = await pairWithSeed({ cfg, baseUrl, username, seed, client: authed });
173
+ client.auth.zk.unlockWithSeed(seed);
174
+ info(`Paired this machine as "${label}". Revoke it any time: muhkoo devices rm ${factorId}`);
175
+ }
176
+
177
+ /**
178
+ * Pair this machine from a seed already in hand (the browser login hands one
179
+ * over): enrol a device factor and save its key, so no later command asks for a
180
+ * password. Needs only the session and the seed — `enrollDevice` wraps the seed
181
+ * under a fresh local key and puts it in the vault, with no ZK proof.
182
+ *
183
+ * `client` is for a caller that already holds a signed-in Client; otherwise one
184
+ * is built over the stored session.
185
+ */
186
+ export async function pairWithSeed({ cfg, baseUrl, token, username, commitment, seed, client }) {
187
+ if (!client) {
188
+ const Client = await loadClient();
189
+ client = new Client({
190
+ baseUrl,
191
+ sessionStore: {
192
+ load: () => ({ token, username: username ?? "", commitment: commitment ?? "" }),
193
+ save: () => {},
194
+ clear: () => {},
195
+ },
196
+ });
197
+ const user = await client.auth.zk.restore();
198
+ if (!user) throw new Error("Your session has expired. Run `muhkoo login` and try again.");
199
+ client.auth.zk.unlockWithSeed(seed);
200
+ }
163
201
  const label = deviceLabel();
164
- const { factorId, deviceKey } = await authed.auth.zk.enrollDevice(label);
202
+ const { factorId, deviceKey } = await client.auth.zk.enrollDevice(label);
165
203
  // `seed: undefined` clears a seed left by an older CLI — the whole point is
166
204
  // that it stops living on this disk.
167
205
  await saveConfig({ ...cfg, username, deviceFactorId: factorId, deviceKey, seed: undefined });
168
- client.auth.zk.unlockWithSeed(seed);
169
- info(`Paired this machine as "${label}". Revoke it any time: muhkoo devices rm ${factorId}`);
206
+ return { factorId, label };
170
207
  }
171
208
 
172
209
  /**
@@ -183,38 +220,3 @@ function pairs(args) {
183
220
  function deviceLabel() {
184
221
  return `${userInfo().username}@${hostname()}`;
185
222
  }
186
-
187
- /**
188
- * The key to write as, from `--key`, the environment, or the app signed in with
189
- * `muhkoo vfs use-app`.
190
- *
191
- * Absent is a legitimate state, not an error: reads work without one, so this
192
- * returns undefined and lets the write itself fail with an explanation.
193
- */
194
- function resolveAppKey(args, cfg) {
195
- if (args.key) return args.key;
196
- if (process.env.MUHKOO_APP_KEY) return process.env.MUHKOO_APP_KEY;
197
- const slug = args.app || cfg.vfsApp;
198
- if (!slug) return undefined;
199
- return (cfg.vfsApps ?? {})[slug];
200
- }
201
-
202
- /**
203
- * Turn the shard store's 401 into an instruction: the lines to print, or null
204
- * when `err` is some other failure.
205
- *
206
- * "API key required to store shards" is accurate and useless — it names a
207
- * concept the person at the terminal has no reason to know, and says nothing
208
- * about what to do next.
209
- */
210
- export function explainWriteFailure(err, cfg) {
211
- const msg = err?.message ?? String(err);
212
- if (!/API key required|store shards|401/.test(msg)) return null;
213
- const known = Object.keys(cfg?.vfsApps ?? {});
214
- return [
215
- "Writing stores bytes, which are metered to an app — so a write needs one signed in.",
216
- ...(known.length
217
- ? [`Try: muhkoo vfs use-app ${known[0]}`]
218
- : ["Sign one in with: muhkoo vfs use-app <slug> --key <appKey>", "App keys are shown when an app is created (muhkoo apps create)."]),
219
- ];
220
- }