Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -290,3 +290,48 @@ jobs:

- name: Install and run the extension (virtual display)
run: xvfb-run -a node apps/ide/scripts/vsixE2e.mjs "$(ls vsix/apps/vscode-extension/artifacts/*.vsix | head -n 1)"

extensions-compat:
name: Popular extensions in the extension host (ubuntu-latest)
# #264: downloads popular extensions from Open VSX and runs each one in
# the IDE's extension host (apps/ide/scripts/extensionCompat.mjs): did it
# activate, and which vscode APIs did it use that the host lacks. A
# measurement for docs/ide/extensions-compatibility.md, not a gate: a
# third-party release must not turn the build red, so it never fails it.
if: github.event_name != 'push'
runs-on: ubuntu-latest
continue-on-error: true
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm

- name: Install
run: npm ci

- name: Probe the extensions
working-directory: apps/ide
run: |
node --experimental-strip-types --no-warnings scripts/extensionCompat.mjs --markdown --json compat.json --open-vsx \
redhat.vscode-yaml esbenp.prettier-vscode dbaeumer.vscode-eslint eamodio.gitlens ms-python.python \
rust-lang.rust-analyzer golang.Go streetsidesoftware.code-spell-checker usernamehw.errorlens \
PKief.material-icon-theme vscodevim.vim christian-kohler.path-intellisense EditorConfig.EditorConfig \
yzhang.markdown-all-in-one Gruntfuggly.todo-tree mechatroner.rainbow-csv formulahendry.code-runner \
dracula-theme.theme-dracula GitHub.github-vscode-theme llvm-vs-code-extensions.vscode-clangd \
Vue.volar svelte.svelte-vscode bradlc.vscode-tailwindcss hashicorp.terraform tamasfe.even-better-toml \
James-Yu.latex-workshop oderwat.indent-rainbow ms-azuretools.vscode-docker redhat.java \
MS-CEINTL.vscode-language-pack-es > compat.md || true
cat compat.md >> "$GITHUB_STEP_SUMMARY"
cat compat.md

- name: Keep the results
uses: actions/upload-artifact@v4
with:
name: extensions-compat
path: apps/ide/compat.json
if-no-files-found: ignore
3 changes: 2 additions & 1 deletion apps/ide/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ Following Electron's [security checklist](https://www.electronjs.org/docs/latest
| Extensions (#251) are unpacked only from checked archives: entries under `extension/` only, no `..`, absolute paths, drive letters or links, size limits; an Open VSX download must match the registry's SHA-256; a native dialog shows publisher, verification, licence and whether it runs code before anything is installed; nothing goes online unless the person searches or installs | `src/main/extensions/` (`vsix.ts`, `openVsx.ts`, `extensionsService.ts`) | Unit tests (`test/extensions.test.ts`: zip-slip, symlink and garbage archives, wrong and missing checksums, http downloads, tampered `extensions.json`). |
| The renderer may compile WebAssembly (`'wasm-unsafe-eval'`) for the TextMate regex engine of extension grammars (#258); `eval` stays blocked | `buildContentSecurityPolicy` | Unit tests; smoke checks `eval` throws. |
| Extensions' code (#259) runs only in the extension host, a separate Node process per window, never in the renderer or main; what it asks of main is checked there (files only inside the folder, links only http/https/mailto, secrets in the OS store per extension, edits refused whole when a file is outside the folder); only workbench activation events are accepted from the renderer, and the documents it reports (#260) go through the workspace path rules with bounded sizes | `src/extensionHost/`, `src/main/extensions/extensionHostManager.ts` | Unit tests (`test/extensionHost.test.ts`, `test/extensionLanguages.test.ts`, with a real host process). |
| Extensions respect workspace trust (#263): in Restricted Mode only those declaring `untrustedWorkspaces.supported` run; what is enabled lives in the user-data folder, never the project; `--disable-extensions` and **Disable All Installed Extensions** for recovery | `src/main/extensions/runState.ts`, `extensionsService.ts`, `extensionStore.ts` | Unit tests (`test/extensionTrust.test.ts`: the run-state rules, the manifest flag, `workspace.isTrusted` and `onDidGrantWorkspaceTrust` in a real host). |
| The dev server URL is ignored in a packaged build | `src/main/index.ts` (`app.isPackaged`) | Code review. |

Running as root (containers, some CI images) requires `--no-sandbox`, which the scripts add only in that case. It turns off Chromium's OS-level sandbox and `app.enableSandbox()`; the per-window `sandbox: true` preference and its assertion stay.
Expand All @@ -192,7 +193,7 @@ Running as root (containers, some CI images) requires `--no-sandbox`, which the

A folder can bring things that run: Git reads the repository's own hooks, filters and configuration, pyright runs the interpreter a project's config names, and tasks (#176) are commands the folder defines. So the first time a folder opens, a notification asks whether you trust its authors: **Trust Folder**, **Trust All in** its parent folder (every folder below a trusted one is trusted), or **Restricted Mode**. Until it is answered the folder is restricted, and a **Restricted Mode** shield sits at the start of the status bar; clicking it, or **Manage Workspace Trust** in the palette, changes the answer later. A folder can be put in Restricted Mode even inside a trusted parent.

In Restricted Mode the main process runs no Git in the folder (Source Control says why), starts no Python language server, and refuses tasks (Run Task and Run Current File say why and offer Manage Workspace Trust). Reading, editing, search, the terminal you open yourself, the IDE's own TypeScript server and the Code-XR analysis (it parses files, it never runs them) work either way. The decisions are stored in `workspace-trust.json` in the IDE's user-data folder, never in the project, so a folder cannot trust itself; paths compare without case on Windows and macOS (`main/trust/`, `renderer/trustView.ts`). The smoke run checks that a new folder starts restricted with Git off, and that trusting it turns Git on.
In Restricted Mode the main process runs no Git in the folder (Source Control says why), starts no Python language server, refuses tasks (Run Task and Run Current File say why and offer Manage Workspace Trust), and starts only the extensions whose manifest declares `capabilities.untrustedWorkspaces.supported` (`true` or `"limited"`, #263): the others show *Disabled in Restricted Mode* in the Extensions view, and trusting the folder restarts the extension host with them, without restarting the IDE. Extensions see the same trust (`workspace.isTrusted`, `onDidGrantWorkspaceTrust`). Which extensions are on is kept in `extensions.json` in the IDE's user-data folder, never in the project, so a folder cannot turn an extension on; `--disable-extensions` on the command line, or **Disable All Installed Extensions** in the palette, turns them all off for recovery. Reading, editing, search, the terminal you open yourself, the IDE's own TypeScript server and the Code-XR analysis (it parses files, it never runs them) work either way. The decisions are stored in `workspace-trust.json` in the IDE's user-data folder, never in the project, so a folder cannot trust itself; paths compare without case on Windows and macOS (`main/trust/`, `renderer/trustView.ts`). The smoke run checks that a new folder starts restricted with Git off, and that trusting it turns Git on.

## Tasks and Run Current File (#176)

Expand Down
1 change: 1 addition & 0 deletions apps/ide/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"typecheck": "node scripts/coreTypes.mjs && node ../../node_modules/typescript/bin/tsc -p tsconfig.node.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.web.json",
"lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts eslint.config.mjs --max-warnings 0",
"test:unit": "node --import ./scripts/testCoreAlias.mjs --test --experimental-strip-types \"test/**/*.test.ts\"",
"compat": "node --experimental-strip-types --no-warnings scripts/extensionCompat.mjs",
"test": "npm run typecheck && npm run lint && npm run test:unit"
},
"engines": {
Expand Down
85 changes: 85 additions & 0 deletions apps/ide/scripts/extensionCompat.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// #264: the compatibility probe, from the command line. Installs each .vsix
// through the IDE's own install path, starts the real extension host on it
// in Node, fires its activation events, and prints what happened: activated
// or failed, and which vscode APIs it used that the host does not implement.
//
// Usage:
// node --experimental-strip-types scripts/extensionCompat.mjs [options] <file.vsix | folder>... [--open-vsx <publisher.name>...]
// Options:
// --json <file> also write the full results as JSON
// --markdown print the Markdown table of docs/ide/extensions-compatibility.md
// --open-vsx ... download these extensions from Open VSX first (the same client and SHA-256 check as the IDE)
// A folder stands for every .vsix directly inside it. Exit code 1 when an extension failed to install, activate or answer.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const IDE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const { probeVsix, probeTable } = await import(path.join(IDE_ROOT, 'src/main/extensions/compatProbe.ts'));
const { OpenVsxClient } = await import(path.join(IDE_ROOT, 'src/main/extensions/openVsx.ts'));

const args = process.argv.slice(2);
const files = [];
const fromOpenVsx = [];
let jsonOut = null;
let markdown = false;
let mode = 'files';
for (let index = 0; index < args.length; index++) {
const arg = args[index];
if (arg === '--json') {
jsonOut = path.resolve(args[++index] ?? 'compat.json');
} else if (arg === '--markdown') {
markdown = true;
} else if (arg === '--open-vsx') {
mode = 'open-vsx';
} else if (mode === 'open-vsx') {
fromOpenVsx.push(arg);
} else if (fs.existsSync(arg) && fs.statSync(arg).isDirectory()) {
files.push(...fs.readdirSync(arg).filter((name) => name.endsWith('.vsix')).sort().map((name) => path.resolve(arg, name)));
} else {
files.push(path.resolve(arg));
}
}

const downloads = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-compat-downloads-'));
const results = [];
try {
if (fromOpenVsx.length > 0) {
const client = new OpenVsxClient('https://open-vsx.org', (url, init) => fetch(url, init));
for (const id of fromOpenVsx) {
try {
const vsix = await client.download(id);
const file = path.join(downloads, `${id}-${vsix.version}.vsix`);
fs.writeFileSync(file, vsix.bytes);
files.push(file);
console.error(`[compat] downloaded ${id} ${vsix.version}${vsix.verified ? ' (verified publisher)' : ''}`);
} catch (error) {
results.push({ file: id, id, version: null, outcome: 'not-installed', engineSupported: null, contributions: null, missingApi: [], errors: [], registeredCommands: 0, milliseconds: 0, detail: `Open VSX: ${error instanceof Error ? error.message : String(error)}` });
}
}
}
if (files.length === 0 && results.length === 0) {
console.error('[compat] no .vsix given.');
process.exit(2);
}
for (const file of files) {
const result = await probeVsix(file, {
hostEntry: path.join(IDE_ROOT, 'src/extensionHost/index.ts'),
execArgv: ['--experimental-strip-types', '--no-warnings'],
});
results.push(result);
const missing = result.missingApi.length > 0 ? `; missing: ${result.missingApi.join(', ')}` : '';
console.error(`[compat] ${result.id ?? path.basename(file)} ${result.version ?? ''}: ${result.outcome}${missing}${result.detail ? ` (${result.detail})` : ''}`);
}
} finally {
fs.rmSync(downloads, { recursive: true, force: true });
}

if (jsonOut) {
fs.writeFileSync(jsonOut, `${JSON.stringify(results, null, 2)}\n`);
}
if (markdown) {
console.log(probeTable(results));
}
process.exit(results.some((result) => result.outcome === 'failed' || result.outcome === 'not-installed' || result.outcome === 'timeout') ? 1 : 0);
68 changes: 54 additions & 14 deletions apps/ide/src/extensionHost/host.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import fs from 'node:fs';
import Module from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
activationMatches, MAIN_METHODS, type HostActivationEvent, type HostExtensionDescription, type HostInitData, type HostLogLine, type HostPassiveExtension, type RpcEndpoint, type UiNotification, type UiRequest,
} from '../shared/extensionHostProtocol.ts';
Expand Down Expand Up @@ -58,6 +59,28 @@ interface RegisteredCommand {

type ModuleWithLoad = typeof Module & { _load(request: string, parent: { filename?: string } | null | undefined, isMain: boolean): unknown };

/** `module.registerHooks` (Node 22.15+, Electron's Node 24): synchronous, in-thread module hooks. Not in this @types/node yet. */
interface SyncModuleHooks {
resolve(specifier: string, context: { parentURL?: string | undefined }, next: (specifier: string, context: unknown) => unknown): unknown;
load(url: string, context: unknown, next: (url: string, context: unknown) => unknown): unknown;
}
type ModuleWithHooks = typeof Module & { registerHooks?: (hooks: SyncModuleHooks) => unknown };

/** The URL an ES module's `import 'vscode'` resolves to; the importing module's URL follows, encoded. */
const ESM_VSCODE_URL = 'codexr-vscode:';
/** Where the generated `vscode` ES module finds the API for the file that imported it. */
const ESM_VSCODE_GLOBAL = Symbol.for('codexr.vscodeFor');

/** The source of the ES module `vscode` for one importer: a default export and one named export per member of the API. */
export function esmVscodeSource(file: string, names: readonly string[]): string {
const exported = names.filter((name) => name !== 'default' && /^[A-Za-z_$][\w$]*$/.test(name));
return [
`const api = globalThis[Symbol.for('codexr.vscodeFor')](${JSON.stringify(file)});`,
'export default api;',
...exported.map((name, index) => `const _${index} = api[${JSON.stringify(name)}];\nexport { _${index} as ${name} };`),
].join('\n');
}

export class ExtensionHost {
readonly rpc: RpcEndpoint;
data!: HostInitData;
Expand Down Expand Up @@ -106,6 +129,8 @@ export class ExtensionHost {
for (const json of [...data.extensions, ...data.passive].map((ext) => ext.packageJSON)) {
this.learnLanguages(json);
}
// VS Code always sets it; some extensions JSON.parse it unguarded (yzhang.markdown-all-in-one).
process.env['VSCODE_NLS_CONFIG'] ??= JSON.stringify({ locale: data.env.language, osLocale: data.env.language, availableLanguages: {} });
this.hookRequire();
// The editor's state before any extension activates, so `*` extensions see the open files.
this.documentsAndEditors.accept([
Expand Down Expand Up @@ -213,28 +238,43 @@ export class ExtensionHost {
return record.api;
}

/** The API for code in `file`: its extension's, or the first extension's for code outside every extension folder (a shared dependency hoisted elsewhere). */
private apiForFile(file: string | undefined): unknown {
const record = this.extensionOfFile(file) ?? this.records.values().next().value;
if (!record) {
throw new Error('Cannot find module \'vscode\'');
}
return this.apiFor(record);
}

private hookRequire(): void {
if (this.moduleHooked) {
return;
}
this.moduleHooked = true;
const loader = Module as ModuleWithLoad;
const original = loader._load.bind(loader);
loader._load = (request, parent, isMain) => {
if (request === 'vscode') {
const record = this.extensionOfFile(parent?.filename);
if (!record) {
// Code outside every extension (a shared dependency hoisted elsewhere): the first extension's view is the best guess.
const first = this.records.values().next().value;
if (!first) {
throw new Error('Cannot find module \'vscode\'');
}
return this.apiFor(first);
loader._load = (request, parent, isMain) => (request === 'vscode' ? this.apiForFile(parent?.filename) : original(request, parent, isMain));
// #264: extensions shipped as ES modules (esbenp.prettier-vscode) `import ... from 'vscode'`, which `_load` never sees.
const registerHooks = (Module as ModuleWithHooks).registerHooks;
if (typeof registerHooks !== 'function') {
return;
}
(globalThis as Record<symbol, unknown>)[ESM_VSCODE_GLOBAL] = (file: string) => this.apiForFile(file || undefined);
registerHooks.call(Module, {
resolve: (specifier, context, next) => (specifier === 'vscode'
? { url: `${ESM_VSCODE_URL}${encodeURIComponent(context.parentURL ?? '')}`, shortCircuit: true }
: next(specifier, context)),
load: (url, context, next) => {
if (!url.startsWith(ESM_VSCODE_URL)) {
return next(url, context);
}
return this.apiFor(record);
}
return original(request, parent, isMain);
};
const parent = decodeURIComponent(url.slice(ESM_VSCODE_URL.length));
const file = parent.startsWith('file:') ? fileURLToPath(parent) : '';
const api = this.apiForFile(file || undefined) as object;
return { format: 'module', source: esmVscodeSource(file, Object.keys(api)), shortCircuit: true };
},
});
}

/* ------------------------------ activation ------------------------------ */
Expand Down
Loading
Loading