From 55335f14e74ed9a4f5efb4b095a7058ea97e1e50 Mon Sep 17 00:00:00 2001 From: Z User Date: Fri, 27 Mar 2026 21:33:56 +0000 Subject: [PATCH] Initial commit: Express backend with user management and SQLite database Features: - Express server on port 9991 with ESM syntax - User registration, login, and session management - Password hashing with bcryptjs - SQLite database with sqlite3 package - User credits and transaction tracking - API key management - Admin endpoints for user management - Stripe and PayPal webhook endpoints (ready for integration) - Rate limiting and error handling - CORS and security headers with helmet Database tables: - users (accounts, subscriptions, credits) - sessions (auth tokens) - api_keys (user API access) - credit_transactions (credit history) - payments (payment tracking) --- .env.example | 24 + .gitignore | 40 + README.md | 172 ++++ package-lock.json | 1994 ++++++++++++++++++++++++++++++++++++++++ package.json | 26 + src/db/database.js | 143 +++ src/index.js | 183 ++++ src/middleware/auth.js | 178 ++++ src/routes/users.js | 463 ++++++++++ src/routes/webhooks.js | 454 +++++++++ src/utils/helpers.js | 85 ++ 11 files changed, 3762 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 README.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 src/db/database.js create mode 100644 src/index.js create mode 100644 src/middleware/auth.js create mode 100644 src/routes/users.js create mode 100644 src/routes/webhooks.js create mode 100644 src/utils/helpers.js diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..31bfb18 --- /dev/null +++ b/.env.example @@ -0,0 +1,24 @@ +# Server Configuration +PORT=9991 +NODE_ENV=development + +# CORS +CORS_ORIGIN=* + +# Stripe Configuration (for future use) +STRIPE_SECRET_KEY=sk_test_xxx +STRIPE_WEBHOOK_SECRET=whsec_xxx +STRIPE_PUBLISHABLE_KEY=pk_test_xxx + +# PayPal Configuration (for future use) +PAYPAL_CLIENT_ID=xxx +PAYPAL_CLIENT_SECRET=xxx +PAYPAL_WEBHOOK_ID=xxx +PAYPAL_MODE=sandbox + +# JWT Secret (optional, for enhanced token security) +JWT_SECRET=your-super-secret-key-change-in-production + +# Admin User (created on first run if set) +ADMIN_EMAIL=admin@example.com +ADMIN_PASSWORD=changeme diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5b4be8f --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +# Dependencies +node_modules/ + +# Environment files +.env +.env.local +.env.production + +# Database +data/ +*.db +*.sqlite +*.sqlite3 + +# Logs +logs/ +*.log +npm-debug.log* + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Build +dist/ +build/ + +# Test coverage +coverage/ + +# Temporary files +tmp/ +temp/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..58a33ee --- /dev/null +++ b/README.md @@ -0,0 +1,172 @@ +# Moxie Backend + +Express.js backend API for user management of an AI site, built with ESM syntax and SQLite database. + +## Features + +- **User Management**: Registration, authentication, profile management +- **Credit System**: Track and manage user credits +- **API Keys**: Generate and manage API keys for programmatic access +- **Payment Webhooks**: Ready for Stripe and PayPal integration +- **Admin Endpoints**: User management for administrators +- **SQLite Database**: Lightweight, file-based storage + +## Quick Start + +```bash +# Install dependencies +npm install + +# Start the server +npm start + +# Start in development mode (with auto-reload) +npm run dev +``` + +The server runs on port 9991 by default. + +## API Endpoints + +### Public Endpoints + +| Method | Endpoint | Description | +|--------|----------|-------------| +| GET | `/api/health` | Health check | +| GET | `/api` | API information | +| POST | `/api/users/register` | Register a new user | +| POST | `/api/users/login` | Login and get session token | + +### Authenticated Endpoints + +All authenticated endpoints require `Authorization: Bearer ` header. + +| Method | Endpoint | Description | +|--------|----------|-------------| +| POST | `/api/users/logout` | Logout and invalidate session | +| GET | `/api/users/me` | Get current user profile | +| PUT | `/api/users/me` | Update profile | +| PUT | `/api/users/me/password` | Change password | +| DELETE | `/api/users/me` | Delete account | +| GET | `/api/users/credits` | Get credits and history | +| GET | `/api/users/api-keys` | List API keys | +| POST | `/api/users/api-keys` | Create new API key | +| DELETE | `/api/users/api-keys/:keyId` | Revoke API key | + +### Admin Endpoints + +Requires `role: 'admin'` in user record. + +| Method | Endpoint | Description | +|--------|----------|-------------| +| GET | `/api/users` | List all users | +| GET | `/api/users/:userId` | Get user by ID | +| PUT | `/api/users/:userId` | Update user | +| DELETE | `/api/users/:userId` | Delete user | +| POST | `/api/users/:userId/credits` | Adjust user credits | + +### Webhook Endpoints + +| Method | Endpoint | Description | +|--------|----------|-------------| +| POST | `/api/webhooks/stripe` | Stripe webhook handler | +| POST | `/api/webhooks/paypal` | PayPal webhook handler | + +## Database Schema + +### Users Table +- `id` - Primary key (UUID) +- `email` - Unique email address +- `password_hash` - Bcrypt hashed password +- `name` - Display name +- `role` - User role ('user' or 'admin') +- `credits` - Available credits +- `subscription_status` - Subscription state +- `subscription_tier` - Subscription level +- `stripe_customer_id` - Stripe customer reference +- `paypal_customer_id` - PayPal customer reference +- `is_active` - Account status flag + +### Sessions Table +- `id` - Session ID +- `user_id` - Foreign key to users +- `token_hash` - Session token +- `expires_at` - Token expiration + +### API Keys Table +- `id` - Key ID +- `user_id` - Foreign key to users +- `key_hash` - Hashed API key +- `name` - Key name/description +- `is_active` - Key status + +### Credit Transactions Table +- `id` - Transaction ID +- `user_id` - Foreign key to users +- `amount` - Credit amount (+/-) +- `type` - 'credit' or 'debit' +- `description` - Transaction description + +### Payments Table +- `id` - Payment ID +- `user_id` - Foreign key to users +- `amount` - Payment amount +- `provider` - 'stripe' or 'paypal' +- `status` - Payment status + +## Caddy Configuration + +Add this to your Caddyfile to proxy the API: + +```caddyfile +yourdomain.com { + # Static site + root * /path/to/static/site + file_server + + # API proxy + handle /api/* { + reverse_proxy localhost:9991 + } +} +``` + +## Environment Variables + +Create a `.env` file based on `.env.example`: + +```env +PORT=9991 +NODE_ENV=production +CORS_ORIGIN=https://yourdomain.com + +# Stripe (when ready) +STRIPE_SECRET_KEY=sk_live_xxx +STRIPE_WEBHOOK_SECRET=whsec_xxx + +# PayPal (when ready) +PAYPAL_CLIENT_ID=xxx +PAYPAL_CLIENT_SECRET=xxx +PAYPAL_WEBHOOK_ID=xxx +PAYPAL_MODE=live +``` + +## Payment Integration + +### Stripe Setup + +1. Create a Stripe account and get API keys +2. Add keys to environment variables +3. Create a webhook endpoint in Stripe dashboard pointing to `https://yourdomain.com/api/webhooks/stripe` +4. Copy the webhook signing secret to `STRIPE_WEBHOOK_SECRET` + +### PayPal Setup + +1. Create a PayPal Developer account +2. Create a REST API application +3. Add credentials to environment variables +4. Configure webhook in PayPal dashboard pointing to `https://yourdomain.com/api/webhooks/paypal` + +## License + +ISC diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..20a958c --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1994 @@ +{ + "name": "moxie-backend", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "moxie-backend", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "bcryptjs": "^3.0.3", + "cors": "^2.8.6", + "express": "^5.2.1", + "helmet": "^8.1.0", + "sqlite3": "^6.0.1", + "uuid": "^13.0.0" + } + }, + "node_modules/@gar/promise-retry": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@gar/promise-retry/-/promise-retry-1.0.3.tgz", + "integrity": "sha512-GmzA9ckNokPypTg10pgpeHNQe7ph+iIKKmhKu3Ob9ANkswreCx7R3cKmY781K8QK3AqVL3xVh9A42JvIAbkkSA==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@npmcli/agent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-4.0.0.tgz", + "integrity": "sha512-kAQTcEN9E8ERLVg5AsGwLNoFb+oEG6engbqAU2P43gD4JEIkNGMHdVQ096FsOAAYpZPB0RSt0zgInKIAS1l5QA==", + "license": "ISC", + "optional": true, + "dependencies": { + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^11.2.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/fs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-5.0.0.tgz", + "integrity": "sha512-7OsC1gNORBEawOa5+j2pXN9vsicaIOH5cPXxoR6fJOmH6/EXpJB2CajXOu1fPRFun2m1lktEFX11+P89hqO/og==", + "license": "ISC", + "optional": true, + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@npmcli/redact": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-4.0.0.tgz", + "integrity": "sha512-gOBg5YHMfZy+TfHArfVogwgfBeQnKbbGo3pSUyK/gSI0AVu+pEiDVcKlQb0D8Mg1LNRZILZ6XG8I5dJ4KuAd9Q==", + "license": "ISC", + "optional": true, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/abbrev": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz", + "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==", + "license": "ISC", + "optional": true, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 14" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "optional": true, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/bcryptjs": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz", + "integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==", + "license": "BSD-3-Clause", + "bin": { + "bcrypt": "bin/bcrypt" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/body-parser": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", + "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.1", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/brace-expansion": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cacache": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-20.0.4.tgz", + "integrity": "sha512-M3Lab8NPYlZU2exsL3bMVvMrMqgwCnMWfdZbK28bn3pK6APT/Te/I8hjRPNu1uwORY9a1eEQoifXbKPQMfMTOA==", + "license": "ISC", + "optional": true, + "dependencies": { + "@npmcli/fs": "^5.0.0", + "fs-minipass": "^3.0.0", + "glob": "^13.0.0", + "lru-cache": "^11.1.0", + "minipass": "^7.0.3", + "minipass-collect": "^2.0.1", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "p-map": "^7.0.2", + "ssri": "^13.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/exponential-backoff": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz", + "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==", + "license": "Apache-2.0", + "optional": true + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/fs-minipass": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz", + "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "license": "BlueOak-1.0.0", + "optional": true, + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC", + "optional": true + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/helmet": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.1.0.tgz", + "integrity": "sha512-jOiHyAZsmnr8LqoPGmCjYAaiuWwjAPLgY8ZX2XrmHawt99/u1y6RgrZMTeoPfpUbV96HOalYgz1qzkRbw54Pmg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz", + "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==", + "license": "BSD-2-Clause", + "optional": true + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/ip-address": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz", + "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz", + "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==", + "license": "BlueOak-1.0.0", + "optional": true, + "engines": { + "node": ">=20" + } + }, + "node_modules/lru-cache": { + "version": "11.2.7", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.7.tgz", + "integrity": "sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==", + "license": "BlueOak-1.0.0", + "optional": true, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/make-fetch-happen": { + "version": "15.0.5", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-15.0.5.tgz", + "integrity": "sha512-uCbIa8jWWmQZt4dSnEStkVC6gdakiinAm4PiGsywIkguF0eWMdcjDz0ECYhUolFU3pFLOev9VNPCEygydXnddg==", + "license": "ISC", + "optional": true, + "dependencies": { + "@gar/promise-retry": "^1.0.0", + "@npmcli/agent": "^4.0.0", + "@npmcli/redact": "^4.0.0", + "cacache": "^20.0.1", + "http-cache-semantics": "^4.1.1", + "minipass": "^7.0.2", + "minipass-fetch": "^5.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^1.0.0", + "proc-log": "^6.0.0", + "ssri": "^13.0.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "10.2.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz", + "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==", + "license": "BlueOak-1.0.0", + "optional": true, + "dependencies": { + "brace-expansion": "^5.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minipass-collect": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-2.0.1.tgz", + "integrity": "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minipass-fetch": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-5.0.2.tgz", + "integrity": "sha512-2d0q2a8eCi2IRg/IGubCNRJoYbA1+YPXAzQVRFmB45gdGZafyivnZ5YSEfo3JikbjGxOdntGFvBQGqaSMXlAFQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "minipass": "^7.0.3", + "minipass-sized": "^2.0.0", + "minizlib": "^3.0.1" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + }, + "optionalDependencies": { + "iconv-lite": "^0.7.2" + } + }, + "node_modules/minipass-flush": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.7.tgz", + "integrity": "sha512-TbqTz9cUwWyHS2Dy89P3ocAGUGxKjjLuR9z8w4WUTGAVgEj17/4nhgo2Du56i0Fm3Pm30g4iA8Lcqctc76jCzA==", + "license": "BlueOak-1.0.0", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minipass-flush/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-flush/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC", + "optional": true + }, + "node_modules/minipass-pipeline": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", + "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-pipeline/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-pipeline/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC", + "optional": true + }, + "node_modules/minipass-sized": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-2.0.0.tgz", + "integrity": "sha512-zSsHhto5BcUVM2m1LurnXY6M//cGhVaegT71OfOXoprxT6o780GZd792ea6FfrQkuU4usHZIUczAQMRUE2plzA==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "license": "MIT", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-abi": { + "version": "3.89.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.89.0.tgz", + "integrity": "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-addon-api": { + "version": "8.7.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.7.0.tgz", + "integrity": "sha512-9MdFxmkKaOYVTV+XVRG8ArDwwQ77XIgIPyKASB1k3JPq3M8fGQQQE3YpMOrKm6g//Ktx8ivZr8xo1Qmtqub+GA==", + "license": "MIT", + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, + "node_modules/node-gyp": { + "version": "12.2.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.2.0.tgz", + "integrity": "sha512-q23WdzrQv48KozXlr0U1v9dwO/k59NHeSzn6loGcasyf0UnSrtzs8kRxM+mfwJSf0DkX0s43hcqgnSO4/VNthQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "env-paths": "^2.2.0", + "exponential-backoff": "^3.1.1", + "graceful-fs": "^4.2.6", + "make-fetch-happen": "^15.0.0", + "nopt": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "tar": "^7.5.4", + "tinyglobby": "^0.2.12", + "which": "^6.0.0" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/nopt": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz", + "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==", + "license": "ISC", + "optional": true, + "dependencies": { + "abbrev": "^4.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/p-map": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.4.tgz", + "integrity": "sha512-tkAQEw8ysMzmkhgw8k+1U/iPhWNhykKnSk4Rd5zLoPJCuJaGRPo6YposrZgaxHKzDHdDWWZvE/Sk7hsL2X/CpQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "license": "BlueOak-1.0.0", + "optional": true, + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.0.tgz", + "integrity": "sha512-PuseHIvAnz3bjrM2rGJtSgo1zjgxapTLZ7x2pjhzWwlp4SJQgK3f3iZIQwkpEnBaKz6seKBADpM4B4ySkuYypg==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "license": "ISC", + "optional": true, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/qs": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz", + "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.7", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz", + "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==", + "license": "MIT", + "optional": true, + "dependencies": { + "ip-address": "^10.0.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/sqlite3": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/sqlite3/-/sqlite3-6.0.1.tgz", + "integrity": "sha512-X0czUUMG2tmSqJpEQa3tCuZSHKIx8PwM53vLZzKp/o6Rpy25fiVfjdbnZ988M8+O3ZWR1ih0K255VumCb3MAnQ==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "bindings": "^1.5.0", + "node-addon-api": "^8.0.0", + "prebuild-install": "^7.1.3", + "tar": "^7.5.10" + }, + "engines": { + "node": ">=20.17.0" + }, + "optionalDependencies": { + "node-gyp": "12.x" + }, + "peerDependencies": { + "node-gyp": "12.x" + }, + "peerDependenciesMeta": { + "node-gyp": { + "optional": true + } + } + }, + "node_modules/ssri": { + "version": "13.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-13.0.1.tgz", + "integrity": "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar": { + "version": "7.5.13", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.13.tgz", + "integrity": "sha512-tOG/7GyXpFevhXVh8jOPJrmtRpOTsYqUIkVdVooZYJS/z8WhfQUX8RJILmeuJNinGAMSu1veBr4asSHFt5/hng==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tar-fs": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-fs/node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/uuid": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz", + "integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist-node/bin/uuid" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", + "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", + "license": "ISC", + "optional": true, + "dependencies": { + "isexe": "^4.0.0" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..79cdbef --- /dev/null +++ b/package.json @@ -0,0 +1,26 @@ +{ + "name": "moxie-backend", + "version": "1.0.0", + "description": "", + "main": "src/index.js", + "scripts": { + "start": "node src/index.js", + "dev": "node --watch src/index.js" + }, + "repository": { + "type": "git", + "url": "https://f8e1300d871e905e27ce54c3455a3343104d9b04@git.client.guacamolebox.net/butterfly/moxie-backend.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "module", + "dependencies": { + "bcryptjs": "^3.0.3", + "cors": "^2.8.6", + "express": "^5.2.1", + "helmet": "^8.1.0", + "sqlite3": "^6.0.1", + "uuid": "^13.0.0" + } +} diff --git a/src/db/database.js b/src/db/database.js new file mode 100644 index 0000000..5b70120 --- /dev/null +++ b/src/db/database.js @@ -0,0 +1,143 @@ +import sqlite3 from 'sqlite3'; +import { fileURLToPath } from 'url'; +import { dirname, join } from 'path'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +const DB_PATH = join(__dirname, '../../data/moxie.db'); + +// Promisify sqlite3 methods +const db = new sqlite3.Database(DB_PATH, (err) => { + if (err) { + console.error('Error opening database:', err.message); + } else { + console.log('Connected to SQLite database at:', DB_PATH); + initDatabase(); + } +}); + +// Promisify database methods +const dbRun = (sql, params = []) => { + return new Promise((resolve, reject) => { + db.run(sql, params, function(err) { + if (err) reject(err); + else resolve({ id: this.lastID, changes: this.changes }); + }); + }); +}; + +const dbGet = (sql, params = []) => { + return new Promise((resolve, reject) => { + db.get(sql, params, (err, row) => { + if (err) reject(err); + else resolve(row); + }); + }); +}; + +const dbAll = (sql, params = []) => { + return new Promise((resolve, reject) => { + db.all(sql, params, (err, rows) => { + if (err) reject(err); + else resolve(rows); + }); + }); +}; + +// Initialize database tables +const initDatabase = async () => { + try { + // Users table + await dbRun(` + CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + email TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + name TEXT, + role TEXT DEFAULT 'user', + credits INTEGER DEFAULT 0, + subscription_status TEXT DEFAULT 'inactive', + subscription_tier TEXT, + stripe_customer_id TEXT, + paypal_customer_id TEXT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + last_login DATETIME, + is_active INTEGER DEFAULT 1 + ) + `); + + // API keys table for user API access + await dbRun(` + CREATE TABLE IF NOT EXISTS api_keys ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + key_hash TEXT NOT NULL, + name TEXT, + last_used DATETIME, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + is_active INTEGER DEFAULT 1, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) + `); + + // Credit transactions table + await dbRun(` + CREATE TABLE IF NOT EXISTS credit_transactions ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + amount INTEGER NOT NULL, + type TEXT NOT NULL, + description TEXT, + reference_id TEXT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) + `); + + // Payment history table + await dbRun(` + CREATE TABLE IF NOT EXISTS payments ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + amount REAL NOT NULL, + currency TEXT DEFAULT 'USD', + provider TEXT NOT NULL, + provider_payment_id TEXT, + status TEXT DEFAULT 'pending', + metadata TEXT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) + `); + + // Sessions table for user sessions + await dbRun(` + CREATE TABLE IF NOT EXISTS sessions ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + token_hash TEXT NOT NULL, + expires_at DATETIME NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) + `); + + // Create indexes for better query performance + await dbRun(`CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)`); + await dbRun(`CREATE INDEX IF NOT EXISTS idx_users_stripe_customer ON users(stripe_customer_id)`); + await dbRun(`CREATE INDEX IF NOT EXISTS idx_users_paypal_customer ON users(paypal_customer_id)`); + await dbRun(`CREATE INDEX IF NOT EXISTS idx_api_keys_user ON api_keys(user_id)`); + await dbRun(`CREATE INDEX IF NOT EXISTS idx_credit_trans_user ON credit_transactions(user_id)`); + await dbRun(`CREATE INDEX IF NOT EXISTS idx_payments_user ON payments(user_id)`); + await dbRun(`CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id)`); + + console.log('Database tables initialized successfully'); + } catch (err) { + console.error('Error initializing database:', err.message); + } +}; + +export { db, dbRun, dbGet, dbAll, initDatabase }; diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..d46a90b --- /dev/null +++ b/src/index.js @@ -0,0 +1,183 @@ +import express from 'express'; +import cors from 'cors'; +import helmet from 'helmet'; +import { fileURLToPath } from 'url'; +import { dirname, join } from 'path'; + +import usersRouter from './routes/users.js'; +import webhooksRouter from './routes/webhooks.js'; +import { ApiResponse } from './utils/helpers.js'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +const app = express(); +const PORT = process.env.PORT || 9991; + +// ============================================ +// Middleware +// ============================================ + +// Security headers +app.use(helmet({ + contentSecurityPolicy: false, // Disable for API + crossOriginEmbedderPolicy: false +})); + +// CORS configuration +app.use(cors({ + origin: process.env.CORS_ORIGIN || '*', + methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], + allowedHeaders: ['Content-Type', 'Authorization'], + credentials: true +})); + +// Body parsing +app.use(express.json({ limit: '10mb' })); +app.use(express.urlencoded({ extended: true })); + +// Request logging +app.use((req, res, next) => { + const timestamp = new Date().toISOString(); + console.log(`[${timestamp}] ${req.method} ${req.path}`); + next(); +}); + +// Trust proxy (for rate limiting behind reverse proxy) +app.set('trust proxy', 1); + +// ============================================ +// Routes +// ============================================ + +// Health check endpoint +app.get('/api/health', (req, res) => { + res.json(ApiResponse(true, { + status: 'healthy', + timestamp: new Date().toISOString(), + uptime: process.uptime() + })); +}); + +// API info endpoint +app.get('/api', (req, res) => { + res.json(ApiResponse(true, { + name: 'Moxie Backend API', + version: '1.0.0', + endpoints: { + users: { + 'POST /api/users/register': 'Register a new user', + 'POST /api/users/login': 'Login user', + 'POST /api/users/logout': 'Logout user (requires auth)', + 'GET /api/users/me': 'Get current user profile (requires auth)', + 'PUT /api/users/me': 'Update current user profile (requires auth)', + 'PUT /api/users/me/password': 'Change password (requires auth)', + 'DELETE /api/users/me': 'Delete account (requires auth)', + 'GET /api/users/credits': 'Get credits and history (requires auth)', + 'GET /api/users/api-keys': 'Get API keys (requires auth)', + 'POST /api/users/api-keys': 'Create API key (requires auth)', + 'DELETE /api/users/api-keys/:keyId': 'Revoke API key (requires auth)' + }, + admin: { + 'GET /api/users': 'List all users (admin only)', + 'GET /api/users/:userId': 'Get user by ID (admin only)', + 'PUT /api/users/:userId': 'Update user (admin only)', + 'DELETE /api/users/:userId': 'Delete user (admin only)', + 'POST /api/users/:userId/credits': 'Adjust user credits (admin only)' + }, + webhooks: { + 'POST /api/webhooks/stripe': 'Stripe webhook endpoint', + 'POST /api/webhooks/paypal': 'PayPal webhook endpoint', + 'POST /api/webhooks/create-payment': 'Create payment record (requires auth)' + } + } + })); +}); + +// Mount routers +app.use('/api/users', usersRouter); +app.use('/api/webhooks', webhooksRouter); + +// ============================================ +// Error Handling +// ============================================ + +// 404 handler +app.use((req, res) => { + res.status(404).json(ApiResponse(false, null, 'Endpoint not found')); +}); + +// Global error handler +app.use((err, req, res, next) => { + console.error('Error:', err); + + // Handle specific error types + if (err.name === 'UnauthorizedError') { + return res.status(401).json(ApiResponse(false, null, 'Invalid token')); + } + + if (err.name === 'ValidationError') { + return res.status(400).json(ApiResponse(false, null, err.message)); + } + + if (err.name === 'SyntaxError' && err.status === 400 && 'body' in err) { + return res.status(400).json(ApiResponse(false, null, 'Invalid JSON')); + } + + // SQLite errors + if (err.code === 'SQLITE_CONSTRAINT') { + return res.status(409).json(ApiResponse(false, null, 'Database constraint violation')); + } + + // Default error + res.status(err.status || 500).json(ApiResponse( + false, + process.env.NODE_ENV === 'development' ? { error: err.message, stack: err.stack } : null, + err.message || 'Internal server error' + )); +}); + +// ============================================ +// Server Startup +// ============================================ + +const server = app.listen(PORT, () => { + console.log(` +╔════════════════════════════════════════════╗ +║ Moxie Backend Server Started ║ +╠════════════════════════════════════════════╣ +║ Port: ${PORT} ║ +║ Mode: ${process.env.NODE_ENV || 'development'} ║ +║ Time: ${new Date().toISOString()} ║ +╚════════════════════════════════════════════╝ + `); +}); + +// Graceful shutdown +process.on('SIGTERM', () => { + console.log('SIGTERM received, shutting down gracefully...'); + server.close(() => { + console.log('Server closed'); + process.exit(0); + }); +}); + +process.on('SIGINT', () => { + console.log('SIGINT received, shutting down gracefully...'); + server.close(() => { + console.log('Server closed'); + process.exit(0); + }); +}); + +// Handle uncaught exceptions +process.on('uncaughtException', (err) => { + console.error('Uncaught Exception:', err); + process.exit(1); +}); + +process.on('unhandledRejection', (reason, promise) => { + console.error('Unhandled Rejection at:', promise, 'reason:', reason); +}); + +export default app; diff --git a/src/middleware/auth.js b/src/middleware/auth.js new file mode 100644 index 0000000..b0d6147 --- /dev/null +++ b/src/middleware/auth.js @@ -0,0 +1,178 @@ +import bcrypt from 'bcryptjs'; +import { dbGet } from '../db/database.js'; +import { ApiResponse } from '../utils/helpers.js'; + +const SALT_ROUNDS = 12; + +/** + * Hash a password + * @param {string} password - Plain text password + * @returns {Promise} Hashed password + */ +export const hashPassword = async (password) => { + return bcrypt.hash(password, SALT_ROUNDS); +}; + +/** + * Compare password with hash + * @param {string} password - Plain text password + * @param {string} hash - Password hash + * @returns {Promise} Passwords match + */ +export const comparePassword = async (password, hash) => { + return bcrypt.compare(password, hash); +}; + +/** + * Authentication middleware using Bearer token + * Expects Authorization: Bearer header + */ +export const authenticateToken = async (req, res, next) => { + try { + const authHeader = req.headers.authorization; + + if (!authHeader || !authHeader.startsWith('Bearer ')) { + return res.status(401).json(ApiResponse(false, null, 'Authorization token required')); + } + + const token = authHeader.split(' ')[1]; + + if (!token) { + return res.status(401).json(ApiResponse(false, null, 'Invalid token format')); + } + + // For now, we'll use a simple token validation + // In production, you'd validate JWT or check against sessions table + const session = await dbGet( + `SELECT s.*, u.id as user_id, u.email, u.name, u.role, u.credits, + u.subscription_status, u.subscription_tier, u.is_active + FROM sessions s + JOIN users u ON s.user_id = u.id + WHERE s.token_hash = ? AND s.expires_at > datetime('now')`, + [token] + ); + + if (!session) { + return res.status(401).json(ApiResponse(false, null, 'Invalid or expired token')); + } + + if (!session.is_active) { + return res.status(403).json(ApiResponse(false, null, 'Account is disabled')); + } + + // Attach user to request + req.user = { + id: session.user_id, + email: session.email, + name: session.name, + role: session.role, + credits: session.credits, + subscription_status: session.subscription_status, + subscription_tier: session.subscription_tier + }; + + req.sessionId = session.id; + next(); + } catch (error) { + console.error('Auth middleware error:', error); + return res.status(500).json(ApiResponse(false, null, 'Authentication error')); + } +}; + +/** + * Optional authentication - doesn't fail if no token + */ +export const optionalAuth = async (req, res, next) => { + try { + const authHeader = req.headers.authorization; + + if (!authHeader || !authHeader.startsWith('Bearer ')) { + req.user = null; + return next(); + } + + const token = authHeader.split(' ')[1]; + + const session = await dbGet( + `SELECT s.*, u.id as user_id, u.email, u.name, u.role, u.credits, + u.subscription_status, u.subscription_tier, u.is_active + FROM sessions s + JOIN users u ON s.user_id = u.id + WHERE s.token_hash = ? AND s.expires_at > datetime('now')`, + [token] + ); + + if (session && session.is_active) { + req.user = { + id: session.user_id, + email: session.email, + name: session.name, + role: session.role, + credits: session.credits, + subscription_status: session.subscription_status, + subscription_tier: session.subscription_tier + }; + req.sessionId = session.id; + } else { + req.user = null; + } + + next(); + } catch (error) { + console.error('Optional auth error:', error); + req.user = null; + next(); + } +}; + +/** + * Admin role check middleware + */ +export const requireAdmin = (req, res, next) => { + if (!req.user || req.user.role !== 'admin') { + return res.status(403).json(ApiResponse(false, null, 'Admin access required')); + } + next(); +}; + +/** + * Rate limiting middleware (simple in-memory implementation) + * In production, use Redis or similar + */ +const rateLimitStore = new Map(); + +export const rateLimit = (maxRequests = 100, windowMs = 60000) => { + return (req, res, next) => { + const ip = req.ip || req.connection.remoteAddress; + const now = Date.now(); + const windowStart = now - windowMs; + + // Get or create request log for IP + let requests = rateLimitStore.get(ip) || []; + + // Filter out old requests + requests = requests.filter(time => time > windowStart); + + if (requests.length >= maxRequests) { + return res.status(429).json(ApiResponse(false, null, 'Too many requests, please try again later')); + } + + requests.push(now); + rateLimitStore.set(ip, requests); + + next(); + }; +}; + +// Clean up rate limit store periodically +setInterval(() => { + const now = Date.now(); + for (const [ip, requests] of rateLimitStore.entries()) { + const filtered = requests.filter(time => time > now - 60000); + if (filtered.length === 0) { + rateLimitStore.delete(ip); + } else { + rateLimitStore.set(ip, filtered); + } + } +}, 60000); diff --git a/src/routes/users.js b/src/routes/users.js new file mode 100644 index 0000000..706fc66 --- /dev/null +++ b/src/routes/users.js @@ -0,0 +1,463 @@ +import express from 'express'; +import { dbRun, dbGet, dbAll } from '../db/database.js'; +import { hashPassword, comparePassword, authenticateToken, optionalAuth, requireAdmin } from '../middleware/auth.js'; +import { generateId, isValidEmail, sanitizeUser, getPagination, ApiResponse, asyncHandler } from '../utils/helpers.js'; + +const router = express.Router(); + +/** + * @route POST /api/users/register + * @desc Register a new user + * @access Public + */ +router.post('/register', asyncHandler(async (req, res) => { + const { email, password, name } = req.body; + + // Validation + if (!email || !password) { + return res.status(400).json(ApiResponse(false, null, 'Email and password are required')); + } + + if (!isValidEmail(email)) { + return res.status(400).json(ApiResponse(false, null, 'Invalid email format')); + } + + if (password.length < 8) { + return res.status(400).json(ApiResponse(false, null, 'Password must be at least 8 characters')); + } + + // Check if user exists + const existingUser = await dbGet('SELECT id FROM users WHERE email = ?', [email.toLowerCase()]); + if (existingUser) { + return res.status(409).json(ApiResponse(false, null, 'Email already registered')); + } + + // Create user + const userId = generateId(); + const passwordHash = await hashPassword(password); + + await dbRun( + `INSERT INTO users (id, email, password_hash, name, role, credits) + VALUES (?, ?, ?, ?, 'user', 0)`, + [userId, email.toLowerCase(), passwordHash, name || null] + ); + + const user = await dbGet('SELECT * FROM users WHERE id = ?', [userId]); + + res.status(201).json(ApiResponse(true, { user: sanitizeUser(user) }, 'User registered successfully')); +})); + +/** + * @route POST /api/users/login + * @desc Login user and return session token + * @access Public + */ +router.post('/login', asyncHandler(async (req, res) => { + const { email, password } = req.body; + + if (!email || !password) { + return res.status(400).json(ApiResponse(false, null, 'Email and password are required')); + } + + // Find user + const user = await dbGet('SELECT * FROM users WHERE email = ?', [email.toLowerCase()]); + if (!user) { + return res.status(401).json(ApiResponse(false, null, 'Invalid credentials')); + } + + if (!user.is_active) { + return res.status(403).json(ApiResponse(false, null, 'Account is disabled')); + } + + // Verify password + const isValid = await comparePassword(password, user.password_hash); + if (!isValid) { + return res.status(401).json(ApiResponse(false, null, 'Invalid credentials')); + } + + // Create session token + const sessionId = generateId(); + const token = sessionId; // In production, use JWT or a more secure token + const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(); // 7 days + + await dbRun( + `INSERT INTO sessions (id, user_id, token_hash, expires_at) + VALUES (?, ?, ?, ?)`, + [sessionId, user.id, token, expiresAt] + ); + + // Update last login + await dbRun('UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?', [user.id]); + + res.json(ApiResponse(true, { + user: sanitizeUser(user), + token, + expiresAt + }, 'Login successful')); +})); + +/** + * @route POST /api/users/logout + * @desc Logout user (invalidate session) + * @access Private + */ +router.post('/logout', authenticateToken, asyncHandler(async (req, res) => { + await dbRun('DELETE FROM sessions WHERE id = ?', [req.sessionId]); + res.json(ApiResponse(true, null, 'Logged out successfully')); +})); + +/** + * @route GET /api/users/me + * @desc Get current user profile + * @access Private + */ +router.get('/me', authenticateToken, asyncHandler(async (req, res) => { + const user = await dbGet('SELECT * FROM users WHERE id = ?', [req.user.id]); + if (!user) { + return res.status(404).json(ApiResponse(false, null, 'User not found')); + } + res.json(ApiResponse(true, { user: sanitizeUser(user) })); +})); + +/** + * @route PUT /api/users/me + * @desc Update current user profile + * @access Private + */ +router.put('/me', authenticateToken, asyncHandler(async (req, res) => { + const { name, email } = req.body; + const updates = []; + const values = []; + + if (name !== undefined) { + updates.push('name = ?'); + values.push(name); + } + + if (email !== undefined) { + if (!isValidEmail(email)) { + return res.status(400).json(ApiResponse(false, null, 'Invalid email format')); + } + const existing = await dbGet('SELECT id FROM users WHERE email = ? AND id != ?', [email.toLowerCase(), req.user.id]); + if (existing) { + return res.status(409).json(ApiResponse(false, null, 'Email already in use')); + } + updates.push('email = ?'); + values.push(email.toLowerCase()); + } + + if (updates.length === 0) { + return res.status(400).json(ApiResponse(false, null, 'No fields to update')); + } + + updates.push('updated_at = CURRENT_TIMESTAMP'); + values.push(req.user.id); + + await dbRun(`UPDATE users SET ${updates.join(', ')} WHERE id = ?`, values); + + const user = await dbGet('SELECT * FROM users WHERE id = ?', [req.user.id]); + res.json(ApiResponse(true, { user: sanitizeUser(user) }, 'Profile updated successfully')); +})); + +/** + * @route PUT /api/users/me/password + * @desc Change user password + * @access Private + */ +router.put('/me/password', authenticateToken, asyncHandler(async (req, res) => { + const { currentPassword, newPassword } = req.body; + + if (!currentPassword || !newPassword) { + return res.status(400).json(ApiResponse(false, null, 'Current and new password are required')); + } + + if (newPassword.length < 8) { + return res.status(400).json(ApiResponse(false, null, 'New password must be at least 8 characters')); + } + + const user = await dbGet('SELECT password_hash FROM users WHERE id = ?', [req.user.id]); + + const isValid = await comparePassword(currentPassword, user.password_hash); + if (!isValid) { + return res.status(401).json(ApiResponse(false, null, 'Current password is incorrect')); + } + + const passwordHash = await hashPassword(newPassword); + await dbRun('UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [passwordHash, req.user.id]); + + // Invalidate all other sessions + await dbRun('DELETE FROM sessions WHERE user_id = ? AND id != ?', [req.user.id, req.sessionId]); + + res.json(ApiResponse(true, null, 'Password changed successfully')); +})); + +/** + * @route DELETE /api/users/me + * @desc Delete user account + * @access Private + */ +router.delete('/me', authenticateToken, asyncHandler(async (req, res) => { + const { password } = req.body; + + if (!password) { + return res.status(400).json(ApiResponse(false, null, 'Password confirmation required')); + } + + const user = await dbGet('SELECT password_hash FROM users WHERE id = ?', [req.user.id]); + + const isValid = await comparePassword(password, user.password_hash); + if (!isValid) { + return res.status(401).json(ApiResponse(false, null, 'Incorrect password')); + } + + // Delete user (cascades to sessions, api_keys, etc.) + await dbRun('DELETE FROM users WHERE id = ?', [req.user.id]); + + res.json(ApiResponse(true, null, 'Account deleted successfully')); +})); + +/** + * @route GET /api/users/credits + * @desc Get user credits and transaction history + * @access Private + */ +router.get('/credits', authenticateToken, asyncHandler(async (req, res) => { + const user = await dbGet('SELECT credits FROM users WHERE id = ?', [req.user.id]); + + const { page, limit, offset } = getPagination(req.query.page, req.query.limit); + + const transactions = await dbAll( + `SELECT * FROM credit_transactions + WHERE user_id = ? + ORDER BY created_at DESC + LIMIT ? OFFSET ?`, + [req.user.id, limit, offset] + ); + + const totalResult = await dbGet( + 'SELECT COUNT(*) as count FROM credit_transactions WHERE user_id = ?', + [req.user.id] + ); + + res.json(ApiResponse(true, { + credits: user.credits, + transactions, + pagination: { + page, + limit, + total: totalResult.count, + totalPages: Math.ceil(totalResult.count / limit) + } + })); +})); + +/** + * @route GET /api/users/api-keys + * @desc Get user API keys + * @access Private + */ +router.get('/api-keys', authenticateToken, asyncHandler(async (req, res) => { + const keys = await dbAll( + `SELECT id, name, last_used, created_at, is_active + FROM api_keys + WHERE user_id = ? + ORDER BY created_at DESC`, + [req.user.id] + ); + + res.json(ApiResponse(true, { keys })); +})); + +/** + * @route POST /api/users/api-keys + * @desc Create a new API key + * @access Private + */ +router.post('/api-keys', authenticateToken, asyncHandler(async (req, res) => { + const { name } = req.body; + + const keyId = generateId(); + const keyValue = `moxie_${generateId()}_${generateId()}`; + const keyHash = await hashPassword(keyValue); + + await dbRun( + `INSERT INTO api_keys (id, user_id, key_hash, name) + VALUES (?, ?, ?, ?)`, + [keyId, req.user.id, keyHash, name || 'API Key'] + ); + + // Return the key value only once (can't be retrieved later) + res.status(201).json(ApiResponse(true, { + key: { + id: keyId, + name: name || 'API Key', + key: keyValue + } + }, 'API key created. Save this key - it cannot be retrieved again.')); +})); + +/** + * @route DELETE /api/users/api-keys/:keyId + * @desc Revoke an API key + * @access Private + */ +router.delete('/api-keys/:keyId', authenticateToken, asyncHandler(async (req, res) => { + const result = await dbRun( + 'DELETE FROM api_keys WHERE id = ? AND user_id = ?', + [req.params.keyId, req.user.id] + ); + + if (result.changes === 0) { + return res.status(404).json(ApiResponse(false, null, 'API key not found')); + } + + res.json(ApiResponse(true, null, 'API key revoked')); +})); + +// ============================================ +// Admin routes +// ============================================ + +/** + * @route GET /api/users + * @desc List all users (admin) + * @access Admin + */ +router.get('/', authenticateToken, requireAdmin, asyncHandler(async (req, res) => { + const { page, limit, offset } = getPagination(req.query.page, req.query.limit); + const search = req.query.search; + + let whereClause = ''; + let params = []; + + if (search) { + whereClause = 'WHERE email LIKE ? OR name LIKE ?'; + const searchPattern = `%${search}%`; + params = [searchPattern, searchPattern]; + } + + const users = await dbAll( + `SELECT id, email, name, role, credits, subscription_status, subscription_tier, + is_active, created_at, last_login + FROM users + ${whereClause} + ORDER BY created_at DESC + LIMIT ? OFFSET ?`, + [...params, limit, offset] + ); + + const totalResult = await dbGet(`SELECT COUNT(*) as count FROM users ${whereClause}`, params); + + res.json(ApiResponse(true, { + users, + pagination: { + page, + limit, + total: totalResult.count, + totalPages: Math.ceil(totalResult.count / limit) + } + })); +})); + +/** + * @route GET /api/users/:userId + * @desc Get user by ID (admin) + * @access Admin + */ +router.get('/:userId', authenticateToken, requireAdmin, asyncHandler(async (req, res) => { + const user = await dbGet('SELECT * FROM users WHERE id = ?', [req.params.userId]); + + if (!user) { + return res.status(404).json(ApiResponse(false, null, 'User not found')); + } + + res.json(ApiResponse(true, { user: sanitizeUser(user) })); +})); + +/** + * @route PUT /api/users/:userId + * @desc Update user by ID (admin) + * @access Admin + */ +router.put('/:userId', authenticateToken, requireAdmin, asyncHandler(async (req, res) => { + const { name, role, credits, subscription_status, subscription_tier, is_active } = req.body; + const updates = []; + const values = []; + + if (name !== undefined) { updates.push('name = ?'); values.push(name); } + if (role !== undefined) { updates.push('role = ?'); values.push(role); } + if (credits !== undefined) { updates.push('credits = ?'); values.push(credits); } + if (subscription_status !== undefined) { updates.push('subscription_status = ?'); values.push(subscription_status); } + if (subscription_tier !== undefined) { updates.push('subscription_tier = ?'); values.push(subscription_tier); } + if (is_active !== undefined) { updates.push('is_active = ?'); values.push(is_active ? 1 : 0); } + + if (updates.length === 0) { + return res.status(400).json(ApiResponse(false, null, 'No fields to update')); + } + + updates.push('updated_at = CURRENT_TIMESTAMP'); + values.push(req.params.userId); + + await dbRun(`UPDATE users SET ${updates.join(', ')} WHERE id = ?`, values); + + const user = await dbGet('SELECT * FROM users WHERE id = ?', [req.params.userId]); + res.json(ApiResponse(true, { user: sanitizeUser(user) }, 'User updated successfully')); +})); + +/** + * @route DELETE /api/users/:userId + * @desc Delete user by ID (admin) + * @access Admin + */ +router.delete('/:userId', authenticateToken, requireAdmin, asyncHandler(async (req, res) => { + const result = await dbRun('DELETE FROM users WHERE id = ?', [req.params.userId]); + + if (result.changes === 0) { + return res.status(404).json(ApiResponse(false, null, 'User not found')); + } + + res.json(ApiResponse(true, null, 'User deleted successfully')); +})); + +/** + * @route POST /api/users/:userId/credits + * @desc Add or remove credits from user (admin) + * @access Admin + */ +router.post('/:userId/credits', authenticateToken, requireAdmin, asyncHandler(async (req, res) => { + const { amount, description } = req.body; + + if (!amount || typeof amount !== 'number') { + return res.status(400).json(ApiResponse(false, null, 'Valid amount is required')); + } + + const user = await dbGet('SELECT credits FROM users WHERE id = ?', [req.params.userId]); + if (!user) { + return res.status(404).json(ApiResponse(false, null, 'User not found')); + } + + const newBalance = user.credits + amount; + if (newBalance < 0) { + return res.status(400).json(ApiResponse(false, null, 'Insufficient credits')); + } + + // Update user credits + await dbRun('UPDATE users SET credits = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [newBalance, req.params.userId]); + + // Record transaction + const transactionId = generateId(); + await dbRun( + `INSERT INTO credit_transactions (id, user_id, amount, type, description) + VALUES (?, ?, ?, ?, ?)`, + [transactionId, req.params.userId, amount, amount > 0 ? 'credit' : 'debit', description || 'Admin adjustment'] + ); + + res.json(ApiResponse(true, { + previousBalance: user.credits, + amount, + newBalance, + transactionId + }, 'Credits updated successfully')); +})); + +export default router; diff --git a/src/routes/webhooks.js b/src/routes/webhooks.js new file mode 100644 index 0000000..b750735 --- /dev/null +++ b/src/routes/webhooks.js @@ -0,0 +1,454 @@ +import express from 'express'; +import { dbRun, dbGet } from '../db/database.js'; +import { generateId, ApiResponse, asyncHandler } from '../utils/helpers.js'; + +const router = express.Router(); + +// ============================================ +// Stripe Webhook Endpoint +// ============================================ + +/** + * @route POST /api/webhooks/stripe + * @desc Handle Stripe webhook events + * @access Public (verified via signature) + * + * Stripe webhook events to handle: + * - checkout.session.completed - Payment successful + * - customer.created - New customer created + * - customer.updated - Customer updated + * - invoice.paid - Subscription payment + * - invoice.payment_failed - Payment failed + * - customer.subscription.created - New subscription + * - customer.subscription.updated - Subscription updated + * - customer.subscription.deleted - Subscription cancelled + */ +router.post('/stripe', express.raw({ type: 'application/json' }), asyncHandler(async (req, res) => { + const sig = req.headers['stripe-signature']; + const body = req.body; + + // TODO: In production, verify Stripe signature + // Example: + // const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); + // const event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET); + + // For now, parse the body as JSON + let event; + try { + event = typeof body === 'string' ? JSON.parse(body) : body; + } catch (err) { + console.error('Failed to parse webhook body:', err); + return res.status(400).json(ApiResponse(false, null, 'Invalid payload')); + } + + console.log('Stripe webhook received:', event.type); + + try { + switch (event.type) { + case 'checkout.session.completed': { + const session = event.data.object; + await handleStripeCheckoutComplete(session); + break; + } + + case 'customer.created': { + const customer = event.data.object; + await handleStripeCustomerCreated(customer); + break; + } + + case 'invoice.paid': { + const invoice = event.data.object; + await handleStripeInvoicePaid(invoice); + break; + } + + case 'invoice.payment_failed': { + const invoice = event.data.object; + await handleStripePaymentFailed(invoice); + break; + } + + case 'customer.subscription.created': + case 'customer.subscription.updated': { + const subscription = event.data.object; + await handleStripeSubscriptionUpdated(subscription); + break; + } + + case 'customer.subscription.deleted': { + const subscription = event.data.object; + await handleStripeSubscriptionDeleted(subscription); + break; + } + + default: + console.log('Unhandled Stripe event type:', event.type); + } + + res.json({ received: true }); + } catch (error) { + console.error('Error processing Stripe webhook:', error); + // Return 200 to acknowledge receipt, but log the error + res.json({ received: true, error: error.message }); + } +})); + +// Stripe event handlers +async function handleStripeCheckoutComplete(session) { + const customerId = session.customer; + const paymentIntentId = session.payment_intent; + const userId = session.client_reference_id || session.metadata?.user_id; + + if (!userId) { + console.log('No user ID in checkout session'); + return; + } + + // Update payment record + await dbRun( + `UPDATE payments SET status = 'completed', updated_at = CURRENT_TIMESTAMP + WHERE provider_payment_id = ?`, + [paymentIntentId] + ); + + // Update user's Stripe customer ID + await dbRun( + `UPDATE users SET stripe_customer_id = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, + [customerId, userId] + ); + + console.log(`Stripe checkout completed for user ${userId}`); +} + +async function handleStripeCustomerCreated(customer) { + const userId = customer.metadata?.user_id; + if (userId) { + await dbRun( + `UPDATE users SET stripe_customer_id = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, + [customer.id, userId] + ); + console.log(`Stripe customer ${customer.id} linked to user ${userId}`); + } +} + +async function handleStripeInvoicePaid(invoice) { + const customerId = invoice.customer; + const amount = invoice.amount_paid / 100; // Convert from cents + + // Find user by Stripe customer ID + const user = await dbGet('SELECT id FROM users WHERE stripe_customer_id = ?', [customerId]); + if (!user) { + console.log(`No user found for Stripe customer ${customerId}`); + return; + } + + // Add credits based on subscription or payment + const creditsToAdd = calculateCredits(amount, invoice.lines?.data); + + if (creditsToAdd > 0) { + await dbRun('UPDATE users SET credits = credits + ? WHERE id = ?', [creditsToAdd, user.id]); + + // Record transaction + await dbRun( + `INSERT INTO credit_transactions (id, user_id, amount, type, description, reference_id) + VALUES (?, ?, ?, 'credit', 'Stripe payment', ?)`, + [generateId(), user.id, creditsToAdd, invoice.id] + ); + } + + // Record payment + await dbRun( + `INSERT INTO payments (id, user_id, amount, provider, provider_payment_id, status, metadata) + VALUES (?, ?, ?, 'stripe', ?, 'completed', ?)`, + [generateId(), user.id, amount, invoice.id, JSON.stringify(invoice)] + ); + + console.log(`Stripe invoice paid: ${amount} for user ${user.id}`); +} + +async function handleStripePaymentFailed(invoice) { + const customerId = invoice.customer; + + const user = await dbGet('SELECT id FROM users WHERE stripe_customer_id = ?', [customerId]); + if (user) { + await dbRun( + `UPDATE users SET subscription_status = 'past_due', updated_at = CURRENT_TIMESTAMP WHERE id = ?`, + [user.id] + ); + + // Record failed payment + await dbRun( + `INSERT INTO payments (id, user_id, amount, provider, provider_payment_id, status, metadata) + VALUES (?, ?, ?, 'stripe', ?, 'failed', ?)`, + [generateId(), user.id, invoice.amount_due / 100, invoice.id, JSON.stringify(invoice)] + ); + } +} + +async function handleStripeSubscriptionUpdated(subscription) { + const customerId = subscription.customer; + + const user = await dbGet('SELECT id FROM users WHERE stripe_customer_id = ?', [customerId]); + if (user) { + const status = mapStripeSubscriptionStatus(subscription.status); + const tier = subscription.metadata?.tier || subscription.items?.data?.[0]?.price?.nickname || 'standard'; + + await dbRun( + `UPDATE users SET subscription_status = ?, subscription_tier = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, + [status, tier, user.id] + ); + } +} + +async function handleStripeSubscriptionDeleted(subscription) { + const customerId = subscription.customer; + + const user = await dbGet('SELECT id FROM users WHERE stripe_customer_id = ?', [customerId]); + if (user) { + await dbRun( + `UPDATE users SET subscription_status = 'cancelled', subscription_tier = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, + [user.id] + ); + } +} + +// ============================================ +// PayPal Webhook Endpoint +// ============================================ + +/** + * @route POST /api/webhooks/paypal + * @desc Handle PayPal webhook events + * @access Public (verified via signature) + * + * PayPal webhook events to handle: + * - CHECKOUT.ORDER.APPROVED - Order approved + * - PAYMENT.CAPTURE.COMPLETED - Payment captured + * - PAYMENT.CAPTURE.DENIED - Payment denied + * - BILLING.SUBSCRIPTION.CREATED - Subscription created + * - BILLING.SUBSCRIPTION.ACTIVATED - Subscription activated + * - BILLING.SUBSCRIPTION.CANCELLED - Subscription cancelled + * - BILLING.SUBSCRIPTION.SUSPENDED - Subscription suspended + */ +router.post('/paypal', express.json(), asyncHandler(async (req, res) => { + const event = req.body; + + // TODO: In production, verify PayPal webhook signature + // See: https://developer.paypal.com/api/rest/webhooks/rest/#verify-webhook-signature + + console.log('PayPal webhook received:', event.event_type); + + try { + switch (event.event_type) { + case 'CHECKOUT.ORDER.APPROVED': { + await handlePaypalOrderApproved(event.resource); + break; + } + + case 'PAYMENT.CAPTURE.COMPLETED': { + await handlePaypalPaymentCompleted(event.resource); + break; + } + + case 'PAYMENT.CAPTURE.DENIED': { + await handlePaypalPaymentDenied(event.resource); + break; + } + + case 'BILLING.SUBSCRIPTION.ACTIVATED': { + await handlePaypalSubscriptionActivated(event.resource); + break; + } + + case 'BILLING.SUBSCRIPTION.CANCELLED': { + await handlePaypalSubscriptionCancelled(event.resource); + break; + } + + case 'BILLING.SUBSCRIPTION.SUSPENDED': { + await handlePaypalSubscriptionSuspended(event.resource); + break; + } + + default: + console.log('Unhandled PayPal event type:', event.event_type); + } + + res.json({ received: true }); + } catch (error) { + console.error('Error processing PayPal webhook:', error); + res.json({ received: true, error: error.message }); + } +})); + +// PayPal event handlers +async function handlePaypalOrderApproved(resource) { + const orderId = resource.id; + const userId = resource.purchase_units?.[0]?.custom_id || resource.metadata?.user_id; + + console.log(`PayPal order ${orderId} approved for user ${userId}`); + // Order will be captured on the frontend or via API call +} + +async function handlePaypalPaymentCompleted(resource) { + const captureId = resource.id; + const amount = parseFloat(resource.amount?.value || 0); + const customId = resource.custom_id || resource.supplementary_data?.related_ids?.order_id; + + // Find payment record + const payment = await dbGet('SELECT user_id FROM payments WHERE provider_payment_id = ?', [captureId]); + + let userId = payment?.user_id; + + // Try to find user by custom_id if no payment record + if (!userId && customId) { + const user = await dbGet('SELECT id FROM users WHERE id = ?', [customId]); + if (user) userId = user.id; + } + + if (!userId) { + console.log('No user ID found for PayPal payment'); + return; + } + + // Update payment status + await dbRun( + `UPDATE payments SET status = 'completed', updated_at = CURRENT_TIMESTAMP + WHERE provider_payment_id = ?`, + [captureId] + ); + + // Add credits + const creditsToAdd = calculateCredits(amount); + if (creditsToAdd > 0) { + await dbRun('UPDATE users SET credits = credits + ? WHERE id = ?', [creditsToAdd, userId]); + + await dbRun( + `INSERT INTO credit_transactions (id, user_id, amount, type, description, reference_id) + VALUES (?, ?, ?, 'credit', 'PayPal payment', ?)`, + [generateId(), userId, creditsToAdd, captureId] + ); + } + + console.log(`PayPal payment completed: ${amount} for user ${userId}`); +} + +async function handlePaypalPaymentDenied(resource) { + const captureId = resource.id; + + await dbRun( + `UPDATE payments SET status = 'failed', updated_at = CURRENT_TIMESTAMP + WHERE provider_payment_id = ?`, + [captureId] + ); + + console.log(`PayPal payment denied: ${captureId}`); +} + +async function handlePaypalSubscriptionActivated(resource) { + const subscriptionId = resource.id; + const customerId = resource.subscriber?.payer_id; + + // Update or create user subscription + const user = await dbGet('SELECT id FROM users WHERE paypal_customer_id = ?', [customerId]); + if (user) { + await dbRun( + `UPDATE users SET subscription_status = 'active', subscription_tier = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, + [resource.plan_id || 'standard', user.id] + ); + } + + console.log(`PayPal subscription activated: ${subscriptionId}`); +} + +async function handlePaypalSubscriptionCancelled(resource) { + const subscriptionId = resource.id; + const customerId = resource.subscriber?.payer_id; + + const user = await dbGet('SELECT id FROM users WHERE paypal_customer_id = ?', [customerId]); + if (user) { + await dbRun( + `UPDATE users SET subscription_status = 'cancelled', subscription_tier = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, + [user.id] + ); + } + + console.log(`PayPal subscription cancelled: ${subscriptionId}`); +} + +async function handlePaypalSubscriptionSuspended(resource) { + const subscriptionId = resource.id; + const customerId = resource.subscriber?.payer_id; + + const user = await dbGet('SELECT id FROM users WHERE paypal_customer_id = ?', [customerId]); + if (user) { + await dbRun( + `UPDATE users SET subscription_status = 'suspended', updated_at = CURRENT_TIMESTAMP WHERE id = ?`, + [user.id] + ); + } + + console.log(`PayPal subscription suspended: ${subscriptionId}`); +} + +// ============================================ +// Helper functions +// ============================================ + +function calculateCredits(amount, lineItems) { + // Implement your credit calculation logic here + // Example: $1 = 100 credits + const baseCredits = Math.floor(amount * 100); + + // Check for bonus credits based on subscription tier + if (lineItems) { + // Add bonus for subscriptions + } + + return baseCredits; +} + +function mapStripeSubscriptionStatus(status) { + const statusMap = { + 'active': 'active', + 'past_due': 'past_due', + 'canceled': 'cancelled', + 'unpaid': 'unpaid', + 'trialing': 'trialing', + 'incomplete': 'incomplete', + 'incomplete_expired': 'expired', + 'paused': 'paused' + }; + return statusMap[status] || status; +} + +// ============================================ +// Payment initialization endpoints +// ============================================ + +/** + * @route POST /api/webhooks/create-payment + * @desc Create a payment record for tracking + * @access Private + */ +router.post('/create-payment', asyncHandler(async (req, res) => { + // This would typically be called from your frontend before initiating payment + const { userId, amount, provider, metadata } = req.body; + + if (!userId || !amount || !provider) { + return res.status(400).json(ApiResponse(false, null, 'userId, amount, and provider are required')); + } + + const paymentId = generateId(); + + await dbRun( + `INSERT INTO payments (id, user_id, amount, provider, status, metadata) + VALUES (?, ?, ?, ?, 'pending', ?)`, + [paymentId, userId, amount, provider, JSON.stringify(metadata || {})] + ); + + res.status(201).json(ApiResponse(true, { paymentId }, 'Payment record created')); +})); + +export default router; diff --git a/src/utils/helpers.js b/src/utils/helpers.js new file mode 100644 index 0000000..08c4cd9 --- /dev/null +++ b/src/utils/helpers.js @@ -0,0 +1,85 @@ +import { v4 as uuidv4 } from 'uuid'; + +/** + * Generate a unique ID + * @returns {string} UUID v4 + */ +export const generateId = () => uuidv4(); + +/** + * Generate a random token + * @param {number} length - Token length + * @returns {string} Random token + */ +export const generateToken = (length = 32) => { + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + let token = ''; + for (let i = 0; i < length; i++) { + token += chars.charAt(Math.floor(Math.random() * chars.length)); + } + return token; +}; + +/** + * Validate email format + * @param {string} email - Email to validate + * @returns {boolean} Is valid email + */ +export const isValidEmail = (email) => { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + return emailRegex.test(email); +}; + +/** + * Sanitize user object (remove sensitive fields) + * @param {Object} user - User object + * @returns {Object} Sanitized user object + */ +export const sanitizeUser = (user) => { + if (!user) return null; + const { password_hash, ...safeUser } = user; + return safeUser; +}; + +/** + * Calculate pagination + * @param {number} page - Current page + * @param {number} limit - Items per page + * @returns {Object} Pagination object + */ +export const getPagination = (page = 1, limit = 10) => { + const offset = (page - 1) * limit; + return { offset, limit: parseInt(limit), page: parseInt(page) }; +}; + +/** + * Format date to ISO string + * @param {Date|string} date - Date to format + * @returns {string} ISO date string + */ +export const formatDate = (date) => { + return new Date(date).toISOString(); +}; + +/** + * Async handler wrapper for Express routes + * @param {Function} fn - Async function to wrap + * @returns {Function} Express middleware + */ +export const asyncHandler = (fn) => (req, res, next) => { + Promise.resolve(fn(req, res, next)).catch(next); +}; + +/** + * Create a standardized API response + * @param {boolean} success - Success status + * @param {*} data - Response data + * @param {string} message - Response message + * @returns {Object} API response object + */ +export const ApiResponse = (success, data = null, message = null) => { + const response = { success }; + if (data !== null) response.data = data; + if (message) response.message = message; + return response; +};