Skip to content
Open
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ Working from scratch? Create an untitled document and choose CSV or TSV as its l

CSV supports VS Code 1.70+. Switching saved files between table and text requires 1.100+, or 1.120+ when there are unsaved changes. [Editing and compatibility details](docs/user-guide.md#open-and-edit-a-file).

CSV also works in [Restricted Mode](https://code.visualstudio.com/docs/editing/workspaces/workspace-trust) (untrusted workspaces). It never runs code from the workspace, and settings that reach the table view are sanitized, so a workspace's `.vscode/settings.json` can't inject content into it.

## Your files stay in your workspace

CSV requires no account or upload service and has no extension-specific analytics client. Processing runs in your VS Code environment, including the remote extension host when you use a remote workspace. [Privacy and data handling](PRIVACY.md).
Expand Down
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@
"Programming Languages",
"Other"
],
"capabilities": {
"untrustedWorkspaces": {
"supported": true
}
},
"activationEvents": [
"onStartupFinished",
"onLanguage:csv",
Expand Down
48 changes: 41 additions & 7 deletions src/CsvEditorProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2567,7 +2567,12 @@ class CsvEditorController {
visibleRowIds: number[];
filterMetadata: { session: string; filterColumnsRevision: number; filters: ColumnFilter[]; columns: FilterColumn[]; matchedRows: number; totalRows: number; maxFilters: number; revision: number; filterDraft?: FilterDraft };
}): string {
const { webview, nonce, fontFamily, fontSize, cellPadding, separator, tableHtml, chunksJson, extraColumnColorCss, nextChunkStart, hasRemoteChunks, headerEnabled, mouseWheelZoomEnabled, mouseWheelZoomInvert, columnSizes, frozenPanes, firstVisibleRow, realRowCount, visibleRowIds, filterMetadata } = args;
const { webview, nonce, separator, tableHtml, chunksJson, extraColumnColorCss, nextChunkStart, hasRemoteChunks, headerEnabled, mouseWheelZoomEnabled, mouseWheelZoomInvert, columnSizes, frozenPanes, firstVisibleRow, realRowCount, visibleRowIds, filterMetadata } = args;
// These come from settings, which an untrusted workspace can set to any JSON value.
// Sanitize them so they can't break out of the CSS or HTML they're interpolated into.
const fontFamily = CsvEditorController.sanitizeFontFamily(args.fontFamily);
const fontSize = CsvEditorController.normalizeFontSize(args.fontSize) ?? 14;
const cellPadding = CsvEditorController.normalizeCellPadding(args.cellPadding);
const themeKind = vscode.window.activeColorTheme.kind;
const isDark = themeKind === vscode.ColorThemeKind.Dark || themeKind === vscode.ColorThemeKind.HighContrast;
const scriptUri = webview.asWebviewUri(
Expand Down Expand Up @@ -2618,7 +2623,7 @@ class CsvEditorController {
--csv-menu-background: #2d2d2d;
--csv-menu-hover-background: #3d3d3d;
}
body { font-family: ${this.escapeCss(fontFamily)}; font-size: ${fontSize}px; margin: 0; padding: 0; user-select: none; }
body { font-family: ${fontFamily}; font-size: ${fontSize}px; margin: 0; padding: 0; user-select: none; }
.table-container { overflow: auto; height: 100vh; }
table { border-collapse: collapse; width: max-content; }
th, td { padding: ${cellPadding}px 8px; border: 1px solid var(--csv-table-border, ${isDark ? '#555' : '#ccc'}); font-size: inherit; }
Expand Down Expand Up @@ -2647,7 +2652,7 @@ class CsvEditorController {
display: none;
align-items: stretch;
color: #d4d4d4;
font-family: ${this.escapeCss(fontFamily)};
font-family: ${fontFamily};
font-size: inherit;
}
#findReplaceWidget.open { display: flex; }
Expand Down Expand Up @@ -2803,7 +2808,7 @@ class CsvEditorController {
font-size: inherit;
}
#findReplaceWidget .fr-overflow-item:hover { background: rgba(255,255,255,0.05); }
#contextMenu { position: fixed; display: none; width: max-content; box-sizing: border-box; overflow: auto; overflow-wrap: anywhere; background: var(--csv-menu-background, ${isDark ? '#2d2d2d' : '#ffffff'}); border: 1px solid var(--csv-table-border, ${isDark ? '#555' : '#ccc'}); z-index: 10000; font-family: ${this.escapeCss(fontFamily)}; font-size: inherit; }
#contextMenu { position: fixed; display: none; width: max-content; box-sizing: border-box; overflow: auto; overflow-wrap: anywhere; background: var(--csv-menu-background, ${isDark ? '#2d2d2d' : '#ffffff'}); border: 1px solid var(--csv-table-border, ${isDark ? '#555' : '#ccc'}); z-index: 10000; font-family: ${fontFamily}; font-size: inherit; }
#contextMenu div { padding: 4px 12px; cursor: pointer; }
#contextMenu div:hover { background: var(--csv-menu-hover-background, ${isDark ? '#3d3d3d' : '#eeeeee'}); }

Expand Down Expand Up @@ -3045,9 +3050,25 @@ class CsvEditorController {
return ` title="${this.escapeHtml(text)}"`;
}

private escapeCss(text: string): string {
// conservative; ok for font-family lists
return text.replace(/[\\"]/g, m => (m === '\\' ? '\\\\' : '\\"'));
// Font-family lists only need names, commas, spaces and quotes. Drop anything that could end
// the declaration or the <style> element, start a comment or at-rule, or call a CSS function
// such as url().
private static sanitizeFontFamily(value: unknown): string {
const cleaned = typeof value === 'string'
? value.replace(/[\u0000-\u001f\u007f;{}<>\\/()@!]/g, '').trim()
: '';
return cleaned || 'monospace';
}

private static normalizeCellPadding(value: unknown): number {
const parsed =
typeof value === 'number' ? value
: typeof value === 'string' && value.trim() !== '' ? Number(value)
: NaN;
if (!Number.isFinite(parsed) || parsed < 0) {
return 4;
}
return Math.min(Math.round(parsed * 100) / 100, 100);
}

private isDate(value: string): boolean {
Expand Down Expand Up @@ -3835,6 +3856,19 @@ export class CsvEditorProvider implements vscode.CustomTextEditorProvider {
resolveEffectiveFontSize(csvFontSize: unknown, editorFontSize: unknown): number {
return (CsvEditorController as any).resolveEffectiveFontSize(csvFontSize, editorFontSize);
},
sanitizeFontFamily(value: unknown): string {
return (CsvEditorController as any).sanitizeFontFamily(value);
},
normalizeCellPadding(value: unknown): number {
return (CsvEditorController as any).normalizeCellPadding(value);
},
wrapHtml(args: Record<string, unknown>): string {
const c: any = new (CsvEditorController as any)({
extensionPath: '/ext',
extensionUri: { path: '/ext', with(change: Record<string, unknown>) { return { ...this, ...change }; } }
} as any);
return c.wrapHtml(args);
},
hslToHex(h: number, s: number, l: number): string {
const c: any = new (CsvEditorController as any)({} as any);
return c.hslToHex(h, s, l);
Expand Down
103 changes: 103 additions & 0 deletions src/test/workspace-trust.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import assert from 'assert';
import { describe, it } from 'node:test';
import Module from 'module';
import fs from 'fs';
import path from 'path';

// Stub the 'vscode' module so the provider can be imported in plain Node.
const originalRequire = Module.prototype.require;
Module.prototype.require = function (id: string) {
if (id === 'vscode') {
return {
window: { activeColorTheme: { kind: 1 } },
ColorThemeKind: { Light: 2, Dark: 1, HighContrast: 3, HighContrastLight: 4 },
Uri: { file: (p: string) => ({ fsPath: p, toString: () => `file://${p}` }) }
} as any;
}
return originalRequire.apply(this, arguments as any);
};

import { CsvEditorProvider } from '../CsvEditorProvider';

const t = CsvEditorProvider.__test;

// Settings an untrusted workspace's .vscode/settings.json could supply.
const hostileFont = 'x; } </style><img src="https://evil.example/leak"><style> body {';
const hostilePadding = '0px; } </style><img src="https://evil.example/leak"><style> td {';

function render(fontFamily: unknown, cellPadding: unknown, fontSize: unknown = 14): string {
return t.wrapHtml({
webview: { cspSource: 'vscode-resource:', asWebviewUri: (u: any) => u },
nonce: 'n0nce',
fontFamily,
fontSize,
cellPadding,
separator: ',',
tableHtml: '<table></table>',
chunksJson: '[]',
extraColumnColorCss: '',
nextChunkStart: -1,
hasRemoteChunks: false,
mouseWheelZoomEnabled: true,
mouseWheelZoomInvert: false,
headerEnabled: true,
columnSizes: {},
frozenPanes: { rows: 0, columns: 0 },
firstVisibleRow: 0,
realRowCount: 0,
visibleRowIds: [],
filterMetadata: { filters: [] }
});
}

describe('Workspace Trust (Restricted Mode)', () => {
it('declares support for untrusted workspaces in package.json', () => {
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8'));
assert.strictEqual(pkg.capabilities?.untrustedWorkspaces?.supported, true);
});

it('sanitizeFontFamily keeps ordinary font lists', () => {
assert.strictEqual(t.sanitizeFontFamily('"Fira Code", Menlo, monospace'), '"Fira Code", Menlo, monospace');
assert.strictEqual(t.sanitizeFontFamily("'Noto Sans JP', sans-serif"), "'Noto Sans JP', sans-serif");
});

it('sanitizeFontFamily strips characters that can escape the declaration', () => {
const out = t.sanitizeFontFamily(hostileFont);
for (const ch of [';', '{', '}', '<', '>', '/', '(', ')']) {
assert.ok(!out.includes(ch), `found ${ch} in ${out}`);
}
assert.ok(!t.sanitizeFontFamily('x, url(https://evil.example)').includes('('));
assert.ok(!t.sanitizeFontFamily('x\n@import "https://evil.example"').includes('@'));
});

it('sanitizeFontFamily falls back for non-strings and empty results', () => {
assert.strictEqual(t.sanitizeFontFamily(undefined), 'monospace');
assert.strictEqual(t.sanitizeFontFamily(42), 'monospace');
assert.strictEqual(t.sanitizeFontFamily(';{}'), 'monospace');
});

it('normalizeCellPadding accepts only finite, non-negative numbers', () => {
assert.strictEqual(t.normalizeCellPadding(6), 6);
assert.strictEqual(t.normalizeCellPadding('8'), 8);
assert.strictEqual(t.normalizeCellPadding(1e9), 100);
for (const bad of [hostilePadding, '', -1, NaN, Infinity, null, undefined, true, {}]) {
assert.strictEqual(t.normalizeCellPadding(bad), 4, `for ${String(bad)}`);
}
});

it('wrapHtml cannot be broken out of by hostile settings', () => {
const html = render(hostileFont, hostilePadding, '14px; } </style><img src=x>');
assert.ok(!html.includes('https://evil.example'), 'injected URL reached the page');
assert.ok(!html.includes('<img'), 'injected element reached the page');
assert.strictEqual(html.match(/<\/style>/g)?.length, html.match(/<style/g)?.length);
assert.ok(html.includes('padding: 4px 8px'));
assert.ok(html.includes('font-size: 14px'));
});

it('wrapHtml keeps legitimate settings', () => {
const html = render('"Fira Code", monospace', 6, 16);
assert.ok(html.includes('font-family: "Fira Code", monospace;'));
assert.ok(html.includes('padding: 6px 8px'));
assert.ok(html.includes('font-size: 16px'));
});
});