From 562a946053e79e3236950bb715a30762c2853869 Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Mon, 4 May 2026 00:41:51 +0100 Subject: [PATCH] fix(extension): harden review-flagged paths A pass over the extension surface to address review feedback: Safety / hardening: - `graphPanel.ts`: validate `m.path` from the webview before opening files. Reject absolute paths and any path that escapes the workspace root (`..`, `/foo`, `C:/...`). Validate the line number is a positive integer before constructing a `Range`. Surface failures via the output channel rather than letting the rejection bubble up. - `mcpProvider.ts`: defensively check that `vscode.lm.registerMcpServerDefinitionProvider` exists before calling it. The `engines.vscode: ^1.99.0` field already enforces this on install, but some VS Code-derived editors mis-report their engine version. The extension now degrades gracefully (sidebar, commands, status bar still work) instead of failing activation. - `commands.ts` and `graphPanel.ts`: wrap `workbench.action.chat.open` in try/catch. Not every VS Code-compatible editor exposes that command; falling back to the output channel avoids unhandled rejections after the user clicked "Open chat". - `extension.ts`: persist the first-run walkthrough flag only after the walkthrough command resolves successfully, so a transient failure doesn't silently skip the onboarding forever. CI gates: - `extension-ci.yml` and `extension-release.yml`: run `npm test` between typecheck and build, so manifest-level smoke regressions can't slip through to either the PR artefact or the marketplace publishes. Settings copy: - `socraticode.env` description: explicitly call out that the setting is for non-secret config only. Recommend OS environment variables / local `.env` files for API keys, since workspace settings can sync via Settings Sync and end up in committed `.vscode/settings.json`. Quality of life: - `sidebar.ts` `formatRelative`: clamp the computed seconds to zero so a file mtime slightly ahead of the local clock doesn't render "-5s ago". - `walkthroughs/first-index.md`: corrected the embedding model name (`nomic-embed-text`, not `mxbai-embed-large`) to match the engine default in `src/constants.ts`. Lint / docs: - `extension/README.md`: hyphenate "Eclipse Theia-based editors". - `DEVELOPER.md`: add `text` language hint to the directory-tree code fence (markdownlint MD040). Updated the inline comment for `settings.ts` to reflect its current shape. - `README.md`: reflow the "extension vs plugin" callout into a single blockquote (markdownlint MD028). Lint, typecheck, manifest tests and build all clean. Engine unit tests unaffected (706/706 still pass). --- .github/workflows/extension-ci.yml | 5 ++- .github/workflows/extension-release.yml | 3 ++ DEVELOPER.md | 4 +- README.md | 4 +- extension/README.md | 2 +- extension/package.json | 2 +- extension/src/commands.ts | 35 ++++++++++++---- extension/src/extension.ts | 22 ++++++---- extension/src/graphPanel.ts | 54 ++++++++++++++++++++----- extension/src/mcpProvider.ts | 19 ++++++++- extension/src/sidebar.ts | 4 +- extension/walkthroughs/first-index.md | 6 +-- 12 files changed, 123 insertions(+), 37 deletions(-) diff --git a/.github/workflows/extension-ci.yml b/.github/workflows/extension-ci.yml index e7c7c58..b19ba47 100644 --- a/.github/workflows/extension-ci.yml +++ b/.github/workflows/extension-ci.yml @@ -17,7 +17,7 @@ permissions: jobs: lint-build-package: - name: Lint, typecheck, build, package + name: Lint, typecheck, test, build, package runs-on: ubuntu-latest defaults: run: @@ -40,6 +40,9 @@ jobs: - name: Typecheck run: npm run typecheck + - name: Test + run: npm test + - name: Build run: npm run compile diff --git a/.github/workflows/extension-release.yml b/.github/workflows/extension-release.yml index f8312c2..827adb5 100644 --- a/.github/workflows/extension-release.yml +++ b/.github/workflows/extension-release.yml @@ -36,6 +36,9 @@ jobs: - name: Typecheck run: npm run typecheck + - name: Test + run: npm test + - name: Build run: npm run compile diff --git a/DEVELOPER.md b/DEVELOPER.md index 289aa3d..721f253 100644 --- a/DEVELOPER.md +++ b/DEVELOPER.md @@ -1417,7 +1417,7 @@ Source: [`extension/`](./extension) ### Layout -``` +```text extension/ ├── package.json # extension manifest ├── tsconfig.json # TS strict, ES2022, Node 18 target @@ -1434,7 +1434,7 @@ extension/ ├── graphPanel.ts # webview panel for the interactive graph ├── statusBar.ts # status-bar item ├── commands.ts # command palette commands - ├── settings.ts # typed config + SecretStorage + ├── settings.ts # typed config accessors ├── output.ts # log/output channel └── __tests__/ # node:test smoke tests for the manifest ``` diff --git a/README.md b/README.md index 7dd3166..a513f5f 100644 --- a/README.md +++ b/README.md @@ -177,11 +177,11 @@ SocratiCode is available as a native plugin on multiple AI coding platforms. Plu | OpenAI Codex | No public plugin directory yet — use the [MCP config](#quick-start) or see **Codex local install** below | > **Extension vs plugin (what to install in VS Code / Cursor):** +> > - The **extension** (Marketplace / Open VSX listing) is a regular VS Code-style extension. It auto-registers the MCP server in Copilot agent mode, Cline, Continue, Roo Code, plus adds a sidebar, status-bar item, interactive graph webview, walkthrough and palette commands. Best for most users. > - The **plugins** (`/add-plugin` for Cursor, `Chat: Install Plugin From Source` for VS Code Copilot) bundle the MCP server **plus skills + agent instructions** that teach the AI to use SocratiCode tools effectively. Best when you want the agent to be opinionated about using SocratiCode. > - You can install both. The extension only registers the MCP server once, so they don't conflict. - -> **VS Code Copilot**: The chat plugins feature is in preview. Enable it with `chat.plugins.enabled: true` in your VS Code settings. +> - **VS Code Copilot note**: the chat plugins feature is in preview. Enable it with `chat.plugins.enabled: true` in your VS Code settings. > **Codex local plugin install**: Clone the repo and register it in your personal plugin marketplace: > ```bash diff --git a/extension/README.md b/extension/README.md index 88e871b..a8254a4 100644 --- a/extension/README.md +++ b/extension/README.md @@ -126,7 +126,7 @@ VS Code 1.99+ extension API: - VSCodium - Gitpod - code-server -- Eclipse Theia based editors +- Eclipse Theia-based editors - Google Antigravity - Particle Workbench diff --git a/extension/package.json b/extension/package.json index 0980dc8..b2c9786 100644 --- a/extension/package.json +++ b/extension/package.json @@ -153,7 +153,7 @@ "additionalProperties": { "type": "string" }, - "description": "Environment variables forwarded to the engine. Use this to point at an external Qdrant (`QDRANT_MODE=external`, `QDRANT_URL`, `QDRANT_API_KEY`), select an embedding provider (`EMBEDDING_PROVIDER`, `OPENAI_API_KEY`, etc.), or any other engine setting documented in the engine README.", + "description": "Non-secret environment variables forwarded to the engine. Use this for non-sensitive engine config like external Qdrant URL (`QDRANT_MODE=external`, `QDRANT_URL`), embedding provider selection (`EMBEDDING_PROVIDER`), project IDs, branch-aware indexing, and so on. AVOID storing API keys or tokens here: workspace settings can be synced via VS Code Settings Sync and may end up in committed `.vscode/settings.json` files. For secrets, prefer OS environment variables, a local `.env` file outside settings, or a system keychain.", "scope": "window" }, "socraticode.statusBar": { diff --git a/extension/src/commands.ts b/extension/src/commands.ts index dc75179..4e35dc2 100644 --- a/extension/src/commands.ts +++ b/extension/src/commands.ts @@ -38,12 +38,21 @@ export function registerCommands( vscode.commands.registerCommand("socraticode.openWalkthrough", async () => { // Use context.extension.id so this keeps working if the publisher // namespace changes. Same pattern as the first-run trigger in - // extension.ts. - await vscode.commands.executeCommand( - "workbench.action.openWalkthrough", - `${context.extension.id}#socraticode.gettingStarted`, - false, - ); + // extension.ts. Wrapped in try/catch because some VS Code forks + // do not expose `workbench.action.openWalkthrough` and the + // command would otherwise reject silently. + try { + await vscode.commands.executeCommand( + "workbench.action.openWalkthrough", + `${context.extension.id}#socraticode.gettingStarted`, + false, + ); + } catch (err) { + log(`Failed to open walkthrough: ${(err as Error).message}`); + vscode.window.showWarningMessage( + "SocratiCode: this editor does not appear to support walkthroughs. See the marketplace listing for getting-started guidance.", + ); + } }), ); @@ -71,7 +80,19 @@ async function indexCurrentWorkspaceCommand(): Promise { "Show output", ); if (action === "Open chat") { - await vscode.commands.executeCommand("workbench.action.chat.open"); + // `workbench.action.chat.open` is not guaranteed across every + // VS Code-compatible editor (some Theia-based forks omit it). Fall + // back to the output channel if the host doesn't expose the chat + // command, so the user always gets useful feedback. + try { + await vscode.commands.executeCommand("workbench.action.chat.open"); + } catch (err) { + log(`Open chat failed: ${(err as Error).message}`); + output().show(true); + vscode.window.showInformationMessage( + "SocratiCode: this editor does not expose a chat command. Opened the SocratiCode output channel instead.", + ); + } } else if (action === "Show output") { output().show(true); } diff --git a/extension/src/extension.ts b/extension/src/extension.ts index c1f2efc..d460fe7 100644 --- a/extension/src/extension.ts +++ b/extension/src/extension.ts @@ -31,15 +31,23 @@ export async function activate(context: vscode.ExtensionContext): Promise registerCommands(context, sidebar); // Show the walkthrough on first install. We use globalState rather than - // a setting so it's per-machine, not per-workspace. + // a setting so it's per-machine, not per-workspace. Persist the + // "shown" flag only AFTER the command resolves, so if the host fails + // to open the walkthrough (some VS Code forks don't expose + // `workbench.action.openWalkthrough`), the user is offered it again + // next session instead of silently skipping it forever. const shown = context.globalState.get(FIRST_RUN_KEY, false); if (!shown) { - void context.globalState.update(FIRST_RUN_KEY, true); - void vscode.commands.executeCommand( - "workbench.action.openWalkthrough", - `${context.extension.id}#socraticode.gettingStarted`, - false, - ); + try { + await vscode.commands.executeCommand( + "workbench.action.openWalkthrough", + `${context.extension.id}#socraticode.gettingStarted`, + false, + ); + await context.globalState.update(FIRST_RUN_KEY, true); + } catch (err) { + log(`Failed to open first-run walkthrough: ${(err as Error).message}`); + } } log("SocratiCode extension activated"); diff --git a/extension/src/graphPanel.ts b/extension/src/graphPanel.ts index 6a72fbe..64454b2 100644 --- a/extension/src/graphPanel.ts +++ b/extension/src/graphPanel.ts @@ -119,7 +119,17 @@ async function offerToGenerate(): Promise { await vscode.env.clipboard.writeText(prompt); vscode.window.showInformationMessage("SocratiCode: prompt copied."); } else if (action === "Open chat") { - await vscode.commands.executeCommand("workbench.action.chat.open"); + // Not all VS Code-compatible editors expose `workbench.action.chat.open` + // (some Theia-based forks omit it). Fall back to a friendlier message + // rather than letting the rejection bubble up unhandled. + try { + await vscode.commands.executeCommand("workbench.action.chat.open"); + } catch (err) { + log(`Open chat failed: ${(err as Error).message}`); + vscode.window.showInformationMessage( + "SocratiCode: this editor does not expose a chat command. Open your AI assistant manually and paste the copied prompt.", + ); + } } } @@ -178,15 +188,37 @@ function wrapHtml(html: string, webview: vscode.Webview): string { function handleWebviewMessage(msg: unknown): void { if (typeof msg !== "object" || msg === null) return; const m = msg as { type?: string; path?: string; line?: number }; - if (m.type === "openFile" && typeof m.path === "string") { - const ws = vscode.workspace.workspaceFolders?.[0]; - if (!ws) { - vscode.window.showWarningMessage("SocratiCode: open a workspace to navigate from the graph."); - return; - } - const uri = vscode.Uri.joinPath(ws.uri, m.path); - const range = - typeof m.line === "number" ? new vscode.Range(m.line - 1, 0, m.line - 1, 0) : undefined; - vscode.window.showTextDocument(uri, range ? { selection: range } : {}); + if (m.type !== "openFile" || typeof m.path !== "string") return; + + const ws = vscode.workspace.workspaceFolders?.[0]; + if (!ws) { + vscode.window.showWarningMessage("SocratiCode: open a workspace to navigate from the graph."); + return; } + + // The webview HTML is generated by us, but the boundary is still + // untrusted: anything that crosses `postMessage` could be tampered + // with. Reject absolute paths and any path that escapes the workspace + // root (`..`). Normalise via posix paths so the same validation works + // on Windows, macOS, and Linux. + const normalised = path.posix.normalize(m.path.replace(/\\/g, "/")); + const isAbsolute = normalised.startsWith("/") || /^[A-Za-z]:\//.test(normalised); + const escapesRoot = + normalised === ".." || normalised.startsWith("../") || normalised.includes("/../"); + if (isAbsolute || escapesRoot || normalised === "." || normalised === "") { + log(`Graph panel: rejecting suspicious path from webview: ${m.path}`); + vscode.window.showWarningMessage("SocratiCode: invalid file path from graph."); + return; + } + + const uri = vscode.Uri.joinPath(ws.uri, ...normalised.split("/")); + const lineIndex = + typeof m.line === "number" && Number.isInteger(m.line) && m.line > 0 ? m.line - 1 : undefined; + const selection = + lineIndex !== undefined ? new vscode.Range(lineIndex, 0, lineIndex, 0) : undefined; + void vscode.window + .showTextDocument(uri, selection ? { selection } : {}) + .then(undefined, (err) => + log(`Graph panel: failed to open ${normalised}: ${(err as Error).message}`), + ); } diff --git a/extension/src/mcpProvider.ts b/extension/src/mcpProvider.ts index cbdb991..2b667c9 100644 --- a/extension/src/mcpProvider.ts +++ b/extension/src/mcpProvider.ts @@ -43,8 +43,25 @@ export class SocratiCodeMcpProvider implements vscode.McpServerDefinitionProvide } } -export function registerMcpProvider(context: vscode.ExtensionContext): SocratiCodeMcpProvider { +export function registerMcpProvider( + context: vscode.ExtensionContext, +): SocratiCodeMcpProvider | undefined { const provider = new SocratiCodeMcpProvider(); + + // The `engines.vscode: ^1.99.0` field in package.json prevents + // installation on hosts without the MCP API, but some VS Code-derived + // editors lie about their reported version. Defensively check that + // the API surface exists before calling it, so activation degrades + // gracefully (sidebar / commands / status bar still work) instead of + // throwing a hard error that disables the entire extension. + if (typeof vscode.lm?.registerMcpServerDefinitionProvider !== "function") { + log( + "vscode.lm.registerMcpServerDefinitionProvider is unavailable in this host; " + + "skipping MCP server registration. Sidebar, commands and status bar still work.", + ); + return undefined; + } + const disposable = vscode.lm.registerMcpServerDefinitionProvider("socraticode.mcp", provider); context.subscriptions.push(disposable); log("Registered SocratiCode MCP server provider"); diff --git a/extension/src/sidebar.ts b/extension/src/sidebar.ts index dff518c..22c4887 100644 --- a/extension/src/sidebar.ts +++ b/extension/src/sidebar.ts @@ -109,7 +109,9 @@ export function registerSidebar(context: vscode.ExtensionContext): ProjectsTreeP } function formatRelative(date: Date): string { - const seconds = Math.round((Date.now() - date.getTime()) / 1000); + // Clamp to zero so a file mtime slightly ahead of the local clock + // (NTP correction, container clock skew) doesn't render "-5s ago". + const seconds = Math.max(0, Math.round((Date.now() - date.getTime()) / 1000)); if (seconds < 60) return `${seconds}s ago`; const minutes = Math.round(seconds / 60); if (minutes < 60) return `${minutes}m ago`; diff --git a/extension/walkthroughs/first-index.md b/extension/walkthroughs/first-index.md index 5cb0352..a4d56ba 100644 --- a/extension/walkthroughs/first-index.md +++ b/extension/walkthroughs/first-index.md @@ -7,9 +7,9 @@ Index the workspace: Index current workspace** from the command palette. The first index downloads the embedding model if it's not already cached -(roughly 700 MB for the default `mxbai-embed-large`), then walks the -workspace. Subsequent updates are incremental and triggered automatically -when files change. +(the default is `nomic-embed-text` via the local Docker Ollama, a few +hundred megabytes), then walks the workspace. Subsequent updates are +incremental and triggered automatically when files change. ## What gets indexed