SafeHtml

The <SafeHtml> component replaces React's insecure dangerouslySetInnerHTML with a cryptographically verified execution boundary. It permits raw HTML from your codebase or server, while blocking unauthenticated raw HTML injections originating from the browser.

Import

usage
import { SafeHtml, createTrustedHtml } from "swift-rust";

How It Works

Unlike Next.js which accepts arbitrary unverified strings that can lead to Cross-Site Scripting (XSS), Swift Rust establishes a strict cryptographic origin policy:

  • Codebase & Server Origin: HTML authored in server components or backend code is signed with createTrustedHtml(rawHtml). This derives an HMAC/BLAKE3 token using the server's runtime secret.
  • Browser Origin Blocking: When running in the browser, any raw string or unsigned object passed to <SafeHtml> is automatically blocked from DOM injection. The content is safely escaped as text or replaced with your fallback UI.
  • Server-side Sanitization: Any untrusted third-party strings rendered on the server (e.g. from a CMS) are automatically stripped of dangerous <script> tags, iframes, and onerror= event handlers.

Examples

1. Server Component (Trusted Codebase Content)

app/blog/[slug]/page.tsx
import { SafeHtml, createTrustedHtml } from "swift-rust";

export default async function BlogPost({ params }: { params: { slug: string } }) {
  const post = await fetchPost(params.slug);
  
  // Cryptographically signs the HTML for safe rendering
  const trustedContent = createTrustedHtml(post.renderedBody);

  return (
    <article className="prose">
      <SafeHtml content={trustedContent} />
    </article>
  );
}

2. Browser Attack Protection

app/search/page.tsx
"use client";
import { SafeHtml } from "swift-rust";

export default function SearchPage({ searchParams }: { searchParams: { q: string } }) {
  // If an attacker attempts query injection: ?q=<script>steal()</script>
  // SafeHtml detects browser execution without a server token and BLOCKS it.
  return (
    <div>
      <SafeHtml 
        content={searchParams.q}
        fallback={<p className="text-muted">Unauthenticated HTML was blocked.</p>}
      />
    </div>
  );
}

Props

PropTypeDefaultDescription
contentTrustedHtml | stringrequiredSigned TrustedHtml token or sanitized string.
trustedKeystringprocess keyOptional explicit verification secret key.
asElementType"div"Wrapper HTML tag or component.
fallbackReactNodeescaped textUI rendered when unauthenticated HTML is blocked.
onBlocked(reason: string) => voidundefinedCallback invoked when an unauthenticated injection is blocked.