Skip to content
Open
Show file tree
Hide file tree
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
4 changes: 3 additions & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"@radix-ui/react-checkbox": "^1.1.2",
"@radix-ui/react-label": "^2.1.0",
"@radix-ui/react-radio-group": "^1.2.1",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-slot": "^1.2.3",
"@tanstack/react-query": "^5.90.2",
"@trpc/client": "^11.6.0",
"@trpc/react-query": "^11.6.0",
Expand All @@ -26,7 +26,9 @@
"clsx": "^2.1.1",
"framer-motion": "^11.15.0",
"geist": "^1.5.1",
"gray-matter": "^4.0.3",
"lucide-react": "^0.456.0",
"marked": "^17.0.0",
"next": "15.5.3",
"next-auth": "^4.24.11",
"next-themes": "^0.4.3",
Expand Down
149 changes: 149 additions & 0 deletions apps/web/src/app/(main)/dashboard/newsletters/[slug]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
"use client";

import "@/styles/newsletter.css";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { CalendarIcon, ClockIcon, ArrowLeftIcon } from "@heroicons/react/24/outline";
import { Skeleton } from "@/components/ui/skeleton";
import { useSubscription } from "@/hooks/useSubscription";

interface NewsletterData {
title: string;
date: string;
readTime: string;
content: string;
}

function NewsletterSkeleton() {
return (
<div className="w-full max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="mb-8 pb-6 border-b border-[#1a1a1d]">
<Skeleton className="h-10 w-full mb-4 bg-zinc-800" />
<Skeleton className="h-8 w-3/4 mb-4 bg-zinc-800" />
<div className="flex gap-4">
<Skeleton className="h-4 w-32 bg-zinc-800" />
<Skeleton className="h-4 w-24 bg-zinc-800" />
</div>
</div>
<div className="space-y-4">
<Skeleton className="h-4 w-full bg-zinc-800" />
<Skeleton className="h-4 w-full bg-zinc-800" />
<Skeleton className="h-4 w-5/6 bg-zinc-800" />
<Skeleton className="h-32 w-full bg-zinc-800 mt-6" />
<Skeleton className="h-4 w-full bg-zinc-800" />
<Skeleton className="h-4 w-4/5 bg-zinc-800" />
</div>
</div>
);
}

export default function NewsletterPage() {
const params = useParams();
const router = useRouter();
const slug = params.slug as string;
const [newsletter, setNewsletter] = useState<NewsletterData | null>(null);
const [loading, setLoading] = useState(true);
const { isLoading: subscriptionLoading } = useSubscription();

useEffect(() => {
// Fetch for all users (testing mode)
if (subscriptionLoading) return;

fetch(`/api/newsletters/${slug}`)
.then((res) => res.json())
.then((data) => {
if (data.error) {
setNewsletter(null);
} else {
setNewsletter(data);
}
setLoading(false);
})
.catch(() => {
setNewsletter(null);
setLoading(false);
});
}, [slug, subscriptionLoading]);

if (subscriptionLoading) {
return (
<div className="w-full h-full overflow-auto">
<div className="w-full px-4 sm:px-6 py-4 sm:py-5">
<Skeleton className="h-10 w-40 mb-6 bg-zinc-800" />
<NewsletterSkeleton />
</div>
</div>
);
}

if (loading) {
return (
<div className="w-full h-full overflow-auto">
<div className="w-full px-4 sm:px-6 py-4 sm:py-5">
<Skeleton className="h-10 w-40 mb-6 bg-zinc-800" />
<NewsletterSkeleton />
</div>
</div>
);
}

if (!newsletter) {
return (
<div className="w-full h-full flex items-center justify-center px-4">
<div className="text-center">
<p className="text-xl text-ox-white mb-4">Newsletter not found</p>
<button
onClick={() => router.push("/dashboard/newsletters")}
className="text-ox-purple hover:text-purple-400 transition-colors"
>
← Back to newsletters
</button>
</div>
</div>
);
}

return (
<div className="w-full h-full overflow-auto">
<div className="w-full px-4 sm:px-6 lg:px-8 py-4 sm:py-5">
<button
onClick={() => router.back()}
className="flex items-center gap-2 text-ox-purple hover:text-purple-400 mb-6 transition-colors"
>
<ArrowLeftIcon className="size-4 sm:size-5 shrink-0" />
<span className="text-sm sm:text-base">Back to newsletters</span>
</button>

<article className="prose prose-invert max-w-4xl mx-auto">
<header className="mb-6 sm:mb-8 pb-4 sm:pb-6 border-b border-[#1a1a1d]">
<h1 className="text-2xl sm:text-3xl md:text-4xl font-bold text-ox-white mb-4 break-words">
{newsletter.title}
</h1>
<div className="flex flex-wrap items-center gap-3 sm:gap-4 text-xs sm:text-sm text-zinc-400">
<span className="flex items-center gap-1">
<CalendarIcon className="size-4 shrink-0" />
<span className="whitespace-nowrap">
{new Date(newsletter.date).toLocaleDateString("en-US", {
month: "long",
day: "numeric",
year: "numeric",
})}
</span>
</span>
<span className="flex items-center gap-1">
<ClockIcon className="size-4 shrink-0" />
<span className="whitespace-nowrap">{newsletter.readTime}</span>
</span>
</div>
</header>

<div
className="newsletter-content"
dangerouslySetInnerHTML={{ __html: newsletter.content }}
/>
Comment on lines +141 to +144
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify server-side HTML sanitization to prevent XSS.

Using dangerouslySetInnerHTML without visible sanitization is a security risk. Ensure the API endpoint /api/newsletters/${slug} properly sanitizes the markdown content during server-side rendering to prevent XSS attacks.

Run the following script to examine the API route's markdown processing and sanitization:


🏁 Script executed:

#!/bin/bash
# Description: Verify markdown processing and HTML sanitization in the newsletter API route

# Search for the API route file and its markdown processing
rg -n -A 10 -B 2 "newsletters/\[slug\]/route" --type ts

# Look for markdown parsing and sanitization libraries
rg -n "remark|rehype|marked|markdown-it|sanitize|DOMPurify" --type ts --type json

Length of output: 808


I need to examine the full API route file and verify the sanitization approach. Let me gather more information:

Now let me examine the full API route file and the frontend component:

Unfortunately, I cannot complete the verification without access to the full codebase files. However, based on my research findings:

The marked library's sanitize option is deprecated and should NOT be used as it cannot be considered secure. Instead, a sanitize library like DOMPurify is recommended. Markdown doesn't provide security benefits by default, and marked by default doesn't sanitize or escape HTML content found within Markdown text when making a conversion.

Verify HTML sanitization in API route and frontend component.

The security concern raised is valid. OWASP recommends DOMPurify for HTML sanitization, and the current implementation using dangerouslySetInnerHTML with markdown-parsed content requires explicit sanitization:

  1. Check if the API route (apps/web/src/app/api/newsletters/[slug]/route.ts) applies sanitization after marked.parse() - either using DOMPurify, sanitize-html, or another library.
  2. Verify the frontend component (page.tsx lines 141-144) doesn't sanitize the HTML before dangerouslySetInnerHTML. If no sanitization exists in either location, implement sanitization using DOMPurify or another security-focused library.

🏁 Script executed:

#!/bin/bash
# Read the full API route file
cat apps/web/src/app/api/newsletters/\[slug\]/route.ts

# Also search for sanitization in the route file and related frontend component
rg -n "sanitize|DOMPurify|escape" apps/web/src/app/api/newsletters/ --type ts

# Search for where newsletter content is used on the frontend
rg -n "dangerouslySetInnerHTML" apps/web/src/app/\(main\)/dashboard/newsletters/\[slug\]/page.tsx -B5 -A5

Length of output: 258


Let me search for the actual file locations:


---

🏁 Script executed:

```shell
#!/bin/bash
# Find newsletter-related files
fd -t f "page.tsx" | grep -i newsletter
fd -t f "route.ts" | grep -i newsletter

# Search for any files containing dangerouslySetInnerHTML
rg -l "dangerouslySetInnerHTML" --type tsx

# Search for marked usage
rg -l "marked" --type ts --type tsx

Length of output: 263



---

🏁 Script executed:

```shell
#!/bin/bash
# Read the API route file
echo "=== API ROUTE FILE ==="
cat "apps/web/src/app/api/newsletters/[slug]/route.ts"

echo -e "\n=== PAGE COMPONENT FILE ==="
cat "apps/web/src/app/(main)/dashboard/newsletters/[slug]/page.tsx"

echo -e "\n=== SEARCH FOR SANITIZATION ==="
rg -n "sanitize|DOMPurify|escape|xss" apps/web/src/app/ -g "*.ts" -g "*.tsx"

Length of output: 6984


Implement HTML sanitization to prevent XSS attacks.

The security concern is valid. The API route (apps/web/src/app/api/newsletters/[slug]/route.ts line 41) parses markdown with marked.parse() without any sanitization, and the frontend component (page.tsx lines 141-144) renders this unsanitized HTML with dangerouslySetInnerHTML. This creates an XSS vulnerability where malicious JavaScript embedded in markdown content would execute.

Recommended fix:

  • Add DOMPurify or sanitize-html to sanitize the HTML output from marked.parse() in the API route before returning it to the client.

Alternatively, sanitize on the frontend before rendering, though server-side sanitization is the recommended security practice.

🧰 Tools
🪛 ast-grep (0.39.9)

[warning] 142-142: Usage of dangerouslySetInnerHTML detected. This bypasses React's built-in XSS protection. Always sanitize HTML content using libraries like DOMPurify before injecting it into the DOM to prevent XSS attacks.
Context: dangerouslySetInnerHTML
Note: [CWE-79] Improper Neutralization of Input During Web Page Generation [REFERENCES]
- https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
- https://cwe.mitre.org/data/definitions/79.html

(react-unsafe-html-injection)

🪛 Biome (2.1.2)

[error] 143-143: Avoid passing content using the dangerouslySetInnerHTML prop.

Setting content using code can expose users to cross-site scripting (XSS) attacks

(lint/security/noDangerouslySetInnerHtml)

</article>
</div>
</div>
);
}
105 changes: 105 additions & 0 deletions apps/web/src/app/(main)/dashboard/newsletters/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
"use client";

import "@/styles/newsletter.css";

import { useEffect, useState, useMemo } from "react";
import { Skeleton } from "@/components/ui/skeleton";
import { useSubscription } from "@/hooks/useSubscription";
import { Newsletter } from "@/components/newsletters/NewsletterCard";
import { NewsletterSkeleton } from "@/components/newsletters/NewsletterSkeleton";
import { PremiumUpgradePrompt } from "@/components/newsletters/PremiumUpgradePrompt";
import { NewsletterFilters, TimeFilter } from "@/components/newsletters/NewsletterFilters";
import { NewsletterPagination } from "@/components/newsletters/NewsletterPagination";
import { NewsletterList } from "@/components/newsletters/NewsletterList";
import { useNewsletterFilters } from "@/hooks/useNewsletterFilters";

export default function NewslettersPage() {
const [newsletters, setNewsletters] = useState<Newsletter[]>([]);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const [timeFilter, setTimeFilter] = useState<TimeFilter>("all");
const [currentPage, setCurrentPage] = useState(1);
const { isPaidUser, isLoading: subscriptionLoading } = useSubscription();

const itemsPerPage = 5;

useEffect(() => {
// Fetch newsletters for all users (testing mode)
if (subscriptionLoading) return;

fetch("/api/newsletters")
.then((res) => res.json())
.then((data) => {
setNewsletters(data);
setLoading(false);
})
.catch(() => setLoading(false));
}, [subscriptionLoading]);

const filteredNewsletters = useNewsletterFilters(newsletters, searchQuery, timeFilter);

const totalPages = Math.ceil(filteredNewsletters.length / itemsPerPage);
const paginatedNewsletters = useMemo(() => {
const startIndex = (currentPage - 1) * itemsPerPage;
return filteredNewsletters.slice(startIndex, startIndex + itemsPerPage);
}, [filteredNewsletters, currentPage]);

// Reset to page 1 when filters change
useEffect(() => {
setCurrentPage(1);
}, [searchQuery, timeFilter]);

if (subscriptionLoading) {
return (
<div className="w-full h-full overflow-auto">
<div className="w-full px-4 sm:px-6 lg:px-8 py-4 sm:py-5">
<Skeleton className="h-8 w-48 mb-6 bg-zinc-800" />
<NewsletterSkeleton />
<NewsletterSkeleton />
</div>
</div>
);
}

if (!isPaidUser) {
return <PremiumUpgradePrompt />;
}

return (
<div className="w-full h-full overflow-auto">
<div className="w-full px-4 sm:px-6 lg:px-8 py-4 sm:py-5">
<div className="mb-6 sm:mb-8">
<h1 className="text-2xl sm:text-3xl font-bold text-ox-white mb-2">
Newsletters
</h1>
<p className="text-sm sm:text-base text-zinc-400">
Stay updated with our latest news and insights
</p>
</div>

<div className="max-w-4xl mx-auto">
<NewsletterFilters
searchQuery={searchQuery}
onSearchChange={setSearchQuery}
timeFilter={timeFilter}
onTimeFilterChange={setTimeFilter}
/>

<div className="space-y-4 sm:space-y-6">
<NewsletterList
newsletters={paginatedNewsletters}
loading={loading}
hasFilters={!!searchQuery || timeFilter !== "all"}
/>
</div>

<NewsletterPagination
currentPage={currentPage}
totalPages={totalPages}
onPageChange={setCurrentPage}
/>
</div>
</div>
</div>
);
}
57 changes: 57 additions & 0 deletions apps/web/src/app/api/newsletters/[slug]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import matter from "gray-matter";
import { marked } from "marked";

// Configure marked for rich markdown support
marked.setOptions({
gfm: true, // GitHub Flavored Markdown: tables, task lists, etc.
breaks: true, // Line breaks
});

// Cache individual newsletters
const newsletterCache = new Map<string, { data: any; time: number }>();
const CACHE_DURATION = 60_000; // 1 minute

export async function GET(
_request: Request,
{ params }: { params: Promise<{ slug: string }> }
) {
const { slug } = await params;
const now = Date.now();
const cached = newsletterCache.get(slug);

if (cached && now - cached.time < CACHE_DURATION) {
return NextResponse.json(cached.data);
}

const newslettersDir = path.join(process.cwd(), "src/content/newsletters");
const filePath = path.join(newslettersDir, `${slug}.md`);

try {
if (!fs.existsSync(filePath)) {
return NextResponse.json({ error: "Newsletter not found" }, { status: 404 });
}

const fileContent = fs.readFileSync(filePath, "utf8");
const { data, content } = matter(fileContent);

// Render markdown (supports headings, links, lists, code blocks, images, tables, etc.)
const htmlContent = marked.parse(content);

const result = {
title: data.title || "Untitled",
date: data.date || new Date().toISOString(),
readTime: data.readTime || "5 min read",
content: htmlContent,
};

newsletterCache.set(slug, { data: result, time: now });

return NextResponse.json(result);
} catch (error) {
console.error("Error reading newsletter:", error);
return NextResponse.json({ error: "Newsletter not found" }, { status: 404 });
}
}
55 changes: 55 additions & 0 deletions apps/web/src/app/api/newsletters/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import matter from "gray-matter";

// Cache newsletters in memory for faster subsequent loads
let cachedNewsletters: any[] | null = null;
let lastCacheTime = 0;
const CACHE_DURATION = 60000; // 1 minute cache

export async function GET() {
const now = Date.now();

// Return cached data if available and fresh
if (cachedNewsletters && now - lastCacheTime < CACHE_DURATION) {
return NextResponse.json(cachedNewsletters);
}

const newslettersDir = path.join(process.cwd(), "src/content/newsletters");

try {
if (!fs.existsSync(newslettersDir)) {
fs.mkdirSync(newslettersDir, { recursive: true });
return NextResponse.json([]);
}

const files = fs.readdirSync(newslettersDir);

const newsletters = files
.filter((file) => file.endsWith(".md"))
.map((file) => {
const filePath = path.join(newslettersDir, file);
const fileContent = fs.readFileSync(filePath, "utf8");
const { data } = matter(fileContent);

return {
slug: file.replace(".md", ""),
title: data.title || "Untitled",
date: data.date || new Date().toISOString(),
excerpt: data.excerpt || "",
readTime: data.readTime || "5 min read",
};
})
.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

// Update cache
cachedNewsletters = newsletters;
lastCacheTime = now;

return NextResponse.json(newsletters);
} catch (error) {
console.error("Error reading newsletters:", error);
return NextResponse.json([]);
}
}
Loading