gitforge/web_src/js/render/ansi.js
Dax Kelson 4fe694fef7 feat: render OSC 8 sequences safely (#13085)
Job logs now render OSC 8 hyperlink escape sequences as clickable links in the Actions log viewer, so the Forgejo log has clickable links. A workflow step opts in by emitting the OSC 8 sequence (`ESC ] 8 ; ; <url> ESC \ <text> ESC ] 8 ; ; ESC \`), which is the same escape code terminals already use for links.

Hardens the anchors `ansi_up` emits: adds `rel="noopener noreferrer nofollow"` and `target="_blank"`, and drops any link whose scheme is not http or https.

## Checklist

### Tests for JavaScript changes

- I added test coverage for JavaScript changes...
  - [x] in `web_src/js/*.test.js` if it can be unit tested.
  - [ ] in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server.

### Documentation

- [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change.
- [x] I did not document these changes and I do not expect someone else to do it.

### Release notes

- [x] This change will be noticed by a Forgejo user or admin (feature, bug fix, performance, etc.). I suggest to include a release note for this change.
- [ ] This change is not visible to a Forgejo user or admin (refactor, dependency upgrade, etc.). I think there is no need to add a release note for this change.

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/13085
Reviewed-by: Andreas Ahlenstorf <aahlenst@noreply.codeberg.org>
Reviewed-by: Mathieu Fenniak <mfenniak@noreply.codeberg.org>
2026-07-06 05:20:09 +02:00

88 lines
3.2 KiB
JavaScript

import {AnsiUp} from 'ansi_up';
const replacements = [
[/\x1b\[\d+[A-H]/g, ''], // Move cursor, treat them as no-op
[/\x1bM/g, ''], // Move cursor one line up, threat them as no-op.
[/\x1b\[\d?[JK]/g, '\r'], // Erase display/line, treat them as a Carriage Return
[/\x1b\]9;\d+.*?(\x07|\x1b\\)/g, ''], // ConEmu, treat them as no-op.
];
// render ANSI to HTML
export function renderAnsi(line) {
// create a fresh ansi_up instance because otherwise previous renders can influence
// the output of future renders, because ansi_up is stateful and remembers things like
// unclosed opening tags for colors.
const ansi_up = new AnsiUp();
ansi_up.use_classes = true;
if (line.endsWith('\r\n')) {
line = line.substring(0, line.length - 2);
} else if (line.endsWith('\n')) {
line = line.substring(0, line.length - 1);
}
if (line.includes('\x1b')) {
for (const [regex, replacement] of replacements) {
line = line.replace(regex, replacement);
}
}
if (!line.includes('\r')) {
return ansi_up.ansi_to_html(line);
}
// handle "\rReading...1%\rReading...5%\rReading...100%",
// convert it into a multiple-line string: "Reading...1%\nReading...5%\nReading...100%"
const lines = [];
for (const part of line.split('\r')) {
if (part === '') continue;
const partHtml = ansi_up.ansi_to_html(part);
if (partHtml !== '') {
lines.push(partHtml);
}
}
// the log message element is with "white-space: break-spaces;", so use "\n" to break lines
return lines.join('\n');
}
// link schemes ansi_up is allowed to emit; re-checked below because log output is
// untrusted and a javascript: or data: href should not become clickable.
const allowedLinkSchemes = new Set(['http:', 'https:']);
// ansi_up renders OSC 8 hyperlink escape codes as <a> tags with the href and text already
// escaped, but without link attributes. add them here, and drop any link whose scheme is
// not http(s) by replacing it with its text. the html is parsed in a detached <template>,
// which runs no scripts and loads no resources, and the href and text are re-escaped when
// it is serialized back to a string.
function hardenRenderedAnsiLinks(html) {
// the usual log line has no link, so skip the parse when there is no <a> to touch
if (!html.includes('<a ')) return html;
const template = document.createElement('template');
template.innerHTML = html;
for (const link of template.content.querySelectorAll('a')) {
let scheme = '';
try {
scheme = new URL(link.getAttribute('href') ?? '').protocol;
} catch {
// an empty, relative or malformed href has no scheme and is dropped below
}
if (!allowedLinkSchemes.has(scheme)) {
link.replaceWith(document.createTextNode(link.textContent));
continue;
}
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer nofollow');
}
return template.innerHTML;
}
// render ANSI to HTML, turning OSC 8 hyperlink escape codes into links. a job opts in by
// emitting OSC 8, the escape code terminals use for links, so output from a standalone
// Forgejo Runner is linked too. plain-text URLs are left as text.
export function renderAnsiWithLinks(line) {
return hardenRenderedAnsiLinks(renderAnsi(line));
}