Enforce Content-Security-Policy (CSP) in Obsidian, Desktop, Web apps

Prevent XSS attacks by enforcing Content-Security-Policy (CSP) in apps.
Do not allow loading images, other assets from untrusted domains.

- Only allow loading assets from trusted domains
  like 'self', khoj.dev, ipapi for geolocation, google (fonts, img)
  - images from khoj domain, google (for profile pic)
  - assets from khoj domain
  - Do not allow iframe src
  - Allow unsafe-inline script and styles for now as markdown-it escapes html
    in user, khoj chat

- Add hostURL to CSP of the Desktop, Obsidian apps
  Given web client is served by khoj server, it doesn't need to
  explicitly allow for khoj.dev domain. So if user self-hosting, it'll
  automatically allow the domain in the CSP (via 'self')

  Whereas the Obsidian, Desktop clients allow configure the server URL.
  Note *switching server URL breaks CSP until app is reloaded*
This commit is contained in:
Debanjum Singh Solanky
2024-02-21 03:12:00 +05:30
parent 179c70dba8
commit 9f80c2ab76
3 changed files with 53 additions and 1 deletions

View File

@@ -80,6 +80,20 @@ export class KhojChatView extends KhojPaneView {
super.onOpen();
// Construct Content Security Policy
let defaultDomains = `'self' ${this.setting.khojUrl} https://app.khoj.dev https://assets.khoj.dev`;
const defaultSrc = `default-src ${defaultDomains};`;
const scriptSrc = `script-src ${defaultDomains} 'unsafe-inline';`;
const connectSrc = `connect-src ${this.setting.khojUrl} https://ipapi.co/json;`;
const styleSrc = `style-src ${defaultDomains} 'unsafe-inline';`;
const imgSrc = `img-src ${defaultDomains} data: https://*.khoj.dev https://*.googleusercontent.com;`;
const childSrc = `child-src 'none';`;
const objectSrc = `object-src 'none';`;
const csp = `${defaultSrc} ${scriptSrc} ${connectSrc} ${styleSrc} ${imgSrc} ${childSrc} ${objectSrc}`;
// Add CSP meta tag to the Khoj Chat modal
document.head.createEl("meta", { attr: { "http-equiv": "Content-Security-Policy", "content": `${csp}` } });
// Create area for chat logs
let chatBodyEl = contentEl.createDiv({ attr: { id: "khoj-chat-body", class: "khoj-chat-body" } });