xss

typescript
import { defaultSchema, type Schema } from 'hast-util-sanitize';

export const markdownSchema: Schema = {
  ...defaultSchema,
  attributes: {
    ...defaultSchema.attributes,

Safe markdown rendering (remark + rehype)

markdown security remark
by codesnips 3 tabs
ruby
Rails.application.config.content_security_policy do |policy|
  policy.default_src :self
  policy.font_src    :self, :https, :data
  policy.img_src     :self, :https, :data, "https://cdn.example.com"
  policy.object_src  :none
  policy.script_src  :self, :https

Content Security Policy (CSP) Starter

rails security csp
by codesnips 3 tabs
erb
<h1><%= @post.title %></h1>
<p><%= @post.author_name %></p>

<%# Only sanitized rich text should be rendered as HTML %>
<div class="prose"><%= sanitize(@post.body_html, tags: %w[p a ul ol li strong em code], attributes: %w[href]) %></div>

Cross site scripting defense with output encoding and CSP

xss content-security-policy owasp
by Kai Nakamura 3 tabs
typescript
import { JSDOM } from 'jsdom';
import createDOMPurify, { DOMPurifyI } from 'dompurify';

const { window } = new JSDOM('');
const DOMPurify: DOMPurifyI = createDOMPurify(window as unknown as Window);

Sanitize user HTML safely (DOMPurify + JSDOM)

security html dompurify
by codesnips 2 tabs
ruby
require "loofah"

class HtmlSanitizer
  ALLOWED_TAGS  = %w[p br a strong em ul ol li blockquote code pre h2 h3].freeze
  ALLOWED_ATTRS = %w[href title].freeze
  SAFE_SCHEMES  = %w[http https mailto].freeze

Safer HTML Sanitization Pipeline

rails security xss
by codesnips 4 tabs
javascript
// 1. DANGEROUS: Never use innerHTML with user input
const userInput = '<img src=x onerror="alert('XSS')">';

// WRONG - vulnerable to XSS
document.getElementById('output').innerHTML = userInput;

Front-end security - XSS and CSRF prevention

security xss csrf
by Alex Chang 1 tab
typescript
import { randomBytes } from 'crypto';
import { Request, Response, NextFunction } from 'express';

interface CspOptions {
  reportOnly?: boolean;
  reportUri?: string;

Content Security Policy headers (defense-in-depth)

security express csp
by codesnips 3 tabs