secure webview resources.

This commit is contained in:
Peng Lyu 2018-05-19 14:12:50 -07:00
parent 33007b4bae
commit 8f429963e4
2 changed files with 91 additions and 139 deletions

View File

@ -1,159 +1,117 @@
import * as path from 'path'; import * as path from 'path';
import * as vscode from 'vscode'; import * as vscode from 'vscode';
const cats = {
'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif',
'Testing Cat': 'https://media.giphy.com/media/3oriO0OEd9QIDdllqo/giphy.gif'
};
export function activate(context: vscode.ExtensionContext) { export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.commands.registerCommand('catCoding.start', () => { context.subscriptions.push(vscode.commands.registerCommand('react-webview.start', () => {
CatCodingPanel.createOrShow(context.extensionPath); ReactPanel.createOrShow(context.extensionPath);
})); }));
context.subscriptions.push(vscode.commands.registerCommand('catCoding.doRefactor', () => {
if (CatCodingPanel.currentPanel) {
CatCodingPanel.currentPanel.doRefactor();
}
}));
} }
/** /**
* Manages cat coding webview panels * Manages react webview panels
*/ */
class CatCodingPanel { class ReactPanel {
/** /**
* Track the currently panel. Only allow a single panel to exist at a time. * Track the currently panel. Only allow a single panel to exist at a time.
*/ */
public static currentPanel: CatCodingPanel | undefined; public static currentPanel: ReactPanel | undefined;
private static readonly viewType = 'catCoding'; private static readonly viewType = 'react';
private readonly _panel: vscode.WebviewPanel; private readonly _panel: vscode.WebviewPanel;
private readonly _extensionPath: string; private readonly _extensionPath: string;
private _disposables: vscode.Disposable[] = []; private _disposables: vscode.Disposable[] = [];
public static createOrShow(extensionPath: string) { public static createOrShow(extensionPath: string) {
const column = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined; const column = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined;
// If we already have a panel, show it. // If we already have a panel, show it.
// Otherwise, create a new panel. // Otherwise, create a new panel.
if (CatCodingPanel.currentPanel) { if (ReactPanel.currentPanel) {
CatCodingPanel.currentPanel._panel.reveal(column); ReactPanel.currentPanel._panel.reveal(column);
} else { } else {
CatCodingPanel.currentPanel = new CatCodingPanel(extensionPath, column || vscode.ViewColumn.One); ReactPanel.currentPanel = new ReactPanel(extensionPath, column || vscode.ViewColumn.One);
} }
} }
private constructor(extensionPath: string, column: vscode.ViewColumn) { private constructor(extensionPath: string, column: vscode.ViewColumn) {
this._extensionPath = extensionPath; this._extensionPath = extensionPath;
// Create and show a new webview panel // Create and show a new webview panel
this._panel = vscode.window.createWebviewPanel(CatCodingPanel.viewType, "Cat Coding", column, { this._panel = vscode.window.createWebviewPanel(ReactPanel.viewType, "React", column, {
// Enable javascript in the webview // Enable javascript in the webview
enableScripts: true, enableScripts: true,
// And restric the webview to only loading content from our extension's `media` directory. // And restric the webview to only loading content from our extension's `media` directory.
localResourceRoots: [ localResourceRoots: [
vscode.Uri.file(path.join(this._extensionPath, 'media')),
vscode.Uri.file(path.join(this._extensionPath, 'build')) vscode.Uri.file(path.join(this._extensionPath, 'build'))
] ]
}); });
// Set the webview's initial html content
this._panel.webview.html = this._getHtmlForWebview();
// Set the webview's initial html content // Listen for when the panel is disposed
this._update(); // This happens when the user closes the panel or when the panel is closed programatically
this._panel.onDidDispose(() => this.dispose(), null, this._disposables);
// Listen for when the panel is disposed // Handle messages from the webview
// This happens when the user closes the panel or when the panel is closed programatically this._panel.webview.onDidReceiveMessage(message => {
this._panel.onDidDispose(() => this.dispose(), null, this._disposables); switch (message.command) {
case 'alert':
vscode.window.showErrorMessage(message.text);
return;
}
}, null, this._disposables);
}
// Update the content based on view changes public doRefactor() {
this._panel.onDidChangeViewState(e => { // Send a message to the webview webview.
if (this._panel.visible) { // You can send any JSON serializable data.
this._update() this._panel.webview.postMessage({ command: 'refactor' });
} }
}, null, this._disposables);
// Handle messages from the webview public dispose() {
this._panel.webview.onDidReceiveMessage(message => { ReactPanel.currentPanel = undefined;
switch (message.command) {
case 'alert':
vscode.window.showErrorMessage(message.text);
return;
}
}, null, this._disposables);
}
public doRefactor() { // Clean up our resources
// Send a message to the webview webview. this._panel.dispose();
// You can send any JSON serializable data.
this._panel.webview.postMessage({ command: 'refactor' });
}
public dispose() { while (this._disposables.length) {
CatCodingPanel.currentPanel = undefined; const x = this._disposables.pop();
if (x) {
x.dispose();
}
}
}
// Clean up our resources private _getHtmlForWebview() {
this._panel.dispose();
while (this._disposables.length) { // Local path to main script run in the webview
const x = this._disposables.pop(); const scriptPathOnDisk = vscode.Uri.file(path.join(this._extensionPath, 'build', 'static', 'js', 'main.6883c34d.js'));
if (x) {
x.dispose();
}
}
}
private _update() { // And the uri we use to load this script in the webview
// Vary the webview's content based on where it is located in the editor.
switch (this._panel.viewColumn) {
case vscode.ViewColumn.Two:
this._updateForCat('Compiling Cat');
return;
case vscode.ViewColumn.Three:
this._updateForCat('Testing Cat');
return;
case vscode.ViewColumn.One:
default:
this._updateForCat('Coding Cat');
return;
}
}
private _updateForCat(catName: keyof typeof cats) {
this._panel.title = catName;
this._panel.webview.html = this._getHtmlForWebview(cats[catName]);
}
private _getHtmlForWebview(catGif: string) {
// Local path to main script run in the webview
const scriptPathOnDisk = vscode.Uri.file(path.join(this._extensionPath, 'build', 'static', 'js', 'main.6883c34d.js'));
// And the uri we use to load this script in the webview
const scriptUri = scriptPathOnDisk.with({ scheme: 'vscode-resource' }); const scriptUri = scriptPathOnDisk.with({ scheme: 'vscode-resource' });
const stylePathOnDisk = vscode.Uri.file(path.join(this._extensionPath, 'build', 'static', 'css', 'main.29266132.css')); const stylePathOnDisk = vscode.Uri.file(path.join(this._extensionPath, 'build', 'static', 'css', 'main.29266132.css'));
// And the uri we use to load this style in the webview // And the uri we use to load this style in the webview
const styleUri = stylePathOnDisk.with({ scheme: 'vscode-resource' }); const styleUri = stylePathOnDisk.with({ scheme: 'vscode-resource' });
const baseStyles = `<link rel="stylesheet" type="text/css" href="${styleUri}">`; const baseStyles = `<link rel="stylesheet" type="text/css" href="${styleUri}">`;
// Use a nonce to whitelist which scripts can be run // Use a nonce to whitelist which scripts can be run
// const nonce = getNonce(); const nonce = getNonce();
return `<!DOCTYPE html> return `<!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"> <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta name="theme-color" content="#000000"> <meta name="theme-color" content="#000000">
<title>React App</title> <title>React App</title>
${baseStyles} ${baseStyles}
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src vscode-resource: https:; script-src 'nonce-${nonce}';style-src vscode-resource: 'unsafe-inline' http: https: data:;">
<base href="${vscode.Uri.file(path.join(this._extensionPath, 'build')).with({ scheme: 'vscode-resource' })}/"> <base href="${vscode.Uri.file(path.join(this._extensionPath, 'build')).with({ scheme: 'vscode-resource' })}/">
</head> </head>
@ -161,17 +119,17 @@ class CatCodingPanel {
<noscript>You need to enable JavaScript to run this app.</noscript> <noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div> <div id="root"></div>
<script src="${scriptUri}"></script> <script nonce="${nonce}" src="${scriptUri}"></script>
</body> </body>
</html>`; </html>`;
} }
} }
// function getNonce() { function getNonce() {
// let text = ""; let text = "";
// const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// for (let i = 0; i < 32; i++) { for (let i = 0; i < 32; i++) {
// text += possible.charAt(Math.floor(Math.random() * possible.length)); text += possible.charAt(Math.floor(Math.random() * possible.length));
// } }
// return text; return text;
// } }

View File

@ -6,21 +6,15 @@
}, },
"publisher": "rebornix", "publisher": "rebornix",
"activationEvents": [ "activationEvents": [
"onCommand:catCoding.start", "onCommand:react-webview.start"
"onCommand:catCoding.doRefactor"
], ],
"main": "./ext-src/extension.js", "main": "./ext-src/extension.js",
"contributes": { "contributes": {
"commands": [ "commands": [
{ {
"command": "catCoding.start", "command": "react-webview.start",
"title": "Start cat coding session", "title": "Start react webview",
"category": "Cat Coding" "category": "React"
},
{
"command": "catCoding.doRefactor",
"title": "Do some refactoring",
"category": "Cat Coding"
} }
] ]
}, },