Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix escaping for embedded gists #381

Merged
merged 1 commit into from
Nov 18, 2024
Merged
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
33 changes: 27 additions & 6 deletions internal/web/gist.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"archive/zip"
"bufio"
"bytes"
gojson "encoding/json"
"errors"
"fmt"
"html/template"
Expand Down Expand Up @@ -428,12 +429,10 @@ func gistJs(ctx echo.Context) error {
return errorRes(500, "Error joining css url", err)
}

js := `document.write('<link rel="stylesheet" href="%s">')
document.write('%s')
`
content := strings.Replace(htmlbuf.String(), `\n`, `\\n`, -1)
content = strings.Replace(content, "\n", `\n`, -1)
js = fmt.Sprintf(js, cssUrl, content)
js, err := escapeJavaScriptContent(htmlbuf.String(), cssUrl)
if err != nil {
return errorRes(500, "Error escaping JavaScript content", err)
}
ctx.Response().Header().Set("Content-Type", "application/javascript")
return plainText(ctx, 200, js)
}
Expand Down Expand Up @@ -894,3 +893,25 @@ func preview(ctx echo.Context) error {

return plainText(ctx, 200, previewStr)
}

func escapeJavaScriptContent(htmlContent, cssUrl string) (string, error) {
jsonContent, err := gojson.Marshal(htmlContent)
if err != nil {
return "", fmt.Errorf("failed to encode content: %w", err)
}

jsonCssUrl, err := gojson.Marshal(cssUrl)
if err != nil {
return "", fmt.Errorf("failed to encode CSS URL: %w", err)
}

js := fmt.Sprintf(`
document.write('<link rel="stylesheet" href=%s>');
document.write(%s);
`,
string(jsonCssUrl),
string(jsonContent),
)

return js, nil
}