@muhkoo/cli 0.10.10-alpha.0 → 0.11.0-alpha.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.
package/bin/muhkoo.js CHANGED
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@muhkoo/cli",
3
- "version": "0.10.10-alpha.0",
3
+ "version": "0.11.0-alpha.0",
4
4
  "description": "Command-line interface for the Muhkoo platform — provision backends, deploy apps, and manage agents, functions, databases, and domains.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -35,10 +35,15 @@
35
35
  "muhkoo": "node bin/muhkoo.js",
36
36
  "lint": "node --check bin/muhkoo.js",
37
37
  "sync-version": "node scripts/sync-version.mjs",
38
- "prepublishOnly": "node scripts/sync-version.mjs --check"
38
+ "prepublishOnly": "node scripts/sync-version.mjs --check",
39
+ "test": "vitest run"
39
40
  },
40
41
  "dependencies": {
41
- "@muhkoo/connect": "0.10.10-alpha.0"
42
+ "@muhkoo/connect": "0.11.0-alpha.0",
43
+ "snarkjs": "^0.7.0"
42
44
  },
43
- "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
45
+ "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",
46
+ "devDependencies": {
47
+ "vitest": "^2.1.9"
48
+ }
44
49
  }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * `muhkoo devices` — machines paired to your account.
3
+ *
4
+ * A paired machine holds a key that unwraps the master seed held (encrypted) in
5
+ * your vault. The seed itself is never on that machine's disk, so revoking here
6
+ * genuinely withdraws its access — unlike a copied seed, which nothing can
7
+ * reach out and un-store.
8
+ */
9
+
10
+ import { openClient } from "../lib/vfs.js";
11
+ import { loadConfig, saveConfig } from "../lib/config.js";
12
+ import { table, json, ok, info, die } from "../lib/ui.js";
13
+
14
+ export const help = `muhkoo devices — machines paired to your account
15
+
16
+ Usage:
17
+ muhkoo devices ls [--json] list paired machines
18
+ muhkoo devices rm <factorId> withdraw a machine's access`;
19
+
20
+ export default async function devices(args) {
21
+ const sub = args._[1] ?? "ls";
22
+ const client = await openClient(args);
23
+ const cfg = await loadConfig();
24
+
25
+ switch (sub) {
26
+ case "ls": {
27
+ const list = await client.auth.zk.listDevices();
28
+ if (args.json) return json(list);
29
+ if (!list.length) return info("No paired machines.");
30
+ return table(
31
+ ["ID", "LABEL", "PAIRED", ""],
32
+ list.map((d) => [
33
+ d.id,
34
+ d.label ?? "-",
35
+ d.createdAt ? new Date(d.createdAt).toISOString().slice(0, 10) : "-",
36
+ d.id === cfg.deviceFactorId ? "← this machine" : "",
37
+ ]),
38
+ );
39
+ }
40
+
41
+ case "rm": {
42
+ const id = args._[2];
43
+ if (!id) die("Missing device id. Usage: muhkoo devices rm <factorId>");
44
+ const deleted = await client.auth.zk.revokeDevice(id);
45
+ if (!deleted) return die(`No paired machine with id ${id}.`);
46
+ // Revoking THIS machine must clear the now-useless local key, or every
47
+ // later command retries a pairing the server has already forgotten.
48
+ if (id === cfg.deviceFactorId) {
49
+ await saveConfig({ ...cfg, deviceFactorId: undefined, deviceKey: undefined });
50
+ return ok("Revoked this machine. Run any `muhkoo vfs` command to pair it again.");
51
+ }
52
+ return ok(`Revoked ${id}.`);
53
+ }
54
+
55
+ default:
56
+ return die(`Unknown subcommand "devices ${sub}". See \`muhkoo devices --help\`.`);
57
+ }
58
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * `muhkoo tokens` — create, list, and revoke scoped access tokens for an app.
3
+ * Access tokens are non-ZK machine credentials (mk_<env>_at_<hex>) that are
4
+ * scoped and expiring. The plaintext is shown only once, on creation.
5
+ */
6
+
7
+ import { devContext } from "../lib/config.js";
8
+ import { devCall, ensure } from "../lib/http.js";
9
+ import { table, json, ok, info, warn, die, c } from "../lib/ui.js";
10
+
11
+ /** Valid token scopes, surfaced in help so callers know the vocabulary. */
12
+ const SCOPES = [
13
+ "db:read",
14
+ "db:write",
15
+ "kv:read",
16
+ "kv:write",
17
+ "storage:read",
18
+ "storage:write",
19
+ "messages:read",
20
+ "messages:write",
21
+ "functions:invoke",
22
+ "ai:infer",
23
+ ];
24
+
25
+ const DEFAULT_SCOPES = ["db:read", "db:write"];
26
+
27
+ export const help = `muhkoo tokens — manage scoped access tokens
28
+
29
+ Usage:
30
+ muhkoo tokens ls <appId> [--json]
31
+ muhkoo tokens create <appId> [--scopes db:read,db:write] [--env test|live] [--expires-in <days>] [--label <name>] [--json]
32
+ muhkoo tokens revoke <appId> <keyId>
33
+
34
+ Scopes:
35
+ ${SCOPES.join(", ")}`;
36
+
37
+ export default async function tokens(args) {
38
+ const sub = args._[1];
39
+ const ctx = await devContext(args);
40
+ const appId = args._[2] || args.app;
41
+ if (!appId) die("Missing app id. Usage: muhkoo tokens <ls|create|revoke> <appId>");
42
+
43
+ switch (sub) {
44
+ case "ls":
45
+ case undefined:
46
+ return list(ctx, appId, args);
47
+ case "create":
48
+ return create(ctx, appId, args);
49
+ case "revoke":
50
+ case "rm":
51
+ return revoke(ctx, appId, args);
52
+ default:
53
+ die(`Unknown subcommand "tokens ${sub}". See \`muhkoo tokens --help\`.`);
54
+ }
55
+ }
56
+
57
+ async function list(ctx, appId, args) {
58
+ const r = ensure(await devCall(ctx, "GET", `/api/apps/${appId}/access-tokens`), "List tokens");
59
+ if (args.json) return json(r.body);
60
+ const items = r.body?.tokens || [];
61
+ if (!items.length) {
62
+ return info("No access tokens. Create one with `muhkoo tokens create <appId>`.");
63
+ }
64
+ table(
65
+ ["LABEL", "KEY ID", "ENV", "SCOPES", "EXPIRES", "STATUS"],
66
+ items.map((t) => [
67
+ t.label || "",
68
+ truncate(t.keyId),
69
+ t.env ?? "",
70
+ Array.isArray(t.scopes) ? t.scopes.join(",") : t.scopes ?? "",
71
+ fmtDate(t.expiresAt),
72
+ statusOf(t),
73
+ ]),
74
+ );
75
+ }
76
+
77
+ async function create(ctx, appId, args) {
78
+ const scopes = args.scopes
79
+ ? String(args.scopes)
80
+ .split(",")
81
+ .map((s) => s.trim())
82
+ .filter(Boolean)
83
+ : DEFAULT_SCOPES;
84
+
85
+ const body = { scopes };
86
+ body.env = args.env === "test" ? "test" : "live";
87
+ if (args["expires-in"] !== undefined) body.expiresInDays = Number(args["expires-in"]);
88
+ if (args.label) body.label = args.label;
89
+
90
+ const r = await devCall(ctx, "POST", `/api/apps/${appId}/access-tokens`, body);
91
+ if (r.status === 402) die("Access tokens need a paid plan.");
92
+ ensure(r, "Create token");
93
+ if (args.json) return json(r.body);
94
+
95
+ const t = r.body;
96
+ ok(`Created ${t.env} access token${t.label ? ` ${c.bold(t.label)}` : ""} (${t.keyId})`);
97
+ info(` scopes: ${(t.scopes || scopes).join(", ")}`);
98
+ if (t.expiresAt) info(` expires: ${fmtDate(t.expiresAt)}`);
99
+ info(`\n ${c.bold(t.plaintext)}`);
100
+ warn("Save this token now — it is shown only once.");
101
+ }
102
+
103
+ async function revoke(ctx, appId, args) {
104
+ const keyId = args._[3] || args.keyId;
105
+ if (!keyId) die("Usage: muhkoo tokens revoke <appId> <keyId>");
106
+ ensure(
107
+ await devCall(ctx, "DELETE", `/api/apps/${appId}/access-tokens/${encodeURIComponent(keyId)}`),
108
+ "Revoke token",
109
+ );
110
+ ok(`Revoked token ${keyId}.`);
111
+ }
112
+
113
+ function statusOf(t) {
114
+ if (t.revoked) return c.red("revoked");
115
+ if (t.expired) return c.yellow("expired");
116
+ return c.green("active");
117
+ }
118
+
119
+ function truncate(keyId, n = 20) {
120
+ const s = String(keyId ?? "");
121
+ return s.length > n ? s.slice(0, n) + "…" : s;
122
+ }
123
+
124
+ function fmtDate(v) {
125
+ if (!v) return "never";
126
+ const d = new Date(v);
127
+ return Number.isNaN(d.getTime()) ? String(v) : d.toISOString().slice(0, 10);
128
+ }
@@ -0,0 +1,331 @@
1
+ /**
2
+ * `muhkoo vfs` — your Muhkoo filesystem from the terminal.
3
+ *
4
+ * Drives `client.vfs` through the SDK, the same code the IDE runs. The
5
+ * directory records are encrypted with keys chained parent-to-child, so a
6
+ * separate HTTP implementation here would be a second copy of that format to
7
+ * keep byte-exact — and the first one to drift would corrupt real files.
8
+ */
9
+
10
+ import { readFile, writeFile } from "node:fs/promises";
11
+ import { basename, resolve } from "node:path";
12
+ import { openClient, explainWriteFailure } from "../lib/vfs.js";
13
+ import { mount as mountDir } from "../lib/mount.js";
14
+ import { loadConfig, saveConfig } from "../lib/config.js";
15
+ import { table, json, ok, info, die } from "../lib/ui.js";
16
+
17
+ export const help = `muhkoo vfs — your encrypted filesystem
18
+
19
+ Usage:
20
+ muhkoo vfs cd <path> change directory (remembered)
21
+ muhkoo vfs pwd print the working directory
22
+ muhkoo vfs ls [path] [--json] list a directory
23
+ muhkoo vfs stat <path> size, versions, modified
24
+ muhkoo vfs tree [path] every file beneath a path
25
+ muhkoo vfs cat <path> print a file
26
+ muhkoo vfs put <local> <path> upload a file
27
+ muhkoo vfs get <path> [local] download a file
28
+ muhkoo vfs mkdir <path> create a directory
29
+ muhkoo vfs rm <path> [-r] delete a file or directory
30
+ muhkoo vfs cp <from> <to> copy (a file copy moves no bytes)
31
+ muhkoo vfs mv <from> <to> move or rename
32
+ muhkoo vfs find <glob> e.g. '/apps/**/*.ts'
33
+ muhkoo vfs history <path> prior versions, newest first
34
+ muhkoo vfs restore <path> [index] restore a version (default 0)
35
+ muhkoo vfs mount <dir> [--path <p>] sync a subtree to disk and keep it live
36
+ muhkoo vfs sweep [--force] reclaim orphaned records
37
+ muhkoo vfs use-app <domain> use an app, by the domain you use it at
38
+ muhkoo vfs app show which app you are writing as
39
+
40
+ Reading your files is free. WRITING stores bytes, which are metered to an
41
+ app — so put, rm, cp, mv and restore need an app signed in first.
42
+
43
+ Options:
44
+ --app <name> write as this app for one command
45
+ --key <k> supply the app key yourself (apps that publish their public
46
+ config at /.well-known/muhkoo.json need no key)
47
+ --no-pair unlock for this command only; pair nothing to this machine`;
48
+
49
+ export default async function vfs(args) {
50
+ const sub = args._[1];
51
+ if (sub === undefined) return die("Missing subcommand. See `muhkoo vfs --help`.");
52
+
53
+ const client = await openClient(args);
54
+ const fs = client.vfs;
55
+ const a = (n, dflt) => args._[n] ?? dflt;
56
+
57
+ try {
58
+ return await run();
59
+ } catch (err) {
60
+ const cfg = await loadConfig();
61
+ const explained = explainWriteFailure(err, cfg);
62
+ if (explained !== (err?.message ?? String(err))) die(explained);
63
+ throw err;
64
+ }
65
+
66
+ async function run() {
67
+ switch (sub) {
68
+ case "cd": {
69
+ const target = await fs.cd(a(2, "/"));
70
+ const current = await loadConfig();
71
+ await saveConfig({ ...current, vfsCwd: target });
72
+ return ok(target);
73
+ }
74
+
75
+ case "pwd":
76
+ return info(fs.cwd);
77
+
78
+ case "stat": {
79
+ const st = await fs.stat(required(a(2), "stat <path>"));
80
+ if (args.json) return json(st);
81
+ return table(
82
+ ["PATH", "TYPE", "SIZE", "VERSIONS", "MODIFIED"],
83
+ [[st.path, st.kind, st.kind === "dir" ? "-" : humanSize(st.size), String(st.versions), new Date(st.mtime).toISOString().replace("T", " ").slice(0, 19)]],
84
+ );
85
+ }
86
+
87
+ case "ls": {
88
+ const path = a(2, ".");
89
+ const entries = await fs.list(path);
90
+ if (args.json) return json(entries);
91
+ if (!entries.length) return info(`${path} is empty.`);
92
+ return table(
93
+ ["TYPE", "SIZE", "VERSIONS", "MODIFIED", "NAME"],
94
+ entries.map((e) => [
95
+ e.kind === "dir" ? "dir" : "file",
96
+ e.kind === "dir" ? "-" : humanSize(e.size),
97
+ e.versions ? String(e.versions) : "-",
98
+ new Date(e.mtime).toISOString().slice(0, 16).replace("T", " "),
99
+ e.kind === "dir" ? `${e.name}/` : e.name,
100
+ ]),
101
+ );
102
+ }
103
+
104
+ case "tree": {
105
+ const paths = await fs.walk(a(2, "."));
106
+ if (args.json) return json(paths);
107
+ return paths.forEach((p) => info(p));
108
+ }
109
+
110
+ case "cat": {
111
+ const path = required(a(2), "cat <path>");
112
+ process.stdout.write(await fs.readText(path));
113
+ return;
114
+ }
115
+
116
+ case "put": {
117
+ const local = required(a(2), "put <local> <path>");
118
+ const bytes = await readLocal(local);
119
+ // Default the destination to the file's own name, so `put ./a.txt` in a
120
+ // directory does the obvious thing.
121
+ const path = a(3) ?? `/${basename(local)}`;
122
+ const stat = await fs.writeFile(path, bytes);
123
+ return ok(`Wrote ${path} (${humanSize(stat.size)})`);
124
+ }
125
+
126
+ case "get": {
127
+ const path = required(a(2), "get <path> [local]");
128
+ const bytes = await fs.readFile(path);
129
+ const dest = a(3) ?? basename(path);
130
+ await writeFile(dest, bytes).catch((err) =>
131
+ die(`Could not write ${dest}: ${err.code === "EACCES" ? "permission denied" : err.message}`),
132
+ );
133
+ return ok(`Saved ${dest} (${humanSize(bytes.length)})`);
134
+ }
135
+
136
+ case "mkdir":
137
+ await fs.mkdir(required(a(2), "mkdir <path>"), { recursive: true });
138
+ return ok(`Created ${a(2)}`);
139
+
140
+ case "rm": {
141
+ const path = required(a(2), "rm <path>");
142
+ await fs.delete(path, { recursive: Boolean(args.r || args.recursive) });
143
+ return ok(`Deleted ${path}`);
144
+ }
145
+
146
+ case "cp": {
147
+ const [from, to] = pair(args, "cp <from> <to>");
148
+ await fs.copy(from, to);
149
+ return ok(`Copied ${from} → ${to}`);
150
+ }
151
+
152
+ case "mv": {
153
+ const [from, to] = pair(args, "mv <from> <to>");
154
+ await fs.rename(from, to);
155
+ return ok(`Moved ${from} → ${to}`);
156
+ }
157
+
158
+ case "find": {
159
+ const matches = await fs.glob(required(a(2), "find <glob>"));
160
+ if (args.json) return json(matches);
161
+ if (!matches.length) return info("No matches.");
162
+ return matches.forEach((p) => info(p));
163
+ }
164
+
165
+ case "history": {
166
+ const versions = await fs.history(required(a(2), "history <path>"));
167
+ if (args.json) return json(versions);
168
+ if (!versions.length) return info("No prior versions — this file has been written once.");
169
+ return table(
170
+ ["#", "SIZE", "SAVED"],
171
+ versions.map((v, i) => [String(i), humanSize(v.size), new Date(v.mtime).toISOString().replace("T", " ").slice(0, 19)]),
172
+ );
173
+ }
174
+
175
+ case "restore": {
176
+ const path = required(a(2), "restore <path> [index]");
177
+ const index = Number(a(3, "0"));
178
+ const stat = await fs.restore(path, index);
179
+ return ok(`Restored ${path} to version ${index} (${humanSize(stat.size)})`);
180
+ }
181
+
182
+ case "use-app": {
183
+ const slug = args._[2];
184
+ if (!slug) die("Missing app. Usage: muhkoo vfs use-app <slug> [--key <appKey>]");
185
+ const saved = await useApp(slug, args.key);
186
+ return ok(
187
+ `Writing as "${saved.slug}". Reads never needed this; writes are now metered to that app.`,
188
+ );
189
+ }
190
+
191
+ case "app": {
192
+ const current = await loadConfig();
193
+ const slug = current.vfsApp;
194
+ if (args.json) return json({ app: slug ?? null, known: Object.keys(current.vfsApps ?? {}) });
195
+ if (!slug) {
196
+ return info(
197
+ "Not writing as any app — reads work, writes will not.\n" +
198
+ "Sign one in with: muhkoo vfs use-app <slug> --key <appKey>",
199
+ );
200
+ }
201
+ return info(`Writing as "${slug}".`);
202
+ }
203
+
204
+ case "mount": {
205
+ const dir = required(a(2), "mount <dir> [--path /apps]");
206
+ const root = normalizeRoot(args.path ?? "/");
207
+ // Ctrl-C is the way out of a foreground watcher, so it has to be a clean
208
+ // stop that flushes state — not a process kill mid-write.
209
+ const controller = new AbortController();
210
+ const stop = () => controller.abort();
211
+ process.on("SIGINT", stop);
212
+ process.on("SIGTERM", stop);
213
+ await mountDir({ client, dir: resolve(dir), root, signal: controller.signal });
214
+ return ok("Unmounted.");
215
+ }
216
+
217
+ case "sweep": {
218
+ const { removed } = await fs.sweep({ force: Boolean(args.force) });
219
+ if (args.json) return json(removed);
220
+ return removed.length
221
+ ? ok(`Reclaimed ${removed.length} orphaned record${removed.length === 1 ? "" : "s"}.`)
222
+ : info("Nothing to reclaim — the filesystem is tidy.");
223
+ }
224
+
225
+ default:
226
+ return die(`Unknown subcommand "vfs ${sub}". See \`muhkoo vfs --help\`.`);
227
+ }
228
+ }
229
+ }
230
+
231
+ function required(value, usage) {
232
+ if (!value) die(`Missing argument. Usage: muhkoo vfs ${usage}`);
233
+ return value;
234
+ }
235
+
236
+ function pair(args, usage) {
237
+ const from = args._[2];
238
+ const to = args._[3];
239
+ if (!from || !to) die(`Missing argument. Usage: muhkoo vfs ${usage}`);
240
+ return [from, to];
241
+ }
242
+
243
+ function humanSize(bytes) {
244
+ if (bytes < 1024) return `${bytes} B`;
245
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
246
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
247
+ }
248
+
249
+ /**
250
+ * Point the CLI at an app, by the domain you use it at.
251
+ *
252
+ * A domain is how a USER knows an app — not a slug, and certainly not a key —
253
+ * and this is meant to work for anyone who uses an app, not only whoever built
254
+ * it. So the app publishes its own public config and we read it from there.
255
+ *
256
+ * It has to come from the app rather than the platform: key plaintexts are
257
+ * never stored server-side (only `keyHashPrefix`), so no API can answer "what
258
+ * is the key for this domain". A publishable key is public by design — it ships
259
+ * in the app's own bundle — so the app serving it at a well-known path gives
260
+ * away nothing that loading the app in a browser does not.
261
+ *
262
+ * A bare slug still works for an app you own and have a key for.
263
+ */
264
+ async function useApp(nameOrDomain, key) {
265
+ const cfg = await loadConfig();
266
+ const known = cfg.vfsApps ?? {};
267
+ const looksLikeDomain = nameOrDomain.includes(".");
268
+
269
+ if (!key && !known[nameOrDomain] && looksLikeDomain) {
270
+ key = await fetchPublicKey(nameOrDomain);
271
+ }
272
+
273
+ if (!key && !known[nameOrDomain]) {
274
+ die(
275
+ `Could not work out the app key for "${nameOrDomain}".\n` +
276
+ (looksLikeDomain
277
+ ? `That app does not publish ${WELL_KNOWN} yet. Pass it once with --key <appKey>.`
278
+ : `Pass it once with --key <appKey>, or use the domain you access the app at.\n` +
279
+ `App keys are shown when an app is created (muhkoo apps create).`),
280
+ );
281
+ }
282
+ const next = key ? { ...known, [nameOrDomain]: key } : known;
283
+ await saveConfig({ ...cfg, vfsApps: next, vfsApp: nameOrDomain });
284
+ return { slug: nameOrDomain, key: next[nameOrDomain] };
285
+ }
286
+
287
+ const WELL_KNOWN = "/.well-known/muhkoo.json";
288
+
289
+ /** Read an app's published public config. Returns the key, or null. */
290
+ async function fetchPublicKey(domain) {
291
+ const host = domain.replace(/^https?:\/\//, "").replace(/\/.*$/, "");
292
+ const url = `https://${host}${WELL_KNOWN}`;
293
+ try {
294
+ const res = await fetch(url);
295
+ if (!res.ok) return null;
296
+ const body = await res.json();
297
+ const key = body?.publishableKey ?? body?.key;
298
+ // Only ever accept a PUBLISHABLE key from a public document. A site that
299
+ // served a secret key here would be leaking it, and storing it because it
300
+ // was offered would make us complicit in that.
301
+ if (typeof key !== "string" || !/_pk_/.test(key)) return null;
302
+ info(`Read ${host}'s public config (app ${body?.slug ?? body?.appId ?? "?"}).`);
303
+ return key;
304
+ } catch {
305
+ return null;
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Read a local file for upload.
311
+ *
312
+ * A missing file is the most likely thing to go wrong here and it is entirely
313
+ * mundane — a typo, or the wrong directory. A Node stack trace for that is
314
+ * noise that buries the one fact that matters: which path was not found.
315
+ */
316
+ async function readLocal(path) {
317
+ try {
318
+ return new Uint8Array(await readFile(path));
319
+ } catch (err) {
320
+ if (err.code === "ENOENT") die(`No such file: ${resolve(path)}`);
321
+ if (err.code === "EISDIR") die(`${path} is a directory — put takes a single file.`);
322
+ if (err.code === "EACCES") die(`Cannot read ${path}: permission denied.`);
323
+ throw err;
324
+ }
325
+ }
326
+
327
+ /** A mount root is always an absolute directory path, with no trailing slash. */
328
+ function normalizeRoot(path) {
329
+ const p = ("/" + path).replace(/\/+/g, "/").replace(/\/$/, "");
330
+ return p === "" ? "/" : p;
331
+ }
package/src/index.js CHANGED
@@ -16,9 +16,12 @@ const COMMANDS = {
16
16
  whoami: () => import("./commands/whoami.js"),
17
17
  apps: () => import("./commands/apps.js"),
18
18
  keys: () => import("./commands/apps.js"), // `keys rotate` lives in apps.js
19
+ tokens: () => import("./commands/tokens.js"),
19
20
  provision: () => import("./commands/provision.js"),
20
21
  deploy: () => import("./commands/deploy.js"),
21
22
  promote: () => import("./commands/promote.js"),
23
+ vfs: () => import("./commands/vfs.js"),
24
+ devices: () => import("./commands/devices.js"),
22
25
  hosting: () => import("./commands/hosting.js"),
23
26
  domains: () => import("./commands/domains.js"),
24
27
  tables: () => import("./commands/tables.js"),
@@ -36,11 +39,13 @@ Usage:
36
39
  Account
37
40
  login sign in as a developer (stores a session token)
38
41
  logout clear the stored session
42
+ devices ls|rm machines paired to your account
39
43
  whoami show the signed-in developer
40
44
 
41
45
  Apps
42
46
  apps ls|get|create|slug|rm manage apps
43
47
  keys rotate <appId> rotate an app's keys
48
+ tokens ls|create|revoke manage scoped access tokens
44
49
 
45
50
  Backend
46
51
  provision --spec <f> create/update tables, agents, functions from a spec
@@ -48,6 +53,10 @@ Backend
48
53
  agents ls|get|rm|enable|disable|models
49
54
  functions ls|get|code|deploy|rm|enable|disable
50
55
 
56
+ Files
57
+ vfs ls|cat|put|get|rm|cp|mv|find|history|restore
58
+ your encrypted filesystem
59
+
51
60
  Hosting
52
61
  deploy deploy a built client to Muhkoo hosting (test env)
53
62
  promote promote an app's test hosting → production
package/src/lib/auth.js CHANGED
@@ -14,7 +14,7 @@ import { die, step } from "./ui.js";
14
14
  * Download the ZK login circuit assets (wasm + zkey) to a temp dir and return
15
15
  * local file paths — in Node the prover reads them off disk, not over HTTP.
16
16
  */
17
- async function downloadCircuits(baseUrl) {
17
+ export async function downloadCircuits(baseUrl) {
18
18
  const dir = await mkdtemp(join(tmpdir(), "muhkoo-circuits-"));
19
19
  const fetchTo = async (path, file) => {
20
20
  const res = await fetch(baseUrl + path);
@@ -31,7 +31,7 @@ async function downloadCircuits(baseUrl) {
31
31
  }
32
32
 
33
33
  /** Resolve `@muhkoo/connect`'s `Client` from the CLI's own dependencies. */
34
- async function loadClient() {
34
+ export async function loadClient() {
35
35
  try {
36
36
  const mod = await import("@muhkoo/connect");
37
37
  if (!mod.Client) throw new Error("Client export missing");
@@ -0,0 +1,235 @@
1
+ /**
2
+ * `muhkoo vfs mount` — a local directory kept in step with your filesystem.
3
+ *
4
+ * Pulls a subtree to disk, then watches BOTH ends: local edits queue upward,
5
+ * remote changes arrive over the personal space's socket and land on disk.
6
+ *
7
+ * ## Why content hashes, not timestamps
8
+ *
9
+ * Every decision is made from the SHA-256 of file contents ({@link planSync}),
10
+ * never mtimes. Two reasons. Timestamps disagree across machines and survive
11
+ * round-trips badly. And hashing is what makes the echo problem disappear: when
12
+ * we write a file because the VFS changed, the resulting filesystem event
13
+ * hashes to what we just recorded, so it plans to "none" and the loop stops on
14
+ * its own. Suppression by flag or by timing window is the usual approach and it
15
+ * is fragile — an editor that rewrites the file 20ms late defeats it.
16
+ *
17
+ * ## What is deliberately not here
18
+ *
19
+ * No daemon. `mount` runs in the foreground until interrupted, like a dev
20
+ * server, because a background process needs supervision, log rotation and a
21
+ * story for "which mounts are running" that is worth more than a first version.
22
+ */
23
+
24
+ import { createHash } from "node:crypto";
25
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
26
+ import { watch } from "node:fs";
27
+ import { dirname, join, relative, sep } from "node:path";
28
+
29
+ import { planSync } from "./syncPlan.js";
30
+ import { info, ok, warn } from "./ui.js";
31
+
32
+ /** Never sync these. Build output and dependencies belong to the machine. */
33
+ const IGNORE = new Set([".git", "node_modules", ".muhkoo", ".DS_Store", "dist", ".cache", ".next"]);
34
+
35
+ /**
36
+ * Skip anything enormous.
37
+ *
38
+ * The VFS chunks large files happily, but mounting a directory that happens to
39
+ * contain a disk image should not silently upload it. Named limit, loud skip.
40
+ */
41
+ const MAX_BYTES = 100 * 1024 * 1024;
42
+
43
+ /** Coalesce editor churn — a save is often several events in a few ms. */
44
+ const SETTLE_MS = 250;
45
+
46
+ const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");
47
+
48
+ /** Where the last-synced view lives, inside the mount. */
49
+ const statePath = (dir) => join(dir, ".muhkoo", "mount.json");
50
+
51
+ async function loadState(dir) {
52
+ try {
53
+ return JSON.parse(await readFile(statePath(dir), "utf8"));
54
+ } catch {
55
+ return {}; // first mount, or someone cleared it — a full compare is safe
56
+ }
57
+ }
58
+
59
+ async function saveState(dir, state) {
60
+ await mkdir(dirname(statePath(dir)), { recursive: true });
61
+ await writeFile(statePath(dir), JSON.stringify(state, null, 2) + "\n");
62
+ }
63
+
64
+ /** Hash every syncable file under `dir`, keyed by VFS-style relative path. */
65
+ async function scanLocal(dir) {
66
+ const out = {};
67
+ const walk = async (abs) => {
68
+ let entries;
69
+ try {
70
+ entries = await readdir(abs, { withFileTypes: true });
71
+ } catch {
72
+ return; // vanished mid-scan; the next pass will see it
73
+ }
74
+ for (const entry of entries) {
75
+ if (IGNORE.has(entry.name)) continue;
76
+ const child = join(abs, entry.name);
77
+ if (entry.isDirectory()) {
78
+ await walk(child);
79
+ continue;
80
+ }
81
+ if (!entry.isFile()) continue; // sockets, fifos, symlinks: not ours
82
+ try {
83
+ const info = await stat(child);
84
+ if (info.size > MAX_BYTES) {
85
+ warn(`skipping ${relative(dir, child)} — ${Math.round(info.size / 1e6)} MB is over the mount limit`);
86
+ continue;
87
+ }
88
+ out["/" + relative(dir, child).split(sep).join("/")] = sha(await readFile(child));
89
+ } catch {
90
+ // Raced with a delete or a permission change; ignore this pass.
91
+ }
92
+ }
93
+ };
94
+ await walk(dir);
95
+ return out;
96
+ }
97
+
98
+ /** Hash every file under the mounted VFS subtree. */
99
+ async function scanRemote(vfs, root) {
100
+ const out = {};
101
+ if (!(await vfs.exists(root))) return out;
102
+ for (const abs of await vfs.walk(root)) {
103
+ out[abs.slice(root.length) || "/" + abs.split("/").pop()] = sha(await vfs.readFile(abs));
104
+ }
105
+ return out;
106
+ }
107
+
108
+ /**
109
+ * Reconcile once, and return the new last-synced view.
110
+ *
111
+ * Applied sequentially rather than in parallel: writes touch one directory
112
+ * record each, and two concurrent writes to the same record would have one
113
+ * silently lose ([[VfsNamespace]] consistency note).
114
+ */
115
+ async function reconcile({ vfs, dir, root, state }) {
116
+ const [local, remote] = await Promise.all([scanLocal(dir), scanRemote(vfs, root)]);
117
+ const plan = planSync({ last: state, local, remote });
118
+ if (!plan.length) return state;
119
+
120
+ const next = { ...state };
121
+ for (const { path, action } of plan) {
122
+ const localAbs = join(dir, path.slice(1).split("/").join(sep));
123
+ const remoteAbs = root + path;
124
+ try {
125
+ switch (action) {
126
+ case "push": {
127
+ const bytes = await readFile(localAbs);
128
+ await vfs.writeFile(remoteAbs, new Uint8Array(bytes));
129
+ next[path] = sha(bytes);
130
+ info(`↑ ${path}`);
131
+ break;
132
+ }
133
+ case "pull": {
134
+ const bytes = await vfs.readFile(remoteAbs);
135
+ await mkdir(dirname(localAbs), { recursive: true });
136
+ await writeFile(localAbs, bytes);
137
+ next[path] = sha(bytes);
138
+ info(`↓ ${path}`);
139
+ break;
140
+ }
141
+ case "delete-remote":
142
+ await vfs.delete(remoteAbs).catch(() => {});
143
+ delete next[path];
144
+ info(`✕ ${path} (removed here)`);
145
+ break;
146
+ case "delete-local":
147
+ await rm(localAbs, { force: true });
148
+ delete next[path];
149
+ info(`✕ ${path} (removed there)`);
150
+ break;
151
+ case "forget":
152
+ delete next[path];
153
+ break;
154
+ case "conflict": {
155
+ // Local wins, because that is where the person is working —
156
+ // but say so, and say how to get the other version back. The
157
+ // VFS keeps history, so this is recoverable rather than lost,
158
+ // which is the only reason picking a winner is acceptable.
159
+ const bytes = await readFile(localAbs);
160
+ await vfs.writeFile(remoteAbs, new Uint8Array(bytes));
161
+ next[path] = sha(bytes);
162
+ warn(
163
+ `conflict on ${path} — kept your local copy.\n` +
164
+ ` The other version is still there: muhkoo vfs history ${remoteAbs}`,
165
+ );
166
+ break;
167
+ }
168
+ }
169
+ } catch (err) {
170
+ warn(`${path}: ${err?.message ?? err}`);
171
+ }
172
+ }
173
+ await saveState(dir, next);
174
+ return next;
175
+ }
176
+
177
+ /**
178
+ * Mount `root` at `dir` and keep them in step until `signal` aborts.
179
+ */
180
+ export async function mount({ client, dir, root, signal }) {
181
+ const vfs = client.vfs;
182
+ await mkdir(dir, { recursive: true });
183
+
184
+ let state = await loadState(dir);
185
+ info(`Mounting ${root} → ${dir}`);
186
+ state = await reconcile({ vfs, dir, root, state });
187
+ ok("In sync. Watching for changes — press Ctrl-C to stop.");
188
+
189
+ // One reconcile at a time, with a trailing pass if anything arrived while we
190
+ // were busy. Without the trailing pass a change landing mid-sync would wait
191
+ // for the NEXT unrelated event to be noticed.
192
+ let running = false;
193
+ let queued = false;
194
+ let timer = null;
195
+ const sync = async () => {
196
+ if (running) {
197
+ queued = true;
198
+ return;
199
+ }
200
+ running = true;
201
+ try {
202
+ state = await reconcile({ vfs, dir, root, state });
203
+ } catch (err) {
204
+ warn(`sync failed: ${err?.message ?? err}`);
205
+ } finally {
206
+ running = false;
207
+ if (queued) {
208
+ queued = false;
209
+ void sync();
210
+ }
211
+ }
212
+ };
213
+ const schedule = () => {
214
+ clearTimeout(timer);
215
+ timer = setTimeout(() => void sync(), SETTLE_MS);
216
+ };
217
+
218
+ const watcher = watch(dir, { recursive: true }, (_event, filename) => {
219
+ // `filename` can be null on some platforms; a bare reconcile is correct
220
+ // either way, so this never has to trust it.
221
+ if (filename && filename.split(sep).some((part) => IGNORE.has(part))) return;
222
+ schedule();
223
+ });
224
+
225
+ const unwatchRemote = vfs.watch(() => schedule());
226
+
227
+ await new Promise((resolve) => {
228
+ signal.addEventListener("abort", resolve, { once: true });
229
+ });
230
+
231
+ clearTimeout(timer);
232
+ watcher.close();
233
+ unwatchRemote();
234
+ await saveState(dir, state);
235
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * What to do about one path, given three views of it.
3
+ *
4
+ * Sync bugs are hard to see and expensive when they land — a wrong answer here
5
+ * silently deletes work — so the decision is a pure function of three content
6
+ * hashes and nothing else:
7
+ *
8
+ * last what we last synced (undefined: never synced)
9
+ * local what is on disk now (undefined: not there)
10
+ * remote what is in the VFS now (undefined: not there)
11
+ *
12
+ * `last` is what makes a DELETE distinguishable from a file that has simply
13
+ * never been seen. Without it, "missing on one side" is ambiguous and the only
14
+ * safe reading is to copy everything back forever.
15
+ */
16
+
17
+ /**
18
+ * @returns one of:
19
+ * "none" nothing to do
20
+ * "push" local → VFS
21
+ * "pull" VFS → local
22
+ * "delete-remote" removed locally; remove it there too
23
+ * "delete-local" removed remotely; remove it here too
24
+ * "forget" gone from both; drop it from state
25
+ * "conflict" changed on BOTH sides since the last sync
26
+ */
27
+ export function planPath({ last, local, remote }) {
28
+ if (local === undefined && remote === undefined) return last === undefined ? "none" : "forget";
29
+
30
+ if (local === undefined) {
31
+ // Only remote has it. If it matches what we last synced, the local copy
32
+ // was deleted; otherwise it is new (or changed) and should come down.
33
+ return last !== undefined && last === remote ? "delete-remote" : "pull";
34
+ }
35
+ if (remote === undefined) {
36
+ return last !== undefined && last === local ? "delete-local" : "push";
37
+ }
38
+ if (local === remote) return "none"; // identical, whatever the history
39
+
40
+ if (local === last) return "pull"; // only the remote moved
41
+ if (remote === last) return "push"; // only the local moved
42
+ return "conflict"; // both moved
43
+ }
44
+
45
+ /** Plan every path across the three views. Returns a list of {path, action}. */
46
+ export function planSync({ last, local, remote }) {
47
+ const paths = new Set([...Object.keys(last), ...Object.keys(local), ...Object.keys(remote)]);
48
+ const plan = [];
49
+ for (const path of [...paths].sort()) {
50
+ const action = planPath({ last: last[path], local: local[path], remote: remote[path] });
51
+ if (action !== "none") plan.push({ path, action });
52
+ }
53
+ return plan;
54
+ }
package/src/lib/vfs.js ADDED
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Open `client.vfs` for the CLI.
3
+ *
4
+ * Uses the SDK, not raw HTTP, on purpose: the filesystem's on-disk format is
5
+ * encrypted directory records with keys chained from parent to child, and a
6
+ * second implementation over HTTP would be a second thing to keep byte-exact.
7
+ * `muhkoo vfs ls` and the IDE's file tree run the SAME code.
8
+ *
9
+ * Two things are needed: a SESSION (to authenticate the calls) and the master
10
+ * SEED (to derive the root key that decrypts the records). The session comes
11
+ * from `muhkoo login`; the seed comes from the stored key, or from a password
12
+ * prompt when there is none.
13
+ */
14
+
15
+ import { hostname, userInfo } from "node:os";
16
+
17
+ import { loadConfig, resolveBase, saveConfig } from "./config.js";
18
+ import { loadClient, downloadCircuits } from "./auth.js";
19
+ import { die, info, step, prompt, promptHidden } from "./ui.js";
20
+
21
+ /**
22
+ * Build a Client whose session and identity are both established.
23
+ *
24
+ * Returns the client so callers can reach `client.vfs` — and anything else the
25
+ * SDK offers — rather than a narrow wrapper that would drift from it.
26
+ */
27
+ export async function openClient(args) {
28
+ const cfg = await loadConfig();
29
+ const baseUrl = await resolveBase(args, cfg);
30
+ const token = args.token || process.env.MUHKOO_DEV_TOKEN || cfg.token;
31
+ if (!token) die("Not signed in. Run `muhkoo login` first.");
32
+
33
+ // Storing bytes is METERED, and the shard store attributes them to an app —
34
+ // so a write needs an app key even though the filesystem is the user's own.
35
+ // Reads do not, which is why ls and cat work with no app signed in at all.
36
+ const apiKey = resolveAppKey(args, cfg);
37
+
38
+ const Client = await loadClient();
39
+ const client = new Client({
40
+ baseUrl,
41
+ apiKey,
42
+ // Hand the SDK the session we already hold instead of logging in again.
43
+ sessionStore: {
44
+ load: () => ({ token, username: cfg.username ?? "", commitment: cfg.commitment ?? "" }),
45
+ save: () => {},
46
+ clear: () => {},
47
+ },
48
+ });
49
+
50
+ // Hydrate the session from the store BEFORE unlocking. `SessionState` loads
51
+ // its store asynchronously, so a freshly-constructed client has no commitment
52
+ // yet — and every personal-space call is addressed by commitment, so they all
53
+ // fail with "no session" until this runs. It also verifies the token, so an
54
+ // expired one says so here instead of surfacing later as a confusing
55
+ // filesystem error. Ordering matters: a failed verify clears session state,
56
+ // which would wipe a seed we had already put there.
57
+ const user = await client.auth.zk.restore();
58
+ if (!user) die("Your session has expired. Run `muhkoo login` and try again.");
59
+
60
+ await unlock({ args, cfg, baseUrl, client });
61
+
62
+ // Restore the working directory. A CLI is a fresh process each time, so `cd`
63
+ // only means anything if it survives between invocations — the same reason a
64
+ // shell keeps PWD. A directory that has since been deleted silently falls
65
+ // back to the root rather than making every later command fail.
66
+ if (cfg.vfsCwd && cfg.vfsCwd !== "/") {
67
+ await client.vfs.cd(cfg.vfsCwd).catch(async () => {
68
+ await saveConfig({ ...cfg, vfsCwd: "/" });
69
+ info(`Working directory ${cfg.vfsCwd} is gone — back to /.`);
70
+ });
71
+ }
72
+ return client;
73
+ }
74
+
75
+ /**
76
+ * Unlock the client's encryption identity.
77
+ *
78
+ * Prefers this machine's DEVICE PAIRING: the vault holds the master seed
79
+ * wrapped under a key that exists only here, so nothing on this disk IS the
80
+ * seed, and the pairing can be withdrawn from anywhere (`muhkoo devices rm`) —
81
+ * which a stored seed never could be, because nothing can reach out and
82
+ * un-store it.
83
+ *
84
+ * With no pairing, signs in once and pairs. `MUHKOO_SEED` stays supported for
85
+ * CI, where there is no interactive login to pair with.
86
+ */
87
+ async function unlock({ args, cfg, baseUrl, client }) {
88
+ if (process.env.MUHKOO_SEED) {
89
+ client.auth.zk.unlockWithSeed(process.env.MUHKOO_SEED);
90
+ return;
91
+ }
92
+
93
+ if (cfg.deviceFactorId && cfg.deviceKey && cfg.username) {
94
+ try {
95
+ await client.auth.zk.unlockWithDevice(cfg.username, cfg.deviceFactorId, cfg.deviceKey);
96
+ return;
97
+ } catch (err) {
98
+ const msg = err?.message ?? String(err);
99
+ // A REVOKED pairing is not something to retry through. Falling back to a
100
+ // password prompt would quietly re-pair a machine whose access was
101
+ // deliberately withdrawn.
102
+ if (/revoked|no longer paired/i.test(msg)) {
103
+ await saveConfig({ ...cfg, deviceFactorId: undefined, deviceKey: undefined });
104
+ die(msg);
105
+ }
106
+ info(`Stored device key did not work (${msg}) — signing in to re-pair.`);
107
+ }
108
+ }
109
+
110
+ await pairThisMachine({ args, cfg, baseUrl, client });
111
+ }
112
+
113
+ /** Sign in once, pair this machine, and unlock the passed client. */
114
+ async function pairThisMachine({ args, cfg, baseUrl, client }) {
115
+ info("This machine is not paired yet — signing in once to pair it.");
116
+ const username = args.username || cfg.username || (await prompt("Username: "));
117
+ const password = args.password || process.env.MUHKOO_PASSWORD || (await promptHidden("Password: "));
118
+ if (!username || !password) die("A username and password are required to pair this machine.");
119
+
120
+ step("Fetching ZK circuit assets…");
121
+ const circuits = await downloadCircuits(baseUrl);
122
+ const Client = await loadClient();
123
+ step("Proving identity…");
124
+ const authed = new Client({ baseUrl, circuits });
125
+ await authed.auth.zk.login(username, password);
126
+
127
+ const seed = authed.auth.zk.seedBase64;
128
+ if (!seed) die("Signed in, but no encryption key was recovered — the account may have no password factor.");
129
+
130
+ if (args.pair === false) {
131
+ client.auth.zk.unlockWithSeed(seed); // --no-pair: unlock now, store nothing
132
+ return;
133
+ }
134
+
135
+ const label = deviceLabel();
136
+ const { factorId, deviceKey } = await authed.auth.zk.enrollDevice(label);
137
+ // `seed: undefined` clears a seed left by an older CLI — the whole point is
138
+ // that it stops living on this disk.
139
+ await saveConfig({ ...cfg, username, deviceFactorId: factorId, deviceKey, seed: undefined });
140
+ client.auth.zk.unlockWithSeed(seed);
141
+ info(`Paired this machine as "${label}". Revoke it any time: muhkoo devices rm ${factorId}`);
142
+ }
143
+
144
+ /** A name the owner will recognise in `muhkoo devices ls`. */
145
+ function deviceLabel() {
146
+ return `${userInfo().username}@${hostname()}`;
147
+ }
148
+
149
+ /**
150
+ * The key to write as, from `--key`, the environment, or the app signed in with
151
+ * `muhkoo vfs use-app`.
152
+ *
153
+ * Absent is a legitimate state, not an error: reads work without one, so this
154
+ * returns undefined and lets the write itself fail with an explanation.
155
+ */
156
+ function resolveAppKey(args, cfg) {
157
+ if (args.key) return args.key;
158
+ if (process.env.MUHKOO_APP_KEY) return process.env.MUHKOO_APP_KEY;
159
+ const slug = args.app || cfg.vfsApp;
160
+ if (!slug) return undefined;
161
+ return (cfg.vfsApps ?? {})[slug];
162
+ }
163
+
164
+ /**
165
+ * Turn the shard store's 401 into an instruction.
166
+ *
167
+ * "API key required to store shards" is accurate and useless — it names a
168
+ * concept the person at the terminal has no reason to know, and says nothing
169
+ * about what to do next.
170
+ */
171
+ export function explainWriteFailure(err, cfg) {
172
+ const msg = err?.message ?? String(err);
173
+ if (!/API key required|store shards|401/.test(msg)) return msg;
174
+ const known = Object.keys(cfg?.vfsApps ?? {});
175
+ return (
176
+ "Writing stores bytes, which are metered to an app — so a write needs one signed in.\n" +
177
+ (known.length
178
+ ? `Try: muhkoo vfs use-app ${known[0]}`
179
+ : "Sign one in with: muhkoo vfs use-app <slug> --key <appKey>\n" +
180
+ "App keys are shown when an app is created (muhkoo apps create).")
181
+ );
182
+ }