Files
vscode/extensions/markdown-language-features/preview-src/csp.ts
Matt Bierner 7df46143a1 Experiment with switching markdown extension to use native privates
Let's try this out with one extension to start
2026-03-10 23:13:16 -07:00

71 lines
2.0 KiB
TypeScript

/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MessagePoster } from './messaging';
import { SettingsManager } from './settings';
import { getStrings } from './strings';
/**
* Shows an alert when there is a content security policy violation.
*/
export class CspAlerter {
#didShow = false;
#didHaveCspWarning = false;
#messaging?: MessagePoster;
readonly #settingsManager: SettingsManager;
constructor(
settingsManager: SettingsManager,
) {
this.#settingsManager = settingsManager;
document.addEventListener('securitypolicyviolation', () => {
this.#onCspWarning();
});
window.addEventListener('message', (event) => {
if (event?.data && event.data.name === 'vscode-did-block-svg') {
this.#onCspWarning();
}
});
}
public setPoster(poster: MessagePoster) {
this.#messaging = poster;
if (this.#didHaveCspWarning) {
this.#showCspWarning();
}
}
#onCspWarning() {
this.#didHaveCspWarning = true;
this.#showCspWarning();
}
#showCspWarning() {
const strings = getStrings();
const settings = this.#settingsManager.settings;
if (this.#didShow || settings.disableSecurityWarnings || !this.#messaging) {
return;
}
this.#didShow = true;
const notification = document.createElement('a');
notification.innerText = strings.cspAlertMessageText;
notification.setAttribute('id', 'code-csp-warning');
notification.setAttribute('title', strings.cspAlertMessageTitle);
notification.setAttribute('role', 'button');
notification.setAttribute('aria-label', strings.cspAlertMessageLabel);
notification.onclick = () => {
this.#messaging!.postMessage('showPreviewSecuritySelector', { source: settings.source });
};
document.body.appendChild(notification);
}
}