The problem: when you post-process generated SVG, an optimizer can reorder or merge elements, so a buried <script> or <foreignObject> can come out the other side intact, or land where a later check does not look.

The code

In Rune, the order is fixed in one function:

export function postProcessSvg(svg: string, options: PostProcessOptions): string {
  let result = svg;

  // Stage 0: sanitization always runs, regardless of options
  result = sanitizeSvg(result);

  // Stage 1: optimization
  if (options.optimize) result = optimizeSvg(result);

  // Stage 2: CSS classes, Stage 3: metadata
  if (options.css_classes) result = injectCssClasses(result);
  if (options.metadata && Object.keys(options.metadata).length > 0) {
    result = injectMetadata(result, options.metadata);
  }
  return result;
}

How it works

Sanitizing always runs first, then optimizing, then CSS classes and metadata, so every later step works on a clean tree and none of them has to be written with hostile input in mind. The sanitizer errs on the side of removing content. It strips:

  1. <script> elements, including namespaced, self-closing and unclosed forms.
  2. <foreignObject> elements.
  3. javascript: links, and data: URIs other than plain raster images, after decoding entities so &#106;avascript: does not slip through.
  4. Inline on* event handlers.
  5. <use> elements that point at external URLs.

Nothing it removes would render in a normal diagram anyway. It is idempotent and covered by 126 tests, including adversarial fixtures. The optimizing stage uses SVGO.

View the source

⌃