-
Notifications
You must be signed in to change notification settings - Fork 182
[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
base: main
Are you sure you want to change the base?
Changes from all commits
ddd4d43
b51b929
2005156
01df440
c13eb75
3ad4701
5aecef1
6c5d52c
30ed9b3
286f0b1
49f740e
c6d38d2
15d2459
560ced8
da4989a
4643a68
f4067d6
a085764
247ceae
0b96b91
133debd
7479594
f17d0d2
c25bf86
a5722c4
37b6cbd
5448b4d
baf013a
0aea504
cd72787
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -39,4 +39,4 @@ | |
| "zeptomail": "^6.2.1", | ||
| "zod": "^4.1.9" | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| 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) => { | ||
huamanraj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // Fetch testimonials directly from database without caching | ||
| const testimonials = await ctx.db.prisma.testimonial.findMany({ | ||
| orderBy: { | ||
| createdAt: 'desc', | ||
| }, | ||
| }); | ||
|
|
||
| return testimonials; | ||
| }), | ||
|
|
||
| getMyTestimonial: protectedProcedure.query(async ({ ctx }: any) => { | ||
| const userId = ctx.user.id; | ||
|
|
||
| // Check subscription | ||
| const { isPaidUser } = await userService.checkSubscriptionStatus(ctx.db.prisma, userId); | ||
|
|
||
| if (!isPaidUser) { | ||
| throw new TRPCError({ | ||
| code: "FORBIDDEN", | ||
| message: "Only premium users can submit testimonials", | ||
| }); | ||
| } | ||
huamanraj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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(1000, "Testimonial must be at most 1000 characters"), | ||
| avatar: z.string().url("Invalid avatar URL"), | ||
| socialLink: z.string().url("Invalid social link URL").refine((url) => { | ||
| const supportedPlatforms = [ | ||
| 'twitter.com', | ||
| 'x.com', | ||
| 'linkedin.com', | ||
| 'instagram.com', | ||
| 'youtube.com', | ||
| 'youtu.be', | ||
| ]; | ||
| try { | ||
| const parsedUrl = new URL(url); | ||
| return supportedPlatforms.some(platform => parsedUrl.hostname.includes(platform)); | ||
| } catch { | ||
| return false; | ||
| } | ||
| }, "Only Twitter/X, LinkedIn, Instagram, and YouTube links are supported").optional().or(z.literal('')), | ||
|
Comment on lines
+46
to
+61
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix insecure hostname validation that allows malicious domains. The 🔎 Proposed fix using exact hostname matching- socialLink: z.string().url("Invalid social link URL").refine((url) => {
- const supportedPlatforms = [
- 'twitter.com',
- 'x.com',
- 'linkedin.com',
- 'instagram.com',
- 'youtube.com',
- 'youtu.be',
- ];
- try {
- const parsedUrl = new URL(url);
- return supportedPlatforms.some(platform => parsedUrl.hostname.includes(platform));
- } catch {
- return false;
- }
- }, "Only Twitter/X, LinkedIn, Instagram, and YouTube links are supported").optional().or(z.literal('')),
+ socialLink: z.string().url("Invalid social link URL").refine((url) => {
+ const supportedPlatforms = [
+ 'twitter.com',
+ 'x.com',
+ 'linkedin.com',
+ 'instagram.com',
+ 'youtube.com',
+ 'youtu.be',
+ ];
+ try {
+ const parsedUrl = new URL(url);
+ const hostname = parsedUrl.hostname;
+ // exact match or subdomain of allowed platform
+ return supportedPlatforms.some(platform =>
+ hostname === platform || hostname.endsWith(`.${platform}`)
+ );
+ } catch {
+ return false;
+ }
+ }, "Only Twitter/X, LinkedIn, Instagram, and YouTube links are supported").optional().or(z.literal('')),🤖 Prompt for AI Agents |
||
| })) | ||
| .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", | ||
| }); | ||
| } | ||
|
|
||
|
|
||
|
|
||
| // Check if testimonial already exists - prevent updates | ||
| 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; | ||
| }), | ||
| }); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -34,5 +34,5 @@ export const userRouter = router({ | |
| userId, | ||
| input.completedSteps | ||
| ); | ||
| }), | ||
| }), | ||
| }); | ||
| 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
|
||
Uh oh!
There was an error while loading. Please reload this page.