@muhkoo/cli 0.7.0-alpha.4
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/LICENSE +21 -0
- package/README.md +122 -0
- package/bin/muhkoo.js +17 -0
- package/package.json +44 -0
- package/src/commands/_eject-runner.mjs +59 -0
- package/src/commands/agents.js +88 -0
- package/src/commands/apps.js +119 -0
- package/src/commands/deploy.js +101 -0
- package/src/commands/domains.js +75 -0
- package/src/commands/eject.js +40 -0
- package/src/commands/functions.js +108 -0
- package/src/commands/hosting.js +76 -0
- package/src/commands/login.js +66 -0
- package/src/commands/logout.js +17 -0
- package/src/commands/logs.js +45 -0
- package/src/commands/provision.js +232 -0
- package/src/commands/tables.js +60 -0
- package/src/commands/whoami.js +26 -0
- package/src/index.js +105 -0
- package/src/lib/args.js +32 -0
- package/src/lib/auth.js +62 -0
- package/src/lib/bases.js +28 -0
- package/src/lib/browser.js +20 -0
- package/src/lib/config.js +66 -0
- package/src/lib/http.js +59 -0
- package/src/lib/pkce.js +18 -0
- package/src/lib/spaces.js +41 -0
- package/src/lib/ui.js +102 -0
- package/src/lib/webLogin.js +140 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* muhkoo CLI entrypoint — argv routing, help, and version. Commands are loaded
|
|
3
|
+
* lazily so startup stays fast and the SDK is only imported when actually needed
|
|
4
|
+
* (login / eject).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { readFile } from "node:fs/promises";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { dirname, join } from "node:path";
|
|
10
|
+
import { parseArgs } from "./lib/args.js";
|
|
11
|
+
import { c, die } from "./lib/ui.js";
|
|
12
|
+
|
|
13
|
+
const COMMANDS = {
|
|
14
|
+
login: () => import("./commands/login.js"),
|
|
15
|
+
logout: () => import("./commands/logout.js"),
|
|
16
|
+
whoami: () => import("./commands/whoami.js"),
|
|
17
|
+
apps: () => import("./commands/apps.js"),
|
|
18
|
+
keys: () => import("./commands/apps.js"), // `keys rotate` lives in apps.js
|
|
19
|
+
provision: () => import("./commands/provision.js"),
|
|
20
|
+
deploy: () => import("./commands/deploy.js"),
|
|
21
|
+
hosting: () => import("./commands/hosting.js"),
|
|
22
|
+
domains: () => import("./commands/domains.js"),
|
|
23
|
+
tables: () => import("./commands/tables.js"),
|
|
24
|
+
agents: () => import("./commands/agents.js"),
|
|
25
|
+
functions: () => import("./commands/functions.js"),
|
|
26
|
+
logs: () => import("./commands/logs.js"),
|
|
27
|
+
eject: () => import("./commands/eject.js"),
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const TOP_HELP = `${c.bold("muhkoo")} — command-line interface for the Muhkoo platform
|
|
31
|
+
|
|
32
|
+
Usage:
|
|
33
|
+
muhkoo <command> [subcommand] [options]
|
|
34
|
+
|
|
35
|
+
Account
|
|
36
|
+
login sign in as a developer (stores a session token)
|
|
37
|
+
logout clear the stored session
|
|
38
|
+
whoami show the signed-in developer
|
|
39
|
+
|
|
40
|
+
Apps
|
|
41
|
+
apps ls|get|create|slug|rm manage apps
|
|
42
|
+
keys rotate <appId> rotate an app's keys
|
|
43
|
+
|
|
44
|
+
Backend
|
|
45
|
+
provision --spec <f> create/update tables, agents, functions from a spec
|
|
46
|
+
tables ls|get|rm inspect database tables
|
|
47
|
+
agents ls|get|rm|enable|disable|models
|
|
48
|
+
functions ls|get|code|deploy|rm|enable|disable
|
|
49
|
+
|
|
50
|
+
Hosting
|
|
51
|
+
deploy deploy a built client to Muhkoo hosting
|
|
52
|
+
hosting status|rollback|rm-release|unpublish
|
|
53
|
+
domains ls|add|rm manage custom domains
|
|
54
|
+
|
|
55
|
+
Tools
|
|
56
|
+
logs <appId> inspect an app's server-log Space
|
|
57
|
+
eject <agentApp.ts> preview an agent's compiled prompt + tools
|
|
58
|
+
|
|
59
|
+
Global options
|
|
60
|
+
--base <env|url> prod (default) | staging | local | a literal URL
|
|
61
|
+
--token <t> developer session token (overrides stored/login)
|
|
62
|
+
--json machine-readable output where supported
|
|
63
|
+
-h, --help help for a command
|
|
64
|
+
-v, --version print the CLI version
|
|
65
|
+
|
|
66
|
+
Run \`muhkoo <command> --help\` for details on a command.`;
|
|
67
|
+
|
|
68
|
+
async function version() {
|
|
69
|
+
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
70
|
+
const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
|
|
71
|
+
return pkg.version;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function run(argv) {
|
|
75
|
+
// Normalize -h/-v before the positional parse.
|
|
76
|
+
const wantsVersion = argv.includes("--version") || argv.includes("-v");
|
|
77
|
+
const wantsHelp = argv.includes("--help") || argv.includes("-h");
|
|
78
|
+
const args = parseArgs(argv.map((a) => (a === "-h" ? "--help" : a === "-v" ? "--version" : a)));
|
|
79
|
+
const name = args._[0];
|
|
80
|
+
|
|
81
|
+
if (wantsVersion) return console.log(await version());
|
|
82
|
+
if (!name || name === "help") return console.log(TOP_HELP);
|
|
83
|
+
|
|
84
|
+
const loader = COMMANDS[name];
|
|
85
|
+
if (!loader) {
|
|
86
|
+
die(`Unknown command "${name}". Run \`muhkoo --help\` for the command list.`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const mod = await loader();
|
|
90
|
+
|
|
91
|
+
// Per-command help.
|
|
92
|
+
if (wantsHelp) {
|
|
93
|
+
// `keys` reuses apps.js, which documents `keys rotate` in its own help.
|
|
94
|
+
console.log(mod.help || TOP_HELP);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// `keys rotate <appId>` dispatches to the named export in apps.js.
|
|
99
|
+
if (name === "keys") {
|
|
100
|
+
if (args._[1] !== "rotate") die("Usage: muhkoo keys rotate <appId>");
|
|
101
|
+
return mod.keysRotate(args);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return mod.default(args);
|
|
105
|
+
}
|
package/src/lib/args.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tiny dependency-free argv parser. Mirrors the convention used across the
|
|
3
|
+
* platform's `.mjs` scripts: `--flag value`, bare `--flag` → `true`, and
|
|
4
|
+
* positionals collected in `_`.
|
|
5
|
+
*
|
|
6
|
+
* parseArgs(["apps", "get", "--base", "staging", "--json"])
|
|
7
|
+
* → { _: ["apps", "get"], base: "staging", json: true }
|
|
8
|
+
*/
|
|
9
|
+
export function parseArgs(argv) {
|
|
10
|
+
const a = { _: [] };
|
|
11
|
+
for (let i = 0; i < argv.length; i++) {
|
|
12
|
+
const t = argv[i];
|
|
13
|
+
if (t.startsWith("--")) {
|
|
14
|
+
const key = t.slice(2);
|
|
15
|
+
const next = argv[i + 1];
|
|
16
|
+
if (next === undefined || next.startsWith("--")) a[key] = true;
|
|
17
|
+
else {
|
|
18
|
+
a[key] = next;
|
|
19
|
+
i++;
|
|
20
|
+
}
|
|
21
|
+
} else {
|
|
22
|
+
a._.push(t);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return a;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** First defined value among the candidates (skips `undefined`/`null`/`""`). */
|
|
29
|
+
export function firstOf(...vals) {
|
|
30
|
+
for (const v of vals) if (v !== undefined && v !== null && v !== "") return v;
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
package/src/lib/auth.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Programmatic developer auth. Uses `@muhkoo/connect` to run the zero-knowledge
|
|
3
|
+
* login and returns the issued session token. The SDK is imported lazily so the
|
|
4
|
+
* rest of the CLI (provision/deploy/etc., which only need a token) works even
|
|
5
|
+
* when the SDK or its prover isn't installed.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { mkdtemp, writeFile } from "node:fs/promises";
|
|
9
|
+
import { tmpdir } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { die, step } from "./ui.js";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Download the ZK login circuit assets (wasm + zkey) to a temp dir and return
|
|
15
|
+
* local file paths — in Node the prover reads them off disk, not over HTTP.
|
|
16
|
+
*/
|
|
17
|
+
async function downloadCircuits(baseUrl) {
|
|
18
|
+
const dir = await mkdtemp(join(tmpdir(), "muhkoo-circuits-"));
|
|
19
|
+
const fetchTo = async (path, file) => {
|
|
20
|
+
const res = await fetch(baseUrl + path);
|
|
21
|
+
if (!res.ok) die(`Could not fetch circuit asset ${path} (${res.status}).`);
|
|
22
|
+
const out = join(dir, file);
|
|
23
|
+
await writeFile(out, Buffer.from(await res.arrayBuffer()));
|
|
24
|
+
return out;
|
|
25
|
+
};
|
|
26
|
+
const [wasmUrl, zkeyUrl] = await Promise.all([
|
|
27
|
+
fetchTo("/circuits/build/preimagePoK_js/preimagePoK.wasm", "preimagePoK.wasm"),
|
|
28
|
+
fetchTo("/circuits/build/preimagePoK_0001.zkey", "preimagePoK_0001.zkey"),
|
|
29
|
+
]);
|
|
30
|
+
return { wasmUrl, zkeyUrl };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Resolve `@muhkoo/connect`'s `Client` from the CLI's own dependencies. */
|
|
34
|
+
async function loadClient() {
|
|
35
|
+
try {
|
|
36
|
+
const mod = await import("@muhkoo/connect");
|
|
37
|
+
if (!mod.Client) throw new Error("Client export missing");
|
|
38
|
+
return mod.Client;
|
|
39
|
+
} catch (e) {
|
|
40
|
+
die(
|
|
41
|
+
"Couldn't load @muhkoo/connect for programmatic login.\n" +
|
|
42
|
+
" Reinstall the CLI, or sign in via the portal and pass --token instead.\n" +
|
|
43
|
+
` Underlying error: ${e?.message || e}`,
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Run a zero-knowledge login and return `{ token, commitment, username }`.
|
|
50
|
+
* Throws (via `die`) on failure.
|
|
51
|
+
*/
|
|
52
|
+
export async function zkLogin({ baseUrl, username, password }) {
|
|
53
|
+
const Client = await loadClient();
|
|
54
|
+
step("Fetching ZK circuit assets…");
|
|
55
|
+
const circuits = await downloadCircuits(baseUrl);
|
|
56
|
+
step("Proving identity…");
|
|
57
|
+
const client = new Client({ baseUrl, circuits });
|
|
58
|
+
const user = await client.auth.zk.login(username, password);
|
|
59
|
+
const token = client.auth.zk.token;
|
|
60
|
+
if (!token) die("Login succeeded but no session token was issued.");
|
|
61
|
+
return { token, commitment: user?.commitment, username: user?.username ?? username };
|
|
62
|
+
}
|
package/src/lib/bases.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Known API bases. A `--base` value that isn't one of these short names is
|
|
3
|
+
* treated as a literal URL, so `--base http://localhost:8787` also works.
|
|
4
|
+
*/
|
|
5
|
+
export const BASES = {
|
|
6
|
+
prod: "https://api.muhkoo.dev",
|
|
7
|
+
production: "https://api.muhkoo.dev",
|
|
8
|
+
staging: "https://api.staging.muhkoo.dev",
|
|
9
|
+
local: "http://localhost:8787",
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
/** Resolve a `--base` short-name or literal URL to a concrete API base URL. */
|
|
13
|
+
export function resolveBaseUrl(value) {
|
|
14
|
+
if (!value) return BASES.prod;
|
|
15
|
+
return BASES[value] || value;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The public hosting host suffix for an API base (apps.* / apps.staging.*). */
|
|
19
|
+
export function appsSuffixFor(baseUrl) {
|
|
20
|
+
return baseUrl.includes("staging") ? "apps.staging.muhkoo.dev" : "apps.muhkoo.dev";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The hosted-auth SPA origin paired with an API base. */
|
|
24
|
+
export function authBaseFor(baseUrl) {
|
|
25
|
+
if (baseUrl.includes("staging")) return "https://auth.staging.muhkoo.dev";
|
|
26
|
+
if (baseUrl.includes("localhost")) return "http://localhost:5173";
|
|
27
|
+
return "https://auth.muhkoo.dev";
|
|
28
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Open a URL in the user's default browser, cross-platform. Best-effort: if the
|
|
3
|
+
* launcher isn't found, the caller still prints the URL for manual opening.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
|
|
8
|
+
export function openBrowser(url) {
|
|
9
|
+
const platform = process.platform;
|
|
10
|
+
const cmd = platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
|
|
11
|
+
const args = platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
12
|
+
try {
|
|
13
|
+
const child = spawn(cmd, args, { stdio: "ignore", detached: true });
|
|
14
|
+
child.on("error", () => {});
|
|
15
|
+
child.unref();
|
|
16
|
+
return true;
|
|
17
|
+
} catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistent CLI config at `~/.muhkoo/config.json`. Holds the developer session
|
|
3
|
+
* token and the default API base, written by `muhkoo login`. Every value can be
|
|
4
|
+
* overridden per-invocation by a flag or environment variable.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { readFile, writeFile, mkdir, chmod } from "node:fs/promises";
|
|
10
|
+
import { resolveBaseUrl } from "./bases.js";
|
|
11
|
+
import { firstOf } from "./args.js";
|
|
12
|
+
import { die } from "./ui.js";
|
|
13
|
+
|
|
14
|
+
export function configDir() {
|
|
15
|
+
return join(homedir(), ".muhkoo");
|
|
16
|
+
}
|
|
17
|
+
export function configPath() {
|
|
18
|
+
return join(configDir(), "config.json");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function loadConfig() {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(await readFile(configPath(), "utf8"));
|
|
24
|
+
} catch {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function saveConfig(next) {
|
|
30
|
+
await mkdir(configDir(), { recursive: true });
|
|
31
|
+
await writeFile(configPath(), JSON.stringify(next, null, 2) + "\n");
|
|
32
|
+
// Contains a session token — keep it owner-only.
|
|
33
|
+
await chmod(configPath(), 0o600).catch(() => {});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Resolve the API base URL for this invocation:
|
|
38
|
+
* --base flag → $MUHKOO_API_BASE → stored config → prod
|
|
39
|
+
*/
|
|
40
|
+
export async function resolveBase(args, cfg) {
|
|
41
|
+
cfg = cfg ?? (await loadConfig());
|
|
42
|
+
return resolveBaseUrl(firstOf(args.base, process.env.MUHKOO_API_BASE, cfg.base, "prod"));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Resolve a developer session token:
|
|
47
|
+
* --token flag → $MUHKOO_DEV_TOKEN → stored config token
|
|
48
|
+
* Exits with a clear hint if none is found.
|
|
49
|
+
*/
|
|
50
|
+
export async function resolveToken(args, cfg) {
|
|
51
|
+
cfg = cfg ?? (await loadConfig());
|
|
52
|
+
const token = firstOf(args.token, process.env.MUHKOO_DEV_TOKEN, cfg.token);
|
|
53
|
+
if (!token) {
|
|
54
|
+
die(
|
|
55
|
+
"Not signed in. Run `muhkoo login`, or pass `--token <sessionToken>` " +
|
|
56
|
+
"(or set MUHKOO_DEV_TOKEN). Copy a token from the portal after signing in.",
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
return token;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Build the `{ baseUrl, token }` context that dev-session commands need. */
|
|
63
|
+
export async function devContext(args) {
|
|
64
|
+
const cfg = await loadConfig();
|
|
65
|
+
return { baseUrl: await resolveBase(args, cfg), token: await resolveToken(args, cfg) };
|
|
66
|
+
}
|
package/src/lib/http.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP helpers for the management + data-plane APIs. Every call returns a
|
|
3
|
+
* normalized `{ ok, status, body }` so commands can branch on status (e.g. 402
|
|
4
|
+
* → "needs a paid plan") without re-parsing.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { die } from "./ui.js";
|
|
8
|
+
|
|
9
|
+
async function request(baseUrl, method, path, { auth, body, raw } = {}) {
|
|
10
|
+
const headers = {};
|
|
11
|
+
if (auth) headers.Authorization = `Bearer ${auth}`;
|
|
12
|
+
if (body !== undefined && !raw) headers["Content-Type"] = "application/json";
|
|
13
|
+
if (raw) headers["Content-Type"] = "application/octet-stream";
|
|
14
|
+
|
|
15
|
+
const res = await fetch(baseUrl + path, {
|
|
16
|
+
method,
|
|
17
|
+
headers,
|
|
18
|
+
body: body === undefined ? undefined : raw ? body : JSON.stringify(body),
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
if (raw) return { ok: res.ok, status: res.status, res };
|
|
22
|
+
const text = await res.text();
|
|
23
|
+
let parsed = null;
|
|
24
|
+
try {
|
|
25
|
+
parsed = text ? JSON.parse(text) : null;
|
|
26
|
+
} catch {
|
|
27
|
+
parsed = text;
|
|
28
|
+
}
|
|
29
|
+
return { ok: res.ok, status: res.status, body: parsed };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A management call authenticated with a developer session token (Bearer). */
|
|
33
|
+
export function devCall(ctx, method, path, body) {
|
|
34
|
+
return request(ctx.baseUrl, method, path, { auth: ctx.token, body });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A hosting/blob call authenticated with an app SECRET key (Bearer). */
|
|
38
|
+
export function skCall(baseUrl, key, method, path, body, opts = {}) {
|
|
39
|
+
return request(baseUrl, method, path, { auth: key, body, raw: opts.raw });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A data-plane GET authenticated with an app key via `X-Muhkoo-Key`. */
|
|
43
|
+
export async function appKeyGet(baseUrl, appKey, path) {
|
|
44
|
+
const res = await fetch(baseUrl + path, { headers: { "X-Muhkoo-Key": appKey } });
|
|
45
|
+
if (!res.ok) return null;
|
|
46
|
+
return res.json().catch(() => null);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Exit with a formatted message when a `{ ok, status, body }` result failed. */
|
|
50
|
+
export function ensure(result, what) {
|
|
51
|
+
if (result.ok) return result;
|
|
52
|
+
const detail =
|
|
53
|
+
typeof result.body === "string"
|
|
54
|
+
? result.body
|
|
55
|
+
: result.body
|
|
56
|
+
? JSON.stringify(result.body)
|
|
57
|
+
: "";
|
|
58
|
+
die(`${what} failed (${result.status})${detail ? `: ${detail}` : ""}`);
|
|
59
|
+
}
|
package/src/lib/pkce.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PKCE (RFC 7636, S256) + random state for the hosted-auth loopback login.
|
|
3
|
+
* Matches what the hosted auth page + accelerator expect (base64url, SHA-256).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { randomBytes, createHash } from "node:crypto";
|
|
7
|
+
|
|
8
|
+
const b64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
9
|
+
|
|
10
|
+
export function generatePkce() {
|
|
11
|
+
const verifier = b64url(randomBytes(32));
|
|
12
|
+
const challenge = b64url(createHash("sha256").update(verifier).digest());
|
|
13
|
+
return { verifier, challenge };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function randomState() {
|
|
17
|
+
return b64url(randomBytes(16));
|
|
18
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolve a `--space` / `--channel` flag to a concrete spaceId.
|
|
3
|
+
*
|
|
4
|
+
* A raw spaceId is returned as-is. A channel name (via `--channel`, or a
|
|
5
|
+
* `--space #name`) is resolved through the app-key channel registry, which needs
|
|
6
|
+
* a publishable key — read from the local `.muhkoo-app.json` written by
|
|
7
|
+
* `muhkoo provision`. If no pk is available, the caller must pass a spaceId.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readFile, access } from "node:fs/promises";
|
|
11
|
+
import { appKeyGet } from "./http.js";
|
|
12
|
+
import { die } from "./ui.js";
|
|
13
|
+
|
|
14
|
+
async function recordPk() {
|
|
15
|
+
try {
|
|
16
|
+
await access(".muhkoo-app.json");
|
|
17
|
+
const rec = JSON.parse(await readFile(".muhkoo-app.json", "utf8"));
|
|
18
|
+
return (rec.keys || []).find((k) => k.env === "test" && k.type === "pk")?.plaintext || null;
|
|
19
|
+
} catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function resolveSpace(ctx, args) {
|
|
25
|
+
const space = args.space;
|
|
26
|
+
const channel =
|
|
27
|
+
args.channel || (typeof space === "string" && space.startsWith("#") ? space.slice(1) : null);
|
|
28
|
+
if (space && !channel) return space;
|
|
29
|
+
if (!channel) die("Pass --space <spaceId> or --channel <name>.");
|
|
30
|
+
|
|
31
|
+
const pk = await recordPk();
|
|
32
|
+
if (!pk) {
|
|
33
|
+
die(
|
|
34
|
+
`Can't resolve channel "${channel}" without a publishable key. ` +
|
|
35
|
+
"Run from a provisioned app dir (.muhkoo-app.json), or pass --space <spaceId>.",
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
const res = await appKeyGet(ctx.baseUrl, pk, `/api/app/channels/${encodeURIComponent(channel)}`);
|
|
39
|
+
if (!res?.spaceId) die(`Channel "${channel}" not found — run the app once so it exists, then retry.`);
|
|
40
|
+
return res.spaceId;
|
|
41
|
+
}
|
package/src/lib/ui.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal terminal UI helpers — colors, status lines, tables, and prompts.
|
|
3
|
+
* No dependencies; respects `NO_COLOR` and non-TTY output.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const ESC = String.fromCharCode(27);
|
|
7
|
+
const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
8
|
+
const wrap = (code) => (s) => (useColor ? `${ESC}[${code}m${s}${ESC}[0m` : String(s));
|
|
9
|
+
|
|
10
|
+
export const c = {
|
|
11
|
+
bold: wrap("1"),
|
|
12
|
+
dim: wrap("2"),
|
|
13
|
+
red: wrap("31"),
|
|
14
|
+
green: wrap("32"),
|
|
15
|
+
yellow: wrap("33"),
|
|
16
|
+
blue: wrap("34"),
|
|
17
|
+
cyan: wrap("36"),
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export function info(msg = "") {
|
|
21
|
+
console.log(msg);
|
|
22
|
+
}
|
|
23
|
+
export function ok(msg) {
|
|
24
|
+
console.log(`${c.green("✓")} ${msg}`);
|
|
25
|
+
}
|
|
26
|
+
export function warn(msg) {
|
|
27
|
+
console.log(`${c.yellow("⚠")} ${msg}`);
|
|
28
|
+
}
|
|
29
|
+
export function step(msg) {
|
|
30
|
+
console.log(`${c.dim("→")} ${msg}`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Print an error and exit non-zero. */
|
|
34
|
+
export function die(msg) {
|
|
35
|
+
console.error(`\n${c.red("✗")} ${msg}\n`);
|
|
36
|
+
process.exit(1);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Pretty-print JSON to stdout (used by `--json` and `get` commands). */
|
|
40
|
+
export function json(obj) {
|
|
41
|
+
console.log(JSON.stringify(obj, null, 2));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Render a simple aligned table from rows of strings. */
|
|
45
|
+
export function table(headers, rows) {
|
|
46
|
+
const widths = headers.map((h, i) =>
|
|
47
|
+
Math.max(h.length, ...rows.map((r) => String(r[i] ?? "").length)),
|
|
48
|
+
);
|
|
49
|
+
const line = (cells) =>
|
|
50
|
+
cells.map((cell, i) => String(cell ?? "").padEnd(widths[i])).join(" ");
|
|
51
|
+
console.log(c.bold(line(headers)));
|
|
52
|
+
for (const r of rows) console.log(line(r));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Prompt for a line of input on stdin. */
|
|
56
|
+
export async function prompt(question) {
|
|
57
|
+
const rl = (await import("node:readline/promises")).createInterface({
|
|
58
|
+
input: process.stdin,
|
|
59
|
+
output: process.stdout,
|
|
60
|
+
});
|
|
61
|
+
try {
|
|
62
|
+
return (await rl.question(question)).trim();
|
|
63
|
+
} finally {
|
|
64
|
+
rl.close();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Prompt for a hidden line (passwords). Masks input on a TTY via raw mode; on a
|
|
70
|
+
* non-TTY (piped) it just reads a line.
|
|
71
|
+
*/
|
|
72
|
+
export function promptHidden(question) {
|
|
73
|
+
const stdin = process.stdin;
|
|
74
|
+
const stdout = process.stdout;
|
|
75
|
+
if (!stdin.isTTY) return prompt(question);
|
|
76
|
+
|
|
77
|
+
return new Promise((resolve) => {
|
|
78
|
+
stdout.write(question);
|
|
79
|
+
stdin.setRawMode(true);
|
|
80
|
+
stdin.resume();
|
|
81
|
+
stdin.setEncoding("utf8");
|
|
82
|
+
let buf = "";
|
|
83
|
+
const onKey = (ch) => {
|
|
84
|
+
const code = ch.charCodeAt(0);
|
|
85
|
+
if (ch === "\n" || ch === "\r" || code === 4 /* EOT */) {
|
|
86
|
+
stdin.setRawMode(false);
|
|
87
|
+
stdin.pause();
|
|
88
|
+
stdin.removeListener("data", onKey);
|
|
89
|
+
stdout.write("\n");
|
|
90
|
+
resolve(buf);
|
|
91
|
+
} else if (code === 3 /* Ctrl-C */) {
|
|
92
|
+
stdout.write("\n");
|
|
93
|
+
process.exit(130);
|
|
94
|
+
} else if (code === 127 || ch === "\b" /* Backspace */) {
|
|
95
|
+
buf = buf.slice(0, -1);
|
|
96
|
+
} else {
|
|
97
|
+
buf += ch;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
stdin.on("data", onKey);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-based developer login via the hosted auth page (auth.muhkoo.dev).
|
|
3
|
+
*
|
|
4
|
+
* Loopback OAuth (authorization-code + PKCE), per RFC 8252:
|
|
5
|
+
* 1. start a localhost HTTP server on a fixed loopback port
|
|
6
|
+
* 2. open the browser to auth.muhkoo.dev/authorize?…&redirect_uri=http://127.0.0.1:<port>/callback
|
|
7
|
+
* 3. the user signs in on the Muhkoo origin (credentials never touch the CLI)
|
|
8
|
+
* 4. the hosted page redirects back to the loopback with ?code&state
|
|
9
|
+
* 5. exchange the code (+ PKCE verifier) at /api/auth/token → a session token
|
|
10
|
+
*
|
|
11
|
+
* The CLI only needs the session token (it drives the developer management API).
|
|
12
|
+
* The sealed master seed rides in the URL fragment, which browsers never send to
|
|
13
|
+
* the loopback server — fine, because management ops don't need the seed.
|
|
14
|
+
*
|
|
15
|
+
* The loopback redirect URIs below are registered as first-party on the
|
|
16
|
+
* accelerator (FIRST_PARTY_REDIRECT_URIS), so the constant `muhkoo-cli` app id
|
|
17
|
+
* needs no per-developer app record.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import http from "node:http";
|
|
21
|
+
import { generatePkce, randomState } from "./pkce.js";
|
|
22
|
+
import { openBrowser } from "./browser.js";
|
|
23
|
+
import { authBaseFor } from "./bases.js";
|
|
24
|
+
import { step, info, die, c } from "./ui.js";
|
|
25
|
+
|
|
26
|
+
/** The CLI's first-party client id. Override with --app-id / $MUHKOO_CLI_APP_ID. */
|
|
27
|
+
export const DEFAULT_CLI_APP_ID = "muhkoo-cli";
|
|
28
|
+
|
|
29
|
+
/** Loopback ports tried in order — each must be registered in FIRST_PARTY_REDIRECT_URIS. */
|
|
30
|
+
const PORTS = [8976, 8977, 8978];
|
|
31
|
+
|
|
32
|
+
function successPage(message, isError) {
|
|
33
|
+
const color = isError ? "#c0392b" : "#0a1929";
|
|
34
|
+
const title = isError ? "Sign-in failed" : "Signed in to the Muhkoo CLI";
|
|
35
|
+
const body = isError ? message : "You can close this tab and return to your terminal.";
|
|
36
|
+
return `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title>
|
|
37
|
+
<style>body{font-family:Inter,system-ui,sans-serif;background:#f6f8fa;color:${color};
|
|
38
|
+
display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0}
|
|
39
|
+
.card{background:#fff;border-radius:12px;padding:40px 48px;box-shadow:0 6px 24px rgba(10,25,41,.08);text-align:center;max-width:420px}
|
|
40
|
+
h1{font-size:20px;margin:0 0 8px}p{color:#5b6b7b;margin:0}</style></head>
|
|
41
|
+
<body><div class="card"><h1>${title}</h1><p>${body}</p></div></body></html>`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function listen(port) {
|
|
45
|
+
return new Promise((resolve, reject) => {
|
|
46
|
+
const srv = http.createServer();
|
|
47
|
+
srv.once("error", reject);
|
|
48
|
+
srv.listen(port, "127.0.0.1", () => resolve(srv));
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function startLoopback() {
|
|
53
|
+
for (const port of PORTS) {
|
|
54
|
+
try {
|
|
55
|
+
const srv = await listen(port);
|
|
56
|
+
return { srv, port };
|
|
57
|
+
} catch (e) {
|
|
58
|
+
if (e?.code === "EADDRINUSE") continue;
|
|
59
|
+
throw e;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
die(`All loopback ports are busy (${PORTS.join(", ")}). Close whatever's using them and retry.`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Run the browser login and resolve `{ token, username, commitment }`.
|
|
67
|
+
* `baseUrl` is the API base; `appId` is the CLI client id.
|
|
68
|
+
*/
|
|
69
|
+
export async function webLogin({ baseUrl, appId }) {
|
|
70
|
+
const { srv, port } = await startLoopback();
|
|
71
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
72
|
+
const { verifier, challenge } = generatePkce();
|
|
73
|
+
const state = randomState();
|
|
74
|
+
const authUrl = `${authBaseFor(baseUrl)}/authorize?` + new URLSearchParams({
|
|
75
|
+
app_id: appId,
|
|
76
|
+
redirect_uri: redirectUri,
|
|
77
|
+
state,
|
|
78
|
+
code_challenge: challenge,
|
|
79
|
+
code_challenge_method: "S256",
|
|
80
|
+
}).toString();
|
|
81
|
+
|
|
82
|
+
const codePromise = new Promise((resolve, reject) => {
|
|
83
|
+
const timer = setTimeout(
|
|
84
|
+
() => reject(new Error("Timed out waiting for browser sign-in (5 min).")),
|
|
85
|
+
300_000,
|
|
86
|
+
);
|
|
87
|
+
srv.on("request", (req, res) => {
|
|
88
|
+
const u = new URL(req.url, redirectUri);
|
|
89
|
+
if (u.pathname !== "/callback") {
|
|
90
|
+
res.writeHead(404);
|
|
91
|
+
res.end("Not found");
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const code = u.searchParams.get("code");
|
|
95
|
+
const gotState = u.searchParams.get("state");
|
|
96
|
+
const error = u.searchParams.get("error");
|
|
97
|
+
const failed = error || !code || gotState !== state;
|
|
98
|
+
res.writeHead(failed ? 400 : 200, { "Content-Type": "text/html" });
|
|
99
|
+
res.end(
|
|
100
|
+
successPage(
|
|
101
|
+
error
|
|
102
|
+
? `The authorization server returned: ${error}`
|
|
103
|
+
: !code
|
|
104
|
+
? "No authorization code was returned."
|
|
105
|
+
: gotState !== state
|
|
106
|
+
? "State mismatch — please start the login again."
|
|
107
|
+
: "",
|
|
108
|
+
!!failed,
|
|
109
|
+
),
|
|
110
|
+
);
|
|
111
|
+
clearTimeout(timer);
|
|
112
|
+
if (error) return reject(new Error(`Sign-in failed: ${error}`));
|
|
113
|
+
if (!code) return reject(new Error("No authorization code returned."));
|
|
114
|
+
if (gotState !== state) return reject(new Error("State mismatch — possible CSRF. Start login again."));
|
|
115
|
+
resolve(code);
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
step("Opening your browser to sign in…");
|
|
120
|
+
const opened = openBrowser(authUrl);
|
|
121
|
+
info(`${opened ? "If it didn't open, visit:" : "Open this URL to sign in:"}\n ${c.cyan(authUrl)}\n`);
|
|
122
|
+
|
|
123
|
+
let code;
|
|
124
|
+
try {
|
|
125
|
+
code = await codePromise;
|
|
126
|
+
} finally {
|
|
127
|
+
srv.close();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
step("Exchanging authorization code…");
|
|
131
|
+
const res = await fetch(`${baseUrl}/api/auth/token`, {
|
|
132
|
+
method: "POST",
|
|
133
|
+
headers: { "Content-Type": "application/json" },
|
|
134
|
+
body: JSON.stringify({ code, codeVerifier: verifier, appId }),
|
|
135
|
+
});
|
|
136
|
+
if (!res.ok) die(`Token exchange failed (${res.status}): ${await res.text()}`);
|
|
137
|
+
const body = await res.json().catch(() => null);
|
|
138
|
+
if (!body?.sessionToken) die("No session token returned from the token exchange.");
|
|
139
|
+
return { token: body.sessionToken, username: body.username, commitment: body.commitment };
|
|
140
|
+
}
|