Compare commits

...

7 Commits

Author SHA1 Message Date
GW_MC
e033d67ec1 feat: Implement knowledge import feature for characters
- Added KnowledgeImport page for importing character knowledge from URLs.
- Integrated URL validation and error handling for unsupported websites.
- Created API endpoints for importing content from URLs and retrieving character knowledge.
- Enhanced VectorStoreService with logging and error handling for vector memory storage.
- Updated frontend to display knowledge sources and manage them effectively.
- Added support for fetching recent character knowledge as a fallback in similarity searches.
- Updated OpenAPI documentation to reflect new import functionality.
2026-02-24 14:29:26 +00:00
GW_MC
8714d6bd22 Phase 1 complete 2026-02-24 10:34:55 +00:00
GW_MC
630b60d7e2 chore: update Dockerfile to set PNPM_HOME and PATH for environment configuration 2026-02-23 22:15:02 +08:00
GW_MC
3456fa5461 chore: add pnpm setup command to Dockerfile for environment configuration 2026-02-23 22:13:53 +08:00
GW_MC
be93b5f3e9 chore: update Dockerfile to set pnpm store directory and remove environment variables 2026-02-23 22:11:03 +08:00
GW_MC
6b1a0136b0 feat: add initial backend and frontend structure with models, DTOs, and WebSocket events 2026-02-23 21:04:50 +08:00
GW_MC
932f384f0d chore: add pnpm workspace configuration for apps and packages 2026-02-23 21:04:19 +08:00
164 changed files with 22442 additions and 203 deletions

21
.devcontainer/Dockerfile Normal file
View File

@@ -0,0 +1,21 @@
FROM mcr.microsoft.com/devcontainers/typescript-node:24
# Install additional tools
RUN apt-get update && apt-get install -y \
postgresql-client \
redis-tools \
&& rm -rf /var/lib/apt/lists/*
# Set up pnpm environment
RUN pnpm config set store-dir /home/node/.local/share/pnpm/store
ENV PNPM_HOME=/home/node/.local/share/pnpm
ENV PATH=$PNPM_HOME:$PATH
USER node
# Set working directory
WORKDIR /workspace
# Install global packages
RUN pnpm install -g @nestjs/cli@latest

View File

@@ -0,0 +1,46 @@
{
"name": "DreamChat Development",
"dockerComposeFile": "docker-compose.yml",
"service": "app",
"workspaceFolder": "/workspace",
"features": {
"ghcr.io/devcontainers/features/node:1": {
"version": "24"
},
"ghcr.io/devcontainers/features/docker-in-docker:2": {
"moby": false
},
"ghcr.io/jsburckhardt/devcontainer-features/just": {}
},
"customizations": {
"vscode": {
"extensions": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode", "bradlc.vscode-tailwindcss", "prisma.prisma"],
"settings": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"typescript.preferences.importModuleSpecifier": "relative"
}
}
},
"forwardPorts": [3000, 5173, 5432],
"portsAttributes": {
"3000": {
"label": "Backend API",
"onAutoForward": "notify"
},
"5173": {
"label": "Frontend Dev Server",
"onAutoForward": "notify"
},
"5432": {
"label": "PostgreSQL",
"onAutoForward": "silent"
}
},
"postStartCommand": "bash .devcontainer/post-start.sh",
"remoteUser": "node",
"mounts": [
"source=${localWorkspaceFolderBasename}-node_modules,target=${containerWorkspaceFolder}/node_modules,type=volume",
"source=${localWorkspaceFolderBasename}-pnpm-store,target=/home/node/.local/share/pnpm/store,type=volume"
]
}

View File

@@ -0,0 +1,47 @@
services:
app:
build:
context: ..
dockerfile: .devcontainer/Dockerfile
volumes:
- ..:/workspace:cached
- /var/run/docker.sock:/var/run/docker.sock
command: sleep infinity
environment:
- DATABASE_URL=postgresql://postgres:postgres@db:5432/dreamchat
- REDIS_URL=redis://redis:6379
# Keycloak is external - configure KEYCLOAK_URL in apps/backend/.env
depends_on:
- db
- redis
networks:
- dreamchat-network
db:
image: ankane/pgvector:latest
restart: unless-stopped
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: dreamchat
volumes:
- postgres-data:/var/lib/postgresql/data
ports:
- "5432:5432"
networks:
- dreamchat-network
redis:
image: redis:7-alpine
restart: unless-stopped
ports:
- "6379:6379"
networks:
- dreamchat-network
volumes:
postgres-data:
networks:
dreamchat-network:
driver: bridge

View File

@@ -0,0 +1,76 @@
#!/bin/bash
set -e
echo "🚀 Setting up DreamChat monorepo development environment..."
# Install all dependencies (uses pnpm workspaces)
echo "📦 Installing dependencies..."
cd /workspace
pnpm install
# Build shared packages first
echo "📦 Building shared packages..."
pnpm --filter @dreamchat/shared build || echo "Shared package build skipped (may not exist yet)"
# Generate Prisma client
echo "🔧 Generating Prisma client..."
cd /workspace/apps/backend
pnpm db:generate || echo "Prisma generate skipped (may not be set up yet)"
cd -
# Copy environment files if they don't exist
if [ ! -f /workspace/apps/backend/.env ]; then
echo "⚙️ Creating backend .env file..."
mkdir -p /workspace/apps/backend
cat > /workspace/apps/backend/.env << EOF
NODE_ENV=development
PORT=3000
DATABASE_URL=postgresql://postgres:postgres@db:5432/dreamchat
JWT_SECRET=dev-jwt-secret-change-in-production
JWT_EXPIRES_IN=1h
JWT_REFRESH_EXPIRES_IN=7d
LLM_PROVIDER=openrouter
LLM_API_KEY=your-openrouter-api-key
LLM_MODEL=openai/gpt-4o
# Keycloak (external) - configure if using external Keycloak
KEYCLOAK_ENABLED=false
# KEYCLOAK_URL=http://your-keycloak-server:8080
# KEYCLOAK_REALM=dreamchat
# KEYCLOAK_CLIENT_ID=dreamchat-backend
# KEYCLOAK_CLIENT_SECRET=your_keycloak_secret
# Keycloak Authorization (optional)
# KEYCLOAK_REQUIRED_GROUP=dreamchat-users
# KEYCLOAK_REQUIRED_ROLE=dreamchat-access
# KEYCLOAK_REQUIRED_CLIENT_ROLE=user
# KEYCLOAK_REQUIRED_ATTRIBUTE=approved:true
# Keycloak Auto-Create Users
KEYCLOAK_AUTO_CREATE_USER=true
KEYCLOAK_DEFAULT_USER_ROLE=USER
EOF
fi
if [ ! -f /workspace/apps/frontend/.env ]; then
echo "⚙️ Creating frontend .env file..."
mkdir -p /workspace/apps/frontend
cat > /workspace/apps/frontend/.env << EOF
VITE_API_URL=http://localhost:3000/api
VITE_WS_URL=ws://localhost:3000
# Keycloak (external) - configure if using external Keycloak
# VITE_KEYCLOAK_URL=http://your-keycloak-server:8080
# VITE_KEYCLOAK_REALM=dreamchat
# VITE_KEYCLOAK_CLIENT_ID=dreamchat-frontend
EOF
fi
echo "✅ Development environment setup complete!"
echo ""
echo "Next steps:"
echo "1. Start all apps: pnpm dev"
echo "2. Or start individually:"
echo " - Backend: pnpm --filter @dreamchat/backend dev"
echo " - Frontend: pnpm --filter @dreamchat/frontend dev"
echo ""
echo "Note: Keycloak is external. Configure KEYCLOAK_URL in apps/backend/.env if needed."

2
.dockerignore Normal file
View File

@@ -0,0 +1,2 @@
node_modules/
.pnpm-store/

80
.env.example Normal file
View File

@@ -0,0 +1,80 @@
# Database
POSTGRES_PASSWORD=your_secure_password_here
# JWT
JWT_SECRET=your_jwt_secret_key_min_32_chars
JWT_EXPIRES_IN=1h
JWT_REFRESH_EXPIRES_IN=7d
# Frontend URL (for OAuth redirects)
FRONTEND_URL=http://localhost:5173
# LLM Configuration
LLM_PROVIDER=openrouter
LLM_API_KEY=sk-or-v1-...
LLM_MODEL=openai/gpt-4o
# Embedding Configuration (Local HuggingFace by default)
EMBEDDING_PROVIDER=local
EMBEDDING_MODEL=Xenova/all-MiniLM-L6-v2
EMBEDDING_DIMENSION=384
EMBEDDING_DEVICE=cpu
# Use quantized model for lower memory usage (~4x smaller, slightly less accurate)
# Set to 'true' for low-memory systems (512MB-1GB RAM)
EMBEDDING_QUANTIZED=false
# Node.js Memory Configuration (increase if embedding causes OOM)
# For 512MB RAM VPS: NODE_OPTIONS=--max-old-space-size=384
# For 1GB RAM VPS: NODE_OPTIONS=--max-old-space-size=768
# For 2GB RAM VPS: NODE_OPTIONS=--max-old-space-size=1536
# Default (no env var): Node uses ~4GB or system limit
#NODE_OPTIONS=--max-old-space-size=768
# Request Logging Configuration
# Enable/disable request logging (default: true)
#REQUEST_LOGGER=true
# Log level: verbose (detailed), standard (default), minimal (status only)
#REQUEST_LOGGER_LEVEL=standard
# HuggingFace API (optional - if not using local embeddings)
# HUGGINGFACE_API_KEY=hf_...
# Keycloak (External) Configuration
# Enable Keycloak authentication
KEYCLOAK_ENABLED=false
KEYCLOAK_URL=http://your-keycloak-server:8080
KEYCLOAK_REALM=dreamchat
KEYCLOAK_CLIENT_ID=dreamchat-backend
KEYCLOAK_CLIENT_SECRET=your_keycloak_secret
# Keycloak OAuth redirect URI (must match Keycloak client configuration)
KEYCLOAK_REDIRECT_URI=http://localhost:3000/api/auth/keycloak/callback
# Keycloak Authorization Settings
# Require specific group/role/attribute for access
# Set at least one of these to enforce authorization checks
# Required Keycloak group (e.g., "dreamchat-users")
KEYCLOAK_REQUIRED_GROUP=
# Required Keycloak realm role (e.g., "dreamchat-access")
KEYCLOAK_REQUIRED_ROLE=
# Required Keycloak client role (e.g., "user")
KEYCLOAK_REQUIRED_CLIENT_ROLE=
# Required Keycloak user attribute (format: "attribute_name:attribute_value")
# Examples:
# KEYCLOAK_REQUIRED_ATTRIBUTE=department:engineering
# KEYCLOAK_REQUIRED_ATTRIBUTE=approved:true
KEYCLOAK_REQUIRED_ATTRIBUTE=
# Auto-create users on first Keycloak login
# If true, users will be automatically created in the database
# If false, only existing users can log in via Keycloak
KEYCLOAK_AUTO_CREATE_USER=true
# Default role for auto-created Keycloak users
KEYCLOAK_DEFAULT_USER_ROLE=USER

51
.gitignore vendored Normal file
View File

@@ -0,0 +1,51 @@
# Dependencies
node_modules/
.pnp
.pnp.js
.pnpm-store/
# Build outputs
dist/
build/
*.tsbuildinfo
# Environment files
.env
.env.local
.env.*.local
# Logs
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Testing
coverage/
.nyc_output/
# Prisma
prisma/migrations/*/migration_lock.toml
# Misc
.cache/
temp/
tmp/
*.tgz
# DevContainer
.devcontainer/.pnpm-store/

3
.npmrc Normal file
View File

@@ -0,0 +1,3 @@
shamefully-hoist=true
auto-install-peers=true
strict-peer-dependencies=false

232
README.md
View File

@@ -1,24 +1,230 @@
# DreamChat # DreamChat
## Overview A character simulation and interactive storytelling platform with AI-powered conversations.
This project is designed to simulate characters, enable interactive conversations with them, and generate stories based on user-provided templates and backgrounds. The platform focuses on creating immersive, personalized fan-like experiences where users can interact with their favorite simulated personas. ## Features
## Core Features - **Character Simulation**: Create custom characters with personalities, attributes, and backstories
- **Interactive Dialogue**: Real-time chat with AI characters using WebSocket streaming
- **Story Generation**: Branching narratives with tree-view visualization
- **Vector Memory**: Context-aware conversations using local embeddings
- **Data Import**: Import character data from files (TXT, PDF, MD) or web sources
- **Multi-Character Chat**: Group conversations with multiple characters (Phase 3)
- Character Simulation: Users can define and customize characters with attributes, personalities, and backstories. ## Tech Stack
- Interactive Dialogue: The main focus is enabling users to talk directly to their simulated characters, using chat data provided by the user.
- Story Generation: The system generates narratives based on user-defined templates, backgrounds, and character interactions.
- User Data Import: Users can import their own chat histories, blogs, or other text data to enrich character simulation and personalize interactions.
## Key Requirements - **Backend**: NestJS + TypeScript + Prisma + PostgreSQL (pgvector)
- **Frontend**: React + Vite + TypeScript + Tailwind CSS
- **Package Manager**: pnpm workspaces (monorepo)
- **AI/LLM**: OpenRouter with flexible provider support
- **Embeddings**: Local HuggingFace models (@xenova/transformers)
- **Auth**: Password-based (with optional external Keycloak SSO supporting group/role/attribute authorization)
- **DevOps**: Docker + DevContainer (external reverse proxy expected)
User-Centric Design: Prioritize ease of use, intuitive character creation, and natural conversational flow. ## Quick Start
## Target Audience ### Using DevContainer (Recommended)
- Storytellers and roleplayers seeking immersive character-driven narratives. 1. Open project in VS Code
2. Install [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers)
3. Press `F1` → "Dev Containers: Reopen in Container"
4. Wait for setup to complete
5. Start development:
```bash
pnpm dev
```
## Goals ### Manual Setup
Deliver a platform where users can define, interact, and narrate with their characters. Prerequisites:
- Node.js 20+
- pnpm 8+
- PostgreSQL 15+ with pgvector extension
- Redis (optional)
1. Install dependencies:
```bash
pnpm install
```
2. Build shared packages:
```bash
pnpm --filter @dreamchat/shared build
```
3. Setup database:
```bash
pnpm db:generate
pnpm db:migrate
pnpm db:seed
```
4. Create environment files:
```bash
cp .env.example apps/backend/.env
cp .env.example apps/frontend/.env
# Edit both files with your configuration
```
5. Start development:
```bash
pnpm dev
```
## Project Structure
```
dreamchat/
├── apps/
│ ├── backend/ # NestJS API
│ └── frontend/ # React + Vite SPA
├── packages/
│ └── shared/ # Shared types & WebSocket definitions
├── prisma/
│ ├── schema.prisma # Main schema (imports from models/)
│ ├── seed.ts # Seed data
│ └── models/ # Individual model files
│ ├── user.prisma
│ ├── character.prisma
│ └── ...
├── .devcontainer/ # DevContainer configuration
├── docker-compose.yml # Production Docker Compose
└── doc/ # Project documentation
```
## Documentation
See the `doc/` folder for comprehensive documentation:
- [architecture.md](doc/architecture.md) - System architecture and design
- [monorepo-guide.md](doc/monorepo-guide.md) - pnpm workspace setup
- [database-schema.md](doc/database-schema.md) - Database schema (Prisma)
- [api-spec.md](doc/api-spec.md) - REST API & WebSocket specifications
- [implementation-plan.md](doc/implementation-plan.md) - Phased roadmap
- [frontend-guide.md](doc/frontend-guide.md) - Frontend architecture
- [deployment.md](doc/deployment.md) - Deployment guide
## Development Commands
```bash
# Install dependencies
pnpm install
# Start all apps in development mode
pnpm dev
# Build all packages
pnpm build
# Run tests
pnpm test
# Database commands
pnpm db:generate # Generate Prisma client
pnpm db:migrate # Run migrations
pnpm db:studio # Open Prisma Studio
pnpm db:seed # Seed database
# Lint
pnpm lint
# Clean
pnpm clean
```
## Environment Variables
### Backend (`apps/backend/.env`)
```bash
NODE_ENV=development
PORT=3000
DATABASE_URL=postgresql://postgres:postgres@db:5432/dreamchat
JWT_SECRET=your-secret-key
LLM_PROVIDER=openrouter
LLM_API_KEY=your-api-key
LLM_MODEL=openai/gpt-4o
EMBEDDING_PROVIDER=local
EMBEDDING_MODEL=Xenova/all-MiniLM-L6-v2
# Keycloak (optional)
KEYCLOAK_ENABLED=false
KEYCLOAK_URL=http://your-keycloak-server:8080
KEYCLOAK_REALM=dreamchat
KEYCLOAK_CLIENT_ID=dreamchat-backend
KEYCLOAK_CLIENT_SECRET=your-secret
# Keycloak Authorization (optional)
KEYCLOAK_REQUIRED_GROUP=dreamchat-users
KEYCLOAK_REQUIRED_ROLE=dreamchat-access
KEYCLOAK_AUTO_CREATE_USER=true
```
### Frontend (`apps/frontend/.env`)
```bash
VITE_API_URL=http://localhost:3000/api
VITE_WS_URL=ws://localhost:3000
```
## Deployment
See [deployment.md](doc/deployment.md) for production deployment instructions.
Quick deployment with Docker:
```bash
# Copy and edit environment file
cp .env.example .env
# Build and start services
docker-compose up -d --build
# Run migrations
docker-compose exec backend pnpm db:migrate
```
**Note:** An external reverse proxy (nginx, Traefik, etc.) is expected for SSL termination and routing. See [deployment.md](doc/deployment.md) for configuration examples.
## Troubleshooting
### Memory Issues (JavaScript heap out of memory)
The local embedding model uses TensorFlow.js which can consume significant memory. If you encounter OOM errors:
1. **Increase Node.js memory limit:**
```bash
# In apps/backend/.env
NODE_OPTIONS=--max-old-space-size=768
# Or when starting manually
node --max-old-space-size=768 dist/main
```
2. **Use low-memory mode (for 512MB RAM VPS):**
```bash
cd apps/backend
pnpm run start:low-memory
```
3. **Use quantized model (4x smaller memory):**
```bash
# In apps/backend/.env
EMBEDDING_QUANTIZED=true
```
4. **Limit import size:** The system automatically:
- Limits content to ~30KB per import
- Limits to 30 chunks maximum
- Processes chunks sequentially with delays
- Adds GC pauses between chunks
### System Requirements
- **Minimum:** 512MB RAM (with low-memory configuration)
- **Recommended:** 1GB+ RAM for comfortable operation
- **Import processing:** Large imports may take longer on low-memory systems
## License
MIT

57
apps/backend/Dockerfile Normal file
View File

@@ -0,0 +1,57 @@
# apps/backend/Dockerfile
FROM node:24-alpine AS base
RUN npm install -g pnpm@8
FROM base AS dependencies
WORKDIR /app
# Copy workspace configuration
COPY pnpm-workspace.yaml package.json ./
COPY apps/backend/package.json ./apps/backend/
COPY packages/shared/package.json ./packages/shared/
# Install dependencies
RUN pnpm install --frozen-lockfile
FROM base AS build
WORKDIR /app
COPY --from=dependencies /app/node_modules ./node_modules
COPY --from=dependencies /app/apps/backend/node_modules ./apps/backend/node_modules
COPY --from=dependencies /app/packages/shared/node_modules ./packages/shared/node_modules
# Copy source code
COPY packages/shared ./packages/shared
COPY apps/backend ./apps/backend
COPY prisma ./prisma
# Build shared packages first
RUN pnpm --filter @dreamchat/shared build
# Generate Prisma client
RUN pnpm db:generate
# Build backend
RUN pnpm --filter @dreamchat/backend build
FROM base AS production
WORKDIR /app
# Copy only production dependencies
COPY --from=dependencies /app/node_modules ./node_modules
COPY --from=dependencies /app/apps/backend/node_modules ./apps/backend/node_modules
COPY --from=build /app/apps/backend/dist ./dist
COPY --from=build /app/packages/shared/dist ./node_modules/@dreamchat/shared/dist
COPY --from=build /app/node_modules/.pnpm/@prisma+client* ./node_modules/.pnpm/
COPY --from=build /app/node_modules/@prisma ./node_modules/@prisma
# Create logs directory
RUN mkdir -p /app/logs
# Non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nodejs -u 1001
USER nodejs
EXPOSE 3000
CMD ["node", "dist/main.js"]

View File

@@ -0,0 +1,42 @@
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './src/app.module';
import * as fs from 'fs';
import * as path from 'path';
async function generateOpenApi() {
// Create app without starting the server
const app = await NestFactory.create(AppModule, {
logger: false, // Suppress logs during generation
});
app.setGlobalPrefix('api');
const config = new DocumentBuilder()
.setTitle('DreamChat API')
.setDescription('The DreamChat API documentation')
.setVersion('1.0.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
// Ensure the output directory exists
const outputDir = path.join(__dirname, '..', '..', 'openapi');
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Write the spec file
const outputPath = path.join(outputDir, 'openapi.json');
fs.writeFileSync(outputPath, JSON.stringify(document, null, 2));
console.log(`📄 OpenAPI spec written to: ${outputPath}`);
await app.close();
process.exit(0);
}
generateOpenApi().catch((err) => {
console.error('Failed to generate OpenAPI spec:', err);
process.exit(1);
});

View File

@@ -0,0 +1,14 @@
module.exports = {
moduleFileExtensions: ['js', 'json', 'ts'],
rootDir: 'src',
testRegex: '.*\\.spec\\.ts$',
transform: {
'^.+\\.(t|j)s$': 'ts-jest',
},
collectCoverageFrom: ['**/*.(t|j)s'],
coverageDirectory: '../coverage',
testEnvironment: 'node',
moduleNameMapper: {
'^@dreamchat/shared$': '<rootDir>/../../packages/shared/dist',
},
};

62
apps/backend/package.json Normal file
View File

@@ -0,0 +1,62 @@
{
"name": "@dreamchat/backend",
"version": "1.0.0",
"scripts": {
"build": "nest build",
"dev": "nest start --watch",
"start": "node --max-old-space-size=768 dist/main",
"start:low-memory": "node --max-old-space-size=384 dist/main",
"start:high-memory": "node --max-old-space-size=1536 dist/main",
"test": "jest",
"test:watch": "jest --watch",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\"",
"db:migrate": "prisma migrate deploy",
"db:generate": "prisma generate",
"db:seed": "prisma db seed",
"openapi:generate": "node dist/generate-openapi.js",
"clean": "rm -r dist"
},
"dependencies": {
"@dreamchat/shared": "workspace:*",
"@nestjs/common": "^11.1.14",
"@nestjs/core": "^11.1.14",
"@nestjs/jwt": "^11.0.0",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.1.14",
"@nestjs/platform-socket.io": "^11.1.14",
"@nestjs/swagger": "^11.0.0",
"@nestjs/websockets": "^11.1.14",
"@prisma/adapter-pg": "^7.4.1",
"@prisma/client": "^7.4.1",
"@types/keycloak-connect": "^7.0.0",
"@xenova/transformers": "^2.15.0",
"bcrypt": "^6.0.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"dotenv": "^17.3.1",
"jsonwebtoken": "^9.0.0",
"keycloak-connect": "^26.1.1",
"passport": "^0.7.0",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"puppeteer": "^24.37.5",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.0",
"socket.io": "^4.7.0"
},
"devDependencies": {
"@nestjs/cli": "^11.0.16",
"@nestjs/testing": "^11.1.14",
"@types/bcrypt": "^6.0.0",
"@types/jest": "^30.0.0",
"@types/jsonwebtoken": "^9.0.0",
"@types/multer": "^1.4.12",
"@types/node": "^24.10.13",
"@types/passport-jwt": "^4.0.0",
"@types/passport-local": "^1.0.0",
"jest": "^30.2.0",
"prisma": "^7.4.1",
"ts-jest": "^29.4.6",
"typescript": "^5.3.0"
}
}

View File

@@ -0,0 +1,13 @@
import { defineConfig, env } from 'prisma/config';
import 'dotenv/config';
export default defineConfig({
schema: 'prisma/',
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
datasource: {
url: env('DATABASE_URL'),
},
});

View File

@@ -0,0 +1,267 @@
-- Enable pgvector extension
CREATE EXTENSION IF NOT EXISTS vector;
-- CreateEnum
CREATE TYPE "ImportSourceType" AS ENUM ('file', 'url', 'manual');
-- CreateEnum
CREATE TYPE "ImportStatus" AS ENUM ('pending', 'processing', 'completed', 'failed');
-- CreateEnum
CREATE TYPE "MessageRole" AS ENUM ('user', 'assistant', 'system');
-- CreateEnum
CREATE TYPE "UserRole" AS ENUM ('USER', 'ADMIN');
-- CreateEnum
CREATE TYPE "MemoryType" AS ENUM ('conversation', 'character');
-- CreateTable
CREATE TABLE "Character" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"avatarUrl" TEXT,
"personalityPrompt" TEXT NOT NULL,
"attributes" JSONB NOT NULL DEFAULT '{}',
"config" JSONB NOT NULL DEFAULT '{}',
"isPublic" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"userId" TEXT NOT NULL,
CONSTRAINT "Character_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CharacterKnowledge" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"sourceType" "ImportSourceType" NOT NULL,
"sourceName" TEXT NOT NULL,
"mimeType" TEXT,
"fileSize" BIGINT,
"rawContent" TEXT,
"status" "ImportStatus" NOT NULL DEFAULT 'pending',
"processingInfo" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"characterId" TEXT NOT NULL,
CONSTRAINT "CharacterKnowledge_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Conversation" (
"id" TEXT NOT NULL,
"title" TEXT,
"messageCount" INTEGER NOT NULL DEFAULT 0,
"totalTokens" INTEGER NOT NULL DEFAULT 0,
"settings" JSONB NOT NULL DEFAULT '{}',
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"userId" TEXT NOT NULL,
"characterId" TEXT NOT NULL,
CONSTRAINT "Conversation_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ConversationParticipant" (
"id" TEXT NOT NULL,
"isActive" BOOLEAN NOT NULL DEFAULT true,
"autoRespond" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"conversationId" TEXT NOT NULL,
"characterId" TEXT NOT NULL,
CONSTRAINT "ConversationParticipant_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ImportDocument" (
"id" TEXT NOT NULL,
"sourceType" "ImportSourceType" NOT NULL,
"sourceName" TEXT NOT NULL,
"mimeType" TEXT,
"fileSize" BIGINT,
"content" TEXT,
"status" "ImportStatus" NOT NULL DEFAULT 'pending',
"errorMessage" TEXT,
"metadata" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"userId" TEXT NOT NULL,
CONSTRAINT "ImportDocument_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Message" (
"id" TEXT NOT NULL,
"role" "MessageRole" NOT NULL,
"content" TEXT NOT NULL,
"tokensUsed" INTEGER,
"model" TEXT,
"metadata" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"conversationId" TEXT NOT NULL,
CONSTRAINT "Message_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "StoryBranch" (
"id" TEXT NOT NULL,
"title" TEXT,
"content" TEXT NOT NULL,
"userDirection" TEXT NOT NULL,
"generationParams" JSONB,
"depth" INTEGER NOT NULL DEFAULT 0,
"branchOrder" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"conversationId" TEXT NOT NULL,
"parentId" TEXT,
CONSTRAINT "StoryBranch_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL,
"email" TEXT NOT NULL,
"username" TEXT NOT NULL,
"passwordHash" TEXT,
"keycloakSub" TEXT,
"role" "UserRole" NOT NULL DEFAULT 'USER',
"isActive" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "VectorMemory" (
"id" TEXT NOT NULL,
"content" TEXT NOT NULL,
"embedding" vector,
"memoryType" "MemoryType" NOT NULL DEFAULT 'conversation',
"metadata" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"conversationId" TEXT,
"characterId" TEXT,
"knowledgeId" TEXT,
CONSTRAINT "VectorMemory_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "Character_userId_idx" ON "Character"("userId");
-- CreateIndex
CREATE INDEX "Character_name_idx" ON "Character"("name");
-- CreateIndex
CREATE INDEX "CharacterKnowledge_characterId_idx" ON "CharacterKnowledge"("characterId");
-- CreateIndex
CREATE INDEX "CharacterKnowledge_status_idx" ON "CharacterKnowledge"("status");
-- CreateIndex
CREATE INDEX "Conversation_userId_idx" ON "Conversation"("userId");
-- CreateIndex
CREATE INDEX "Conversation_characterId_idx" ON "Conversation"("characterId");
-- CreateIndex
CREATE INDEX "Conversation_createdAt_idx" ON "Conversation"("createdAt");
-- CreateIndex
CREATE INDEX "ConversationParticipant_conversationId_idx" ON "ConversationParticipant"("conversationId");
-- CreateIndex
CREATE UNIQUE INDEX "ConversationParticipant_conversationId_characterId_key" ON "ConversationParticipant"("conversationId", "characterId");
-- CreateIndex
CREATE INDEX "ImportDocument_userId_idx" ON "ImportDocument"("userId");
-- CreateIndex
CREATE INDEX "ImportDocument_status_idx" ON "ImportDocument"("status");
-- CreateIndex
CREATE INDEX "Message_conversationId_idx" ON "Message"("conversationId");
-- CreateIndex
CREATE INDEX "Message_createdAt_idx" ON "Message"("createdAt");
-- CreateIndex
CREATE INDEX "Message_conversationId_createdAt_idx" ON "Message"("conversationId", "createdAt");
-- CreateIndex
CREATE INDEX "StoryBranch_conversationId_idx" ON "StoryBranch"("conversationId");
-- CreateIndex
CREATE INDEX "StoryBranch_parentId_idx" ON "StoryBranch"("parentId");
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
-- CreateIndex
CREATE UNIQUE INDEX "User_username_key" ON "User"("username");
-- CreateIndex
CREATE UNIQUE INDEX "User_keycloakSub_key" ON "User"("keycloakSub");
-- CreateIndex
CREATE INDEX "User_email_idx" ON "User"("email");
-- CreateIndex
CREATE INDEX "User_keycloakSub_idx" ON "User"("keycloakSub");
-- CreateIndex
CREATE INDEX "VectorMemory_conversationId_idx" ON "VectorMemory"("conversationId");
-- CreateIndex
CREATE INDEX "VectorMemory_characterId_idx" ON "VectorMemory"("characterId");
-- CreateIndex
CREATE INDEX "VectorMemory_knowledgeId_idx" ON "VectorMemory"("knowledgeId");
-- CreateIndex
CREATE INDEX "VectorMemory_memoryType_idx" ON "VectorMemory"("memoryType");
-- AddForeignKey
ALTER TABLE "Character" ADD CONSTRAINT "Character_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CharacterKnowledge" ADD CONSTRAINT "CharacterKnowledge_characterId_fkey" FOREIGN KEY ("characterId") REFERENCES "Character"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Conversation" ADD CONSTRAINT "Conversation_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Conversation" ADD CONSTRAINT "Conversation_characterId_fkey" FOREIGN KEY ("characterId") REFERENCES "Character"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ConversationParticipant" ADD CONSTRAINT "ConversationParticipant_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "Conversation"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ImportDocument" ADD CONSTRAINT "ImportDocument_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Message" ADD CONSTRAINT "Message_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "Conversation"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "StoryBranch" ADD CONSTRAINT "StoryBranch_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "Conversation"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "StoryBranch" ADD CONSTRAINT "StoryBranch_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "StoryBranch"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "VectorMemory" ADD CONSTRAINT "VectorMemory_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "Conversation"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "VectorMemory" ADD CONSTRAINT "VectorMemory_characterId_fkey" FOREIGN KEY ("characterId") REFERENCES "Character"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "VectorMemory" ADD CONSTRAINT "VectorMemory_knowledgeId_fkey" FOREIGN KEY ("knowledgeId") REFERENCES "CharacterKnowledge"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"

View File

@@ -0,0 +1,56 @@
// Character model and character knowledge
enum ImportSourceType {
file
url
manual
}
enum ImportStatus {
pending
processing
completed
failed
}
model Character {
id String @id @default(uuid())
name String
avatarUrl String?
personalityPrompt String
attributes Json @default("{}")
config Json @default("{}")
isPublic Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
conversations Conversation[]
knowledgeSources CharacterKnowledge[]
vectorMemories VectorMemory[]
@@index([userId])
@@index([name])
}
model CharacterKnowledge {
id String @id @default(uuid())
name String
sourceType ImportSourceType
sourceName String
mimeType String?
fileSize BigInt?
rawContent String?
status ImportStatus @default(pending)
processingInfo Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
characterId String
character Character @relation(fields: [characterId], references: [id], onDelete: Cascade)
vectorMemories VectorMemory[]
@@index([characterId])
@@index([status])
}

View File

@@ -0,0 +1,38 @@
// Conversation and participant models
model Conversation {
id String @id @default(uuid())
title String?
messageCount Int @default(0)
totalTokens Int @default(0)
settings Json @default("{}")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
characterId String
character Character @relation(fields: [characterId], references: [id], onDelete: Cascade)
messages Message[]
vectorMemories VectorMemory[]
storyBranches StoryBranch[]
participants ConversationParticipant[]
@@index([userId])
@@index([characterId])
@@index([createdAt])
}
model ConversationParticipant {
id String @id @default(uuid())
isActive Boolean @default(true)
autoRespond Boolean @default(true)
createdAt DateTime @default(now())
conversationId String
conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
characterId String
@@unique([conversationId, characterId])
@@index([conversationId])
}

View File

@@ -0,0 +1,21 @@
// General import documents (not linked to characters)
model ImportDocument {
id String @id @default(uuid())
sourceType ImportSourceType
sourceName String
mimeType String?
fileSize BigInt?
content String?
status ImportStatus @default(pending)
errorMessage String?
metadata Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
@@index([status])
}

View File

@@ -0,0 +1,24 @@
// Message model
enum MessageRole {
user
assistant
system
}
model Message {
id String @id @default(uuid())
role MessageRole
content String
tokensUsed Int?
model String?
metadata Json?
createdAt DateTime @default(now())
conversationId String
conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
@@index([conversationId])
@@index([createdAt])
@@index([conversationId, createdAt])
}

View File

@@ -0,0 +1,21 @@
// Story branching for narrative generation (Phase 2)
model StoryBranch {
id String @id @default(uuid())
title String?
content String
userDirection String
generationParams Json?
depth Int @default(0)
branchOrder Int @default(0)
createdAt DateTime @default(now())
conversationId String
conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
parentId String?
parent StoryBranch? @relation("BranchTree", fields: [parentId], references: [id], onDelete: Cascade)
children StoryBranch[] @relation("BranchTree")
@@index([conversationId])
@@index([parentId])
}

View File

@@ -0,0 +1,25 @@
// User model and related enums
enum UserRole {
USER
ADMIN
}
model User {
id String @id @default(uuid())
email String @unique
username String @unique
passwordHash String?
keycloakSub String? @unique
role UserRole @default(USER)
isActive Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
characters Character[]
conversations Conversation[]
importDocs ImportDocument[]
@@index([email])
@@index([keycloakSub])
}

View File

@@ -0,0 +1,29 @@
// Vector memory for embeddings (conversation and character knowledge)
enum MemoryType {
conversation
character
}
model VectorMemory {
id String @id @default(uuid())
content String
embedding Unsupported("vector")?
memoryType MemoryType @default(conversation)
metadata Json?
createdAt DateTime @default(now())
conversationId String?
conversation Conversation? @relation(fields: [conversationId], references: [id], onDelete: Cascade)
characterId String?
character Character? @relation(fields: [characterId], references: [id], onDelete: Cascade)
knowledgeId String?
knowledge CharacterKnowledge? @relation(fields: [knowledgeId], references: [id], onDelete: Cascade)
@@index([conversationId])
@@index([characterId])
@@index([knowledgeId])
@@index([memoryType])
}

View File

@@ -0,0 +1,15 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
generator client {
provider = "prisma-client-js"
previewFeatures = ["strictUndefinedChecks"]
engineType = "binary"
}
datasource db {
provider = "postgresql"
}

View File

@@ -0,0 +1,54 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
console.log('🌱 Seeding database...');
// Create default admin user
const admin = await prisma.user.upsert({
where: { email: 'admin@dreamchat.local' },
update: {},
create: {
email: 'admin@dreamchat.local',
username: 'admin',
role: 'ADMIN',
passwordHash: '$2b$10$YourHashedPasswordHere', // Replace with actual hash
},
});
console.log(`✅ Created admin user: ${admin.email}`);
// Create a sample character
const character = await prisma.character.upsert({
where: {
id: '00000000-0000-0000-0000-000000000001'
},
update: {},
create: {
id: '00000000-0000-0000-0000-000000000001',
name: 'Alice',
personalityPrompt: 'You are Alice, a curious and adventurous explorer who loves discovering new things. You are friendly, witty, and always eager to help.',
attributes: {
traits: ['curious', 'brave', 'witty', 'friendly'],
age: 25,
species: 'human',
skills: ['navigation', 'survival', 'cartography'],
},
userId: admin.id,
},
});
console.log(`✅ Created sample character: ${character.name}`);
console.log('✅ Seeding complete!');
}
main()
.catch((e) => {
console.error('❌ Seeding failed:', e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});

View File

@@ -0,0 +1,39 @@
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { PrismaModule } from './prisma/prisma.module';
import { AuthModule } from './auth/auth.module';
import { UserModule } from './user/user.module';
import { CharacterModule } from './character/character.module';
import { LLMModule } from './llm/llm.module';
import { VectorModule } from './vector/vector.module';
import { ChatModule } from './chat/chat.module';
import { ImportModule } from './import/import.module';
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
import { RequestLoggerMiddleware } from './common/middleware';
@Module({
imports: [
PrismaModule,
AuthModule,
UserModule,
CharacterModule,
LLMModule,
VectorModule,
ChatModule,
ImportModule,
],
controllers: [],
providers: [
{
provide: APP_GUARD,
useClass: JwtAuthGuard,
},
],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(RequestLoggerMiddleware)
.forRoutes('*');
}
}

View File

@@ -0,0 +1,125 @@
import { Controller, Post, Get, Body, Query, HttpCode, HttpStatus, UseGuards, Req, Res } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { Request, Response } from 'express';
import { AuthService } from './auth.service';
import { KeycloakService } from './keycloak.service';
import { LoginDto, RefreshTokenDto } from './dto/login.dto';
import { AuthResponseDto } from './dto/auth-response.dto';
import { KeycloakLoginUrlDto, KeycloakCallbackQueryDto, KeycloakConfigDto } from './dto/keycloak.dto';
import { Public } from '../common/decorators/public.decorator';
import { KeycloakAuthGuard } from './guards/keycloak-auth.guard';
@ApiTags('auth')
@Controller('auth')
export class AuthController {
constructor(
private authService: AuthService,
private keycloakService: KeycloakService,
) {}
@Public()
@Post('login')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Login with email and password' })
@ApiResponse({ status: 200, description: 'Login successful', type: AuthResponseDto })
@ApiResponse({ status: 401, description: 'Invalid credentials' })
async login(@Body() loginDto: LoginDto): Promise<AuthResponseDto> {
return this.authService.login(loginDto);
}
@Public()
@Post('refresh')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Refresh access token' })
@ApiResponse({ status: 200, description: 'Token refreshed', type: AuthResponseDto })
@ApiResponse({ status: 401, description: 'Invalid refresh token' })
async refreshTokens(@Body() refreshTokenDto: RefreshTokenDto): Promise<AuthResponseDto> {
return this.authService.refreshTokens(refreshTokenDto.refreshToken);
}
// ==================== KEYCLOAK OAUTH FLOW ====================
@Public()
@Get('keycloak/config')
@ApiOperation({ summary: 'Get Keycloak configuration for frontend' })
@ApiResponse({ status: 200, description: 'Keycloak config', type: KeycloakConfigDto })
getKeycloakConfig(): KeycloakConfigDto {
return this.keycloakService.getConfig();
}
@Public()
@Get('keycloak/login')
@ApiOperation({ summary: 'Get Keycloak login URL (initiates OAuth flow)' })
@ApiQuery({ name: 'redirectTo', required: false, description: 'Frontend path to redirect after login' })
@ApiResponse({ status: 200, description: 'Login URL generated', type: KeycloakLoginUrlDto })
@ApiResponse({ status: 400, description: 'Keycloak not enabled' })
keycloakLogin(@Query('redirectTo') redirectTo?: string): KeycloakLoginUrlDto {
return this.keycloakService.generateLoginUrl(redirectTo);
}
@Public()
@Get('keycloak/callback')
@ApiOperation({ summary: 'Keycloak OAuth callback endpoint' })
@ApiQuery({ name: 'code', required: true, description: 'Authorization code from Keycloak' })
@ApiQuery({ name: 'state', required: true, description: 'State parameter for CSRF validation' })
@ApiQuery({ name: 'error', required: false, description: 'Error message if authentication failed' })
@ApiQuery({ name: 'error_description', required: false, description: 'Error description' })
@ApiResponse({ status: 302, description: 'Redirect to frontend with tokens' })
@ApiResponse({ status: 401, description: 'Authentication failed' })
async keycloakCallback(
@Query() query: KeycloakCallbackQueryDto,
@Res() res: Response,
): Promise<void> {
// Handle errors from Keycloak
if (query.error) {
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:5173';
const errorMessage = encodeURIComponent(query.error_description || query.error);
return res.redirect(`${frontendUrl}/login?error=${errorMessage}`);
}
if (!query.code) {
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:5173';
return res.redirect(`${frontendUrl}/login?error=Missing authorization code`);
}
// Exchange code for tokens
const result = await this.keycloakService.handleCallback(query.code, query.state);
// Redirect to frontend with tokens
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:5173';
const redirectPath = result.redirectTo || '/characters';
// Build redirect URL with tokens
const params = new URLSearchParams({
accessToken: result.authResponse.accessToken,
refreshToken: result.authResponse.refreshToken,
});
return res.redirect(`${frontendUrl}${redirectPath}?${params.toString()}`);
}
// ==================== KEYCLOAK BEARER TOKEN (Legacy/Alternative) ====================
@Public()
@Post('keycloak')
@HttpCode(HttpStatus.OK)
@UseGuards(KeycloakAuthGuard)
@ApiOperation({ summary: 'Login with Keycloak bearer token (Authorization: Bearer <keycloak-jwt>)' })
@ApiBearerAuth()
@ApiResponse({ status: 200, description: 'Login successful', type: AuthResponseDto })
@ApiResponse({ status: 401, description: 'Invalid Keycloak token' })
async keycloakBearerLogin(@Req() req: Request): Promise<AuthResponseDto> {
// The Keycloak guard validates the token and attaches the user to req.user
const keycloakUser = req.user as {
userId: string;
email: string;
role: string;
};
return this.authService.generateTokensFromUser(
keycloakUser.userId,
keycloakUser.email,
keycloakUser.role,
);
}
}

View File

@@ -0,0 +1,33 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { KeycloakService } from './keycloak.service';
import { JwtStrategy } from './strategies/jwt.strategy';
import { LocalStrategy } from './strategies/local.strategy';
import { KeycloakStrategy } from './strategies/keycloak.strategy';
import { PrismaModule } from '../prisma/prisma.module';
@Module({
imports: [
PrismaModule,
PassportModule,
JwtModule.registerAsync({
useFactory: () => ({
secret: process.env.JWT_SECRET || 'dev-jwt-secret-change-in-production',
signOptions: { expiresIn: '1h' },
}),
}),
],
providers: [
AuthService,
KeycloakService,
JwtStrategy,
LocalStrategy,
KeycloakStrategy,
],
controllers: [AuthController],
exports: [AuthService, KeycloakService],
})
export class AuthModule {}

View File

@@ -0,0 +1,112 @@
import { Injectable, UnauthorizedException, ConflictException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '../prisma/prisma.service';
import * as bcrypt from 'bcrypt';
import { LoginDto, RegisterDto } from './dto/login.dto';
import { AuthResponseDto } from './dto/auth-response.dto';
import { User } from '@prisma/client';
@Injectable()
export class AuthService {
constructor(
private prisma: PrismaService,
private jwtService: JwtService,
) {}
async validateUser(email: string, password: string): Promise<Omit<User, 'passwordHash'> | null> {
const user = await this.prisma.user.findUnique({
where: { email },
});
if (user && user.passwordHash) {
const isMatch = await bcrypt.compare(password, user.passwordHash);
if (isMatch) {
const { passwordHash, ...result } = user;
return result;
}
}
return null;
}
async login(loginDto: LoginDto): Promise<AuthResponseDto> {
const user = await this.validateUser(loginDto.email, loginDto.password);
if (!user) {
throw new UnauthorizedException('Invalid credentials');
}
if (!user.isActive) {
throw new UnauthorizedException('Account is deactivated');
}
return this.generateTokens(user);
}
async register(registerDto: RegisterDto): Promise<AuthResponseDto> {
const existingUser = await this.prisma.user.findFirst({
where: {
OR: [
{ email: registerDto.email },
{ username: registerDto.username },
],
},
});
if (existingUser) {
throw new ConflictException('Email or username already exists');
}
const hashedPassword = await bcrypt.hash(registerDto.password, 10);
const user = await this.prisma.user.create({
data: {
email: registerDto.email,
username: registerDto.username,
passwordHash: hashedPassword,
},
});
const { passwordHash, ...userWithoutPassword } = user;
return this.generateTokens(userWithoutPassword);
}
async refreshTokens(refreshToken: string): Promise<AuthResponseDto> {
try {
const payload = this.jwtService.verify(refreshToken, {
secret: process.env.JWT_SECRET,
});
const user = await this.prisma.user.findUnique({
where: { id: payload.sub },
});
if (!user || !user.isActive) {
throw new UnauthorizedException('Invalid refresh token');
}
const { passwordHash, ...userWithoutPassword } = user;
return this.generateTokens(userWithoutPassword);
} catch {
throw new UnauthorizedException('Invalid refresh token');
}
}
generateTokensFromUser(userId: string, email: string, role: string): AuthResponseDto {
const payload = { sub: userId, email, role };
return {
accessToken: this.jwtService.sign(payload),
refreshToken: this.jwtService.sign(payload, { expiresIn: '7d' }),
user: {
id: userId,
email,
username: email.split('@')[0],
role,
},
};
}
private generateTokens(user: Omit<User, 'passwordHash'>): AuthResponseDto {
return this.generateTokensFromUser(user.id, user.email, user.role);
}
}

View File

@@ -0,0 +1,26 @@
import { ApiProperty } from '@nestjs/swagger';
class UserDto {
@ApiProperty({ description: 'User ID', example: '550e8400-e29b-41d4-a716-446655440000' })
id: string;
@ApiProperty({ description: 'User email', example: 'admin@dreamchat.local' })
email: string;
@ApiProperty({ description: 'User username', example: 'admin' })
username: string;
@ApiProperty({ description: 'User role', example: 'USER', enum: ['USER', 'ADMIN'] })
role: string;
}
export class AuthResponseDto {
@ApiProperty({ description: 'JWT access token' })
accessToken: string;
@ApiProperty({ description: 'JWT refresh token' })
refreshToken: string;
@ApiProperty({ description: 'User information', type: UserDto })
user: UserDto;
}

View File

@@ -0,0 +1,37 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class KeycloakConfigDto {
@ApiProperty({ description: 'Whether Keycloak authentication is enabled' })
enabled: boolean;
@ApiPropertyOptional({ description: 'Keycloak realm URL' })
url?: string;
@ApiPropertyOptional({ description: 'Keycloak realm name' })
realm?: string;
@ApiPropertyOptional({ description: 'Keycloak client ID' })
clientId?: string;
}
export class KeycloakLoginUrlDto {
@ApiProperty({ description: 'Keycloak login URL to redirect the user to' })
loginUrl: string;
@ApiProperty({ description: 'State parameter for CSRF protection' })
state: string;
}
export class KeycloakCallbackQueryDto {
@ApiPropertyOptional({ description: 'Authorization code from Keycloak' })
code?: string;
@ApiPropertyOptional({ description: 'Error message if authentication failed' })
error?: string;
@ApiPropertyOptional({ description: 'Error description' })
error_description?: string;
@ApiProperty({ description: 'State parameter for CSRF validation' })
state: string;
}

View File

@@ -0,0 +1,35 @@
import { IsString, IsEmail, MinLength } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class LoginDto {
@ApiProperty({ description: 'User email address', example: 'admin@dreamchat.local' })
@IsEmail()
email: string;
@ApiProperty({ description: 'User password', example: 'password123' })
@IsString()
@MinLength(6)
password: string;
}
export class RegisterDto {
@ApiProperty({ description: 'User email address', example: 'user@example.com' })
@IsEmail()
email: string;
@ApiProperty({ description: 'Username', example: 'myusername' })
@IsString()
@MinLength(3)
username: string;
@ApiProperty({ description: 'User password', example: 'password123' })
@IsString()
@MinLength(6)
password: string;
}
export class RefreshTokenDto {
@ApiProperty({ description: 'Refresh token', example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' })
@IsString()
refreshToken: string;
}

View File

@@ -0,0 +1,24 @@
import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from '../../common/decorators/public.decorator';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
constructor(private reflector: Reflector) {
super();
}
canActivate(context: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
return true;
}
return super.canActivate(context);
}
}

View File

@@ -0,0 +1,13 @@
import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class KeycloakAuthGuard extends AuthGuard('keycloak') {
canActivate(context: ExecutionContext) {
// Skip if Keycloak is not enabled
if (process.env.KEYCLOAK_ENABLED !== 'true') {
return false;
}
return super.canActivate(context);
}
}

View File

@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}

View File

@@ -0,0 +1,333 @@
import { Injectable, UnauthorizedException, BadRequestException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '../prisma/prisma.service';
import { UserRole } from '@prisma/client';
import { AuthResponseDto } from './dto/auth-response.dto';
import * as crypto from 'crypto';
interface KeycloakTokenResponse {
access_token: string;
expires_in: number;
refresh_expires_in: number;
refresh_token: string;
token_type: string;
id_token?: string;
session_state?: string;
scope: string;
}
interface KeycloakUserInfo {
sub: string;
email?: string;
email_verified?: boolean;
name?: string;
preferred_username?: string;
given_name?: string;
family_name?: string;
groups?: string[];
// Keycloak may also put groups in these locations
realm_access?: {
roles?: string[];
};
resource_access?: {
[key: string]: {
roles?: string[];
};
};
[key: string]: any;
}
@Injectable()
export class KeycloakService {
private readonly keycloakEnabled: boolean;
private readonly keycloakUrl: string;
private readonly keycloakRealm: string;
private readonly clientId: string;
private readonly clientSecret: string;
private readonly redirectUri: string;
private stateStore: Map<string, { createdAt: number; redirectTo?: string }> = new Map();
constructor(
private prisma: PrismaService,
private jwtService: JwtService,
) {
this.keycloakEnabled = process.env.KEYCLOAK_ENABLED === 'true';
this.keycloakUrl = process.env.KEYCLOAK_URL || '';
this.keycloakRealm = process.env.KEYCLOAK_REALM || '';
this.clientId = process.env.KEYCLOAK_CLIENT_ID || '';
this.clientSecret = process.env.KEYCLOAK_CLIENT_SECRET || '';
this.redirectUri = process.env.KEYCLOAK_REDIRECT_URI || 'http://localhost:3000/api/auth/keycloak/callback';
// Clean up old state entries every 5 minutes
setInterval(() => this.cleanupState(), 5 * 60 * 1000);
}
isEnabled(): boolean {
return this.keycloakEnabled;
}
getConfig() {
return {
enabled: this.keycloakEnabled,
url: this.keycloakUrl || undefined,
realm: this.keycloakRealm || undefined,
clientId: this.clientId || undefined,
};
}
generateLoginUrl(redirectTo?: string): { loginUrl: string; state: string } {
if (!this.keycloakEnabled) {
throw new BadRequestException('Keycloak is not enabled');
}
const state = crypto.randomBytes(32).toString('hex');
this.stateStore.set(state, {
createdAt: Date.now(),
redirectTo,
});
const baseUrl = `${this.keycloakUrl}/realms/${this.keycloakRealm}/protocol/openid-connect/auth`;
const params = new URLSearchParams({
client_id: this.clientId,
redirect_uri: this.redirectUri,
response_type: 'code',
scope: 'openid email profile',
state,
});
return {
loginUrl: `${baseUrl}?${params.toString()}`,
state,
};
}
async handleCallback(code: string, state: string): Promise<{
authResponse: AuthResponseDto;
redirectTo?: string;
}> {
if (!this.keycloakEnabled) {
throw new BadRequestException('Keycloak is not enabled');
}
// Validate state
const stateData = this.stateStore.get(state);
if (!stateData) {
throw new UnauthorizedException('Invalid or expired state parameter');
}
this.stateStore.delete(state);
// Exchange code for tokens
const tokens = await this.exchangeCodeForTokens(code);
// Get user info from Keycloak
const userInfo = await this.getUserInfo(tokens.access_token);
// DEBUG: Log the full userinfo to see what groups are actually returned
console.log('[Keycloak Debug] UserInfo:', JSON.stringify(userInfo, null, 2));
// Validate user info
if (!userInfo.sub) {
throw new UnauthorizedException('Invalid user info from Keycloak');
}
// Check authorization requirements
this.checkAuthorization(userInfo);
// Find or create user
const user = await this.findOrCreateUser(userInfo);
if (!user.isActive) {
throw new UnauthorizedException('Account is deactivated');
}
// Generate DreamChat tokens
const authResponse = this.generateTokens(user);
return {
authResponse,
redirectTo: stateData.redirectTo,
};
}
private async exchangeCodeForTokens(code: string): Promise<KeycloakTokenResponse> {
const tokenUrl = `${this.keycloakUrl}/realms/${this.keycloakRealm}/protocol/openid-connect/token`;
const params = new URLSearchParams({
grant_type: 'authorization_code',
client_id: this.clientId,
client_secret: this.clientSecret,
code,
redirect_uri: this.redirectUri,
});
const response = await fetch(tokenUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params.toString(),
});
if (!response.ok) {
const error = await response.text();
throw new UnauthorizedException(`Failed to exchange code for tokens: ${error}`);
}
return response.json();
}
private async getUserInfo(accessToken: string): Promise<KeycloakUserInfo> {
const userInfoUrl = `${this.keycloakUrl}/realms/${this.keycloakRealm}/protocol/openid-connect/userinfo`;
const response = await fetch(userInfoUrl, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
if (!response.ok) {
throw new UnauthorizedException('Failed to get user info from Keycloak');
}
return response.json();
}
private async findOrCreateUser(userInfo: KeycloakUserInfo) {
const keycloakSub = userInfo.sub;
const email = userInfo.email;
const username = userInfo.preferred_username || email || keycloakSub;
// Try to find user by keycloakSub first
let user = await this.prisma.user.findUnique({
where: { keycloakSub },
});
if (user) {
return user;
}
// Try to find by email and link accounts
if (email) {
const existingUser = await this.prisma.user.findUnique({
where: { email },
});
if (existingUser) {
// Link existing user to Keycloak
return this.prisma.user.update({
where: { id: existingUser.id },
data: { keycloakSub },
});
}
}
// Check if auto-create is enabled
const autoCreate = process.env.KEYCLOAK_AUTO_CREATE_USER !== 'false';
if (!autoCreate) {
throw new UnauthorizedException('User not found and auto-creation is disabled');
}
// Create new user
const defaultRole =
process.env.KEYCLOAK_DEFAULT_USER_ROLE === 'ADMIN'
? UserRole.ADMIN
: UserRole.USER;
return this.prisma.user.create({
data: {
email: email || `${keycloakSub}@keycloak.local`,
username: username,
keycloakSub,
role: defaultRole,
},
});
}
private checkAuthorization(userInfo: KeycloakUserInfo): void {
const requiredGroup = process.env.KEYCLOAK_REQUIRED_GROUP;
const requiredRole = process.env.KEYCLOAK_REQUIRED_ROLE;
const requiredClientRole = process.env.KEYCLOAK_REQUIRED_CLIENT_ROLE;
const requiredAttribute = process.env.KEYCLOAK_REQUIRED_ATTRIBUTE;
// Collect all possible sources of groups/roles
const groups = userInfo.groups || [];
const realmRoles = userInfo.realm_access?.roles || [];
const clientRoles = userInfo.resource_access?.[this.clientId]?.roles || [];
console.log('[Keycloak Debug] Authorization Check:');
console.log(' Required Group:', requiredGroup);
console.log(' User Groups:', groups);
console.log(' Realm Roles:', realmRoles);
console.log(' Client Roles:', clientRoles);
// Check required group - try groups array, then realm roles, then client roles
if (requiredGroup) {
// Check in groups claim (most common location)
const hasGroup = groups.includes(requiredGroup);
// Also check in realm roles (sometimes groups are mapped as roles)
const hasGroupAsRole = realmRoles.includes(requiredGroup);
// Also check in client roles
const hasGroupAsClientRole = clientRoles.includes(requiredGroup);
if (!hasGroup && !hasGroupAsRole && !hasGroupAsClientRole) {
throw new UnauthorizedException(
`Access denied: required group '${requiredGroup}' not found. Your groups: [${groups.join(', ')}], realm roles: [${realmRoles.join(', ')}], client roles: [${clientRoles.join(', ')}]`,
);
}
}
// Check required realm role
if (requiredRole) {
if (!realmRoles.includes(requiredRole)) {
throw new UnauthorizedException(
`Access denied: required role '${requiredRole}' not found. Your roles: [${realmRoles.join(', ')}]`,
);
}
}
// Check required client role
if (requiredClientRole) {
if (!clientRoles.includes(requiredClientRole)) {
throw new UnauthorizedException(
`Access denied: required client role '${requiredClientRole}' not found. Your client roles: [${clientRoles.join(', ')}]`,
);
}
}
// Check required attribute
if (requiredAttribute) {
const [attrKey, attrValue] = requiredAttribute.split(':');
if (userInfo[attrKey] !== attrValue) {
throw new UnauthorizedException(
`Access denied: required attribute '${attrKey}=${attrValue}' not found`,
);
}
}
}
private generateTokens(user: { id: string; email: string; username: string; role: string }): AuthResponseDto {
const payload = { sub: user.id, email: user.email, role: user.role };
return {
accessToken: this.jwtService.sign(payload),
refreshToken: this.jwtService.sign(payload, { expiresIn: '7d' }),
user: {
id: user.id,
email: user.email,
username: user.username,
role: user.role,
},
};
}
private cleanupState(): void {
const now = Date.now();
const maxAge = 10 * 60 * 1000; // 10 minutes
for (const [state, data] of this.stateStore.entries()) {
if (now - data.createdAt > maxAge) {
this.stateStore.delete(state);
}
}
}
}

View File

@@ -0,0 +1,37 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PrismaService } from '../../prisma/prisma.service';
interface JwtPayload {
sub: string;
email: string;
role: string;
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(private prisma: PrismaService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET || 'dev-jwt-secret-change-in-production',
});
}
async validate(payload: JwtPayload) {
const user = await this.prisma.user.findUnique({
where: { id: payload.sub },
});
if (!user || !user.isActive) {
throw new UnauthorizedException('User not found or inactive');
}
return {
userId: payload.sub,
email: payload.email,
role: payload.role,
};
}
}

View File

@@ -0,0 +1,191 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { PrismaService } from '../../prisma/prisma.service';
import { UserRole } from '@prisma/client';
interface KeycloakJwtPayload {
sub: string;
email?: string;
preferred_username?: string;
realm_access?: {
roles?: string[];
};
resource_access?: {
[key: string]: {
roles?: string[];
};
};
groups?: string[];
[key: string]: any;
}
@Injectable()
export class KeycloakStrategy extends PassportStrategy(Strategy, 'keycloak') {
private keycloakEnabled: boolean;
constructor(private prisma: PrismaService) {
const keycloakEnabled = process.env.KEYCLOAK_ENABLED === 'true';
const keycloakUrl = process.env.KEYCLOAK_URL || '';
const keycloakRealm = process.env.KEYCLOAK_REALM || '';
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: keycloakEnabled
? undefined
: 'keycloak-not-enabled-placeholder',
secretOrKeyProvider: keycloakEnabled
? async (request, rawJwtToken, done) => {
try {
// Fetch Keycloak realm public key
const response = await fetch(
`${keycloakUrl}/realms/${keycloakRealm}`,
);
const realmInfo = await response.json();
const publicKey = realmInfo.public_key;
if (!publicKey) {
throw new Error('No public key found in Keycloak realm');
}
done(
null,
`-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`,
);
} catch (error) {
done(error as Error, '');
}
}
: undefined,
algorithms: ['RS256'],
});
this.keycloakEnabled = keycloakEnabled;
}
async validate(payload: KeycloakJwtPayload): Promise<{
userId: string;
email: string;
role: UserRole;
keycloakSub: string;
}> {
if (!this.keycloakEnabled) {
throw new UnauthorizedException('Keycloak is not enabled');
}
const keycloakSub = payload.sub;
const email = payload.email;
const username = payload.preferred_username || email;
if (!keycloakSub) {
throw new UnauthorizedException('Invalid Keycloak token');
}
// Check authorization requirements
this.checkAuthorization(payload);
// Find or create user
let user = await this.prisma.user.findUnique({
where: { keycloakSub },
});
if (!user) {
// Auto-create user if enabled
const autoCreate = process.env.KEYCLOAK_AUTO_CREATE_USER !== 'false';
if (!autoCreate) {
throw new UnauthorizedException(
'User not found and auto-creation is disabled',
);
}
// Check if email already exists
if (email) {
const existingUser = await this.prisma.user.findUnique({
where: { email },
});
if (existingUser) {
// Link existing user to Keycloak
user = await this.prisma.user.update({
where: { id: existingUser.id },
data: { keycloakSub },
});
}
}
if (!user) {
// Create new user
const defaultRole =
process.env.KEYCLOAK_DEFAULT_USER_ROLE === 'ADMIN'
? UserRole.ADMIN
: UserRole.USER;
user = await this.prisma.user.create({
data: {
email: email || `${keycloakSub}@keycloak.local`,
username: username || keycloakSub,
keycloakSub,
role: defaultRole,
},
});
}
}
if (!user.isActive) {
throw new UnauthorizedException('Account is deactivated');
}
return {
userId: user.id,
email: user.email,
role: user.role,
keycloakSub,
};
}
private checkAuthorization(payload: KeycloakJwtPayload): void {
const requiredGroup = process.env.KEYCLOAK_REQUIRED_GROUP;
const requiredRole = process.env.KEYCLOAK_REQUIRED_ROLE;
const requiredClientRole = process.env.KEYCLOAK_REQUIRED_CLIENT_ROLE;
const requiredAttribute = process.env.KEYCLOAK_REQUIRED_ATTRIBUTE;
// Check required group
if (requiredGroup) {
const groups = payload.groups || [];
if (!groups.includes(requiredGroup)) {
throw new UnauthorizedException(
`Access denied: required group '${requiredGroup}' not found`,
);
}
}
// Check required realm role
if (requiredRole) {
const roles = payload.realm_access?.roles || [];
if (!roles.includes(requiredRole)) {
throw new UnauthorizedException(
`Access denied: required role '${requiredRole}' not found`,
);
}
}
// Check required client role
if (requiredClientRole) {
const clientId = process.env.KEYCLOAK_CLIENT_ID || '';
const clientRoles = payload.resource_access?.[clientId]?.roles || [];
if (!clientRoles.includes(requiredClientRole)) {
throw new UnauthorizedException(
`Access denied: required client role '${requiredClientRole}' not found`,
);
}
}
// Check required attribute
if (requiredAttribute) {
const [attrKey, attrValue] = requiredAttribute.split(':');
if (payload[attrKey] !== attrValue) {
throw new UnauthorizedException(
`Access denied: required attribute '${attrKey}=${attrValue}' not found`,
);
}
}
}
}

View File

@@ -0,0 +1,21 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { AuthService } from '../auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy, 'local') {
constructor(private authService: AuthService) {
super({
usernameField: 'email',
});
}
async validate(email: string, password: string): Promise<any> {
const user = await this.authService.validateUser(email, password);
if (!user) {
throw new UnauthorizedException('Invalid credentials');
}
return user;
}
}

View File

@@ -0,0 +1,85 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiParam } from '@nestjs/swagger';
import { CharacterService } from './character.service';
import { CreateCharacterDto, UpdateCharacterDto } from './dto/create-character.dto';
import { CharacterResponseDto } from './dto/character-response.dto';
import { CurrentUser } from '../common/decorators/current-user.decorator';
import { Character } from '@prisma/client';
@ApiTags('characters')
@ApiBearerAuth()
@Controller('characters')
export class CharacterController {
constructor(private characterService: CharacterService) {}
@Post()
@ApiOperation({ summary: 'Create a new character' })
@ApiResponse({ status: 201, description: 'Character created', type: CharacterResponseDto })
@ApiResponse({ status: 401, description: 'Unauthorized' })
async create(
@CurrentUser('userId') userId: string,
@Body() createCharacterDto: CreateCharacterDto,
): Promise<Character> {
return this.characterService.create(userId, createCharacterDto);
}
@Get()
@ApiOperation({ summary: 'Get all characters for current user' })
@ApiResponse({ status: 200, description: 'List of characters', type: [CharacterResponseDto] })
@ApiResponse({ status: 401, description: 'Unauthorized' })
async findAll(@CurrentUser('userId') userId: string): Promise<Character[]> {
return this.characterService.findAllByUser(userId);
}
@Get(':id')
@ApiOperation({ summary: 'Get character by ID' })
@ApiParam({ name: 'id', description: 'Character ID' })
@ApiResponse({ status: 200, description: 'Character found', type: CharacterResponseDto })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 403, description: 'Access denied' })
@ApiResponse({ status: 404, description: 'Character not found' })
async findOne(
@Param('id') id: string,
@CurrentUser('userId') userId: string,
): Promise<Character> {
return this.characterService.findById(id, userId);
}
@Put(':id')
@ApiOperation({ summary: 'Update character' })
@ApiParam({ name: 'id', description: 'Character ID' })
@ApiResponse({ status: 200, description: 'Character updated', type: CharacterResponseDto })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 403, description: 'Access denied' })
@ApiResponse({ status: 404, description: 'Character not found' })
async update(
@Param('id') id: string,
@CurrentUser('userId') userId: string,
@Body() updateCharacterDto: UpdateCharacterDto,
): Promise<Character> {
return this.characterService.update(id, userId, updateCharacterDto);
}
@Delete(':id')
@ApiOperation({ summary: 'Delete character' })
@ApiParam({ name: 'id', description: 'Character ID' })
@ApiResponse({ status: 200, description: 'Character deleted' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 403, description: 'Access denied' })
@ApiResponse({ status: 404, description: 'Character not found' })
async delete(
@Param('id') id: string,
@CurrentUser('userId') userId: string,
): Promise<{ message: string }> {
await this.characterService.delete(id, userId);
return { message: 'Character deleted successfully' };
}
}

View File

@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { CharacterService } from './character.service';
import { CharacterController } from './character.controller';
@Module({
providers: [CharacterService],
controllers: [CharacterController],
exports: [CharacterService],
})
export class CharacterModule {}

View File

@@ -0,0 +1,74 @@
import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateCharacterDto, UpdateCharacterDto } from './dto/create-character.dto';
import { Character } from '@prisma/client';
@Injectable()
export class CharacterService {
constructor(private prisma: PrismaService) {}
async create(userId: string, createCharacterDto: CreateCharacterDto): Promise<Character> {
return this.prisma.character.create({
data: {
...createCharacterDto,
userId,
},
});
}
async findAllByUser(userId: string): Promise<Character[]> {
return this.prisma.character.findMany({
where: { userId },
orderBy: { createdAt: 'desc' },
});
}
async findById(id: string, userId?: string): Promise<Character> {
const character = await this.prisma.character.findUnique({
where: { id },
include: {
knowledgeSources: true,
},
});
if (!character) {
throw new NotFoundException('Character not found');
}
// If userId is provided, check if user owns the character or if it's public
if (userId && character.userId !== userId && !character.isPublic) {
throw new ForbiddenException('You do not have access to this character');
}
return character;
}
async update(
id: string,
userId: string,
updateCharacterDto: UpdateCharacterDto,
): Promise<Character> {
const character = await this.findById(id, userId);
if (character.userId !== userId) {
throw new ForbiddenException('You can only update your own characters');
}
return this.prisma.character.update({
where: { id },
data: updateCharacterDto,
});
}
async delete(id: string, userId: string): Promise<void> {
const character = await this.findById(id, userId);
if (character.userId !== userId) {
throw new ForbiddenException('You can only delete your own characters');
}
await this.prisma.character.delete({
where: { id },
});
}
}

View File

@@ -0,0 +1,38 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class CharacterResponseDto {
@ApiProperty({ description: 'Character ID', example: '550e8400-e29b-41d4-a716-446655440000' })
id: string;
@ApiProperty({ description: 'Character name', example: 'Alice the Explorer' })
name: string;
@ApiPropertyOptional({ description: 'Avatar URL', example: 'https://example.com/avatar.jpg' })
avatarUrl: string | null;
@ApiProperty({ description: 'Personality prompt', example: 'You are Alice, a curious explorer...' })
personalityPrompt: string;
@ApiProperty({ description: 'Custom attributes', example: { age: 25, traits: ['curious'] } })
attributes: Record<string, any>;
@ApiProperty({ description: 'Character configuration', example: {} })
config: Record<string, any>;
@ApiProperty({ description: 'Whether character is public', example: false })
isPublic: boolean;
@ApiProperty({ description: 'Creation date' })
createdAt: Date;
@ApiProperty({ description: 'Last update date' })
updatedAt: Date;
@ApiProperty({ description: 'User ID', example: '550e8400-e29b-41d4-a716-446655440000' })
userId: string;
}
export class CharacterListResponseDto {
@ApiProperty({ description: 'List of characters', type: [CharacterResponseDto] })
characters: CharacterResponseDto[];
}

View File

@@ -0,0 +1,68 @@
import { IsString, IsOptional, IsBoolean, IsObject, MinLength } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class CreateCharacterDto {
@ApiProperty({ description: 'Character name', example: 'Alice the Explorer' })
@IsString()
@MinLength(1)
name: string;
@ApiPropertyOptional({ description: 'Avatar URL', example: 'https://example.com/avatar.jpg' })
@IsOptional()
@IsString()
avatarUrl?: string;
@ApiProperty({ description: 'Personality prompt that guides AI responses', example: 'You are Alice, a curious and adventurous explorer...' })
@IsString()
@MinLength(10)
personalityPrompt: string;
@ApiPropertyOptional({ description: 'Custom attributes (JSON)', example: { age: 25, traits: ['curious', 'brave'] } })
@IsOptional()
@IsObject()
attributes?: Record<string, any>;
@ApiPropertyOptional({ description: 'Character configuration (JSON)', example: { voice: 'friendly' } })
@IsOptional()
@IsObject()
config?: Record<string, any>;
@ApiPropertyOptional({ description: 'Whether the character is publicly visible', example: false })
@IsOptional()
@IsBoolean()
isPublic?: boolean;
}
export class UpdateCharacterDto {
@ApiPropertyOptional({ description: 'Character name', example: 'Alice the Explorer' })
@IsOptional()
@IsString()
@MinLength(1)
name?: string;
@ApiPropertyOptional({ description: 'Avatar URL', example: 'https://example.com/avatar.jpg' })
@IsOptional()
@IsString()
avatarUrl?: string;
@ApiPropertyOptional({ description: 'Personality prompt', example: 'You are Alice...' })
@IsOptional()
@IsString()
@MinLength(10)
personalityPrompt?: string;
@ApiPropertyOptional({ description: 'Custom attributes (JSON)' })
@IsOptional()
@IsObject()
attributes?: Record<string, any>;
@ApiPropertyOptional({ description: 'Character configuration (JSON)' })
@IsOptional()
@IsObject()
config?: Record<string, any>;
@ApiPropertyOptional({ description: 'Whether the character is publicly visible' })
@IsOptional()
@IsBoolean()
isPublic?: boolean;
}

View File

@@ -0,0 +1,92 @@
import {
Controller,
Get,
Post,
Delete,
Body,
Param,
HttpCode,
HttpStatus,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiParam } from '@nestjs/swagger';
import { ChatService } from './chat.service';
import { CreateConversationDto, SendMessageDto } from './dto/chat.dto';
import {
ConversationResponseDto,
ConversationWithMessagesResponseDto,
SendMessageResponseDto
} from './dto/conversation-response.dto';
import { CurrentUser } from '../common/decorators/current-user.decorator';
import { Conversation, Message } from '@prisma/client';
@ApiTags('conversations')
@ApiBearerAuth()
@Controller('conversations')
export class ChatController {
constructor(private chatService: ChatService) {}
@Post()
@ApiOperation({ summary: 'Create a new conversation' })
@ApiResponse({ status: 201, description: 'Conversation created', type: ConversationResponseDto })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 404, description: 'Character not found' })
async createConversation(
@CurrentUser('userId') userId: string,
@Body() createConversationDto: CreateConversationDto,
): Promise<Conversation> {
return this.chatService.createConversation(userId, createConversationDto);
}
@Get()
@ApiOperation({ summary: 'Get all conversations for current user' })
@ApiResponse({ status: 200, description: 'List of conversations', type: [ConversationResponseDto] })
@ApiResponse({ status: 401, description: 'Unauthorized' })
async getConversations(@CurrentUser('userId') userId: string): Promise<Conversation[]> {
return this.chatService.findConversationsByUser(userId);
}
@Get(':id')
@ApiOperation({ summary: 'Get conversation by ID with messages' })
@ApiParam({ name: 'id', description: 'Conversation ID' })
@ApiResponse({ status: 200, description: 'Conversation found', type: ConversationWithMessagesResponseDto })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 403, description: 'Access denied' })
@ApiResponse({ status: 404, description: 'Conversation not found' })
async getConversation(
@Param('id') id: string,
@CurrentUser('userId') userId: string,
): Promise<Conversation & { messages: Message[] }> {
return this.chatService.findConversationById(id, userId);
}
@Delete(':id')
@ApiOperation({ summary: 'Delete conversation' })
@ApiParam({ name: 'id', description: 'Conversation ID' })
@ApiResponse({ status: 200, description: 'Conversation deleted' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 403, description: 'Access denied' })
@ApiResponse({ status: 404, description: 'Conversation not found' })
async deleteConversation(
@Param('id') id: string,
@CurrentUser('userId') userId: string,
): Promise<{ message: string }> {
await this.chatService.deleteConversation(id, userId);
return { message: 'Conversation deleted successfully' };
}
@Post(':id/messages')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Send a message in a conversation' })
@ApiParam({ name: 'id', description: 'Conversation ID' })
@ApiResponse({ status: 200, description: 'Message sent', type: SendMessageResponseDto })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 403, description: 'Access denied' })
@ApiResponse({ status: 404, description: 'Conversation not found' })
async sendMessage(
@Param('id') conversationId: string,
@CurrentUser('userId') userId: string,
@Body() sendMessageDto: SendMessageDto,
): Promise<SendMessageResponseDto> {
return this.chatService.sendMessage(conversationId, userId, sendMessageDto);
}
}

View File

@@ -0,0 +1,148 @@
import {
WebSocketGateway,
WebSocketServer,
SubscribeMessage,
MessageBody,
ConnectedSocket,
OnGatewayConnection,
OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { UseGuards, Logger } from '@nestjs/common';
import { ChatService } from './chat.service';
import { JwtService } from '@nestjs/jwt';
interface AuthenticatedSocket extends Socket {
userId?: string;
}
@WebSocketGateway({
cors: {
origin: ['http://localhost:5173'],
credentials: true,
},
namespace: '/chat',
})
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server: Server;
private readonly logger = new Logger(ChatGateway.name);
constructor(
private chatService: ChatService,
private jwtService: JwtService,
) {}
async handleConnection(client: AuthenticatedSocket) {
try {
const token = client.handshake.auth.token as string;
if (!token) {
client.disconnect();
return;
}
const payload = this.jwtService.verify(token.replace('Bearer ', ''));
client.userId = payload.sub;
console.log(`Client connected: ${client.id}, user: ${client.userId}`);
} catch {
client.disconnect();
}
}
handleDisconnect(client: AuthenticatedSocket) {
console.log(`Client disconnected: ${client.id}`);
}
@SubscribeMessage('join_conversation')
async handleJoinConversation(
@MessageBody() data: { conversationId: string },
@ConnectedSocket() client: AuthenticatedSocket,
) {
if (!client.userId) return;
const room = `conversation:${data.conversationId}`;
await client.join(room);
client.emit('joined', { conversationId: data.conversationId });
}
@SubscribeMessage('leave_conversation')
async handleLeaveConversation(
@MessageBody() data: { conversationId: string },
@ConnectedSocket() client: AuthenticatedSocket,
) {
const room = `conversation:${data.conversationId}`;
await client.leave(room);
client.emit('left', { conversationId: data.conversationId });
}
@SubscribeMessage('send_message')
async handleSendMessage(
@MessageBody()
data: { conversationId: string; content: string },
@ConnectedSocket() client: AuthenticatedSocket,
) {
if (!client.userId) return;
this.logger.debug(`[handleSendMessage] Received message from user ${client.userId} for conversation ${data.conversationId}: "${data.content}"`);
const room = `conversation:${data.conversationId}`;
try {
// Stream the response
const stream = this.chatService.streamMessage(
data.conversationId,
client.userId,
{ content: data.content },
);
let assistantMessage: any = null;
for await (const event of stream) {
if (event.type === 'chunk') {
// Broadcast chunk to all clients in the room
this.server.to(room).emit('message_chunk', {
conversationId: data.conversationId,
chunk: event.data,
});
} else if (event.type === 'message') {
if (event.data.assistantMessage) {
assistantMessage = event.data.assistantMessage;
}
// Broadcast the full message
this.server.to(room).emit('message', {
conversationId: data.conversationId,
message: event.data,
});
}
}
// Signal completion
this.server.to(room).emit('message_complete', {
conversationId: data.conversationId,
assistantMessage,
});
this.logger.debug(`[handleSendMessage] Message streaming completed for conversation ${data.conversationId}`);
} catch (error) {
client.emit('error', {
conversationId: data.conversationId,
message: error instanceof Error ? error.message : 'Unknown error',
});
}
}
@SubscribeMessage('typing')
async handleTyping(
@MessageBody() data: { conversationId: string; isTyping: boolean },
@ConnectedSocket() client: AuthenticatedSocket,
) {
if (!client.userId) return;
const room = `conversation:${data.conversationId}`;
client.to(room).emit('user_typing', {
conversationId: data.conversationId,
isTyping: data.isTyping,
});
}
}

View File

@@ -0,0 +1,16 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { ChatService } from './chat.service';
import { ChatController } from './chat.controller';
import { ChatGateway } from './chat.gateway';
import { LLMModule } from '../llm/llm.module';
import { VectorModule } from '../vector/vector.module';
import { CharacterModule } from '../character/character.module';
@Module({
imports: [LLMModule, VectorModule, CharacterModule, JwtModule],
providers: [ChatService, ChatGateway],
controllers: [ChatController],
exports: [ChatService],
})
export class ChatModule {}

View File

@@ -0,0 +1,258 @@
import { Injectable, NotFoundException, ForbiddenException, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { LLMService } from '../llm/llm.service';
import { MemoryService } from '../vector/memory.service';
import { CharacterService } from '../character/character.service';
import { CreateConversationDto, SendMessageDto } from './dto/chat.dto';
import { Conversation, Message, MessageRole } from '@prisma/client';
@Injectable()
export class ChatService {
private readonly logger = new Logger(ChatService.name);
constructor(
private prisma: PrismaService,
private llmService: LLMService,
private memoryService: MemoryService,
private characterService: CharacterService,
) {}
async createConversation(userId: string, createConversationDto: CreateConversationDto): Promise<Conversation> {
// Verify character exists and user has access
const character = await this.characterService.findById(createConversationDto.characterId, userId);
return this.prisma.conversation.create({
data: {
userId,
characterId: createConversationDto.characterId,
title: createConversationDto.title || `Chat with ${character.name}`,
},
});
}
async findConversationsByUser(userId: string): Promise<Conversation[]> {
return this.prisma.conversation.findMany({
where: { userId },
include: {
character: {
select: {
id: true,
name: true,
avatarUrl: true,
},
},
},
orderBy: { updatedAt: 'desc' },
});
}
async findConversationById(
id: string,
userId: string,
): Promise<Conversation & { messages: Message[]; character: { id: string; name: string; personalityPrompt: string } }> {
const conversation = await this.prisma.conversation.findUnique({
where: { id },
include: {
messages: {
orderBy: { createdAt: 'asc' },
},
character: {
select: {
id: true,
name: true,
personalityPrompt: true,
},
},
},
});
if (!conversation) {
throw new NotFoundException('Conversation not found');
}
if (conversation.userId !== userId) {
throw new ForbiddenException('You do not have access to this conversation');
}
return conversation;
}
async deleteConversation(id: string, userId: string): Promise<void> {
const conversation = await this.findConversationById(id, userId);
if (conversation.userId !== userId) {
throw new ForbiddenException('You can only delete your own conversations');
}
// Delete related vector memories first
await this.memoryService['vectorStore'].deleteByConversation(id);
await this.prisma.conversation.delete({
where: { id },
});
}
async sendMessage(conversationId: string, userId: string, sendMessageDto: SendMessageDto): Promise<{ userMessage: Message; assistantMessage: Message }> {
const conversation = await this.findConversationById(conversationId, userId);
// Create user message
const userMessage = await this.prisma.message.create({
data: {
conversationId,
role: 'user',
content: sendMessageDto.content,
},
});
// Store user message in vector memory
await this.memoryService.storeConversationMessage(`User: ${sendMessageDto.content}`, conversationId, { messageId: userMessage.id });
// Generate context from memory
const memoryContext = await this.memoryService.buildContextForConversation(conversationId, sendMessageDto.content, conversation.characterId);
// Build messages for LLM
const messages = this.buildLLMMessages(conversation.character.personalityPrompt, conversation.messages, sendMessageDto.content, memoryContext);
// Grouped debug logging
this.logger.debug(
`[sendMessage] conversation=${conversationId}\n` +
`--- Knowledges/Context ---\n${memoryContext || '(none)'}\n` +
`--- Full Messages to LLM ---\n` +
messages.map((msg, idx) => `[${idx}] ${msg.role}: ${msg.content.substring(0, 200)}${msg.content.length > 200 ? '...' : ''}`).join('\n'),
);
// Generate response
const response = await this.llmService.generateCompletion(messages, {
temperature: 0.7,
maxTokens: 2000,
});
// Create assistant message
const assistantMessage = await this.prisma.message.create({
data: {
conversationId,
role: 'assistant',
content: response.content,
tokensUsed: response.tokensUsed,
model: response.model,
},
});
// Update conversation stats
await this.prisma.conversation.update({
where: { id: conversationId },
data: {
messageCount: { increment: 2 },
totalTokens: { increment: response.tokensUsed },
},
});
// Store assistant response in vector memory
await this.memoryService.storeConversationMessage(`${conversation.character.name}: ${response.content}`, conversationId, { messageId: assistantMessage.id });
return { userMessage, assistantMessage };
}
async *streamMessage(conversationId: string, userId: string, sendMessageDto: SendMessageDto): AsyncGenerator<{ type: 'chunk' | 'message'; data: any }> {
const conversation = await this.findConversationById(conversationId, userId);
// Create user message
const userMessage = await this.prisma.message.create({
data: {
conversationId,
role: 'user',
content: sendMessageDto.content,
},
});
yield { type: 'message', data: { userMessage } };
// Store user message in vector memory
await this.memoryService.storeConversationMessage(`User: ${sendMessageDto.content}`, conversationId, { messageId: userMessage.id });
// Generate context from memory
const memoryContext = await this.memoryService.buildContextForConversation(conversationId, sendMessageDto.content, conversation.characterId);
// Build messages for LLM
const messages = this.buildLLMMessages(conversation.character.personalityPrompt, conversation.messages, sendMessageDto.content, memoryContext);
// Grouped debug logging
this.logger.debug(
`[streamMessage] conversation=${conversationId}\n` +
`--- Knowledges/Context ---\n${memoryContext || '(none)'}\n` +
`--- Full Messages to LLM ---\n` +
messages.map((msg, idx) => `[${idx}] ${msg.role}: ${msg.content.substring(0, 200)}${msg.content.length > 200 ? '...' : ''}`).join('\n'),
);
// Generate streaming response
let fullContent = '';
const stream = this.llmService.generateStream(messages, {
temperature: 0.7,
maxTokens: 2000,
});
for await (const chunk of stream) {
fullContent += chunk.content;
yield { type: 'chunk', data: chunk };
}
// Create assistant message
const assistantMessage = await this.prisma.message.create({
data: {
conversationId,
role: 'assistant',
content: fullContent,
model: process.env.LLM_MODEL || 'openai/gpt-4o',
},
});
// Update conversation stats
const tokensUsed = this.llmService.countTokens([...messages, { role: 'assistant', content: fullContent }]);
await this.prisma.conversation.update({
where: { id: conversationId },
data: {
messageCount: { increment: 2 },
totalTokens: { increment: tokensUsed },
},
});
// Store assistant response in vector memory
await this.memoryService.storeConversationMessage(`${conversation.character.name}: ${fullContent}`, conversationId, { messageId: assistantMessage.id });
yield { type: 'message', data: { assistantMessage } };
}
private buildLLMMessages(
personalityPrompt: string | null,
history: Message[],
currentMessage: string,
memoryContext: string,
): Array<{ role: 'system' | 'user' | 'assistant'; content: string }> {
const messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }> = [];
// Add system message with personality and context
let systemContent = `You are now role playing as the character based on the following personality description. You should use this information to inform your responses and stay in character. Always try to stay in character and provide responses that align with the personality and history provided. You are now talking to a user. The user will say something, and you will respond as the character. Remember this is a conversation, keep it talking like and maintain your character\n\n`;
if (personalityPrompt) {
systemContent = personalityPrompt;
}
if (memoryContext) {
systemContent += `\n\nUse the following context to inform your responses:\n${memoryContext}`;
}
messages.push({ role: 'system', content: systemContent });
// Add recent conversation history (last 10 messages)
const recentHistory = history.slice(-10);
for (const message of recentHistory) {
messages.push({
role: message.role.toLowerCase() as 'user' | 'assistant',
content: message.content,
});
}
// Add current message
messages.push({ role: 'user', content: currentMessage });
return messages;
}
}

View File

@@ -0,0 +1,25 @@
import { IsString, IsOptional } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class CreateConversationDto {
@ApiProperty({ description: 'Character ID to chat with', example: '550e8400-e29b-41d4-a716-446655440000' })
@IsString()
characterId: string;
@ApiPropertyOptional({ description: 'Conversation title', example: 'My Adventure with Alice' })
@IsOptional()
@IsString()
title?: string;
}
export class SendMessageDto {
@ApiProperty({ description: 'Message content', example: 'Hello! Tell me about yourself.' })
@IsString()
content: string;
}
export class UpdateMessageDto {
@ApiProperty({ description: 'Updated message content' })
@IsString()
content: string;
}

View File

@@ -0,0 +1,72 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { MessageRole } from '@prisma/client';
export class MessageResponseDto {
@ApiProperty({ description: 'Message ID' })
id: string;
@ApiProperty({ description: 'Message role', enum: MessageRole })
role: MessageRole;
@ApiProperty({ description: 'Message content' })
content: string;
@ApiPropertyOptional({ description: 'Tokens used' })
tokensUsed: number | null;
@ApiPropertyOptional({ description: 'Model used' })
model: string | null;
@ApiProperty({ description: 'Creation date' })
createdAt: Date;
}
export class CharacterSummaryDto {
@ApiProperty({ description: 'Character ID' })
id: string;
@ApiProperty({ description: 'Character name' })
name: string;
@ApiPropertyOptional({ description: 'Avatar URL' })
avatarUrl: string | null;
}
export class ConversationResponseDto {
@ApiProperty({ description: 'Conversation ID' })
id: string;
@ApiPropertyOptional({ description: 'Conversation title' })
title: string | null;
@ApiProperty({ description: 'Character ID' })
characterId: string;
@ApiProperty({ description: 'Number of messages' })
messageCount: number;
@ApiProperty({ description: 'Total tokens used' })
totalTokens: number;
@ApiProperty({ description: 'Creation date' })
createdAt: Date;
@ApiProperty({ description: 'Last update date' })
updatedAt: Date;
@ApiPropertyOptional({ description: 'Character info', type: CharacterSummaryDto })
character?: CharacterSummaryDto;
}
export class ConversationWithMessagesResponseDto extends ConversationResponseDto {
@ApiProperty({ description: 'Messages in conversation', type: [MessageResponseDto] })
messages: MessageResponseDto[];
}
export class SendMessageResponseDto {
@ApiProperty({ description: 'User message', type: MessageResponseDto })
userMessage: MessageResponseDto;
@ApiProperty({ description: 'Assistant response', type: MessageResponseDto })
assistantMessage: MessageResponseDto;
}

View File

@@ -0,0 +1,10 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
export const CurrentUser = createParamDecorator(
(data: keyof any | undefined, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const user = request.user;
return data ? user?.[data] : user;
},
);

View File

@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';
export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);

View File

@@ -0,0 +1 @@
export { RequestLoggerMiddleware } from './request-logger.middleware';

View File

@@ -0,0 +1,62 @@
import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class RequestLoggerMiddleware implements NestMiddleware {
private logger = new Logger('HTTP');
private readonly isEnabled: boolean;
private readonly logLevel: 'verbose' | 'standard' | 'minimal';
constructor() {
this.isEnabled = process.env.REQUEST_LOGGER !== 'false';
const level = process.env.REQUEST_LOGGER_LEVEL;
this.logLevel = level === 'verbose' || level === 'minimal' ? level : 'standard';
}
use(req: Request, res: Response, next: NextFunction) {
if (!this.isEnabled) {
return next();
}
const { method, originalUrl, ip, headers } = req;
const userAgent = headers['user-agent'] || 'unknown';
const startTime = Date.now();
// Log request start (verbose only)
if (this.logLevel === 'verbose') {
this.logger.log(`${method} ${originalUrl} - ${ip} - ${userAgent}`);
}
// Capture response finish
res.on('finish', () => {
const duration = Date.now() - startTime;
const statusCode = res.statusCode;
const contentLength = res.get('content-length') || 0;
// Build message based on log level
let message: string;
switch (this.logLevel) {
case 'verbose':
message = `${method} ${originalUrl} ${statusCode} - ${duration}ms - ${contentLength}b - ${ip}`;
break;
case 'minimal':
message = `${method} ${originalUrl} ${statusCode}`;
break;
default: // standard
message = `${method} ${originalUrl} ${statusCode} - ${duration}ms`;
break;
}
// Determine log level based on status code
if (statusCode >= 500) {
this.logger.error(message);
} else if (statusCode >= 400) {
this.logger.warn(message);
} else {
this.logger.log(message);
}
});
next();
}
}

View File

@@ -0,0 +1,40 @@
import { IImportAdapter, ImportResult } from '../interfaces/import-adapter.interface';
export class TextFileAdapter implements IImportAdapter {
private readonly supportedMimeTypes = [
'text/plain',
'text/markdown',
'text/x-markdown',
'application/octet-stream',
];
private readonly supportedExtensions = ['.txt', '.md', '.markdown'];
canHandle(file: Express.Multer.File): boolean {
// Check MIME type
if (this.supportedMimeTypes.includes(file.mimetype)) {
return true;
}
// Check file extension
const ext = file.originalname.toLowerCase().slice(file.originalname.lastIndexOf('.'));
if (this.supportedExtensions.includes(ext)) {
return true;
}
return false;
}
async parse(file: Express.Multer.File): Promise<ImportResult> {
const content = file.buffer.toString('utf-8');
return {
content,
metadata: {
sourceName: file.originalname,
mimeType: file.mimetype,
fileSize: file.size,
},
};
}
}

View File

@@ -0,0 +1,134 @@
import {
Controller,
Post,
Get,
Delete,
Param,
Body,
UploadedFile,
UseInterceptors,
BadRequestException,
Logger,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiParam, ApiConsumes, ApiBody, ApiProperty } from '@nestjs/swagger';
import { ImportService } from './import.service';
import { CurrentUser } from '../common/decorators/current-user.decorator';
import { CharacterKnowledge } from '@prisma/client';
class UploadResponseDto {
@ApiProperty({ description: 'Knowledge ID' })
knowledgeId: string;
@ApiProperty({ description: 'Status message' })
message: string;
}
class ImportUrlDto {
@ApiProperty({ description: 'URL to import', example: 'https://sakurazaka46.com/s/s46/diary/detail/68008' })
url: string;
}
@ApiTags('import')
@ApiBearerAuth()
@Controller('import')
export class ImportController {
private readonly logger = new Logger(ImportController.name);
constructor(private importService: ImportService) {}
@Post('characters/:characterId/files')
@ApiOperation({ summary: 'Upload a file for character knowledge' })
@ApiParam({ name: 'characterId', description: 'Character ID' })
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
properties: {
file: {
type: 'string',
format: 'binary',
description: 'File to upload (.txt, .md)',
},
},
},
})
@ApiResponse({ status: 201, description: 'File uploaded and processing' })
@ApiResponse({ status: 400, description: 'Invalid file type' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@UseInterceptors(FileInterceptor('file'))
async uploadFile(
@Param('characterId') characterId: string,
@UploadedFile() file: Express.Multer.File,
@CurrentUser('userId') userId: string,
): Promise<UploadResponseDto> {
if (!file) {
throw new BadRequestException('No file uploaded');
}
return this.importService.uploadFile(file, characterId, userId);
}
@Get('knowledge/:knowledgeId/status')
@ApiOperation({ summary: 'Get knowledge processing status' })
@ApiParam({ name: 'knowledgeId', description: 'Knowledge ID' })
@ApiResponse({ status: 200, description: 'Knowledge status' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 404, description: 'Knowledge not found' })
async getKnowledgeStatus(
@Param('knowledgeId') knowledgeId: string,
@CurrentUser('userId') userId: string,
): Promise<CharacterKnowledge> {
return this.importService.getKnowledgeStatus(knowledgeId, userId);
}
@Get('characters/:characterId/knowledge')
@ApiOperation({ summary: 'Get all knowledge for a character' })
@ApiParam({ name: 'characterId', description: 'Character ID' })
@ApiResponse({ status: 200, description: 'List of knowledge' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
async getCharacterKnowledge(
@Param('characterId') characterId: string,
@CurrentUser('userId') userId: string,
): Promise<CharacterKnowledge[]> {
return this.importService.getCharacterKnowledge(characterId, userId);
}
@Delete('knowledge/:knowledgeId')
@ApiOperation({ summary: 'Delete knowledge' })
@ApiParam({ name: 'knowledgeId', description: 'Knowledge ID' })
@ApiResponse({ status: 200, description: 'Knowledge deleted' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 404, description: 'Knowledge not found' })
async deleteKnowledge(
@Param('knowledgeId') knowledgeId: string,
@CurrentUser('userId') userId: string,
): Promise<{ message: string }> {
await this.importService.deleteKnowledge(knowledgeId, userId);
return { message: 'Knowledge deleted successfully' };
}
@Post('characters/:characterId/url')
@ApiOperation({ summary: 'Import content from URL for character knowledge' })
@ApiParam({ name: 'characterId', description: 'Character ID' })
@ApiBody({ type: ImportUrlDto })
@ApiResponse({ status: 201, description: 'URL content is being imported and processed', type: UploadResponseDto })
@ApiResponse({ status: 400, description: 'Invalid URL or unsupported website' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
async importFromUrl(
@Param('characterId') characterId: string,
@Body() importUrlDto: ImportUrlDto,
@CurrentUser('userId') userId: string,
): Promise<UploadResponseDto> {
this.logger.log(`Received URL import request for character: ${characterId}, url: ${importUrlDto.url}`);
if (!importUrlDto.url) {
this.logger.warn('URL import request rejected: URL is required');
throw new BadRequestException('URL is required');
}
const result = await this.importService.importFromUrl(importUrlDto.url, characterId, userId);
this.logger.log(`URL import started, knowledgeId: ${result.knowledgeId}`);
return result;
}
}

View File

@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { ImportService } from './import.service';
import { ImportController } from './import.controller';
import { VectorModule } from '../vector/vector.module';
@Module({
imports: [VectorModule],
providers: [ImportService],
controllers: [ImportController],
exports: [ImportService],
})
export class ImportModule {}

View File

@@ -0,0 +1,449 @@
import { Injectable, BadRequestException, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { MemoryService } from '../vector/memory.service';
import { TextFileAdapter } from './adapters/text-file.adapter';
import { IImportAdapter, ImportResult } from './interfaces/import-adapter.interface';
import { IWebScraper, WebScraperResult } from './interfaces/web-scraper.interface';
import { SakurazakaScraper } from './scrapers/sakurazaka-scraper';
@Injectable()
export class ImportService {
private readonly logger = new Logger(ImportService.name);
private adapters: IImportAdapter[];
private scrapers: IWebScraper[];
constructor(
private prisma: PrismaService,
private memoryService: MemoryService,
) {
this.adapters = [new TextFileAdapter()];
this.scrapers = [new SakurazakaScraper()];
}
async uploadFile(
file: Express.Multer.File,
characterId: string,
userId: string,
): Promise<{ knowledgeId: string; message: string }> {
// Find appropriate adapter
const adapter = this.adapters.find((a) => a.canHandle(file));
if (!adapter) {
throw new BadRequestException(
`Unsupported file type: ${file.mimetype}. Supported types: .txt, .md`,
);
}
// Parse the file
const result = await adapter.parse(file);
// Reject if content is too large
const maxRawContentLength = 100000;
if (result.content.length > maxRawContentLength) {
throw new BadRequestException(
`File too large: ${result.content.length} characters (max: ${maxRawContentLength}). Please use a smaller file.`
);
}
// Create knowledge entry
const knowledge = await this.prisma.characterKnowledge.create({
data: {
name: file.originalname,
sourceType: 'file',
sourceName: file.originalname,
mimeType: file.mimetype,
fileSize: BigInt(file.size),
rawContent: result.content,
status: 'processing',
processingInfo: result.metadata,
characterId,
},
});
// Process the content in the background
this.logger.log(`[${knowledge.id}] Starting background processing for file upload, character: ${characterId}`);
this.processContent(knowledge.id, characterId, result).catch((error) => {
this.logger.error(`[${knowledge.id}] Error processing file import:`, error);
});
return {
knowledgeId: knowledge.id,
message: 'File uploaded and is being processed',
};
}
async getKnowledgeStatus(knowledgeId: string, userId: string) {
const knowledge = await this.prisma.characterKnowledge.findFirst({
where: {
id: knowledgeId,
character: {
userId,
},
},
include: {
character: {
select: {
id: true,
name: true,
},
},
},
});
if (!knowledge) {
throw new BadRequestException('Knowledge not found');
}
return knowledge;
}
async deleteKnowledge(knowledgeId: string, userId: string): Promise<void> {
const knowledge = await this.prisma.characterKnowledge.findFirst({
where: {
id: knowledgeId,
character: {
userId,
},
},
});
if (!knowledge) {
throw new BadRequestException('Knowledge not found');
}
// Delete associated vector memories
await this.memoryService['vectorStore'].deleteByKnowledge(knowledgeId);
// Delete the knowledge entry
await this.prisma.characterKnowledge.delete({
where: { id: knowledgeId },
});
}
async getCharacterKnowledge(characterId: string, userId: string) {
// Verify user owns the character
const character = await this.prisma.character.findFirst({
where: {
id: characterId,
userId,
},
});
if (!character) {
throw new BadRequestException('Character not found');
}
return this.prisma.characterKnowledge.findMany({
where: { characterId },
orderBy: { createdAt: 'desc' },
});
}
private async processContent(
knowledgeId: string,
characterId: string,
result: ImportResult,
): Promise<void> {
this.logger.log(`[${knowledgeId}] Starting processContent, content length: ${result.content.length}`);
// Reduce memory pressure by limiting content size more aggressively
const maxContentLength = 15000; // Reduced from 30000
let content = result.content;
if (content.length > maxContentLength) {
this.logger.warn(`[${knowledgeId}] Content truncated from ${content.length} to ${maxContentLength} characters`);
content = content.substring(0, maxContentLength) + '\n\n[Content truncated due to size limits]';
}
// Process chunks one at a time using generator to minimize memory usage
const chunkSize = 800; // Reduced from 1000
const overlap = 100; // Reduced from 200
const maxChunks = 20; // Reduced from 30
let processedChunks = 0;
let totalChunks = 0;
let start = 0;
try {
this.logger.log(`[${knowledgeId}] Processing chunks with streaming approach...`);
while (start < content.length && processedChunks < maxChunks) {
// Calculate chunk boundaries
const end = Math.min(start + chunkSize, content.length);
let chunkEnd = end;
// Try to break at a sentence boundary (only if not at end)
if (end < content.length) {
const chunk = content.slice(start, end);
const lastPeriod = chunk.lastIndexOf('.');
const lastNewline = chunk.lastIndexOf('\n');
const breakPoint = Math.max(lastPeriod, lastNewline);
if (breakPoint > chunkSize * 0.5) {
chunkEnd = start + breakPoint + 1;
}
}
// Extract the chunk
const chunk = content.slice(start, chunkEnd).trim();
if (chunk.length > 0) {
totalChunks++;
if (processedChunks < maxChunks) {
this.logger.debug(`[${knowledgeId}] Processing chunk ${processedChunks + 1} (${chunk.length} chars)...`);
try {
await this.memoryService.storeCharacterKnowledge(
chunk,
characterId,
knowledgeId,
{
...result.metadata,
chunkIndex: processedChunks,
},
);
processedChunks++;
this.logger.debug(`[${knowledgeId}] Chunk ${processedChunks} stored successfully`);
} catch (chunkError) {
this.logger.error(`[${knowledgeId}] Failed to store chunk ${processedChunks + 1}:`, chunkError);
throw chunkError;
}
// Force garbage collection opportunity between chunks
if (processedChunks % 2 === 0) {
await new Promise((resolve) => setTimeout(resolve, 150));
}
}
}
// Move to next chunk position
const nextStart = start + (chunkEnd - start) - overlap;
if (nextStart <= start) break; // Prevent infinite loop
start = nextStart;
}
this.logger.log(`[${knowledgeId}] Processed ${processedChunks}/${totalChunks} chunks, updating status to completed`);
// Update status to completed
await this.prisma.characterKnowledge.update({
where: { id: knowledgeId },
data: {
status: 'completed',
processingInfo: {
...result.metadata,
chunksProcessed: processedChunks,
originalChunks: totalChunks,
wasTruncated: result.content.length > maxContentLength || totalChunks > maxChunks,
},
},
});
this.logger.log(`[${knowledgeId}] Processing completed successfully`);
} catch (error) {
this.logger.error(`[${knowledgeId}] Error in processContent:`, error);
// Update status to failed
try {
await this.prisma.characterKnowledge.update({
where: { id: knowledgeId },
data: {
status: 'failed',
processingInfo: {
...result.metadata,
error: error instanceof Error ? error.message : 'Unknown error',
},
},
});
this.logger.log(`[${knowledgeId}] Status updated to failed`);
} catch (dbError) {
this.logger.error(`[${knowledgeId}] Failed to update status to failed:`, dbError);
}
throw error;
}
}
async importFromUrl(
url: string,
characterId: string,
userId: string,
): Promise<{ knowledgeId: string; message: string }> {
// Validate URL format
let urlObj: URL;
try {
urlObj = new URL(url);
} catch {
throw new BadRequestException('Invalid URL format');
}
// Find appropriate scraper
const scraper = this.scrapers.find((s) => s.canHandle(url));
if (!scraper) {
throw new BadRequestException(
`Unsupported URL: ${urlObj.hostname}. No scraper available for this website.`,
);
}
// Scrape the content
const result = await scraper.scrape(url);
// Reject if content is too large
const maxRawContentLength = 100000;
if (result.content.length > maxRawContentLength) {
throw new BadRequestException(
`Content too large: ${result.content.length} characters (max: ${maxRawContentLength}). Please use a shorter article.`
);
}
// Create knowledge entry
const knowledgeName = result.metadata.title || `Import from ${urlObj.hostname}`;
const knowledge = await this.prisma.characterKnowledge.create({
data: {
name: knowledgeName,
sourceType: 'url',
sourceName: url,
mimeType: 'text/html',
rawContent: result.content,
status: 'processing',
processingInfo: result.metadata,
characterId,
},
});
// Process the content in the background
this.logger.log(`[${knowledge.id}] Starting background processing for URL: ${url}, character: ${characterId}`);
this.processScrapedContent(knowledge.id, characterId, result).catch((error) => {
this.logger.error(`[${knowledge.id}] Error processing URL import:`, error);
});
return {
knowledgeId: knowledge.id,
message: 'URL content is being imported and processed',
};
}
private async processScrapedContent(
knowledgeId: string,
characterId: string,
result: WebScraperResult,
): Promise<void> {
this.logger.log(`[${knowledgeId}] Starting processScrapedContent, content length: ${result.content.length}`);
// Reduce memory pressure by limiting content size more aggressively
const maxContentLength = 15000; // Reduced from 30000
let content = result.content;
if (content.length > maxContentLength) {
this.logger.warn(`[${knowledgeId}] Content truncated from ${content.length} to ${maxContentLength} characters`);
content = content.substring(0, maxContentLength) + '\n\n[Content truncated due to size limits]';
}
// Process chunks one at a time using streaming approach to minimize memory usage
const chunkSize = 800; // Reduced from 1000
const overlap = 100; // Reduced from 200
const maxChunks = 20; // Reduced from 30
let processedChunks = 0;
let totalChunks = 0;
let start = 0;
try {
this.logger.log(`[${knowledgeId}] Processing chunks with streaming approach...`);
while (start < content.length && processedChunks < maxChunks) {
// Calculate chunk boundaries
const end = Math.min(start + chunkSize, content.length);
let chunkEnd = end;
// Try to break at a sentence boundary (only if not at end)
if (end < content.length) {
const chunk = content.slice(start, end);
const lastPeriod = chunk.lastIndexOf('.');
const lastNewline = chunk.lastIndexOf('\n');
const breakPoint = Math.max(lastPeriod, lastNewline);
if (breakPoint > chunkSize * 0.5) {
chunkEnd = start + breakPoint + 1;
}
}
// Extract the chunk
const chunk = content.slice(start, chunkEnd).trim();
if (chunk.length > 0) {
totalChunks++;
if (processedChunks < maxChunks) {
this.logger.debug(`[${knowledgeId}] Processing chunk ${processedChunks + 1} (${chunk.length} chars)...`);
try {
await this.memoryService.storeCharacterKnowledge(
chunk,
characterId,
knowledgeId,
{
...result.metadata,
chunkIndex: processedChunks,
},
);
processedChunks++;
this.logger.debug(`[${knowledgeId}] Chunk ${processedChunks} stored successfully`);
} catch (chunkError) {
this.logger.error(`[${knowledgeId}] Failed to store chunk ${processedChunks + 1}:`, chunkError);
throw chunkError;
}
// Force garbage collection opportunity between chunks
if (processedChunks % 2 === 0) {
await new Promise((resolve) => setTimeout(resolve, 150));
}
}
}
// Move to next chunk position
const nextStart = start + (chunkEnd - start) - overlap;
if (nextStart <= start) break; // Prevent infinite loop
start = nextStart;
}
this.logger.log(`[${knowledgeId}] Processed ${processedChunks}/${totalChunks} chunks, updating status to completed`);
// Update status to completed
await this.prisma.characterKnowledge.update({
where: { id: knowledgeId },
data: {
status: 'completed',
processingInfo: {
...result.metadata,
chunksProcessed: processedChunks,
originalChunks: totalChunks,
wasTruncated: result.content.length > maxContentLength || totalChunks > maxChunks,
},
},
});
this.logger.log(`[${knowledgeId}] Processing completed successfully`);
} catch (error) {
this.logger.error(`[${knowledgeId}] Error in processScrapedContent:`, error);
// Update status to failed
try {
await this.prisma.characterKnowledge.update({
where: { id: knowledgeId },
data: {
status: 'failed',
processingInfo: {
...result.metadata,
error: error instanceof Error ? error.message : 'Unknown error',
},
},
});
this.logger.log(`[${knowledgeId}] Status updated to failed`);
} catch (dbError) {
this.logger.error(`[${knowledgeId}] Failed to update status to failed:`, dbError);
}
throw error;
}
}
}

View File

@@ -0,0 +1,14 @@
export interface ImportResult {
content: string;
metadata: {
sourceName: string;
mimeType: string;
fileSize?: number;
[key: string]: any;
};
}
export interface IImportAdapter {
canHandle(file: Express.Multer.File): boolean;
parse(file: Express.Multer.File): Promise<ImportResult>;
}

View File

@@ -0,0 +1,2 @@
export { IImportAdapter, ImportResult } from './import-adapter.interface';
export { IWebScraper, WebScraperResult } from './web-scraper.interface';

View File

@@ -0,0 +1,23 @@
export interface WebScraperResult {
content: string;
metadata: {
sourceName: string;
url: string;
title?: string;
author?: string;
publishedDate?: string;
[key: string]: any;
};
}
export interface IWebScraper {
/**
* Check if this scraper can handle the given URL
*/
canHandle(url: string): boolean;
/**
* Scrape content from the URL
*/
scrape(url: string): Promise<WebScraperResult>;
}

View File

@@ -0,0 +1 @@
export { SakurazakaScraper } from './sakurazaka-scraper';

View File

@@ -0,0 +1,337 @@
import { SakurazakaScraper } from './sakurazaka-scraper';
describe('SakurazakaScraper', () => {
let scraper: SakurazakaScraper;
beforeEach(() => {
scraper = new SakurazakaScraper();
});
describe('canHandle', () => {
it('should return true for sakurazaka46.com URLs', () => {
const urls = [
'https://sakurazaka46.com/s/s46/diary/detail/68008',
'https://sakurazaka46.com/s/s46/diary/detail/68008?ima=0000&cd=blog',
'https://www.sakurazaka46.com/s/s46/diary/detail/10000',
'https://sakurazaka46.com/s/s46/diary/blog/list',
];
urls.forEach((url) => {
expect(scraper.canHandle(url)).toBe(true);
});
});
it('should return false for non-sakurazaka46.com URLs', () => {
const urls = [
'https://example.com/blog/123',
'https://nogizaka46.com/s/n46/diary/detail/12345',
'https://hinatazaka46.com/s/h46/diary/detail/12345',
'https://sakurazaka46.net/fake/blog/123',
'not-a-url',
'',
];
urls.forEach((url) => {
expect(scraper.canHandle(url)).toBe(false);
});
});
it('should return false for invalid URLs', () => {
expect(scraper.canHandle('invalid-url')).toBe(false);
expect(scraper.canHandle('')).toBe(false);
});
});
describe('scrape', () => {
const mockBlogHtml = `
<article class="post wovn-ignore">
<div class="col-l widfix-sp">
<div class="com-calendindinav">
<div class="wrap-bg">
<div class="inner">
<div class="year-month">
<div class="ym-inner wf-a">
<div class="ym-txt">
<span class="ym-year">2026</span>
<span class="ym-month">2</span>
</div>
<p class="date wf-a">18</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-r widfix-sp">
<div class="inner title-wrap"><h1 class="title">The growing up train</h1></div>
</div>
<div class="col-l eigo-wrap pc">
<div class="eigo-inner">
<p class="eigo wf-a">YU MURAI</p>
</div>
</div>
<div class="col-r">
<div class="box-article">
<p><br/><br/>こんばんは<br/><br/>14thシングル<br/><br/>嬉しいです</p>
<p>四期生は肝が据わっています!<br/></p>
<img src="/files/14/diary/s46/blog/moblog/202602/mobpqiCQR.jpg"/>
<p>またね〜<br/>村井優</p>
</div>
<div class="blog-foot-nav">
<div class="com-btn-lcr">
<p class="btn-type1s"><a href="/s/s46/diary/detail/67798">前へ</a></p>
<p class="btn-type3"><a href="/s/s46/diary/blog/list?ct=67">村井 優のブログ一覧</a></p>
</div>
</div>
<div class="app-button">
<div class="box-a">
<p class="app-title">櫻坂46メッセージ</p>
</div>
</div>
</div>
</article>
`;
beforeEach(() => {
global.fetch = jest.fn();
});
afterEach(() => {
jest.resetAllMocks();
});
it('should successfully scrape blog content', async () => {
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
text: () => Promise.resolve(mockBlogHtml),
});
const result = await scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/68008');
expect(result.content).toContain('Title: The growing up train');
expect(result.content).toContain('Author: YU MURAI');
expect(result.content).toContain('Date: 2026-02-18');
expect(result.content).toContain('こんばんは');
expect(result.content).toContain('[Image: mobpqiCQR.jpg]');
expect(result.content).toContain('またね〜');
expect(result.content).toContain('村井優');
});
it('should extract correct metadata', async () => {
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
text: () => Promise.resolve(mockBlogHtml),
});
const result = await scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/68008');
expect(result.metadata).toEqual({
sourceName: 'Sakurazaka46 Blog',
url: 'https://sakurazaka46.com/s/s46/diary/detail/68008',
title: 'The growing up train',
author: 'YU MURAI',
publishedDate: '2026-02-18',
blogId: '68008',
});
});
it('should handle blog posts without title gracefully', async () => {
const htmlWithoutTitle = mockBlogHtml.replace(
/<h1 class="title">[^<]*<\/h1>/,
''
);
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
text: () => Promise.resolve(htmlWithoutTitle),
});
const result = await scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/68008');
expect(result.metadata.title).toBeFalsy();
});
it('should handle blog posts without author gracefully', async () => {
const htmlWithoutAuthor = mockBlogHtml.replace(
/<p class="eigo wf-a">[^<]*<\/p>/,
''
);
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
text: () => Promise.resolve(htmlWithoutAuthor),
});
const result = await scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/68008');
expect(result.metadata.author).toBeFalsy();
});
it('should handle HTTP errors', async () => {
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: false,
status: 404,
statusText: 'Not Found',
});
await expect(
scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/99999')
).rejects.toThrow('Failed to fetch page: 404 Not Found');
});
it('should handle network errors', async () => {
(global.fetch as jest.Mock).mockRejectedValueOnce(new Error('Network error'));
await expect(
scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/68008')
).rejects.toThrow('Failed to scrape Sakurazaka46 blog: Network error');
});
it('should handle missing article element', async () => {
const htmlWithoutArticle = '<div>No article here</div>';
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
text: () => Promise.resolve(htmlWithoutArticle),
});
await expect(
scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/68008')
).rejects.toThrow('Failed to scrape Sakurazaka46 blog: Could not find article content in the page');
});
it('should handle blog ID extraction from various URL formats', async () => {
(global.fetch as jest.Mock).mockResolvedValue({
ok: true,
text: () => Promise.resolve(mockBlogHtml),
});
const testCases = [
{ url: 'https://sakurazaka46.com/s/s46/diary/detail/68008', expectedId: '68008' },
{ url: 'https://sakurazaka46.com/s/s46/diary/detail/68008?ima=0000&cd=blog', expectedId: '68008' },
{ url: 'https://sakurazaka46.com/s/s46/diary/detail/12345#anchor', expectedId: '12345' },
];
for (const { url, expectedId } of testCases) {
const result = await scraper.scrape(url);
expect(result.metadata.blogId).toBe(expectedId);
}
});
it('should clean up HTML entities and tags properly', async () => {
const htmlWithEntities = `
<article>
<h1 class="title">Test &amp; Example</h1>
<div class="box-article">
<p>Hello&nbsp;world &lt;script&gt;alert(1)&lt;/script&gt;</p>
<p>Line 1<br/>Line 2</p>
</div>
</article>
`;
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
text: () => Promise.resolve(htmlWithEntities),
});
const result = await scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/1');
expect(result.content).toContain('Test & Example');
expect(result.content).toContain('Hello world');
expect(result.content).not.toContain('&nbsp;');
expect(result.content).not.toContain('&lt;script&gt;');
expect(result.content).not.toContain('<br/>');
});
it('should remove navigation and footer sections', async () => {
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
text: () => Promise.resolve(mockBlogHtml),
});
const result = await scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/68008');
// Navigation elements should not be in the content
expect(result.content).not.toContain('前へ');
expect(result.content).not.toContain('村井 優のブログ一覧');
expect(result.content).not.toContain('櫻坂46メッセージ');
expect(result.content).not.toContain('blog-foot-nav');
expect(result.content).not.toContain('app-button');
});
it('should handle multiple images in blog post', async () => {
const htmlWithMultipleImages = `
<article>
<h1 class="title">Multi Image Post</h1>
<div class="box-article">
<img src="/files/image1.jpg"/>
<p>Text between images</p>
<img src="/files/image2.png"/>
<img src="/files/image3.gif"/>
<p>After images text</p>
</div>
</article>
`;
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
text: () => Promise.resolve(htmlWithMultipleImages),
});
const result = await scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/1');
expect(result.content).toContain('[Image: image1.jpg]');
expect(result.content).toContain('[Image: image2.png]');
expect(result.content).toContain('[Image: image3.gif]');
expect(result.content).toContain('Text between images');
expect(result.content).toContain('After images text');
});
it('should extract all images from complex blog structure', async () => {
const htmlWithComplexImages = `
<article class="post">
<div class="col-r">
<div class="box-article">
<p><img src="/files/14/diary/blog1.jpg"/></p>
<p>First paragraph</p>
<p><img src="/files/14/diary/blog2.jpg"/><br/><img src="/files/14/diary/blog3.jpg"/></p>
<p>Second paragraph with <img src="/files/14/diary/blog4.jpg"/> inline image</p>
</div>
</div>
</article>
`;
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
text: () => Promise.resolve(htmlWithComplexImages),
});
const result = await scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/1');
expect(result.content).toContain('[Image: blog1.jpg]');
expect(result.content).toContain('[Image: blog2.jpg]');
expect(result.content).toContain('[Image: blog3.jpg]');
expect(result.content).toContain('[Image: blog4.jpg]');
expect(result.content).toContain('First paragraph');
expect(result.content).toContain('Second paragraph');
});
it('should set correct User-Agent header', async () => {
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
text: () => Promise.resolve(mockBlogHtml),
});
await scraper.scrape('https://sakurazaka46.com/s/s46/diary/detail/68008');
expect(global.fetch).toHaveBeenCalledWith(
'https://sakurazaka46.com/s/s46/diary/detail/68008',
expect.objectContaining({
headers: expect.objectContaining({
'User-Agent': expect.stringContaining('Mozilla/5.0'),
}),
})
);
});
});
});

View File

@@ -0,0 +1,238 @@
import { Logger } from '@nestjs/common';
import { IWebScraper, WebScraperResult } from '../interfaces/web-scraper.interface';
/**
* Web scraper for Sakurazaka46 blog posts
* Handles URLs like: https://sakurazaka46.com/s/s46/diary/detail/{id}
*/
export class SakurazakaScraper implements IWebScraper {
private readonly logger = new Logger(SakurazakaScraper.name);
private readonly baseUrl = 'sakurazaka46.com';
canHandle(url: string): boolean {
try {
const urlObj = new URL(url);
return (
urlObj.hostname === this.baseUrl ||
urlObj.hostname === `www.${this.baseUrl}`
);
} catch {
return false;
}
}
async scrape(url: string): Promise<WebScraperResult> {
this.logger.log(`Starting to scrape URL: ${url}`);
try {
// Fetch the page content
this.logger.debug(`Fetching page content from: ${url}`);
const response = await fetch(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
},
});
if (!response.ok) {
this.logger.error(`Failed to fetch page: ${response.status} ${response.statusText}`);
throw new Error(`Failed to fetch page: ${response.status} ${response.statusText}`);
}
this.logger.debug(`Page fetched successfully, reading content...`);
const html = await response.text();
this.logger.debug(`HTML content received: ${html.length} bytes`);
// Extract content
this.logger.debug('Extracting content from HTML...');
const content = this.extractContent(html);
this.logger.log(`Content extracted: ${content.length} characters`);
const metadata = this.extractMetadata(html, url);
this.logger.log(`Metadata extracted:`, metadata);
return {
content,
metadata,
};
} catch (error) {
this.logger.error(`Failed to scrape Sakurazaka46 blog:`, error);
throw new Error(
`Failed to scrape Sakurazaka46 blog: ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
}
private extractContent(html: string): string {
// Find the article element
const articleMatch = html.match(/<article[^>]*>([\s\S]*?)<\/article>/i);
if (!articleMatch) {
throw new Error('Could not find article content in the page');
}
const article = articleMatch[0];
const parts: string[] = [];
// Extract title
const titleMatch = article.match(/<h1[^>]*class="[^"]*title[^"]*"[^>]*>([\s\S]*?)<\/h1>/i);
if (titleMatch) {
const title = this.stripHtml(titleMatch[1]).trim();
if (title) parts.push(`Title: ${title}`);
}
// Extract author
const authorMatch = article.match(/<p[^>]*class="[^"]*eigo[^"]*"[^>]*>([\s\S]*?)<\/p>/i);
if (authorMatch) {
const author = this.stripHtml(authorMatch[1]).trim();
if (author) parts.push(`Author: ${author}`);
}
// Extract date from the calendar structure
const yearMatch = article.match(/<span[^>]*class="[^"]*ym-year[^"]*"[^>]*>([\s\S]*?)<\/span>/i);
const monthMatch = article.match(/<span[^>]*class="[^"]*ym-month[^"]*"[^>]*>([\s\S]*?)<\/span>/i);
const dayMatch = article.match(/<p[^>]*class="[^"]*date[^"]*"[^>]*>([\s\S]*?)<\/p>/i);
if (yearMatch && monthMatch && dayMatch) {
const year = this.stripHtml(yearMatch[1]).trim();
const month = this.stripHtml(monthMatch[1]).trim();
const day = this.stripHtml(dayMatch[1]).trim();
parts.push(`Date: ${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`);
}
// Extract main content from box-article
// Find box-article and capture until we hit navigation sections
const boxMatch = article.match(/<div[^>]*class="[^"]*box-article[^"]*"[^>]*>([\s\S]*)$/i);
if (boxMatch) {
let content = boxMatch[1];
// Find where navigation starts and cut there
const navIndex = content.search(/<div[^>]*class="[^"]*col-l[^"]*"[^>]*>/i);
if (navIndex !== -1) {
content = content.substring(0, navIndex);
}
// Also cut at app-button section
const appIndex = content.search(/<div[^>]*class="[^"]*app-button[^"]*"/i);
if (appIndex !== -1) {
content = content.substring(0, appIndex);
}
const mainContent = this.cleanBlogContent(content);
if (mainContent) {
parts.push('');
parts.push(mainContent);
}
}
return parts.join('\n');
}
private extractMetadata(html: string, url: string): WebScraperResult['metadata'] {
const metadata: WebScraperResult['metadata'] = {
sourceName: 'Sakurazaka46 Blog',
url,
};
// Extract title
const titleMatch = html.match(/<h1[^>]*class="[^"]*title[^"]*"[^>]*>([\s\S]*?)<\/h1>/i);
if (titleMatch) {
metadata.title = this.stripHtml(titleMatch[1]).trim();
}
// Extract author
const authorMatch = html.match(/<p[^>]*class="[^"]*eigo[^"]*"[^>]*>([\s\S]*?)<\/p>/i);
if (authorMatch) {
metadata.author = this.stripHtml(authorMatch[1]).trim();
}
// Extract date
const yearMatch = html.match(/<span[^>]*class="[^"]*ym-year[^"]*"[^>]*>([\s\S]*?)<\/span>/i);
const monthMatch = html.match(/<span[^>]*class="[^"]*ym-month[^"]*"[^>]*>([\s\S]*?)<\/span>/i);
const dayMatch = html.match(/<p[^>]*class="[^"]*date[^"]*"[^>]*>([\s\S]*?)<\/p>/i);
if (yearMatch && monthMatch && dayMatch) {
const year = this.stripHtml(yearMatch[1]).trim();
const month = this.stripHtml(monthMatch[1]).trim().padStart(2, '0');
const day = this.stripHtml(dayMatch[1]).trim().padStart(2, '0');
metadata.publishedDate = `${year}-${month}-${day}`;
}
// Extract blog ID from URL
const idMatch = url.match(/detail\/(\d+)/);
if (idMatch) {
metadata.blogId = idMatch[1];
}
return metadata;
}
private stripHtml(html: string): string {
return html
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p>/gi, '\n')
.replace(/<[^>]+>/g, '')
.replace(/&nbsp;/g, ' ')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.trim();
}
private cleanBlogContent(html: string): string {
// Remove HTML comments
html = html.replace(/<!--[\s\S]*?-->/g, '');
// Remove blog navigation/footer section
html = html.replace(/<div[^>]*class="[^"]*blog-foot-nav[^"]*"[\s\S]*$/i, '');
// Remove app button section
html = html.replace(/<div[^>]*class="[^"]*app-button[^"]*"[\s\S]*$/i, '');
// Remove script and style tags
let cleaned = html
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '');
// Convert <br> tags to newlines
cleaned = cleaned.replace(/<br\s*\/?>/gi, '\n');
// Handle image tags - convert to descriptive text
cleaned = cleaned.replace(/<img[^>]*src="([^"]*)"[^>]*>/gi, (match, src) => {
// Extract filename from src
const filename = src.split('/').pop();
return `\n[Image: ${filename}]\n`;
});
// Convert paragraph closings to double newlines
cleaned = cleaned.replace(/<\/p>/gi, '\n\n');
// Convert div closings to single newlines
cleaned = cleaned.replace(/<\/div>/gi, '\n');
// Remove remaining HTML tags
cleaned = cleaned.replace(/<[^>]+>/g, '');
// Decode HTML entities
cleaned = cleaned
.replace(/&nbsp;/g, ' ')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'");
// Clean up excessive whitespace
cleaned = cleaned
.replace(/\n{4,}/g, '\n\n\n')
.trim();
// Remove trailing empty image references
cleaned = cleaned.replace(/\n*\[Image:[^\]]*\]\s*$/g, '');
// Remove trailing author/date section if present
cleaned = cleaned.replace(/\s+村井\s*優\s*\d{4}\/\d{2}\/\d{2}\s*\d{2}:\d{2}\s*$/g, '');
// Final trim
cleaned = cleaned.trim();
return cleaned;
}
}

View File

@@ -0,0 +1,40 @@
export interface LLMMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
export interface LLMCompletionOptions {
model?: string;
temperature?: number;
maxTokens?: number;
topP?: number;
frequencyPenalty?: number;
presencePenalty?: number;
stop?: string[];
}
export interface LLMCompletionResponse {
content: string;
model: string;
tokensUsed: number;
finishReason: string;
}
export interface LLMStreamChunk {
content: string;
isDone: boolean;
}
export interface ILLMProvider {
generateCompletion(
messages: LLMMessage[],
options?: LLMCompletionOptions,
): Promise<LLMCompletionResponse>;
generateStream(
messages: LLMMessage[],
options?: LLMCompletionOptions,
): AsyncGenerator<LLMStreamChunk>;
countTokens(messages: LLMMessage[]): number;
}

View File

@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { LLMService } from './llm.service';
@Module({
providers: [LLMService],
exports: [LLMService],
})
export class LLMModule {}

View File

@@ -0,0 +1,38 @@
import { Injectable } from '@nestjs/common';
import {
ILLMProvider,
LLMMessage,
LLMCompletionOptions,
LLMCompletionResponse,
LLMStreamChunk,
} from './interfaces/llm-provider.interface';
import { OpenRouterProvider } from './providers/openrouter.provider';
@Injectable()
export class LLMService {
private provider: ILLMProvider;
constructor() {
// For now, only OpenRouter is supported
// In the future, this could be configurable
this.provider = new OpenRouterProvider();
}
async generateCompletion(
messages: LLMMessage[],
options?: LLMCompletionOptions,
): Promise<LLMCompletionResponse> {
return this.provider.generateCompletion(messages, options);
}
async *generateStream(
messages: LLMMessage[],
options?: LLMCompletionOptions,
): AsyncGenerator<LLMStreamChunk> {
yield* this.provider.generateStream(messages, options);
}
countTokens(messages: LLMMessage[]): number {
return this.provider.countTokens(messages);
}
}

View File

@@ -0,0 +1,140 @@
import { Injectable } from '@nestjs/common';
import {
ILLMProvider,
LLMMessage,
LLMCompletionOptions,
LLMCompletionResponse,
LLMStreamChunk,
} from '../interfaces/llm-provider.interface';
@Injectable()
export class OpenRouterProvider implements ILLMProvider {
private readonly apiKey: string;
private readonly baseUrl = 'https://openrouter.ai/api/v1';
private readonly defaultModel: string;
constructor() {
this.apiKey = process.env.LLM_API_KEY || '';
this.defaultModel = process.env.LLM_MODEL || 'openai/gpt-4o';
if (!this.apiKey) {
console.warn('LLM_API_KEY not set. OpenRouter provider will not work.');
}
}
async generateCompletion(
messages: LLMMessage[],
options?: LLMCompletionOptions,
): Promise<LLMCompletionResponse> {
const response = await fetch(`${this.baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
'HTTP-Referer': process.env.APP_URL || 'http://localhost:3000',
'X-Title': 'DreamChat',
},
body: JSON.stringify({
model: options?.model || this.defaultModel,
messages,
temperature: options?.temperature ?? 0.7,
max_tokens: options?.maxTokens,
top_p: options?.topP,
frequency_penalty: options?.frequencyPenalty,
presence_penalty: options?.presencePenalty,
stop: options?.stop,
}),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`OpenRouter API error: ${error}`);
}
const data = await response.json();
const choice = data.choices[0];
return {
content: choice.message.content,
model: data.model,
tokensUsed: data.usage?.total_tokens || 0,
finishReason: choice.finish_reason,
};
}
async *generateStream(
messages: LLMMessage[],
options?: LLMCompletionOptions,
): AsyncGenerator<LLMStreamChunk> {
const response = await fetch(`${this.baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
'HTTP-Referer': process.env.APP_URL || 'http://localhost:3000',
'X-Title': 'DreamChat',
},
body: JSON.stringify({
model: options?.model || this.defaultModel,
messages,
temperature: options?.temperature ?? 0.7,
max_tokens: options?.maxTokens,
top_p: options?.topP,
frequency_penalty: options?.frequencyPenalty,
presence_penalty: options?.presencePenalty,
stop: options?.stop,
stream: true,
}),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`OpenRouter API error: ${error}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('No response body');
}
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') {
yield { content: '', isDone: true };
return;
}
try {
const parsed = JSON.parse(data);
const content = parsed.choices[0]?.delta?.content || '';
const isDone = parsed.choices[0]?.finish_reason != null;
yield { content, isDone };
} catch {
// Skip invalid JSON
}
}
}
}
yield { content: '', isDone: true };
}
countTokens(messages: LLMMessage[]): number {
// Simple estimation: ~4 characters per token on average
const totalChars = messages.reduce((sum, msg) => sum + msg.content.length, 0);
return Math.ceil(totalChars / 4);
}
}

51
apps/backend/src/main.ts Normal file
View File

@@ -0,0 +1,51 @@
import 'dotenv/config';
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: ['http://localhost:5173'],
credentials: true,
});
app.setGlobalPrefix('api');
// Swagger/OpenAPI setup
const config = new DocumentBuilder()
.setTitle('DreamChat API')
.setDescription('The DreamChat API documentation')
.setVersion('1.0.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/docs', app, document);
// Also export the OpenAPI spec as JSON
const fs = await import('fs');
const path = await import('path');
// Ensure the output directory exists
const outputDir = path.join(process.cwd(), '..', '..', 'openapi');
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Write the spec file
fs.writeFileSync(
path.join(outputDir, 'openapi.json'),
JSON.stringify(document, null, 2),
);
console.log(`📄 OpenAPI spec written to: ${path.join(outputDir, 'openapi.json')}`);
const port = process.env.PORT || 3000;
await app.listen(port);
console.log(`🚀 Backend running on: http://localhost:${port}/api`);
console.log(`📚 API docs available at: http://localhost:${port}/api/docs`);
}
bootstrap();

View File

@@ -0,0 +1,9 @@
import { Module, Global } from '@nestjs/common';
import { PrismaService } from './prisma.service';
@Global()
@Module({
providers: [PrismaService],
exports: [PrismaService],
})
export class PrismaModule {}

View File

@@ -0,0 +1,20 @@
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
constructor() {
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!,
});
super({ adapter: adapter });
}
async onModuleInit() {
await this.$connect();
}
async onModuleDestroy() {
await this.$disconnect();
}
}

View File

@@ -0,0 +1,27 @@
import { IsString, IsEmail, MinLength, IsOptional } from 'class-validator';
import { ApiPropertyOptional } from '@nestjs/swagger';
export class UpdateUserDto {
@ApiPropertyOptional({ description: 'New email address', example: 'newemail@example.com' })
@IsOptional()
@IsEmail()
email?: string;
@ApiPropertyOptional({ description: 'New username', example: 'newusername' })
@IsOptional()
@IsString()
@MinLength(3)
username?: string;
}
export class UpdatePasswordDto {
@ApiPropertyOptional({ description: 'Current password', example: 'oldpassword123' })
@IsString()
@MinLength(6)
currentPassword: string;
@ApiPropertyOptional({ description: 'New password', example: 'newpassword123' })
@IsString()
@MinLength(6)
newPassword: string;
}

View File

@@ -0,0 +1,54 @@
import { Controller, Get, Put, Delete, Body } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { UserService } from './user.service';
import { UpdateUserDto, UpdatePasswordDto } from './dto/update-user.dto';
import { CurrentUser } from '../common/decorators/current-user.decorator';
import { User } from '@prisma/client';
@ApiTags('users')
@ApiBearerAuth()
@Controller('users')
export class UserController {
constructor(private userService: UserService) {}
@Get('me')
@ApiOperation({ summary: 'Get current user profile' })
@ApiResponse({ status: 200, description: 'User profile retrieved' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
async getProfile(@CurrentUser('userId') userId: string): Promise<Omit<User, 'passwordHash'>> {
return this.userService.findById(userId);
}
@Put('me')
@ApiOperation({ summary: 'Update current user profile' })
@ApiResponse({ status: 200, description: 'Profile updated' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 409, description: 'Email or username already exists' })
async updateProfile(
@CurrentUser('userId') userId: string,
@Body() updateUserDto: UpdateUserDto,
): Promise<Omit<User, 'passwordHash'>> {
return this.userService.update(userId, updateUserDto);
}
@Put('me/password')
@ApiOperation({ summary: 'Update user password' })
@ApiResponse({ status: 200, description: 'Password updated successfully' })
@ApiResponse({ status: 401, description: 'Current password incorrect' })
async updatePassword(
@CurrentUser('userId') userId: string,
@Body() updatePasswordDto: UpdatePasswordDto,
): Promise<{ message: string }> {
await this.userService.updatePassword(userId, updatePasswordDto);
return { message: 'Password updated successfully' };
}
@Delete('me')
@ApiOperation({ summary: 'Delete user account' })
@ApiResponse({ status: 200, description: 'Account deleted' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
async deleteAccount(@CurrentUser('userId') userId: string): Promise<{ message: string }> {
await this.userService.delete(userId);
return { message: 'Account deleted successfully' };
}
}

View File

@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';
@Module({
providers: [UserService],
controllers: [UserController],
exports: [UserService],
})
export class UserModule {}

View File

@@ -0,0 +1,95 @@
import { Injectable, NotFoundException, ConflictException, UnauthorizedException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { UpdateUserDto, UpdatePasswordDto } from './dto/update-user.dto';
import * as bcrypt from 'bcrypt';
import { User } from '@prisma/client';
@Injectable()
export class UserService {
constructor(private prisma: PrismaService) {}
async findById(id: string): Promise<Omit<User, 'passwordHash'>> {
const user = await this.prisma.user.findUnique({
where: { id },
});
if (!user) {
throw new NotFoundException('User not found');
}
const { passwordHash, ...userWithoutPassword } = user;
return userWithoutPassword;
}
async update(id: string, updateUserDto: UpdateUserDto): Promise<Omit<User, 'passwordHash'>> {
const existingUser = await this.prisma.user.findUnique({
where: { id },
});
if (!existingUser) {
throw new NotFoundException('User not found');
}
if (updateUserDto.email && updateUserDto.email !== existingUser.email) {
const emailExists = await this.prisma.user.findUnique({
where: { email: updateUserDto.email },
});
if (emailExists) {
throw new ConflictException('Email already in use');
}
}
if (updateUserDto.username && updateUserDto.username !== existingUser.username) {
const usernameExists = await this.prisma.user.findUnique({
where: { username: updateUserDto.username },
});
if (usernameExists) {
throw new ConflictException('Username already in use');
}
}
const user = await this.prisma.user.update({
where: { id },
data: updateUserDto,
});
const { passwordHash, ...userWithoutPassword } = user;
return userWithoutPassword;
}
async updatePassword(id: string, updatePasswordDto: UpdatePasswordDto): Promise<void> {
const user = await this.prisma.user.findUnique({
where: { id },
});
if (!user || !user.passwordHash) {
throw new NotFoundException('User not found');
}
const isMatch = await bcrypt.compare(updatePasswordDto.currentPassword, user.passwordHash);
if (!isMatch) {
throw new UnauthorizedException('Current password is incorrect');
}
const hashedPassword = await bcrypt.hash(updatePasswordDto.newPassword, 10);
await this.prisma.user.update({
where: { id },
data: { passwordHash: hashedPassword },
});
}
async delete(id: string): Promise<void> {
const user = await this.prisma.user.findUnique({
where: { id },
});
if (!user) {
throw new NotFoundException('User not found');
}
await this.prisma.user.delete({
where: { id },
});
}
}

View File

@@ -0,0 +1,38 @@
import { Injectable, Logger } from '@nestjs/common';
import { IEmbeddingProvider } from './interfaces/embedding-provider.interface';
import { LocalEmbeddingProvider } from './providers/local-embedding.provider';
@Injectable()
export class EmbeddingService {
private readonly logger = new Logger(EmbeddingService.name);
private provider: IEmbeddingProvider;
constructor() {
const providerType = process.env.EMBEDDING_PROVIDER || 'local';
this.logger.log(`Initializing EmbeddingService with provider: ${providerType}`);
switch (providerType) {
case 'local':
this.provider = new LocalEmbeddingProvider();
break;
default:
throw new Error(`Unknown embedding provider: ${providerType}`);
}
}
async embed(text: string): Promise<number[]> {
this.logger.debug(`Generating embedding for text (${text.length} chars)...`);
const startTime = Date.now();
const result = await this.provider.embed(text);
this.logger.debug(`Embedding generated in ${Date.now() - startTime}ms`);
return result;
}
async embedBatch(texts: string[]): Promise<number[][]> {
return this.provider.embedBatch(texts);
}
getDimension(): number {
return this.provider.getDimension();
}
}

View File

@@ -0,0 +1,5 @@
export interface IEmbeddingProvider {
embed(text: string): Promise<number[]>;
embedBatch(texts: string[]): Promise<number[][]>;
getDimension(): number;
}

View File

@@ -0,0 +1,145 @@
import { Injectable, Logger } from '@nestjs/common';
import { EmbeddingService } from './embedding.service';
import { VectorStoreService, SearchResult } from './vector-store.service';
import { MemoryType } from '@prisma/client';
export interface MemoryContext {
content: string;
metadata: any;
similarity: number;
}
@Injectable()
export class MemoryService {
private readonly logger = new Logger(MemoryService.name);
constructor(
private embeddingService: EmbeddingService,
private vectorStore: VectorStoreService,
) {}
async addMemory(
content: string,
memoryType: MemoryType,
options: {
conversationId?: string;
characterId?: string;
knowledgeId?: string;
metadata?: any;
},
): Promise<void> {
const startTime = Date.now();
this.logger.debug(`[${options.knowledgeId || options.conversationId}] Generating embedding for content (${content.length} chars)...`);
const embedding = await this.embeddingService.embed(content);
this.logger.debug(`[${options.knowledgeId || options.conversationId}] Embedding generated in ${Date.now() - startTime}ms, dimension: ${embedding.length}`);
this.logger.debug(`[${options.knowledgeId || options.conversationId}] Storing in vector store...`);
await this.vectorStore.store(content, embedding, memoryType, options);
this.logger.debug(`[${options.knowledgeId || options.conversationId}] Stored in vector store in ${Date.now() - startTime}ms`);
}
async retrieveRelevantMemories(
query: string,
options: {
limit?: number;
threshold?: number;
conversationId?: string;
characterId?: string;
memoryType?: MemoryType;
},
): Promise<MemoryContext[]> {
const { limit = 5, threshold = 0.6, conversationId, characterId, memoryType } = options;
this.logger.debug(
`[retrieveRelevantMemories] Query: "${query.substring(0, 100)}...", type: ${memoryType}, characterId: ${characterId}, conversationId: ${conversationId}, threshold: ${threshold}`,
);
const embedding = await this.embeddingService.embed(query);
const results = await this.vectorStore.searchSimilar(embedding, options);
this.logger.debug(`[retrieveRelevantMemories] Found ${results.length} results for type ${memoryType}:`);
results.forEach((r, i) => {
this.logger.debug(` [${i}] similarity: ${r.similarity.toFixed(4)}, content: "${r.content.substring(0, 80)}..."`);
});
return results.map((result) => ({
content: result.content,
metadata: result.metadata,
similarity: result.similarity,
}));
}
async buildContextForConversation(conversationId: string, currentMessage: string, characterId: string): Promise<string> {
this.logger.debug(
`[buildContextForConversation] Building context for conversation ${conversationId}, character ${characterId}, message: "${currentMessage.substring(0, 100)}"`,
);
// Retrieve recent conversation memories
const conversationMemories = await this.retrieveRelevantMemories(currentMessage, {
limit: 3,
threshold: 0.6,
conversationId,
memoryType: 'conversation',
});
// Retrieve character knowledge - using multilingual embedding model for cross-lingual support
// Lower threshold (0.3) for cross-lingual matching (English query -> Japanese content)
let characterMemories = await this.retrieveRelevantMemories(currentMessage, {
limit: 3,
threshold: 0.3,
characterId,
memoryType: 'character',
});
// Fallback: If vector search returns no results, retrieve the most recent knowledge
// This ensures the character always has some context for roleplaying
if (characterMemories.length === 0) {
this.logger.debug(`[buildContextForConversation] No similar memories found, falling back to most recent knowledge`);
const recentResults = await this.vectorStore.getRecentByCharacterId(characterId, 2);
characterMemories = recentResults.map((r) => ({
content: r.content,
metadata: r.metadata,
similarity: r.similarity,
}));
}
const contextParts: string[] = [];
if (characterMemories.length > 0) {
contextParts.push('Here are some descriptions of yourself. These knowledge are your history, what you have done, talked, or imagined:');
characterMemories.forEach((memory) => {
contextParts.push(`- ${memory.content}`);
});
}
if (conversationMemories.length > 0) {
contextParts.push('\nRelevant conversation history:');
conversationMemories.forEach((memory) => {
contextParts.push(`- ${memory.content}`);
});
}
const result = contextParts.join('\n');
this.logger.debug(`[buildContextForConversation] Final context (${result.length} chars):\n${result || '(empty)'}`);
return result;
}
async storeConversationMessage(content: string, conversationId: string, metadata?: any): Promise<void> {
await this.addMemory(content, 'conversation', {
conversationId,
metadata,
});
}
async storeCharacterKnowledge(content: string, characterId: string, knowledgeId: string, metadata?: any): Promise<void> {
this.logger.debug(`[${knowledgeId}] Storing character knowledge chunk for character: ${characterId}`);
await this.addMemory(content, 'character', {
characterId,
knowledgeId,
metadata,
});
this.logger.debug(`[${knowledgeId}] Character knowledge chunk stored successfully`);
}
}

View File

@@ -0,0 +1,91 @@
import { Injectable, OnModuleInit, Logger } from '@nestjs/common';
import { IEmbeddingProvider } from '../interfaces/embedding-provider.interface';
import { pipeline, FeatureExtractionPipeline } from '@xenova/transformers';
@Injectable()
export class LocalEmbeddingProvider implements IEmbeddingProvider, OnModuleInit {
private extractor: FeatureExtractionPipeline | null = null;
private readonly modelName: string;
private readonly dimension: number;
private readonly logger = new Logger(LocalEmbeddingProvider.name);
private isLoading = false;
constructor() {
this.modelName = process.env.EMBEDDING_MODEL || 'Xenova/all-MiniLM-L6-v2';
this.dimension = parseInt(process.env.EMBEDDING_DIMENSION || '384', 10);
}
async onModuleInit() {
// Lazy initialization - model will be loaded on first use
this.logger.log(`LocalEmbeddingProvider initialized with model: ${this.modelName}`);
}
private async getExtractor(): Promise<FeatureExtractionPipeline> {
if (!this.extractor) {
if (this.isLoading) {
// Wait for existing load to complete
while (this.isLoading) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
if (this.extractor) {
return this.extractor;
}
}
this.isLoading = true;
this.logger.log(`Loading embedding model: ${this.modelName}...`);
try {
// Use quantized model to reduce memory usage
this.extractor = await pipeline('feature-extraction', this.modelName, {
quantized: true,
revision: 'main',
});
this.logger.log('Embedding model loaded successfully');
} catch (error) {
this.logger.error('Failed to load embedding model:', error);
throw error;
} finally {
this.isLoading = false;
}
}
return this.extractor;
}
async embed(text: string): Promise<number[]> {
// Truncate text to prevent excessive memory usage
const maxLength = 512; // Maximum tokens the model can handle efficiently
const truncatedText = text.length > maxLength * 4 ? text.substring(0, maxLength * 4) : text;
const extractor = await this.getExtractor();
const output = await extractor(truncatedText, { pooling: 'mean', normalize: true });
// Convert to array - this creates a copy, allowing original to be GC'd
const result = Array.from(output.data as Float32Array);
// Add delay to allow GC between embeddings
await new Promise((resolve) => setTimeout(resolve, 10));
return result;
}
async embedBatch(texts: string[]): Promise<number[][]> {
const results: number[][] = [];
// Process one at a time to minimize memory spikes
for (let i = 0; i < texts.length; i++) {
results.push(await this.embed(texts[i]));
// Add delay every few items to allow GC
if (i > 0 && i % 2 === 0) {
await new Promise((resolve) => setTimeout(resolve, 50));
}
}
return results;
}
getDimension(): number {
return this.dimension;
}
}

View File

@@ -0,0 +1,181 @@
import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { MemoryType, VectorMemory } from '@prisma/client';
export interface SearchResult {
id: string;
content: string;
memoryType: MemoryType;
metadata: any;
similarity: number;
}
@Injectable()
export class VectorStoreService {
private readonly logger = new Logger(VectorStoreService.name);
constructor(private prisma: PrismaService) {}
async store(
content: string,
embedding: number[],
memoryType: MemoryType,
options: {
conversationId?: string;
characterId?: string;
knowledgeId?: string;
metadata?: any;
},
): Promise<VectorMemory> {
const startTime = Date.now();
const vectorString = `[${embedding.join(',')}]`;
const metadataJson = options.metadata ? JSON.stringify(options.metadata) : null;
this.logger.debug(`[${options.knowledgeId}] Storing vector memory, type: ${memoryType}, vector dim: ${embedding.length}`);
try {
const result = await this.prisma.$queryRaw<VectorMemory[]>`
INSERT INTO "VectorMemory" (id, content, embedding, "memoryType", metadata, "conversationId", "characterId", "knowledgeId", "createdAt")
VALUES (
gen_random_uuid(),
${content},
${vectorString}::vector,
${memoryType},
${metadataJson}::jsonb,
${options.conversationId || null},
${options.characterId || null},
${options.knowledgeId || null},
NOW()
)
RETURNING *
`.then((results) => results[0]);
this.logger.debug(`[${options.knowledgeId}] Vector memory stored in ${Date.now() - startTime}ms, id: ${result.id}`);
return result;
} catch (error) {
this.logger.error(`[${options.knowledgeId}] Failed to store vector memory:`, error);
throw error;
}
}
async searchSimilar(
embedding: number[],
options: {
limit?: number;
threshold?: number;
conversationId?: string;
characterId?: string;
memoryType?: MemoryType;
},
): Promise<SearchResult[]> {
const { limit = 5, threshold = 0.7 } = options;
const vectorString = `[${embedding.join(',')}]`;
let whereClause = '';
const params: any[] = [vectorString, threshold, limit];
let paramIndex = 4;
if (options.conversationId) {
whereClause += ` AND "conversationId" = $${paramIndex}`;
params.push(options.conversationId);
paramIndex++;
}
if (options.characterId) {
whereClause += ` AND "characterId" = $${paramIndex}`;
params.push(options.characterId);
paramIndex++;
}
if (options.memoryType) {
whereClause += ` AND "memoryType" = $${paramIndex}`;
params.push(options.memoryType);
paramIndex++;
}
const query = `
SELECT
id,
content,
"memoryType",
metadata,
1 - (embedding <=> $1::vector) as similarity
FROM "VectorMemory"
WHERE 1 - (embedding <=> $1::vector) >= $2
${whereClause}
ORDER BY embedding <=> $1::vector
LIMIT $3
`;
this.logger.debug(`[searchSimilar] Query params: threshold=${threshold}, limit=${limit}, characterId=${options.characterId}, memoryType=${options.memoryType}`);
const results = await this.prisma.$queryRawUnsafe<SearchResult[]>(query, ...params);
this.logger.debug(`[searchSimilar] Found ${results.length} results matching criteria`);
// Debug: Show all similarities for character knowledge
if (options.characterId && options.memoryType === 'character') {
const allQuery = `
SELECT
id,
content,
"memoryType",
metadata,
1 - (embedding <=> $1::vector) as similarity
FROM "VectorMemory"
WHERE "characterId" = $2 AND "memoryType" = $3
ORDER BY embedding <=> $1::vector
LIMIT 10
`;
const allResults = await this.prisma.$queryRawUnsafe<SearchResult[]>(allQuery, vectorString, options.characterId, options.memoryType);
this.logger.debug(`[searchSimilar] All ${allResults.length} similarities for character ${options.characterId}:`);
allResults.forEach((r, i) => {
this.logger.debug(` [${i}] similarity=${r.similarity.toFixed(4)}, content="${r.content.substring(0, 50)}..."`);
});
}
return results;
}
async deleteByConversation(conversationId: string): Promise<void> {
await this.prisma.vectorMemory.deleteMany({
where: { conversationId },
});
}
async deleteByCharacter(characterId: string): Promise<void> {
await this.prisma.vectorMemory.deleteMany({
where: { characterId },
});
}
async deleteByKnowledge(knowledgeId: string): Promise<void> {
await this.prisma.vectorMemory.deleteMany({
where: { knowledgeId },
});
}
/**
* Retrieve most recent character knowledge (fallback when similarity search returns nothing)
*/
async getRecentByCharacterId(characterId: string, limit: number = 2): Promise<SearchResult[]> {
this.logger.debug(`[getRecentByCharacterId] Retrieving recent knowledge for character ${characterId}`);
const results = await this.prisma.$queryRaw<SearchResult[]>`
SELECT
id,
content,
"memoryType",
metadata,
1.0 as similarity
FROM "VectorMemory"
WHERE "characterId" = ${characterId} AND "memoryType" = 'character'
ORDER BY "createdAt" DESC
LIMIT ${limit}
`;
this.logger.debug(`[getRecentByCharacterId] Found ${results.length} recent memories`);
return results;
}
}

View File

@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { EmbeddingService } from './embedding.service';
import { VectorStoreService } from './vector-store.service';
import { MemoryService } from './memory.service';
@Module({
providers: [EmbeddingService, VectorStoreService, MemoryService],
exports: [EmbeddingService, VectorStoreService, MemoryService],
})
export class VectorModule {}

View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}

55
apps/frontend/Dockerfile Normal file
View File

@@ -0,0 +1,55 @@
# apps/frontend/Dockerfile
FROM node:24-alpine AS base
RUN npm install -g pnpm@8
FROM base AS dependencies
WORKDIR /app
# Copy workspace configuration
COPY pnpm-workspace.yaml package.json ./
COPY apps/frontend/package.json ./apps/frontend/
COPY packages/shared/package.json ./packages/shared/
# Install dependencies
RUN pnpm install --frozen-lockfile
FROM base AS build
WORKDIR /app
COPY --from=dependencies /app/node_modules ./node_modules
COPY --from=dependencies /app/apps/frontend/node_modules ./apps/frontend/node_modules
COPY --from=dependencies /app/packages/shared/node_modules ./packages/shared/node_modules
# Copy source code
COPY packages/shared ./packages/shared
COPY apps/frontend ./apps/frontend
# Build shared packages first
RUN pnpm --filter @dreamchat/shared build
# Build frontend
RUN pnpm --filter @dreamchat/frontend build
# Production stage - using serve for static files
# External reverse proxy (nginx/traefik/etc.) expected
FROM node:24-alpine AS production
WORKDIR /app
# Install serve
RUN npm install -g serve
# Copy built assets
COPY --from=build /app/apps/frontend/dist ./dist
# Create non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nodejs -u 1001
USER nodejs
EXPOSE 3000
# Serve static files
# Note: External reverse proxy should handle:
# - SSL/TLS termination
# - Path routing (/api -> backend, / -> frontend)
# - WebSocket proxying
CMD ["serve", "-s", "dist", "-l", "3000"]

13
apps/frontend/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>DreamChat</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -0,0 +1,7 @@
{
"$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json",
"spaces": 2,
"generator-cli": {
"version": "7.20.0"
}
}

View File

@@ -0,0 +1,24 @@
module.exports = {
dreamchat: {
input: {
target: '../openapi/openapi.json',
},
output: {
mode: 'tags-split',
target: './src/api/generated',
schemas: './src/api/generated/model',
client: 'fetch',
baseUrl: 'http://localhost:3000',
mock: false,
override: {
fetch: {
includeHttpResponseReturnType: false,
},
mutator: {
path: './src/api/mutator/custom-fetch.ts',
name: 'customFetch',
},
},
},
},
};

View File

@@ -0,0 +1,37 @@
{
"name": "@dreamchat/frontend",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"test": "vitest",
"lint": "eslint . --ext ts,tsx",
"clean": "rm -rf dist",
"api:generate": "orval"
},
"dependencies": {
"@dreamchat/shared": "workspace:*",
"@tanstack/react-query": "^5.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.20.0",
"socket.io-client": "^4.7.0",
"zustand": "^4.5.0"
},
"devDependencies": {
"@openapitools/openapi-generator-cli": "^2.29.0",
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
"@vitejs/plugin-react": "^4.2.0",
"autoprefixer": "^10.4.0",
"openapi-typescript": "^7.13.0",
"orval": "^8.4.2",
"postcss": "^8.4.0",
"tailwindcss": "^3.4.0",
"typescript": "^5.3.0",
"vite": "^5.0.0",
"vitest": "^1.0.0"
}
}

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

View File

143
apps/frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,143 @@
import { useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate, useSearchParams, useNavigate } from 'react-router-dom';
import { useAuthStore } from './stores/authStore';
import { Login } from './pages/Login';
import { CharacterList } from './pages/CharacterList';
import { CharacterForm } from './pages/CharacterForm';
import { ConversationList } from './pages/ConversationList';
import { Chat } from './pages/Chat';
import { KnowledgeImport } from './pages/KnowledgeImport';
// OAuth Callback Handler - processes tokens from URL before routing
function OAuthCallbackHandler({ children }: { children: React.ReactNode }) {
const [searchParams, setSearchParams] = useSearchParams();
const navigate = useNavigate();
const { setTokens } = useAuthStore();
useEffect(() => {
const accessToken = searchParams.get('accessToken');
const refreshToken = searchParams.get('refreshToken');
const errorMsg = searchParams.get('error');
if (errorMsg) {
// Redirect to login with error
const decodedError = decodeURIComponent(errorMsg);
setSearchParams({}, { replace: true });
navigate(`/login?error=${encodeURIComponent(decodedError)}`, { replace: true });
return;
}
if (accessToken && refreshToken) {
// Store tokens
setTokens(accessToken, refreshToken);
// Clear tokens from URL but keep the path
setSearchParams({}, { replace: true });
}
}, [searchParams, setSearchParams, navigate, setTokens]);
return <>{children}</>;
}
function PrivateRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated } = useAuthStore();
return isAuthenticated ? <>{children}</> : <Navigate to="/login" replace />;
}
function PublicRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated } = useAuthStore();
return !isAuthenticated ? <>{children}</> : <Navigate to="/characters" replace />;
}
function App() {
const { init } = useAuthStore();
useEffect(() => {
init();
}, [init]);
return (
<BrowserRouter>
<OAuthCallbackHandler>
<Routes>
<Route path="/" element={<Navigate to="/characters" replace />} />
<Route
path="/login"
element={
<PublicRoute>
<Login />
</PublicRoute>
}
/>
<Route
path="/characters"
element={
<PrivateRoute>
<CharacterList />
</PrivateRoute>
}
/>
<Route
path="/characters/new"
element={
<PrivateRoute>
<CharacterForm />
</PrivateRoute>
}
/>
<Route
path="/characters/:id"
element={
<PrivateRoute>
<CharacterForm />
</PrivateRoute>
}
/>
<Route
path="/conversations"
element={
<PrivateRoute>
<ConversationList />
</PrivateRoute>
}
/>
<Route
path="/conversations/:conversationId"
element={
<PrivateRoute>
<Chat />
</PrivateRoute>
}
/>
<Route
path="/chat/:characterId"
element={
<PrivateRoute>
<Chat />
</PrivateRoute>
}
/>
<Route
path="/characters/:characterId/knowledge"
element={
<PrivateRoute>
<KnowledgeImport />
</PrivateRoute>
}
/>
</Routes>
</OAuthCallbackHandler>
</BrowserRouter>
);
}
export default App;

View File

@@ -0,0 +1,173 @@
/**
* Generated by orval v8.4.2 🍺
* Do not edit manually.
* DreamChat API
* The DreamChat API documentation
* OpenAPI spec version: 1.0.0
*/
import type {
AuthControllerKeycloakCallbackParams,
AuthControllerKeycloakLoginParams,
AuthResponseDto,
KeycloakConfigDto,
KeycloakLoginUrlDto,
LoginDto,
RefreshTokenDto
} from '.././model';
import { customFetch } from '../../mutator/custom-fetch';
/**
* @summary Login with email and password
*/
export const getAuthControllerLoginUrl = () => {
return `http://localhost:3000/api/auth/login`
}
export const authControllerLogin = async (loginDto: LoginDto, options?: RequestInit): Promise<AuthResponseDto> => {
return customFetch<AuthResponseDto>(getAuthControllerLoginUrl(),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
body: JSON.stringify(
loginDto,)
}
);}
/**
* @summary Refresh access token
*/
export const getAuthControllerRefreshTokensUrl = () => {
return `http://localhost:3000/api/auth/refresh`
}
export const authControllerRefreshTokens = async (refreshTokenDto: RefreshTokenDto, options?: RequestInit): Promise<AuthResponseDto> => {
return customFetch<AuthResponseDto>(getAuthControllerRefreshTokensUrl(),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
body: JSON.stringify(
refreshTokenDto,)
}
);}
/**
* @summary Get Keycloak configuration for frontend
*/
export const getAuthControllerGetKeycloakConfigUrl = () => {
return `http://localhost:3000/api/auth/keycloak/config`
}
export const authControllerGetKeycloakConfig = async ( options?: RequestInit): Promise<KeycloakConfigDto> => {
return customFetch<KeycloakConfigDto>(getAuthControllerGetKeycloakConfigUrl(),
{
...options,
method: 'GET'
}
);}
/**
* @summary Get Keycloak login URL (initiates OAuth flow)
*/
export const getAuthControllerKeycloakLoginUrl = (params?: AuthControllerKeycloakLoginParams,) => {
const normalizedParams = new URLSearchParams();
Object.entries(params || {}).forEach(([key, value]) => {
if (value !== undefined) {
normalizedParams.append(key, value === null ? 'null' : value.toString())
}
});
const stringifiedParams = normalizedParams.toString();
return stringifiedParams.length > 0 ? `http://localhost:3000/api/auth/keycloak/login?${stringifiedParams}` : `http://localhost:3000/api/auth/keycloak/login`
}
export const authControllerKeycloakLogin = async (params?: AuthControllerKeycloakLoginParams, options?: RequestInit): Promise<KeycloakLoginUrlDto> => {
return customFetch<KeycloakLoginUrlDto>(getAuthControllerKeycloakLoginUrl(params),
{
...options,
method: 'GET'
}
);}
/**
* @summary Keycloak OAuth callback endpoint
*/
export const getAuthControllerKeycloakCallbackUrl = (params: AuthControllerKeycloakCallbackParams,) => {
const normalizedParams = new URLSearchParams();
Object.entries(params || {}).forEach(([key, value]) => {
if (value !== undefined) {
normalizedParams.append(key, value === null ? 'null' : value.toString())
}
});
const stringifiedParams = normalizedParams.toString();
return stringifiedParams.length > 0 ? `http://localhost:3000/api/auth/keycloak/callback?${stringifiedParams}` : `http://localhost:3000/api/auth/keycloak/callback`
}
export const authControllerKeycloakCallback = async (params: AuthControllerKeycloakCallbackParams, options?: RequestInit): Promise<unknown> => {
return customFetch<unknown>(getAuthControllerKeycloakCallbackUrl(params),
{
...options,
method: 'GET'
}
);}
/**
* @summary Login with Keycloak bearer token (Authorization: Bearer <keycloak-jwt>)
*/
export const getAuthControllerKeycloakBearerLoginUrl = () => {
return `http://localhost:3000/api/auth/keycloak`
}
export const authControllerKeycloakBearerLogin = async ( options?: RequestInit): Promise<AuthResponseDto> => {
return customFetch<AuthResponseDto>(getAuthControllerKeycloakBearerLoginUrl(),
{
...options,
method: 'POST'
}
);}

View File

@@ -0,0 +1,133 @@
/**
* Generated by orval v8.4.2 🍺
* Do not edit manually.
* DreamChat API
* The DreamChat API documentation
* OpenAPI spec version: 1.0.0
*/
import type {
CharacterResponseDto,
CreateCharacterDto,
UpdateCharacterDto
} from '.././model';
import { customFetch } from '../../mutator/custom-fetch';
/**
* @summary Create a new character
*/
export const getCharacterControllerCreateUrl = () => {
return `http://localhost:3000/api/characters`
}
export const characterControllerCreate = async (createCharacterDto: CreateCharacterDto, options?: RequestInit): Promise<CharacterResponseDto> => {
return customFetch<CharacterResponseDto>(getCharacterControllerCreateUrl(),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
body: JSON.stringify(
createCharacterDto,)
}
);}
/**
* @summary Get all characters for current user
*/
export const getCharacterControllerFindAllUrl = () => {
return `http://localhost:3000/api/characters`
}
export const characterControllerFindAll = async ( options?: RequestInit): Promise<CharacterResponseDto[]> => {
return customFetch<CharacterResponseDto[]>(getCharacterControllerFindAllUrl(),
{
...options,
method: 'GET'
}
);}
/**
* @summary Get character by ID
*/
export const getCharacterControllerFindOneUrl = (id: string,) => {
return `http://localhost:3000/api/characters/${id}`
}
export const characterControllerFindOne = async (id: string, options?: RequestInit): Promise<CharacterResponseDto> => {
return customFetch<CharacterResponseDto>(getCharacterControllerFindOneUrl(id),
{
...options,
method: 'GET'
}
);}
/**
* @summary Update character
*/
export const getCharacterControllerUpdateUrl = (id: string,) => {
return `http://localhost:3000/api/characters/${id}`
}
export const characterControllerUpdate = async (id: string,
updateCharacterDto: UpdateCharacterDto, options?: RequestInit): Promise<CharacterResponseDto> => {
return customFetch<CharacterResponseDto>(getCharacterControllerUpdateUrl(id),
{
...options,
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...options?.headers },
body: JSON.stringify(
updateCharacterDto,)
}
);}
/**
* @summary Delete character
*/
export const getCharacterControllerDeleteUrl = (id: string,) => {
return `http://localhost:3000/api/characters/${id}`
}
export const characterControllerDelete = async (id: string, options?: RequestInit): Promise<void> => {
return customFetch<void>(getCharacterControllerDeleteUrl(id),
{
...options,
method: 'DELETE'
}
);}

View File

@@ -0,0 +1,135 @@
/**
* Generated by orval v8.4.2 🍺
* Do not edit manually.
* DreamChat API
* The DreamChat API documentation
* OpenAPI spec version: 1.0.0
*/
import type {
ConversationResponseDto,
ConversationWithMessagesResponseDto,
CreateConversationDto,
SendMessageDto,
SendMessageResponseDto
} from '.././model';
import { customFetch } from '../../mutator/custom-fetch';
/**
* @summary Create a new conversation
*/
export const getChatControllerCreateConversationUrl = () => {
return `http://localhost:3000/api/conversations`
}
export const chatControllerCreateConversation = async (createConversationDto: CreateConversationDto, options?: RequestInit): Promise<ConversationResponseDto> => {
return customFetch<ConversationResponseDto>(getChatControllerCreateConversationUrl(),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
body: JSON.stringify(
createConversationDto,)
}
);}
/**
* @summary Get all conversations for current user
*/
export const getChatControllerGetConversationsUrl = () => {
return `http://localhost:3000/api/conversations`
}
export const chatControllerGetConversations = async ( options?: RequestInit): Promise<ConversationResponseDto[]> => {
return customFetch<ConversationResponseDto[]>(getChatControllerGetConversationsUrl(),
{
...options,
method: 'GET'
}
);}
/**
* @summary Get conversation by ID with messages
*/
export const getChatControllerGetConversationUrl = (id: string,) => {
return `http://localhost:3000/api/conversations/${id}`
}
export const chatControllerGetConversation = async (id: string, options?: RequestInit): Promise<ConversationWithMessagesResponseDto> => {
return customFetch<ConversationWithMessagesResponseDto>(getChatControllerGetConversationUrl(id),
{
...options,
method: 'GET'
}
);}
/**
* @summary Delete conversation
*/
export const getChatControllerDeleteConversationUrl = (id: string,) => {
return `http://localhost:3000/api/conversations/${id}`
}
export const chatControllerDeleteConversation = async (id: string, options?: RequestInit): Promise<void> => {
return customFetch<void>(getChatControllerDeleteConversationUrl(id),
{
...options,
method: 'DELETE'
}
);}
/**
* @summary Send a message in a conversation
*/
export const getChatControllerSendMessageUrl = (id: string,) => {
return `http://localhost:3000/api/conversations/${id}/messages`
}
export const chatControllerSendMessage = async (id: string,
sendMessageDto: SendMessageDto, options?: RequestInit): Promise<SendMessageResponseDto> => {
return customFetch<SendMessageResponseDto>(getChatControllerSendMessageUrl(id),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
body: JSON.stringify(
sendMessageDto,)
}
);}

View File

@@ -0,0 +1,139 @@
/**
* Generated by orval v8.4.2 🍺
* Do not edit manually.
* DreamChat API
* The DreamChat API documentation
* OpenAPI spec version: 1.0.0
*/
import type {
ImportControllerUploadFileBody,
ImportUrlDto,
UploadResponseDto,
} from '.././model';
import { customFetch } from '../../mutator/custom-fetch';
/**
* @summary Upload a file for character knowledge
*/
export const getImportControllerUploadFileUrl = (characterId: string,) => {
return `http://localhost:3000/api/import/characters/${characterId}/files`
}
export const importControllerUploadFile = async (characterId: string,
importControllerUploadFileBody: ImportControllerUploadFileBody, options?: RequestInit): Promise<void> => {
const formData = new FormData();
if(importControllerUploadFileBody.file !== undefined) {
formData.append(`file`, importControllerUploadFileBody.file);
}
return customFetch<void>(getImportControllerUploadFileUrl(characterId),
{
...options,
method: 'POST'
,
body:
formData,
}
);}
/**
* @summary Get knowledge processing status
*/
export const getImportControllerGetKnowledgeStatusUrl = (knowledgeId: string,) => {
return `http://localhost:3000/api/import/knowledge/${knowledgeId}/status`
}
export const importControllerGetKnowledgeStatus = async (knowledgeId: string, options?: RequestInit): Promise<void> => {
return customFetch<void>(getImportControllerGetKnowledgeStatusUrl(knowledgeId),
{
...options,
method: 'GET'
}
);}
/**
* @summary Get all knowledge for a character
*/
export const getImportControllerGetCharacterKnowledgeUrl = (characterId: string,) => {
return `http://localhost:3000/api/import/characters/${characterId}/knowledge`
}
export const importControllerGetCharacterKnowledge = async (characterId: string, options?: RequestInit): Promise<void> => {
return customFetch<void>(getImportControllerGetCharacterKnowledgeUrl(characterId),
{
...options,
method: 'GET'
}
);}
/**
* @summary Delete knowledge
*/
export const getImportControllerDeleteKnowledgeUrl = (knowledgeId: string,) => {
return `http://localhost:3000/api/import/knowledge/${knowledgeId}`
}
export const importControllerDeleteKnowledge = async (knowledgeId: string, options?: RequestInit): Promise<void> => {
return customFetch<void>(getImportControllerDeleteKnowledgeUrl(knowledgeId),
{
...options,
method: 'DELETE'
}
);}
/**
* @summary Import content from URL for character knowledge
*/
export const getImportControllerImportFromUrlUrl = (characterId: string,) => {
return `http://localhost:3000/api/import/characters/${characterId}/url`
}
export const importControllerImportFromUrl = async (characterId: string,
importUrlDto: ImportUrlDto, options?: RequestInit): Promise<UploadResponseDto> => {
return customFetch<UploadResponseDto>(getImportControllerImportFromUrlUrl(characterId),
{
...options,
method: 'POST',
headers: {
...options?.headers,
'Content-Type': 'application/json',
},
body: JSON.stringify(importUrlDto),
}
);}

View File

@@ -0,0 +1,26 @@
/**
* Generated by orval v8.4.2 🍺
* Do not edit manually.
* DreamChat API
* The DreamChat API documentation
* OpenAPI spec version: 1.0.0
*/
export type AuthControllerKeycloakCallbackParams = {
/**
* Authorization code from Keycloak
*/
code: string;
/**
* Error message if authentication failed
*/
error?: string;
/**
* Error description
*/
error_description?: string;
/**
* State parameter for CSRF validation
*/
state: string;
};

View File

@@ -0,0 +1,14 @@
/**
* Generated by orval v8.4.2 🍺
* Do not edit manually.
* DreamChat API
* The DreamChat API documentation
* OpenAPI spec version: 1.0.0
*/
export type AuthControllerKeycloakLoginParams = {
/**
* Frontend path to redirect after login
*/
redirectTo?: string;
};

View File

@@ -0,0 +1,17 @@
/**
* Generated by orval v8.4.2 🍺
* Do not edit manually.
* DreamChat API
* The DreamChat API documentation
* OpenAPI spec version: 1.0.0
*/
import type { UserDto } from './userDto';
export interface AuthResponseDto {
/** JWT access token */
accessToken: string;
/** JWT refresh token */
refreshToken: string;
/** User information */
user: UserDto;
}

View File

@@ -0,0 +1,32 @@
/**
* Generated by orval v8.4.2 🍺
* Do not edit manually.
* DreamChat API
* The DreamChat API documentation
* OpenAPI spec version: 1.0.0
*/
import type { CharacterResponseDtoAttributes } from './characterResponseDtoAttributes';
import type { CharacterResponseDtoConfig } from './characterResponseDtoConfig';
export interface CharacterResponseDto {
/** Character ID */
id: string;
/** Character name */
name: string;
/** Avatar URL */
avatarUrl?: string;
/** Personality prompt */
personalityPrompt: string;
/** Custom attributes */
attributes: CharacterResponseDtoAttributes;
/** Character configuration */
config: CharacterResponseDtoConfig;
/** Whether character is public */
isPublic: boolean;
/** Creation date */
createdAt: string;
/** Last update date */
updatedAt: string;
/** User ID */
userId: string;
}

View File

@@ -0,0 +1,12 @@
/**
* Generated by orval v8.4.2 🍺
* Do not edit manually.
* DreamChat API
* The DreamChat API documentation
* OpenAPI spec version: 1.0.0
*/
/**
* Custom attributes
*/
export type CharacterResponseDtoAttributes = { [key: string]: unknown };

View File

@@ -0,0 +1,12 @@
/**
* Generated by orval v8.4.2 🍺
* Do not edit manually.
* DreamChat API
* The DreamChat API documentation
* OpenAPI spec version: 1.0.0
*/
/**
* Character configuration
*/
export type CharacterResponseDtoConfig = { [key: string]: unknown };

Some files were not shown because too many files have changed in this diff Show More