managarten/services/mana-core-auth
Till-JS 20db01628a fix(auth): remove conflicting JSON body parser middleware
The manual bodyParser.json() middleware conflicts with NestJS rawBody mode.
When rawBody: true is enabled, NestJS consumes the body stream first, then
the manual parser tries to read it again causing "stream is not readable".

NestJS handles JSON parsing internally, so the manual middleware was redundant
and causing 500 errors on login requests.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-16 14:30:06 +01:00
..
docs 📝 docs(auth): update organization endpoint documentation 2026-02-16 12:57:29 +01:00
postgres/init first auth impl 2025-12-01 13:30:58 +01:00
scripts 🔧 chore(auth): improve migration safety and docker setup 2025-12-19 02:18:31 +01:00
src fix(auth): remove conflicting JSON body parser middleware 2026-02-16 14:30:06 +01:00
test 🐛 fix(matrix-mana-bot): resolve QEMU emulation failure in CI 2026-02-01 13:59:04 +01:00
.dockerignore 🐛 fix(mana-core-auth): use EdDSA for OIDC id_token signing 2026-02-01 13:24:55 +01:00
.env.example feat(auth): enable cross-domain SSO via shared cookies on .mana.how 2026-02-02 03:58:29 +01:00
.gitignore 📈 feat(monitoring): upgrade to VictoriaMetrics + DuckDB analytics 2026-01-28 12:38:04 +01:00
auth.ts test(auth): update tests for minimal JWT claims architecture 2025-12-01 15:21:19 +01:00
CLAUDE.md docs(auth): add SSO documentation and test credentials 2026-02-02 04:09:07 +01:00
docker-entrypoint.sh 🔧 fix(auth): skip migrations in Docker entrypoint 2025-12-02 14:41:34 +01:00
Dockerfile 🩹 fix(auth): correct healthcheck endpoint path 2026-02-13 23:48:45 +01:00
drizzle.config.ts feat(auth): add gift codes and enhanced credit system 2026-02-13 23:29:30 +01:00
eslint.config.mjs improve code quality 2025-12-03 23:42:37 +01:00
jest.config.js test: implement comprehensive automated testing system with daily CI/CD 2025-12-25 19:12:27 +01:00
MIGRATIONS.md fix(ci): build shared packages before tests and fix formatting 2025-12-01 23:15:00 +01:00
nest-cli.json style: auto-format codebase with Prettier 2025-11-27 18:33:16 +01:00
package.json feat(auth): add avatar upload with S3/MinIO and subscription plans seed 2026-02-13 23:06:24 +01:00
pnpm-lock.yaml refactor: restructure 2025-11-26 03:03:24 +01:00
QUICKSTART.md 📝 docs(credits): update documentation for simplified credit system 2026-02-16 12:03:35 +01:00
README.md 📝 docs(credits): update documentation for simplified credit system 2026-02-16 12:03:35 +01:00
tsconfig.json style: auto-format codebase with Prettier 2025-11-27 18:33:16 +01:00

Mana Core Auth

Central authentication and credit management system for the Mana Universe ecosystem.

Features

  • JWT-based Authentication (EdDSA algorithm via Better Auth)

    • User registration and login
    • Refresh token rotation
    • Multi-session management
    • JWKS endpoint for token verification
  • Credit System

    • User balance management
    • Transaction ledger (purchase, usage, refund, gift)
    • Optimistic locking for concurrency
    • Idempotency for credit operations
    • Gift code system with auto-redemption on registration
  • Security

    • Row-Level Security (RLS) on PostgreSQL
    • Rate limiting
    • CORS protection
    • Helmet security headers
    • SCRAM-SHA-256 password authentication
  • Infrastructure

    • Docker-based deployment
    • Traefik reverse proxy with automatic SSL
    • PgBouncer connection pooling
    • Redis caching
    • Prometheus + Grafana monitoring

Quick Start

Development Setup

  1. Install dependencies

    pnpm install
    
  2. Generate JWT keys

    cd mana-core-auth
    ./scripts/generate-keys.sh
    
  3. Set up environment variables

    cp .env.example .env
    # Edit .env and add your JWT keys and other configuration
    
  4. Start PostgreSQL and Redis (using Docker)

    docker-compose up postgres redis -d
    
  5. Run migrations

    pnpm migration:generate
    pnpm migration:run
    
  6. Start development server

    pnpm start:dev
    

    The server will be available at http://localhost:3001/api/v1

Production Deployment (Docker)

  1. Set up environment variables

    cp .env.example .env
    # Edit .env with production values
    
  2. Generate JWT keys

    ./mana-core-auth/scripts/generate-keys.sh
    # Add the generated keys to .env
    
  3. Start all services

    docker-compose up -d
    
  4. Check service health

    docker-compose ps
    docker-compose logs -f mana-core-auth
    

API Endpoints

Authentication

POST /api/v1/auth/register

  • Register a new user
  • Body: { email, password, name? }
  • Returns: User object

POST /api/v1/auth/login

  • Login with email and password
  • Body: { email, password, deviceId?, deviceName? }
  • Returns: { user, accessToken, refreshToken, expiresIn, tokenType }

POST /api/v1/auth/refresh

  • Refresh access token
  • Body: { refreshToken }
  • Returns: New token pair

POST /api/v1/auth/logout

  • Logout and revoke session
  • Requires: Bearer token
  • Returns: Success message

POST /api/v1/auth/validate

  • Validate a JWT token
  • Body: { token }
  • Returns: { valid, payload }

Credits

GET /api/v1/credits/balance

  • Get current credit balance
  • Requires: Bearer token
  • Returns: { balance, totalEarned, totalSpent }

POST /api/v1/credits/use

  • Deduct credits from balance
  • Requires: Bearer token
  • Body: { amount, appId, description, idempotencyKey?, metadata? }
  • Returns: Transaction details

GET /api/v1/credits/transactions?limit=50&offset=0

  • Get transaction history
  • Requires: Bearer token
  • Returns: Array of transactions

GET /api/v1/credits/purchases

  • Get purchase history
  • Requires: Bearer token
  • Returns: Array of purchases

GET /api/v1/credits/packages

  • Get available credit packages
  • Requires: Bearer token
  • Returns: Array of packages

Database Schema

Auth Schema

  • auth.users - User accounts
  • auth.sessions - Active sessions
  • auth.passwords - Hashed passwords
  • auth.accounts - OAuth provider accounts
  • auth.verification_tokens - Email verification & password reset
  • auth.two_factor_auth - 2FA configuration
  • auth.security_events - Security audit log

Credits Schema

  • credits.balances - User credit balances
  • credits.transactions - Transaction ledger
  • credits.packages - Available credit packages
  • credits.purchases - Purchase history
  • credits.usage_stats - Usage analytics

Environment Variables

See .env.example for all available configuration options.

Key variables:

  • DATABASE_URL - PostgreSQL connection string
  • REDIS_HOST, REDIS_PORT, REDIS_PASSWORD - Redis configuration
  • STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET - Stripe integration
  • CORS_ORIGINS - Allowed origins for CORS
  • BASE_URL - Base URL for JWKS endpoint (e.g., http://localhost:3001)

Development

Available Scripts

# Start development server with hot-reload
pnpm start:dev

# Build for production
pnpm build

# Start production server
pnpm start:prod

# Run tests
pnpm test

# Generate database migration
pnpm migration:generate

# Run migrations
pnpm migration:run

# Open Drizzle Studio (database GUI)
pnpm db:studio

# Lint and format
pnpm lint
pnpm format

Architecture

Token Flow

  1. User registers/logs in → Receives accessToken (15min) + refreshToken (7 days)
  2. Client stores tokens securely (httpOnly cookies on web, SecureStore on mobile)
  3. Client includes Authorization: Bearer <accessToken> in requests
  4. When access token expires, client uses refresh token to get new pair
  5. Refresh tokens are single-use (rotation for security)

Credit System

  • Paid Credits: Purchased via Stripe (100 mana = €1)
  • Gift Codes: Can be created and redeemed, auto-redeem on registration if pending
  • Transaction Types: purchase, usage, refund, gift
  • Idempotency: Duplicate requests with same key are detected and ignored
  • Concurrency: Optimistic locking prevents race conditions

Security Considerations

  1. JWT Keys: Better Auth auto-generates EdDSA keys stored in auth.jwks table
  2. Database: Use strong passwords and enable SSL in production
  3. Redis: Always set a password for Redis
  4. CORS: Only allow trusted origins
  5. Rate Limiting: Configured via Traefik and NestJS throttler
  6. RLS Policies: Enforce data isolation at database level
  7. HTTPS: Always use SSL/TLS in production (via Traefik)

Monitoring

  • Prometheus: Available at http://localhost:9090
  • Grafana: Available at http://localhost:3000
  • Logs: docker-compose logs -f mana-core-auth

License

Private - Mana Universe

Support

For issues and questions, contact the development team.