Skip to main content

Utility Functions (Utils)

src/shared/utils.ts — Shared security and utility functions.

Important Rule

These functions must never be redefined locally. All usage must be imported from shared/utils.ts.

escapeHtml()

Makes HTML text content safe. Prevents XSS attacks.

export function escapeHtml(text: string): string

Parameters:

  • text — Text to escape

Returns: Safe HTML text

Method: Uses the DOM API — creates safe text with document.createTextNode().

Protected Characters:

InputOutput
<&lt;
>&gt;
&&amp;
"&quot;
'&#039;

Usage:

import { escapeHtml } from "../shared/utils";

// ✅ Safe DOM insertion
element.innerHTML = `<span>${escapeHtml(userValue)}</span>`;

// ❌ Dangerous
element.innerHTML = `<span>${userValue}</span>`;

escapeAttr()

Makes HTML attribute values safe.

export function escapeAttr(text: string): string

Parameters:

  • text — Attribute value to escape

Returns: Safe attribute string

Protected Characters:

CharacterConversion
&&amp;
"&quot;
'&#039;
<&lt;
>&gt;

Usage:

import { escapeAttr } from "../shared/utils";

// ✅ Safe attribute
html = `<div data-value="${escapeAttr(fieldValue)}">...</div>`;

// ❌ Dangerous
html = `<div data-value="${fieldValue}">...</div>`;

copyToClipboard()

Copies text to the clipboard. Supports both modern and fallback methods.

export function copyToClipboard(text: string): Promise<void>

Parameters:

  • text — Text to copy to clipboard

Methods:

  1. Modern (preferred): navigator.clipboard.writeText()

    • Requires HTTPS
    • May require user permission
  2. Fallback (for HTTP environments): document.execCommand('copy')

    • Creates a temporary textarea
    • Copies with execCommand()
    • Cleans up the textarea

Usage:

import { copyToClipboard } from "../shared/utils";

try {
await copyToClipboard(jsonText);
showNotification("Copied!", "success");
} catch (error) {
showNotification("Copy failed", "error");
}

Security Note

These functions are Graytool's primary line of defense against XSS (Cross-Site Scripting) attacks:

Log data (untrusted) → escapeHtml/escapeAttr → Safe DOM insertion

Log data is generated by Graylog users and may potentially contain harmful content. Therefore, all log data must be escaped before being added to the DOM.