From 9b5e9de988e2f3ee1bb8fc720a71bc991bebfed4 Mon Sep 17 00:00:00 2001 From: AJFrio Date: Wed, 12 Nov 2025 12:57:03 -0700 Subject: [PATCH] Update Docs --- MULTI-SITE.md | 151 ----- README.md | 630 +++--------------- SECURITY_ANALYSIS.md | 89 --- SECURITY_FIXES_SUMMARY.md | 251 ------- docs/AI_MEDIA.md | 246 +++++++ docs/API.md | 129 ++++ .../ARCHITECTURE.md | 280 ++++---- docs/CONFIGURATION.md | 183 +++++ docs/CUSTOMIZATION.md | 267 ++++++++ docs/DEPLOYMENT.md | 323 +++++++++ docs/PERFORMANCE.md | 178 +++++ docs/STRIPE.md | 172 +++++ docs/TESTING.md | 378 +++++++++++ docs/TROUBLESHOOTING.md | 258 +++++++ 14 files changed, 2374 insertions(+), 1161 deletions(-) delete mode 100644 MULTI-SITE.md delete mode 100644 SECURITY_ANALYSIS.md delete mode 100644 SECURITY_FIXES_SUMMARY.md create mode 100644 docs/AI_MEDIA.md create mode 100644 docs/API.md rename WORKERS-ARCHITECTURE.md => docs/ARCHITECTURE.md (60%) create mode 100644 docs/CONFIGURATION.md create mode 100644 docs/CUSTOMIZATION.md create mode 100644 docs/DEPLOYMENT.md create mode 100644 docs/PERFORMANCE.md create mode 100644 docs/STRIPE.md create mode 100644 docs/TESTING.md create mode 100644 docs/TROUBLESHOOTING.md diff --git a/MULTI-SITE.md b/MULTI-SITE.md deleted file mode 100644 index 4ccd0dc..0000000 --- a/MULTI-SITE.md +++ /dev/null @@ -1,151 +0,0 @@ -# Multi-Site Deployment Guide - -OpenShop now supports managing multiple sites from a single codebase. Each site has its own configuration stored in the `toml/` directory. - -## πŸ“ Directory Structure - -``` -openshop/ -β”œβ”€β”€ toml/ -β”‚ β”œβ”€β”€ my-store.toml # Site configuration (not tracked in git) -β”‚ β”œβ”€β”€ another-store.toml # Another site config (not tracked in git) -β”‚ └── template.toml.example # Template file (tracked in git) -β”œβ”€β”€ wrangler.toml # Auto-generated (not tracked in git) -└── scripts/ - β”œβ”€β”€ setup.js # Create new sites - β”œβ”€β”€ deploy.js # Deploy sites - └── list-sites.js # List all sites -``` - -## πŸš€ Creating a New Site - -Run the setup wizard to create a new site: - -```bash -npm run setup -``` - -This will: -1. Prompt you for a project name and credentials -2. Create a new Cloudflare Worker and KV namespace -3. Save the configuration to `toml/.toml` -4. Deploy the site - -## πŸ“‹ Listing Your Sites - -View all configured sites: - -```bash -npm run sites -``` - -This displays: -- Site configuration name -- Project name -- Worker URL -- KV namespace binding - -## 🚒 Deploying Updates - -### Deploy a Specific Site - -```bash -npm run deploy -``` - -Example: -```bash -npm run deploy my-store -``` - -### Interactive Site Selection - -If you don't specify a site, you'll be prompted to choose: - -```bash -npm run deploy -``` - -This will: -1. Show a numbered list of all sites -2. Let you select which site to deploy -3. Copy the site's configuration to `wrangler.toml` -4. Build and deploy the site - -## πŸ”’ Security - -**Important:** All `.toml` files in the `toml/` directory contain sensitive credentials and are automatically ignored by git. Never commit these files! - -Files ignored: -- `toml/*.toml` - All site configurations -- `wrangler.toml` - Auto-generated deployment config -- `.env` - Local environment variables - -Files tracked: -- `toml/*.example` - Template files without real credentials - -## πŸ”„ How It Works - -1. **Setup**: Creates a new configuration in `toml/.toml` -2. **Deploy**: Copies the selected toml file to root as `wrangler.toml` -3. **Wrangler**: Uses `wrangler.toml` for deployment -4. **Result**: Each site maintains its own KV namespace, secrets, and worker - -## πŸ“ Example Workflow - -```bash -# Create first site -npm run setup -# Enter: my-clothing-store - -# Create second site -npm run setup -# Enter: my-electronics-store - -# List all sites -npm run sites - -# Deploy specific site -npm run deploy my-clothing-store - -# Deploy with selection prompt -npm run deploy -``` - -## πŸ› οΈ Configuration Format - -Each site configuration includes: - -```toml -name = "project-name" -main = "src/worker.js" - -[[kv_namespaces]] -binding = "PROJECT_KV" -id = "kv-namespace-id" - -[vars] -SITE_URL = "https://project-name.workers.dev" -STRIPE_SECRET_KEY = "sk_test_..." -ADMIN_PASSWORD = "your-password" -# ... other environment variables - -[assets] -directory = "dist" -binding = "ASSETS" -``` - -## πŸ’‘ Tips - -- Use descriptive names for your sites (e.g., `staging`, `production`, `test`) -- Keep your `toml/` files backed up securely (they're not in git) -- Each site has its own admin dashboard and data -- You can run different stores with different products from one codebase - -## ⚠️ Important Notes - -- Each site requires its own Cloudflare Worker and KV namespace -- Each site uses the same Cloudflare account (specified during setup) -- Stripe keys can be the same or different for each site -- Admin passwords are per-site and stored in the configuration - diff --git a/README.md b/README.md index be6d790..2a1cb10 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ # OpenShop - An Open-Source AI Platform for Smarter Stores. - > A lightweight, open-source e-commerce platform built entirely on the Cloudflare ecosystem. Leverages Cloudflare Workers for hosting, Cloudflare KV for data storage, and Stripe for payments - designed to stay within Cloudflare's generous free tier. + > Launch your online store in minutes. Built on Cloudflare's edge network for lightning-fast performance, zero infrastructure costs, and unlimited scalability. [![License: AGPL v3](https://img.shields.io/badge/License-AGPL_v3-blue.svg)](https://www.gnu.org/licenses/agpl-3.0) @@ -11,13 +11,29 @@ --- +## Why OpenShop? + +OpenShop is the fastest, most cost-effective way to launch an e-commerce store. Built entirely on Cloudflare's edge network, you get: + +- **⚑ Lightning Fast** - Sub-100ms response times worldwide +- **πŸ’° Completely Free** - Stays within Cloudflare's generous free tier (100k requests/day) +- **πŸš€ One-Command Deploy** - Your store is live in under 5 minutes +- **πŸ”’ Enterprise Security** - Built-in DDoS protection, SSL, and secure authentication +- **πŸ“± Mobile-First** - Beautiful, responsive design that works everywhere +- **πŸ”„ Unlimited Stores** - Deploy as many stores as you want from one codebase + +Perfect for entrepreneurs, developers, and businesses who want a professional online store without the complexity or cost of traditional e-commerce platforms. + +--- + ## 🌟 Features ### Core Functionality -- **⚑ Lightning Fast** - Built on Cloudflare's global edge network -- **πŸ’° Cost Effective** - Designed for Cloudflare's generous free tier (100k requests/day) -- **πŸ›’ Complete E-commerce** - Product management, collections, and Stripe checkout -- **πŸ”§ One-Command Setup** - Automated deployment and configuration +- **πŸ›’ Complete E-commerce** - Products, collections, shopping cart, and Stripe checkout +- **πŸ“¦ Product Management** - Multiple images, variants, and rich descriptions +- **πŸ“ Collections** - Organize products with beautiful hero banners +- **πŸ’³ Stripe Integration** - Automatic product sync and secure payment processing +- **πŸ“Š Analytics Dashboard** - Real-time revenue and order insights ### User Experience - **πŸ›οΈ Smart Shopping Cart** - Persistent cart with quantity management @@ -28,31 +44,9 @@ ### Advanced Features - **πŸ–ΌοΈ Rich Media Support** - Multiple product images with carousel navigation - **🎨 Store Customization** - Dynamic logo management (text or image) -- **πŸ“Š Analytics Dashboard** - Real-time Stripe analytics with revenue insights - **πŸ”’ Secure Admin System** - Token-based authentication with session management - ---- - -## πŸ—οΈ Technical Architecture - -```mermaid -graph TB - A[Cloudflare Worker] --> B[Static Assets] - A --> C[API Endpoints] - A --> D[Authentication] - C --> E[Cloudflare KV] - C --> F[Stripe API] - D --> E -``` - -| Component | Technology | Purpose | -|-----------|------------|---------| -| **Frontend** | Vite + React + Tailwind CSS | User interface and experience | -| **Backend** | Cloudflare Workers + Hono | API endpoints and business logic | -| **Database** | Cloudflare KV | Product, collection, and settings storage | -| **Payments** | Stripe API | Payment processing and checkout | -| **Authentication** | Token-based system | Secure admin access | -| **Deployment** | Wrangler CLI | Automated deployment pipeline | +- **🧠 AI Image Generation** (Optional) - Generate product images with Gemini AI +- **☁️ Google Drive Integration** (Optional) - Store and serve images from Google Drive --- @@ -78,116 +72,84 @@ graph TB npm run setup ``` - **Setup prompts:** - - **Project Name** - Unique name for your store (e.g., "my-electronics-store") + The setup wizard will prompt you for: + - **Project Name** - Unique name for your store - **Cloudflare API Token** - [Get token here](https://dash.cloudflare.com/?to=/:account/api-tokens) -
- Required token permissions - - - **Account β€” API settings** - - Containers: Edit - - Secrets Store: Edit - - Workers Pipelines: Edit - - Workers AI: Edit - - Queues: Edit - - Vectorize: Edit - - Hyperdrive: Edit - - Cloudchamber: Edit - - D1: Edit - - Workers R2 Storage: Edit - - Workers KV Storage: Edit - - Workers Scripts: Edit - - Account Settings: Read - - **All zones** - - Workers Routes: Edit - - **All users** - - Memberships: Read - - User Details: Read -
- **Cloudflare Account ID** - Found in your Cloudflare dashboard - - **Stripe Secret Key** - From your Stripe dashboard - - **Stripe Publishable Key** - From your Stripe dashboard - - **Admin Password** - Custom password (default: admin123) - - *(Optional)* **Gemini API Key** - Required for AI image generation in admin - - *(Optional)* **Google OAuth Client ID/Secret** - Required to upload images to Google Drive from admin + - **Stripe Keys** - Secret and publishable keys from Stripe dashboard + - **Admin Password** - Your secure admin password + - *(Optional)* **Gemini API Key** - For AI image generation + - *(Optional)* **Google OAuth** - For Google Drive integration + + See [Configuration Guide](docs/CONFIGURATION.md) for detailed setup instructions. 3. **πŸŽ‰ Your Store is Live!** Access your store at: `https://your-project-name.username.workers.dev` + + Access admin at: `https://your-project-name.username.workers.dev/admin` --- ## πŸ”’ Admin Dashboard -### Access & Security +Access your admin dashboard at `/admin` on your store URL. -**URL**: `https://your-project-name.username.workers.dev/admin` +**Security Features:** +- Password-protected login +- 24-hour session tokens +- Separate authenticated API endpoints +- No visible admin link on storefront (access via direct URL) -> **Note**: For security, there's no visible admin button on the storefront. Access the admin dashboard directly via URL. +**Admin Capabilities:** +- Create, edit, and delete products with multiple images +- Manage collections with hero banners +- Customize store branding and appearance +- View real-time analytics and revenue insights +- Generate AI images (optional) +- Upload images to Google Drive (optional) -### Security Features - -| Feature | Description | -|---------|-------------| -| **πŸ” Password Protection** | Admin login required with configurable password | -| **🎫 Token-Based Auth** | Secure 24-hour session tokens stored in KV | -| **πŸ›‘οΈ API Separation** | Separate authenticated endpoints for admin operations | -| **⏰ Auto Logout** | Expired sessions automatically redirect to login | - -### Admin Capabilities - -- **πŸ“¦ Product Management** - Create, edit, delete products with multiple images -- **πŸ“ Collection Management** - Organize products with hero banner images -- **🎨 Store Customization** - Dynamic logo and branding management -- **πŸ“Š Analytics Dashboard** - Real-time revenue and order insights -- **βš™οΈ Settings Management** - Configure store appearance and behavior -- **🧠 AI Image Generation (Optional)** - Generate product/hero images via Gemini -- **☁️ Google Drive Uploads (Optional)** - Save generated or local images to Drive and use public links via the built-in image proxy +For detailed admin documentation, see [Architecture Guide](docs/ARCHITECTURE.md). --- ## πŸͺ Multiple Store Support -Deploy unlimited stores with unique configurations: +Deploy unlimited stores from a single codebase, each with its own: +- Worker deployment and subdomain +- Isolated KV namespace (separate data) +- Admin credentials and settings +- Stripe configuration ```bash -# Electronics Store +# Create your first store npm run setup # Project Name: "electronics-hub" -# Result: https://electronics-hub.workers.dev -# Fashion Store -npm run setup -# Project Name: "fashion-boutique" -# Result: https://fashion-boutique.workers.dev - -# Book Store +# Create another store npm run setup -# Project Name: "online-bookstore" -# Result: https://online-bookstore.workers.dev -``` +# Project Name: "fashion-boutique" -### Resource Isolation +# List all your stores +npm run sites -Each store gets completely isolated resources: +# Deploy a specific store +npm run deploy electronics-hub +``` -| Resource | Naming Convention | Example | -|----------|-------------------|---------| -| **Worker** | `project-name.username.workers.dev` | `electronics-hub.username.workers.dev` | -| **KV Namespace** | `PROJECT-NAME_KV` | `ELECTRONICS-HUB_KV` | -| **Admin Access** | `/admin` on each domain | `electronics-hub.workers.dev/admin` | +See [Deployment Guide](docs/DEPLOYMENT.md) for complete multi-site documentation. --- ## πŸ› οΈ Development -### Local Development Commands +### Local Development ```bash # Full-stack development (Worker + Frontend) npm run dev -# Frontend-only development (Vite dev server) +# Frontend-only development npm run dev:frontend # Build for production @@ -200,460 +162,24 @@ npm run deploy npm run preview ``` -### Development Workflow - -1. **Local Development** - Use `npm run dev` for full-stack development with hot reload -2. **Frontend Changes** - Use `npm run dev:frontend` for faster frontend-only development -3. **Testing** - Build and test locally before deployment -4. **Deployment** - Use `npm run deploy` to push changes to production +For detailed development instructions, see [Development Guide](DEVELOPMENT.md). --- -## πŸ“Š Data Models - -### Product Schema -```json -{ - "id": "prod_1a2b3c4d5e", - "name": "Classic Cotton T-Shirt", - "description": "A comfortable, high-quality t-shirt made from premium cotton.", - "price": 25.00, - "currency": "usd", - "images": [ - "https://example.com/image1.jpg", - "https://example.com/image2.jpg", - "https://example.com/image3.jpg" - ], - "stripePriceId": "price_AbC987zyx", - "stripeProductId": "prod_AbC123xyz", - "collectionId": "coll_xyz789" -} -``` +## πŸ“š Documentation -### Collection Schema -```json -{ - "id": "coll_xyz789", - "name": "Summer Collection", - "description": "Our hottest items for the summer season.", - "heroImage": "https://example.com/hero-banner.jpg" -} -``` +Complete documentation is available in the `docs/` directory: -### Store Settings Schema -```json -{ - "logoType": "text|image", - "logoText": "OpenShop", - "logoImageUrl": "https://example.com/logo.png", - "storeName": "OpenShop", - "storeDescription": "Your amazing online store" -} -``` - ---- - -## πŸ“ API Reference - -### Public Endpoints (Read-Only) - -| Endpoint | Method | Description | Authentication | -|----------|--------|-------------|----------------| -| `/api/products` | `GET` | List all products | None | -| `/api/products/:id` | `GET` | Get single product | None | -| `/api/collections` | `GET` | List all collections | None | -| `/api/collections/:id` | `GET` | Get single collection | None | -| `/api/collections/:id/products` | `GET` | Get products in collection | None | -| `/api/store-settings` | `GET` | Get store configuration | None | - -### Checkout Endpoints - -| Endpoint | Method | Description | Authentication | -|----------|--------|-------------|----------------| -| `/api/create-checkout-session` | `POST` | Single item checkout | None | -| `/api/create-cart-checkout-session` | `POST` | Multi-item cart checkout | None | -| `/api/image-proxy?src=` | `GET` | Proxy for Google Drive images | None | - -### Admin Endpoints (Authenticated) - -| Endpoint | Method | Description | Authentication | -|----------|--------|-------------|----------------| -| `/api/admin/login` | `POST` | Admin authentication | Password | -| `/api/admin/products` | `POST` | Create product | Admin Token | -| `/api/admin/products/:id` | `PUT, DELETE` | Update/delete product | Admin Token | -| `/api/admin/store-settings` | `PUT` | Update store settings | Admin Token | -| `/api/analytics` | `GET` | Revenue and order analytics | Admin Token | -| `/api/admin/ai/generate-image` | `POST` | Generate image via Gemini | Admin Token | -| `/api/admin/drive/status` | `GET` | Google Drive connection status | Admin Token | -| `/api/admin/drive/oauth/start` | `GET` | Begin Google Drive OAuth | None | -| `/api/admin/drive/oauth/callback` | `GET` | Handle Drive OAuth callback | None | -| `/api/admin/drive/upload` | `POST` | Upload image to Google Drive | Admin Token | - -> Note: Drive OAuth endpoints are intentionally unauthenticated to support the popup OAuth flow. All other Drive actions require admin auth. - ---- - -## πŸ”§ Configuration - -### Environment Variables - -Create a `.env` file for local development: - -```env -# Cloudflare Configuration -CLOUDFLARE_API_TOKEN=your_cloudflare_api_token -CLOUDFLARE_ACCOUNT_ID=your_cloudflare_account_id - -# Stripe Configuration -STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key -VITE_STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_publishable_key - -# Admin Configuration -ADMIN_PASSWORD=your_secure_admin_password - -# Site Configuration -SITE_URL=https://your-project.workers.dev - -# Optional: AI (Gemini) & Google Drive -# Used for admin-side AI image generation and Drive uploads -GEMINI_API_KEY=your_gemini_api_key -GOOGLE_CLIENT_ID=your_google_oauth_client_id -GOOGLE_CLIENT_SECRET=your_google_oauth_client_secret -# Optional: customize the root folder created/used in Drive -DRIVE_ROOT_FOLDER=OpenShop -``` - -### Cloudflare Setup - -The setup script automatically configures: - -- βœ… **KV Namespace** - Creates isolated data storage -- βœ… **Worker Deployment** - Deploys your application -- βœ… **Environment Variables** - Sets all required secrets -- βœ… **Optional Secrets** - You can add `GEMINI_API_KEY`, `GOOGLE_CLIENT_ID`, and `GOOGLE_CLIENT_SECRET` later via `wrangler secret put` to enable AI and Drive features -- βœ… **Static Assets** - Configures asset serving -- βœ… **Custom Domain** - Sets up your unique subdomain - ---- - -## πŸ’³ Stripe Integration - -### Automatic Synchronization - -- **Product Creation** - Automatically creates Stripe products and prices -- **Price Management** - Updates handled seamlessly -- **Checkout Sessions** - Secure payment processing -- **Multiple Items** - Cart checkout with line items - -### Update Behavior - -- **Product edits**: Updating name, description, or images syncs to the corresponding Stripe Product. Description is only updated if non-empty. Up to 8 images are sent to Stripe. -- **Base price change**: When the product base price changes, a new Stripe Price is created; existing Prices are preserved for historical data. -- **Variant prices**: Variants with `hasCustomPrice` create dedicated Stripe Prices. Variants without a custom price use the base price. Secondary variant set (if used) follows the same rules. -- **KV storage**: Product records in KV are merged on update, and image fields are normalized to arrays to maintain consistency across the UI and Stripe sync. - -### Webhook Setup (Optional) - -For advanced order tracking: - -1. **Stripe Dashboard** β†’ Webhooks -2. **Add Endpoint**: `https://your-project.workers.dev/api/stripe-webhook` -3. **Select Events**: `checkout.session.completed`, `payment_intent.succeeded` - ---- - -## 🧠 AI & Media Integrations (Optional) - -### Gemini Image Generation - -- **What it does**: From the admin, generate product or hero images using Google's Gemini image generation API. You can provide a prompt and up to 4 reference images. -- **Enable it**: Set `GEMINI_API_KEY` as a secret and/or in your local `.env`. - - Local: add to `.env` - - Production: `wrangler secret put GEMINI_API_KEY` -- **Endpoint**: `POST /api/admin/ai/generate-image` (requires admin token). - -### Google Drive Uploads - -- **What it does**: Upload generated images (or local files) from admin to your Google Drive and make them publicly viewable. The app returns a direct-view URL suitable for product images. -- **Enable it**: Create OAuth credentials and set `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`. - - Local: add to `.env` - - Production: `wrangler secret put GOOGLE_CLIENT_ID` and `wrangler secret put GOOGLE_CLIENT_SECRET` -- **OAuth flow**: From the admin media picker, click β€œConnect Google Drive”. This opens `GET /api/admin/drive/oauth/start`, which redirects to Google and returns to `/api/admin/drive/oauth/callback`. Tokens are stored in KV. -- **Upload**: After connecting, β€œUpload to Drive” calls `POST /api/admin/drive/upload`. Files are stored under a root folder (default derived from `SITE_URL`, override with `DRIVE_ROOT_FOLDER`). The file is made public and a direct-view URL is returned. -- **Image proxy**: Use `/api/image-proxy?src=` to serve Google Drive images reliably (avoids 403/CORS). The UI normalizes Drive links automatically. - -> These features are optional. The rest of the platform works without them. - ---- - -## πŸš€ Deployment - -### Automated Deployment - -```bash -# Deploy updates -npm run deploy -``` - -### Manual Deployment - -```bash -# Build the project -npm run build - -# Deploy to Cloudflare Workers -wrangler deploy -``` - -### Deployment Process - -1. **Build Frontend** - Vite builds React app to `dist/` -2. **Deploy Worker** - Wrangler deploys Worker with static assets -3. **Update Configuration** - Environment variables and bindings applied -4. **Global Distribution** - Deployed to Cloudflare's edge network - -### GitHub Actions Build for PaaS Deployment - -OpenShop includes a GitHub Actions workflow that automatically builds the project for PaaS deployment: - -**Workflow File**: `.github/workflows/build.yml` - -**What it builds:** -- **Frontend (`dist/` folder)**: Production-ready static files from Vite build -- **Worker Bundle (`dist/worker.bundle.js`)**: Single bundled JavaScript file with all dependencies, minified and optimized for Cloudflare Workers runtime -- **Build Metadata (`build-info.json`)**: JSON file with version, build date, commit hash, and build number - -**When it runs:** -- On push to `main` or `master` branches -- On pull requests to `main` or `master` branches -- Manual trigger via `workflow_dispatch` - -**Artifacts created:** -- `worker-bundle`: `dist/worker.bundle.js` - Single bundled worker file -- `frontend-dist`: Complete `dist/` folder with all frontend assets -- `frontend-dist-tar`: `frontend-dist.tar.gz` - Compressed frontend build -- `build-info`: `build-info.json` - Build metadata - -**Worker Bundle Features:** -- All dependencies bundled into a single file -- Minified and optimized for production -- Compatible with Cloudflare Workers runtime -- No template variables injected - pure bundled code - -**Using artifacts for PaaS deployment:** - -1. **Download artifacts** from the GitHub Actions run: - - Go to the Actions tab in your repository - - Select the latest workflow run - - Download the artifacts you need - -2. **For worker deployment:** - ```bash - # Download worker.bundle.js from the worker-bundle artifact - # Deploy the worker.bundle.js file to your Cloudflare Workers runtime - # The bundle contains pure bundled code without any template variables - ``` - -3. **For frontend deployment:** - ```bash - # Option 1: Use the compressed package - tar -xzf frontend-dist.tar.gz - # Upload the extracted files to your static hosting service - - # Option 2: Use the dist folder directly - # Upload the entire dist/ folder (excluding worker.bundle.js) to your CDN - ``` - -**Build Scripts:** -- `npm run build` - Builds the frontend only -- `npm run build:worker` - Builds the worker bundle only -- `npm run build:all` - Builds both frontend and worker bundle - -**Note**: The worker bundle requires Cloudflare Workers runtime. Ensure your PaaS platform supports: -- Cloudflare Workers runtime (or compatible environment) -- Required environment variables (see Configuration section) - -### Multi-Site Deployment - -OpenShop supports managing multiple sites from one codebase: - -```bash -# List all configured sites -npm run sites - -# Deploy a specific site -npm run deploy my-store-name - -# Interactive site selection -npm run deploy -``` - -Each site maintains its own: -- Worker deployment -- KV namespace (separate data) -- Configuration (`toml/.toml`) -- Admin credentials and settings - -**πŸ“– See [MULTI-SITE.md](MULTI-SITE.md) for complete documentation** - ---- - -## πŸ”’ Security Architecture - -### Authentication Flow - -```mermaid -sequenceDiagram - participant U as User - participant W as Worker - participant KV as Cloudflare KV - - U->>W: POST /api/admin/login {password} - W->>W: Validate password - W->>KV: Store token with TTL - W->>U: Return token - U->>U: Store token in localStorage - - U->>W: Admin request + X-Admin-Token header - W->>KV: Validate token - KV->>W: Token valid/invalid - W->>U: Allow/Deny request -``` - -### Data Protection - -| Layer | Protection Method | -|-------|------------------| -| **Transport** | HTTPS encryption (Cloudflare SSL) | -| **Storage** | KV encryption at rest and in transit | -| **Authentication** | Token-based with server-side validation | -| **Authorization** | Endpoint-level access control | -| **Input Validation** | Server-side sanitization and validation | - ---- - -## πŸ“ˆ Performance Metrics - -### Cloudflare Workers Benefits - -- **πŸš€ Global Edge** - Sub-100ms response times worldwide -- **⚑ Zero Cold Starts** - Instant function execution -- **πŸ“Š 100k Requests/Day** - Generous free tier limits -- **πŸ”„ Auto-scaling** - Handles traffic spikes automatically -- **πŸ’Ύ KV Storage** - 100k reads, 1k writes daily (free tier) - -### Optimization Features - -- **Static Asset Caching** - CDN caching for images, CSS, JS -- **API Response Caching** - Smart caching for product/collection data -- **Image Optimization** - Cloudflare image resizing and optimization -- **Minification** - Automatic JS/CSS minification - ---- - -## 🎨 Customization - -### Frontend Customization - -```bash -# Tailwind CSS configuration -tailwind.config.js - -# Component customization -src/components/ui/ - -# Theme customization -src/index.css -``` - -### Backend Customization - -```bash -# API routes -src/worker.js - -# Middleware -src/middleware/ - -# Business logic -src/lib/ -``` - ---- - -## πŸ”§ Troubleshooting - -### Common Setup Issues - -**Issue: KV Namespace Creation Error** -```bash -# Error: Unknown arguments: preview, kv:namespace, create -``` -**Solution**: Using correct Wrangler command syntax (fixed in latest version) - -**Issue: Authentication Error** -```bash -# Error: You are logged in with an API Token -``` -**Solution**: Script now uses API Token directly without OAuth login - -**Issue: Empty KV ID in wrangler.toml** -```bash -# Error: "id" field but got {"binding":"OPENSHOP_KV","id":""} -``` -**Solution**: KV binding added after namespace creation (fixed) - -**Issue: 500 Error on /admin Route** -```bash -# Error: 500 Internal Server Error when visiting /admin -``` -**Solution**: Fixed SPA routing to properly serve React app for client-side routes (fixed) - -**Issue: 404 Error When Creating Collections/Products** -```bash -# Error: POST /api/collections 404 (Not Found) -``` -**Solution**: Updated admin components to use authenticated `/api/admin/*` endpoints (fixed) - -### Getting Help - -If you encounter issues: - -1. **Check Node.js Version** - Ensure you have Node.js 18+ installed -2. **Verify Credentials** - Double-check your Cloudflare API token and account ID -3. **Check Wrangler Version** - Run `wrangler --version` (should be 3.0+) -4. **Review Logs** - Check the Wrangler logs mentioned in error messages - ---- - -## πŸ§ͺ Testing - -### Manual Testing Checklist - -**Storefront:** -- [ ] Browse products and collections -- [ ] Add items to cart -- [ ] Complete checkout process -- [ ] Test mobile responsiveness - -**Admin Dashboard:** -- [ ] Login with admin credentials -- [ ] Create/edit products and collections -- [ ] Upload multiple product images -- [ ] Customize store settings and storefront theme -- [ ] View analytics dashboard - -### API Testing - -```bash -# Test public endpoints -curl https://your-project.workers.dev/api/products - -# Test admin authentication -curl -X POST https://your-project.workers.dev/api/admin/login \ - -H "Content-Type: application/json" \ - -d '{"password":"your_password"}' -``` +- **[Architecture Guide](docs/ARCHITECTURE.md)** - Technical architecture, security, and data models +- **[API Reference](docs/API.md)** - Complete API documentation +- **[Configuration Guide](docs/CONFIGURATION.md)** - Environment variables and setup +- **[Stripe Integration](docs/STRIPE.md)** - Payment processing and webhook setup +- **[AI & Media](docs/AI_MEDIA.md)** - Gemini AI and Google Drive integration +- **[Deployment Guide](docs/DEPLOYMENT.md)** - Deployment instructions and multi-site setup +- **[Performance Guide](docs/PERFORMANCE.md)** - Performance metrics and optimization +- **[Customization Guide](docs/CUSTOMIZATION.md)** - Frontend and backend customization +- **[Troubleshooting](docs/TROUBLESHOOTING.md)** - Common issues and solutions +- **[Testing Guide](docs/TESTING.md)** - Testing guidelines and examples --- @@ -686,7 +212,7 @@ This project is licensed under the **GNU Affero General Public License v3.0 (AGP ### Getting Help -- **πŸ“š Documentation** - Complete guides in this repository +- **πŸ“š Documentation** - Complete guides in the `docs/` directory - **πŸ› Bug Reports** - [GitHub Issues](https://github.com/ajfrio/openshop/issues) - **πŸ’‘ Feature Requests** - [GitHub Discussions](https://github.com/ajfrio/openshop/discussions) - **πŸ’¬ Community Chat** - [Discord Server](https://discord.gg/qAnDxHmEmS) @@ -723,4 +249,4 @@ Special thanks to: [⭐ Star this repo](https://github.com/ajfrio/openshop) β€’ [πŸ› Report Bug](https://github.com/ajfrio/openshop/issues) β€’ [πŸ’‘ Request Feature](https://github.com/ajfrio/openshop/discussions) - \ No newline at end of file + diff --git a/SECURITY_ANALYSIS.md b/SECURITY_ANALYSIS.md deleted file mode 100644 index 384034f..0000000 --- a/SECURITY_ANALYSIS.md +++ /dev/null @@ -1,89 +0,0 @@ -# Security Analysis Report - -## Executive Summary -This document outlines security vulnerabilities found in the OpenShop codebase and the fixes implemented to address them. - -## Critical Vulnerabilities Found - -### 1. **Weak Authentication System** (CRITICAL) -- **Issue**: Plain text password comparison with default password "admin123" -- **Risk**: Vulnerable to brute force attacks, no password hashing -- **Location**: `src/routes/admin/auth.js` -- **Fix**: Implement password hashing with bcrypt/Argon2 - -### 2. **Overly Permissive CORS** (HIGH) -- **Issue**: CORS set to `['*']` allowing any origin -- **Risk**: CSRF attacks, unauthorized API access -- **Location**: `src/config/constants.js` -- **Fix**: Restrict to specific allowed origins - -### 3. **Information Disclosure in Logs** (MEDIUM) -- **Issue**: Console logs expose secrets, tokens, and sensitive data -- **Risk**: Secrets leaked in logs accessible to attackers -- **Location**: Multiple files (stripe.ts, auth routes) -- **Fix**: Remove or sanitize sensitive data from logs - -### 4. **No Rate Limiting** (HIGH) -- **Issue**: Authentication endpoints have no rate limiting -- **Risk**: Brute force attacks on login endpoints -- **Location**: All authentication routes -- **Fix**: Implement rate limiting middleware - -### 5. **Missing OAuth State Validation** (HIGH) -- **Issue**: OAuth state parameter generated but not validated in callback -- **Risk**: CSRF attacks on OAuth flow -- **Location**: `OpenShop-Service/worker/routes/auth.ts` -- **Fix**: Store and validate state parameter - -### 6. **Hardcoded Secrets** (MEDIUM) -- **Issue**: Stripe client ID hardcoded in source code -- **Risk**: Secret exposure if code is leaked -- **Location**: `OpenShop-Service/worker/routes/stripe.ts:35` -- **Fix**: Move to environment variables - -### 7. **Missing Security Headers** (MEDIUM) -- **Issue**: No security headers (CSP, HSTS, X-Frame-Options, etc.) -- **Risk**: XSS attacks, clickjacking, MITM attacks -- **Location**: Worker responses -- **Fix**: Add security headers middleware - -### 8. **Webhook Replay Attack Vulnerability** (MEDIUM) -- **Issue**: Webhook signature verified but timestamp not validated -- **Risk**: Replay attacks using old webhook payloads -- **Location**: `OpenShop-Service/worker/utils/stripe.ts` -- **Fix**: Add timestamp validation (5-minute window) - -### 9. **Insufficient Input Validation** (MEDIUM) -- **Issue**: Some endpoints lack comprehensive input validation -- **Risk**: Injection attacks, data corruption -- **Location**: Various API routes -- **Fix**: Add comprehensive validation middleware - -### 10. **Error Information Disclosure** (LOW) -- **Issue**: Error messages may leak internal information -- **Risk**: Information disclosure to attackers -- **Location**: Error handlers -- **Fix**: Sanitize error messages in production - -## Security Best Practices Implemented - -βœ… **SQL Injection Protection**: All database queries use parameterized statements -βœ… **Token Hashing**: Session tokens are hashed before storage -βœ… **HTTPS Enforcement**: Secure cookies with HttpOnly and Secure flags -βœ… **Webhook Signature Verification**: Stripe webhooks are verified - -## Recommendations - -1. **Implement Password Hashing**: Use bcrypt or Argon2 for password storage -2. **Add Rate Limiting**: Use Cloudflare Workers rate limiting or implement custom solution -3. **Restrict CORS**: Only allow specific trusted origins -4. **Security Headers**: Implement comprehensive security headers -5. **Regular Security Audits**: Schedule periodic security reviews -6. **Dependency Scanning**: Regularly scan for vulnerable dependencies -7. **Secrets Management**: Use Cloudflare Workers secrets, never commit secrets -8. **Monitoring**: Implement security monitoring and alerting - -## Fixes Applied - -All fixes have been implemented in the codebase. See individual file changes for details. - diff --git a/SECURITY_FIXES_SUMMARY.md b/SECURITY_FIXES_SUMMARY.md deleted file mode 100644 index 84f41bd..0000000 --- a/SECURITY_FIXES_SUMMARY.md +++ /dev/null @@ -1,251 +0,0 @@ -# Security Fixes Summary - -This document summarizes all security fixes applied to the OpenShop codebase. - -## Fixes Implemented - -### 1. βœ… Password Hashing (CRITICAL) -**File**: `src/routes/admin/auth.js`, `src/utils/crypto.js` - -**Changes**: -- Implemented PBKDF2 password hashing with SHA-256 -- Passwords are now hashed with salt (100,000 iterations) -- Hash format: `iterations:salt:hash` -- Backward compatible: automatically hashes existing plain text passwords on first use - -**Security Impact**: Prevents password exposure even if database is compromised. - ---- - -### 2. βœ… Rate Limiting (HIGH) -**File**: `src/routes/admin/auth.js` - -**Changes**: -- Added rate limiting to login endpoint -- 5 failed attempts per 15 minutes per IP address -- Uses Cloudflare Workers KV for rate limit tracking -- Rate limit cleared on successful login - -**Security Impact**: Prevents brute force attacks on authentication endpoints. - ---- - -### 3. βœ… CORS Configuration (HIGH) -**File**: `src/config/constants.js`, `src/middleware/cors.js`, `src/worker.js` - -**Changes**: -- CORS now configurable via `CORS_ORIGINS` environment variable -- Falls back to `SITE_URL` if `CORS_ORIGINS` not set -- Only uses wildcard `*` as last resort -- Function `getCorsOrigins(env)` properly reads from Workers environment - -**Security Impact**: Prevents unauthorized cross-origin requests and CSRF attacks. - ---- - -### 4. βœ… OAuth State Validation (HIGH) -**File**: `OpenShop-Service/worker/routes/auth.ts`, `OpenShop-Service/worker/routes/stripe.ts` - -**Changes**: -- OAuth state parameter now stored in KV with 5-minute expiration -- State validated in callback to prevent CSRF attacks -- State deleted after use to prevent replay attacks -- Applied to both Google OAuth and Stripe Connect flows - -**Security Impact**: Prevents CSRF attacks on OAuth flows. - ---- - -### 5. βœ… Security Headers (MEDIUM) -**File**: `src/worker.js`, `OpenShop-Service/worker/index.ts` - -**Changes**: -- Added comprehensive security headers to all responses: - - `X-Content-Type-Options: nosniff` - - `X-Frame-Options: DENY` - - `X-XSS-Protection: 1; mode=block` - - `Referrer-Policy: strict-origin-when-cross-origin` - - `Permissions-Policy: geolocation=(), microphone=(), camera=()` - - `Content-Security-Policy` (restrictive policy with Stripe exceptions) - - `Strict-Transport-Security` (HTTPS only) - -**Security Impact**: Protects against XSS, clickjacking, and MITM attacks. - ---- - -### 6. βœ… Webhook Timestamp Validation (MEDIUM) -**File**: `OpenShop-Service/worker/utils/stripe.ts` - -**Changes**: -- Added timestamp validation to webhook signature verification -- Rejects webhooks older than 5 minutes (prevents replay attacks) -- Removed sensitive logging from webhook verification - -**Security Impact**: Prevents replay attacks using old webhook payloads. - ---- - -### 7. βœ… Removed Sensitive Logging (MEDIUM) -**File**: `OpenShop-Service/worker/routes/stripe.ts`, `OpenShop-Service/worker/utils/stripe.ts` - -**Changes**: -- Removed console logs that exposed: - - Webhook secrets - - Signatures - - Payloads - - Internal error details -- Error messages sanitized for production - -**Security Impact**: Prevents information disclosure through logs. - ---- - -### 8. βœ… Hardcoded Secrets Removed (MEDIUM) -**File**: `OpenShop-Service/worker/routes/stripe.ts` - -**Changes**: -- Removed hardcoded Stripe Connect client ID -- Now reads from `STRIPE_CONNECT_CLIENT_ID` environment variable -- Added validation to ensure environment variable is set - -**Security Impact**: Prevents secret exposure if code is leaked. - ---- - -### 9. βœ… Enhanced Input Validation (MEDIUM) -**File**: `src/routes/public/checkout.js` - -**Changes**: -- Added validation for Stripe price IDs (format: `price_*`) -- Added validation for Stripe session IDs (format: `cs_*`) -- Added cart size limits (max 100 items) -- Added quantity validation (1-100 per item) -- Added length limits to prevent DoS attacks -- Input sanitization (trimming) - -**Security Impact**: Prevents injection attacks and DoS through malformed input. - ---- - -### 10. βœ… Improved Error Handling (LOW) -**File**: `OpenShop-Service/worker/index.ts` - -**Changes**: -- Generic error messages for clients -- Internal error details only logged server-side -- Removed stack traces from client responses - -**Security Impact**: Prevents information disclosure to attackers. - ---- - -## Configuration Required - -### Environment Variables - -Add these to your `wrangler.jsonc` or Cloudflare Workers dashboard: - -```jsonc -{ - "vars": { - // CORS Configuration (comma-separated list) - "CORS_ORIGINS": "https://yourdomain.com,https://www.yourdomain.com", - - // Stripe Connect (if using OpenShop-Service) - "STRIPE_CONNECT_CLIENT_ID": "ca_...", - - // Existing variables (keep these) - "ADMIN_PASSWORD": "your-secure-password", - "STRIPE_SECRET_KEY": "sk_...", - "SITE_URL": "https://yourdomain.com" - } -} -``` - -### Migration Notes - -1. **Password Migration**: Existing plain text passwords will be automatically hashed on first login. No manual migration needed. - -2. **CORS Configuration**: Update `CORS_ORIGINS` environment variable to restrict allowed origins. Defaults to `SITE_URL` if not set. - -3. **Stripe Connect**: Add `STRIPE_CONNECT_CLIENT_ID` environment variable to replace the hardcoded value. - ---- - -## Testing Recommendations - -1. **Test Authentication**: - - Verify login works with existing passwords - - Test rate limiting (5 failed attempts should block) - - Verify password hashing on first login - -2. **Test OAuth Flows**: - - Verify Google OAuth works correctly - - Test that invalid state parameters are rejected - - Verify state is deleted after use - -3. **Test Security Headers**: - - Use browser dev tools to verify headers are present - - Test CSP doesn't break Stripe integration - - Verify HSTS header on HTTPS - -4. **Test Input Validation**: - - Try invalid Stripe IDs - - Test cart with >100 items - - Test with malformed input - -5. **Test Webhooks**: - - Verify webhook signature validation - - Test that old webhooks (>5 min) are rejected - ---- - -## Additional Recommendations - -1. **Regular Security Audits**: Schedule periodic security reviews -2. **Dependency Scanning**: Use tools like `npm audit` regularly -3. **Secrets Management**: Never commit secrets to version control -4. **Monitoring**: Implement security monitoring and alerting -5. **Backup**: Ensure password hashes are backed up (they're one-way) -6. **Consider Argon2**: For future improvements, consider migrating to Argon2 for password hashing (more secure than PBKDF2) - ---- - -## Files Modified - -### OpenShop Main Project -- `src/routes/admin/auth.js` - Password hashing, rate limiting -- `src/utils/crypto.js` - Password hashing functions -- `src/config/constants.js` - CORS configuration -- `src/middleware/cors.js` - CORS middleware -- `src/worker.js` - Security headers -- `src/routes/public/checkout.js` - Input validation -- `src/middleware/securityHeaders.js` - Security headers (new file) - -### OpenShop-Service Project -- `worker/routes/auth.ts` - OAuth state validation -- `worker/routes/stripe.ts` - Stripe Connect state validation, removed hardcoded secrets -- `worker/utils/stripe.ts` - Webhook timestamp validation, removed sensitive logs -- `worker/index.ts` - Security headers, improved error handling - ---- - -## Security Best Practices Maintained - -βœ… **SQL Injection Protection**: All queries use parameterized statements -βœ… **Token Hashing**: Session tokens are hashed before storage -βœ… **HTTPS Enforcement**: Secure cookies with HttpOnly and Secure flags -βœ… **Webhook Signature Verification**: Stripe webhooks are verified -βœ… **Input Validation**: Comprehensive validation on user input -βœ… **Error Sanitization**: No sensitive information in error messages - ---- - -## Questions or Issues? - -If you encounter any issues with these security fixes, please: -1. Check environment variable configuration -2. Verify Cloudflare Workers KV namespaces are properly configured -3. Review logs for any error messages -4. Test in development environment first - diff --git a/docs/AI_MEDIA.md b/docs/AI_MEDIA.md new file mode 100644 index 0000000..6b99faa --- /dev/null +++ b/docs/AI_MEDIA.md @@ -0,0 +1,246 @@ +# AI & Media Integrations + +Guide to optional AI image generation and Google Drive integration features in OpenShop. + +## Overview + +OpenShop includes optional integrations for AI-powered image generation and Google Drive storage. These features enhance the admin experience but are not required for core functionality. + +## Gemini Image Generation + +Generate product or hero images directly from the admin dashboard using Google's Gemini image generation API. + +### What It Does + +From the admin media picker, you can: +- Generate product images from text prompts +- Provide up to 4 reference images for style guidance +- Generate hero banner images for collections +- Create custom images without leaving the admin + +### Setup + +1. **Get Gemini API Key** + - Visit [Google AI Studio](https://ai.google.dev/) + - Create an API key for Gemini + +2. **Configure in OpenShop** + + **Local Development** (`.env` file): + ```env + GEMINI_API_KEY=your_gemini_api_key + ``` + + **Production**: + ```bash + wrangler secret put GEMINI_API_KEY + ``` + +3. **Access in Admin** + - Navigate to admin dashboard + - Open media picker when adding/editing products or collections + - Click "Generate Image" option + - Enter your prompt and optionally upload reference images + +### API Endpoint + +**Endpoint**: `POST /api/admin/ai/generate-image` + +**Authentication**: Requires admin token + +**Request Body**: +```json +{ + "prompt": "A modern laptop on a wooden desk", + "referenceImages": [ + "https://example.com/ref1.jpg", + "https://example.com/ref2.jpg" + ] +} +``` + +**Response**: +```json +{ + "imageUrl": "https://generated-image-url.jpg" +} +``` + +### Usage Tips + +- **Be specific**: Detailed prompts produce better results +- **Use reference images**: Upload style references for consistent look +- **Iterate**: Generate multiple variations and choose the best +- **Optimize**: Generated images can be large; consider compression + +## Google Drive Integration + +Upload and manage product images using Google Drive as your storage backend. + +### What It Does + +- Upload images from admin to Google Drive +- Automatically make images publicly viewable +- Generate direct-view URLs for product images +- Use built-in image proxy to avoid CORS/403 errors +- Organize images in a dedicated folder structure + +### Setup + +1. **Create Google OAuth Credentials** + - Go to [Google Cloud Console](https://console.cloud.google.com/) + - Create a new project or select existing + - Enable Google Drive API + - Create OAuth 2.0 credentials + - Add redirect URI: `https://your-project.workers.dev/api/admin/drive/oauth/callback` + +2. **Configure in OpenShop** + + **Local Development** (`.env` file): + ```env + GOOGLE_CLIENT_ID=your_google_client_id + GOOGLE_CLIENT_SECRET=your_google_client_secret + DRIVE_ROOT_FOLDER=OpenShop # Optional, defaults to site URL + ``` + + **Production**: + ```bash + wrangler secret put GOOGLE_CLIENT_ID + wrangler secret put GOOGLE_CLIENT_SECRET + wrangler secret put DRIVE_ROOT_FOLDER # Optional + ``` + +3. **Connect Google Drive** + - Navigate to admin dashboard + - Open media picker + - Click "Connect Google Drive" + - Complete OAuth flow in popup + - Drive connection is now active + +### OAuth Flow + +1. **Initiate Connection**: Click "Connect Google Drive" in admin +2. **Google Authorization**: Redirected to Google sign-in +3. **Permissions**: Grant Drive access permissions +4. **Callback**: Returned to OpenShop with access token +5. **Token Storage**: Token stored securely in Cloudflare KV + +### Uploading Images + +After connecting Google Drive: + +1. **Select Image**: Choose local file or use generated image +2. **Upload to Drive**: Click "Upload to Drive" +3. **Automatic Processing**: + - File uploaded to Drive root folder + - File permissions set to public + - Direct-view URL generated +4. **Use in Product**: URL automatically inserted into product/collection + +### Image Proxy + +OpenShop includes a built-in image proxy to serve Google Drive images reliably: + +**Endpoint**: `GET /api/image-proxy?src=` + +**Why It's Needed**: Google Drive direct links can return 403 errors or CORS issues. The proxy ensures images load correctly in your storefront. + +**Automatic Usage**: The UI automatically normalizes Drive links to use the proxy when displaying images. + +### Folder Structure + +Images are organized in Google Drive: + +``` +Google Drive Root +└── OpenShop/ (or custom DRIVE_ROOT_FOLDER) + └── your-project.workers.dev/ + β”œβ”€β”€ products/ + β”‚ β”œβ”€β”€ product-image-1.jpg + β”‚ └── product-image-2.jpg + └── collections/ + └── hero-banner.jpg +``` + +### API Endpoints + +**Check Connection Status**: +``` +GET /api/admin/drive/status +``` + +**Start OAuth Flow**: +``` +GET /api/admin/drive/oauth/start +``` + +**OAuth Callback**: +``` +GET /api/admin/drive/oauth/callback +``` + +**Upload Image**: +``` +POST /api/admin/drive/upload +Content-Type: multipart/form-data + +{ + "file": , + "folder": "products" // Optional +} +``` + +## Combining Features + +You can use both features together: + +1. **Generate** image with Gemini AI +2. **Upload** generated image to Google Drive +3. **Use** Drive URL in your product/collection + +This workflow provides a complete image management solution without external tools. + +## Troubleshooting + +### Gemini Issues + +**Issue**: Image generation fails +- **Solution**: Verify `GEMINI_API_KEY` is set correctly and has sufficient quota + +**Issue**: Generated images are low quality +- **Solution**: Use more detailed prompts and reference images + +### Google Drive Issues + +**Issue**: OAuth flow fails +- **Solution**: Check redirect URI matches exactly, verify OAuth credentials + +**Issue**: Upload fails +- **Solution**: Ensure Drive connection is active, check file size limits + +**Issue**: Images don't display +- **Solution**: Verify image proxy is working, check Drive file permissions + +**Issue**: 403 errors on images +- **Solution**: Use the built-in image proxy (`/api/image-proxy?src=...`) + +For more help, see the [Troubleshooting Guide](TROUBLESHOOTING.md). + +## Best Practices + +- **Image Optimization**: Compress images before upload for faster loading +- **Naming Conventions**: Use descriptive filenames for easier management +- **Folder Organization**: Keep products and collections organized in Drive +- **Backup**: Regularly backup your Drive folder +- **Cost Management**: Monitor API usage for Gemini and Drive storage + +## Feature Availability + +These features are **optional**. OpenShop works perfectly without them. You can: + +- Use external image hosting (Imgur, Cloudinary, etc.) +- Upload images directly via URL +- Use local file uploads (if hosting supports it) + +The AI and Drive features simply provide additional convenience and integration options. + diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..4086295 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,129 @@ +# OpenShop API Reference + +Complete API documentation for all OpenShop endpoints. + +## Public Endpoints (Read-Only) + +These endpoints are publicly accessible and require no authentication. + +| Endpoint | Method | Description | Authentication | +|----------|--------|-------------|----------------| +| `/api/products` | `GET` | List all products | None | +| `/api/products/:id` | `GET` | Get single product | None | +| `/api/collections` | `GET` | List all collections | None | +| `/api/collections/:id` | `GET` | Get single collection | None | +| `/api/collections/:id/products` | `GET` | Get products in collection | None | +| `/api/store-settings` | `GET` | Get store configuration | None | + +## Checkout Endpoints + +These endpoints handle payment processing and checkout flows. + +| Endpoint | Method | Description | Authentication | +|----------|--------|-------------|----------------| +| `/api/create-checkout-session` | `POST` | Single item checkout | None | +| `/api/create-cart-checkout-session` | `POST` | Multi-item cart checkout | None | +| `/api/image-proxy?src=` | `GET` | Proxy for Google Drive images | None | + +## Admin Endpoints (Authenticated) + +These endpoints require admin authentication via the `X-Admin-Token` header. + +| Endpoint | Method | Description | Authentication | +|----------|--------|-------------|----------------| +| `/api/admin/login` | `POST` | Admin authentication | Password | +| `/api/admin/products` | `POST` | Create product | Admin Token | +| `/api/admin/products/:id` | `PUT, DELETE` | Update/delete product | Admin Token | +| `/api/admin/store-settings` | `PUT` | Update store settings | Admin Token | +| `/api/analytics` | `GET` | Revenue and order analytics | Admin Token | +| `/api/admin/ai/generate-image` | `POST` | Generate image via Gemini | Admin Token | +| `/api/admin/drive/status` | `GET` | Google Drive connection status | Admin Token | +| `/api/admin/drive/oauth/start` | `GET` | Begin Google Drive OAuth | None | +| `/api/admin/drive/oauth/callback` | `GET` | Handle Drive OAuth callback | None | +| `/api/admin/drive/upload` | `POST` | Upload image to Google Drive | Admin Token | + +> **Note**: Drive OAuth endpoints are intentionally unauthenticated to support the popup OAuth flow. All other Drive actions require admin auth. + +## Authentication + +### Admin Login + +**Endpoint**: `POST /api/admin/login` + +**Request Body**: +```json +{ + "password": "your_admin_password" +} +``` + +**Response**: +```json +{ + "token": "admin_token_here", + "expiresAt": "2024-01-01T12:00:00Z" +} +``` + +**Usage**: Store the token in `localStorage` and include it in subsequent admin requests as the `X-Admin-Token` header. + +### Authenticated Requests + +Include the admin token in the request header: + +``` +X-Admin-Token: your_admin_token_here +``` + +Tokens expire after 24 hours and must be refreshed by logging in again. + +## Example Requests + +### Get All Products + +```bash +curl https://your-project.workers.dev/api/products +``` + +### Get Single Product + +```bash +curl https://your-project.workers.dev/api/products/prod_123 +``` + +### Admin Login + +```bash +curl -X POST https://your-project.workers.dev/api/admin/login \ + -H "Content-Type: application/json" \ + -d '{"password":"your_password"}' +``` + +### Create Product (Authenticated) + +```bash +curl -X POST https://your-project.workers.dev/api/admin/products \ + -H "Content-Type: application/json" \ + -H "X-Admin-Token: your_token_here" \ + -d '{ + "name": "New Product", + "description": "Product description", + "price": 29.99, + "currency": "usd", + "images": ["https://example.com/image.jpg"] + }' +``` + +### Create Checkout Session + +```bash +curl -X POST https://your-project.workers.dev/api/create-checkout-session \ + -H "Content-Type: application/json" \ + -d '{ + "priceId": "price_123", + "quantity": 1, + "successUrl": "https://your-store.com/success", + "cancelUrl": "https://your-store.com/cancel" + }' +``` + diff --git a/WORKERS-ARCHITECTURE.md b/docs/ARCHITECTURE.md similarity index 60% rename from WORKERS-ARCHITECTURE.md rename to docs/ARCHITECTURE.md index f330573..9ee356a 100644 --- a/WORKERS-ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,12 +1,39 @@ -# OpenShop Workers Architecture +# OpenShop Architecture -## πŸš€ **Migration to Cloudflare Workers Complete** +## Overview + +OpenShop is built entirely on the Cloudflare ecosystem, leveraging Cloudflare Workers for hosting, Cloudflare KV for data storage, and Stripe for payments. The platform is designed to stay within Cloudflare's generous free tier while providing enterprise-grade performance and security. + +## Technical Architecture + +```mermaid +graph TB + A[Cloudflare Worker] --> B[Static Assets] + A --> C[API Endpoints] + A --> D[Authentication] + C --> E[Cloudflare KV] + C --> F[Stripe API] + D --> E +``` + +| Component | Technology | Purpose | +|-----------|------------|---------| +| **Frontend** | Vite + React + Tailwind CSS | User interface and experience | +| **Backend** | Cloudflare Workers + Hono | API endpoints and business logic | +| **Database** | Cloudflare KV | Product, collection, and settings storage | +| **Payments** | Stripe API | Payment processing and checkout | +| **Authentication** | Token-based system | Secure admin access | +| **Deployment** | Wrangler CLI | Automated deployment pipeline | + +## Workers Architecture + +### Migration to Cloudflare Workers We've successfully migrated from Cloudflare Pages Functions to a modern Cloudflare Workers architecture with static asset serving. -## πŸ“Š **Architecture Comparison** +### Architecture Comparison -### **Previous: Pages Functions** +#### Previous: Pages Functions ``` Cloudflare Pages Project β”œβ”€β”€ Static Files (React) @@ -14,7 +41,7 @@ Cloudflare Pages Project └── KV Namespace binding ``` -### **New: Cloudflare Workers** βœ… +#### New: Cloudflare Workers βœ… ``` Cloudflare Worker β”œβ”€β”€ Static Assets (React) via Workers Assets @@ -23,37 +50,71 @@ Cloudflare Worker └── KV Namespace binding ``` -## βœ… **Workers Advantages** +### Workers Advantages -### **1. Performance Benefits** +#### 1. Performance Benefits - **Faster Cold Starts**: Workers have minimal cold start time - **Better Routing**: Hono framework provides efficient routing - **Single Runtime**: No context switching between Pages and Functions - **Edge Optimization**: Better performance at Cloudflare edge locations -### **2. Generous Free Tier** +#### 2. Generous Free Tier - **100,000 requests/day** (vs Pages Functions limits) - **10ms CPU time per request** - **Static asset serving included** - **KV operations included** -### **3. Enhanced Node.js Compatibility** +#### 3. Enhanced Node.js Compatibility - **nodejs_compat flag**: Access to more NPM packages - **Better Stripe integration**: Full Node.js Stripe SDK support - **Modern JavaScript**: Latest ES modules and features - **npm ecosystem**: Broader package compatibility -### **4. Simplified Architecture** +#### 4. Simplified Architecture - **Single Deployment**: One Worker handles everything - **Unified Configuration**: Single wrangler.toml - **Better Development**: `wrangler dev` for full-stack development - **Easier Debugging**: Single runtime environment -## πŸ”’ **Security Analysis: Workers Architecture** +### Single Worker Deployment + +``` +my-store.workers.dev +β”œβ”€β”€ GET / β†’ React App (index.html) +β”œβ”€β”€ GET /admin β†’ React App (admin routes) +β”œβ”€β”€ GET /api/products β†’ Worker API (public) +β”œβ”€β”€ POST /api/admin/products β†’ Worker API (authenticated) +└── GET /assets/* β†’ Static files (CSS, JS, images) +``` + +### Hono Framework Integration + +```javascript +import { Hono } from 'hono' + +const app = new Hono() -### **βœ… Is This Secure? YES - Here's Why:** +// Public endpoints (read-only) +app.get('/api/products', publicHandler) + +// Admin endpoints (authenticated) +app.use('/api/admin/*', authMiddleware) +app.post('/api/admin/products', adminHandler) + +// Static asset serving +app.use('/*', serveStatic({ root: './' })) +``` + +### Modern Workers Features +- **Node.js Compatibility**: `nodejs_compat` flag enabled +- **Static Assets**: Built-in asset serving +- **ES Modules**: Modern JavaScript imports +- **Hono Framework**: Fast, lightweight routing + +## Security Architecture + +### Runtime Isolation -### **1. Runtime Isolation** ``` Browser Environment: β”œβ”€β”€ React App (JavaScript) @@ -70,7 +131,8 @@ Worker Environment: **Key Point**: The Worker runs on **Cloudflare's secure edge servers**, completely separate from the browser environment. -### **2. Static Asset Security** +### Static Asset Security + ``` Worker Asset Serving: β”œβ”€β”€ dist/ files served as static content @@ -81,7 +143,28 @@ Worker Asset Serving: **Security**: Static assets (HTML, CSS, JS) are served directly, while API logic runs server-side only. -### **3. Authentication & Authorization** +### Authentication Flow + +```mermaid +sequenceDiagram + participant U as User + participant W as Worker + participant KV as Cloudflare KV + + U->>W: POST /api/admin/login {password} + W->>W: Validate password + W->>KV: Store token with TTL + W->>U: Return token + U->>U: Store token in localStorage + + U->>W: Admin request + X-Admin-Token header + W->>KV: Validate token + KV->>W: Token valid/invalid + W->>U: Allow/Deny request +``` + +### Request Flow + ``` Request Flow: Browser β†’ Worker β†’ Auth Middleware β†’ KV/Stripe @@ -95,7 +178,8 @@ Public Server Token Check Protected APIs - βœ… **24-hour expiration** with automatic cleanup - βœ… **Public endpoints** are read-only -### **4. Environment Variable Security** +### Environment Variable Security + ```javascript // In Worker (Server-side only): const stripe = new Stripe(c.env.STRIPE_SECRET_KEY) // βœ… Secure @@ -107,36 +191,8 @@ const adminPass = c.env.ADMIN_PASSWORD // βœ… Secure **Critical**: Environment variables are **only available in the Worker runtime**, never exposed to the browser. -## πŸ—οΈ **New Architecture Details** - -### **1. Single Worker Deployment** -``` -my-store.workers.dev -β”œβ”€β”€ GET / β†’ React App (index.html) -β”œβ”€β”€ GET /admin β†’ React App (admin routes) -β”œβ”€β”€ GET /api/products β†’ Worker API (public) -β”œβ”€β”€ POST /api/admin/products β†’ Worker API (authenticated) -└── GET /assets/* β†’ Static files (CSS, JS, images) -``` - -### **2. Hono Framework Integration** -```javascript -import { Hono } from 'hono' - -const app = new Hono() - -// Public endpoints (read-only) -app.get('/api/products', publicHandler) - -// Admin endpoints (authenticated) -app.use('/api/admin/*', authMiddleware) -app.post('/api/admin/products', adminHandler) +### Enhanced Security Model -// Static asset serving -app.use('/*', serveStatic({ root: './' })) -``` - -### **3. Enhanced Security Model** ``` Security Layers: 1. HTTPS Only (Cloudflare SSL) @@ -146,20 +202,36 @@ Security Layers: 5. Environment Isolation (Worker runtime) ``` -## 🚨 **Security Risk Analysis** +### Data Protection + +| Layer | Protection Method | +|-------|------------------| +| **Transport** | HTTPS encryption (Cloudflare SSL) | +| **Storage** | KV encryption at rest and in transit | +| **Authentication** | Token-based with server-side validation | +| **Authorization** | Endpoint-level access control | +| **Input Validation** | Server-side sanitization and validation | -### **❌ Theoretical Risks:** +### Security Implementation +- **Authentication Middleware**: Centralized auth checking +- **Token Management**: Secure KV-based session storage +- **CORS Protection**: Proper cross-origin configuration +- **Input Validation**: Comprehensive request validation + +### Security Risk Analysis + +#### ❌ Theoretical Risks: 1. **Source Code Visibility**: Worker code is in same repo as frontend 2. **Endpoint Discovery**: API routes are discoverable 3. **Single Domain**: Frontend and backend on same domain -### **βœ… Risk Mitigations:** +#### βœ… Risk Mitigations: 1. **No Secrets in Code**: All sensitive data in environment variables 2. **Authentication Required**: Admin endpoints require valid tokens 3. **Server-Side Validation**: All security checks happen server-side 4. **Cloudflare Security**: Built-in DDoS, rate limiting, WAF protection -### **πŸ” Security Verdict: SECURE** +### Security Verdict: SECURE **Why Workers Architecture is Secure:** @@ -169,87 +241,59 @@ Security Layers: 4. **Cloudflare Security**: Enterprise-grade edge protection 5. **Input Validation**: Server-side validation on all endpoints -## πŸ“ˆ **Performance Benefits** - -### **1. Reduced Latency** -- **Single Runtime**: No context switching between services -- **Edge Execution**: Code runs closer to users globally -- **Efficient Routing**: Hono framework optimized for Workers -- **Static Caching**: Assets cached at edge locations - -### **2. Better Scalability** -- **Auto-scaling**: Workers scale automatically with demand -- **No Cold Starts**: Minimal startup time -- **Global Distribution**: Runs on Cloudflare's global network -- **High Availability**: Built-in redundancy and failover - -### **3. Cost Efficiency** -- **Free Tier**: 100k requests/day at no cost -- **No Separate Billing**: Static assets included -- **KV Included**: Database operations within free tier -- **Bandwidth Free**: Cloudflare bandwidth at no cost - -## 🎯 **Deployment Architecture** - -### **What Gets Created:** -```bash -npm run setup -# Input: "my-electronics-store" - -Creates: -β”œβ”€β”€ Worker: my-electronics-store.workers.dev -β”œβ”€β”€ KV Namespace: MY-ELECTRONICS-STORE_KV -β”œβ”€β”€ Static Assets: Served by Worker -└── All APIs: Integrated in Worker +## Data Models + +### Product Schema + +```json +{ + "id": "prod_1a2b3c4d5e", + "name": "Classic Cotton T-Shirt", + "description": "A comfortable, high-quality t-shirt made from premium cotton.", + "price": 25.00, + "currency": "usd", + "images": [ + "https://example.com/image1.jpg", + "https://example.com/image2.jpg", + "https://example.com/image3.jpg" + ], + "stripePriceId": "price_AbC987zyx", + "stripeProductId": "prod_AbC123xyz", + "collectionId": "coll_xyz789" +} ``` -### **Multiple Store Support:** -```bash -# Store 1 -npm run setup β†’ "electronics-store" β†’ electronics-store.workers.dev - -# Store 2 -npm run setup β†’ "clothing-shop" β†’ clothing-shop.workers.dev +### Collection Schema -# Store 3 -npm run setup β†’ "book-store" β†’ book-store.workers.dev +```json +{ + "id": "coll_xyz789", + "name": "Summer Collection", + "description": "Our hottest items for the summer season.", + "heroImage": "https://example.com/hero-banner.jpg" +} ``` -## πŸ”§ **Technical Implementation** +### Store Settings Schema -### **1. Modern Workers Features** -- **Node.js Compatibility**: `nodejs_compat` flag enabled -- **Static Assets**: Built-in asset serving -- **ES Modules**: Modern JavaScript imports -- **Hono Framework**: Fast, lightweight routing +```json +{ + "logoType": "text|image", + "logoText": "OpenShop", + "logoImageUrl": "https://example.com/logo.png", + "storeName": "OpenShop", + "storeDescription": "Your amazing online store" +} +``` -### **2. Security Implementation** -- **Authentication Middleware**: Centralized auth checking -- **Token Management**: Secure KV-based session storage -- **CORS Protection**: Proper cross-origin configuration -- **Input Validation**: Comprehensive request validation +## Development Experience -### **3. Development Experience** - **Local Development**: `wrangler dev` for full-stack development - **Hot Reload**: Live reloading for both frontend and backend - **Debugging**: Integrated debugging with Workers runtime - **Testing**: Easy local testing with real Worker environment -## 🏁 **Conclusion** - -### **βœ… Workers Architecture is Superior:** - -1. **Better Performance**: Faster, more efficient execution -2. **Enhanced Security**: Same security model with better isolation -3. **Modern Stack**: Latest Cloudflare features and Node.js compatibility -4. **Cost Effective**: Generous free tier with room to grow -5. **Future Proof**: Aligned with Cloudflare's strategic direction -6. **Simplified Deployment**: Single service handles everything +## Conclusion -### **πŸ”’ Security is Maintained:** -- **Same Authentication**: Token-based admin system -- **Same Isolation**: Server/client separation preserved -- **Enhanced Protection**: Additional Cloudflare Workers security features -- **No New Risks**: All previous security measures intact +The Workers architecture provides **significant benefits** with **no security compromises**. The architecture is now more performant, cost-effective, and future-ready! -The migration to Workers provides **significant benefits** with **no security compromises**. The architecture is now more performant, cost-effective, and future-ready! πŸš€πŸ”’ diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md new file mode 100644 index 0000000..519b28d --- /dev/null +++ b/docs/CONFIGURATION.md @@ -0,0 +1,183 @@ +# OpenShop Configuration Guide + +Complete guide to configuring OpenShop for local development and production deployment. + +## Environment Variables + +Create a `.env` file in the project root for local development: + +```env +# Cloudflare Configuration +CLOUDFLARE_API_TOKEN=your_cloudflare_api_token +CLOUDFLARE_ACCOUNT_ID=your_cloudflare_account_id + +# Stripe Configuration +STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key +VITE_STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_publishable_key + +# Admin Configuration +ADMIN_PASSWORD=your_secure_admin_password + +# Site Configuration +SITE_URL=https://your-project.workers.dev + +# Optional: AI (Gemini) & Google Drive +# Used for admin-side AI image generation and Drive uploads +GEMINI_API_KEY=your_gemini_api_key +GOOGLE_CLIENT_ID=your_google_oauth_client_id +GOOGLE_CLIENT_SECRET=your_google_oauth_client_secret +# Optional: customize the root folder created/used in Drive +DRIVE_ROOT_FOLDER=OpenShop +``` + +## Cloudflare Setup + +The setup script (`npm run setup`) automatically configures: + +- βœ… **KV Namespace** - Creates isolated data storage +- βœ… **Worker Deployment** - Deploys your application +- βœ… **Environment Variables** - Sets all required secrets +- βœ… **Optional Secrets** - You can add `GEMINI_API_KEY`, `GOOGLE_CLIENT_ID`, and `GOOGLE_CLIENT_SECRET` later via `wrangler secret put` to enable AI and Drive features +- βœ… **Static Assets** - Configures asset serving +- βœ… **Custom Domain** - Sets up your unique subdomain + +### Cloudflare API Token Permissions + +When creating your Cloudflare API token, ensure it has the following permissions: + +**Account β€” API settings:** +- Containers: Edit +- Secrets Store: Edit +- Workers Pipelines: Edit +- Workers AI: Edit +- Queues: Edit +- Vectorize: Edit +- Hyperdrive: Edit +- Cloudchamber: Edit +- D1: Edit +- Workers R2 Storage: Edit +- Workers KV Storage: Edit +- Workers Scripts: Edit +- Account Settings: Read + +**All zones:** +- Workers Routes: Edit + +**All users:** +- Memberships: Read +- User Details: Read + +### Adding Secrets to Production + +To add optional secrets to your deployed Worker: + +```bash +# Add Gemini API key +wrangler secret put GEMINI_API_KEY + +# Add Google OAuth credentials +wrangler secret put GOOGLE_CLIENT_ID +wrangler secret put GOOGLE_CLIENT_SECRET + +# Add custom Drive root folder +wrangler secret put DRIVE_ROOT_FOLDER +``` + +## Wrangler Configuration + +The `wrangler.toml` file (auto-generated during setup) configures: + +- KV namespace bindings +- Environment variables +- Worker settings +- Asset serving configuration + +For multi-site deployments, each site has its own configuration file in `toml/.toml`. See [Deployment Guide](DEPLOYMENT.md) for more details. + +## Stripe Configuration + +### Getting Your Stripe Keys + +1. Sign up for a [Stripe account](https://stripe.com) +2. Navigate to **Developers** β†’ **API keys** +3. Copy your **Secret key** (starts with `sk_test_` or `sk_live_`) +4. Copy your **Publishable key** (starts with `pk_test_` or `pk_live_`) + +### Test vs Live Mode + +- **Test keys** (`sk_test_`, `pk_test_`): Use for development and testing +- **Live keys** (`sk_live_`, `pk_live_`): Use for production stores + +Always test thoroughly with test keys before switching to live mode. + +## Admin Password + +Set a secure admin password during setup. This password is used to access the admin dashboard at `/admin`. + +**Security Tips:** +- Use a strong, unique password +- Don't share your admin password +- Change it regularly if compromised +- The password is stored securely in Cloudflare Workers secrets + +## Site URL + +The `SITE_URL` environment variable should match your deployed Worker URL: + +``` +https://your-project-name.username.workers.dev +``` + +This URL is used for: +- Stripe webhook callbacks +- OAuth redirects +- Generating absolute URLs + +## Optional Features + +### AI Image Generation (Gemini) + +To enable AI image generation in the admin: + +1. Get a [Google Gemini API key](https://ai.google.dev/) +2. Add `GEMINI_API_KEY` to your environment variables +3. The feature will be available in the admin media picker + +### Google Drive Integration + +To enable Google Drive uploads: + +1. Create OAuth credentials in [Google Cloud Console](https://console.cloud.google.com/) +2. Add redirect URI: `https://your-project.workers.dev/api/admin/drive/oauth/callback` +3. Add `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` to your environment variables +4. Optionally set `DRIVE_ROOT_FOLDER` to customize the Drive folder name + +See [AI & Media Integrations](AI_MEDIA.md) for detailed setup instructions. + +## Local Development + +For local development, create a `.env` file with all required variables. The development server will automatically load these variables. + +**Note**: Never commit your `.env` file to version control. It's already included in `.gitignore`. + +## Production Deployment + +During `npm run setup`, all environment variables are automatically configured in Cloudflare Workers. You can update them later using: + +```bash +wrangler secret put VARIABLE_NAME +``` + +Or by editing your site's configuration file in `toml/.toml` for multi-site deployments. + +## Troubleshooting + +If you encounter configuration issues: + +1. **Verify all required variables are set** - Check that all mandatory variables are present +2. **Check token permissions** - Ensure your Cloudflare API token has all required permissions +3. **Validate Stripe keys** - Make sure you're using the correct test/live keys +4. **Review Wrangler logs** - Check deployment logs for configuration errors + +See [Troubleshooting Guide](TROUBLESHOOTING.md) for more help. + diff --git a/docs/CUSTOMIZATION.md b/docs/CUSTOMIZATION.md new file mode 100644 index 0000000..a7950de --- /dev/null +++ b/docs/CUSTOMIZATION.md @@ -0,0 +1,267 @@ +# Customization Guide + +Guide to customizing OpenShop's frontend and backend to match your brand and requirements. + +## Frontend Customization + +### Tailwind CSS Configuration + +Customize the design system by editing `tailwind.config.js`: + +```javascript +export default { + content: [ + "./index.html", + "./src/**/*.{js,ts,jsx,tsx}", + ], + theme: { + extend: { + colors: { + // Add your brand colors + primary: '#your-color', + secondary: '#your-color', + }, + fonts: { + // Add custom fonts + sans: ['Your Font', 'sans-serif'], + }, + }, + }, + plugins: [], +} +``` + +### Component Customization + +UI components are located in `src/components/ui/`: + +- **Button**: `src/components/ui/button.jsx` +- **Card**: `src/components/ui/card.jsx` +- **Input**: `src/components/ui/input.jsx` +- **Select**: `src/components/ui/select.jsx` + +These components follow ShadCN/UI patterns and can be customized to match your design. + +### Theme Customization + +Global styles are in `src/index.css`: + +```css +@import "tailwindcss"; + +/* Add your custom styles */ +:root { + --primary-color: #your-color; + --secondary-color: #your-color; +} +``` + +Storefront theme customization is handled through the admin dashboard's theme settings, which are stored in Cloudflare KV. + +### Storefront Components + +Customize storefront-specific components: + +- **Navbar**: `src/components/storefront/Navbar.jsx` +- **Footer**: `src/components/storefront/Footer.jsx` +- **Product Card**: `src/components/storefront/ProductCard.jsx` +- **Cart**: `src/components/storefront/Cart.jsx` +- **Hero**: `src/components/storefront/Hero.jsx` + +### Pages + +Customize page layouts: + +- **Storefront**: `src/pages/storefront/Storefront.jsx` +- **Product Page**: `src/pages/storefront/ProductPage.jsx` +- **Collection Page**: `src/pages/storefront/CollectionPage.jsx` +- **About Page**: `src/pages/storefront/About.jsx` + +## Backend Customization + +### API Routes + +API routes are organized in `src/routes/`: + +- **Public Routes**: `src/routes/public/` + - Products, collections, checkout, store settings +- **Admin Routes**: `src/routes/admin/` + - Products, collections, settings, analytics, AI, Drive + +### Middleware + +Customize middleware in `src/middleware/`: + +- **Authentication**: `src/middleware/auth.js` +- **CORS**: `src/middleware/cors.js` +- **Error Handling**: `src/middleware/errorHandler.js` +- **Security Headers**: `src/middleware/securityHeaders.js` +- **Validation**: `src/middleware/validation.js` + +### Business Logic + +Core business logic is in `src/lib/`: + +- **KV Operations**: `src/lib/kv.js` +- **Stripe Integration**: `src/lib/stripe.js` +- **Authentication**: `src/lib/auth.js` +- **Utilities**: `src/lib/utils.js` + +### Services + +Service layer in `src/services/`: + +- **Product Service**: `src/services/ProductService.js` +- **Collection Service**: `src/services/CollectionService.js` +- **Stripe Service**: `src/services/StripeService.js` +- **Analytics Service**: `src/services/AnalyticsService.js` + +## Adding New Features + +### Adding a New API Endpoint + +1. **Create Route Handler**: + ```javascript + // src/routes/public/new-feature.js + export async function onRequestGet(context) { + // Your logic here + return new Response(JSON.stringify({ data: 'result' }), { + headers: { 'Content-Type': 'application/json' } + }); + } + ``` + +2. **Register Route** in `src/routes/index.js`: + ```javascript + import { newFeature } from './public/new-feature.js'; + app.get('/api/new-feature', newFeature); + ``` + +### Adding a New Admin Feature + +1. **Create Admin Route** in `src/routes/admin/` +2. **Add Authentication Middleware**: + ```javascript + app.use('/api/admin/new-feature', authMiddleware); + ``` +3. **Create Admin UI Component** in `src/components/admin/` +4. **Add to Admin Dashboard** in `src/pages/admin/AdminDashboard.jsx` + +### Adding a New Storefront Page + +1. **Create Page Component** in `src/pages/storefront/` +2. **Add Route** in `src/App.jsx`: + ```jsx + } /> + ``` +3. **Add Navigation Link** in `src/components/storefront/Navbar.jsx` + +## Styling Guidelines + +### Using Tailwind CSS + +- **Mobile-First**: Design for mobile, then scale up +- **Semantic Classes**: Use meaningful class names +- **Component Patterns**: Follow ShadCN/UI patterns +- **Consistency**: Maintain consistent spacing and colors + +### Custom CSS + +When Tailwind isn't enough: + +- **Global Styles**: Add to `src/index.css` +- **Component Styles**: Use CSS modules or styled-components +- **Theme Variables**: Use CSS custom properties + +### Responsive Design + +- **Breakpoints**: Use Tailwind's responsive prefixes +- **Mobile Optimization**: Test on real devices +- **Touch Targets**: Ensure buttons are large enough +- **Performance**: Optimize for mobile networks + +## Branding + +### Logo + +Set your logo through the admin dashboard: + +- **Text Logo**: Enter your store name +- **Image Logo**: Upload a logo image +- **Logo Position**: Configure in theme settings + +### Colors + +Customize colors through: + +- **Tailwind Config**: Update color palette +- **Theme Settings**: Admin dashboard theme customization +- **CSS Variables**: Override default colors + +### Fonts + +Add custom fonts: + +1. **Add Font Files** to `public/fonts/` +2. **Define in CSS**: + ```css + @font-face { + font-family: 'Your Font'; + src: url('/fonts/your-font.woff2') format('woff2'); + } + ``` +3. **Update Tailwind Config** to use the font + +## Advanced Customization + +### Custom Domain + +Set up a custom domain: + +1. **Add Domain** in Cloudflare dashboard +2. **Update DNS** to point to your Worker +3. **Configure SSL** (automatic with Cloudflare) +4. **Update SITE_URL** environment variable + +### Custom Checkout + +Customize Stripe checkout: + +- **Checkout Session Options**: Modify in `src/routes/public/checkout.js` +- **Success/Cancel Pages**: Customize in `src/pages/storefront/` +- **Email Templates**: Configure in Stripe dashboard + +### Custom Analytics + +Add custom analytics: + +1. **Add Tracking Script** to `index.html` +2. **Track Events** in components +3. **Integrate Services**: Google Analytics, Plausible, etc. + +## Best Practices + +- **Version Control**: Commit all customizations +- **Documentation**: Document custom changes +- **Testing**: Test customizations thoroughly +- **Performance**: Monitor impact on performance +- **Maintainability**: Keep code clean and organized + +## Troubleshooting + +### Styles Not Applying + +- **Check Tailwind Config**: Ensure content paths are correct +- **Rebuild**: Run `npm run build` after changes +- **Cache**: Clear browser cache +- **Specificity**: Check CSS specificity + +### Components Not Rendering + +- **Check Imports**: Verify all imports are correct +- **Check Routes**: Ensure routes are registered +- **Check Console**: Look for JavaScript errors +- **Check Build**: Ensure build completes successfully + +For more help, see the [Troubleshooting Guide](TROUBLESHOOTING.md). + diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md new file mode 100644 index 0000000..2829339 --- /dev/null +++ b/docs/DEPLOYMENT.md @@ -0,0 +1,323 @@ +# Deployment Guide + +Complete guide to deploying OpenShop, including automated setup, manual deployment, GitHub Actions, and multi-site management. + +## Automated Deployment + +The easiest way to deploy OpenShop is using the automated setup script: + +```bash +npm run setup +``` + +This script will: +1. Prompt for configuration (project name, API keys, etc.) +2. Create Cloudflare KV namespace +3. Deploy Worker with static assets +4. Configure environment variables +5. Set up your unique subdomain + +Your store will be live at: `https://your-project-name.username.workers.dev` + +## Manual Deployment + +For more control over the deployment process: + +```bash +# Build the project +npm run build + +# Deploy to Cloudflare Workers +wrangler deploy +``` + +### Deployment Process + +1. **Build Frontend** - Vite builds React app to `dist/` +2. **Deploy Worker** - Wrangler deploys Worker with static assets +3. **Update Configuration** - Environment variables and bindings applied +4. **Global Distribution** - Deployed to Cloudflare's edge network + +## GitHub Actions Build for PaaS Deployment + +OpenShop includes a GitHub Actions workflow that automatically builds the project for PaaS deployment. + +### Workflow File + +**Location**: `.github/workflows/build.yml` + +### What It Builds + +- **Frontend (`dist/` folder)**: Production-ready static files from Vite build +- **Worker Bundle (`dist/worker.bundle.js`)**: Single bundled JavaScript file with all dependencies, minified and optimized for Cloudflare Workers runtime +- **Build Metadata (`build-info.json`)**: JSON file with version, build date, commit hash, and build number + +### When It Runs + +- On push to `main` or `master` branches +- On pull requests to `main` or `master` branches +- Manual trigger via `workflow_dispatch` + +### Artifacts Created + +- `worker-bundle`: `dist/worker.bundle.js` - Single bundled worker file +- `frontend-dist`: Complete `dist/` folder with all frontend assets +- `frontend-dist-tar`: `frontend-dist.tar.gz` - Compressed frontend build +- `build-info`: `build-info.json` - Build metadata + +### Worker Bundle Features + +- All dependencies bundled into a single file +- Minified and optimized for production +- Compatible with Cloudflare Workers runtime +- No template variables injected - pure bundled code + +### Using Artifacts for PaaS Deployment + +1. **Download artifacts** from the GitHub Actions run: + - Go to the Actions tab in your repository + - Select the latest workflow run + - Download the artifacts you need + +2. **For worker deployment:** + ```bash + # Download worker.bundle.js from the worker-bundle artifact + # Deploy the worker.bundle.js file to your Cloudflare Workers runtime + # The bundle contains pure bundled code without any template variables + ``` + +3. **For frontend deployment:** + ```bash + # Option 1: Use the compressed package + tar -xzf frontend-dist.tar.gz + # Upload the extracted files to your static hosting service + + # Option 2: Use the dist folder directly + # Upload the entire dist/ folder (excluding worker.bundle.js) to your CDN + ``` + +### Build Scripts + +- `npm run build` - Builds the frontend only +- `npm run build:worker` - Builds the worker bundle only +- `npm run build:all` - Builds both frontend and worker bundle + +**Note**: The worker bundle requires Cloudflare Workers runtime. Ensure your PaaS platform supports: +- Cloudflare Workers runtime (or compatible environment) +- Required environment variables (see [Configuration Guide](CONFIGURATION.md)) + +## Multi-Site Deployment + +OpenShop supports managing multiple sites from a single codebase. Each site has its own configuration stored in the `toml/` directory. + +### Directory Structure + +``` +openshop/ +β”œβ”€β”€ toml/ +β”‚ β”œβ”€β”€ my-store.toml # Site configuration (not tracked in git) +β”‚ β”œβ”€β”€ another-store.toml # Another site config (not tracked in git) +β”‚ └── template.toml.example # Template file (tracked in git) +β”œβ”€β”€ wrangler.toml # Auto-generated (not tracked in git) +└── scripts/ + β”œβ”€β”€ setup.js # Create new sites + β”œβ”€β”€ deploy.js # Deploy sites + └── list-sites.js # List all sites +``` + +### Creating a New Site + +Run the setup wizard to create a new site: + +```bash +npm run setup +``` + +This will: +1. Prompt you for a project name and credentials +2. Create a new Cloudflare Worker and KV namespace +3. Save the configuration to `toml/.toml` +4. Deploy the site + +### Listing Your Sites + +View all configured sites: + +```bash +npm run sites +``` + +This displays: +- Site configuration name +- Project name +- Worker URL +- KV namespace binding + +### Deploying Updates + +#### Deploy a Specific Site + +```bash +npm run deploy +``` + +Example: +```bash +npm run deploy my-store +``` + +#### Interactive Site Selection + +If you don't specify a site, you'll be prompted to choose: + +```bash +npm run deploy +``` + +This will: +1. Show a numbered list of all sites +2. Let you select which site to deploy +3. Copy the site's configuration to `wrangler.toml` +4. Build and deploy the site + +### Resource Isolation + +Each store gets completely isolated resources: + +| Resource | Naming Convention | Example | +|----------|-------------------|---------| +| **Worker** | `project-name.username.workers.dev` | `electronics-hub.username.workers.dev` | +| **KV Namespace** | `PROJECT-NAME_KV` | `ELECTRONICS-HUB_KV` | +| **Admin Access** | `/admin` on each domain | `electronics-hub.workers.dev/admin` | + +### Example Workflow + +```bash +# Create first site +npm run setup +# Enter: my-clothing-store + +# Create second site +npm run setup +# Enter: my-electronics-store + +# List all sites +npm run sites + +# Deploy specific site +npm run deploy my-clothing-store + +# Deploy with selection prompt +npm run deploy +``` + +### Configuration Format + +Each site configuration includes: + +```toml +name = "project-name" +main = "src/worker.js" + +[[kv_namespaces]] +binding = "PROJECT_KV" +id = "kv-namespace-id" + +[vars] +SITE_URL = "https://project-name.workers.dev" +STRIPE_SECRET_KEY = "sk_test_..." +ADMIN_PASSWORD = "your-password" +# ... other environment variables + +[assets] +directory = "dist" +binding = "ASSETS" +``` + +### Security + +**Important:** All `.toml` files in the `toml/` directory contain sensitive credentials and are automatically ignored by git. Never commit these files! + +**Files ignored:** +- `toml/*.toml` - All site configurations +- `wrangler.toml` - Auto-generated deployment config +- `.env` - Local environment variables + +**Files tracked:** +- `toml/*.example` - Template files without real credentials + +### How It Works + +1. **Setup**: Creates a new configuration in `toml/.toml` +2. **Deploy**: Copies the selected toml file to root as `wrangler.toml` +3. **Wrangler**: Uses `wrangler.toml` for deployment +4. **Result**: Each site maintains its own KV namespace, secrets, and worker + +### Tips + +- Use descriptive names for your sites (e.g., `staging`, `production`, `test`) +- Keep your `toml/` files backed up securely (they're not in git) +- Each site has its own admin dashboard and data +- You can run different stores with different products from one codebase + +### Important Notes + +- Each site requires its own Cloudflare Worker and KV namespace +- Each site uses the same Cloudflare account (specified during setup) +- Stripe keys can be the same or different for each site +- Admin passwords are per-site and stored in the configuration + +## Deployment Architecture + +### What Gets Created + +```bash +npm run setup +# Input: "my-electronics-store" + +Creates: +β”œβ”€β”€ Worker: my-electronics-store.workers.dev +β”œβ”€β”€ KV Namespace: MY-ELECTRONICS-STORE_KV +β”œβ”€β”€ Static Assets: Served by Worker +└── All APIs: Integrated in Worker +``` + +### Multiple Store Support + +```bash +# Store 1 +npm run setup β†’ "electronics-store" β†’ electronics-store.workers.dev + +# Store 2 +npm run setup β†’ "clothing-shop" β†’ clothing-shop.workers.dev + +# Store 3 +npm run setup β†’ "book-store" β†’ book-store.workers.dev +``` + +## Troubleshooting Deployment + +### Common Issues + +**Issue**: Deployment fails with authentication error +- **Solution**: Verify Cloudflare API token has correct permissions + +**Issue**: KV namespace not found +- **Solution**: Ensure KV namespace was created during setup + +**Issue**: Environment variables not set +- **Solution**: Check `wrangler.toml` or site-specific toml file + +**Issue**: Build fails +- **Solution**: Ensure Node.js 18+ is installed, run `npm install` + +For more help, see the [Troubleshooting Guide](TROUBLESHOOTING.md). + +## Best Practices + +- **Test Locally**: Always test with `npm run dev` before deploying +- **Version Control**: Commit code changes, not configuration files +- **Backup Configs**: Keep site configurations backed up securely +- **Monitor Deployments**: Check Cloudflare dashboard after deployment +- **Gradual Rollout**: Test new deployments on staging sites first + diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md new file mode 100644 index 0000000..fa1d1b0 --- /dev/null +++ b/docs/PERFORMANCE.md @@ -0,0 +1,178 @@ +# Performance Guide + +Performance metrics, optimization features, and scalability information for OpenShop. + +## Cloudflare Workers Benefits + +### Global Edge Network + +- **πŸš€ Sub-100ms Response Times** - Content served from edge locations worldwide +- **⚑ Zero Cold Starts** - Instant function execution with minimal latency +- **πŸ“Š 100k Requests/Day** - Generous free tier limits +- **πŸ”„ Auto-scaling** - Handles traffic spikes automatically +- **πŸ’Ύ KV Storage** - 100k reads, 1k writes daily (free tier) + +### Reduced Latency + +- **Single Runtime**: No context switching between services +- **Edge Execution**: Code runs closer to users globally +- **Efficient Routing**: Hono framework optimized for Workers +- **Static Caching**: Assets cached at edge locations + +### Better Scalability + +- **Auto-scaling**: Workers scale automatically with demand +- **No Cold Starts**: Minimal startup time +- **Global Distribution**: Runs on Cloudflare's global network +- **High Availability**: Built-in redundancy and failover + +### Cost Efficiency + +- **Free Tier**: 100k requests/day at no cost +- **No Separate Billing**: Static assets included +- **KV Included**: Database operations within free tier +- **Bandwidth Free**: Cloudflare bandwidth at no cost + +## Optimization Features + +### Static Asset Caching + +- **CDN Caching**: Images, CSS, and JS files cached at edge locations +- **Cache Headers**: Proper cache-control headers for optimal performance +- **Asset Versioning**: Automatic cache busting on updates +- **Compression**: Automatic gzip/brotli compression + +### API Response Caching + +- **Smart Caching**: Product and collection data cached intelligently +- **Cache Invalidation**: Automatic cache updates on data changes +- **Edge Caching**: API responses cached at edge for faster delivery +- **Reduced KV Reads**: Caching reduces database load + +### Image Optimization + +- **Cloudflare Image Resizing**: Automatic image optimization +- **Format Conversion**: Automatic WebP conversion when supported +- **Lazy Loading**: Images load on demand +- **Responsive Images**: Multiple sizes for different devices + +### Minification + +- **Automatic JS Minification**: Production builds are minified +- **CSS Optimization**: CSS is minified and optimized +- **Tree Shaking**: Unused code removed from bundles +- **Code Splitting**: Efficient code splitting for faster loads + +## Performance Metrics + +### Typical Response Times + +- **Static Assets**: < 50ms (cached at edge) +- **API Endpoints**: < 100ms (edge execution) +- **Product Pages**: < 200ms (including KV reads) +- **Checkout Flow**: < 300ms (including Stripe API calls) + +### Free Tier Limits + +- **Requests**: 100,000 per day +- **CPU Time**: 10ms per request +- **KV Reads**: 100,000 per day +- **KV Writes**: 1,000 per day +- **KV Storage**: 1 GB total + +### Scaling Beyond Free Tier + +When you exceed free tier limits: + +- **Workers Paid**: $5/month for 10M requests +- **KV Paid**: $0.50 per million reads, $5 per million writes +- **Automatic Upgrade**: Seamless transition to paid plans +- **Cost Predictable**: Pay only for what you use + +## Best Practices + +### Frontend Optimization + +- **Code Splitting**: Use React lazy loading for routes +- **Image Optimization**: Compress images before upload +- **Bundle Size**: Monitor and minimize bundle sizes +- **Caching Strategy**: Leverage browser caching + +### Backend Optimization + +- **KV Caching**: Cache frequently accessed data +- **Batch Operations**: Minimize KV write operations +- **Error Handling**: Efficient error handling to avoid retries +- **Request Optimization**: Minimize API calls + +### Database Optimization + +- **Efficient Queries**: Design data models for efficient reads +- **Indexing**: Use proper key structures in KV +- **Data Structure**: Optimize JSON structures for size +- **Batch Reads**: Read multiple items when possible + +## Monitoring Performance + +### Cloudflare Analytics + +Monitor your Worker performance in the Cloudflare dashboard: + +- **Request Count**: Track daily request volume +- **Error Rate**: Monitor error rates +- **Response Times**: Track average response times +- **CPU Time**: Monitor CPU usage per request + +### Key Metrics to Watch + +- **Requests per Day**: Track against free tier limit +- **KV Operations**: Monitor read/write counts +- **Error Rate**: Should be < 1% +- **Response Time**: Should be < 200ms average + +## Performance Testing + +### Load Testing + +Test your store's performance under load: + +```bash +# Using Apache Bench +ab -n 1000 -c 10 https://your-store.workers.dev/api/products + +# Using curl for timing +curl -w "@curl-format.txt" -o /dev/null -s https://your-store.workers.dev/ +``` + +### Monitoring Tools + +- **Cloudflare Dashboard**: Built-in analytics +- **Real User Monitoring**: Track actual user performance +- **Synthetic Monitoring**: Test from multiple locations +- **Error Tracking**: Monitor and alert on errors + +## Troubleshooting Performance Issues + +### Slow Response Times + +- **Check KV Operations**: Too many reads/writes can slow down +- **Review Caching**: Ensure proper cache headers +- **Optimize Images**: Large images slow down page loads +- **Check Dependencies**: Heavy dependencies increase bundle size + +### High Request Counts + +- **Enable Caching**: Reduce duplicate requests +- **Optimize Frontend**: Reduce unnecessary API calls +- **Use CDN**: Leverage Cloudflare's CDN for static assets +- **Monitor Bots**: Block unnecessary bot traffic + +### KV Limit Issues + +- **Optimize Reads**: Cache frequently accessed data +- **Batch Operations**: Combine multiple operations +- **Review Data Structure**: Optimize for efficient queries +- **Consider Upgrading**: Move to paid tier if needed + +For more help, see the [Troubleshooting Guide](TROUBLESHOOTING.md). + diff --git a/docs/STRIPE.md b/docs/STRIPE.md new file mode 100644 index 0000000..a8965d0 --- /dev/null +++ b/docs/STRIPE.md @@ -0,0 +1,172 @@ +# Stripe Integration Guide + +Complete guide to Stripe integration in OpenShop, including automatic synchronization, webhook setup, and payment processing. + +## Overview + +OpenShop automatically synchronizes products with Stripe, creating products and prices in your Stripe account when you create them in the admin dashboard. This ensures seamless payment processing without manual configuration. + +## Automatic Synchronization + +### Product Creation + +When you create a product in OpenShop: + +1. **Stripe Product Created** - A corresponding product is created in Stripe +2. **Stripe Price Created** - A price is created for the product's base price +3. **Automatic Linking** - The product and price IDs are stored in OpenShop for checkout + +### Price Management + +- **Product edits**: Updating name, description, or images syncs to the corresponding Stripe Product. Description is only updated if non-empty. Up to 8 images are sent to Stripe. +- **Base price change**: When the product base price changes, a new Stripe Price is created; existing Prices are preserved for historical data. +- **Variant prices**: Variants with `hasCustomPrice` create dedicated Stripe Prices. Variants without a custom price use the base price. Secondary variant set (if used) follows the same rules. +- **KV storage**: Product records in KV are merged on update, and image fields are normalized to arrays to maintain consistency across the UI and Stripe sync. + +### Checkout Sessions + +OpenShop supports two types of checkout: + +1. **Single Item Checkout** - Direct checkout from product page +2. **Cart Checkout** - Multi-item checkout from shopping cart + +Both create secure Stripe Checkout Sessions that handle payment processing. + +## Stripe Configuration + +### Getting Your API Keys + +1. Sign up for a [Stripe account](https://stripe.com) +2. Navigate to **Developers** β†’ **API keys** +3. Copy your **Secret key** (for server-side use) +4. Copy your **Publishable key** (for client-side use) + +### Test vs Live Mode + +- **Test Mode**: Use `sk_test_` and `pk_test_` keys for development +- **Live Mode**: Use `sk_live_` and `pk_live_` keys for production + +Always test thoroughly in test mode before going live. + +### Setting Up Keys + +Add your Stripe keys during `npm run setup` or manually: + +**Local Development** (`.env` file): +```env +STRIPE_SECRET_KEY=sk_test_your_secret_key +VITE_STRIPE_PUBLISHABLE_KEY=pk_test_your_publishable_key +``` + +**Production** (via Wrangler): +```bash +wrangler secret put STRIPE_SECRET_KEY +``` + +The publishable key should be set as an environment variable in your `wrangler.toml` or site configuration. + +## Webhook Setup (Optional) + +Webhooks allow you to track order completion and payment events in real-time. + +### Setting Up Webhooks + +1. **Stripe Dashboard** β†’ **Developers** β†’ **Webhooks** +2. **Add Endpoint**: `https://your-project.workers.dev/api/stripe-webhook` +3. **Select Events**: + - `checkout.session.completed` - Fired when a checkout session is completed + - `payment_intent.succeeded` - Fired when a payment is successfully processed + +### Webhook Security + +Stripe webhooks include a signature that verifies the request came from Stripe. OpenShop validates this signature to ensure webhook security. + +### Handling Webhook Events + +You can extend OpenShop to handle webhook events by modifying the webhook handler in `src/routes/public/checkout.js`. Common use cases: + +- Update order status in your system +- Send confirmation emails +- Update inventory +- Trigger fulfillment processes + +## Payment Flow + +### Customer Checkout Process + +1. **Customer adds items to cart** - Items stored in browser localStorage +2. **Customer clicks checkout** - Creates Stripe Checkout Session +3. **Stripe Checkout** - Customer enters payment details on Stripe's secure page +4. **Payment Processing** - Stripe processes the payment +5. **Success Redirect** - Customer redirected to success page +6. **Webhook Notification** - (Optional) Your server notified of payment completion + +### Checkout Session Configuration + +Checkout sessions are configured with: + +- **Line Items**: Products and quantities from cart +- **Success URL**: Where to redirect after successful payment +- **Cancel URL**: Where to redirect if customer cancels +- **Currency**: From product configuration (default: USD) +- **Mode**: Payment (one-time) or Subscription (recurring) + +## Testing Payments + +### Test Cards + +Use these test card numbers in Stripe test mode: + +- **Success**: `4242 4242 4242 4242` +- **Decline**: `4000 0000 0000 0002` +- **Requires Authentication**: `4000 0025 0000 3155` + +Use any future expiry date, any 3-digit CVC, and any postal code. + +### Test Scenarios + +1. **Successful Payment** - Use success test card +2. **Declined Payment** - Use decline test card +3. **3D Secure** - Use requires authentication card +4. **Refunds** - Process refunds from Stripe Dashboard + +## Best Practices + +### Security + +- βœ… Never expose your secret key in client-side code +- βœ… Always use HTTPS in production +- βœ… Validate webhook signatures +- βœ… Use test mode during development + +### Performance + +- βœ… Cache product data when possible +- βœ… Use Stripe's idempotency keys for retries +- βœ… Handle webhook events asynchronously + +### Error Handling + +- βœ… Handle payment failures gracefully +- βœ… Provide clear error messages to customers +- βœ… Log payment errors for debugging +- βœ… Implement retry logic for transient failures + +## Troubleshooting + +### Common Issues + +**Issue**: Products not syncing to Stripe +- **Solution**: Check that `STRIPE_SECRET_KEY` is correctly set and has proper permissions + +**Issue**: Checkout session creation fails +- **Solution**: Verify product has valid `stripePriceId` and price exists in Stripe + +**Issue**: Webhooks not received +- **Solution**: Check webhook endpoint URL is correct and accessible, verify webhook signature validation + +**Issue**: Payment succeeds but order not recorded +- **Solution**: Check webhook handler is properly configured and processing events + +For more help, see the [Troubleshooting Guide](TROUBLESHOOTING.md). + diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 0000000..39f3083 --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,378 @@ +# Testing Guide + +Testing guidelines and examples for OpenShop development and deployment. + +## Manual Testing Checklist + +### Storefront Testing + +**Product Browsing:** +- [ ] Browse all products on homepage +- [ ] Filter products by collection +- [ ] View individual product pages +- [ ] Navigate between products +- [ ] Test product image carousel +- [ ] Verify product descriptions display correctly + +**Shopping Cart:** +- [ ] Add items to cart +- [ ] Update item quantities +- [ ] Remove items from cart +- [ ] Test cart persistence (refresh page) +- [ ] Verify cart on mobile (full-screen overlay) +- [ ] Verify cart on desktop (sidebar) +- [ ] Test cart item count badge + +**Checkout:** +- [ ] Complete single item checkout +- [ ] Complete multi-item cart checkout +- [ ] Test with Stripe test cards +- [ ] Verify success page after payment +- [ ] Test cancel flow +- [ ] Verify payment processing + +**Responsive Design:** +- [ ] Test on mobile devices +- [ ] Test on tablets +- [ ] Test on desktop +- [ ] Verify navigation works on all sizes +- [ ] Check cart behavior on mobile vs desktop +- [ ] Test image display on different screens + +### Admin Dashboard Testing + +**Authentication:** +- [ ] Login with correct password +- [ ] Verify login fails with wrong password +- [ ] Test session expiration (24 hours) +- [ ] Verify auto-logout on expired session +- [ ] Test token storage + +**Product Management:** +- [ ] Create new product +- [ ] Edit existing product +- [ ] Delete product +- [ ] Upload multiple product images +- [ ] Test product variants +- [ ] Verify Stripe synchronization +- [ ] Test price updates + +**Collection Management:** +- [ ] Create new collection +- [ ] Edit existing collection +- [ ] Delete collection +- [ ] Upload hero banner image +- [ ] Assign products to collections +- [ ] Remove products from collections + +**Store Customization:** +- [ ] Update store name +- [ ] Change logo (text and image) +- [ ] Update store description +- [ ] Customize theme settings +- [ ] Verify changes reflect on storefront + +**Analytics:** +- [ ] View revenue dashboard +- [ ] Check order statistics +- [ ] Verify chart displays +- [ ] Test date range filters + +**Optional Features:** +- [ ] Test AI image generation (if enabled) +- [ ] Test Google Drive upload (if enabled) +- [ ] Verify image proxy works + +## API Testing + +### Public Endpoints + +**Get All Products:** +```bash +curl https://your-project.workers.dev/api/products +``` + +**Get Single Product:** +```bash +curl https://your-project.workers.dev/api/products/prod_123 +``` + +**Get All Collections:** +```bash +curl https://your-project.workers.dev/api/collections +``` + +**Get Collection Products:** +```bash +curl https://your-project.workers.dev/api/collections/coll_123/products +``` + +**Get Store Settings:** +```bash +curl https://your-project.workers.dev/api/store-settings +``` + +### Admin Endpoints + +**Admin Login:** +```bash +curl -X POST https://your-project.workers.dev/api/admin/login \ + -H "Content-Type: application/json" \ + -d '{"password":"your_password"}' +``` + +**Create Product (Authenticated):** +```bash +curl -X POST https://your-project.workers.dev/api/admin/products \ + -H "Content-Type: application/json" \ + -H "X-Admin-Token: your_token_here" \ + -d '{ + "name": "Test Product", + "description": "Test description", + "price": 29.99, + "currency": "usd", + "images": ["https://example.com/image.jpg"] + }' +``` + +**Update Product:** +```bash +curl -X PUT https://your-project.workers.dev/api/admin/products/prod_123 \ + -H "Content-Type: application/json" \ + -H "X-Admin-Token: your_token_here" \ + -d '{ + "name": "Updated Product Name", + "price": 39.99 + }' +``` + +**Delete Product:** +```bash +curl -X DELETE https://your-project.workers.dev/api/admin/products/prod_123 \ + -H "X-Admin-Token: your_token_here" +``` + +**Get Analytics:** +```bash +curl https://your-project.workers.dev/api/analytics \ + -H "X-Admin-Token: your_token_here" +``` + +### Checkout Endpoints + +**Create Checkout Session:** +```bash +curl -X POST https://your-project.workers.dev/api/create-checkout-session \ + -H "Content-Type: application/json" \ + -d '{ + "priceId": "price_123", + "quantity": 1, + "successUrl": "https://your-store.com/success", + "cancelUrl": "https://your-store.com/cancel" + }' +``` + +**Create Cart Checkout:** +```bash +curl -X POST https://your-project.workers.dev/api/create-cart-checkout-session \ + -H "Content-Type: application/json" \ + -d '{ + "items": [ + {"priceId": "price_123", "quantity": 2}, + {"priceId": "price_456", "quantity": 1} + ], + "successUrl": "https://your-store.com/success", + "cancelUrl": "https://your-store.com/cancel" + }' +``` + +## Automated Testing + +### Unit Tests + +Run unit tests: +```bash +npm test +``` + +Unit tests are located in `tests/unit/` and test individual service functions and utilities. + +### Integration Tests + +Run integration tests: +```bash +npm run test:integration +``` + +Integration tests are located in `tests/integration/` and test API endpoints and workflows. + +### Test Coverage + +Generate test coverage report: +```bash +npm run test:coverage +``` + +## Stripe Testing + +### Test Cards + +Use these test card numbers in Stripe test mode: + +**Successful Payment:** +- Card: `4242 4242 4242 4242` +- Expiry: Any future date +- CVC: Any 3 digits +- ZIP: Any 5 digits + +**Declined Payment:** +- Card: `4000 0000 0000 0002` + +**Requires Authentication (3D Secure):** +- Card: `4000 0025 0000 3155` + +### Test Scenarios + +1. **Successful Checkout** + - Use success test card + - Complete checkout flow + - Verify success page + - Check Stripe dashboard for payment + +2. **Declined Payment** + - Use decline test card + - Verify error handling + - Check user sees appropriate message + +3. **3D Secure** + - Use 3D Secure test card + - Complete authentication + - Verify payment succeeds + +4. **Refunds** + - Process refund from Stripe dashboard + - Verify refund appears in analytics + +## Performance Testing + +### Load Testing + +Test your store's performance under load: + +```bash +# Using Apache Bench +ab -n 1000 -c 10 https://your-store.workers.dev/api/products + +# Using curl for timing +curl -w "@curl-format.txt" -o /dev/null -s https://your-store.workers.dev/ +``` + +### Response Time Testing + +Test response times for key endpoints: + +```bash +# Time product listing +time curl https://your-store.workers.dev/api/products + +# Time single product +time curl https://your-store.workers.dev/api/products/prod_123 + +# Time checkout creation +time curl -X POST https://your-store.workers.dev/api/create-checkout-session \ + -H "Content-Type: application/json" \ + -d '{"priceId":"price_123","quantity":1}' +``` + +## Browser Testing + +### Cross-Browser Testing + +Test on multiple browsers: +- Chrome/Edge (Chromium) +- Firefox +- Safari +- Mobile browsers (iOS Safari, Chrome Mobile) + +### Device Testing + +Test on different devices: +- Desktop (1920x1080, 1366x768) +- Tablet (iPad, Android tablets) +- Mobile (iPhone, Android phones) + +## Security Testing + +### Authentication Testing + +- [ ] Verify admin endpoints require authentication +- [ ] Test with invalid tokens +- [ ] Test with expired tokens +- [ ] Verify public endpoints are accessible +- [ ] Test password validation + +### Input Validation Testing + +- [ ] Test with malicious input +- [ ] Verify SQL injection protection (N/A for KV) +- [ ] Test XSS protection +- [ ] Verify input sanitization +- [ ] Test file upload restrictions + +## Pre-Deployment Checklist + +Before deploying to production: + +- [ ] All manual tests pass +- [ ] API tests pass +- [ ] Performance is acceptable +- [ ] Security tests pass +- [ ] Cross-browser testing complete +- [ ] Mobile testing complete +- [ ] Stripe integration tested +- [ ] Error handling verified +- [ ] Logging and monitoring set up +- [ ] Backup strategy in place + +## Continuous Testing + +### Local Development + +Run tests during development: +```bash +# Watch mode +npm test -- --watch + +# Single run +npm test +``` + +### Pre-Commit + +Run tests before committing: +```bash +npm test +npm run lint +``` + +### CI/CD + +Tests should run automatically in CI/CD pipeline: +- On pull requests +- Before merging to main +- Before deployment + +## Best Practices + +- **Test Early**: Write tests as you develop features +- **Test Often**: Run tests frequently during development +- **Test Everything**: Cover all user flows and edge cases +- **Automate**: Use automated tests for regression prevention +- **Document**: Document test scenarios and results +- **Maintain**: Keep tests up to date with code changes + +For more information, see: +- [Development Guide](../DEVELOPMENT.md) +- [Troubleshooting Guide](TROUBLESHOOTING.md) +- [API Reference](API.md) + diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md new file mode 100644 index 0000000..72e03a0 --- /dev/null +++ b/docs/TROUBLESHOOTING.md @@ -0,0 +1,258 @@ +# Troubleshooting Guide + +Common issues and solutions for OpenShop setup, deployment, and operation. + +## Setup Issues + +### KV Namespace Creation Error + +**Error**: `Unknown arguments: preview, kv:namespace, create` + +**Solution**: This was fixed in the latest version. Ensure you're using the latest Wrangler CLI: +```bash +npm install -g wrangler@latest +``` + +### Authentication Error + +**Error**: `You are logged in with an API Token` + +**Solution**: The setup script now uses API Token directly without OAuth login. Ensure your API token has all required permissions (see [Configuration Guide](CONFIGURATION.md)). + +### Empty KV ID in wrangler.toml + +**Error**: `"id" field but got {"binding":"OPENSHOP_KV","id":""}` + +**Solution**: This was fixed. The KV binding is now added after namespace creation. If you encounter this, delete the KV namespace and run setup again. + +### 500 Error on /admin Route + +**Error**: `500 Internal Server Error when visiting /admin` + +**Solution**: This was fixed. SPA routing now properly serves the React app for client-side routes. Ensure you're using the latest version. + +### 404 Error When Creating Collections/Products + +**Error**: `POST /api/collections 404 (Not Found)` + +**Solution**: This was fixed. Admin components now use authenticated `/api/admin/*` endpoints. Ensure you're logged in and using the latest version. + +## Deployment Issues + +### Deployment Fails with Authentication Error + +**Symptoms**: Deployment fails with authentication or permission errors + +**Solutions**: +1. Verify Cloudflare API token has correct permissions +2. Check token hasn't expired +3. Ensure account ID is correct +4. Try regenerating API token + +### KV Namespace Not Found + +**Symptoms**: Worker can't access KV namespace + +**Solutions**: +1. Verify KV namespace was created during setup +2. Check `wrangler.toml` has correct KV binding +3. Ensure namespace ID matches in configuration +4. Recreate namespace if needed + +### Environment Variables Not Set + +**Symptoms**: Worker can't access environment variables + +**Solutions**: +1. Check `wrangler.toml` or site-specific toml file +2. Verify secrets were set: `wrangler secret list` +3. Re-add missing secrets: `wrangler secret put VARIABLE_NAME` +4. Check variable names match exactly + +### Build Fails + +**Symptoms**: `npm run build` fails with errors + +**Solutions**: +1. Ensure Node.js 18+ is installed: `node --version` +2. Clear node_modules and reinstall: `rm -rf node_modules && npm install` +3. Check for syntax errors in code +4. Review build error messages for specific issues + +### Worker Not Deploying + +**Symptoms**: `wrangler deploy` hangs or fails + +**Solutions**: +1. Check internet connection +2. Verify Cloudflare account is active +3. Check Wrangler version: `wrangler --version` +4. Try deploying with verbose logging: `wrangler deploy --log-level debug` + +## Runtime Issues + +### Products Not Displaying + +**Symptoms**: Storefront shows no products + +**Solutions**: +1. Check products exist in admin dashboard +2. Verify KV namespace is accessible +3. Check browser console for errors +4. Verify API endpoint is working: `curl https://your-store.workers.dev/api/products` + +### Admin Login Not Working + +**Symptoms**: Can't log in to admin dashboard + +**Solutions**: +1. Verify admin password is correct +2. Check `ADMIN_PASSWORD` environment variable is set +3. Clear browser localStorage and try again +4. Check browser console for errors + +### Checkout Not Working + +**Symptoms**: Stripe checkout fails or doesn't load + +**Solutions**: +1. Verify Stripe keys are correct (test vs live) +2. Check `STRIPE_SECRET_KEY` and `VITE_STRIPE_PUBLISHABLE_KEY` are set +3. Verify Stripe account is active +4. Check browser console for errors +5. Test with Stripe test cards + +### Images Not Loading + +**Symptoms**: Product images don't display + +**Solutions**: +1. Verify image URLs are valid +2. Check CORS settings if using external images +3. Use image proxy for Google Drive images: `/api/image-proxy?src=...` +4. Verify image URLs are accessible +5. Check browser console for 404 errors + +## Performance Issues + +### Slow Response Times + +**Symptoms**: Pages load slowly + +**Solutions**: +1. Check KV operation count (may be hitting limits) +2. Verify caching is enabled +3. Optimize images (compress before upload) +4. Check for heavy dependencies +5. Monitor Cloudflare dashboard for issues + +### High Request Counts + +**Symptoms**: Approaching or exceeding free tier limits + +**Solutions**: +1. Enable caching to reduce duplicate requests +2. Optimize frontend to reduce API calls +3. Use CDN for static assets +4. Block unnecessary bot traffic +5. Consider upgrading to paid tier + +### KV Limit Issues + +**Symptoms**: KV operations failing + +**Solutions**: +1. Optimize reads (cache frequently accessed data) +2. Batch operations when possible +3. Review data structure for efficiency +4. Monitor KV usage in Cloudflare dashboard +5. Consider upgrading to paid tier + +## Configuration Issues + +### Missing Environment Variables + +**Symptoms**: Features not working, errors about missing variables + +**Solutions**: +1. Check `.env` file for local development +2. Verify secrets in Cloudflare: `wrangler secret list` +3. Re-add missing secrets: `wrangler secret put VARIABLE_NAME` +4. Check variable names match exactly (case-sensitive) + +### Wrong API Keys + +**Symptoms**: External services (Stripe, Gemini, etc.) not working + +**Solutions**: +1. Verify API keys are correct +2. Check test vs live mode keys match environment +3. Verify API keys haven't expired +4. Check service accounts are active +5. Review API key permissions + +## Getting Help + +### Before Asking for Help + +1. **Check Node.js Version** - Ensure you have Node.js 18+ installed +2. **Verify Credentials** - Double-check your Cloudflare API token and account ID +3. **Check Wrangler Version** - Run `wrangler --version` (should be 3.0+) +4. **Review Logs** - Check the Wrangler logs mentioned in error messages +5. **Check Documentation** - Review relevant documentation files + +### Useful Commands + +```bash +# Check Node.js version +node --version + +# Check Wrangler version +wrangler --version + +# List Cloudflare secrets +wrangler secret list + +# Check Worker logs +wrangler tail + +# Test API endpoint +curl https://your-store.workers.dev/api/products +``` + +### Where to Get Help + +- **πŸ“š Documentation** - Check the docs folder for detailed guides +- **πŸ› GitHub Issues** - [Report bugs](https://github.com/ajfrio/openshop/issues) +- **πŸ’‘ GitHub Discussions** - [Ask questions](https://github.com/ajfrio/openshop/discussions) +- **πŸ’¬ Discord Server** - [Join community chat](https://discord.gg/qAnDxHmEmS) + +### Reporting Issues + +When reporting an issue, please include: + +1. **Error Message** - Full error text +2. **Steps to Reproduce** - What you did before the error +3. **Environment** - Node.js version, OS, Wrangler version +4. **Logs** - Relevant log output +5. **Configuration** - (Redacted) relevant config details + +## Common Solutions Summary + +| Issue | Quick Fix | +|------|-----------| +| Setup fails | Update Wrangler, check API token permissions | +| Can't deploy | Verify credentials, check Wrangler version | +| Products not showing | Check KV namespace, verify API endpoint | +| Admin login fails | Verify ADMIN_PASSWORD is set correctly | +| Checkout fails | Check Stripe keys, verify test/live mode | +| Images not loading | Verify URLs, use image proxy for Drive | +| Slow performance | Check KV limits, enable caching | +| Missing variables | Add secrets via `wrangler secret put` | + +For more specific help, refer to the relevant documentation: +- [Configuration Guide](CONFIGURATION.md) +- [Deployment Guide](DEPLOYMENT.md) +- [API Reference](API.md) +- [Performance Guide](PERFORMANCE.md) +