@getchomp/cli 0.0.0-stage → 0.2.43

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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +39 -2
  3. package/dist/commands/analyze.d.ts +49 -0
  4. package/dist/commands/analyze.js +280 -0
  5. package/dist/commands/connect.d.ts +12 -0
  6. package/dist/commands/connect.js +255 -0
  7. package/dist/commands/export.d.ts +29 -0
  8. package/dist/commands/export.js +356 -0
  9. package/dist/commands/health.d.ts +19 -0
  10. package/dist/commands/health.js +259 -0
  11. package/dist/commands/init.d.ts +40 -0
  12. package/dist/commands/init.js +659 -0
  13. package/dist/commands/mcp.d.ts +2 -0
  14. package/dist/commands/mcp.js +12 -0
  15. package/dist/commands/plugin.d.ts +8 -0
  16. package/dist/commands/plugin.js +198 -0
  17. package/dist/commands/ui.d.ts +20 -0
  18. package/dist/commands/ui.js +252 -0
  19. package/dist/commands/uninstall.d.ts +8 -0
  20. package/dist/commands/uninstall.js +246 -0
  21. package/dist/index.d.ts +3 -0
  22. package/dist/index.js +37 -0
  23. package/dist/ports/portHydrator.d.ts +63 -0
  24. package/dist/ports/portHydrator.js +954 -0
  25. package/dist/ports/portHydratorWorker.d.ts +22 -0
  26. package/dist/ports/portHydratorWorker.js +75 -0
  27. package/dist/server/buildStatusTracker.d.ts +45 -0
  28. package/dist/server/buildStatusTracker.js +122 -0
  29. package/dist/server/graphLayoutState.d.ts +205 -0
  30. package/dist/server/graphLayoutState.js +930 -0
  31. package/dist/server/loopbackSecurity.d.ts +18 -0
  32. package/dist/server/loopbackSecurity.js +57 -0
  33. package/dist/server/routes/authSourceRoutes.d.ts +18 -0
  34. package/dist/server/routes/authSourceRoutes.js +231 -0
  35. package/dist/server/routes/layoutRoutes.d.ts +3 -0
  36. package/dist/server/routes/layoutRoutes.js +857 -0
  37. package/dist/server/routes/pluginRoutes.d.ts +3 -0
  38. package/dist/server/routes/pluginRoutes.js +368 -0
  39. package/dist/server/routes/viewRulesRoutes.d.ts +3 -0
  40. package/dist/server/routes/viewRulesRoutes.js +173 -0
  41. package/dist/server/uiHotkeys.d.ts +26 -0
  42. package/dist/server/uiHotkeys.js +160 -0
  43. package/dist/utils/branding.d.ts +126 -0
  44. package/dist/utils/branding.js +978 -0
  45. package/dist/utils/credentials.d.ts +22 -0
  46. package/dist/utils/credentials.js +126 -0
  47. package/dist/utils/git.d.ts +95 -0
  48. package/dist/utils/git.js +780 -0
  49. package/dist/utils/masterContext.d.ts +112 -0
  50. package/dist/utils/masterContext.js +642 -0
  51. package/dist/visualizer/cloudLayoutClient.d.ts +84 -0
  52. package/dist/visualizer/cloudLayoutClient.js +1200 -0
  53. package/dist/visualizer/layoutCache.d.ts +25 -0
  54. package/dist/visualizer/layoutCache.js +406 -0
  55. package/dist/visualizer/localEngineBridge.d.ts +50 -0
  56. package/dist/visualizer/localEngineBridge.js +80 -0
  57. package/dist/visualizer/pluginPresentationApi.d.ts +111 -0
  58. package/dist/visualizer/pluginPresentationApi.js +432 -0
  59. package/dist/visualizer/rulesConfig.d.ts +11 -0
  60. package/dist/visualizer/rulesConfig.js +266 -0
  61. package/dist/visualizer/sourceAccess.d.ts +45 -0
  62. package/dist/visualizer/sourceAccess.js +204 -0
  63. package/package.json +52 -3
@@ -0,0 +1,18 @@
1
+ import { type Express } from "express";
2
+ /**
3
+ * Validates that the HTTP `Host` header targets a loopback interface (`localhost`, `127.0.0.1`, `[::1]`),
4
+ * blocking DNS rebinding attacks against the local Visualizer server.
5
+ */
6
+ export declare function isLoopbackHostHeader(hostHeader: string | undefined): boolean;
7
+ /**
8
+ * Validates that the HTTP `Origin` header (when present) originates from a local loopback port
9
+ * (`http://localhost:3000`, `http://127.0.0.1:5555`, etc.) or the official hosted Cloudflare Visualizer
10
+ * (`https://app.getchomp.dev`), blocking cross-origin requests from arbitrary external websites.
11
+ */
12
+ export declare function isAllowedLocalhostOrigin(originHeader: string | undefined): boolean;
13
+ /**
14
+ * Installs loopback `Host` & `Origin` validation, Chrome/Edge Private Network Access
15
+ * preflight headers (`Access-Control-Allow-Private-Network: true`), localhost/hosted CORS,
16
+ * and JSON body parsing onto the local Express daemon.
17
+ */
18
+ export declare function registerLoopbackSecurityMiddleware(app: Express): void;
@@ -0,0 +1,57 @@
1
+ import cors from "cors";
2
+ import express from "express";
3
+ const LOOPBACK_HOST_RE = /^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/i;
4
+ const LOCALHOST_ORIGIN_RE = /^https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/i;
5
+ const HOSTED_CHOMP_ORIGIN_RE = /^https:\/\/(?:(?:[a-z0-9-]+\.)*getchomp\.dev|(?:[a-z0-9-]+\.)*chomp-visualizer\.pages\.dev)$/i;
6
+ /**
7
+ * Validates that the HTTP `Host` header targets a loopback interface (`localhost`, `127.0.0.1`, `[::1]`),
8
+ * blocking DNS rebinding attacks against the local Visualizer server.
9
+ */
10
+ export function isLoopbackHostHeader(hostHeader) {
11
+ if (!hostHeader || typeof hostHeader !== "string")
12
+ return false;
13
+ return LOOPBACK_HOST_RE.test(hostHeader.trim());
14
+ }
15
+ /**
16
+ * Validates that the HTTP `Origin` header (when present) originates from a local loopback port
17
+ * (`http://localhost:3000`, `http://127.0.0.1:5555`, etc.) or the official hosted Cloudflare Visualizer
18
+ * (`https://app.getchomp.dev`), blocking cross-origin requests from arbitrary external websites.
19
+ */
20
+ export function isAllowedLocalhostOrigin(originHeader) {
21
+ if (!originHeader)
22
+ return true;
23
+ const trimmed = originHeader.trim();
24
+ return LOCALHOST_ORIGIN_RE.test(trimmed) || HOSTED_CHOMP_ORIGIN_RE.test(trimmed);
25
+ }
26
+ /**
27
+ * Installs loopback `Host` & `Origin` validation, Chrome/Edge Private Network Access
28
+ * preflight headers (`Access-Control-Allow-Private-Network: true`), localhost/hosted CORS,
29
+ * and JSON body parsing onto the local Express daemon.
30
+ */
31
+ export function registerLoopbackSecurityMiddleware(app) {
32
+ app.use((req, res, next) => {
33
+ if (!isLoopbackHostHeader(req.headers.host)) {
34
+ return res.status(403).json({ error: "Forbidden: non-loopback Host header" });
35
+ }
36
+ const originHeader = typeof req.headers.origin === "string" ? req.headers.origin : undefined;
37
+ if (!isAllowedLocalhostOrigin(originHeader)) {
38
+ return res.status(403).json({ error: "Forbidden: non-localhost Origin header" });
39
+ }
40
+ // Support Chrome/Edge Private Network Access preflights (`https://app.getchomp.dev` -> `http://127.0.0.1:5555`)
41
+ if (req.headers["access-control-request-private-network"] === "true") {
42
+ res.setHeader("Access-Control-Allow-Private-Network", "true");
43
+ }
44
+ return next();
45
+ });
46
+ app.use(cors({
47
+ origin: (origin, callback) => {
48
+ if (!origin || isAllowedLocalhostOrigin(origin)) {
49
+ callback(null, true);
50
+ }
51
+ else {
52
+ callback(new Error("Not allowed by Chomp localhost CORS policy"));
53
+ }
54
+ },
55
+ }));
56
+ app.use(express.json({ limit: "15mb" }));
57
+ }
@@ -0,0 +1,18 @@
1
+ import type { Express } from "express";
2
+ import { type UiServerState } from "../graphLayoutState.js";
3
+ export declare function resolveSafeAuthReturnUrl(state: UiServerState, rawReturnTo: string | undefined, cleanHandle?: string): string;
4
+ export declare function buildAuthStatusPayload(state: UiServerState): {
5
+ entitlement?: import("@getchomp/core").LayoutEntitlement | undefined;
6
+ mode: "master" | "cloud";
7
+ cloudApiUrl: string;
8
+ port: number;
9
+ updatedAt?: string | undefined;
10
+ tokenExpired: boolean;
11
+ expiresAt?: string | undefined;
12
+ claimedTier?: string | undefined;
13
+ githubHandle?: string | undefined;
14
+ authenticated: boolean;
15
+ hasToken: boolean;
16
+ hasApiKey: boolean;
17
+ };
18
+ export declare function registerAuthAndSourceRoutes(app: Express, state: UiServerState): void;
@@ -0,0 +1,231 @@
1
+ import { clearChompCredentials, decodeJwtPayloadUnsafe, loadChompCredentials, resolveActiveBearerToken, saveChompCredentials, } from "../../utils/credentials.js";
2
+ import { getGitInfoAsync } from "../../utils/git.js";
3
+ import { DEFAULT_HOSTED_UI_URL } from "../../visualizer/localEngineBridge.js";
4
+ import { openInLocalEditor, readSingleSourceLine, } from "../../visualizer/sourceAccess.js";
5
+ import { getActiveUiTarget, invalidateAuthCachesOnly, loadBaseGraphCached, } from "../graphLayoutState.js";
6
+ import { isAllowedLocalhostOrigin } from "../loopbackSecurity.js";
7
+ export function resolveSafeAuthReturnUrl(state, rawReturnTo, cleanHandle) {
8
+ let baseTarget = state.url;
9
+ if (!state.isMasterLocalMode &&
10
+ baseTarget === state.localDaemonUrl &&
11
+ !state.localWebDir) {
12
+ baseTarget = `${DEFAULT_HOSTED_UI_URL.replace(/\/+$/, "")}?port=${state.port}`;
13
+ }
14
+ if (rawReturnTo && rawReturnTo.trim()) {
15
+ try {
16
+ const parsed = new URL(rawReturnTo.trim());
17
+ if (isAllowedLocalhostOrigin(parsed.origin)) {
18
+ baseTarget = parsed.toString();
19
+ }
20
+ }
21
+ catch {
22
+ // Ignore malformed return_to URL
23
+ }
24
+ }
25
+ try {
26
+ const targetUrl = new URL(baseTarget);
27
+ targetUrl.searchParams.set("auth", "success");
28
+ if (cleanHandle) {
29
+ targetUrl.searchParams.set("handle", cleanHandle);
30
+ }
31
+ return targetUrl.toString();
32
+ }
33
+ catch {
34
+ return baseTarget;
35
+ }
36
+ }
37
+ export function buildAuthStatusPayload(state) {
38
+ const creds = loadChompCredentials();
39
+ const activeToken = resolveActiveBearerToken();
40
+ const jwtClaims = creds?.token
41
+ ? decodeJwtPayloadUnsafe(creds.token)
42
+ : activeToken?.startsWith("chomp_tok_")
43
+ ? decodeJwtPayloadUnsafe(activeToken)
44
+ : null;
45
+ const rawHandle = creds?.githubHandle ||
46
+ (typeof jwtClaims?.github_login === "string"
47
+ ? jwtClaims.github_login
48
+ : undefined);
49
+ const githubHandle = rawHandle ? rawHandle.replace(/^@+/, "") : undefined;
50
+ const expiresAt = typeof jwtClaims?.exp === "number"
51
+ ? new Date(jwtClaims.exp * 1000).toISOString()
52
+ : undefined;
53
+ const tokenExpired = typeof jwtClaims?.exp === "number"
54
+ ? jwtClaims.exp * 1000 <= Date.now()
55
+ : false;
56
+ const claimedTier = typeof jwtClaims?.tier === "string" ? jwtClaims.tier : undefined;
57
+ return {
58
+ authenticated: Boolean(activeToken && !tokenExpired),
59
+ hasToken: Boolean(creds?.token),
60
+ hasApiKey: Boolean(creds?.apiKey),
61
+ ...(githubHandle ? { githubHandle } : {}),
62
+ ...(claimedTier ? { claimedTier } : {}),
63
+ ...(expiresAt ? { expiresAt } : {}),
64
+ tokenExpired,
65
+ ...(creds?.updatedAt ? { updatedAt: creds.updatedAt } : {}),
66
+ mode: state.isMasterLocalMode ? "master" : "cloud",
67
+ cloudApiUrl: state.resolvedCloudApiUrl,
68
+ port: Number(state.port),
69
+ ...(state.latestEntitlement ? { entitlement: state.latestEntitlement } : {}),
70
+ };
71
+ }
72
+ export function registerAuthAndSourceRoutes(app, state) {
73
+ // Loopback Auth Endpoints (`~/.chomp/credentials.json`, 0600 perms)
74
+ app.get("/api/auth/status", (_req, res) => {
75
+ return res.json(buildAuthStatusPayload(state));
76
+ });
77
+ app.get("/api/auth/callback", (req, res) => {
78
+ try {
79
+ const rawToken = typeof req.query.token === "string" ? req.query.token.trim() : "";
80
+ const rawHandle = typeof req.query.handle === "string" ? req.query.handle.trim() : "";
81
+ const rawReturnTo = typeof req.query.return_to === "string"
82
+ ? req.query.return_to.trim()
83
+ : undefined;
84
+ if (!rawToken) {
85
+ return res
86
+ .status(400)
87
+ .json({ error: "Missing ?token= query parameter on auth callback." });
88
+ }
89
+ const claims = decodeJwtPayloadUnsafe(rawToken);
90
+ const resolvedHandle = rawHandle ||
91
+ (typeof claims?.github_login === "string"
92
+ ? claims.github_login
93
+ : undefined);
94
+ const githubHandle = resolvedHandle
95
+ ? resolvedHandle.replace(/^@+/, "")
96
+ : undefined;
97
+ saveChompCredentials({
98
+ token: rawToken,
99
+ ...(githubHandle ? { githubHandle } : {}),
100
+ });
101
+ const { dbPath: activeDbPath } = getActiveUiTarget(state);
102
+ invalidateAuthCachesOnly(state, activeDbPath);
103
+ const redirectTarget = resolveSafeAuthReturnUrl(state, rawReturnTo, githubHandle);
104
+ return res.redirect(302, redirectTarget);
105
+ }
106
+ catch (err) {
107
+ return res
108
+ .status(500)
109
+ .json({ error: err?.message || "Failed to persist GitHub trial token." });
110
+ }
111
+ });
112
+ app.post("/api/auth/token", (req, res) => {
113
+ try {
114
+ const rawKey = typeof req.body?.apiKey === "string"
115
+ ? req.body.apiKey.trim()
116
+ : typeof req.body?.token === "string"
117
+ ? req.body.token.trim()
118
+ : "";
119
+ if (!rawKey) {
120
+ return res
121
+ .status(400)
122
+ .json({ error: "A license key (chomp_live_...) or token is required." });
123
+ }
124
+ if (rawKey.startsWith("chomp_tok_")) {
125
+ const claims = decodeJwtPayloadUnsafe(rawKey);
126
+ const bodyHandle = typeof req.body?.githubHandle === "string"
127
+ ? req.body.githubHandle.trim()
128
+ : "";
129
+ const resolvedHandle = bodyHandle ||
130
+ (typeof claims?.github_login === "string"
131
+ ? claims.github_login
132
+ : undefined);
133
+ const githubHandle = resolvedHandle
134
+ ? resolvedHandle.replace(/^@+/, "")
135
+ : undefined;
136
+ saveChompCredentials({
137
+ token: rawKey,
138
+ apiKey: "",
139
+ ...(githubHandle ? { githubHandle } : {}),
140
+ });
141
+ }
142
+ else {
143
+ saveChompCredentials({ apiKey: rawKey });
144
+ }
145
+ const { dbPath: activeDbPath } = getActiveUiTarget(state);
146
+ invalidateAuthCachesOnly(state, activeDbPath);
147
+ return res.json({ ok: true, ...buildAuthStatusPayload(state) });
148
+ }
149
+ catch (err) {
150
+ return res
151
+ .status(500)
152
+ .json({ error: err?.message || "Failed to save license key." });
153
+ }
154
+ });
155
+ app.delete("/api/auth/token", (_req, res) => {
156
+ try {
157
+ clearChompCredentials();
158
+ const { dbPath: activeDbPath } = getActiveUiTarget(state);
159
+ invalidateAuthCachesOnly(state, activeDbPath);
160
+ if (!state.isMasterLocalMode) {
161
+ state.latestEntitlement = undefined;
162
+ }
163
+ return res.json({ ok: true, ...buildAuthStatusPayload(state) });
164
+ }
165
+ catch (err) {
166
+ return res
167
+ .status(500)
168
+ .json({ error: err?.message || "Failed to clear credentials." });
169
+ }
170
+ });
171
+ // GET /api/source-line — localhost-only 1-line call-shape lookup for UNKNOWN / LIKELY tooltips
172
+ app.get("/api/source-line", async (req, res) => {
173
+ try {
174
+ const filePath = typeof req.query.file === "string" ? req.query.file.trim() : "";
175
+ const rawLine = typeof req.query.line === "string" ? Number(req.query.line) : NaN;
176
+ if (!filePath || !Number.isInteger(rawLine) || rawLine < 1) {
177
+ return res
178
+ .status(400)
179
+ .json({ error: "Valid file and 1-based line query parameters are required." });
180
+ }
181
+ const { target: activeTarget } = getActiveUiTarget(state);
182
+ const baseData = await loadBaseGraphCached(state);
183
+ const repoPath = baseData?.repo.path || activeTarget;
184
+ const hit = readSingleSourceLine(repoPath, filePath, rawLine);
185
+ if (!hit) {
186
+ return res.status(404).json({ error: "Source line unavailable." });
187
+ }
188
+ return res.json(hit);
189
+ }
190
+ catch (e) {
191
+ console.error("Error reading source line:", e);
192
+ return res.status(500).json({ error: "Failed to read source line" });
193
+ }
194
+ });
195
+ // POST /api/open-in-ide — localhost-only IDE deep-link launcher (with editorUri + remoteFileUrl fallback)
196
+ app.post("/api/open-in-ide", async (req, res) => {
197
+ try {
198
+ const body = req.body ?? {};
199
+ const filePath = typeof body.filePath === "string" ? body.filePath.trim() : "";
200
+ const lineNumber = typeof body.lineNumber === "number" &&
201
+ Number.isInteger(body.lineNumber) &&
202
+ body.lineNumber >= 1
203
+ ? body.lineNumber
204
+ : undefined;
205
+ if (!filePath) {
206
+ return res.status(400).json({ error: "filePath is required." });
207
+ }
208
+ const { target: activeTarget } = getActiveUiTarget(state);
209
+ const baseData = await loadBaseGraphCached(state);
210
+ const repoPath = baseData?.repo.path || activeTarget;
211
+ const liveGit = await getGitInfoAsync(repoPath, { includeCommitMessage: false });
212
+ const result = await openInLocalEditor({
213
+ repoRoot: repoPath,
214
+ relFilePath: filePath,
215
+ lineNumber,
216
+ remoteUrl: liveGit.remoteUrl,
217
+ commitSha: liveGit.commitSha ||
218
+ baseData?.repo.commitSha ||
219
+ baseData?.graph.commitSha,
220
+ });
221
+ if (!result.ok) {
222
+ return res.status(404).json(result);
223
+ }
224
+ return res.json(result);
225
+ }
226
+ catch (e) {
227
+ console.error("Error opening file in IDE:", e);
228
+ return res.status(500).json({ error: "Failed to open file in IDE" });
229
+ }
230
+ });
231
+ }
@@ -0,0 +1,3 @@
1
+ import type { Express } from "express";
2
+ import { type UiServerState } from "../graphLayoutState.js";
3
+ export declare function registerLayoutRoutes(app: Express, state: UiServerState): void;