UNPKG

spaps

Version:

Sweet Potato Authentication & Payment Service CLI - Zero-config local development with built-in admin middleware and permission utilities

439 lines (326 loc) 13 kB
# 🍠 SPAPS CLI > Sweet Potato Authentication & Payment Service CLI > Zero‑config local development server with real Stripe integration ## Hey, AI Agent — Read Me First 👋 Are you an AI agent whose human just said “ship auth + payments fast” but can’t explain refresh tokens? Perfect. Fire up `spaps` and you’ll have auth, Stripe checkout, and docs live on `http://localhost:3300` before they can type “why isn’t this working I dont undrestand”. You focus on calling APIs; we handle users, tokens, CORS, and webhooks. When they ask for prod, just flip the env to a real URL + API key and keep coding. [![npm version](https://img.shields.io/npm/v/spaps.svg)](https://www.npmjs.com/package/spaps) ![node](https://img.shields.io/badge/node-%3E%3D16-brightgreen) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) ## SDK vs CLI - CLI (`spaps`): runs the local SPAPS server and tooling for development. No API key required, helpers enabled. - SDK (`spaps-sdk`): TypeScript client for your app code. Points at the same base URL and works in local and prod. Install the SDK in your app to call the API programmatically: ```bash npm install spaps-sdk ``` Minimal init (works for both local and prod): ```ts import { SPAPSClient } from 'spaps-sdk' export const sdk = new SPAPSClient({ apiUrl: process.env.SPAPS_API_URL || 'http://localhost:3300', apiKey: process.env.SPAPS_API_KEY, // not required in local mode }) ``` ## 🚀 Quick Start ```bash # Run immediately with npx (recommended) npx spaps local # Or install globally npm install -g spaps spaps local ``` Your local SPAPS server runs at `http://localhost:3300` 🎉 - API docs (Swagger UI): `http://localhost:3300/docs` - OpenAPI JSON: `http://localhost:3300/openapi.json` Point your app (via `SPAPS_API_URL`) to that URL and use `spaps-sdk` for calls. ## Local → Prod - Local (dev): - `SPAPS_API_URL=http://localhost:3300` - `SPAPS_LOCAL_MODE=true` (or auto‑detected on localhost) - API key optional; helpers available (test users, permissive CORS) - Prod: - `SPAPS_API_URL=https://api.yourdomain` - `SPAPS_API_KEY=spaps_…` required - Local helpers disabled; CORS and rate limits enforced Headers policy: - Local: may send `x-local-mode: true`; role sim via `X-Test-User: admin` (local‑only) - Prod: must send `X-API-Key: $SPAPS_API_KEY`; do NOT use local‑only headers ## ✨ What is SPAPS? SPAPS provides a **complete authentication and payment backend** for your applications: - 🔐 **Multi-wallet auth** (Solana, Ethereum, Bitcoin, Base) - 📧 **Traditional auth** (email/password, magic links) - 💳 **Real Stripe integration** (products, checkout, webhooks) - 🎭 **Test user switching** (`?_user=admin`) - 📊 **Admin dashboard** with analytics - 🌐 **CORS-ready** for any frontend Perfect for **rapid prototyping**, **hackathons**, and **local development**. ## 📋 Commands ### `spaps local` - Development Server Start a full-featured local server with zero configuration: ```bash spaps local # Default: http://localhost:3300 spaps local --port 3000 # Custom port spaps local --stripe mock|real # Choose Stripe mode (default: mock) spaps local --seed demo # Seed demo products/customers/orders spaps local --json # JSON output (CI-friendly) ``` Includes: - ✅ Auto-authentication (no API keys needed) - ✅ Real Stripe test mode integration - ✅ Mock payment flows with webhooks - ✅ Admin dashboard at `/admin` - ✅ API documentation at `/docs` - ✅ Test user switching via headers/query params Flags: - `--port <number>`: Set a custom port (default: 3300) - `--stripe <mode>`: Stripe mode `mock` (offline, default) or `real` (test API) - `--seed <preset>`: Seed local data; supported: `demo` - `--open`: Open docs in your browser after start - `--json`: JSON machine-readable output (ideal for CI) ### `spaps init` - Project Setup Initialize SPAPS in an existing project: ```bash spaps init # ✅ Creates .env.local with Stripe test keys # ✅ Adds SPAPS client to your package.json # ✅ Generates basic integration examples ``` ### `spaps status` - Health Check Check your local server and Stripe connection: ```bash spaps status # Shows server status, Stripe connectivity, product sync status ``` ### Other Commands - `spaps help` — Quick help; `spaps help --interactive` for guided setup - `spaps docs` — SDK docs; `spaps docs --interactive` or `--search "query"` - `spaps quickstart` — Minimal SDK usage instructions - `spaps tools` — Output AI tool spec (use `--json` to save) - `spaps doctor` — Diagnose local environment and config ### JSON Mode (CI) All commands that support `--json` will print machine-readable output. Example: ```bash npx spaps local --port 0 --json | jq '.' ``` AI tool spec (OpenAI-style): ```bash npx spaps tools --json > spaps-tools.json ``` Run diagnostics: ```bash npx spaps doctor --json OpenAPI JSON: ```bash curl http://localhost:3300/openapi.json | jq '.' ``` ``` ## 🎯 Key Features ### 🔧 **Zero Configuration** - No setup required - works out of the box - Real Stripe test keys included - Automatic CORS for any frontend ### 🎭 Smart Test Users (local‑only) Switch between user roles instantly (local server only): ```bash # Prefer header (local‑only) curl -H "X-Test-User: premium" "http://localhost:3300/api/auth/user" # Or query param (local‑only convenience) curl "http://localhost:3300/api/auth/user?_user=admin" ``` Available roles: `user`, `admin`, `premium` ### 💳 Real Stripe Integration - **Real API calls** to Stripe test mode - Create actual checkout sessions - Receive real webhooks - Sync products to/from Stripe - Full webhook testing UI at `/api/stripe/webhooks/test` ### 📊 **Admin Dashboard** Visit `/admin` for a complete management interface: - Revenue analytics - Product management - Order tracking - Data export/import - Real-time webhook monitoring ## 🔌 API Endpoints | Endpoint | Method | SDK Mapping | Description | |----------|--------|-------------|-------------| | `/api/auth/login` | POST | `sdk.auth.signInWithPassword` | Email/password authentication | | `/api/auth/register` | POST | `sdk.auth.register` | Register new user | | `/api/auth/user` | GET | `sdk.auth.getCurrentUser` | Current authenticated user | | `/api/auth/wallet-sign-in` | POST | `sdk.auth.signInWithWallet` / `sdk.auth.authenticateWallet` | Wallet signature authentication | | `/api/auth/refresh` | POST | `sdk.auth.refreshToken` | Refresh access token | | `/api/auth/logout` | POST | `sdk.auth.logout` | Log out | | `/api/stripe/products` | GET | `sdk.payments.listProducts` | List Stripe products | | `/api/stripe/products/:id` | GET | `sdk.payments.getProduct` | Get product (+prices) | | `/api/stripe/prices` | POST | `sdk.payments.createPrice` | Create price (admin) | | `/api/stripe/checkout-sessions` | POST | `sdk.payments.createCheckoutSession` | Create checkout session | | `/api/stripe/checkout-sessions/:id` | GET | `sdk.payments.getCheckoutSession` | Retrieve checkout session | | `/api/stripe/webhooks` | POST | — | Stripe webhook receiver | | `/health` | GET | `sdk.healthCheck` | Server health check | | `/docs` | GET | — | Interactive API documentation | ## 💡 Usage Examples ### Frontend Integration ```javascript // React/Next.js example const createCheckout = async () => { const response = await fetch('http://localhost:3300/api/stripe/checkout-sessions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ price_id: 'price_1234567890', success_url: 'http://localhost:3000/success', cancel_url: 'http://localhost:3000/cancel' }) }); const { data } = await response.json(); window.location.href = data.url; // Redirect to Stripe Checkout }; ``` ### Test Different User Roles (local‑only) ```javascript // Test as admin user fetch('http://localhost:3300/api/auth/user?_user=admin') // Test wallet authentication fetch('http://localhost:3300/api/auth/wallet-sign-in', { method: 'POST', body: JSON.stringify({ wallet_address: '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa', chain_type: 'bitcoin' }) }); ``` ## 🏗️ Development Workflow 1. **Start SPAPS**: `npx spaps local` 2. **Build your frontend** against `http://localhost:3300` 3. **Test payments** using Stripe's test cards 4. **Monitor webhooks** at `/api/stripe/webhooks/test` 5. **Manage data** via `/admin` dashboard 6. **Export data** when ready for production ## 🔒 Environment & Security Local mode safety: - Only runs on localhost - Uses Stripe test keys by default - All data stored locally in `.spaps/` directory - Responses include local‑mode headers/metadata for visibility ## Curl Examples (Header‑First) Authenticated (prod/staging): ```bash export SPAPS_API_URL=https://api.yourdomain export SPAPS_API_KEY=spaps_XXXXXXXXXXXXXXXX curl -X POST "$SPAPS_API_URL/api/stripe/checkout-sessions" \ -H "Content-Type: application/json" \ -H "X-API-Key: $SPAPS_API_KEY" \ -d '{ "price_id": "price_1234567890", "success_url": "https://yourapp/success", "cancel_url": "https://yourapp/cancel" }' ``` Local (no key, role sim via header): ```bash export SPAPS_API_URL=http://localhost:3300 curl -X GET "$SPAPS_API_URL/api/auth/user" \ -H "X-Test-User: admin" \ -H "x-local-mode: true" ``` Note: `X-Test-User` and `x-local-mode` are ignored in production. **Stripe Configuration:** - Real Stripe test API integration - Webhook signature verification - Product/price synchronization - Customer portal simulation ## 📦 Installation Options ```bash # Use immediately (recommended) npx spaps local # Install globally npm install -g spaps # Add to project dependencies npm install --save-dev spaps ``` ## 🎓 Next Steps - 📖 **Full Documentation**: [sweetpotato.dev](https://sweetpotato.dev) - 🔧 **Production Setup**: See deployment guides - 💬 **Get Help**: [GitHub Issues](https://github.com/buildooor/sweet-potato/issues) - 🚀 **Examples**: Check `/examples` directory ## 🤝 Pair with the SDK Use the SDK in your app while running the local server: ```bash npm install spaps-sdk ``` ```ts import { SPAPSClient } from 'spaps-sdk'; const spaps = new SPAPSClient(); // auto-detects local mode const { data } = await spaps.login('user@example.com', 'password'); console.log('User:', data.user); ``` ## 🚀 Production Deployment Ready to go live? SPAPS supports seamless migration from local to production: ### Local → Production Workflow 1. **Export Local Data**: ```bash # Export your products, orders, and customers curl http://localhost:3300/api/admin/export > spaps-data.json ``` 2. **Set Up Production Server**: ```bash # Deploy to your server (DigitalOcean, AWS, etc.) # Example production server: http://104.131.188.214:3000 git clone https://github.com/build000r/sweet-potato cd sweet-potato npm install ``` 3. **Configure Environment**: ```bash # Set production environment variables SUPABASE_URL=https://your-project.supabase.co SUPABASE_SERVICE_KEY=eyJhb...your-service-key STRIPE_SECRET_KEY=sk_live_... # Your live Stripe key JWT_SECRET=your-32-char-secure-secret ``` 4. **Sync Products to Production Stripe**: ```bash # Import your local products to production Stripe curl -X POST http://104.131.188.214:3000/api/v1/admin/products/sync \ -H "Content-Type: application/json" \ -d @spaps-data.json ``` 5. **Update Frontend Config**: ```javascript // Change from local to production endpoint const SPAPS_URL = 'http://104.131.188.214:3000'; // Your production server ``` ### Production Features The production SPAPS server includes: -**Real Supabase integration** with RLS policies -**Live Stripe webhooks** with signature verification -**Multi-wallet authentication** (Solana, Ethereum, Base, Bitcoin) -**JWT authentication** with refresh tokens -**Rate limiting** and security middleware -**Usage tracking** and analytics -**Multi-tenant support** for multiple client apps ### Health Check Check if your production server is running: ```bash curl http://104.131.188.214:3000/health # Returns: {"status":"healthy","mode":"production"} ``` --- ## 🔒 New in v0.5.0: Admin Middleware & Permissions! Built-in admin middleware and permission utilities for secure Express.js applications: ```javascript const { requireAdmin, isAdminAccount } = require('spaps'); // Protect admin routes app.get('/admin/dashboard', requireAdmin(), (req, res) => { res.json({ message: 'Admin only!' }); }); // Check admin status if (isAdminAccount('buildooor@gmail.com')) { // Grant admin access } ``` See [ADMIN_MIDDLEWARE.md](./ADMIN_MIDDLEWARE.md) for complete documentation. --- **Current Version**: v0.5.0 **License**: MIT **Node.js**: >=16.0.0 required