返回 DeepSeek-Reasonix
markdown_image_resolver.go
根目录 / desktop / markdown_image_resolver.go
1 package main
2
3 import (
4 "encoding/base64"
5 "errors"
6 "net/url"
7 "os"
8 "path/filepath"
9 "strings"
10 )
11
12 // MarkdownImageView is the renderer-safe form of an assistant-provided image
13 // source. URL is always either a vetted data URI or a same-origin media/proxy
14 // URL; native file:// paths are never handed to the WebView as image sources.
15 type MarkdownImageView struct {
16 URL string `json:"url"`
17 Filename string `json:"filename,omitempty"`
18 Mime string `json:"mime,omitempty"`
19 Size int64 `json:"size,omitempty"`
20 OpenHref string `json:"openHref,omitempty"`
21 ErrorCode string `json:"errorCode,omitempty"`
22 }
23
24 const markdownDataImageMaxEncodedBytes = remoteMarkdownImageMaxBytes*4/3 + 1024
25
26 // ResolveMarkdownImageForTab applies a tag-specific policy that is deliberately
27 // stricter than ordinary Markdown links.
28 func (a *App) ResolveMarkdownImageForTab(tabID, source string) MarkdownImageView {
29 source = strings.TrimSpace(source)
30 if source == "" {
31 return MarkdownImageView{ErrorCode: "invalid-source"}
32 }
33 if strings.HasPrefix(source, "//") {
34 source = "https:" + source
35 }
36 if strings.HasPrefix(strings.ToLower(source), "http://") || strings.HasPrefix(strings.ToLower(source), "https://") {
37 remote, err := validateRemoteMarkdownImageURL(source)
38 if err != nil {
39 return MarkdownImageView{OpenHref: source, ErrorCode: "blocked-remote"}
40 }
41 name := filepath.Base(strings.TrimSpace(mustURLPath(remote)))
42 if name == "." || name == string(filepath.Separator) {
43 name = "image"
44 }
45 return MarkdownImageView{
46 URL: remoteMarkdownImagePath + "?url=" + url.QueryEscape(remote),
47 Filename: name,
48 OpenHref: remote,
49 }
50 }
51 if strings.HasPrefix(strings.ToLower(source), "data:") {
52 return resolveMarkdownDataImage(source)
53 }
54
55 path, err := a.authorizedMarkdownImagePath(tabID, source)
56 if err != nil {
57 code := "invalid-path"
58 if errors.Is(err, os.ErrPermission) {
59 code = "forbidden"
60 } else if errors.Is(err, os.ErrNotExist) {
61 code = "not-found"
62 }
63 return MarkdownImageView{ErrorCode: code}
64 }
65 info, err := os.Lstat(path)
66 if err != nil {
67 return MarkdownImageView{ErrorCode: "not-found"}
68 }
69 openHref := localFileHref(path)
70 if info.Mode()&os.ModeSymlink != 0 {
71 return MarkdownImageView{OpenHref: openHref, ErrorCode: "forbidden"}
72 }
73 if info.IsDir() || !info.Mode().IsRegular() {
74 return MarkdownImageView{OpenHref: openHref, ErrorCode: "not-a-file"}
75 }
76 kind, mimeType := previewMediaKind(path)
77 if kind != "image" {
78 return MarkdownImageView{Filename: info.Name(), Size: info.Size(), OpenHref: openHref, ErrorCode: "unsupported-type"}
79 }
80 f, err := os.Open(path)
81 if err != nil {
82 return MarkdownImageView{Filename: info.Name(), OpenHref: openHref, ErrorCode: "not-found"}
83 }
84 defer f.Close()
85 opened, err := f.Stat()
86 if err != nil || !opened.Mode().IsRegular() || !os.SameFile(info, opened) {
87 return MarkdownImageView{Filename: info.Name(), OpenHref: openHref, ErrorCode: "invalid-path"}
88 }
89 if err := validateOpenMarkdownImageFile(f, mimeType, opened.Size()); err != nil {
90 code := "invalid-image"
91 if errors.Is(err, errMarkdownImageTooLarge) {
92 code = "too-large"
93 }
94 return MarkdownImageView{Filename: info.Name(), Size: opened.Size(), OpenHref: openHref, ErrorCode: code}
95 }
96 token := a.ensureMediaTokenStore().createMarkdownImage(path, info.Name(), mimeType, opened)
97 return MarkdownImageView{
98 URL: "/__reasonix_workspace_media/" + token + "/" + url.PathEscape(info.Name()),
99 Filename: info.Name(),
100 Mime: mimeType,
101 Size: opened.Size(),
102 OpenHref: openHref,
103 }
104 }
105
106 func mustURLPath(raw string) string {
107 u, err := url.Parse(raw)
108 if err != nil {
109 return ""
110 }
111 return u.Path
112 }
113
114 func resolveMarkdownDataImage(source string) MarkdownImageView {
115 if len(source) > markdownDataImageMaxEncodedBytes {
116 return MarkdownImageView{ErrorCode: "too-large"}
117 }
118 comma := strings.IndexByte(source, ',')
119 if comma <= len("data:") {
120 return MarkdownImageView{ErrorCode: "invalid-data"}
121 }
122 header := strings.ToLower(strings.TrimSpace(source[len("data:"):comma]))
123 parts := strings.Split(header, ";")
124 declared := strings.TrimSpace(parts[0])
125 allowed := declared == "image/png" || declared == "image/jpeg" || declared == "image/gif" || declared == "image/webp"
126 if !allowed {
127 return MarkdownImageView{ErrorCode: "unsupported-type"}
128 }
129 base64Encoded := false
130 for _, part := range parts[1:] {
131 if strings.TrimSpace(part) == "base64" {
132 base64Encoded = true
133 continue
134 }
135 return MarkdownImageView{ErrorCode: "invalid-data"}
136 }
137 payload := source[comma+1:]
138 var data []byte
139 var err error
140 if base64Encoded {
141 data, err = base64.StdEncoding.DecodeString(strings.Map(func(r rune) rune {
142 if r == '\r' || r == '\n' || r == '\t' || r == ' ' {
143 return -1
144 }
145 return r
146 }, payload))
147 } else {
148 var decoded string
149 decoded, err = url.PathUnescape(payload)
150 data = []byte(decoded)
151 }
152 if err != nil || len(data) == 0 {
153 return MarkdownImageView{ErrorCode: "invalid-data"}
154 }
155 if len(data) > remoteMarkdownImageMaxBytes {
156 return MarkdownImageView{ErrorCode: "too-large"}
157 }
158 validated, detected := safeRemoteMarkdownImage(data)
159 if detected != declared || detected == "image/svg+xml" {
160 return MarkdownImageView{ErrorCode: "invalid-data"}
161 }
162 if err := validateMarkdownImageBytes(validated, detected); err != nil {
163 if errors.Is(err, errMarkdownImageTooLarge) {
164 return MarkdownImageView{ErrorCode: "too-large"}
165 }
166 return MarkdownImageView{ErrorCode: "invalid-data"}
167 }
168 return MarkdownImageView{URL: source, Mime: detected, Size: int64(len(data))}
169 }
170
171 func (a *App) authorizedMarkdownImagePath(tabID, source string) (string, error) {
172 root, ctrl, ok := a.workspaceTargetForTab(tabID)
173 if !ok {
174 return "", os.ErrNotExist
175 }
176 if browser := externalFolderRefBrowserFromController(ctrl); browser != nil {
177 if external, _, found := browser.ExternalFolderRefLocalPath(source); found {
178 return filepath.Clean(external), nil
179 }
180 }
181
182 pathSource, err := localPathSource(source)
183 if err != nil {
184 return "", err
185 }
186 if filepath.IsAbs(pathSource) {
187 if authorizer, ok := ctrl.(interface {
188 AuthorizedExternalFolderLocalPath(string) (string, bool)
189 }); ok {
190 if external, allowed := authorizer.AuthorizedExternalFolderLocalPath(pathSource); allowed {
191 return external, nil
192 }
193 }
194 }
195 base, err := workspaceBaseFromRoot(root)
196 if err != nil {
197 return "", err
198 }
199 candidate, inside, err := workspacePathForBase(base, pathSource)
200 if err != nil || !inside {
201 return "", os.ErrPermission
202 }
203 contained, _, err := canonicalPathWithin(base, candidate)
204 return contained, err
205 }
206
206 lines GO