@sandbaseai/cli 0.1.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/LICENSE ADDED
@@ -0,0 +1,3 @@
1
+ Copyright 2026 SandBase
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy at https://www.apache.org/licenses/LICENSE-2.0
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # @sandbaseai/cli
2
+
3
+ Node.js 20+ CLI for securely connecting Codex, Claude Code, Cursor, or Hermes to SandBase MCP.
4
+
5
+ ```sh
6
+ npx -y @sandbaseai/cli connect --client codex
7
+ sandbase doctor --client codex
8
+ sandbase unregister --client codex
9
+ ```
10
+
11
+ The CLI opens the SandBase authorization page. Secrets are never included in command-line arguments or browser URLs. `SANDBASE_API_URL` may override the API origin for development and tests.
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ const client = process.argv[process.argv.indexOf("--client") + 1];
6
+ const store = join(process.env.SANDBASE_HOME || join(homedir(), ".sandbase"), "credentials.json");
7
+ let record;
8
+ try { record = JSON.parse(await readFile(store, "utf8"))[client]; } catch { process.stderr.write("SandBase credential is unavailable. Run sandbase connect again.\n"); process.exit(1); }
9
+ if (!record?.credential || !record?.mcpUrl) { process.stderr.write("SandBase credential is unavailable.\n"); process.exit(1); }
10
+ let buffer = Buffer.alloc(0), session;
11
+ process.stdin.on("data", async chunk => { buffer = Buffer.concat([buffer, chunk]); for (;;) { const split = buffer.indexOf("\n"); if (split < 0) break; const line = buffer.subarray(0, split).toString().trim(); buffer = buffer.subarray(split + 1); if (!line) continue; let request; try { request = JSON.parse(line); } catch { continue; } try { const headers = { authorization: `Bearer ${record.credential}`, "content-type": "application/json", accept: "application/json, text/event-stream" }; if (session) headers["mcp-session-id"] = session; const response = await fetch(record.mcpUrl, { method: "POST", headers, body: JSON.stringify(request) }); session = response.headers.get("mcp-session-id") || session; const text = await response.text(); for (const part of text.split("\n")) { const payload = part.startsWith("data:") ? part.slice(5).trim() : part.trim(); if (payload.startsWith("{")) process.stdout.write(payload + "\n"); } if (!response.ok && request.id !== undefined) process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, error: { code: -32000, message: `SandBase MCP request failed (${response.status})` } }) + "\n"); } catch { if (request.id !== undefined) process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, error: { code: -32000, message: "SandBase MCP is unavailable" } }) + "\n"); } } });
@@ -0,0 +1,23 @@
1
+ import type { Client } from "../types.js";
2
+ export interface AdapterResult {
3
+ path: string;
4
+ backup?: string;
5
+ changed: boolean;
6
+ }
7
+ export interface BridgeResult extends AdapterResult {
8
+ }
9
+ export interface AdapterIO {
10
+ backup(path: string): Promise<string | undefined>;
11
+ write(path: string, data: string, mode?: number): Promise<void>;
12
+ restore(path: string, backupPath?: string): Promise<void>;
13
+ }
14
+ export declare function detectClient(client: Client): {
15
+ installed: boolean;
16
+ detail: string;
17
+ };
18
+ export declare function installBridge(home?: string): Promise<BridgeResult>;
19
+ export declare function rollbackBridge(result: BridgeResult): Promise<void>;
20
+ export declare function configure(client: Client, bridge: string, env?: NodeJS.ProcessEnv, io?: AdapterIO): Promise<AdapterResult>;
21
+ export declare function rollback(result: AdapterResult): Promise<void>;
22
+ export declare function unregister(client: Client, env?: NodeJS.ProcessEnv): Promise<boolean>;
23
+ export declare function isConfigured(client: Client, env?: NodeJS.ProcessEnv): Promise<boolean>;
@@ -0,0 +1,104 @@
1
+ import { mkdir, readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { spawnSync } from "node:child_process";
5
+ import { parse as parseToml } from "smol-toml";
6
+ import { parseDocument } from "yaml";
7
+ import { atomicWrite, backup, readOptional, restore } from "../fs-safe.js";
8
+ import { configPath, sandbaseHome } from "../paths.js";
9
+ const defaultIO = { backup, write: atomicWrite, restore };
10
+ const executables = { codex: "codex", "claude-code": "claude", cursor: "cursor", hermes: "hermes" };
11
+ export function detectClient(client) { const result = spawnSync(executables[client], ["--version"], { encoding: "utf8", timeout: 5000 }); const detail = (result.stdout || result.stderr || "").trim().split("\n")[0] || "not found"; return { installed: result.status === 0, detail }; }
12
+ const start = "# >>> sandbase managed >>>", end = "# <<< sandbase managed <<<";
13
+ function block(client, bridge) {
14
+ if (client === "codex")
15
+ return `${start}\n[mcp_servers.sandbase]\ncommand = "node"\nargs = ["${bridge.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}", "--client", "codex"]\n${end}`;
16
+ return ` ${start}\n sandbase:\n command: node\n args:\n - ${JSON.stringify(bridge)}\n - --client\n - hermes\n ${end}`;
17
+ }
18
+ function managedText(raw, value) { const re = new RegExp(`${start.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${end.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "m"); return re.test(raw) ? raw.replace(re, value) : raw.replace(/\s*$/, "") + (raw.trim() ? "\n\n" : "") + value + "\n"; }
19
+ function removeManaged(raw) { return raw.replace(new RegExp(`\\n?[ \\t]*${start.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?[ \\t]*${end.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\n?`, "m"), "\n"); }
20
+ function removeCodexEntry(raw) { const lines = raw.split("\n"); const at = lines.findIndex(line => line.trim() === "[mcp_servers.sandbase]"); if (at < 0)
21
+ return raw; let end = at + 1; while (end < lines.length && !lines[end]?.trimStart().startsWith("["))
22
+ end++; lines.splice(at, end - at); return lines.join("\n").replace(/\n{3,}/g, "\n\n"); }
23
+ function removeHermesEntry(raw) { const lines = raw.split("\n"); const at = lines.findIndex(line => /^ sandbase:[ \t]*$/.test(line)); if (at < 0)
24
+ return raw; let end = at + 1; while (end < lines.length) {
25
+ const line = lines[end] || "";
26
+ if (line.trim() && !line.startsWith(" "))
27
+ break;
28
+ end++;
29
+ } lines.splice(at, end - at); return lines.join("\n"); }
30
+ function hermesUpdate(raw, bridge) { const own = block("hermes", bridge); const cleaned = removeHermesEntry(removeManaged(raw)).replace(/^(mcp_servers:[ \t]*)\n+/m, "$1\n"); if (/^mcp_servers:[ \t]*$/m.test(cleaned))
31
+ return cleaned.replace(/^mcp_servers:[ \t]*$/m, match => `${match}\n${own}`); return cleaned.replace(/\s*$/, "") + (cleaned.trim() ? "\n" : "") + `mcp_servers:\n${own}\n`; }
32
+ function jsonUpdate(raw, client, bridge, remove = false) { const obj = raw ? JSON.parse(raw) : {}; if (!obj || Array.isArray(obj))
33
+ throw new Error("Client configuration root must be an object"); const servers = obj.mcpServers === undefined ? {} : obj.mcpServers; if (!servers || typeof servers !== "object" || Array.isArray(servers))
34
+ throw new Error("mcpServers must be an object"); const map = servers; if (remove)
35
+ delete map.sandbase;
36
+ else
37
+ map.sandbase = { command: "node", args: [bridge, "--client", client] }; obj.mcpServers = map; return JSON.stringify(obj, null, 2) + "\n"; }
38
+ function validateText(client, text) { if (!text.trim())
39
+ return; if (client === "codex") {
40
+ const value = parseToml(text);
41
+ if (!value || typeof value !== "object" || Array.isArray(value))
42
+ throw new Error("TOML root must be a table");
43
+ return;
44
+ } if (client === "hermes") {
45
+ const doc = parseDocument(text, { prettyErrors: false, uniqueKeys: true });
46
+ if (doc.errors.length)
47
+ throw doc.errors[0];
48
+ const value = doc.toJS({ maxAliasCount: 50 });
49
+ if (!value || typeof value !== "object" || Array.isArray(value))
50
+ throw new Error("YAML root must be a mapping");
51
+ } }
52
+ export async function installBridge(home = sandbaseHome()) { const dir = join(home, "bin"); await mkdir(dir, { recursive: true, mode: 0o700 }); const target = join(dir, "sandbase-mcp-bridge.mjs"); const source = fileURLToPath(new URL("../../assets/mcp-bridge.mjs", import.meta.url)); const next = await readFile(source, "utf8"); const current = await readOptional(target); if (current === next)
53
+ return { path: target, changed: false }; const backupPath = await backup(target); try {
54
+ await atomicWrite(target, next, 0o600);
55
+ }
56
+ catch (e) {
57
+ await restore(target, backupPath);
58
+ throw e;
59
+ } return backupPath ? { path: target, backup: backupPath, changed: true } : { path: target, changed: true }; }
60
+ export async function rollbackBridge(result) { await rollback(result); }
61
+ export async function configure(client, bridge, env = process.env, io = defaultIO) { const path = configPath(client, env); const raw = await readOptional(path); let next; try {
62
+ const text = raw || "";
63
+ validateText(client, text);
64
+ next = client === "claude-code" || client === "cursor" ? jsonUpdate(raw, client, bridge) : client === "hermes" ? hermesUpdate(text, bridge) : managedText(text.includes(start) ? text : removeCodexEntry(text), block(client, bridge));
65
+ validateText(client, next);
66
+ }
67
+ catch {
68
+ throw new Error(`${client} configuration is invalid; no changes were made`);
69
+ } if (next === raw)
70
+ return { path, changed: false }; const backupPath = await io.backup(path); try {
71
+ await io.write(path, next);
72
+ }
73
+ catch (e) {
74
+ await io.restore(path, backupPath);
75
+ throw e;
76
+ } return backupPath ? { path, backup: backupPath, changed: true } : { path, changed: true }; }
77
+ export async function rollback(result) { if (result.changed)
78
+ await restore(result.path, result.backup); }
79
+ export async function unregister(client, env = process.env) { const path = configPath(client, env); const raw = await readOptional(path); if (!raw)
80
+ return false; let next; try {
81
+ validateText(client, raw);
82
+ next = client === "claude-code" || client === "cursor" ? jsonUpdate(raw, client, "", true) : client === "codex" ? removeCodexEntry(removeManaged(raw)) : removeHermesEntry(removeManaged(raw));
83
+ validateText(client, next);
84
+ }
85
+ catch {
86
+ throw new Error(`${client} configuration is invalid; no changes were made`);
87
+ } if (next === raw)
88
+ return false; const backupPath = await backup(path); try {
89
+ await atomicWrite(path, next);
90
+ }
91
+ catch (e) {
92
+ await restore(path, backupPath);
93
+ throw e;
94
+ } return true; }
95
+ export async function isConfigured(client, env = process.env) { const raw = await readOptional(configPath(client, env)); if (!raw)
96
+ return false; if (client === "claude-code" || client === "cursor") {
97
+ try {
98
+ const o = JSON.parse(raw);
99
+ return !!o.mcpServers?.sandbase;
100
+ }
101
+ catch {
102
+ return false;
103
+ }
104
+ } return raw.includes(start) && raw.includes(end); }
@@ -0,0 +1,28 @@
1
+ import type { Client, Exchange, Grant } from "../types.js";
2
+ export interface Secrets {
3
+ requestId: string;
4
+ deviceSecret: string;
5
+ verifier: string;
6
+ deviceChallenge: string;
7
+ codeChallenge: string;
8
+ }
9
+ export declare function createSecrets(): Secrets;
10
+ export declare class ApiError extends Error {
11
+ readonly status: number;
12
+ readonly code: string;
13
+ constructor(status: number, code: string, message: string);
14
+ }
15
+ export declare class AuthorizationApi {
16
+ readonly baseUrl: string;
17
+ private readonly fetcher;
18
+ constructor(baseUrl: string, fetcher?: typeof fetch);
19
+ private request;
20
+ create(client: Client, s: Secrets): Promise<Grant>;
21
+ status(id: string, secret: string): Promise<{
22
+ status: string;
23
+ interval: number;
24
+ }>;
25
+ exchange(id: string, secret: string, verifier: string): Promise<Exchange>;
26
+ cancel(id: string, secret: string): Promise<void>;
27
+ cleanup(id: string, token: string): Promise<void>;
28
+ }
@@ -0,0 +1,28 @@
1
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
+ const b64 = (b) => b.toString("base64url");
3
+ export function createSecrets() { const deviceSecret = b64(randomBytes(32)); const verifier = b64(randomBytes(32)); return { requestId: randomUUID(), deviceSecret, verifier, deviceChallenge: b64(createHash("sha256").update(deviceSecret).digest()), codeChallenge: b64(createHash("sha256").update(verifier).digest()) }; }
4
+ export class ApiError extends Error {
5
+ status;
6
+ code;
7
+ constructor(status, code, message) {
8
+ super(message);
9
+ this.status = status;
10
+ this.code = code;
11
+ }
12
+ }
13
+ export class AuthorizationApi {
14
+ baseUrl;
15
+ fetcher;
16
+ constructor(baseUrl, fetcher = fetch) {
17
+ this.baseUrl = baseUrl;
18
+ this.fetcher = fetcher;
19
+ }
20
+ async request(path, init) { const res = await this.fetcher(this.baseUrl + path, init); if (res.status === 204)
21
+ return undefined; const body = await res.json().catch(() => ({})); if (!res.ok)
22
+ throw new ApiError(res.status, body.error?.code || "request_failed", body.error?.message || `Request failed (${res.status})`); return body; }
23
+ create(client, s) { return this.request("/api/cli/authorizations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ request_id: s.requestId, client, device_secret_challenge: s.deviceChallenge, code_challenge: s.codeChallenge, code_challenge_method: "S256" }) }); }
24
+ status(id, secret) { return this.request(`/api/cli/authorizations/${encodeURIComponent(id)}/status`, { headers: { authorization: `Device ${secret}` } }); }
25
+ exchange(id, secret, verifier) { return this.request(`/api/cli/authorizations/${encodeURIComponent(id)}/token`, { method: "POST", headers: { authorization: `Device ${secret}`, "content-type": "application/json" }, body: JSON.stringify({ code_verifier: verifier }) }); }
26
+ cancel(id, secret) { return this.request(`/api/cli/authorizations/${encodeURIComponent(id)}`, { method: "DELETE", headers: { authorization: `Device ${secret}` } }); }
27
+ cleanup(id, token) { return this.request(`/api/cli/authorizations/${encodeURIComponent(id)}/credential`, { method: "DELETE", headers: { authorization: `Cleanup ${token}` } }); }
28
+ }
@@ -0,0 +1,12 @@
1
+ import type { Client, Exchange } from "../types.js";
2
+ import { AuthorizationApi } from "./api.js";
3
+ export interface FlowOptions {
4
+ signal?: AbortSignal;
5
+ open(url: string): Promise<void>;
6
+ sleep(ms: number, signal?: AbortSignal): Promise<void>;
7
+ log(message: string): void;
8
+ }
9
+ export declare function authorize(api: AuthorizationApi, client: Client, options: FlowOptions): Promise<{
10
+ authorizationId: string;
11
+ exchange: Exchange;
12
+ }>;
@@ -0,0 +1,42 @@
1
+ import { ApiError, createSecrets } from "./api.js";
2
+ export async function authorize(api, client, options) {
3
+ const secrets = createSecrets();
4
+ const grant = await api.create(client, secrets);
5
+ let pending = true;
6
+ const cancel = async () => { if (pending)
7
+ await api.cancel(grant.authorization_id, secrets.deviceSecret).catch(() => undefined); };
8
+ options.signal?.addEventListener("abort", () => void cancel(), { once: true });
9
+ try {
10
+ options.log(`Open this URL to authorize: ${grant.verification_uri_complete}`);
11
+ await options.open(grant.verification_uri_complete);
12
+ let interval = Math.max(1, grant.interval) * 1000;
13
+ for (;;) {
14
+ if (options.signal?.aborted)
15
+ throw new Error("Authorization cancelled");
16
+ await options.sleep(interval, options.signal);
17
+ try {
18
+ const state = await api.status(grant.authorization_id, secrets.deviceSecret);
19
+ interval = Math.max(interval, state.interval * 1000);
20
+ if (state.status === "pending")
21
+ continue;
22
+ if (state.status === "approved")
23
+ break;
24
+ throw new Error(`Authorization ${state.status}`);
25
+ }
26
+ catch (e) {
27
+ if (e instanceof ApiError && e.code === "slow_down") {
28
+ interval += 5000;
29
+ continue;
30
+ }
31
+ throw e;
32
+ }
33
+ }
34
+ const exchange = await api.exchange(grant.authorization_id, secrets.deviceSecret, secrets.verifier);
35
+ pending = false;
36
+ return { authorizationId: grant.authorization_id, exchange };
37
+ }
38
+ catch (e) {
39
+ await cancel();
40
+ throw e;
41
+ }
42
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ import { connect, doctor, unregister } from "./commands.js";
3
+ import { isClient } from "./types.js";
4
+ if (Number(process.versions.node.split(".")[0]) < 20) {
5
+ console.error("SandBase CLI requires Node.js 20 or newer. Upgrade Node.js and retry.");
6
+ process.exit(1);
7
+ }
8
+ const [command, ...args] = process.argv.slice(2);
9
+ const at = args.indexOf("--client");
10
+ const value = at >= 0 ? args[at + 1] : undefined;
11
+ if (!command || !value || !isClient(value) || !["connect", "doctor", "unregister"].includes(command)) {
12
+ console.error("Usage: sandbase <connect|doctor|unregister> --client <codex|claude-code|cursor|hermes>");
13
+ process.exit(2);
14
+ }
15
+ const controller = new AbortController();
16
+ for (const signal of ["SIGINT", "SIGTERM"])
17
+ process.once(signal, () => controller.abort());
18
+ try {
19
+ if (command === "connect")
20
+ await connect(value, { signal: controller.signal });
21
+ else if (command === "doctor") {
22
+ if (!(await doctor(value)))
23
+ process.exitCode = 1;
24
+ }
25
+ else
26
+ await unregister(value);
27
+ }
28
+ catch (e) {
29
+ const message = e instanceof Error ? e.message : "Unknown failure";
30
+ if (message.includes("fetch failed"))
31
+ console.error("Authorization response may have been lost. Check SandBase Dashboard for a newly created CLI credential, revoke it if present, then retry.");
32
+ else
33
+ console.error(message.replace(/sk-[A-Za-z0-9_-]+/g, "[REDACTED]"));
34
+ process.exitCode = 1;
35
+ }
@@ -0,0 +1,17 @@
1
+ import type { Client } from "./types.js";
2
+ import { AuthorizationApi } from "./auth/api.js";
3
+ import { FileCredentialStore } from "./credentials/store.js";
4
+ export declare function openBrowser(url: string): Promise<void>;
5
+ export declare function connect(client: Client, deps?: {
6
+ api?: AuthorizationApi;
7
+ store?: FileCredentialStore;
8
+ open?: (url: string) => Promise<void>;
9
+ signal?: AbortSignal;
10
+ log?: (s: string) => void;
11
+ detect?: (client: Client) => {
12
+ installed: boolean;
13
+ detail: string;
14
+ };
15
+ }): Promise<void>;
16
+ export declare function doctor(client: Client, store?: FileCredentialStore): Promise<boolean>;
17
+ export declare function unregister(client: Client, store?: FileCredentialStore): Promise<void>;
@@ -0,0 +1,55 @@
1
+ import { spawn } from "node:child_process";
2
+ import { platform } from "node:os";
3
+ import { AuthorizationApi } from "./auth/api.js";
4
+ import { authorize } from "./auth/flow.js";
5
+ import { FileCredentialStore } from "./credentials/store.js";
6
+ import { configure, detectClient, installBridge, isConfigured, rollback, rollbackBridge, unregister as removeAdapter } from "./adapters/index.js";
7
+ const sleep = (ms, signal) => new Promise((resolve, reject) => { const t = setTimeout(resolve, ms); signal?.addEventListener("abort", () => { clearTimeout(t); reject(new Error("Authorization cancelled")); }, { once: true }); });
8
+ async function compensate(api, authorizationId, token) { for (const delay of [0, 250, 750]) {
9
+ if (delay)
10
+ await sleep(delay);
11
+ try {
12
+ await api.cleanup(authorizationId, token);
13
+ return true;
14
+ }
15
+ catch { /* bounded retry inside the five-minute capability window */ }
16
+ } return false; }
17
+ export async function openBrowser(url) { const cmd = platform() === "darwin" ? "open" : platform() === "win32" ? "cmd" : "xdg-open"; const args = platform() === "win32" ? ["/c", "start", "", url] : [url]; const child = spawn(cmd, args, { detached: true, stdio: "ignore" }); child.unref(); }
18
+ export async function connect(client, deps = {}) {
19
+ const api = deps.api || new AuthorizationApi((process.env.SANDBASE_API_URL || "https://sandbase.ai").replace(/\/$/, ""));
20
+ const store = deps.store || new FileCredentialStore();
21
+ const log = deps.log || console.log;
22
+ const detected = (deps.detect || detectClient)(client);
23
+ if (!detected.installed)
24
+ throw new Error(`${client} is not installed or is incompatible (${detected.detail}). Install a supported version, then retry.`);
25
+ const previous = await store.get(client);
26
+ const { authorizationId, exchange } = await authorize(api, client, { open: deps.open || openBrowser, sleep, log, ...(deps.signal ? { signal: deps.signal } : {}) });
27
+ let configured;
28
+ let bridgeResult;
29
+ try {
30
+ const record = { credential: exchange.credential, credentialId: exchange.credential_id, keyPrefix: exchange.key_prefix, client, scope: exchange.scope, mcpUrl: exchange.mcp_url, createdAt: exchange.created_at };
31
+ await store.save(record);
32
+ bridgeResult = await installBridge();
33
+ configured = await configure(client, bridgeResult.path);
34
+ if (!(await isConfigured(client)))
35
+ throw new Error("Client configuration verification failed");
36
+ log(`Connected ${client} to ${record.mcpUrl} with ${record.keyPrefix}… (${record.scope.join(",")})`);
37
+ exchange.cleanup_token = "";
38
+ }
39
+ catch (e) {
40
+ if (configured)
41
+ await rollback(configured).catch(() => undefined);
42
+ if (bridgeResult)
43
+ await rollbackBridge(bridgeResult).catch(() => undefined);
44
+ if (previous)
45
+ await store.save(previous).catch(() => undefined);
46
+ else
47
+ await store.remove(client).catch(() => undefined);
48
+ if (!(await compensate(api, authorizationId, exchange.cleanup_token)))
49
+ console.error("WARNING: automatic credential cleanup failed. Revoke the new CLI credential in SandBase Dashboard immediately.");
50
+ exchange.cleanup_token = "";
51
+ throw e;
52
+ }
53
+ }
54
+ export async function doctor(client, store = new FileCredentialStore()) { const credential = await store.get(client); const configured = await isConfigured(client); const detected = detectClient(client); console.log(`${client}: installed=${detected.installed ? "yes" : "no"}, config=${configured ? "ok" : "missing"}, credential=${credential ? credential.keyPrefix + "…" : "missing"}, url=${credential?.mcpUrl || "unknown"}, scope=${credential?.scope.join(",") || "unknown"}`); return detected.installed && !!credential && configured; }
55
+ export async function unregister(client, store = new FileCredentialStore()) { await removeAdapter(client); await store.remove(client); console.log(`Removed local SandBase registration for ${client}. Revoke the server credential in SandBase Dashboard if it is no longer needed.`); }
@@ -0,0 +1,14 @@
1
+ import type { Client, CredentialRecord } from "../types.js";
2
+ export interface CredentialStore {
3
+ save(record: CredentialRecord): Promise<void>;
4
+ get(client: Client): Promise<CredentialRecord | undefined>;
5
+ remove(client: Client): Promise<void>;
6
+ }
7
+ export declare class FileCredentialStore implements CredentialStore {
8
+ readonly path: string;
9
+ constructor(home?: string);
10
+ private all;
11
+ save(record: CredentialRecord): Promise<void>;
12
+ get(client: Client): Promise<CredentialRecord | undefined>;
13
+ remove(client: Client): Promise<void>;
14
+ }
@@ -0,0 +1,13 @@
1
+ import { join } from "node:path";
2
+ import { atomicWrite, readOptional } from "../fs-safe.js";
3
+ import { sandbaseHome } from "../paths.js";
4
+ export class FileCredentialStore {
5
+ path;
6
+ constructor(home = sandbaseHome()) { this.path = join(home, "credentials.json"); }
7
+ async all() { const raw = await readOptional(this.path); if (!raw)
8
+ return {}; const parsed = JSON.parse(raw); if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
9
+ throw new Error("SandBase credential store is invalid"); return parsed; }
10
+ async save(record) { const all = await this.all(); all[record.client] = record; await atomicWrite(this.path, JSON.stringify(all, null, 2) + "\n"); }
11
+ async get(client) { return (await this.all())[client]; }
12
+ async remove(client) { const all = await this.all(); delete all[client]; await atomicWrite(this.path, JSON.stringify(all, null, 2) + "\n"); }
13
+ }
@@ -0,0 +1,4 @@
1
+ export declare function readOptional(path: string): Promise<string | undefined>;
2
+ export declare function atomicWrite(path: string, data: string, mode?: number): Promise<void>;
3
+ export declare function backup(path: string): Promise<string | undefined>;
4
+ export declare function restore(path: string, backupPath?: string): Promise<void>;
@@ -0,0 +1,45 @@
1
+ import { chmod, copyFile, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import { randomBytes } from "node:crypto";
4
+ export async function readOptional(path) { try {
5
+ return await readFile(path, "utf8");
6
+ }
7
+ catch (e) {
8
+ if (e.code === "ENOENT")
9
+ return undefined;
10
+ throw e;
11
+ } }
12
+ export async function atomicWrite(path, data, mode = 0o600) {
13
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
14
+ const tmp = `${path}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
15
+ const fh = await open(tmp, "wx", mode);
16
+ try {
17
+ await fh.writeFile(data, "utf8");
18
+ await fh.sync();
19
+ }
20
+ finally {
21
+ await fh.close();
22
+ }
23
+ await rename(tmp, path);
24
+ await chmod(path, mode);
25
+ }
26
+ export async function backup(path) {
27
+ try {
28
+ await stat(path);
29
+ }
30
+ catch (e) {
31
+ if (e.code === "ENOENT")
32
+ return undefined;
33
+ throw e;
34
+ }
35
+ const dest = `${path}.sandbase-backup-${Date.now()}-${randomBytes(3).toString("hex")}`;
36
+ await copyFile(path, dest);
37
+ await chmod(dest, 0o600);
38
+ return dest;
39
+ }
40
+ export async function restore(path, backupPath) { if (backupPath) {
41
+ await copyFile(backupPath, path);
42
+ await chmod(path, 0o600);
43
+ }
44
+ else
45
+ await rm(path, { force: true }); }
@@ -0,0 +1,2 @@
1
+ export declare function sandbaseHome(env?: NodeJS.ProcessEnv): string;
2
+ export declare function configPath(client: string, env?: NodeJS.ProcessEnv): string;
package/dist/paths.js ADDED
@@ -0,0 +1,13 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ export function sandbaseHome(env = process.env) { return env.SANDBASE_HOME || join(homedir(), ".sandbase"); }
4
+ export function configPath(client, env = process.env) {
5
+ const home = env.HOME || homedir();
6
+ if (client === "codex")
7
+ return env.CODEX_HOME ? join(env.CODEX_HOME, "config.toml") : join(home, ".codex", "config.toml");
8
+ if (client === "claude-code")
9
+ return join(home, ".claude.json");
10
+ if (client === "cursor")
11
+ return join(home, ".cursor", "mcp.json");
12
+ return env.HERMES_HOME ? join(env.HERMES_HOME, "config.yaml") : join(home, ".hermes", "config.yaml");
13
+ }
@@ -0,0 +1,30 @@
1
+ export declare const clients: readonly ["codex", "claude-code", "cursor", "hermes"];
2
+ export type Client = typeof clients[number];
3
+ export declare function isClient(value: string): value is Client;
4
+ export interface CredentialRecord {
5
+ credential: string;
6
+ credentialId: string;
7
+ keyPrefix: string;
8
+ client: Client;
9
+ scope: string[];
10
+ mcpUrl: string;
11
+ createdAt: string;
12
+ }
13
+ export interface Grant {
14
+ authorization_id: string;
15
+ status: string;
16
+ verification_uri_complete: string;
17
+ expires_at: string;
18
+ interval: number;
19
+ }
20
+ export interface Exchange {
21
+ credential: string;
22
+ credential_id: string;
23
+ key_prefix: string;
24
+ client: Client;
25
+ scope: string[];
26
+ mcp_url: string;
27
+ created_at: string;
28
+ cleanup_token: string;
29
+ cleanup_expires_at: string;
30
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export const clients = ["codex", "claude-code", "cursor", "hermes"];
2
+ export function isClient(value) { return clients.includes(value); }
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@sandbaseai/cli",
3
+ "version": "0.1.0",
4
+ "description": "Secure SandBase MCP onboarding CLI",
5
+ "type": "module",
6
+ "bin": {
7
+ "sandbase": "dist/cli.js"
8
+ },
9
+ "engines": {
10
+ "node": ">=20"
11
+ },
12
+ "files": [
13
+ "dist",
14
+ "assets/mcp-bridge.mjs",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsc -p tsconfig.json",
20
+ "test": "npm run build && tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js",
21
+ "lint": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json --noEmit",
22
+ "audit:package": "bash scripts/audit-package.sh",
23
+ "prepack": "npm run build"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "22.15.3",
27
+ "typescript": "5.8.3"
28
+ },
29
+ "license": "Apache-2.0",
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "https://github.com/sandbaseai/sandbase.git",
33
+ "directory": "sandbase-cli"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "provenance": true
38
+ },
39
+ "dependencies": {
40
+ "smol-toml": "1.7.0",
41
+ "yaml": "2.9.0"
42
+ }
43
+ }