shorten-url.ts128 lines, 3.4 KB
| 1 | "use server"; |
| 2 | |
| 3 | import { ApiResponse } from "@/lib/types"; |
| 4 | import { ensureHttps, isValidUrl } from "@/lib/utils"; |
| 5 | import { custom, z } from "zod"; |
| 6 | import { nanoid } from "nanoid"; |
| 7 | import { db } from "@/server/db"; |
| 8 | import { urls } from "@/server/db/schema"; |
| 9 | import { revalidatePath } from "next/cache"; |
| 10 | import { auth } from "@/server/auth"; |
| 11 | import { checkUrlSafety } from "./check-url-safety"; |
| 12 | |
| 13 | const shortenUrlSchema = z.object({ |
| 14 | url: z.string().refine(isValidUrl, { |
| 15 | message: "Please enter a valid URL", |
| 16 | }), |
| 17 | customCode: z |
| 18 | .string() |
| 19 | .max(20, "Custom code must be less than 255 characters") |
| 20 | .regex(/^[a-zA-Z0-9_-]+$/, "Custom code must be alphanumeric or hyphen") |
| 21 | .optional() |
| 22 | .nullable() |
| 23 | .transform((val) => (val === null || val === "" ? undefined : val)), |
| 24 | }); |
| 25 | |
| 26 | export async function shortenUrl(formData: FormData): Promise< |
| 27 | ApiResponse<{ |
| 28 | shortUrl: string; |
| 29 | flagged: boolean; |
| 30 | flagReason?: string | null; |
| 31 | message?: string; |
| 32 | }> |
| 33 | > { |
| 34 | try { |
| 35 | const session = await auth(); |
| 36 | const userId = session?.user?.id; |
| 37 | |
| 38 | const url = formData.get("url") as string; |
| 39 | const customCode = formData.get("customCode") as string; |
| 40 | |
| 41 | const validatedFields = shortenUrlSchema.safeParse({ |
| 42 | url, |
| 43 | customCode: customCode ? customCode : undefined, |
| 44 | }); |
| 45 | |
| 46 | if (!validatedFields.success) { |
| 47 | return { |
| 48 | success: false, |
| 49 | error: |
| 50 | validatedFields.error.flatten().fieldErrors.url?.[0] || |
| 51 | validatedFields.error.flatten().fieldErrors.customCode?.[0] || |
| 52 | "Invalid URL", |
| 53 | }; |
| 54 | } |
| 55 | |
| 56 | const originalUrl = ensureHttps(validatedFields.data.url); |
| 57 | |
| 58 | const safetyCheck = await checkUrlSafety(originalUrl); |
| 59 | let flagged = false; |
| 60 | let flagReason = null; |
| 61 | |
| 62 | if (safetyCheck.success && safetyCheck.data) { |
| 63 | flagged = safetyCheck.data.flagged; |
| 64 | flagReason = safetyCheck.data.reason; |
| 65 | |
| 66 | if ( |
| 67 | safetyCheck.data.category === "malicious" && |
| 68 | safetyCheck.data.confidence > 0.7 && |
| 69 | session?.user?.role !== "admin" |
| 70 | ) { |
| 71 | return { |
| 72 | success: false, |
| 73 | error: "This URL is flagged as malicious", |
| 74 | }; |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | const shortCode = validatedFields.data.customCode || nanoid(6); |
| 79 | |
| 80 | // check if the short code already exists |
| 81 | const existingUrl = await db.query.urls.findFirst({ |
| 82 | where: (urls, { eq }) => eq(urls.shortCode, shortCode), |
| 83 | }); |
| 84 | |
| 85 | if (existingUrl) { |
| 86 | if (validatedFields.data.customCode) { |
| 87 | return { |
| 88 | success: false, |
| 89 | error: "Custom code already exists", |
| 90 | }; |
| 91 | } |
| 92 | return shortenUrl(formData); |
| 93 | } |
| 94 | |
| 95 | await db.insert(urls).values({ |
| 96 | originalUrl, |
| 97 | shortCode, |
| 98 | createdAt: new Date(), |
| 99 | updatedAt: new Date(), |
| 100 | userId: userId || null, |
| 101 | flagged, |
| 102 | flagReason, |
| 103 | }); |
| 104 | |
| 105 | const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"; |
| 106 | const shortUrl = `${baseUrl}/r/${shortCode}`; |
| 107 | |
| 108 | revalidatePath("/"); |
| 109 | |
| 110 | return { |
| 111 | success: true, |
| 112 | data: { |
| 113 | shortUrl, |
| 114 | flagged, |
| 115 | flagReason, |
| 116 | message: flagged |
| 117 | ? "This URL has been flagged for review by our safety system. It may be temporarily limited until approved by an administrator." |
| 118 | : undefined, |
| 119 | }, |
| 120 | }; |
| 121 | } catch (error) { |
| 122 | console.error("Failed to shorten URL", error); |
| 123 | return { |
| 124 | success: false, |
| 125 | error: "Failed to shorten URL", |
| 126 | }; |
| 127 | } |
| 128 | } |