-
Notifications
You must be signed in to change notification settings - Fork 186
[Feat] pro users testimonials page with redis caching #262
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
21
commits into
apsinghdev:main
Choose a base branch
from
huamanraj:feat/testimonials-page
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
21 commits
Select commit
Hold shift + click to select a range
9663a18
added back navbar to layout file
praveenzsp 605875a
lint fix
praveenzsp d7dcb6f
fix: typos in blog titles
Lucifer-0612 f7d8ba3
fix: normalize blog titles to lowercase
Lucifer-0612 b1e0fd8
chore: extend offer
apsinghdev 34b63be
feat: OSS programs added with data
huamanraj 0563959
fix: fix jsdom esmodule requirement err
apsinghdev 69a7161
fix: ui repsnsiveness and design
huamanraj ee54a2d
feat: Implement testimonials management with Redis caching
huamanraj 1cbfb85
fix: type fixes and image validation
huamanraj a350b4d
fix: redirect protection to prevent SSRF
huamanraj 64331c1
fix: added links to testimnial and payment fix
huamanraj 71c256c
build fix
huamanraj 2839e99
redis removed for testimonials
huamanraj 045a93b
fix: improve testimonial URL validation
huamanraj ee0df8e
add migration
apsinghdev 546c747
chore: fix the typeErr
apsinghdev d191b6e
chore: hide the char limit
apsinghdev cfa2360
feat: add the final tweeks in testimonials
apsinghdev 345fc68
chore: fix the join button
apsinghdev e3f4f38
fix: fix the race condition in checkout page
apsinghdev 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
Some comments aren't visible on the classic Files Changed page.
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
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 |
|---|---|---|
|
|
@@ -42,4 +42,4 @@ | |
| "prisma": { | ||
| "seed": "tsx prisma/seed.ts" | ||
| } | ||
| } | ||
| } | ||
19 changes: 19 additions & 0 deletions
19
apps/api/prisma/migrations/20251218121459_add_testimonials/migration.sql
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,19 @@ | ||
| -- CreateTable | ||
| CREATE TABLE "Testimonial" ( | ||
| "id" TEXT NOT NULL, | ||
| "userId" TEXT NOT NULL, | ||
| "content" TEXT NOT NULL, | ||
| "name" TEXT NOT NULL, | ||
| "avatar" TEXT NOT NULL, | ||
| "socialLink" TEXT, | ||
| "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
| "updatedAt" TIMESTAMP(3) NOT NULL, | ||
|
|
||
| CONSTRAINT "Testimonial_pkey" PRIMARY KEY ("id") | ||
| ); | ||
|
|
||
| -- CreateIndex | ||
| CREATE UNIQUE INDEX "Testimonial_userId_key" ON "Testimonial"("userId"); | ||
|
|
||
| -- AddForeignKey | ||
| ALTER TABLE "Testimonial" ADD CONSTRAINT "Testimonial_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; |
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
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
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,129 @@ | ||
| import { router, protectedProcedure, publicProcedure } from "../trpc.js"; | ||
| import { z } from "zod"; | ||
| import { userService } from "../services/user.service.js"; | ||
| import { TRPCError } from "@trpc/server"; | ||
| import { validateAvatarUrl } from "../utils/avatar-validator.js"; | ||
|
|
||
| export const testimonialRouter = router({ | ||
| getAll: publicProcedure.query(async ({ ctx }: any) => { | ||
| const testimonials = await ctx.db.prisma.testimonial.findMany({ | ||
| orderBy: { | ||
| createdAt: "desc", | ||
| }, | ||
| }); | ||
|
|
||
| return testimonials; | ||
| }), | ||
|
|
||
| getMyTestimonial: protectedProcedure.query(async ({ ctx }: any) => { | ||
| const userId = ctx.user.id; | ||
|
|
||
| const { isPaidUser } = await userService.checkSubscriptionStatus( | ||
| ctx.db.prisma, | ||
| userId | ||
| ); | ||
|
|
||
| if (!isPaidUser) { | ||
| throw new TRPCError({ | ||
| code: "FORBIDDEN", | ||
| message: "Only premium users can submit testimonials", | ||
| }); | ||
| } | ||
|
|
||
| const testimonial = await ctx.db.prisma.testimonial.findUnique({ | ||
| where: { userId }, | ||
| }); | ||
|
|
||
| return { | ||
| testimonial, | ||
| }; | ||
| }), | ||
|
|
||
| submit: protectedProcedure | ||
| .input( | ||
| z.object({ | ||
| name: z | ||
| .string() | ||
| .min(1, "Name is required") | ||
| .max(40, "Name must be at most 40 characters"), | ||
| content: z | ||
| .string() | ||
| .min(10, "Testimonial must be at least 10 characters") | ||
| .max(1500, "Testimonial must be at most 1500 characters"), | ||
| avatar: z.url(), | ||
| socialLink: z | ||
| .string() | ||
| .optional() | ||
| .refine( | ||
| (val) => { | ||
| if (!val || val === "") return true; | ||
| try { | ||
| const parsedUrl = new URL(val); | ||
| const supportedPlatforms = [ | ||
| "twitter.com", | ||
| "x.com", | ||
| "linkedin.com", | ||
| "instagram.com", | ||
| "youtube.com", | ||
| "youtu.be", | ||
| ]; | ||
| return supportedPlatforms.some( | ||
| (platform) => | ||
| parsedUrl.hostname === platform || | ||
| parsedUrl.hostname.endsWith("." + platform) | ||
| ); | ||
| } catch { | ||
| return false; | ||
| } | ||
| }, | ||
| { | ||
| message: | ||
| "Must be a valid Twitter/X, LinkedIn, Instagram, or YouTube URL", | ||
| } | ||
| ) | ||
| .or(z.literal("")), | ||
| }) | ||
| ) | ||
| .mutation(async ({ ctx, input }: any) => { | ||
| const userId = ctx.user.id; | ||
|
|
||
| const { isPaidUser } = await userService.checkSubscriptionStatus( | ||
| ctx.db.prisma, | ||
| userId | ||
| ); | ||
|
|
||
| if (!isPaidUser) { | ||
| throw new TRPCError({ | ||
| code: "FORBIDDEN", | ||
| message: "Only premium users can submit testimonials", | ||
| }); | ||
| } | ||
|
|
||
| const existingTestimonial = await ctx.db.prisma.testimonial.findUnique({ | ||
| where: { userId }, | ||
| }); | ||
|
|
||
| if (existingTestimonial) { | ||
| throw new TRPCError({ | ||
| code: "BAD_REQUEST", | ||
| message: | ||
| "You have already submitted a testimonial. Testimonials cannot be edited once submitted.", | ||
| }); | ||
| } | ||
|
|
||
| // Validate avatar URL with strict security checks | ||
| await validateAvatarUrl(input.avatar); | ||
|
|
||
| const result = await ctx.db.prisma.testimonial.create({ | ||
| data: { | ||
| userId, | ||
| name: input.name, | ||
| content: input.content, | ||
| avatar: input.avatar, | ||
| socialLink: input.socialLink || null, | ||
| }, | ||
| }); | ||
|
|
||
| return result; | ||
| }), | ||
| }); |
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 |
|---|---|---|
|
|
@@ -34,5 +34,5 @@ export const userRouter = router({ | |
| userId, | ||
| input.completedSteps | ||
| ); | ||
| }), | ||
| }), | ||
| }); | ||
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
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,172 @@ | ||
| import { TRPCError } from "@trpc/server"; | ||
| import { isIP } from "net"; | ||
|
|
||
| // Configuration | ||
| const ALLOWED_IMAGE_HOSTS = [ | ||
| "avatars.githubusercontent.com", | ||
| "lh3.googleusercontent.com", | ||
| "graph.facebook.com", | ||
| "pbs.twimg.com", | ||
| "cdn.discordapp.com", | ||
| "i.imgur.com", | ||
| "res.cloudinary.com", | ||
| "ik.imagekit.io", | ||
| "images.unsplash.com", | ||
| "ui-avatars.com", | ||
| ]; | ||
|
|
||
| const MAX_IMAGE_SIZE_BYTES = 5 * 1024 * 1024; // 5MB | ||
| const REQUEST_TIMEOUT_MS = 5000; // 5 seconds | ||
|
|
||
| // Private IP ranges | ||
| const PRIVATE_IP_RANGES = [ | ||
| /^127\./, // 127.0.0.0/8 (localhost) | ||
| /^10\./, // 10.0.0.0/8 | ||
| /^172\.(1[6-9]|2[0-9]|3[0-1])\./, // 172.16.0.0/12 | ||
| /^192\.168\./, // 192.168.0.0/16 | ||
| /^169\.254\./, // 169.254.0.0/16 (link-local) | ||
| /^::1$/, // IPv6 localhost | ||
| /^fe80:/, // IPv6 link-local | ||
| /^fc00:/, // IPv6 unique local | ||
| /^fd00:/, // IPv6 unique local | ||
huamanraj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ]; | ||
|
|
||
| /** | ||
| * Validates if an IP address is private or localhost | ||
| */ | ||
| function isPrivateOrLocalIP(ip: string): boolean { | ||
| return PRIVATE_IP_RANGES.some((range) => range.test(ip)); | ||
| } | ||
|
|
||
| /** | ||
| * Validates avatar URL with strict security checks | ||
| * @param avatarUrl - The URL to validate | ||
| * @throws TRPCError if validation fails | ||
| */ | ||
| export async function validateAvatarUrl(avatarUrl: string): Promise<void> { | ||
| // Step 1: Basic URL format validation | ||
| let parsedUrl: URL; | ||
| try { | ||
| parsedUrl = new URL(avatarUrl); | ||
| } catch (error) { | ||
| throw new TRPCError({ | ||
| code: "BAD_REQUEST", | ||
| message: "Invalid avatar URL format", | ||
| }); | ||
| } | ||
|
|
||
| // Step 2: Require HTTPS scheme | ||
| if (parsedUrl.protocol !== "https:") { | ||
| throw new TRPCError({ | ||
| code: "BAD_REQUEST", | ||
| message: "Avatar URL must use HTTPS protocol", | ||
| }); | ||
| } | ||
|
|
||
| // Step 3: Extract and validate hostname | ||
| const hostname = parsedUrl.hostname; | ||
|
|
||
| // Step 4: Reject direct IP addresses | ||
| if (isIP(hostname)) { | ||
| throw new TRPCError({ | ||
| code: "BAD_REQUEST", | ||
| message: "Avatar URL cannot be a direct IP address. Please use a trusted image hosting service.", | ||
| }); | ||
| } | ||
|
|
||
| // Step 5: Check for localhost or private IP ranges | ||
| if (isPrivateOrLocalIP(hostname)) { | ||
| throw new TRPCError({ | ||
| code: "BAD_REQUEST", | ||
| message: "Avatar URL cannot point to localhost or private network addresses", | ||
| }); | ||
| } | ||
|
|
||
| // Step 6: Validate against allowlist of trusted hosts | ||
| const isAllowedHost = ALLOWED_IMAGE_HOSTS.some((allowedHost) => { | ||
| return hostname === allowedHost || hostname.endsWith(`.${allowedHost}`); | ||
| }); | ||
|
|
||
| if (!isAllowedHost) { | ||
| throw new TRPCError({ | ||
| code: "BAD_REQUEST", | ||
| message: `Avatar URL must be from a trusted image hosting service. Allowed hosts: ${ALLOWED_IMAGE_HOSTS.join(", ")}`, | ||
| }); | ||
| } | ||
|
|
||
huamanraj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // Step 7: Perform server-side HEAD request to validate the resource | ||
| try { | ||
| const controller = new AbortController(); | ||
| const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); | ||
|
|
||
| const response = await fetch(avatarUrl, { | ||
| method: "HEAD", | ||
| signal: controller.signal, | ||
| redirect: "error", | ||
| headers: { | ||
| "User-Agent": "OpenSox-Avatar-Validator/1.0", | ||
| }, | ||
| }); | ||
|
|
||
| clearTimeout(timeoutId); | ||
|
|
||
| // Check if request was successful | ||
| if (!response.ok) { | ||
| throw new TRPCError({ | ||
| code: "BAD_REQUEST", | ||
| message: `Avatar URL is not accessible (HTTP ${response.status})`, | ||
| }); | ||
| } | ||
|
|
||
| // Step 8: Validate Content-Type is an image | ||
| const contentType = response.headers.get("content-type"); | ||
| if (!contentType || !contentType.startsWith("image/")) { | ||
| throw new TRPCError({ | ||
| code: "BAD_REQUEST", | ||
| message: `Avatar URL must point to an image file. Received content-type: ${contentType || "unknown"}`, | ||
| }); | ||
| } | ||
|
|
||
| // Step 9: Validate Content-Length is within limits | ||
| const contentLength = response.headers.get("content-length"); | ||
| if (contentLength) { | ||
| const sizeBytes = parseInt(contentLength, 10); | ||
| if (sizeBytes > MAX_IMAGE_SIZE_BYTES) { | ||
| throw new TRPCError({ | ||
| code: "BAD_REQUEST", | ||
| message: `Avatar image is too large. Maximum size: ${MAX_IMAGE_SIZE_BYTES / 1024 / 1024}MB`, | ||
| }); | ||
| } | ||
| } | ||
| } catch (error) { | ||
| // Handle fetch errors | ||
| if (error instanceof TRPCError) { | ||
| throw error; | ||
| } | ||
|
|
||
| if ((error as Error).name === "AbortError") { | ||
| throw new TRPCError({ | ||
| code: "BAD_REQUEST", | ||
| message: "Avatar URL validation timed out. The image may be too large or the server is unresponsive.", | ||
| }); | ||
| } | ||
|
|
||
| throw new TRPCError({ | ||
| code: "BAD_REQUEST", | ||
| message: `Failed to validate avatar URL: ${(error as Error).message}`, | ||
| }); | ||
| } | ||
| } | ||
huamanraj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /** | ||
| * Zod custom refinement for avatar URL validation | ||
| * Use this with .refine() on a z.string().url() schema | ||
| */ | ||
| export async function avatarUrlRefinement(url: string): Promise<boolean> { | ||
| try { | ||
| await validateAvatarUrl(url); | ||
| return true; | ||
| } catch (error) { | ||
| return false; | ||
| } | ||
| } | ||
huamanraj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.