Skip to content

Instantly share code, notes, and snippets.

@loftwah
Last active March 16, 2025 07:35
Show Gist options
  • Save loftwah/a5ee224d1fbe6f3e533b249050609a6e to your computer and use it in GitHub Desktop.
Save loftwah/a5ee224d1fbe6f3e533b249050609a6e to your computer and use it in GitHub Desktop.
Linkarooie V4

Linkarooie V4 - Design Document

1. Project Overview

Linkarooie V4 is a modern Linktree alternative built with Astro and deployed on Cloudflare Pages. It transforms the previous static site (V3) into a full-featured web application with user authentication, profile management, analytics tracking, and more.

Core Functionality

  • User registration and authentication (email/password + 2FA)
  • Profile customization (bio, avatar, banner, social links)
  • Link and achievement management
  • Visit analytics
  • Dark/light mode
  • Automatic Open Graph image generation
  • Mobile-responsive design

Technology Stack

  • Frontend: Astro, TailwindCSS
  • Backend: Cloudflare Pages Functions
  • Database: Cloudflare D1 (SQLite)
  • Storage: Cloudflare R2 (for uploaded files)
  • Caching: Cloudflare KV
  • Email: Resend API
  • Build Tools: Bun, TypeScript, Vite

2. Project Structure & File Responsibilities

Root Directory

File/Directory Description
astro.config.mjs Astro configuration with Cloudflare adapter settings, SSR mode, and route definitions
wrangler.toml Cloudflare Workers configuration (D1, KV, R2 bindings)
package.json Project dependencies and scripts
tailwind.config.js TailwindCSS configuration with custom color schemes
tsconfig.json TypeScript configuration
.env.example Example environment variables template

/src Directory

/src/assets

Static assets used throughout the application:

  • background.svg - Background pattern for landing page
  • astro.svg - Astro logo for attribution
  • images/ - Contains default images, icons, and branding assets

/src/components

Component Responsibility
Auth Components
LoginForm.astro Handles user login with username/password and optional 2FA verification
RegisterForm.astro User registration form with validation
TwoFactorForm.astro TOTP verification interface for 2FA
ForgotPasswordForm.astro Password reset request form
ResetPasswordForm.astro Form for setting a new password
Profile Components
ProfileHeader.astro Displays user avatar, name, and bio
ProfileEditor.astro Form for editing profile information
TagEditor.astro Interface for adding/removing tags
SocialLinksEditor.astro Controls for managing social media links
AvatarUploader.astro Interface for uploading and cropping profile images
BannerUploader.astro Interface for uploading and cropping banner images
Link Components
LinkCard.astro Displays a user's link with title, description, and icon
LinksList.astro Container that displays all user links
LinkEditor.astro Form for creating and editing links
LinkSorter.astro Drag-and-drop interface for reordering links
Achievement Components
AchievementCard.astro Displays an achievement with title, date, and description
AchievementsList.astro Container for all user achievements
AchievementEditor.astro Form for creating and editing achievements
Analytics Components
AnalyticsDashboard.astro Displays analytics overview with charts
VisitorsChart.astro Line chart showing visits over time
ReferrersList.astro Shows top traffic sources
GeographyMap.astro Displays visitor countries on a map
Utility Components
AlertBox.astro Reusable alert component for success/error messages
LoadingSpinner.astro Loading indicator for async operations
ConfirmDialog.astro Confirmation dialog for dangerous actions
Pagination.astro Paginated display for long lists
Directory.astro Grid display of public profiles

/src/layouts

Layout Responsibility
Layout.astro Base layout with common head tags, theme toggle, and footer
DashboardLayout.astro Admin dashboard layout with sidebar navigation
ProfileLayout.astro Public-facing profile layout for visitors

/src/pages

Page Responsibility
index.astro Landing page with featured profiles and app information
login.astro User login page
register.astro New user registration page
verify-email.astro Email verification handler
forgot-password.astro Password reset request page
reset-password.astro Password reset confirmation page
[username].astro Dynamic route for public user profiles
/dashboard/index.astro User dashboard home with stats overview
/dashboard/profile.astro Profile editing interface
/dashboard/links.astro Link management interface
/dashboard/achievements.astro Achievements management interface
/dashboard/analytics.astro Analytics dashboard
/dashboard/settings.astro Account settings (privacy, security, etc.)

/src/services

Service Responsibility
auth.ts Authentication logic (login, register, JWT, 2FA)
profile.ts Profile data management
links.ts Link creation, updating, ordering
achievements.ts Achievement management
analytics.ts Visit tracking and statistics
email.ts Email sending via Resend API
storage.ts File upload handling with R2
og-image.ts Open Graph image generation

/src/db

File Responsibility
schema.ts TypeScript definitions matching database schema
/migrations/init.sql Initial database schema creation
/migrations/updates/ Incremental schema updates

/src/types

File Responsibility
index.ts Core TypeScript interfaces for the application
env.d.ts Environment type definitions
api.ts API request/response type definitions

/src/utils

Utility Responsibility
validation.ts Input validation helpers
formatters.ts Date, number, and string formatting utilities
security.ts Security-related helpers
image-processing.ts Image manipulation utilities

/functions Directory (Cloudflare Functions)

Function Responsibility
[[path]].ts Catch-all middleware for auth verification
/api/auth/login.ts Handle login requests
/api/auth/register.ts Process new user registrations
/api/auth/logout.ts Handle logout
/api/auth/verify-email.ts Verify user email addresses
/api/auth/reset-password.ts Handle password reset flow
/api/auth/totp-setup.ts Configure 2FA for users
/api/profiles/[username].ts Get public profile data
/api/profiles/create.ts Create new profile
/api/profiles/update.ts Update profile information
/api/links/create.ts Add new link
/api/links/update.ts Update existing link
/api/links/delete.ts Remove link
/api/links/reorder.ts Change link ordering
/api/achievements/create.ts Add new achievement
/api/achievements/update.ts Update existing achievement
/api/achievements/delete.ts Remove achievement
/api/analytics/track.ts Record profile visits
/api/analytics/[username].ts Get analytics for a profile
/api/og-image/generate.ts Generate Open Graph images

/scripts Directory

Script Responsibility
init-project.ts Set up initial project configuration
seed-database.ts Populate database with sample data for development
backup-database.ts D1 database backup utility
generate-og-image.ts Utility for generating Open Graph images

3. Key Components

3.1 Authentication System

The authentication system uses JWT tokens stored in HTTP-only cookies for secure sessions, with email verification and optional TOTP-based two-factor authentication.

Key Files:

  • src/services/auth.ts - Core authentication logic
  • functions/api/auth/* - Auth API endpoints
  • src/components/auth/* - Auth UI components

Flow:

  1. User registers with email/password
  2. Verification email sent via Resend API
  3. User verifies email by clicking link
  4. User logs in with credentials
  5. JWT token stored in HTTP-only cookie
  6. Optional 2FA verification step
  7. User session maintained until logout or expiration

3.2 Profile Management

The profile management system handles all aspects of a user's public profile.

Key Files:

  • src/services/profile.ts - Profile data operations
  • functions/api/profiles/* - Profile API endpoints
  • src/pages/dashboard/profile.astro - Profile editing interface
  • src/components/profile/* - Profile UI components

Features:

  • Basic profile info (name, bio, description)
  • Avatar and banner image upload and cropping
  • Tags and categories
  • Social media links
  • Privacy settings
  • SEO settings

3.3 Links Management

The links system allows users to create, edit, and organize their collection of links.

Key Files:

  • src/services/links.ts - Link operations
  • functions/api/links/* - Link API endpoints
  • src/pages/dashboard/links.astro - Link management interface
  • src/components/LinkEditor.astro - Link editing component

Features:

  • Add, edit, and delete links
  • Customize link title, URL, description, and icon
  • Drag-and-drop reordering
  • Hide/show specific links
  • Track click statistics

3.4 Achievements System

The achievements system showcases user accomplishments, certifications, and milestones.

Key Files:

  • src/services/achievements.ts - Achievement operations
  • functions/api/achievements/* - Achievement API endpoints
  • src/pages/dashboard/achievements.astro - Achievement management interface
  • src/components/AchievementEditor.astro - Achievement editing component

Features:

  • Add, edit, and delete achievements
  • Customize title, date, description, and icon
  • Attach verification links
  • Format dates flexibly
  • Hide/show specific achievements

3.5 Analytics System

The analytics system tracks profile visits and provides insights to users.

Key Files:

  • src/services/analytics.ts - Analytics operations
  • functions/api/analytics/* - Analytics API endpoints
  • src/pages/dashboard/analytics.astro - Analytics dashboard
  • src/components/analytics/* - Analytics UI components

Features:

  • Profile visit tracking
  • Unique visitor counts
  • Referrer analysis
  • Geographic distribution of visitors
  • Time-based trends
  • Optional public analytics page

3.6 Open Graph Image Generation

Automatic generation of customized Open Graph images for sharing on social media.

Key Files:

  • src/services/og-image.ts - Image generation logic
  • functions/api/og-image/generate.ts - Image generation API
  • src/components/profile/OgImagePreview.astro - Preview component

Features:

  • Real-time OG image generation
  • Customized with user profile data
  • Multiple theme options (light/dark)
  • Automatic updating when profile changes
  • Cache with R2 storage for performance

Implementation:

  1. Uses satori to render React components as SVG
  2. Converts SVG to PNG using resvg/Sharp
  3. Stores generated images in R2 bucket
  4. Automatically regenerates when profile is updated
  5. Includes profile avatar, name, bio, and tags

4. Database Schema

The D1 database uses the following tables:

users

Stores core user account information:

  • id - Primary key
  • username - Unique username
  • email - User's email address
  • password - Hashed password
  • name - User's display name
  • description - Short profile description
  • bio - Longer biography
  • avatar_url - Profile image URL
  • banner_url - Profile banner URL
  • og_image_url - Open Graph image URL
  • og_title - SEO title
  • og_description - SEO description
  • is_email_verified - Email verification status
  • is_public - Profile visibility toggle
  • show_in_directory - Directory inclusion toggle
  • totp_secret - 2FA secret (if enabled)
  • totp_enabled - 2FA status flag
  • is_admin - Admin privileges flag
  • created_at - Account creation timestamp
  • updated_at - Last update timestamp

tags

Stores available tags:

  • id - Primary key
  • name - Tag name

user_tags

Junction table linking users to tags:

  • user_id - References users.id
  • tag_id - References tags.id

social_links

Stores user's social media profiles:

  • id - Primary key
  • user_id - References users.id
  • platform - Social platform identifier
  • url - Profile URL

links

Stores user's shared links:

  • id - Primary key
  • user_id - References users.id
  • link_id - Unique identifier for the link
  • title - Link title
  • description - Link description
  • url - Link URL
  • icon - Icon identifier
  • is_hidden - Visibility toggle
  • sort_order - Position in list
  • created_at - Creation timestamp
  • updated_at - Last update timestamp

achievements

Stores user's achievements:

  • id - Primary key
  • user_id - References users.id
  • achievement_id - Unique identifier
  • title - Achievement title
  • description - Achievement description
  • date - Achievement date
  • url - Verification link
  • icon - Icon identifier
  • show_full_date - Date format toggle
  • is_hidden - Visibility toggle
  • sort_order - Position in list
  • created_at - Creation timestamp
  • updated_at - Last update timestamp

analytics

Stores profile visit data:

  • id - Primary key
  • user_id - References users.id
  • visitor_ip - Visitor's IP address (hashed)
  • user_agent - Browser user agent
  • referrer - Traffic source
  • country - Visitor country
  • city - Visitor city
  • visited_at - Visit timestamp

reset_tokens

Stores password reset tokens:

  • id - Primary key
  • user_id - References users.id
  • token - Unique reset token
  • expires_at - Token expiration timestamp
  • created_at - Token creation timestamp

email_verification_tokens

Stores email verification tokens:

  • id - Primary key
  • user_id - References users.id
  • token - Unique verification token
  • expires_at - Token expiration timestamp
  • created_at - Token creation timestamp

5. API Endpoints

Authentication Endpoints

Endpoint Method Description
/api/auth/register POST Create new user account
/api/auth/login POST Authenticate user
/api/auth/logout POST End user session
/api/auth/verify-email GET Verify email address
/api/auth/reset-password POST Request password reset
/api/auth/reset-password PUT Complete password reset
/api/auth/totp-setup POST Initialize 2FA setup
/api/auth/totp-verify POST Verify and enable 2FA
/api/auth/totp-disable POST Disable 2FA

Profile Endpoints

Endpoint Method Description
/api/profiles/:username GET Get public profile data
/api/profiles/me GET Get current user's profile
/api/profiles/update PUT Update profile information
/api/profiles/social-links PUT Update social media links
/api/profiles/tags PUT Update profile tags
/api/profiles/avatar POST Upload avatar image
/api/profiles/banner POST Upload banner image

Links Endpoints

Endpoint Method Description
/api/links GET Get user's links
/api/links/create POST Create new link
/api/links/:linkId PUT Update existing link
/api/links/:linkId DELETE Delete link
/api/links/reorder PUT Change link order

Achievements Endpoints

Endpoint Method Description
/api/achievements GET Get user's achievements
/api/achievements/create POST Create new achievement
/api/achievements/:achievementId PUT Update achievement
/api/achievements/:achievementId DELETE Delete achievement
/api/achievements/reorder PUT Change achievement order

Analytics Endpoints

Endpoint Method Description
/api/analytics/:username GET Get profile analytics
/api/analytics/track POST Record profile visit
/api/analytics/clear DELETE Clear analytics data

Open Graph Image Endpoints

Endpoint Method Description
/api/og-image/generate POST Generate OG image
/api/og-image/:username GET Get user's OG image

6. Open Graph Image Generation

The Open Graph image generation system creates custom images for social media sharing.

Implementation

  1. Image Generation Service (src/services/og-image.ts)

    • Uses satori to render React components as SVG
    • Converts SVG to PNG or JPEG using resvg/sharp
    • Handles different themes and layouts
    • Caches generated images in R2 storage
  2. Generation Process

    • User profile data is fetched from the database
    • Data is passed to a React template component
    • Component is rendered to SVG using satori
    • SVG is converted to PNG using resvg/sharp
    • Image is stored in R2 bucket with appropriate cache headers
    • URL is saved to user's profile
  3. Trigger Points

    • Initial profile creation
    • Profile updates (name, bio, avatar, etc.)
    • Theme changes
    • Manual regeneration from settings
  4. Templates

    • src/components/og-templates/ProfileTemplate.tsx - Standard profile OG image
    • src/components/og-templates/AchievementTemplate.tsx - Achievement showcase template
    • src/components/og-templates/LinkTemplate.tsx - Link-specific template
  5. Preview Component

    • Live preview of OG image in dashboard
    • Allows testing different layouts/themes before saving

7. Deployment Architecture

Cloudflare Pages Deployment

  1. Build Process

    • Astro builds optimized frontend assets
    • TypeScript compilation for server functions
    • Assets bundled for deployment
  2. Database Setup

    • D1 database created in Cloudflare dashboard
    • Initial schema migration run via wrangler CLI
    • Binding configured in wrangler.toml
  3. Environment Variables

    • JWT_SECRET - For secure token signing
    • RESEND_API_KEY - For transactional emails
    • Environment-specific variables (staging vs production)
  4. Custom Domain Configuration

    • DNS records set up in Cloudflare
    • SSL certificate automatically provisioned
  5. Continuous Deployment

    • GitHub integration with Cloudflare Pages
    • Automatic deployments on push to main branch
    • Preview deployments for pull requests

8. Security Considerations

  1. Authentication

    • Passwords hashed with bcrypt
    • HTTP-only cookies for JWT
    • Optional TOTP 2FA
    • CSRF protection
    • Rate limiting on auth endpoints
  2. Input Validation

    • All user input validated with Zod schemas
    • Protection against XSS and injection
  3. API Security

    • Authentication middleware for protected routes
    • Input sanitization
    • Resource authorization checks
  4. Privacy

    • IP addresses hashed for analytics
    • Profile privacy controls
    • Data minimization principles
  5. Monitoring & Logging

    • Error tracking
    • Security event logging
    • Suspicious activity detection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment