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, andonerror=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
| Prop | Type | Default | Description |
|---|---|---|---|
content | TrustedHtml | string | required | Signed TrustedHtml token or sanitized string. |
trustedKey | string | process key | Optional explicit verification secret key. |
as | ElementType | "div" | Wrapper HTML tag or component. |
fallback | ReactNode | escaped text | UI rendered when unauthenticated HTML is blocked. |
onBlocked | (reason: string) => void | undefined | Callback invoked when an unauthenticated injection is blocked. |