Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 24 additions & 10 deletions src/yetibot/core/adapters/discord.clj
Original file line number Diff line number Diff line change
Expand Up @@ -705,26 +705,40 @@
(timbre/debug "Guild Channels: " (pr-str guild-channels))
(guild-channels)))

(def ^:private generated-media-pattern
#"https?://[^\s<>]+?/generated-images/([^./\s]+)\.(png|gif|mp4|svg|pdf|jpeg|jpg|webp|txt|utxt|base64)(?![A-Za-z0-9_.-])")

(defn- generated-image-info [msg]
(when-let [[url id ext] (re-find #"https?://\S+?/generated-images/([^./\s]+)\.(png|gif|mp4)" msg)]
(when-let [[url id ext] (re-find generated-media-pattern msg)]
{:url url :id id :ext ext}))

;; Ordinary content and conservative caller budgeting. V2 text uses the
;; separate components/max-text-length budget.
(def discord-max-message-length 2000)

(defn- message-parts [msg]
(let [{:keys [url id ext]} (generated-image-info msg)
data (:data (get @images/image-store id))]
(if data
(let [caption (str/replace msg url "")
image {:image data :filename (str id "." ext)}
(let [media (->> (re-seq generated-media-pattern msg)
distinct
(keep (fn [[url id ext]]
(when-let [stored (get @images/image-store id)]
{:url url :image (:data stored)
:filename (str id "." ext)
:download?
(not (contains? images/preview-mime-types
(or (:mime-type stored)
(case ext "png" "image/png"
"gif" "image/gif"
"mp4" "video/mp4" nil))))}))))
budget (if (command-timing?) 3968 4000)]
(if (seq media)
(let [caption (reduce #(str/replace %1 (:url %2) "") msg media)
parts (mapv #(dissoc % :url) media)
caption-part (when-not (str/blank? caption)
(first (components/text-parts caption (if (command-timing?) 3968 4000))))]
(first (components/text-parts caption budget)))]
(if (:file caption-part)
[image caption-part]
[(merge image caption-part)]))
(components/text-parts msg (if (command-timing?) 3968 4000)))))
(conj parts caption-part)
(assoc parts 0 (merge (first parts) caption-part))))
(components/text-parts msg budget))))

(defn- command-part [part]
(if-let [{:keys [key entry]} *command-context*]
Expand Down
8 changes: 5 additions & 3 deletions src/yetibot/core/adapters/discord_components.clj
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,10 @@

(defn payload
"Build a V2 card. Details is a bounded caller-sanitized snapshot, never raw data."
[{:keys [content image file filename command-key details details-token elapsed
[{:keys [content image file filename download? command-key details details-token elapsed
data? data-token error? allowed-mentions navigation]}]
(let [media (or (when image (str "attachment://" filename)) (media-url content))
(let [media (when-not download?
(or (when image (str "attachment://" filename)) (media-url content)))
buttons (when command-key
(mapv (fn [[action label]]
{:type 2 :style 2 :label label
Expand All @@ -158,7 +159,8 @@
(and (not (str/blank? content)) (not= content media))
(conj {:type 10 :content content})
media (conj {:type 12 :items [{:media {:url media}}]})
file (conj {:type 13 :file {:url (str "attachment://" filename)}})
(or file download?)
(conj {:type 13 :file {:url (str "attachment://" filename)}})
navigation (conj navigation)
elapsed (conj {:type 10 :content (str "-# " elapsed)})
(seq buttons) (conj {:type 1 :components buttons}))]
Expand Down
4 changes: 3 additions & 1 deletion src/yetibot/core/parser.clj
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
<nestable-sub-expr> = <dollar> <lparen> expr <rparen>
<non-nestable-sub-expr> = dollar !lparen
words = space* word (space* word)* space*
<word> = sub-expr | word-chars | lparen | rparen | quote | literal | regex-pipe | non-nestable-sub-expr
<word> = fenced / (sub-expr | word-chars | lparen | rparen | quote | literal | regex-pipe | non-nestable-sub-expr)
fenced = #'(?s)(`{3,}|~{3,})[^\\r\\n]*\\r?\\n.*?\\r?\\n\\1(?=[ \\t]*(?:\\r?\\n|$|\\|))'
<word-chars> = #'[^ `$()|\"]+'
parened = lparen words rparen
<regex-pipe> = word-chars pipe word-chars (pipe word-chars)*
Expand Down Expand Up @@ -56,6 +57,7 @@
:space (join nodes)
:parened (join nodes)
:literal (join nodes)
:fenced (join nodes)
:sub-expr (let [{:keys [value error] :as evaled}
(transformer head)]
;; extract either the error or the value out of the sub-expr
Expand Down
1 change: 1 addition & 0 deletions src/yetibot/core/unparser.clj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
insta/transform
{:words str
:literal str
:fenced str
:space str
:parened str
:cmd identity
Expand Down
34 changes: 28 additions & 6 deletions src/yetibot/core/webapp/routes/images.clj
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
(ns yetibot.core.webapp.routes.images
"Serves generated media stored in the in-memory image store."
(:require [compojure.core :refer [GET defroutes]]
(:require [clojure.string :as str]
[compojure.core :refer [GET defroutes]]
[ring.util.response :as response])
(:import [java.util Base64]))

(defonce image-store (atom {}))

(def preview-mime-types
#{"image/png" "image/jpeg" "image/gif" "image/webp" "video/mp4"})

(def ^:private max-stored-images 100)

(defn store-image!
Expand All @@ -29,13 +33,31 @@
"Serve stored media by id, falling back to default-mime if none was recorded."
[id default-mime]
(if-let [{:keys [data mime-type]} (get @image-store id)]
(let [bytes (.decode (Base64/getDecoder) ^String data)]
(-> (response/response (java.io.ByteArrayInputStream. bytes))
(response/content-type (or mime-type default-mime))
(response/header "Cache-Control" "public, max-age=3600")))
(let [bytes (.decode (Base64/getDecoder) ^String data)
mime (or mime-type default-mime)
inline? (contains? preview-mime-types mime)]
(cond-> (-> (response/response (java.io.ByteArrayInputStream. bytes))
(response/content-type mime)
(response/header "Cache-Control" "public, max-age=3600")
(response/header "X-Content-Type-Options" "nosniff"))
;; Apply to the stored MIME, not the requested suffix: legacy .png
;; URLs must not provide an unprotected alias for an active document.
(not inline?)
(-> (response/header "Content-Disposition"
(str "attachment; filename=\""
(str/replace id #"[^A-Za-z0-9_-]" "_")
"." (case mime "image/svg+xml" "svg"
"application/pdf" "pdf" "txt") "\""))
(response/header "Content-Security-Policy"
"sandbox; default-src 'none'; style-src 'unsafe-inline'"))))
(response/not-found "Image not found")))

(defroutes image-routes
(GET "/generated-images/:id.png" [id] (serve-stored id "image/png"))
(GET "/generated-images/:id.gif" [id] (serve-stored id "image/gif"))
(GET "/generated-images/:id.mp4" [id] (serve-stored id "video/mp4")))
(GET "/generated-images/:id.mp4" [id] (serve-stored id "video/mp4"))
(GET ["/generated-images/:id.:ext" :ext #"svg|pdf|jpeg|jpg|webp|txt|utxt|base64"]
[id ext]
(serve-stored id (case ext "svg" "image/svg+xml" "pdf" "application/pdf"
"jpeg" "image/jpeg" "jpg" "image/jpeg"
"webp" "image/webp" "text/plain"))))
33 changes: 33 additions & 0 deletions test/yetibot/core/test/adapters/discord_components.clj
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,39 @@
=> "attachment://photo.png"
(get-in payload [:stream :filename]) => "photo.png")))))

(fact "generated SVG and PDF upload as exact downloadable files with captions"
(doseq [[ext mime] [["svg" "image/svg+xml"] ["pdf" "application/pdf"]
["txt" "text/plain"]]]
(with-redefs [images/image-store
(atom {"diagram" {:data "SGVsbG8=" :mime-type mime}})]
(session (fn [& _]
(chat/send-msg (str "A diagram https://example.org/generated-images/diagram." ext)))
(fn [event! calls _]
(await! (event! :message-create original))
(let [payload (last (first @calls))]
(count @calls) => 1
(first (children payload)) => {:type 10 :content "A diagram "}
(get-in (second (children payload)) [:file :url])
=> (str "attachment://diagram." ext)
(some #(= 12 (:type %)) (children payload)) => nil
(slurp (get-in payload [:stream :content])) => "Hello"
(get-in payload [:allowed-mentions :replied_user]) => false))))))

(fact "multiple generated diagrams each receive an upload without duplicating a repeated URL"
(with-redefs [images/image-store
(atom {"one" {:data "SGVsbG8=" :mime-type "image/png"}
"two" {:data "SGVsbG8=" :mime-type "image/svg+xml"}})]
(session (fn [& _]
(chat/send-msg (str "Diagrams\nhttps://example.org/generated-images/one.png\n"
"https://example.org/generated-images/two.svg\n"
"https://example.org/generated-images/one.png")))
(fn [event! calls _]
(await! (event! :message-create original))
(count @calls) => 2
(mapv #(get-in (last %) [:stream :filename]) @calls) => ["one.png" "two.svg"]
(get-in (first (children (last (second @calls)))) [:file :url])
=> "attachment://two.svg"))))

(fact "generated image captions use the same deterministic table renderer"
(with-redefs [images/image-store (atom {"photo" {:data "SGVsbG8="}})]
(session (fn [& _]
Expand Down
35 changes: 35 additions & 0 deletions test/yetibot/core/test/parser_fences.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
(ns yetibot.core.test.parser-fences
(:require [midje.sweet :refer [fact =>]]
[yetibot.core.interpreter :as interpreter]
[yetibot.core.parser :as parser]
[yetibot.core.unparser :as unparser]))

(fact "complete Markdown fences are literal, including pipes and executable-looking text"
(doseq [marker ["```" "~~~~"]]
(let [source (str marker "mermaid\ngraph TD\n A[\"x | y $(cron delete) `command`\"]\n" marker)
input (str "kroki render mermaid " source)
calls (atom 0)]
(unparser/unparse (parser/parser input)) => input
(with-redefs [interpreter/handle-expr
(fn [evaluate cmds]
(swap! calls inc)
{:value (mapv evaluate cmds)})]
(:value (parser/parse-and-eval input)) => [input]
@calls => 1))))

(fact "a fence-like prefix within the source does not terminate the literal block"
(let [input "echo ```txt\nfirst\n```not-closing\n$(cron delete)\n```"
calls (atom 0)]
(unparser/unparse (parser/parser input)) => input
(with-redefs [interpreter/handle-expr
(fn [evaluate cmds]
(swap! calls inc)
{:value (mapv evaluate cmds)})]
(:value (parser/parse-and-eval input)) => [input]
@calls => 1)))

(fact "a pipeline after a fenced source remains an ordinary outer pipeline"
(let [input "echo ```txt\na | b\n``` | echo done"
tree (parser/parser input)]
(count (rest tree)) => 2
(unparser/unparse tree) => input))
44 changes: 44 additions & 0 deletions test/yetibot/core/test/webapp/routes/images.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
(ns yetibot.core.test.webapp.routes.images
(:require [clojure.string :as str]
[midje.sweet :refer [fact =>]]
[yetibot.core.webapp.routes.images :as images])
(:import [java.util Base64]))

(defn request [extension]
(images/image-routes {:request-method :get
:uri (str "/generated-images/diagram." extension)}))

(fact "diagram downloads retain exact bytes and sandbox active SVG on every alias"
(let [svg "<svg xmlns='http://www.w3.org/2000/svg'><script>bad()</script></svg>"
data (.encodeToString (Base64/getEncoder) (.getBytes svg "UTF-8"))]
(with-redefs [images/image-store (atom {"diagram" {:data data :mime-type "image/svg+xml"}})]
(doseq [extension ["svg" "png"]]
(let [response (request extension)]
(:status response) => 200
(get-in response [:headers "Content-Type"]) => "image/svg+xml"
(get-in response [:headers "X-Content-Type-Options"]) => "nosniff"
(str/includes? (get-in response [:headers "Content-Security-Policy"] "")
"sandbox") => true
(str/starts-with? (get-in response [:headers "Content-Disposition"] "")
"attachment;") => true
(slurp (:body response)) => svg)))))

(fact "PDF and textual diagrams are downloads, not active inline documents"
(doseq [[extension mime] [["pdf" "application/pdf"] ["txt" "text/plain"]
["utxt" "text/plain"] ["base64" "text/plain"]]]
(with-redefs [images/image-store
(atom {"diagram" {:data "SGVsbG8=" :mime-type mime}})]
(let [response (request extension)]
(:status response) => 200
(slurp (:body response)) => "Hello"
(get-in response [:headers "Content-Type"]) => mime
(str/starts-with? (get-in response [:headers "Content-Disposition"] "")
"attachment;") => true))))

(fact "ordinary raster media remains inline and unknown artifacts stay missing"
(with-redefs [images/image-store (atom {"diagram" {:data "SGVsbG8=" :mime-type "image/jpeg"}})]
(:status (request "jpeg")) => 200
(get-in (request "jpeg") [:headers "Content-Disposition"]) => nil
(images/image-routes {:request-method :get :uri "/generated-images/missing.svg"})
=> {:status 404 :headers {} :body "Image not found"}
(request "html") => nil))