A platform for community discussion. Free, open, simple.
FEATURE: Modernize Graphviz implementation (#40720)
David Taylorbe74f5ff1cb1
diff --git a/db/structure.sql b/db/structure.sqlindex 21bf0feacdf..ac4aaee428b 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -21913,6 +21913,7 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groupsSET search_path TO "$user", public;INSERT INTO "schema_migrations" (version) VALUES+('20260610075829'),('20260609050938'),('20260607161322'),('20260604052235'),diff --git a/plugins/discourse-graphviz/assets/javascripts/discourse-markdown/discourse-graphviz.js b/plugins/discourse-graphviz/assets/javascripts/discourse-markdown/discourse-graphviz.jsindex d02526877b1..8747316aa13 100644--- a/plugins/discourse-graphviz/assets/javascripts/discourse-markdown/discourse-graphviz.js+++ b/plugins/discourse-graphviz/assets/javascripts/discourse-markdown/discourse-graphviz.js@@ -3,11 +3,7 @@ export function setup(helper) {return;}- helper.allowList([- "div.graphviz",- "div.graphviz.is-loading",- "div.graphviz-svg",- ]);+ helper.allowList(["div.graphviz", "div.graphviz.is-loading"]);helper.registerOptions((opts, siteSettings) => {opts.features.graphviz = siteSettings.discourse_graphviz_enabled;@@ -28,14 +24,7 @@ export function setup(helper) {? `data-engine='${inputEngine}'`: "data-engine='dot'";- let svgOnly = "";- if (tagInfo.attrs.svg === "true") {- svgOnly = " graphviz-svg";- } else if (tagInfo.attrs.svg === "false") {- svgOnly = " graphviz-no-svg";- }-- token.content = `<div class="graphviz is-loading${svgOnly}" ${engine}>\n${escaped}\n</div>\n`;+ token.content = `<div class="graphviz is-loading" ${engine}>\n${escaped}\n</div>\n`;return true;},diff --git a/plugins/discourse-graphviz/assets/javascripts/discourse/api-initializers/discourse-graphviz.js b/plugins/discourse-graphviz/assets/javascripts/discourse/api-initializers/discourse-graphviz.jsnew file mode 100644index 00000000000..2bf3467e1ed--- /dev/null+++ b/plugins/discourse-graphviz/assets/javascripts/discourse/api-initializers/discourse-graphviz.js@@ -0,0 +1,38 @@+import { apiInitializer } from "discourse/lib/api";+import GraphvizInline from "../components/graphviz-inline";++function applyGraphviz(element, helper) {+ const src = element.textContent.trim();+ if (!src) {+ return;+ }++ const wrapper = document.createElement("div");+ wrapper.classList.add("graphviz-wrapper");+ helper.renderGlimmer(wrapper, GraphvizInline, {+ src,+ engine: element.dataset.engine,+ });+ element.replaceWith(wrapper);+}++export default apiInitializer((api) => {+ api.decorateCookedElement((element, helper) => {+ element+ .querySelectorAll("div.graphviz")+ .forEach((graph) => applyGraphviz(graph, helper));+ });++ api.addComposerToolbarPopupMenuOption({+ icon: "diagram-project",+ label: "graphviz.composer_title",+ action: (toolbarEvent) => {+ toolbarEvent.applySurround(+ "\n[graphviz]\n",+ "\n[/graphviz]\n",+ "graphviz_sample",+ { multiline: false }+ );+ },+ });+});diff --git a/plugins/discourse-graphviz/assets/javascripts/discourse/components/graphviz-diagram.gjs b/plugins/discourse-graphviz/assets/javascripts/discourse/components/graphviz-diagram.gjsnew file mode 100644index 00000000000..97f2a744d9e--- /dev/null+++ b/plugins/discourse-graphviz/assets/javascripts/discourse/components/graphviz-diagram.gjs@@ -0,0 +1,46 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import DAsyncContent from "discourse/ui-kit/d-async-content";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import { generateGraph } from "../lib/render-graphviz";++export default class GraphvizDiagram extends Component {+ @tracked zoomed = false;++ @action+ loadGraph() {+ return generateGraph(this.args.src, this.args.engine);+ }++ @action+ toggleZoom(event) {+ event.preventDefault();+ if (!this.args.enableZoom) {+ return;+ }+ this.zoomed = !this.zoomed;+ }++ <template>+ {{! eslint-disable ember/template-no-invalid-interactive }}+ <div+ class={{dConcatClass+ "graphviz-diagram"+ (if @enableZoom "zoomable")+ (if this.zoomed "zoomed")+ }}+ {{on "click" this.toggleZoom}}+ >+ <DAsyncContent @asyncData={{this.loadGraph}}>+ <:content as |svg|>+ {{svg}}+ </:content>+ <:error as |error|>+ <div class="graph-error">{{error.message}}</div>+ </:error>+ </DAsyncContent>+ </div>+ </template>+}diff --git a/plugins/discourse-graphviz/assets/javascripts/discourse/components/graphviz-fullscreen.gjs b/plugins/discourse-graphviz/assets/javascripts/discourse/components/graphviz-fullscreen.gjsnew file mode 100644index 00000000000..0a096163335--- /dev/null+++ b/plugins/discourse-graphviz/assets/javascripts/discourse/components/graphviz-fullscreen.gjs@@ -0,0 +1,14 @@+import DModal from "discourse/ui-kit/d-modal";+import GraphvizDiagram from "./graphviz-diagram";++const GraphvizFullscreen = <template>+ <DModal @closeModal={{@closeModal}} class="graphviz-fullscreen">+ <GraphvizDiagram+ @src={{@model.src}}+ @engine={{@model.engine}}+ @enableZoom={{true}}+ />+ </DModal>+</template>;++export default GraphvizFullscreen;diff --git a/plugins/discourse-graphviz/assets/javascripts/discourse/components/graphviz-inline.gjs b/plugins/discourse-graphviz/assets/javascripts/discourse/components/graphviz-inline.gjsnew file mode 100644index 00000000000..ed6cd6ba7cb--- /dev/null+++ b/plugins/discourse-graphviz/assets/javascripts/discourse/components/graphviz-inline.gjs@@ -0,0 +1,32 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { service } from "@ember/service";+import DButton from "discourse/ui-kit/d-button";+import GraphvizDiagram from "./graphviz-diagram";+import GraphvizFullscreen from "./graphviz-fullscreen";++export default class GraphvizInline extends Component {+ @service modal;++ @action+ fullscreen() {+ this.modal.show(GraphvizFullscreen, {+ model: {+ src: this.args.data.src,+ engine: this.args.data.engine,+ },+ });+ }++ <template>+ <div class="graphviz-diagram-controls">+ <DButton+ @icon="discourse-expand"+ class="btn-flat graphviz-fullscreen-button"+ @action={{this.fullscreen}}+ />+ </div>++ <GraphvizDiagram @src={{@data.src}} @engine={{@data.engine}} />+ </template>+}diff --git a/plugins/discourse-graphviz/assets/javascripts/discourse/lib/render-graphviz.js b/plugins/discourse-graphviz/assets/javascripts/discourse/lib/render-graphviz.jsnew file mode 100644index 00000000000..a08d6239a52--- /dev/null+++ b/plugins/discourse-graphviz/assets/javascripts/discourse/lib/render-graphviz.js@@ -0,0 +1,52 @@+import { trustHTML } from "@ember/template";+import { hrefAllowed } from "pretty-text/sanitizer";+import loadScript from "discourse/lib/load-script";++let vizPromise;++function loadViz() {+ vizPromise ??= loadScript(+ "/plugins/discourse-graphviz/javascripts/viz-3.0.1.js"+ );+ return vizPromise;+}++// viz.js does not sanitize its output, so strip dangerous links and attributes+// before the SVG is injected into the page.+export function sanitizeGraphvizSvg(svg) {+ svg.querySelectorAll("script, foreignObject").forEach((el) => el.remove());++ svg.querySelectorAll("*").forEach((el) => {+ for (const attr of [...el.attributes]) {+ const name = attr.name.toLowerCase();+ if (name.startsWith("on") || /javascript:/i.test(attr.value)) {+ el.removeAttribute(attr.name);+ }+ }+ });++ svg.querySelectorAll("a").forEach((anchor) => {+ const href =+ anchor.getAttribute("href") || anchor.getAttribute("xlink:href");+ // Allow only http/https and relative/anchor links; drop mailto, which hrefAllowed otherwise permits.+ if (href && (!hrefAllowed(href) || /^\s*mailto:/i.test(href))) {+ anchor.replaceWith(...anchor.childNodes);+ }+ });++ return svg;+}++export async function generateGraph(source, engine) {+ await loadViz();++ /* global vizRenderStringSync */+ const rendered = vizRenderStringSync(source, { format: "svg", engine });++ const doc = new DOMParser().parseFromString(rendered, "image/svg+xml");+ if (doc.querySelector("parsererror")) {+ throw new Error(doc.querySelector("parsererror").textContent);+ }++ return trustHTML(sanitizeGraphvizSvg(doc.documentElement).outerHTML);+}diff --git a/plugins/discourse-graphviz/assets/javascripts/initializers/discourse-graphviz.js b/plugins/discourse-graphviz/assets/javascripts/initializers/discourse-graphviz.jsdeleted file mode 100644index 20c31aee642..00000000000--- a/plugins/discourse-graphviz/assets/javascripts/initializers/discourse-graphviz.js+++ /dev/null@@ -1,69 +0,0 @@-/* eslint-disable ember/no-jquery */-import $ from "jquery";-import { escape } from "pretty-text/sanitizer";-import discourseDebounce from "discourse/lib/debounce";-import loadScript from "discourse/lib/load-script";-import { withPluginApi } from "discourse/lib/plugin-api";--export default {- name: "discourse-graphviz",-- renderGraphs($containers) {- $containers.each((_, container) => {- const $container = $(container);-- // if the container content has not yet been replaced- // do nothing- if (!$container.find("svg").length) {- this.renderGraph($container);- }- });- },-- renderGraph($container) {- const graphDefinition = $container.text().trim();- const engine = $container.attr("data-engine");-- const $spinner = $("<div class='spinner tiny'></div>");- $container.html($spinner);-- loadScript("/plugins/discourse-graphviz/javascripts/viz-3.0.1.js").then(- () => {- $container.removeClass("is-loading");-- try {- /* global vizRenderStringSync */- const svgChart = vizRenderStringSync(graphDefinition, {- format: "svg",- engine,- });-- $container.html(svgChart);- } catch (e) {- const $error = $(- `<div class='graph-error'>${escape(e.message)}</div>`- );- $container.html($error);- }- }- );- },-- initialize(container) {- const siteSettings = container.lookup("service:site-settings");-- if (siteSettings.discourse_graphviz_enabled) {- withPluginApi((api) => {- api.decorateCooked(- ($elem) => {- const $graphviz = $elem.find(".graphviz");- if ($graphviz.length) {- discourseDebounce(this, this.renderGraphs, $graphviz, 200);- }- },- { id: "graphviz" }- );- });- }- },-};diff --git a/plugins/discourse-graphviz/assets/stylesheets/common/graphviz.scss b/plugins/discourse-graphviz/assets/stylesheets/common/graphviz.scssindex 507fcd10a6d..1334a9e0bcd 100644--- a/plugins/discourse-graphviz/assets/stylesheets/common/graphviz.scss+++ b/plugins/discourse-graphviz/assets/stylesheets/common/graphviz.scss@@ -1,22 +1,92 @@-div.graphviz {- svg {- max-width: 100%;+// Reserve the diagram box up-front (placeholder and rendered wrapper alike) so+// the layout does not shift when the client renders the graph.+div.graphviz.is-loading,+.graphviz-wrapper {+ margin: 1em 0;+ aspect-ratio: 16 / 9;+ background-color: var(--primary-50);++ &:first-child {+ margin-top: 0;}+}++// Hide the raw DOT source until the client replaces the placeholder.+div.graphviz.is-loading {+ font-size: 0;+}++.graphviz-wrapper {+ position: relative;- &.is-loading {- padding: 2em;- background: var(--primary-very-low);+ .graphviz-diagram-controls {+ position: absolute;+ display: flex;+ top: 0;+ right: 0;+ user-select: none;+ z-index: 1;}- .graph-error {- padding: 2em;- background-color: var(--danger-low);- margin: 0;- color: var(--danger);- text-align: center;+ html.no-touch & .graphviz-diagram-controls {+ transition: opacity 0.3s;+ opacity: 0;+ }++ html.no-touch &:hover .graphviz-diagram-controls {+ opacity: 1;}}-svg.graphviz-svg-render {- max-width: 100%;+.graphviz-diagram {+ height: 100%;+ width: 100%;+ overflow: auto;+ box-sizing: border-box;+ padding: 1em;+ display: flex;++ // Centre the graph, but fall back to start-alignment (reachable by scroll)+ // when it is larger than the box.+ align-items: safe center;+ justify-content: safe center;++ > * {+ flex: 0 0 auto;+ }+}++.graph-error {+ padding: 2em;+ background-color: var(--danger-low);+ margin: 0;+ color: var(--danger);+ text-align: center;+}++.d-modal.graphviz-fullscreen .d-modal__container {+ width: 100%;+ height: 100%;++ --modal-max-width: 95vw;++ .d-modal__body {+ height: 100%;+ }++ .graphviz-diagram {+ &.zoomable {+ cursor: zoom-in;+ }++ &.zoomed {+ cursor: zoom-out;++ > svg {+ max-width: none;+ width: auto;+ height: 100%;+ }+ }+ }}diff --git a/plugins/discourse-graphviz/config/locales/client.en.yml b/plugins/discourse-graphviz/config/locales/client.en.ymlnew file mode 100644index 00000000000..d83b23a362c--- /dev/null+++ b/plugins/discourse-graphviz/config/locales/client.en.yml@@ -0,0 +1,6 @@+en:+ js:+ graphviz:+ composer_title: "Insert Graphviz graph"+ composer:+ graphviz_sample: "digraph G {\n a -> b;\n b -> c;\n a -> c;\n}"diff --git a/plugins/discourse-graphviz/config/locales/server.en.yml b/plugins/discourse-graphviz/config/locales/server.en.ymlindex 866cb3a581e..daad56df1f0 100644--- a/plugins/discourse-graphviz/config/locales/server.en.yml+++ b/plugins/discourse-graphviz/config/locales/server.en.yml@@ -1,4 +1,3 @@en:site_settings:discourse_graphviz_enabled: "Enable the Graphviz plugin"- graphviz_default_svg: "Default to SVG rendering instead of image rendering, can be customized per graph with `svg=true|false` element."diff --git a/plugins/discourse-graphviz/config/settings.yml b/plugins/discourse-graphviz/config/settings.ymlindex 55f806fa573..e4870b466d3 100644--- a/plugins/discourse-graphviz/config/settings.yml+++ b/plugins/discourse-graphviz/config/settings.yml@@ -2,5 +2,3 @@ plugins:discourse_graphviz_enabled:default: falseclient: true- graphviz_default_svg:- default: truediff --git a/plugins/discourse-graphviz/db/post_migrate/20260610075829_make_graphviz_frontend_only.rb b/plugins/discourse-graphviz/db/post_migrate/20260610075829_make_graphviz_frontend_only.rbnew file mode 100644index 00000000000..379be489b78--- /dev/null+++ b/plugins/discourse-graphviz/db/post_migrate/20260610075829_make_graphviz_frontend_only.rb@@ -0,0 +1,18 @@+# frozen_string_literal: true+class MakeGraphvizFrontendOnly < ActiveRecord::Migration[8.0]+ def up+ execute "DELETE FROM site_settings WHERE name = 'graphviz_default_svg'"++ # Rebake existing graphviz posts so their stored HTML matches the current output.+ execute <<~SQL+ UPDATE posts+ SET baked_version = 0+ WHERE raw LIKE '%[graphviz]%'+ OR raw LIKE '%[graphviz %'+ SQL+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/discourse-graphviz/plugin.rb b/plugins/discourse-graphviz/plugin.rbindex 7e8fef4f3a8..783d24e6a3a 100644--- a/plugins/discourse-graphviz/plugin.rb+++ b/plugins/discourse-graphviz/plugin.rb@@ -11,113 +11,3 @@ enabled_site_setting :discourse_graphviz_enabledregister_svg_icon "diagram-project"register_asset "stylesheets/common/graphviz.scss"--module ::DiscourseGraphviz- ALLOWED_URL_SCHEMES = %w[http https].freeze- ALLOWED_ENGINES = %w[dot neato circo fdp osage twopi].freeze- DEFAULT_ENGINE = "dot"-- RENDER_TIMEOUT_MS = 5_000-- def self.context- context = MiniRacer::Context.new(timeout: RENDER_TIMEOUT_MS)- context.load("#{Rails.root.join("plugins/discourse-graphviz/public/javascripts/viz-3.0.1.js")}")- context- end-- def self.allowed_svg_xpath- @@allowed_svg_xpath ||=- "//*[#{UploadCreator::ALLOWED_SVG_ELEMENTS.map { |e| "name()!='#{e}'" }.join(" and ")}]"- end-- def self.sanitize_svg_links(svg_node)- svg_node- .css("a")- .each do |anchor|- href = anchor["href"] || anchor["xlink:href"]- next unless href-- begin- uri = URI.parse(href)- scheme = uri.scheme&.downcase-- if scheme && !ALLOWED_URL_SCHEMES.include?(scheme)- anchor.replace(anchor.children)- elsif scheme.nil? && href.strip.match?(/\A\s*javascript:/i)- anchor.replace(anchor.children)- end- rescue URI::InvalidURIError- anchor.replace(anchor.children)- end- end- end-end--after_initialize do- on(:before_post_process_cooked) do |doc, post|- if SiteSetting.discourse_graphviz_enabled- doc- .css("div.graphviz")- .each do |graph|- engine = graph.attribute("data-engine")&.value- valid_engine = DiscourseGraphviz::ALLOWED_ENGINES.include?(engine)- engine = DiscourseGraphviz::DEFAULT_ENGINE if !valid_engine- svg_graph =- begin- DiscourseGraphviz.context.call(- "vizRenderStringSync",- graph.children[0].content,- { engine: engine },- )- rescue StandardError- nil- end- next if svg_graph.nil?-- should_use_svg = SiteSetting.graphviz_default_svg- should_use_svg ||= graph.classes.include?("graphviz-svg")- should_use_svg &&= !graph.classes.include?("graphviz-no-svg")-- if should_use_svg- # Changing to Nokogiri::HTML5.fragment returns `nil` for `.css('svg')`- # rubocop:todo Discourse/NoNokogiriHtmlFragment- new_graph_node = Nokogiri::HTML.fragment(svg_graph).css("svg").first- # rubocop:enable Discourse/NoNokogiriHtmlFragment- new_graph_node["class"] = "graphviz-svg-render"- DiscourseGraphviz.sanitize_svg_links(new_graph_node)- new_graph_node.xpath(DiscourseGraphviz.allowed_svg_xpath).remove- graph.replace new_graph_node- next- end-- tmp_svg = Tempfile.new(%w[svgfile .svg])- tmp_png = Tempfile.new(%w[vizgraph- .png])-- tmp_svg.write(svg_graph)- tmp_svg.rewind-- graph_title =- Nokogiri- .parse(svg_graph)- .at("//comment()[contains(.,'Title')]")- &.content- &.match(/Title:\s(?<title>.+)\sPages:/)- &.[](:title)- filename = graph_title != "%0" ? graph_title : File.basename(tmp_png.path)-- Discourse::Utils.execute_command("convert", "-density", "300", tmp_svg.path, tmp_png.path)-- upload = UploadCreator.new(tmp_png, filename).create_for(-1)-- # replace div.graphviz with image node- new_graph_node = Nokogiri::XML::Node.new("img", doc)- new_graph_node["src"] = upload.url- new_graph_node["alt"] = filename- graph.replace new_graph_node-- tmp_svg.close!- tmp_png.close!- end- end- end-enddiff --git a/plugins/discourse-graphviz/spec/integration/graphviz_cooking_spec.rb b/plugins/discourse-graphviz/spec/integration/graphviz_cooking_spec.rbnew file mode 100644index 00000000000..2c239d9b21f--- /dev/null+++ b/plugins/discourse-graphviz/spec/integration/graphviz_cooking_spec.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++RSpec.describe "Graphviz cooking" do+ before { SiteSetting.discourse_graphviz_enabled = true }++ it "emits a placeholder with the engine and escaped source for the client to render" do+ post = Fabricate(:post, raw: <<~MD)+ [graphviz engine=neato]+ digraph G { a -> b }+ [/graphviz]+ MD++ expect(post.cooked).to include("graphviz is-loading")+ expect(post.cooked).to include("neato")+ expect(post.cooked).to include("digraph G { a -> b }")+ end++ it "defaults to the dot engine for unknown engines" do+ post = Fabricate(:post, raw: "[graphviz engine=bogus]\ndigraph { a }\n[/graphviz]")++ expect(post.cooked).to include("dot")+ expect(post.cooked).not_to include("bogus")+ end++ it "does not render when the plugin is disabled" do+ SiteSetting.discourse_graphviz_enabled = false+ post = Fabricate(:post, raw: "[graphviz]\ndigraph { a }\n[/graphviz]")++ expect(post.cooked).not_to include("class=\"graphviz")+ end+enddiff --git a/plugins/discourse-graphviz/spec/integration/graphviz_spec.rb b/plugins/discourse-graphviz/spec/integration/graphviz_spec.rbdeleted file mode 100644index a3c1c337520..00000000000--- a/plugins/discourse-graphviz/spec/integration/graphviz_spec.rb+++ /dev/null@@ -1,123 +0,0 @@-# frozen_string_literal: true--RSpec.describe "Graphviz" do- before do- SiteSetting.discourse_graphviz_enabled = true- SiteSetting.graphviz_default_svg = true- end-- it "strips anchor elements with javascript: URLs to prevent XSS" do- post = Fabricate(:post, raw: <<~MD)- [graphviz]- digraph G { a [label="XSS", URL="javascript:alert(1)"] }- [/graphviz]- MD-- cp = CookedPostProcessor.new(post)- cp.post_process-- expect(cp.html).not_to include("javascript:")- expect(cp.html).to include("graphviz-svg-render")- expect(cp.html).to include("<text")- end-- it "preserves legitimate HTTP and HTTPS URLs" do- post = Fabricate(:post, raw: <<~MD)- [graphviz]- digraph G {- a [label="HTTP", URL="http://example.com"]- b [label="HTTPS", URL="https://example.com"]- a -> b- }- [/graphviz]- MD-- cp = CookedPostProcessor.new(post)- cp.post_process-- expect(cp.html).to include('href="http://example.com"')- expect(cp.html).to include('href="https://example.com"')- expect(cp.html).to include("<a")- end-- it "strips mailto: URLs" do- post = Fabricate(:post, raw: <<~MD)- [graphviz]- digraph G { a [label="Email", URL="mailto:[email protected]"] }- [/graphviz]- MD-- cp = CookedPostProcessor.new(post)- cp.post_process-- expect(cp.html).not_to include("mailto:")- end-- it "strips anchor elements with data: URLs to prevent XSS" do- post = Fabricate(:post, raw: <<~MD)- [graphviz]- digraph G { a [label="Data", URL="data:text/html,<script>alert(1)</script>"] }- [/graphviz]- MD-- cp = CookedPostProcessor.new(post)- cp.post_process-- expect(cp.html).not_to include("data:")- expect(cp.html).not_to include("alert")- end-- it "strips anchor elements with vbscript: URLs to prevent XSS" do- post = Fabricate(:post, raw: <<~MD)- [graphviz]- digraph G { a [label="VBScript", URL="vbscript:alert(1)"] }- [/graphviz]- MD-- cp = CookedPostProcessor.new(post)- cp.post_process-- expect(cp.html).not_to include("vbscript:")- end-- it "strips anchor elements with file: URLs" do- post = Fabricate(:post, raw: <<~MD)- [graphviz]- digraph G { a [label="File", URL="file:///etc/passwd"] }- [/graphviz]- MD-- cp = CookedPostProcessor.new(post)- cp.post_process-- expect(cp.html).not_to include("file:")- end-- it "handles case-insensitive javascript: URLs" do- post = Fabricate(:post, raw: <<~MD)- [graphviz]- digraph G { a [label="XSS", URL="JaVaScRiPt:alert(1)"] }- [/graphviz]- MD-- cp = CookedPostProcessor.new(post)- cp.post_process-- expect(cp.html).not_to include("JaVaScRiPt:")- expect(cp.html).not_to include("javascript:")- end-- it "preserves relative URLs" do- post = Fabricate(:post, raw: <<~MD)- [graphviz]- digraph G { a [label="Relative", URL="/some/path"] }- [/graphviz]- MD-- cp = CookedPostProcessor.new(post)- cp.post_process-- expect(cp.html).to include('href="/some/path"')- expect(cp.html).to include("<a")- end-enddiff --git a/plugins/discourse-graphviz/spec/system/graphviz_spec.rb b/plugins/discourse-graphviz/spec/system/graphviz_spec.rbnew file mode 100644index 00000000000..f691c9377e1--- /dev/null+++ b/plugins/discourse-graphviz/spec/system/graphviz_spec.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++describe "Graphviz" do+ fab!(:admin)+ fab!(:topic)++ let(:topic_page) { PageObjects::Pages::Topic.new }++ before do+ SiteSetting.discourse_graphviz_enabled = true+ sign_in(admin)+ end++ it "renders the graph on the client and opens the fullscreen popup" do+ post = Fabricate(:post, topic:, raw: <<~RAW)+ [graphviz]+ digraph G { a -> b; b -> c; }+ [/graphviz]+ RAW++ topic_page.visit_topic(post.topic)++ expect(page).to have_css(".graphviz-wrapper .graphviz-diagram svg")++ # revealed on hover; visible: :all avoids racing the opacity transition+ find(".graphviz-wrapper").hover+ find(".graphviz-fullscreen-button", visible: :all).click++ expect(page).to have_css(".d-modal.graphviz-fullscreen .graphviz-diagram svg")+ end++ it "shows an error message for invalid syntax" do+ post = Fabricate(:post, topic:, raw: "[graphviz]\ndigraph G { a -> }\n[/graphviz]")++ topic_page.visit_topic(post.topic)++ expect(page).to have_css(".graphviz-wrapper .graph-error")+ end+enddiff --git a/plugins/discourse-graphviz/test/javascripts/unit/lib/render-graphviz-test.js b/plugins/discourse-graphviz/test/javascripts/unit/lib/render-graphviz-test.jsnew file mode 100644index 00000000000..4c3bc70e04e--- /dev/null+++ b/plugins/discourse-graphviz/test/javascripts/unit/lib/render-graphviz-test.js@@ -0,0 +1,71 @@+/* eslint-disable no-script-url */+import { module, test } from "qunit";+import { sanitizeGraphvizSvg } from "discourse/plugins/discourse-graphviz/discourse/lib/render-graphviz";++function sanitize(inner) {+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">${inner}</svg>`;+ const doc = new DOMParser().parseFromString(svg, "image/svg+xml");+ return sanitizeGraphvizSvg(doc.documentElement).outerHTML;+}++module("Unit | Utility | render-graphviz | sanitize", function () {+ test("strips anchors with javascript: URLs", function (assert) {+ const result = sanitize(+ `<a xlink:href="javascript:alert(1)"><text>x</text></a>`+ );+ assert.false(result.includes("javascript:"), "removes javascript scheme");+ assert.true(result.includes("<text"), "keeps the inner content");+ });++ test("strips anchors case-insensitively", function (assert) {+ const result = sanitize(+ `<a xlink:href="JaVaScRiPt:alert(1)"><text>x</text></a>`+ );+ assert.false(/javascript:/i.test(result), "removes mixed-case javascript");+ });++ test("strips data:, vbscript:, file: and mailto: URLs", function (assert) {+ for (const scheme of [+ "data:text/html,alert(1)",+ "vbscript:alert(1)",+ "file:///etc/passwd",+ "mailto:[email protected]",+ ]) {+ const result = sanitize(`<a xlink:href="${scheme}"><text>x</text></a>`);+ assert.true(+ result.includes("<text"),+ `unwraps anchor but keeps content for ${scheme}`+ );+ assert.false(result.includes("<a"), `removes the anchor for ${scheme}`);+ }+ });++ test("preserves http and https URLs", function (assert) {+ for (const url of ["http://example.com", "https://example.com"]) {+ const result = sanitize(`<a xlink:href="${url}"><text>x</text></a>`);+ assert.true(result.includes(url), `keeps ${url}`);+ assert.true(result.includes("<a"), `keeps the anchor for ${url}`);+ }+ });++ test("preserves relative URLs", function (assert) {+ const result = sanitize(`<a xlink:href="/some/path"><text>x</text></a>`);+ assert.true(result.includes("/some/path"), "keeps relative path");+ assert.true(result.includes("<a"), "keeps the anchor");+ });++ test("removes script and foreignObject elements", function (assert) {+ const result = sanitize(+ `<script>alert(1)</script><foreignObject><div>x</div></foreignObject><text>ok</text>`+ );+ assert.false(result.includes("alert"), "removes script content");+ assert.false(result.includes("foreignObject"), "removes foreignObject");+ assert.true(result.includes("ok"), "keeps safe content");+ });++ test("strips on* event handler attributes", function (assert) {+ const result = sanitize(`<rect onclick="alert(1)" width="10"></rect>`);+ assert.false(result.includes("onclick"), "removes onclick attribute");+ assert.true(result.includes("width"), "keeps benign attributes");+ });+});