Connect, collaborate, and grow with a community of TypeScript developers
feat: url-shortener (#1507)
Ayush Kumar Yadav0c76c5fc1b84
diff --git a/apps/web/package.json b/apps/web/package.jsonindex fd7ed24c..193b1e2b 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -54,6 +54,7 @@"lz-string": "^1.5.0","million": "2.6.0-beta.12","monaco-vim": "^0.4.0",+ "nanoid": "^5.0.7","next": "14.2.5","next-themes": "^0.2.1","react": "18.2.0",diff --git a/apps/web/src/app/api/cron/short-url-cleanup/route.ts b/apps/web/src/app/api/cron/short-url-cleanup/route.tsnew file mode 100644index 00000000..cbccd236--- /dev/null+++ b/apps/web/src/app/api/cron/short-url-cleanup/route.ts@@ -0,0 +1,28 @@+import { prisma } from '@repo/db';+import type { NextRequest } from 'next/server';++export async function GET(request: NextRequest) {+ const authHeader = request.headers.get('authorization');+ if (authHeader !== `Bearer ${process.env.CRON_SECRET}` && process.env.NODE_ENV === 'production') {+ return new Response('Unauthorized', {+ status: 401,+ });+ }++ try {+ await prisma.shortURL.deleteMany({+ where: {+ expiresAt: {+ lte: new Date(),+ },+ },+ });+ } catch (error) {+ console.log(error);+ return new Response('Internal Server Error', {+ status: 500,+ });+ }++ return Response.json({ success: true });+}diff --git a/apps/web/src/app/challenge/_components/description/index.tsx b/apps/web/src/app/challenge/_components/description/index.tsxindex f79a1d23..1b992d35 100644--- a/apps/web/src/app/challenge/_components/description/index.tsx+++ b/apps/web/src/app/challenge/_components/description/index.tsx@@ -23,11 +23,11 @@ import { type ChallengeRouteData } from '~/app/challenge/[slug]/getChallengeRoutimport { ReportDialog } from '~/components/ReportDialog';import { getRelativeTimeStrict } from '~/utils/relativeTime';import { addOrRemoveBookmark } from '../bookmark.action';-import { ShareForm } from '../share-form';import { Vote } from '../vote';import { AOT_CHALLENGES } from '../../[slug]/aot-slugs';import { Suggestions } from './suggestions';import { UserBadge } from '../comments/enhanced-user-badge';+import { ShareUrl } from '~/components/share-url';interface Props {challenge: ChallengeRouteData['challenge'];@@ -144,10 +144,11 @@ export function Description({ challenge }: Props) {<DialogTitle>Share</DialogTitle></DialogHeader><div className="pt-4">- <ShareForm />+ <ShareUrl isChallenge /></div></DialogContent></Dialog>+<Tooltip><TooltipTrigger asChild><Buttondiff --git a/apps/web/src/app/challenge/_components/share-form.tsx b/apps/web/src/app/challenge/_components/share-form.tsxdeleted file mode 100644index bda9723d..00000000--- a/apps/web/src/app/challenge/_components/share-form.tsx+++ /dev/null@@ -1,80 +0,0 @@-'use client';--import { Checkbox } from '@repo/ui/components/checkbox';-import { DialogFooter } from '@repo/ui/components/dialog';-import { CheckCircle2 as CheckCircle2Icon, Clipboard as ClipboardIcon } from '@repo/ui/icons';-import lzstring from 'lz-string';-import { useParams } from 'next/navigation';-import { useCallback, useState } from 'react';-import { useLocalStorage } from '~/utils/useLocalStorage';--export function ShareForm() {- const { slug } = useParams();- const [copied, setCopied] = useState(false);- const [copyWithCode, setCopyWithCode] = useState(false);- const [codeToCompress] = useLocalStorage(`challenge-${slug}`, '');- const url = `${window.location.origin}/challenge/${slug}`;-- const copyToClipboard = useCallback(async () => {- let url = `${window.location.origin}/challenge/${slug}`;- if (copyWithCode && codeToCompress) {- const compressedCode = lzstring.compressToEncodedURIComponent(codeToCompress);- url += `?code=${compressedCode}`;- }-- try {- if (navigator.clipboard && !copied) {- await navigator.clipboard.writeText(url);- setCopied(true);- window.setTimeout(() => setCopied(false), 3000);- }- } catch (e) {- console.error('copyToClipboard', e);- setCopied(false);- }- }, [slug, copied, copyWithCode, codeToCompress]);-- const onCopyWithCodeChange = useCallback((checked: boolean) => {- setCopyWithCode(checked);- }, []);-- return (- <div className="flex flex-col space-y-4">- <p>Copy this challenge url to share with your friends!</p>- <code className="rounded-lg border border-black/20 px-4 py-2 dark:border-white/20">- {url}- </code>-- <DialogFooter>- <div className="flex items-center justify-end gap-2">- {Boolean(codeToCompress) && (- <div className="flex h-fit items-center justify-center gap-2 text-xs">- <Checkbox- id="copy-with-code"- checked={copyWithCode}- onCheckedChange={onCopyWithCodeChange}- />- <label htmlFor="copy-with-code">Copy with code</label>- </div>- )}- <button- className={`flex items-center justify-between space-x-2 rounded-lg px-2 py-1 duration-300 active:scale-75- ${- copied- ? 'border border-green-500 text-green-500 dark:border-green-700 dark:bg-green-700 dark:text-white'- : 'border border-black/20 text-black hover:bg-gray-100 dark:bg-white'- }`}- onClick={copyToClipboard}- >- <span>{copied ? 'Copied!' : 'Copy'}</span>- {copied ? (- <CheckCircle2Icon className="h-4 w-4" />- ) : (- <ClipboardIcon className="h-4 w-4" />- )}- </button>- </div>- </DialogFooter>- </div>- );-}diff --git a/apps/web/src/app/share/[slug]/page.tsx b/apps/web/src/app/share/[slug]/page.tsxnew file mode 100644index 00000000..a33abc82--- /dev/null+++ b/apps/web/src/app/share/[slug]/page.tsx@@ -0,0 +1,20 @@+import { notFound, permanentRedirect } from 'next/navigation';+import { getLongURL } from '../_actions/get-long-url';+import { updateClick } from '../_actions/update-click-count';++interface Props {+ params: {+ slug: string;+ };+}++export default async function Page({ params }: Props) {+ const { slug } = params;+ const longURL = await getLongURL(slug);++ if (!longURL) return notFound();++ await updateClick(slug);++ return permanentRedirect(longURL);+}diff --git a/apps/web/src/app/share/_actions/create-url-with-slug/index.ts b/apps/web/src/app/share/_actions/create-url-with-slug/index.tsnew file mode 100644index 00000000..fa3246c6--- /dev/null+++ b/apps/web/src/app/share/_actions/create-url-with-slug/index.ts@@ -0,0 +1,45 @@+'use server';+import { auth } from '~/server/auth';+import { prisma } from '@repo/db';+import { getBaseUrl } from '~/utils/getBaseUrl';+import { THREE_MONTHS } from '../increment-time';+import { isAdmin } from '~/utils/auth-guards';++export async function createShortURLWithSlug(url: string, slug: string): Promise<string | null> {+ const session = await auth();+ const baseURL = getBaseUrl();+ if (!session) {+ return null;+ }++ // check for admin role to create a short URL with a custom slug+ if (!isAdmin(session)) {+ return null;+ }++ const existingSlug = await prisma.shortURL.findUnique({+ where: {+ shortUrlSlug: slug,+ },+ });++ if (existingSlug) {+ return null;+ }++ await prisma.shortURL.create({+ data: {+ shortUrlSlug: slug,+ originalUrl: url,+ expiresAt: new Date(Date.now() + THREE_MONTHS),+ user: {+ connect: {+ id: session.user.id,+ },+ },+ },+ });++ const newURL = `${baseURL}/share/${slug}`;+ return newURL;+}diff --git a/apps/web/src/app/share/_actions/create-url/index.ts b/apps/web/src/app/share/_actions/create-url/index.tsnew file mode 100644index 00000000..303474b5--- /dev/null+++ b/apps/web/src/app/share/_actions/create-url/index.ts@@ -0,0 +1,53 @@+'use server';++import { newShortURLSlug } from '../shortUrlSlug';+import { prisma } from '@repo/db';+import { getBaseUrl } from '~/utils/getBaseUrl';+import { THREE_MONTHS } from '../increment-time';+import { headers } from 'next/headers';+import { rateLimit } from '~/utils/rateLimit';++interface CreateShortURLConfig {+ forceNewUrl?: boolean;+ expiresAt?: Date;+}++export async function createShortURL(+ url: string,+ config = {} as CreateShortURLConfig,+): Promise<string | null> {+ // Rate limit the creation of new short URLs+ const ip = headers().get('x-forwarded-for') ?? 'unknown';+ const isRateLimited = rateLimit(ip);+ if (isRateLimited) {+ console.error('Rate limited:', ip);+ return null;+ }++ const baseURL = getBaseUrl();+ const slug = newShortURLSlug();++ if (!config.forceNewUrl) {+ // check if the long url already exists+ const existing = await prisma.shortURL.findFirst({+ where: {+ originalUrl: url,+ },+ });++ if (existing) {+ return `${baseURL}/share/${existing.shortUrlSlug}`;+ }+ }++ await prisma.shortURL.create({+ data: {+ shortUrlSlug: slug,+ originalUrl: url,+ expiresAt: config.expiresAt ?? new Date(Date.now() + THREE_MONTHS),+ },+ });++ const newURL = `${baseURL}/share/${slug}`;+ return newURL;+}diff --git a/apps/web/src/app/share/_actions/get-long-url/index.ts b/apps/web/src/app/share/_actions/get-long-url/index.tsnew file mode 100644index 00000000..b22ed7ed--- /dev/null+++ b/apps/web/src/app/share/_actions/get-long-url/index.ts@@ -0,0 +1,13 @@+import { prisma } from '@repo/db';++export async function getLongURL(slug: string): Promise<string | null> {+ const url = await prisma.shortURL.findUnique({+ where: {+ shortUrlSlug: slug,+ },+ });+ if (url) {+ return url.originalUrl;+ }+ return null;+}diff --git a/apps/web/src/app/share/_actions/increment-time.ts b/apps/web/src/app/share/_actions/increment-time.tsnew file mode 100644index 00000000..ede08459--- /dev/null+++ b/apps/web/src/app/share/_actions/increment-time.ts@@ -0,0 +1,8 @@+export const ONE_MONTH =+ 1000 * // milliseconds (1 second)+ 60 * // seconds (1 minute)+ 60 * // minutes (1 hour)+ 24 * // hours (1 day)+ 30; // days (1 month)++export const THREE_MONTHS = ONE_MONTH * 3;diff --git a/apps/web/src/app/share/_actions/shortUrlSlug.ts b/apps/web/src/app/share/_actions/shortUrlSlug.tsnew file mode 100644index 00000000..58bc6d47--- /dev/null+++ b/apps/web/src/app/share/_actions/shortUrlSlug.ts@@ -0,0 +1,9 @@+import { customAlphabet } from 'nanoid';++// removed confusing characters from the alphabet (0, O, I, l) for the URL+const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz123456789';++export function newShortURLSlug(): string {+ const nanoid = customAlphabet(alphabet, 7); // fixed slug size = 7+ return nanoid();+}diff --git a/apps/web/src/app/share/_actions/update-click-count/index.ts b/apps/web/src/app/share/_actions/update-click-count/index.tsnew file mode 100644index 00000000..92393f5b--- /dev/null+++ b/apps/web/src/app/share/_actions/update-click-count/index.ts@@ -0,0 +1,17 @@+import { prisma } from '@repo/db';+import { ONE_MONTH } from '../increment-time';++export async function updateClick(slug: string): Promise<void> {+ await prisma.shortURL.update({+ where: {+ shortUrlSlug: slug,+ },+ data: {+ // increase the expiration date by one month on each click+ expiresAt: new Date(Date.now() + ONE_MONTH),+ clicks: {+ increment: 1,+ },+ },+ });+}diff --git a/apps/web/src/app/share/_components/greet-user.tsx b/apps/web/src/app/share/_components/greet-user.tsxnew file mode 100644index 00000000..b2d44175--- /dev/null+++ b/apps/web/src/app/share/_components/greet-user.tsx@@ -0,0 +1,12 @@+import { auth } from '~/server/auth';++export async function GreetUser() {+ const session = await auth();+ return (+ <div className="flex flex-col items-center justify-center">+ <p>+ Welcome <span className="font-semibold">@{session?.user.name}</span>+ </p>+ </div>+ );+}diff --git a/apps/web/src/app/share/_components/url-shortner-form.tsx b/apps/web/src/app/share/_components/url-shortner-form.tsxnew file mode 100644index 00000000..28e4c4d8--- /dev/null+++ b/apps/web/src/app/share/_components/url-shortner-form.tsx@@ -0,0 +1,175 @@+'use client';+import * as React from 'react';+import { Input } from '@repo/ui/components/input';+import { Button } from '@repo/ui/components/button';+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from '@repo/ui/components/form';+import { zodResolver } from '@hookform/resolvers/zod';+import { useForm } from 'react-hook-form';+import { z } from 'zod';+import { useToast } from '@repo/ui/components/use-toast';+import { createShortURLWithSlug } from '../_actions/create-url-with-slug';+import { createShortURL } from '../_actions/create-url';+import { Clipboard, ExternalLink } from '@repo/ui/icons';+import { getBaseUrl } from '~/utils/getBaseUrl';++const FormSchema = z.object({+ url: z.string().url({+ message: 'Please enter a valid URL e.g. https://typehero.dev',+ }),+ slug: z.string().optional(),+});++export function URLShortnerForm() {+ const [shortURL, setShortURL] = React.useState<string | null>(null);+ const { toast } = useToast();+ const baseURL = `${getBaseUrl()}/share`;+ const form = useForm<z.infer<typeof FormSchema>>({+ mode: 'onChange',+ resolver: zodResolver(FormSchema),+ defaultValues: {+ url: '',+ slug: '',+ },+ });++ const handleShareClick = async () => {+ if (navigator.clipboard) {+ const url = window.location.href;+ await navigator.clipboard.writeText(url);+ toast({+ variant: 'success',+ description: 'Link To Short URL Copied!',+ title: 'Copied',+ });+ }+ };++ async function onSubmit(data: z.infer<typeof FormSchema>) {+ setShortURL(null);+ if (data.slug && data.slug.length > 0) {+ const shortURL = await createShortURLWithSlug(data.url, data.slug);+ if (shortURL) {+ toast({+ title: 'Short URL created',+ description: shortURL,+ variant: 'success',+ });+ setShortURL(shortURL);+ } else if (shortURL === null) {+ toast({+ title: `Slug '/${data.slug}' already exists`,+ description: 'Please try another slug',+ variant: 'destructive',+ });+ } else+ toast({+ title: 'Something went wrong',+ description: 'Error creating short URL',+ variant: 'destructive',+ });+ } else {+ const shortURL = await createShortURL(data.url);+ if (shortURL) {+ toast({+ title: 'Short URL created',+ description: shortURL,+ variant: 'success',+ });+ setShortURL(shortURL);+ } else {+ toast({+ title: 'Error creating short URL',+ description: 'Please try again',+ variant: 'destructive',+ });+ }+ }+ }++ return (+ <Form {...form}>+ <form className="z-10 flex flex-col space-y-4" onSubmit={form.handleSubmit(onSubmit)}>+ <FormField+ control={form.control}+ name="url"+ render={({ field }) => (+ <FormItem>+ <FormLabel>URL</FormLabel>+ <FormControl>+ <Input+ placeholder="https://typehero.dev/tracks/typescript-foundations"+ autoFocus+ className="border-slate-400 dark:border-slate-800"+ {...field}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="slug"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Custom Slug (Optional)</FormLabel>+ <FormControl>+ <div className="flex items-center">+ <p className="border-r-none rounded-l-lg border border-slate-400 bg-slate-100 p-[5.5px] px-3 text-lg dark:border-slate-800 dark:bg-slate-800">+ {baseURL}/+ </p>+ <Input+ placeholder="virus-link"+ {...field}+ className="rounded-l-none border-l-0 border-slate-400 dark:border-slate-800"+ />+ </div>+ </FormControl>+ <FormDescription>Leave empty to auto-generate a slug</FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />++ <Button+ disabled={+ !form.formState.isDirty || !form.formState.isValid || form.formState.isSubmitting+ }+ type="submit"+ variant="secondary"+ className="border border-slate-400 dark:border-slate-800"+ >+ Shorten+ </Button>+ {shortURL ? (+ <div className="flex w-full flex-col items-center gap-2 md:flex-row">+ <div className="flex-grow rounded-xl border border-green-900 px-4 py-1.5">+ <span className="text-muted-foreground mr-1 text-sm">Short URL: </span>+ <span className="text-sm">{shortURL}</span>+ </div>+ <div className="flex items-center gap-2">+ <Button onClick={handleShareClick} size="sm" type="button" variant="secondary">+ <Clipboard className="mr-1 h-4 w-4" />+ Copy+ </Button>+ <a href={shortURL}>+ <Button size="sm" type="button" variant="link">+ Test URL+ <ExternalLink className="ml-1 h-4 w-4" />+ </Button>+ </a>+ </div>+ </div>+ ) : null}+ </form>+ </Form>+ );+}diff --git a/apps/web/src/app/share/page.tsx b/apps/web/src/app/share/page.tsxnew file mode 100644index 00000000..405679fc--- /dev/null+++ b/apps/web/src/app/share/page.tsx@@ -0,0 +1,25 @@+import { isAdmin } from '~/utils/auth-guards';+import { GreetUser } from './_components/greet-user';+import { URLShortnerForm } from './_components/url-shortner-form';+import { auth } from '~/server/auth';+import { notFound } from 'next/navigation';++export default async function Home() {+ const session = await auth();+ if (!isAdmin(session)) {+ return notFound();+ }+ return (+ <main className="relative flex h-screen w-screen items-center justify-center">+ <div className="relative space-y-2 p-2">+ <div className="z-10 rounded-xl border p-6 shadow">+ <h1 className="text-primary/50 rounded-2xl p-4 text-2xl font-bold md:text-5xl">+ TypeHero URL Shortner+ </h1>+ <GreetUser />+ <URLShortnerForm />+ </div>+ </div>+ </main>+ );+}diff --git a/apps/web/src/components/Navigation/index.tsx b/apps/web/src/components/Navigation/index.tsxindex c334f33e..ad053a62 100644--- a/apps/web/src/components/Navigation/index.tsx+++ b/apps/web/src/components/Navigation/index.tsx@@ -6,10 +6,10 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from '@repo/ui/components/dropdown-menu';-import { Play, Settings, Settings2, User, Palette } from '@repo/ui/icons';+import { ExternalLink, Play, Settings, Settings2, User, Palette } from '@repo/ui/icons';import Link from 'next/link';import { Suspense } from 'react';-import { isAdminOrModerator } from '~/utils/auth-guards';+import { isAdmin, isAdminOrModerator } from '~/utils/auth-guards';import { getAllFlags } from '~/utils/feature-flags';import { Search } from '../search/search';import { LoginLink } from './login-link';@@ -41,6 +41,7 @@ export async function Navigation() {getNotificationCount(),]);const isAdminOrMod = isAdminOrModerator(session);+ const isAdminRole = isAdmin(session);const TopSectionLinks = (<>@@ -79,6 +80,7 @@ export async function Navigation() {{isAdminOrMod ? (<NavLink title="Challenge Playground" href="/challenge-playground" />) : null}+ {isAdminRole ? <NavLink title="URL Shortner" href="/share" /> : null}<SignOutLink className="px-0" /></>) : (@@ -130,7 +132,7 @@ export async function Navigation() {</Suspense>{session ? <NotificationLink notificationCount={notificationCount} /> : null}{featureFlags?.enableLogin ? (- <LoginButton isAdminOrMod={isAdminOrMod} session={session} />+ <LoginButton isAdminOrMod={isAdminOrMod} session={session} isAdmin={isAdminRole} />) : null}<MobileNav>{NavLinks}</MobileNav></div>@@ -143,9 +145,11 @@ export async function Navigation() {async function LoginButton({isAdminOrMod,+ isAdmin,session,}: {isAdminOrMod: boolean;+ isAdmin: boolean;session: Session | null;}) {return session?.user ? (@@ -203,6 +207,14 @@ async function LoginButton({</DropdownMenuItem></a>) : null}+ {isAdmin ? (+ <a className="block" href="/share">+ <DropdownMenuItem className="focus:bg-accent rounded-lg p-2 duration-300 focus:outline-none dark:hover:bg-neutral-700/50">+ <ExternalLink className="mr-2 h-4 w-4" />+ <span>URL Shortner</span>+ </DropdownMenuItem>+ </a>+ ) : null}<DropdownMenuSeparator /><SignOutLink className="w-full rounded-b-lg rounded-t-sm" />diff --git a/apps/web/src/components/share-url.tsx b/apps/web/src/components/share-url.tsxnew file mode 100644index 00000000..9eb6022f--- /dev/null+++ b/apps/web/src/components/share-url.tsx@@ -0,0 +1,117 @@+'use client';+import { useState, useCallback } from 'react';+import { useParams } from 'next/navigation';+import lzstring from 'lz-string';+import { createShortURL } from '~/app/share/_actions/create-url';+import { useLocalStorage } from '~/utils/useLocalStorage';+import { Checkbox } from '@repo/ui/components/checkbox';+import { CheckCircle2, Clipboard } from '@repo/ui/icons';+import { DialogFooter } from '@repo/ui/components/dialog';+import { useToast } from '@repo/ui/components/use-toast';++interface ShareShortUrlProps {+ desciprtion?: string;+ isChallenge?: boolean;+}++export function ShareUrl({ desciprtion, isChallenge = false }: ShareShortUrlProps) {+ const { slug } = useParams();+ const { toast } = useToast();+ const shareType = isChallenge ? 'challenge' : 'playground';+ const [state, setState] = useState<'copied' | 'idle' | 'loading'>('idle');+ // enable copy with code by default on playground+ const [copyWithCode, setCopyWithCode] = useState(shareType === 'playground');+ const [codeToCompress] = useLocalStorage(`${shareType}-${slug}`, '');+ const [shortUrl, setShortUrl] = useState('');+ const [previousCode, setPreviousCode] = useState('');+ const url = `${window.location.origin}/${shareType}/${slug}`;++ const genShortUrl = useCallback(async () => {+ let long = url;+ if (copyWithCode && codeToCompress) {+ const compressedCode = lzstring.compressToEncodedURIComponent(codeToCompress);+ long += `?code=${compressedCode}`;++ // Check if the code has changed+ if (codeToCompress !== previousCode) {+ const short = await createShortURL(long);+ setPreviousCode(codeToCompress);+ return short ?? long;+ }+ return shortUrl;+ }+ return long;+ }, [url, copyWithCode, codeToCompress, previousCode, shortUrl]);++ const copyToClipboard = useCallback(async () => {+ setState('loading');+ const short = await genShortUrl();+ setShortUrl(short);+ try {+ if (navigator.clipboard) {+ await navigator.clipboard.writeText(short);+ setState('copied');+ toast({+ title: 'URL Copied!!',+ description: 'Share url is copied to your clipboard.',+ });+ window.setTimeout(() => setState('idle'), 3000);+ }+ } catch (e) {+ console.error('copyToClipboard', e);+ setState('idle');+ toast({+ title: 'Copy Failed!!',+ variant: 'destructive',+ });+ }+ }, [genShortUrl, toast]);++ const onCopyWithCodeChange = useCallback((checked: boolean) => {+ setCopyWithCode(checked);+ }, []);++ return (+ <div className="flex flex-col space-y-4">+ <p>{desciprtion ?? 'Copy this url to share with your friends!'}</p>+ <code+ aria-disabled={state === 'loading'}+ className="break-all rounded-lg border border-black/20 bg-white px-4 py-2 aria-disabled:cursor-not-allowed aria-disabled:opacity-50 dark:border-white/20 dark:bg-black"+ >+ {shortUrl.length === 0 ? url : shortUrl}+ </code>+ <DialogFooter>+ <div className="flex items-center justify-end gap-2">+ {/* Checkbox not needed in playground */}+ {codeToCompress && isChallenge ? (+ <div className="flex h-fit items-center justify-center gap-2 text-xs">+ <Checkbox+ id="copy-with-code"+ checked={copyWithCode}+ onCheckedChange={onCopyWithCodeChange}+ />+ <label htmlFor="copy-with-code">Copy with code</label>+ </div>+ ) : null}+ <button+ disabled={state === 'loading'}+ className={`flex items-center justify-between space-x-2 rounded-lg px-2 py-1 duration-300 active:scale-75 disabled:cursor-not-allowed disabled:opacity-50+ ${+ state === 'copied'+ ? 'border border-green-500 text-green-500 dark:border-green-700 dark:bg-green-700 dark:text-white'+ : 'border border-black/20 text-black hover:bg-gray-100 dark:bg-white'+ }`}+ onClick={copyToClipboard}+ >+ <span>{state === 'copied' ? 'Copied!' : 'Copy'}</span>+ {state === 'copied' ? (+ <CheckCircle2 className="h-4 w-4" />+ ) : (+ <Clipboard className="h-4 w-4" />+ )}+ </button>+ </div>+ </DialogFooter>+ </div>+ );+}diff --git a/apps/web/src/utils/auth-guards.ts b/apps/web/src/utils/auth-guards.tsindex 833007f9..8d20af78 100644--- a/apps/web/src/utils/auth-guards.ts+++ b/apps/web/src/utils/auth-guards.ts@@ -8,3 +8,8 @@ export function isAdminOrModerator(session: Session | null) {export function isAuthor(session: Session | null, userId?: string | null) {return Boolean(userId && session?.user?.id && userId === session?.user?.id);}++export function isAdmin(session: Session | null) {+ if (!session) return false;+ return session.user.role.includes(RoleTypes.ADMIN);+}diff --git a/apps/web/src/utils/rateLimit.ts b/apps/web/src/utils/rateLimit.tsnew file mode 100644index 00000000..1d8fedc0--- /dev/null+++ b/apps/web/src/utils/rateLimit.ts@@ -0,0 +1,31 @@+const idToRequestCount = new Map<string, number>(); // keeps track of individual users+const rateLimiter = {+ windowStart: Date.now(),+ windowSize: 60 * 60 * 1000,+ maxRequests: 30,+};+// Max 30 requests per hour per user by default++interface RateLimiterConfig {+ windowStart?: number;+ windowSize?: number;+ maxRequests?: number;+}++export const rateLimit = (ip: string, config = {} as RateLimiterConfig) => {+ const { windowStart, windowSize, maxRequests } = { ...rateLimiter, ...config };+ // Check and update current window+ const now = Date.now();+ const isNewWindow = now - windowStart > windowSize;+ if (isNewWindow) {+ config.windowStart = now;+ idToRequestCount.set(ip, 0);+ }++ // Check and update current request limits+ const currentRequestCount = idToRequestCount.get(ip) ?? 0;+ if (currentRequestCount >= maxRequests) return true;+ idToRequestCount.set(ip, currentRequestCount + 1);++ return false;+};diff --git a/apps/web/vercel.json b/apps/web/vercel.jsonindex e40d89b4..0c670847 100644--- a/apps/web/vercel.json+++ b/apps/web/vercel.json@@ -3,6 +3,10 @@"framework": "nextjs","buildCommand": "turbo build","crons": [+ {+ "path": "/api/cron/short-url-cleanup",+ "schedule": "0 0 1 * *"+ },{"path": "/api/cron/sync-contributors","schedule": "0 0 * * *"diff --git a/packages/db/schema.prisma b/packages/db/schema.prismaindex 182afdf6..fcd1033d 100644--- a/packages/db/schema.prisma+++ b/packages/db/schema.prisma@@ -143,6 +143,7 @@ model User {imageUpload ImageUpload[]tracks Track[]BetaTokens BetaTokens[]+ shortUrls ShortURL[]toUserNotification Notification[] @relation("notificationToUser")fromUserNotification Notification[] @relation("notificationFromUser")}@@ -464,3 +465,21 @@ model Notification {@@index([challengeId])@@index([sharedSolutionId])}++model ShortURL {+ id Int @id @default(autoincrement())+ /// the original full url that we want to shorten e.g. https://www.url.com+ originalUrl String @db.MediumText+ /// slug for the short url e.g. url.com/[shortUrlSlug]+ shortUrlSlug String @unique+ createdAt DateTime @default(now())+ /// the time the short url will expire+ expiresAt DateTime?+ /// the number of times the short url has redirected to the original url+ clicks Int @default(0)+ userId String?+ user User? @relation(fields: [userId], references: [id])++ @@index([userId])+ @@index([shortUrlSlug])+}\ No newline at end of filediff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f90b578f..8da34d80 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -444,6 +444,9 @@ importers:monaco-vim:specifier: ^0.4.0version: 0.4.0(patch_hash=j3oqxjoadtct3pc6tokddngzsm)([email protected])+ nanoid:+ specifier: ^5.0.7+ version: 5.0.7next:specifier: 14.2.5version: 14.2.5(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])@@ -6380,6 +6383,11 @@ packages:engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}hasBin: true+ resolution: {integrity: sha512-oLxFY2gd2IqnjcYyOXD8XGCftpGtZP2AbHbOkthDkvRywH5ayNtPVy9YlOPcHckXzbLTCHpkb7FB+yuxKV13pQ==}+ engines: {node: ^18 || >=20}+ hasBin: true+resolution: {integrity: sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==}@@ -14595,6 +14603,8 @@ snapshots:+ [email protected]: {}+