@mushi-mushi/cli 0.43.0 → 0.44.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/README.md +5 -3
- package/dist/{chunk-AEXZYEUS.js → chunk-25YBYYYC.js} +3085 -345
- package/dist/{chunk-X64CFG54.js → chunk-2XODEIM4.js} +0 -1
- package/dist/chunk-6XKFNK4C.js +8 -0
- package/dist/{connect-HSL2EUEV.js → chunk-NEFF6WK5.js} +40 -7
- package/dist/chunk-O6RN5FT5.js +178 -0
- package/dist/{chunk-AKUYV2CR.js → chunk-T3Q44NPC.js} +444 -16
- package/dist/{chunk-UZQZU5OP.js → chunk-ZL2HSPR5.js} +12 -8
- package/dist/connect-HTAUIXDX.js +13 -0
- package/dist/{daemon-ZQ6WYRLD.js → daemon-VDYY6GWG.js} +6 -5
- package/dist/detect.d.ts +2 -1
- package/dist/{endpoint-KN5YEANQ.js → endpoint-BPPL6DJN.js} +3 -5
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3413 -4840
- package/dist/init.d.ts +2 -1
- package/dist/init.js +6 -5
- package/dist/version.d.ts +6 -5
- package/dist/version.js +1 -1
- package/dist/wizard-args.d.ts +2 -1
- package/dist/wizard-bin.d.ts +2 -1
- package/dist/wizard-bin.js +6 -5
- package/package.json +5 -5
- package/templates/node/.env.example +1 -1
- package/templates/svelte/.env.example +1 -1
- package/templates/svelte/package.json +4 -4
- package/templates/svelte/src/App.svelte +1 -1
- package/templates/vue/.env.example +1 -1
- package/templates/vue/package.json +2 -2
- package/templates/vue/src/App.vue +1 -1
- package/dist/chunk-25P6NAME.js +0 -436
- package/dist/chunk-CG5KPP4S.js +0 -504
- package/dist/chunk-JQQACG3P.js +0 -10
- package/dist/chunk-LHSWFJOB.js +0 -765
- package/dist/chunk-WJ7ZTOF7.js +0 -8
- package/dist/chunk-X6SC4JKO.js +0 -67
- package/dist/chunk-ZDAN3RYF.js +0 -85
- package/dist/connect-OPWVFSNG.js +0 -13
- package/dist/detect-SOXPECZ3.js +0 -25
- package/dist/endpoint-XZHMF6EZ.js +0 -21
- package/dist/snippet-inject-BQO5I2RN.js +0 -15
- package/dist/version-JUEQJNGV.js +0 -9
package/dist/chunk-LHSWFJOB.js
DELETED
|
@@ -1,765 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
MUSHI_CLI_VERSION
|
|
3
|
-
} from "./chunk-WJ7ZTOF7.js";
|
|
4
|
-
import {
|
|
5
|
-
assertEndpoint,
|
|
6
|
-
normalizeEndpoint,
|
|
7
|
-
resolvePublicOrigin
|
|
8
|
-
} from "./chunk-X64CFG54.js";
|
|
9
|
-
|
|
10
|
-
// src/keychain.ts
|
|
11
|
-
import { createRequire } from "module";
|
|
12
|
-
var KEYCHAIN_SERVICE = "mushi-cli";
|
|
13
|
-
function accountName(profile = "default") {
|
|
14
|
-
return `api-key:${profile}`;
|
|
15
|
-
}
|
|
16
|
-
var _EntryClass = void 0;
|
|
17
|
-
function getEntryClass() {
|
|
18
|
-
if (process.env["MUSHI_NO_KEYCHAIN"]) return null;
|
|
19
|
-
if (_EntryClass === void 0) {
|
|
20
|
-
try {
|
|
21
|
-
const mod = createRequire(import.meta.url)("@napi-rs/keyring");
|
|
22
|
-
_EntryClass = mod.Entry ?? null;
|
|
23
|
-
} catch {
|
|
24
|
-
_EntryClass = null;
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
return _EntryClass ?? null;
|
|
28
|
-
}
|
|
29
|
-
function trySaveKeyToKeychain(apiKey, profile = "default") {
|
|
30
|
-
return saveSecret(accountName(profile), apiKey);
|
|
31
|
-
}
|
|
32
|
-
function saveSecret(account, apiKey) {
|
|
33
|
-
if (!apiKey) return false;
|
|
34
|
-
const EntryClass = getEntryClass();
|
|
35
|
-
if (!EntryClass) return false;
|
|
36
|
-
try {
|
|
37
|
-
const entry = new EntryClass(KEYCHAIN_SERVICE, account);
|
|
38
|
-
entry.setPassword(apiKey);
|
|
39
|
-
return true;
|
|
40
|
-
} catch {
|
|
41
|
-
return false;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
function tryLoadKeyFromKeychain(profile = "default") {
|
|
45
|
-
return loadSecret(accountName(profile));
|
|
46
|
-
}
|
|
47
|
-
function loadSecret(account) {
|
|
48
|
-
const EntryClass = getEntryClass();
|
|
49
|
-
if (!EntryClass) return null;
|
|
50
|
-
try {
|
|
51
|
-
const entry = new EntryClass(KEYCHAIN_SERVICE, account);
|
|
52
|
-
const key = entry.getPassword();
|
|
53
|
-
return key && key.length > 0 ? key : null;
|
|
54
|
-
} catch {
|
|
55
|
-
return null;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
// src/config.ts
|
|
60
|
-
import { randomUUID } from "crypto";
|
|
61
|
-
import { spawnSync } from "child_process";
|
|
62
|
-
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "fs";
|
|
63
|
-
import { homedir } from "os";
|
|
64
|
-
import { dirname, join } from "path";
|
|
65
|
-
var DEFAULT_PROFILE = "default";
|
|
66
|
-
function isMultiProfileFile(value) {
|
|
67
|
-
return typeof value === "object" && value !== null && "profiles" in value && typeof value.profiles === "object" && value.profiles !== null;
|
|
68
|
-
}
|
|
69
|
-
function savedSdkKeyFor(config, projectId) {
|
|
70
|
-
const saved = config.sdkKey;
|
|
71
|
-
if (!projectId || !saved || typeof saved !== "object") return void 0;
|
|
72
|
-
return saved.projectId === projectId && typeof saved.key === "string" && saved.key ? saved.key : void 0;
|
|
73
|
-
}
|
|
74
|
-
function resolveProfileName(explicit, fileActive) {
|
|
75
|
-
const fromEnv = process.env["MUSHI_PROFILE"]?.trim();
|
|
76
|
-
return explicit?.trim() || fromEnv || fileActive || DEFAULT_PROFILE;
|
|
77
|
-
}
|
|
78
|
-
var SECURE_FILE_MODE = 384;
|
|
79
|
-
var SECURE_DIR_MODE = 448;
|
|
80
|
-
function resolveXdgConfigPath() {
|
|
81
|
-
const xdg = process.env["XDG_CONFIG_HOME"];
|
|
82
|
-
if (xdg && xdg.length > 0) {
|
|
83
|
-
return join(xdg, "mushi", "config.json");
|
|
84
|
-
}
|
|
85
|
-
if (process.platform === "win32") {
|
|
86
|
-
const appData = process.env["APPDATA"];
|
|
87
|
-
if (appData && appData.length > 0) {
|
|
88
|
-
return join(appData, "mushi", "config.json");
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
return join(homedir(), ".config", "mushi", "config.json");
|
|
92
|
-
}
|
|
93
|
-
var LEGACY_CONFIG_PATH = join(homedir(), ".mushirc");
|
|
94
|
-
var CONFIG_PATH = resolveXdgConfigPath();
|
|
95
|
-
function loadConfig(path = CONFIG_PATH, opts = {}) {
|
|
96
|
-
let file = {};
|
|
97
|
-
if (existsSync(path)) {
|
|
98
|
-
tightenPermissions(path);
|
|
99
|
-
try {
|
|
100
|
-
const parsed = JSON.parse(readFileSync(path, "utf-8"));
|
|
101
|
-
if (isMultiProfileFile(parsed)) {
|
|
102
|
-
const name = resolveProfileName(opts.profile, parsed.activeProfile);
|
|
103
|
-
file = parsed.profiles[name] ?? {};
|
|
104
|
-
} else if (resolveProfileName(opts.profile, void 0) === DEFAULT_PROFILE) {
|
|
105
|
-
file = parsed ?? {};
|
|
106
|
-
}
|
|
107
|
-
} catch {
|
|
108
|
-
}
|
|
109
|
-
} else if (path === CONFIG_PATH && existsSync(LEGACY_CONFIG_PATH)) {
|
|
110
|
-
file = migrateLegacyConfig() ?? {};
|
|
111
|
-
}
|
|
112
|
-
const profile = resolveProfileName(opts.profile, void 0);
|
|
113
|
-
const keychainKey = tryLoadKeyFromKeychain(profile);
|
|
114
|
-
if (keychainKey) {
|
|
115
|
-
file = { ...file, apiKey: keychainKey };
|
|
116
|
-
}
|
|
117
|
-
const endpointFromEnv = process.env["MUSHI_API_ENDPOINT"]?.trim() || process.env["MUSHI_ENDPOINT"]?.trim() || void 0;
|
|
118
|
-
const fromEnv = {
|
|
119
|
-
...process.env["MUSHI_API_KEY"] ? { apiKey: process.env["MUSHI_API_KEY"] } : {},
|
|
120
|
-
...process.env["MUSHI_PROJECT_ID"] ? { projectId: process.env["MUSHI_PROJECT_ID"] } : {},
|
|
121
|
-
// Saved endpoints are normalized by assertEndpoint; the env value isn't,
|
|
122
|
-
// so strip trailing slashes here (no `.../api//v1/...` in any caller).
|
|
123
|
-
...endpointFromEnv ? { endpoint: normalizeEndpoint(endpointFromEnv) } : {},
|
|
124
|
-
...process.env["MUSHI_CONSOLE_URL"] ? { consoleUrl: process.env["MUSHI_CONSOLE_URL"].trim() } : {}
|
|
125
|
-
};
|
|
126
|
-
return { ...file, ...fromEnv };
|
|
127
|
-
}
|
|
128
|
-
function peekConfig(path = CONFIG_PATH) {
|
|
129
|
-
let file = {};
|
|
130
|
-
try {
|
|
131
|
-
const parsed = JSON.parse(readFileSync(path, "utf-8"));
|
|
132
|
-
if (isMultiProfileFile(parsed)) {
|
|
133
|
-
file = parsed.profiles[resolveProfileName(void 0, parsed.activeProfile)] ?? {};
|
|
134
|
-
} else if (resolveProfileName(void 0, void 0) === DEFAULT_PROFILE) {
|
|
135
|
-
file = parsed ?? {};
|
|
136
|
-
}
|
|
137
|
-
} catch {
|
|
138
|
-
}
|
|
139
|
-
const endpointFromEnv = process.env["MUSHI_API_ENDPOINT"]?.trim() || process.env["MUSHI_ENDPOINT"]?.trim() || void 0;
|
|
140
|
-
return {
|
|
141
|
-
...file,
|
|
142
|
-
...process.env["MUSHI_API_KEY"] ? { apiKey: process.env["MUSHI_API_KEY"] } : {},
|
|
143
|
-
...process.env["MUSHI_PROJECT_ID"] ? { projectId: process.env["MUSHI_PROJECT_ID"] } : {},
|
|
144
|
-
...endpointFromEnv ? { endpoint: normalizeEndpoint(endpointFromEnv) } : {}
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
function ensureClientId(path = CONFIG_PATH) {
|
|
148
|
-
const existing = loadConfig(path);
|
|
149
|
-
if (existing.clientId && /^[A-Za-z0-9_-]{8,64}$/.test(existing.clientId)) {
|
|
150
|
-
return existing.clientId;
|
|
151
|
-
}
|
|
152
|
-
const clientId = `cli_${randomUUID().replace(/-/g, "")}`;
|
|
153
|
-
try {
|
|
154
|
-
saveConfig({ ...existing, clientId }, path);
|
|
155
|
-
} catch {
|
|
156
|
-
}
|
|
157
|
-
return clientId;
|
|
158
|
-
}
|
|
159
|
-
function maybeShowTelemetryNotice(config, path = CONFIG_PATH) {
|
|
160
|
-
if (config.telemetryNoticeShown) return;
|
|
161
|
-
if (process.env.MUSHI_NO_TELEMETRY) {
|
|
162
|
-
saveConfig({ ...config, telemetryNoticeShown: true }, path);
|
|
163
|
-
return;
|
|
164
|
-
}
|
|
165
|
-
console.log("");
|
|
166
|
-
console.log(" \u{1F4CA} Mushi collects minimal anonymous usage data to improve the CLI");
|
|
167
|
-
console.log(" (funnel step + error category \u2014 never your code or bug content).");
|
|
168
|
-
console.log(" To opt out: export MUSHI_NO_TELEMETRY=1");
|
|
169
|
-
console.log("");
|
|
170
|
-
saveConfig({ ...config, telemetryNoticeShown: true }, path);
|
|
171
|
-
}
|
|
172
|
-
function saveConfig(config, path = CONFIG_PATH, opts = {}) {
|
|
173
|
-
const dir = dirname(path);
|
|
174
|
-
if (!existsSync(dir)) {
|
|
175
|
-
mkdirSync(dir, { recursive: true, mode: SECURE_DIR_MODE });
|
|
176
|
-
} else {
|
|
177
|
-
tightenDirPermissions(dir);
|
|
178
|
-
}
|
|
179
|
-
let existing = null;
|
|
180
|
-
try {
|
|
181
|
-
existing = JSON.parse(readFileSync(path, "utf-8"));
|
|
182
|
-
} catch {
|
|
183
|
-
existing = null;
|
|
184
|
-
}
|
|
185
|
-
const wantsProfile = opts.profile !== void 0 || process.env["MUSHI_PROFILE"] !== void 0 || isMultiProfileFile(existing);
|
|
186
|
-
if (!wantsProfile) {
|
|
187
|
-
writeFileSync(path, JSON.stringify(config, null, 2), { mode: SECURE_FILE_MODE });
|
|
188
|
-
tightenPermissions(path);
|
|
189
|
-
return;
|
|
190
|
-
}
|
|
191
|
-
const file = isMultiProfileFile(existing) ? { version: 2, activeProfile: existing.activeProfile || DEFAULT_PROFILE, profiles: { ...existing.profiles } } : {
|
|
192
|
-
version: 2,
|
|
193
|
-
activeProfile: DEFAULT_PROFILE,
|
|
194
|
-
// A pre-existing flat file becomes the default profile.
|
|
195
|
-
profiles: { [DEFAULT_PROFILE]: existing ?? {} }
|
|
196
|
-
};
|
|
197
|
-
const target = resolveProfileName(opts.profile, file.activeProfile);
|
|
198
|
-
file.profiles[target] = config;
|
|
199
|
-
writeFileSync(path, JSON.stringify(file, null, 2), { mode: SECURE_FILE_MODE });
|
|
200
|
-
tightenPermissions(path);
|
|
201
|
-
}
|
|
202
|
-
function migrateLegacyConfig(legacyPath = LEGACY_CONFIG_PATH, destPath = CONFIG_PATH) {
|
|
203
|
-
if (!existsSync(legacyPath)) return null;
|
|
204
|
-
let parsed;
|
|
205
|
-
try {
|
|
206
|
-
parsed = JSON.parse(readFileSync(legacyPath, "utf-8"));
|
|
207
|
-
} catch {
|
|
208
|
-
return null;
|
|
209
|
-
}
|
|
210
|
-
const dir = dirname(destPath);
|
|
211
|
-
if (!existsSync(dir)) {
|
|
212
|
-
mkdirSync(dir, { recursive: true, mode: SECURE_DIR_MODE });
|
|
213
|
-
}
|
|
214
|
-
try {
|
|
215
|
-
renameSync(legacyPath, destPath);
|
|
216
|
-
} catch {
|
|
217
|
-
writeFileSync(destPath, JSON.stringify(parsed, null, 2), { mode: SECURE_FILE_MODE });
|
|
218
|
-
try {
|
|
219
|
-
unlinkSync(legacyPath);
|
|
220
|
-
} catch {
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
tightenPermissions(destPath);
|
|
224
|
-
tightenDirPermissions(dir);
|
|
225
|
-
return parsed;
|
|
226
|
-
}
|
|
227
|
-
function tightenPermissions(path) {
|
|
228
|
-
if (process.platform === "win32") {
|
|
229
|
-
tightenWindowsAcl(path, "file");
|
|
230
|
-
return;
|
|
231
|
-
}
|
|
232
|
-
try {
|
|
233
|
-
const current = statSync(path).mode & 511;
|
|
234
|
-
if (current !== SECURE_FILE_MODE) chmodSync(path, SECURE_FILE_MODE);
|
|
235
|
-
} catch {
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
function tightenDirPermissions(path) {
|
|
239
|
-
if (process.platform === "win32") {
|
|
240
|
-
tightenWindowsAcl(path, "dir");
|
|
241
|
-
return;
|
|
242
|
-
}
|
|
243
|
-
try {
|
|
244
|
-
const current = statSync(path).mode & 511;
|
|
245
|
-
if (current !== SECURE_DIR_MODE) chmodSync(path, SECURE_DIR_MODE);
|
|
246
|
-
} catch {
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
var _cachedWindowsUser = void 0;
|
|
250
|
-
var _aclTightened = /* @__PURE__ */ new Set();
|
|
251
|
-
function getWindowsUser() {
|
|
252
|
-
if (_cachedWindowsUser !== void 0) return _cachedWindowsUser;
|
|
253
|
-
try {
|
|
254
|
-
const result = spawnSync("whoami", [], { encoding: "utf8", timeout: 500 });
|
|
255
|
-
_cachedWindowsUser = result.stdout?.trim() || null;
|
|
256
|
-
} catch {
|
|
257
|
-
_cachedWindowsUser = null;
|
|
258
|
-
}
|
|
259
|
-
return _cachedWindowsUser;
|
|
260
|
-
}
|
|
261
|
-
function tightenWindowsAcl(path, type) {
|
|
262
|
-
if (_aclTightened.has(path)) return;
|
|
263
|
-
try {
|
|
264
|
-
const user = getWindowsUser();
|
|
265
|
-
if (!user) return;
|
|
266
|
-
const args = [path, "/inheritance:r", `/grant:r`, `${user}:F`, `SYSTEM:F`];
|
|
267
|
-
if (type === "dir") args.push("/T");
|
|
268
|
-
spawnSync("icacls", args, { encoding: "utf8", timeout: 1e3 });
|
|
269
|
-
_aclTightened.add(path);
|
|
270
|
-
} catch {
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// src/key-scopes.ts
|
|
275
|
-
var SDK_KEY_SCOPES = ["report:write"];
|
|
276
|
-
var CLI_KEY_SCOPES = ["report:write", "mcp:read"];
|
|
277
|
-
function editorKeyCommand(projectId) {
|
|
278
|
-
return `npx mushi-mushi login${projectId ? ` --project-id ${projectId}` : ""}`;
|
|
279
|
-
}
|
|
280
|
-
var SDK_KEY_LABEL = "sdk-ingest";
|
|
281
|
-
var CLI_KEY_LABEL = "cli-login";
|
|
282
|
-
async function probeKeyScope(endpoint, apiKey, projectId, doFetch = globalThis.fetch) {
|
|
283
|
-
let base = endpoint;
|
|
284
|
-
while (base.endsWith("/")) base = base.slice(0, -1);
|
|
285
|
-
let res;
|
|
286
|
-
try {
|
|
287
|
-
res = await doFetch(`${base}/v1/admin/mcp/account-overview`, {
|
|
288
|
-
headers: { "X-Mushi-Api-Key": apiKey, "X-Mushi-Project": projectId },
|
|
289
|
-
signal: AbortSignal.timeout(8e3)
|
|
290
|
-
});
|
|
291
|
-
} catch (err) {
|
|
292
|
-
return { result: "unreachable", message: err instanceof Error ? err.message : String(err) };
|
|
293
|
-
}
|
|
294
|
-
if (res.ok) return { result: "mcp", status: res.status };
|
|
295
|
-
if (res.status === 401) return { result: "invalid", status: res.status };
|
|
296
|
-
if (res.status === 403) {
|
|
297
|
-
const body = await res.json().catch(() => null);
|
|
298
|
-
const code = body?.error?.code ?? body?.code;
|
|
299
|
-
if (code === "INSUFFICIENT_SCOPE") return { result: "ingest-only", status: res.status };
|
|
300
|
-
}
|
|
301
|
-
return { result: "unknown", status: res.status };
|
|
302
|
-
}
|
|
303
|
-
function describeUnsafeSdkKey(probe, endpoint) {
|
|
304
|
-
switch (probe.result) {
|
|
305
|
-
case "mcp":
|
|
306
|
-
return "this key can read your bug reports (mcp scope), and SDK env vars ship inside the app bundle";
|
|
307
|
-
case "invalid":
|
|
308
|
-
return "the backend rejected this key";
|
|
309
|
-
case "unreachable":
|
|
310
|
-
return `could not reach ${endpoint} to confirm the key is ingest-only (${probe.message ?? "network error"})`;
|
|
311
|
-
case "unknown":
|
|
312
|
-
return `could not confirm the key is ingest-only (HTTP ${probe.status ?? "?"})`;
|
|
313
|
-
case "ingest-only":
|
|
314
|
-
return "the key is ingest-only";
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
// src/console-url.ts
|
|
319
|
-
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
320
|
-
import { dirname as dirname2, join as join2 } from "path";
|
|
321
|
-
var HOSTED_CONSOLE_BASE = `${resolvePublicOrigin()}/mushi-mushi/admin`;
|
|
322
|
-
var LOCAL_ADMIN_URL = "http://localhost:6464";
|
|
323
|
-
var LOCAL_PROBE_MS = 800;
|
|
324
|
-
function normalizeConsoleBase(url) {
|
|
325
|
-
const trimmed = url.trim();
|
|
326
|
-
let end = trimmed.length;
|
|
327
|
-
while (end > 0 && trimmed.charCodeAt(end - 1) === 47) end--;
|
|
328
|
-
return trimmed.slice(0, end);
|
|
329
|
-
}
|
|
330
|
-
function consoleUrl(base, route) {
|
|
331
|
-
const normalizedRoute = route.startsWith("/") ? route : `/${route}`;
|
|
332
|
-
return `${normalizeConsoleBase(base)}${normalizedRoute}`;
|
|
333
|
-
}
|
|
334
|
-
function resolveConsoleUrlFromEnv() {
|
|
335
|
-
const raw = process.env["MUSHI_CONSOLE_URL"]?.trim();
|
|
336
|
-
return raw ? normalizeConsoleBase(raw) : void 0;
|
|
337
|
-
}
|
|
338
|
-
function isInsideMushiMonorepo(cwd) {
|
|
339
|
-
let dir = cwd;
|
|
340
|
-
for (let depth = 0; depth < 14; depth += 1) {
|
|
341
|
-
const pkgPath = join2(dir, "package.json");
|
|
342
|
-
if (existsSync2(pkgPath)) {
|
|
343
|
-
try {
|
|
344
|
-
const pkg = JSON.parse(readFileSync2(pkgPath, "utf-8"));
|
|
345
|
-
if (pkg.name === "mushi-mushi") return true;
|
|
346
|
-
} catch {
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
const parent = dirname2(dir);
|
|
350
|
-
if (parent === dir) break;
|
|
351
|
-
dir = parent;
|
|
352
|
-
}
|
|
353
|
-
return false;
|
|
354
|
-
}
|
|
355
|
-
async function probeLocalAdminConsole() {
|
|
356
|
-
try {
|
|
357
|
-
const controller = new AbortController();
|
|
358
|
-
const timer = setTimeout(() => controller.abort(), LOCAL_PROBE_MS);
|
|
359
|
-
const res = await fetch(LOCAL_ADMIN_URL, {
|
|
360
|
-
signal: controller.signal,
|
|
361
|
-
method: "HEAD"
|
|
362
|
-
});
|
|
363
|
-
clearTimeout(timer);
|
|
364
|
-
if (res.ok || res.status === 404 || res.status === 401) {
|
|
365
|
-
return LOCAL_ADMIN_URL;
|
|
366
|
-
}
|
|
367
|
-
} catch {
|
|
368
|
-
}
|
|
369
|
-
return null;
|
|
370
|
-
}
|
|
371
|
-
function resolveConsoleUrlSync(cwd = process.cwd()) {
|
|
372
|
-
const fromEnv = resolveConsoleUrlFromEnv();
|
|
373
|
-
if (fromEnv) return fromEnv;
|
|
374
|
-
const config = loadConfig();
|
|
375
|
-
if (config.consoleUrl) return normalizeConsoleBase(config.consoleUrl);
|
|
376
|
-
if (isInsideMushiMonorepo(cwd)) return LOCAL_ADMIN_URL;
|
|
377
|
-
return HOSTED_CONSOLE_BASE;
|
|
378
|
-
}
|
|
379
|
-
async function resolveConsoleUrl(options) {
|
|
380
|
-
const fromEnv = resolveConsoleUrlFromEnv();
|
|
381
|
-
if (fromEnv) return fromEnv;
|
|
382
|
-
const config = loadConfig();
|
|
383
|
-
if (config.consoleUrl) return normalizeConsoleBase(config.consoleUrl);
|
|
384
|
-
const local = await probeLocalAdminConsole();
|
|
385
|
-
if (local) return local;
|
|
386
|
-
const cwd = options?.cwd ?? process.cwd();
|
|
387
|
-
if (isInsideMushiMonorepo(cwd)) return LOCAL_ADMIN_URL;
|
|
388
|
-
return HOSTED_CONSOLE_BASE;
|
|
389
|
-
}
|
|
390
|
-
function projectIdHint(base) {
|
|
391
|
-
return `Where to find it: ${consoleUrl(base, "/projects")} \u2192 select your project \u2192 click the UUID chip to copy (or copy it from the panel right after you create the project).`;
|
|
392
|
-
}
|
|
393
|
-
function apiKeyHint(base) {
|
|
394
|
-
return `Where to find it: ${consoleUrl(base, "/onboarding?tab=verify")} \u2192 Generate API key (SDK ingest needs report:write \u2014 not Settings \u2192 BYOK keys). Treat it like a password \u2014 env file only, never commit.`;
|
|
395
|
-
}
|
|
396
|
-
function cliSetupDeepLink(base) {
|
|
397
|
-
return consoleUrl(base, "/onboarding?tab=steps&setup=cli");
|
|
398
|
-
}
|
|
399
|
-
function reportsUrl(base, reportId) {
|
|
400
|
-
return reportId ? consoleUrl(base, `/reports/${reportId}`) : consoleUrl(base, "/reports");
|
|
401
|
-
}
|
|
402
|
-
async function openInBrowser(url) {
|
|
403
|
-
let parsed;
|
|
404
|
-
try {
|
|
405
|
-
parsed = new URL(url);
|
|
406
|
-
} catch {
|
|
407
|
-
return;
|
|
408
|
-
}
|
|
409
|
-
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
410
|
-
return;
|
|
411
|
-
}
|
|
412
|
-
const safeUrl = parsed.toString();
|
|
413
|
-
const { spawn } = await import("child_process");
|
|
414
|
-
const [command, args] = process.platform === "win32" ? (
|
|
415
|
-
// Open via rundll32's FileProtocolHandler rather than `cmd /c start`.
|
|
416
|
-
// `start` is a cmd builtin, so the URL would be re-parsed by cmd.exe and
|
|
417
|
-
// characters like `&` / `|` / `^` could still break out — exactly the
|
|
418
|
-
// injection surface CodeQL flags. rundll32 never invokes a shell: the URL
|
|
419
|
-
// is handed to the default browser as one opaque argument.
|
|
420
|
-
["rundll32", ["url.dll,FileProtocolHandler", safeUrl]]
|
|
421
|
-
) : process.platform === "darwin" ? ["open", [safeUrl]] : ["xdg-open", [safeUrl]];
|
|
422
|
-
await new Promise((resolve) => {
|
|
423
|
-
try {
|
|
424
|
-
const child = spawn(command, [...args], { stdio: "ignore", shell: false, detached: process.platform !== "win32" });
|
|
425
|
-
child.once("spawn", () => resolve());
|
|
426
|
-
child.once("error", () => resolve());
|
|
427
|
-
child.unref();
|
|
428
|
-
} catch {
|
|
429
|
-
resolve();
|
|
430
|
-
}
|
|
431
|
-
});
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
// src/errors.ts
|
|
435
|
-
var EXIT_CODE_MAP = {
|
|
436
|
-
E_AUTH_MISSING: 2,
|
|
437
|
-
E_AUTH_INVALID: 2,
|
|
438
|
-
E_PROJECT_MISSING: 2,
|
|
439
|
-
E_ENDPOINT_INVALID: 2,
|
|
440
|
-
E_INVALID_INPUT: 2,
|
|
441
|
-
E_WRONG_REPO: 2,
|
|
442
|
-
E_NOT_INTERACTIVE: 2,
|
|
443
|
-
E_NETWORK: 3,
|
|
444
|
-
E_TIMEOUT: 3,
|
|
445
|
-
E_API_ERROR: 3,
|
|
446
|
-
E_RATE_LIMITED: 3,
|
|
447
|
-
E_FILE_NOT_FOUND: 1,
|
|
448
|
-
E_FILE_PERMISSION: 1,
|
|
449
|
-
E_FRESHNESS_STALE: 1,
|
|
450
|
-
E_INTERRUPTED: 130,
|
|
451
|
-
// 128 + SIGINT (2). POSIX convention.
|
|
452
|
-
E_INTERNAL: 1
|
|
453
|
-
};
|
|
454
|
-
var MushiCliError = class extends Error {
|
|
455
|
-
code;
|
|
456
|
-
hint;
|
|
457
|
-
cause;
|
|
458
|
-
constructor(code, message, hint, cause) {
|
|
459
|
-
super(message);
|
|
460
|
-
this.name = "MushiCliError";
|
|
461
|
-
this.code = code;
|
|
462
|
-
if (hint) this.hint = hint;
|
|
463
|
-
if (cause !== void 0) this.cause = cause;
|
|
464
|
-
}
|
|
465
|
-
/** Exit code POSIX-aware shell scripts should branch on. */
|
|
466
|
-
get exitCode() {
|
|
467
|
-
return EXIT_CODE_MAP[this.code];
|
|
468
|
-
}
|
|
469
|
-
/**
|
|
470
|
-
* Format for `--json` output. Used by the JSON writer when a CLI
|
|
471
|
-
* subcommand was invoked with `--json` and an error escapes.
|
|
472
|
-
*/
|
|
473
|
-
toJSON() {
|
|
474
|
-
return {
|
|
475
|
-
error: {
|
|
476
|
-
code: this.code,
|
|
477
|
-
message: this.message,
|
|
478
|
-
...this.hint ? { hint: this.hint } : {}
|
|
479
|
-
}
|
|
480
|
-
};
|
|
481
|
-
}
|
|
482
|
-
};
|
|
483
|
-
|
|
484
|
-
// src/signals.ts
|
|
485
|
-
var activeController = null;
|
|
486
|
-
function getAbortSignal(external) {
|
|
487
|
-
if (external) return external.signal;
|
|
488
|
-
if (!activeController || activeController.signal.aborted) {
|
|
489
|
-
activeController = new AbortController();
|
|
490
|
-
}
|
|
491
|
-
return activeController.signal;
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
// src/cli-shared.ts
|
|
495
|
-
var UUID_RX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
496
|
-
function requireUuid(value, label = "id") {
|
|
497
|
-
if (UUID_RX.test(value)) return value;
|
|
498
|
-
throw new MushiCliError(
|
|
499
|
-
"E_INVALID_INPUT",
|
|
500
|
-
`${label} must be a valid UUID`,
|
|
501
|
-
"copy the full id from `mushi reports list` or the console URL"
|
|
502
|
-
);
|
|
503
|
-
}
|
|
504
|
-
var API_TIMEOUT_MS = 15e3;
|
|
505
|
-
function normalizeApiError(error, httpStatus) {
|
|
506
|
-
const fallbackCode = httpStatus ? `HTTP_${httpStatus}` : "API_ERROR";
|
|
507
|
-
if (typeof error === "string") return { code: fallbackCode, message: error };
|
|
508
|
-
if (error && typeof error === "object") {
|
|
509
|
-
const e = error;
|
|
510
|
-
if (typeof e["code"] === "string" && typeof e["message"] === "string") {
|
|
511
|
-
return e;
|
|
512
|
-
}
|
|
513
|
-
const formErrors = Array.isArray(e["formErrors"]) ? e["formErrors"].map(String) : [];
|
|
514
|
-
const fieldErrors = e["fieldErrors"] && typeof e["fieldErrors"] === "object" ? Object.entries(e["fieldErrors"]).map(
|
|
515
|
-
([field, msgs]) => `${field}: ${Array.isArray(msgs) ? msgs.join(", ") : String(msgs)}`
|
|
516
|
-
) : [];
|
|
517
|
-
const parts = [...formErrors, ...fieldErrors];
|
|
518
|
-
if (parts.length > 0) return { code: "VALIDATION_ERROR", message: parts.join("; ") };
|
|
519
|
-
return {
|
|
520
|
-
...e,
|
|
521
|
-
code: typeof e["code"] === "string" ? e["code"] : fallbackCode,
|
|
522
|
-
message: typeof e["message"] === "string" ? e["message"] : `Request failed${httpStatus ? ` (${httpStatus})` : ""}`
|
|
523
|
-
};
|
|
524
|
-
}
|
|
525
|
-
return { code: fallbackCode, message: `Request failed${httpStatus ? ` (${httpStatus})` : ""}` };
|
|
526
|
-
}
|
|
527
|
-
async function apiCall(path, config, options = {}, callOptions = {}) {
|
|
528
|
-
const timeoutMs = callOptions.timeoutMs ?? API_TIMEOUT_MS;
|
|
529
|
-
const endpoint = config.endpoint ? normalizeEndpoint(config.endpoint) : config.endpoint;
|
|
530
|
-
if (!endpoint) {
|
|
531
|
-
return {
|
|
532
|
-
ok: false,
|
|
533
|
-
error: {
|
|
534
|
-
code: "NO_ENDPOINT",
|
|
535
|
-
message: "No API endpoint configured.\n Run: mushi login --api-key <key> --endpoint <url> --project-id <id>\n Or: export MUSHI_API_ENDPOINT=https://<project-ref>.supabase.co/functions/v1/api"
|
|
536
|
-
}
|
|
537
|
-
};
|
|
538
|
-
}
|
|
539
|
-
const controller = new AbortController();
|
|
540
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
541
|
-
const signals = [controller.signal, getAbortSignal()];
|
|
542
|
-
const compositeSignal = AbortSignal.any ? AbortSignal.any(signals) : controller.signal;
|
|
543
|
-
try {
|
|
544
|
-
const res = await fetch(`${endpoint}${path}`, {
|
|
545
|
-
...options,
|
|
546
|
-
signal: compositeSignal,
|
|
547
|
-
headers: {
|
|
548
|
-
"Content-Type": "application/json",
|
|
549
|
-
// `apiKeyAuth` reads X-Mushi-Api-Key; the Authorization header is a
|
|
550
|
-
// fallback accepted by some older middleware. Both are sent.
|
|
551
|
-
"Authorization": `Bearer ${config.apiKey ?? ""}`,
|
|
552
|
-
"X-Mushi-Api-Key": config.apiKey ?? "",
|
|
553
|
-
"X-Mushi-Project": config.projectId ?? "",
|
|
554
|
-
"X-Mushi-Cli-Version": MUSHI_CLI_VERSION,
|
|
555
|
-
...options.headers
|
|
556
|
-
}
|
|
557
|
-
});
|
|
558
|
-
clearTimeout(timer);
|
|
559
|
-
let body;
|
|
560
|
-
const contentType = res.headers.get("content-type") ?? "";
|
|
561
|
-
if (contentType.includes("application/json")) {
|
|
562
|
-
try {
|
|
563
|
-
body = await res.json();
|
|
564
|
-
} catch {
|
|
565
|
-
body = null;
|
|
566
|
-
}
|
|
567
|
-
} else {
|
|
568
|
-
const text = await res.text();
|
|
569
|
-
if (callOptions.text && res.ok) return { ok: true, data: text };
|
|
570
|
-
try {
|
|
571
|
-
body = JSON.parse(text);
|
|
572
|
-
} catch {
|
|
573
|
-
body = {
|
|
574
|
-
ok: false,
|
|
575
|
-
error: {
|
|
576
|
-
code: `HTTP_${res.status}`,
|
|
577
|
-
message: text.trim().slice(0, 300) || `HTTP ${res.status}`
|
|
578
|
-
}
|
|
579
|
-
};
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
if (!res.ok && typeof body === "object" && body !== null && !("ok" in body)) {
|
|
583
|
-
const b = body;
|
|
584
|
-
const nested = b["error"];
|
|
585
|
-
const errCode = nested?.["code"] ?? b["code"] ?? `HTTP_${res.status}`;
|
|
586
|
-
const errMsg = nested?.["message"] ?? b["message"] ?? `Request failed (${res.status})`;
|
|
587
|
-
return {
|
|
588
|
-
ok: false,
|
|
589
|
-
httpStatus: res.status,
|
|
590
|
-
error: { code: errCode, message: errMsg }
|
|
591
|
-
};
|
|
592
|
-
}
|
|
593
|
-
if (typeof body === "object" && body !== null && body.ok === false) {
|
|
594
|
-
return {
|
|
595
|
-
ok: false,
|
|
596
|
-
httpStatus: res.status,
|
|
597
|
-
error: normalizeApiError(body.error, res.status)
|
|
598
|
-
};
|
|
599
|
-
}
|
|
600
|
-
return body;
|
|
601
|
-
} catch (err) {
|
|
602
|
-
clearTimeout(timer);
|
|
603
|
-
if (err instanceof Error && err.name === "AbortError") {
|
|
604
|
-
return {
|
|
605
|
-
ok: false,
|
|
606
|
-
error: {
|
|
607
|
-
code: "TIMEOUT",
|
|
608
|
-
message: `Request timed out after ${timeoutMs / 1e3}s. Check your network or endpoint.`
|
|
609
|
-
}
|
|
610
|
-
};
|
|
611
|
-
}
|
|
612
|
-
return {
|
|
613
|
-
ok: false,
|
|
614
|
-
error: {
|
|
615
|
-
code: "NETWORK_ERROR",
|
|
616
|
-
message: err instanceof Error ? err.message : String(err)
|
|
617
|
-
}
|
|
618
|
-
};
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
|
|
622
|
-
// src/sanitize-config.ts
|
|
623
|
-
var PROJECT_ID_RE = /^(?:proj_[A-Za-z0-9_-]{10,}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
|
624
|
-
var API_KEY_RE = /^(mushi_|mush_pk_)[A-Za-z0-9_-]{10,}$/;
|
|
625
|
-
function sanitizeApiKey(raw) {
|
|
626
|
-
const key = raw.replace(/[\r\n\0]/g, "");
|
|
627
|
-
if (!API_KEY_RE.test(key)) {
|
|
628
|
-
throw new Error(
|
|
629
|
-
"Invalid API key in config \u2014 run `mushi login --api-key <key>` to refresh credentials."
|
|
630
|
-
);
|
|
631
|
-
}
|
|
632
|
-
return key;
|
|
633
|
-
}
|
|
634
|
-
function sanitizeProjectId(raw) {
|
|
635
|
-
const id = raw.trim();
|
|
636
|
-
if (!PROJECT_ID_RE.test(id)) {
|
|
637
|
-
throw new Error(
|
|
638
|
-
"Invalid project ID in config \u2014 expected a UUID or proj_* slug from the admin console."
|
|
639
|
-
);
|
|
640
|
-
}
|
|
641
|
-
return id;
|
|
642
|
-
}
|
|
643
|
-
function sanitizeEndpoint(raw) {
|
|
644
|
-
return assertEndpoint(normalizeEndpoint(raw));
|
|
645
|
-
}
|
|
646
|
-
function sanitizeCliCredentials(config) {
|
|
647
|
-
if (!config.endpoint || !config.apiKey || !config.projectId) {
|
|
648
|
-
throw new Error("Missing endpoint, apiKey, or projectId");
|
|
649
|
-
}
|
|
650
|
-
return {
|
|
651
|
-
endpoint: sanitizeEndpoint(config.endpoint),
|
|
652
|
-
apiKey: sanitizeApiKey(config.apiKey),
|
|
653
|
-
projectId: sanitizeProjectId(config.projectId)
|
|
654
|
-
};
|
|
655
|
-
}
|
|
656
|
-
function apiKeyHeaders(apiKey, projectId) {
|
|
657
|
-
const headers = {
|
|
658
|
-
Authorization: `Bearer ${apiKey}`,
|
|
659
|
-
"X-Mushi-Api-Key": apiKey
|
|
660
|
-
};
|
|
661
|
-
if (projectId) headers["X-Mushi-Project"] = projectId;
|
|
662
|
-
return headers;
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
// src/heartbeat-wait.ts
|
|
666
|
-
var IngestSetupHttpError = class extends Error {
|
|
667
|
-
status;
|
|
668
|
-
constructor(status) {
|
|
669
|
-
super(`ingest-setup HTTP ${status}`);
|
|
670
|
-
this.name = "IngestSetupHttpError";
|
|
671
|
-
this.status = status;
|
|
672
|
-
}
|
|
673
|
-
};
|
|
674
|
-
var NON_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([401, 403, 404]);
|
|
675
|
-
async function fetchIngestSetup(config, doFetch = globalThis.fetch) {
|
|
676
|
-
const endpoint = sanitizeEndpoint(config.endpoint);
|
|
677
|
-
const apiKey = sanitizeApiKey(config.apiKey);
|
|
678
|
-
const projectId = config.projectId ? sanitizeProjectId(config.projectId) : void 0;
|
|
679
|
-
const res = await doFetch(`${endpoint}/v1/sync/ingest-setup`, {
|
|
680
|
-
headers: apiKeyHeaders(apiKey, projectId),
|
|
681
|
-
signal: AbortSignal.timeout(8e3)
|
|
682
|
-
});
|
|
683
|
-
if (!res.ok) {
|
|
684
|
-
if (NON_RETRYABLE_STATUSES.has(res.status)) throw new IngestSetupHttpError(res.status);
|
|
685
|
-
return null;
|
|
686
|
-
}
|
|
687
|
-
const body = await res.json();
|
|
688
|
-
return body.ok && body.data ? body.data : null;
|
|
689
|
-
}
|
|
690
|
-
async function waitForIngestReady(options) {
|
|
691
|
-
const doFetch = options.fetch ?? globalThis.fetch;
|
|
692
|
-
const maxAttempts = options.maxAttempts ?? 40;
|
|
693
|
-
const intervalMs = options.intervalMs ?? 3e3;
|
|
694
|
-
let lastPayload = null;
|
|
695
|
-
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
696
|
-
if (options.signal?.aborted) {
|
|
697
|
-
return { ok: false, payload: lastPayload, attempts: attempt - 1, reason: "aborted" };
|
|
698
|
-
}
|
|
699
|
-
try {
|
|
700
|
-
lastPayload = await fetchIngestSetup(
|
|
701
|
-
{ endpoint: options.endpoint, apiKey: options.apiKey, projectId: options.projectId },
|
|
702
|
-
doFetch
|
|
703
|
-
);
|
|
704
|
-
if (lastPayload) {
|
|
705
|
-
options.onPoll?.(lastPayload, attempt);
|
|
706
|
-
if (lastPayload.ready) {
|
|
707
|
-
return { ok: true, payload: lastPayload, attempts: attempt, reason: "ready" };
|
|
708
|
-
}
|
|
709
|
-
const sdkStep = lastPayload.steps.find((s) => s.id === "sdk_installed");
|
|
710
|
-
if (sdkStep?.complete) {
|
|
711
|
-
return { ok: true, payload: lastPayload, attempts: attempt, reason: "heartbeat" };
|
|
712
|
-
}
|
|
713
|
-
}
|
|
714
|
-
} catch (err) {
|
|
715
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
716
|
-
if (err instanceof IngestSetupHttpError) {
|
|
717
|
-
return { ok: false, payload: lastPayload, attempts: attempt, reason: "unauthorized", error: msg };
|
|
718
|
-
}
|
|
719
|
-
if (options.signal?.aborted) {
|
|
720
|
-
return { ok: false, payload: lastPayload, attempts: attempt, reason: "aborted", error: msg };
|
|
721
|
-
}
|
|
722
|
-
if (attempt === maxAttempts) {
|
|
723
|
-
return { ok: false, payload: lastPayload, attempts: attempt, reason: "fetch-error", error: msg };
|
|
724
|
-
}
|
|
725
|
-
}
|
|
726
|
-
if (attempt < maxAttempts) {
|
|
727
|
-
await new Promise((r) => setTimeout(r, intervalMs));
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
return { ok: false, payload: lastPayload, attempts: maxAttempts, reason: "timeout" };
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
export {
|
|
734
|
-
trySaveKeyToKeychain,
|
|
735
|
-
savedSdkKeyFor,
|
|
736
|
-
resolveProfileName,
|
|
737
|
-
CONFIG_PATH,
|
|
738
|
-
loadConfig,
|
|
739
|
-
peekConfig,
|
|
740
|
-
ensureClientId,
|
|
741
|
-
maybeShowTelemetryNotice,
|
|
742
|
-
saveConfig,
|
|
743
|
-
SDK_KEY_SCOPES,
|
|
744
|
-
CLI_KEY_SCOPES,
|
|
745
|
-
editorKeyCommand,
|
|
746
|
-
SDK_KEY_LABEL,
|
|
747
|
-
CLI_KEY_LABEL,
|
|
748
|
-
probeKeyScope,
|
|
749
|
-
describeUnsafeSdkKey,
|
|
750
|
-
consoleUrl,
|
|
751
|
-
resolveConsoleUrlSync,
|
|
752
|
-
resolveConsoleUrl,
|
|
753
|
-
projectIdHint,
|
|
754
|
-
apiKeyHint,
|
|
755
|
-
cliSetupDeepLink,
|
|
756
|
-
reportsUrl,
|
|
757
|
-
openInBrowser,
|
|
758
|
-
requireUuid,
|
|
759
|
-
apiCall,
|
|
760
|
-
sanitizeEndpoint,
|
|
761
|
-
sanitizeCliCredentials,
|
|
762
|
-
apiKeyHeaders,
|
|
763
|
-
fetchIngestSetup,
|
|
764
|
-
waitForIngestReady
|
|
765
|
-
};
|