-
Notifications
You must be signed in to change notification settings - Fork 116
feat: newsletter page for pro users #155 #158
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
huamanraj
wants to merge
2
commits into
apsinghdev:main
Choose a base branch
from
huamanraj:feat_newsletter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
149 changes: 149 additions & 0 deletions
149
apps/web/src/app/(main)/dashboard/newsletters/[slug]/page.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }} | ||
| /> | ||
| </article> | ||
| </div> | ||
| </div> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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([]); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
Verify server-side HTML sanitization to prevent XSS.
Using
dangerouslySetInnerHTMLwithout 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:
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
dangerouslySetInnerHTMLwith markdown-parsed content requires explicit sanitization:apps/web/src/app/api/newsletters/[slug]/route.ts) applies sanitization aftermarked.parse()- either using DOMPurify, sanitize-html, or another library.page.tsxlines 141-144) doesn't sanitize the HTML beforedangerouslySetInnerHTML. If no sanitization exists in either location, implement sanitization using DOMPurify or another security-focused library.🏁 Script executed:
Length of output: 258
Let me search for the actual file locations:
Length of output: 263
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.tsline 41) parses markdown withmarked.parse()without any sanitization, and the frontend component (page.tsxlines 141-144) renders this unsanitized HTML withdangerouslySetInnerHTML. This creates an XSS vulnerability where malicious JavaScript embedded in markdown content would execute.Recommended fix:
DOMPurifyorsanitize-htmlto sanitize the HTML output frommarked.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)