π The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.
Vue dockergolangkanbanknowledge-baseknowledge-managementmarkdownnote-takingnotesnotes-appnotionnuxtnuxtjsoffline-firstoidcpwaselfhostedssovuevuejswiki
Improve deploy documentation
Smaug673976f4287a7698
diff --git a/.env.example b/.env.exampleindex 300963e6..8228e549 100644--- a/.env.example+++ b/.env.example@@ -7,9 +7,12 @@# 3. DO NOT commit your final ".env" file to source control# ==============================================================================+# Important: If you want more detailed explanations about each variable, please refer to the "docs/README.md" file.+# Important: If you have some errors or something is not working as expected, please refer to FAQ in the "docs/README.md" file.-# -------------------------------------------------------------------------------# 0. Common Settings+# ==============================================================================+# 1. PUBLIC ACCESS & GLOBAL URLS+# ==============================================================================# Public URLs used by the client's browser to reach the services.# If using a Reverse Proxy (Nginx/Traefik), use your public domain names here.@@ -17,54 +20,69 @@ FRONTEND_URL=http://localhost:8200API_URL=http://localhost:8201CDN_URL=http://localhost:9005-# Flags to enable or disable certain app features+CDN_ENDPOINT=/alexandrie/ # The base path in the CDN where files are served from (you probably want to keep this as /alexandrie/ to match the bucket name, change it only if you changed the bucket name or if you have configured a reverse proxy path)++# ==============================================================================+# 2. APPLICATION FEATURE FLAGS+# ==============================================================================+# Enable or disable optional frontend features.+CONFIG_DISABLE_LANDING=false # Disable the landing page if set to trueCONFIG_DISABLE_SIGNUP=false # Disable the signup page if set to true-# -------------------------------------------------------------------------------# 1. DATABASE CONFIGURATION (MySQL)+# ==============================================================================+# 3. BACKEND API β RUNTIME & SECURITY+# ==============================================================================++BACKEND_EXTERNAL_PORT=8201 # The port exposed on your host machine for the Backend API++COOKIE_DOMAIN=localhost:8200 # Common domain for cookies (e.g., yourdomain.com if you have frontend.yourdomain.com and api.yourdomain.com)+ALLOW_UNSECURE=true # true = HTTP allowed (local dev / local machine), false = HTTPS only+JWT_SECRET=your-secure-jwt-secret-key-change-this-in-production-MYSQL_EXTERNAL_PORT=3307 # The port exposed on your host machine for database access-MYSQL_ROOT_PASSWORD=rootpassword # Root password for the MySQL instance-MYSQL_DATABASE=alexandrie # The name of the application database+# ==============================================================================+# 4. DATABASE β MYSQL+# ==============================================================================+# MySQL service configuration++MYSQL_EXTERNAL_PORT=3307+MYSQL_DATABASE=alexandrie++# CredentialsMYSQL_USER=alexandrieMYSQL_PASSWORD=password+MYSQL_ROOT_PASSWORD=rootpassword-# -------------------------------------------------------------------------------# 2. OBJECT STORAGE (RustFS / S3 Compatible)-RUSTFS_EXTERNAL_PORT=9005 # The port exposed on your host machine for S3 API access-MINIO_SECURE=false # Set to 'true' if your S3 endpoint uses HTTPS (true/false)+# ==============================================================================+# 5. OBJECT STORAGE β S3 (RustFS / MinIO-compatible) (optional, leave empty to disable)+# ==============================================================================+# S3 API exposure+RUSTFS_EXTERNAL_PORT=9005-# Access credentials for the object storage+# Access credentialsRUSTFS_ACCESS_KEY=alexandrie-keyRUSTFS_SECRET_KEY=alexandrie-secret-MINIO_BUCKET=alexandrie # The default S3 bucket name where files will be stored (alexandrie and alexandrie-backups are created by default)-RUSTFS_CONSOLE_ENABLE=false # Enable or disable the RustFS web management console (true/false)-RUSTFS_LOG_LEVEL=info # Logging level (debug, info, warn, error)+# Default bucket used by the application+MINIO_BUCKET=alexandrie-CDN_ENDPOINT=/alexandrie/ # The base path in the CDN where files are served from (you probably want to keep this as /alexandrie/ to match the bucket name, change it only if you changed the bucket name or if you have configured a reverse proxy path)-# -------------------------------------------------------------------------------# 3. BACKEND API CONFIGURATION-BACKEND_EXTERNAL_PORT=8201 # The port exposed on your host machine for the Backend API--# Security: Secret key used to sign JWT tokens.-# /!\ IMPORTANT: Change this to a random long string in production /!\-JWT_SECRET=your-secure-jwt-secret-key-change-this-in-production+# Runtime options+RUSTFS_CONSOLE_ENABLE=false+RUSTFS_LOG_LEVEL=error # debug | info | warn | error+# ==============================================================================+# 6. EMAIL β SMTP (OPTIONAL)+# ==============================================================================+# Required only for password reset only.+# Leave empty to disable email features.-COOKIE_DOMAIN=localhost:8200 # Common domain for cookies (e.g., yourdomain.com if you have frontend.yourdomain.com and api.yourdomain.com)-ALLOW_UNSECURE=true # Set to 'true' if running without HTTPS (local dev). Set to 'false' in production.--# -------------------------------------------------------------------------------# 4. SMTP CONFIGURATION (Email Service)-# Optional: Only required for password reset features.-# Leave empty if you do not wish to use email functionality.SMTP_HOST=SMTP_MAIL=SMTP_PASSWORD=-# -------------------------------------------------------------------------------# 5. FRONTEND CONFIGURATION (Nuxt)-FRONTEND_EXTERNAL_PORT=8200 # The port exposed on your host machine for the web interface\ No newline at end of file+# ==============================================================================+# 7. FRONTEND β NUXT+# ==============================================================================++FRONTEND_EXTERNAL_PORT=8200 # The port exposed on your host machine for the Frontend service\ No newline at end of filediff --git a/docs/README.md b/docs/README.mdindex e4f10866..33e93525 100644--- a/docs/README.md+++ b/docs/README.md@@ -1,2421 +1,228 @@-# Alexandrie - Technical Documentation+# Alexandrie Setup Guide-## Table of Contents+This guide explains how to set up, configure, and deploy the Alexandrie stack.-- [1. Application Overview](#1-application-overview)-- [2. System Architecture](#2-system-architecture)-- [3. Backend Architecture](#3-backend-architecture)-- [4. Frontend Architecture](#4-frontend-architecture)-- [5. Data Models](#5-data-models)-- [6. Key Features Implementation](#6-key-features-implementation)-- [7. External Services Integration](#7-external-services-integration)-- [8. Security Implementation](#8-security-implementation)-- [9. Development Workflow](#9-development-workflow)-- [10. Configuration Reference](#10-configuration-reference)+It covers both **local development** and **production deployment**, including how to configure environment variables, connect the different services, and handle HTTPS with a reverse proxy.----## 1. Application Overview--### 1.1 Purpose--Alexandrie is a modern, full-featured note-taking application designed for students and productivity enthusiasts. It provides an intuitive interface for creating, organizing, and managing notes written in extended Markdown format with advanced features like workspace organization, real-time collaboration through permissions, and S3-compatible file storage.--### 1.2 Key Features--- **Enhanced Markdown Editor**: CodeMirror 6-based editor with syntax highlighting, autocomplete, and extended Markdown features-- **Hierarchical Organization**: Workspaces, categories, and nested documents with unlimited depth-- **Granular Permissions**: Fine-grained access control system (Read, Write, Admin, Owner)-- **File Storage**: S3-compatible CDN integration for attachments and media-- **Search Capabilities**: Full-text search across all documents-- **Export Options**: PDF and Markdown export functionality-- **Progressive Web App**: Offline support with service worker caching-- **Multi-theme Support**: Dark and light modes with smooth transitions-- **Collaboration**: Share notes with unique links and manage user permissions--### 1.3 Technology Stack--| Layer | Technology | Version | Purpose |-| -------------------- | ------------ | ------------- | ---------------------------------- |-| **Backend** | Go (Golang) | 1.24.0 | High-performance API server |-| **Web Framework** | Gin | 1.11.0 | HTTP routing and middleware |-| **Frontend** | Nuxt | 4.2.1 | Vue.js meta-framework with SSR/SPA |-| **UI Framework** | Vue.js | 3.5.24 | Reactive UI components |-| **State Management** | Pinia | 3.0.4 | Centralized state management |-| **Database** | MySQL | 8.0+ | Relational data storage |-| **Object Storage** | MinIO/RustFS | - | S3-compatible file storage |-| **Code Editor** | CodeMirror | 6.x | Markdown editing experience |-| **Authentication** | JWT | golang-jwt/v5 | Stateless authentication |-| **Email** | go-mail | 0.7.2 | SMTP email sending |-| **Build Tool** | Bun | Latest | Fast package manager for frontend |-| **Containerization** | Docker | - | Development and deployment |+## Overview of the Stack------## 2. System Architecture--### 2.1 High-Level Architecture--Alexandrie follows a **microservices architecture** with clear separation of concerns:--```-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-β Client Layer β-β (Browser / PWA with Service Worker for offline support) β-ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ- β HTTPS- βΌ-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-β Reverse Proxy (Nginx) β-β (SSL Termination, Load Balancing) β-ββββββββββββββββ¬ββββββββββββββββββββββββββ¬βββββββββββββββββββββ- β β- β Port 8200 β Port 8201- βΌ βΌ-ββββββββββββββββββββββββ βββββββββββββββββββββββββββββββ-β Frontend Service β β Backend API Service β-β (Nuxt 4/Vue) ββββββββ€ (Go/Gin) β-β - Server Render β API β - REST API β-β - Static Assets β β - Business Logic β-β - PWA Service β β - Authentication β-ββββββββββββββββββββββββ ββββββββββββ¬βββββββββββββββββββ- β- ββββββββββββββββββββββΌβββββββββββββββββββββ- β β β- βΌ βΌ βΌ- βββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββ- β MySQL Database β β MinIO/RustFS β β SMTP Server β- β - User Data β β - File Storage β β - Email β- β - Documents β β - S3 API β β Sending β- β - Permissions β β - Media CDN β β β- βββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββ-```+The Alexandrie stack consists of four main services, defined in the `docker-compose.yml` file:-### 2.2 Network Communication+| Service | Description |+| ------------ | ------------------------------------------------------------------------------ |+| **MySQL** | Relational database used to store user data and metadata. |+| **RustFS** | S3-compatible object storage used for file and media storage. |+| **Backend** | The Go-based API server providing authentication, storage, and access control. |+| **Frontend** | A Nuxt 4 web app that communicates with the backend via REST API. |-All services communicate through a dedicated Docker network (`alexandrie-network`) in development/production setups:--- **Frontend β User**: HTTP/HTTPS on port 8200-- **Backend β Frontend**: REST API on port 8201 (all routes prefixed with `/api`)-- **Backend β MySQL**: Internal connection on port 3306-- **Backend β MinIO**: S3 protocol on port 9000-- **Backend β SMTP**: TLS connection for email delivery--### 2.3 Data Flow--1. **User Action**: User interacts with Vue.js frontend-2. **State Update**: Pinia store dispatches action-3. **API Request**: HTTP request sent to backend API-4. **Authentication**: JWT token validated by middleware-5. **Authorization**: Permissions checked against database-6. **Business Logic**: Service layer processes request-7. **Data Persistence**: MySQL stores data or MinIO stores files-8. **Response**: JSON response sent back to frontend-9. **UI Update**: Vue components re-render with new data+All services are connected through a dedicated Docker network (`alexandrie-network`).----## 3. Backend Architecture--### 3.1 Project Structure--```-backend/-βββ main.go # Application entry point-βββ go.mod # Go module dependencies-βββ go.sum # Dependency checksums-βββ config.toml # Application configuration-βββ Dockerfile # Container image definition-β-βββ app/ # Core application setup-β βββ app.go # App initialization & dependency injection-β βββ database.go # MySQL connection & configuration-β βββ migrations.go # Database migration runner-β βββ minio.go # S3 client initialization-β βββ mail.go # SMTP client setup-β-βββ server/ # HTTP server setup-β βββ server.go # Server initialization & config loading-β-βββ router/ # HTTP routing-β βββ router.go # Main router with CORS & middleware-β βββ routes/ # Route definitions by domain-β βββ auth.go-β βββ users.go-β βββ nodes.go-β βββ permissions.go-β βββ uploads.go-β-βββ controllers/ # HTTP request handlers-β βββ authentication.controller.go # Login, register, logout, token refresh-β βββ users.controller.go # User CRUD operations-β βββ nodes.controller.go # Nodes (document/category/wp) CRUD operations-β βββ permissions.controller.go # Permission management (for nodes, will be moved soon on /nodes/permissions and nodes.permissions.controller.go)-β βββ resources.controller.go # File upload/download (resources)-β βββ index.go # Not implemented yey but healtcheck-β-βββ services/ # Business logic layer-β βββ services.go # Service interfaces (types & logic definitions)-β βββ user.service.go # User business logic-β βββ session.service.go # Authentication & session management-β βββ node.service.go # Document/category operations-β βββ permissions.service.go # Access control logic-β βββ minio.service.go # File storage operations-β βββ log.service.go # Activity logging-β-βββ models/ # Data structures-β βββ index.go # Model registration-β βββ user.model.go # User entity-β βββ node.model.go # Document/category entity-β βββ permission.model.go # Permission entity-β βββ session.model.go # Session entity-β βββ log.model.go # Activity log entity-β-βββ middlewares/ # HTTP middleware-β βββ authentification.go # JWT validation-β βββ admin.go # Admin role check-β-βββ permissions/ # Access control system-β βββ constants.go # Permission levels & actions-β βββ service.go # Permission checking logic-β-βββ types/ # Custom types-β βββ Snowflake.go # Distributed ID generation-β βββ JSON.go # JSONB type for MySQL-β-βββ utils/ # Utility functions-β βββ constants.go # Application constants-β βββ snowflake.go # Snowflake ID generator-β βββ responses.go # Standard API responses-β βββ permissions.go # Permission helpers -> to get connected user infos-β βββ escape-html.go # XSS prevention-β βββ domains.go # Domain configuration-β βββ utils.go # General utilities-β-βββ migrations/ # Database migrations-β βββ 000001_init.up.sql # Initial schema-β βββ 000002_change_ids_to_bigints.up.sql-β βββ 000003_add_ip_indx.up.sql-β βββ 000004_add_category_color.up.sql-β βββ 000005_resource_parent.up.sql-β βββ 000006_file_parent_id_constraint_rmdoc.up.sql-β βββ 000007_pin_doc.up.sql-β βββ 000008_reset_pass.up.sql-β βββ 000009_doc_meta.up.sql-β βββ 000010_nodes.up.sql # Unified node system-β βββ 000011_permissions.up.sql # Permission system-β-βββ tests/ # Integration tests- βββ client.go # Test HTTP client- βββ helpers.go # Test utilities- βββ auth_test.go # Authentication tests- βββ user_lifecycle_test.go # User CRUD tests- βββ user_admin_test.go # Admin functionality tests-```--### 3.2 Application Initialization Flow--```go-// main.go-1. Load .env file (godotenv)-2. Set domain environment variables-3. Get BACKEND_PORT from env-4. Call server.SetupServer()- ββ> Load config.toml- ββ> Initialize App struct- ββ> Connect to MySQL (DBConnection)- ββ> Connect to MinIO (MinioConnection)- ββ> Setup SMTP client (GetMailClient)- ββ> Initialize Snowflake ID generator- ββ> Initialize all services:- β ββ> UserService- β ββ> AuthService (Session)- β ββ> LogService- β ββ> NodeService- β ββ> PermissionService- β ββ> MinioService- ββ> Run database migrations-5. Initialize Gin router with CORS-6. Register route groups:- ββ> /api/auth/*- ββ> /api/users/*- ββ> /api/nodes/*- ββ> /api/permissions/*- ββ> /api/uploads/*-7. Start HTTP server on configured port-```--### 3.3 API Endpoints--#### Authentication Endpoints--| Method | Endpoint | Description | Auth Required |-| ------ | --------------------------- | ----------------------------- | ------------------- |-| POST | `/api/auth/register` | Create new user account | No |-| POST | `/api/auth/login` | Login and get JWT tokens | No |-| POST | `/api/auth/logout` | Logout and invalidate session | Yes |-| POST | `/api/auth/refresh` | Refresh access token | Yes (Refresh Token) |-| POST | `/api/auth/forgot-password` | Request password reset email | No |-| POST | `/api/auth/reset-password` | Reset password with token | No |--#### User Endpoints--| Method | Endpoint | Description | Auth Required |-| ------ | ---------------- | --------------------------- | ------------- |-| GET | `/api/users/@me` | Get current user profile | Yes |-| PATCH | `/api/users/@me` | Update current user | Yes |-| DELETE | `/api/users/@me` | Delete current user account | Yes |-| GET | `/api/users/:id` | Get user by ID (admin) | Yes (Admin) |-| GET | `/api/users` | List all users (admin) | Yes (Admin) |-| DELETE | `/api/users/:id` | Delete user (admin) | Yes (Admin) |--#### Node Endpoints (Documents & Categories)--| Method | Endpoint | Description | Auth Required |-| ------ | ------------------------- | -------------------------------- | ---------------------- |-| GET | `/api/nodes` | List user's nodes (with filters) | Yes |-| GET | `/api/nodes/:id` | Get single node details | Yes (Permission) |-| POST | `/api/nodes` | Create new node | Yes |-| PATCH | `/api/nodes/:id` | Update node | Yes (Write Permission) |-| DELETE | `/api/nodes/:id` | Delete node | Yes (Admin Permission) |-| GET | `/api/nodes/:id/children` | Get child nodes | Yes (Permission) |-| POST | `/api/nodes/:id/pin` | Pin/unpin node | Yes (Write Permission) |--#### Permission Endpoints--| Method | Endpoint | Description | Auth Required |-| ------ | ------------------------------- | ------------------------ | ------------- |-| GET | `/api/permissions/node/:nodeId` | Get node permissions | Yes (Owner) |-| POST | `/api/permissions/node/:nodeId` | Grant permission to user | Yes (Owner) |-| PATCH | `/api/permissions/:id` | Update permission level | Yes (Owner) |-| DELETE | `/api/permissions/:id` | Revoke permission | Yes (Owner) |--#### File Upload Endpoints--| Method | Endpoint | Description | Auth Required |-| ------ | ------------------ | -------------------- | ------------- |-| POST | `/api/uploads` | Upload file to CDN | Yes |-| GET | `/api/uploads` | List user's uploads | Yes |-| GET | `/api/uploads/:id` | Get file metadata | Yes |-| DELETE | `/api/uploads/:id` | Delete uploaded file | Yes |--### 3.4 Service Layer Architecture--The service layer implements the business logic and separates it from HTTP concerns:--```go-// Example: NodeService interface-type NodeService interface {- Create(node *models.Node) error- GetByID(id types.Snowflake, userID types.Snowflake) (*models.Node, error)- Update(node *models.Node, userID types.Snowflake) error- Delete(id types.Snowflake, userID types.Snowflake) error- List(userID types.Snowflake, filters NodeFilters) ([]*models.Node, error)- GetChildren(parentID types.Snowflake, userID types.Snowflake) ([]*models.Node, error)-}-```--**Service Layer Benefits:**--- Reusability across different controllers-- Easier unit testing (mock dependencies)-- Clear separation of concerns-- Consistent error handling-- Transaction management--### 3.5 Middleware Stack--Requests flow through the following middleware layers:--```-Request- β- ββ> gin.Recovery() # Panic recovery- β- ββ> CORS Middleware # Cross-origin handling- β ββ> Origin: FRONTEND_URL- β ββ> Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS- β ββ> Credentials: true- β ββ> Headers: Authorization, Content-Type, etc.- β- ββ> Authentication Middleware # JWT validation (if protected route)- β ββ> Extract JWT from Authorization header- β ββ> Validate token signature- β ββ> Check token expiration- β ββ> Load user from database- β ββ> Attach user to context- β- ββ> Admin Middleware # Role check (if admin route)- β ββ> Check user.Role == RoleAdministrator- β ββ> Return 403 if not admin- β- ββ> Controller Handler # Business logic- ββ> Response-```--### 3.6 Database Connection Management--```go-// Connection configuration-- Driver: MySQL (go-sql-driver/mysql)-- Connection pooling enabled-- Max open connections: 25-- Max idle connections: 10-- Connection max lifetime: 5 minutes-- Charset: utf8mb4 (full Unicode support)-- ParseTime: true (automatic time parsing)-- Location: UTC--// Connection string format-user:password@tcp(host:port)/database?charset=utf8mb4&parseTime=True&loc=UTC-```--### 3.7 ID Generation (Snowflake)--Alexandrie uses **Discord/Twitter Snowflake** algorithm for distributed ID generation:--```-Snowflake ID Structure (64 bits):-βββββββββββββββββββββββββββββββββββββββββββββββββββ-β 1 bit β 41 bits β 10 bits β 12 bits β-β Sign β Timestamp β Machine β Sequence β-β 0 β Millisecond β ID β Number β-βββββββββββββββββββββββββββββββββββββββββββββββββββ--Features:-- Sortable by time (timestamp-based)-- Guaranteed uniqueness across distributed systems-- No database round-trip required-- 64-bit integer (fits in BIGINT)-- Epoch: 1609459200000 (2021-01-01 00:00:00 UTC)-```-------## 4. Frontend Architecture--### 4.1 Project Structure--```-frontend/-βββ nuxt.config.ts # Nuxt configuration-βββ package.json # Dependencies-βββ bun.lock # Dependency lock file-βββ tsconfig.json # TypeScript configuration-βββ eslint.config.mjs # ESLint configuration-βββ stylelint.config.js # Stylelint configuration-βββ Dockerfile # Production container-βββ Dockerfile.dev # Development container-βββ docker-entrypoint.sh # Container startup script-β-βββ app/ # Application source-β βββ App.vue # Root component-β βββ error.vue # Error page component-β β-β βββ pages/ # Route pages (file-based routing)-β β βββ index.vue # Landing page-β β βββ dashboard.vue # Main dashboard layout-β β βββ dashboard/-β β β βββ docs/ # Document management pages-β β β β βββ index.vue # Document list-β β β β βββ new.vue # Create document-β β β β βββ edit/[id].vue # Edit document-β β β β βββ _components/ # Document-specific components-β β β β βββ DocumentCard*.vue-β β β β βββ DocumentEditor.vue-β β β β βββ table-of-content/-β β β β-β β β βββ cdn/ # File management-β β β β βββ index.vue-β β β β βββ [id]/-β β β β βββ _modals/-β β β β-β β β βββ admin.vue # Admin panel-β β β-β β βββ auth/ # Authentication pages-β β βββ login.vue-β β βββ register.vue-β β-β βββ components/ # Reusable components-β β βββ layout/ # Layout components-β β β βββ Header.vue-β β β βββ Sidebar.vue-β β β βββ Footer.vue-β β β-β β βββ ui/ # UI components-β β β βββ Button.vue-β β β βββ Modal.vue-β β β βββ Dropdown.vue-β β β βββ Input.vue-β β β-β β βββ editor/ # Editor components-β β βββ MarkdownEditor.vue-β β βββ MarkdownPreview.vue-β β βββ EditorToolbar.vue-β β-β βββ composables/ # Composition API functions-β β βββ useAuth.ts # Authentication logic-β β βββ useApi.ts # API client wrapper-β β βββ useNodes.ts # Node operations-β β βββ usePermissions.ts # Permission checks-β β βββ useTheme.ts # Theme management-β β-β βββ stores/ # Pinia stores (state management)-β β βββ index.ts # Store exports-β β βββ user.store.ts # User state & auth-β β βββ nodes.store.ts # Documents & categories-β β βββ resources.store.ts # File uploads-β β βββ admin.store.ts # Admin functionality-β β βββ collection.ts # Collection helpers-β β βββ db_structures.d.ts # TypeScript definitions-β β-β βββ middleware/ # Route middleware-β β βββ auth.ts # Authentication guard-β β βββ guest.ts # Guest-only guard-β β βββ admin.ts # Admin-only guard-β β-β βββ helpers/ # Helper functions-β β βββ colors.ts # Colors management in the app (primary, available in selector etc.)-β β βββ importations.ts # Decoder for JSON Nodes format-β β βββ paginator.ts # Pagniation helper for datatable-β β βββ navigation.ts # Navigation constants-β β βββ resources.ts # Files management (file size, filetype, resolveUrl)-β β βββ utils.ts # General helpers-β β-β βββ styles/ # Global styles-β β βββ main.scss # Main stylesheet-β β βββ _variables.scss # SCSS variables-β β βββ katex/ # Math rendering styles-β β-β βββ assets/ # Static assets-β βββ images/-β βββ fonts/-β-βββ public/ # Static files- βββ favicon.ico- βββ icons/ # App icons- βββ app-icons/ # SVG icons - from https://fonts.google.com/icons- βββ screenshots/ # App screenshots & mocks- βββ Logo/ # Brand assets-```--### 4.2 State Management (Pinia Stores)--#### User Store (`user.store.ts`)--```typescript-// Manages authentication and user profile--State:-- user: User | null // Current user object-- isAuthenticated: boolean // Auth status-- loading: boolean // Loading state (to display loading indicator in interface)--Actions:-- login(credentials) // Login user-- logout() // Logout user-- register(userData) // Create account-- updateProfile(data) // Update user info-- fetchProfile() // Load current user--Getters:-- isAdmin // Check if user is admin-- fullName // User's full name-- initials // User initials for avatar-```--#### Nodes Store (`nodes.store.ts`)--```typescript-// Manages documents and categories--State:-- nodes: Node[] // All nodes (docs + categories)-- loading: boolean-- searchQuery: string--Actions:-- fetchNodes(filters) // Load nodes with filters-- getNode(id) // Get single node-- createNode(data) // Create document/category-- updateNode(id, data) // Update node-- deleteNode(id) // Delete node-- searchNodes(query) // Search functionality with advanced options, see available in the file--Getters:-- workspaces // Filter nodes with role=1-- categories // Filter nodes with role=2-- documents // Filter nodes with role=3-- resources // Filter nodes with role=4-```--#### Resources Store (`resources.store.ts`)--```typescript-// Manages file uploads and CDN resources--State:-- resources: Resource[] // Uploaded files-- loading: boolean-- uploadProgress: number--Actions:-- uploadFile(file) // Upload to CDN-- fetchResources() // List all uploads-- deleteResource(id) // Remove file-- getResourceUrl(id) // Get CDN URL--Getters:-- images // Filter image files-- documents // Filter document files-- totalSize // Total storage used-```--### 4.3 Routing System+## Quick Start-Nuxt uses **file-based routing** where the file structure determines routes:--```-pages/index.vue β /-pages/dashboard.vue β /dashboard-pages/dashboard/docs.vue β /dashboard/docs-pages/dashboard/docs/new.vue β /dashboard/docs/new-pages/dashboard/docs/edit/[id].vue β /dashboard/docs/edit/:id (dynamic)-```--#### Route Guards (Middleware)--```typescript-// auth.ts - Protect authenticated routes-export default defineNuxtRouteMiddleware((to, from) => {- const userStore = useUserStore();-- if (!userStore.isAuthenticated) {- return navigateTo('/auth/login');- }-});--// admin.ts - Protect admin routes-export default defineNuxtRouteMiddleware((to, from) => {- const userStore = useUserStore();-- if (!userStore.isAdmin) {- return navigateTo('/dashboard');- }-});-```--### 4.4 Markdown Editor Implementation--Alexandrie uses **CodeMirror 6** for the Markdown editor:--```typescript-// Key CodeMirror extensions used:--import { EditorView } from '@codemirror/view';-import { EditorState } from '@codemirror/state';-import { markdown } from '@codemirror/lang-markdown';-import { autocompletion } from '@codemirror/autocomplete';-import { search } from '@codemirror/search';-import { highlightSelectionMatches } from '@codemirror/search';--// Editor configuration-const editorView = new EditorView({- state: EditorState.create({- doc: initialContent,- extensions: [- markdown(), // Markdown syntax- autocompletion(), // Autocomplete- search(), // Search & replace- highlightSelectionMatches(), // Highlight matches- // Custom theme- // Keybindings- // Event handlers- ],- }),- parent: editorElement,-});-```--#### Markdown Rendering--```typescript-// markdown-it configuration for rendering--import MarkdownIt from 'markdown-it';-import markdownItAnchor from 'markdown-it-anchor';-import markdownItContainer from 'markdown-it-container';-import markdownItHighlightjs from 'markdown-it-highlightjs';-import markdownItMark from 'markdown-it-mark';-import markdownItUnderline from 'markdown-it-underline';--const md = new MarkdownIt({- html: true, // Enable HTML tags- linkify: true, // Auto-convert URLs to links- typographer: true, // Smart quotes, dashes- breaks: false, // Convert \n to <br>-})- .use(markdownItAnchor, {- /* heading anchors */- })- .use(markdownItContainer, 'warning') // ::: warning blocks- .use(markdownItContainer, 'info') // ::: info blocks- .use(markdownItHighlightjs) // Code syntax highlighting- .use(markdownItMark) // ==marked text==- .use(markdownItUnderline); // ++underlined text++--// Render markdown to HTML-const html = md.render(markdownContent);-```--#### KaTeX Math Rendering--```typescript-// Math formula rendering with KaTeX--import katex from 'katex';--// Inline math: $formula$-// Block math: $$formula$$--// Custom markdown-it plugin for math-md.use(markdownItMath, {- engine: katex,- delimiters: 'dollars',-});-```--### 4.6 Component Architecture--```vue-<!-- Example: DocumentCard.vue -->--<template>- <div class="document-card" @click="openDocument">- <div class="document-header">- <Icon :name="node.icon" />- <h3>{{ node.name }}</h3>- </div>-- <div class="document-meta">- <span>{{ formatDate(node.updated_timestamp) }}</span>- <Badge v-if="node.tags">{{ node.tags }}</Badge>- </div>-- <div class="document-actions">- <AppButton @click.stop="shareDocument">Share</AppButton>- </div>- </div>-</template>--<script setup lang="ts">-// NOTHING :) Nuxt automaticly import components from "app/components" folder-import type { Node } from '~/stores';-</script>--<style scoped lang="scss">-.document-card {- // Component styles-}-</style>-```--### 4.7 Theme System--```typescript-// Color mode configuration--// nuxt.config.ts-colorMode: {- preference: 'light', // Default theme- fallback: 'light', // Fallback if no system preference- classSuffix: '' // CSS class suffix-}--// Usage in components-const colorMode = useColorMode()--// Switch theme-colorMode.preference = 'dark'--// CSS variables per theme-:root {- // Default variables correspond to the default primary color- --default: #3956e7;- --default-dark: #2c3eb9;- --default-bg: #dde1f8;- --default-border: #dde1f8;-- --bg-color: #ffffff;- --bg-contrast: #fbfbfb;- --font-color: #3c4450;-}--.dark {- --color-bg: #1a1a1a;- --color-text: #ffffff;- --color-primary: #5c7cfa;-}-```-------## 5. Data Models--### 5.1 User Model--```go-type User struct {- Id Snowflake `json:"id"`- Username string `json:"username"` // 5-30 chars, unique- Firstname *string `json:"firstname"` // Optional- Lastname *string `json:"lastname"` // Optional- Role int `json:"role"` // 1: user, 2: admin- Avatar *string `json:"avatar"` // Avatar URL- Email string `json:"email"` // Email address, unique- Password string `json:"-"` // Bcrypt hash (hidden from JSON)- CreatedTimestamp int64 `json:"created_timestamp"`- UpdatedTimestamp int64 `json:"updated_timestamp"`-}-```--**Database Schema:**--```sql-CREATE TABLE `users` (- `id` varchar(50) NOT NULL PRIMARY KEY,- `username` varchar(25) NOT NULL UNIQUE,- `firstname` varchar(25) DEFAULT NULL,- `lastname` varchar(25) DEFAULT NULL,- `role` int NOT NULL DEFAULT '1',- `avatar` varchar(75) DEFAULT NULL,- `email` varchar(50) NOT NULL UNIQUE,- `password` varchar(255) NOT NULL,- `created_timestamp` bigint NOT NULL,- `updated_timestamp` bigint NOT NULL-);-```--### 5.2 Node Model (Unified Document/Category)--```go-type Node struct {- // Core fields- Id Snowflake `json:"id"`- UserId Snowflake `json:"user_id"` // Owner- ParentId *Snowflake `json:"parent_id"` // Hierarchical structure- Name string `json:"name"` // Display name (max 50 chars)- Description *string `json:"description"` // Optional description (max 250)- Tags *string `json:"tags"` // Comma-separated tags-- // Node type and appearance- Role int `json:"role"` // 1: workspace, 2: category, 3: document- Color *int `json:"color"` // Color code for UI- Icon *string `json:"icon"` // Icon identifier- Thumbnail *string `json:"thumbnail"` // Thumbnail URL- Theme *string `json:"theme"` // Custom theme settings-- // Access control- Accessibility *int `json:"accessibility"` // 0: Public, 1: Private, 2: Unlisted- Access int `json:"access"` // Bit field: 1=view, 2=edit-- // Display and ordering- Display *int `json:"display"` // Display mode- Order *int `json:"order"` // Sort order (-1: pinned, -2: bookmark)-- // Content (for document nodes)- Content *string `json:"content"` // Markdown content- ContentCompiled *string `json:"content_compiled"` // Rendered HTML- Size *int64 `json:"size"` // Content size in bytes-- // Metadata- Metadata *JSONB `json:"metadata"` // Additional JSON data- CreatedTimestamp int64 `json:"created_timestamp"`- UpdatedTimestamp int64 `json:"updated_timestamp"`-- // Relations- Permissions []*Permission `json:"permissions"` // Access permissions-}-```--**Node Roles:**--- `1` - Workspace: Top-level container-- `2` - Category: Organizational folder-- `3` - Document: Actual note/content-- `4` - Resource: An uploaded file--**Accessibility Levels:**--- `0` - Public: Anyone can view-- `1` - Private: Only owner and permitted users-- `2` - Unlisted: Accessible via direct link--### 5.3 Permission Model--```go-type Permission struct {- Id Snowflake `json:"id"`- NodeId Snowflake `json:"node_id"` // Target node- UserId *Snowflake `json:"user_id"` // User granted permission- Email *string `json:"email"` // Or email for invite- Level int `json:"level"` // Permission level (1-5)- CreatedTimestamp int64 `json:"created_timestamp"`- UpdatedTimestamp int64 `json:"updated_timestamp"`-}-```--**Permission Levels:**--```go-const (- PermNone = 0 // No access- PermRead = 1 // Read-only access- PermWrite = 2 // Can edit content- PermAdmin = 3 // Can delete, share- PermOwner = 4 // Full control, manage permissions-)-```--**Permission Actions:**--```go-const (- ActionRead = 1 // Requires: PermRead- ActionUpdate = 2 // Requires: PermWrite- ActionDelete = 3 // Requires: PermAdmin- ActionShare = 4 // Requires: PermAdmin- ActionManagePermissions = 5 // Requires: PermOwner-)-```--### 5.4 Session Model--```go-type Session struct {- Id Snowflake `json:"id"`- UserId Snowflake `json:"user_id"`- RefreshToken *string `json:"refresh_token"` // JWT refresh token- ExpireToken *int64 `json:"expire_token"` // Token expiration- LastRefreshTimestamp *int64 `json:"last_refresh_timestamp"`- Active *int `json:"active"` // 1: active, 0: inactive- LoginTimestamp *int64 `json:"login_timestamp"`- LogoutTimestamp *int64 `json:"logout_timestamp"`-}-```--### 5.5 Resource Model (File Uploads)--```go-type Resource struct {- Id Snowflake `json:"id"`- Filename string `json:"filename"`- FileSize int `json:"file_size"` // Bytes- FileType string `json:"file_type"` // MIME type- OriginalPath string `json:"original_path"` // S3 path- TransformedPath *string `json:"transformed_path"` // Optimized version- ParentId *Snowflake `json:"parent_id"` // Parent node- AuthorId Snowflake `json:"author_id"`- CreatedTimestamp int64 `json:"created_timestamp"`-}-```--### 5.6 Activity Log Model--```go-type ConnectionLog struct {- Id Snowflake `json:"id"`- UserId Snowflake `json:"user_id"`- IpAddress *string `json:"ip_address"`- UserAgent *string `json:"user_agent"`- Location *string `json:"location"` // Geolocation- Type string `json:"type"` // "login", "logout", "failed"- Timestamp int64 `json:"timestamp"`-}-```--### 5.7 Entity Relationships--```-βββββββββββββββ-β User β-ββββββββ¬βββββββ- β 1- β- β owns- β- βββββββββββββββββββ¬ββββββββββββββββββ¬βββββββββββββββββ- β * β * β * β- βΌ βΌ βΌ βΌ-ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ-β Node β β Resource β β Session β β Log β-ββββββ¬ββββββ ββββββββββββ ββββββββββββ ββββββββββββ- β parent- β *- βΌ-ββββββββββββ-β Node β (child nodes - recursive)-β β-β can have β-ββββββ¬ββββββ- β *- βΌ-βββββββββββββββ-β Permission β-β (shared β-β access) β-βββββββββββββββ-```+For local testing, you can run Alexandrie directly using the provided `docker-compose.yml`:------## 6. Key Features Implementation--### 6.1 Authentication Flow--#### Registration--```-User submits registration form- ββ> Frontend validates input (email, password strength)- ββ> POST /api/auth/register- β ββ> Backend validates data (Gin binding validation)- β ββ> Check if username already exists- β ββ> Hash password with bcrypt- β ββ> Generate Snowflake ID- β ββ> Create user in database- β ββ> Return tokens + user data- ββ> Frontend stores tokens (localStorage + cookie)- ββ> Redirect to dashboard-```--#### Login--```-User submits credentials- ββ> POST /api/auth/login- β ββ> Find user by email- β ββ> Compare password with bcrypt hash- β ββ> Generate JWT tokens- β β ββ> Access token: expires in 15 minutes- β β ββ> Refresh token: expires in 7 days- β ββ> Create/update session- β ββ> Log connection (IP, user agent, geolocation)- β ββ> Return tokens + user data- ββ> Frontend stores tokens- ββ> Initialize user store- ββ> Redirect to dashboard-```--#### Token Refresh--```-Access token expired (401 response)- ββ> Frontend intercepts 401- ββ> POST /api/auth/refresh (with refresh token)- β ββ> Validate refresh token- β ββ> Check session is active- β ββ> Generate new access token- β ββ> Update session last_refresh_timestamp- β ββ> Return new access token- ββ> Frontend stores new token- ββ> Retry original request- ββ> Frontend reveive an error- ββ> User disconnected-```--#### JWT Token Structure--```go-// Access Token Claims-{- "user_id": "123456789",- "username": "johndoe",- "role": 1,- "exp": 1234567890, // 15 minutes from issue- "iat": 1234567000-}--// Refresh Token Claims-{- "user_id": "123456789",- "session_id": "987654321",- "exp": 1235172000, // 7 days from issue- "iat": 1234567000-}-```--### 6.2 Node System (Documents & Categories)--#### Node Creation--```-User clicks "New Document" or "New Category"- ββ> Frontend shows creation modal- ββ> User fills form (name, parent, role, etc.)- ββ> POST /api/nodes- β ββ> Validate input (name required, max length)- β ββ> Check parent exists (if provided)- β ββ> Check user has write permission on parent- β ββ> Generate Snowflake ID- β ββ> Set default values:- β β ββ> user_id: current user- β β ββ> accessibility: 1 (private)- β β ββ> access: 3 (view + edit for owner)- β β ββ> timestamps- β ββ> Insert into database- β ββ> Return created node- ββ> Frontend updates nodes store- ββ> Navigate to node (if document)-```--#### Hierarchical Structure--```-Workspace (role=1)- ββ Category (role=2, parent_id=workspace.id)- ββ Document (role=3, parent_id=category.id)- ββ Document (role=3, parent_id=category.id)- ββ Sub-category (role=2, parent_id=category.id)- ββ Document (role=3, parent_id=sub-category.id)-```--#### Node Retrieval with Permissions--```go-// Service layer logic for GetNode--func (s *NodeService) GetNode(nodeId, userId Snowflake) (*Node, error) {- // 1. Load node from database- node := loadNodeFromDB(nodeId)-- // 2. Check if user is owner- if node.UserId == userId {- return node, nil // Owner has full access- }-- // 3. Load permissions for this node- permissions := loadPermissions(nodeId)-- // 4. Check if user has permission- for _, perm := range permissions {- if perm.UserId == userId && perm.Level >= PermRead {- return node, nil- }- }-- // 5. Check accessibility- if node.Accessibility == Public {- return node, nil // Public nodes are visible to all- }-- return nil, ErrForbidden-}-```--### 6.3 Permission System--#### Granting Permission--```-Node owner shares document- ββ> GET /api/users (search for user)- ββ> Select user and permission level- ββ> POST /api/permissions/node/:nodeId- β ββ> Verify requester is owner (PermOwner level)- β ββ> Validate permission level (1-4)- β ββ> Check if permission already exists- β β ββ> If exists: update level- β β ββ> If not: create new permission- β ββ> Insert/update database- β ββ> Return permission object- ββ> Frontend updates UI- ββ> Send notification (if implemented)-```--#### Permission Checking--```go-// Check if user can perform action on node--func CanPerform(userId, nodeId Snowflake, action NodeAction) bool {- // 1. Load node- node := getNode(nodeId)-- // 2. Owner always has full access- if node.UserId == userId {- return true- }-- // 3. Get required permission level for action- requiredLevel := action.RequiredLevel()-- // 4. Load user's permission for this node- permission := getPermission(nodeId, userId)-- // 5. Compare levels- return permission.Level >= requiredLevel-}--// Examples:-CanPerform(userId, nodeId, ActionRead) // Requires PermRead (1)-CanPerform(userId, nodeId, ActionUpdate) // Requires PermWrite (2)-CanPerform(userId, nodeId, ActionDelete) // Requires PermAdmin (3)-CanPerform(userId, nodeId, ActionManagePermissions) // Requires PermOwner (4)-```--#### Inherited Permissions--```-When checking permissions on a node:- 1. Check direct permissions on the node- 2. If no permission found, check parent node- 3. Recurse up the tree until permission found or root reached- 4. If accessibility is Public, grant read access- 5. Otherwise, deny access-```--### 6.4 File Storage (S3/MinIO)--#### File Upload Flow--```-User uploads file (drag & drop or file picker)- ββ> Frontend validates file:- β ββ> Check file size (max from config)- β ββ> Check file type (supported formats)- ββ> POST /api/uploads (multipart/form-data)- β ββ> Backend receives file- β ββ> Validate file size and type- β ββ> Generate unique filename (UUID + extension)- β ββ> Upload to MinIO/RustFS:- β β ββ> Bucket: "alexandrie"- β β ββ> Path: uploads/{userId}/{filename}- β β ββ> Set content type- β ββ> Create resource record in database (node, role=4)- β ββ> Return resource object with URLs- ββ> Frontend displays uploaded file- ββ> Update resources store-```--#### File Access--```-User requests node (view node)- ββ> GET /api/uploads/:id- β ββ> Load resource from database- β ββ> Check user has access:- β β ββ> User is owner, OR- β β ββ> File is in a node user can access- β β ββ> (Check node permissions)- β ββ> Generate presigned URL from MinIO- β β ββ> Valid for 1 hour- β ββ> Return presigned URL- ββ> Frontend redirects to presigned URL- ββ> Browser downloads from MinIO directly-```--To access the file, the request must be on the S3 server directly (minio, rustfs etc.)--### 6.5 Search Functionality--#### Frontend Search UX--```typescript-// Debounced search composable--const searchQuery = ref('');-const searchResults = ref<Node[]>([]);--// Debounce to avoid excessive API calls-const debouncedSearch = useDebounceFn(async (query: string) => {- if (query.length < 2) {- searchResults.value = [];- return;- }-- const results = await api(`/api/nodes?search=${query}`);- searchResults.value = results;-}, 300);--watch(searchQuery, newQuery => {- debouncedSearch(newQuery);-});-```--### 6.6 Export Functionality--#### Markdown Export--```typescript-// Generate .md file from node content--const exportMarkdown = (node: Node) => {- const content = `# ${node.name}\n\n${node.content}`;- const blob = new Blob([content], { type: 'text/markdown' });- const url = URL.createObjectURL(blob);-- const link = document.createElement('a');- link.href = url;- link.download = `${node.name}.md`;- link.click();-- URL.revokeObjectURL(url);-};-```--#### PDF Export--```typescript-// Use browser's print functionality with custom styles--const exportPDF = (node: Node) => {- // Render node content in printable format- const printWindow = window.open('', '_blank');- printWindow.document.write(`- <!DOCTYPE html>- <html>- <head>- <title>${node.name}</title>- <style>- /* Print-optimized styles */- body { font-family: serif; }- @page { margin: 2cm; }- </style>- </head>- <body>- <h1>${node.name}</h1>- ${node.content_compiled}- </body>- </html>- `);-- printWindow.document.close();- printWindow.print();-};-```--## 7. External Services Integration--### 7.1 MySQL Database--#### Connection Configuration--```go-// Database connection from environment variables--DATABASE_HOST=mysql // Container name or hostname-DATABASE_PORT=3306 // MySQL default port-DATABASE_NAME=alexandrie // Database name-DATABASE_USER=alexandrie // Database user-DATABASE_PASSWORD=password // User password--// Connection string-dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=UTC",- user, password, host, port, database)--// Connection pool settings-db.SetMaxOpenConns(25) // Maximum open connections-db.SetMaxIdleConns(10) // Maximum idle connections-db.SetConnMaxLifetime(5 * time.Minute)-```--#### Migration System--```go-// Database migrations using golang-migrate--// Migration files format: {version}_{name}.{up|down}.sql-// Example: 000001_init.up.sql--// Run migrations on application start-func Migrate(config *Config) {- driver, _ := mysql.WithInstance(db, &mysql.Config{})-- m, _ := migrate.NewWithDatabaseInstance(- "file://migrations",- "mysql",- driver,- )-- // Apply all pending migrations- m.Up()-}--// Migration history tracked in schema_migrations table-```--#### Transactions--```go-// Example transaction for creating node with permissions--func CreateNodeWithPermissions(node *Node, permissions []*Permission) error {- // Begin transaction- tx, err := db.Begin()- if err != nil {- return err- }-- // Defer rollback (no-op if commit succeeds)- defer tx.Rollback()-- // Insert node- _, err = tx.Exec("INSERT INTO nodes (...) VALUES (...)", node)- if err != nil {- return err // Automatic rollback- }-- // Insert permissions- for _, perm := range permissions {- _, err = tx.Exec("INSERT INTO permissions (...) VALUES (...)", perm)- if err != nil {- return err // Automatic rollback- }- }-- // Commit transaction- return tx.Commit()-}-```--### 7.2 MinIO/RustFS (S3-Compatible Storage)--#### Connection Setup--```go-// MinIO client initialization--import "github.com/minio/minio-go/v7"--MINIO_ENDPOINT=rustfs:9000 // S3 endpoint-MINIO_ACCESSKEY=alexandrie-key // Access key-MINIO_SECRETKEY=alexandrie-secret // Secret key-MINIO_BUCKET=alexandrie // Bucket name--// Initialize client-minioClient, err := minio.New(endpoint, &minio.Options{- Creds: credentials.NewStaticV4(accessKey, secretKey, ""),- Secure: false, // Use HTTPS in production-})--// Ensure bucket exists-exists, _ := minioClient.BucketExists(context.Background(), bucketName)-if !exists {- minioClient.MakeBucket(context.Background(), bucketName, minio.MakeBucketOptions{})-}-```--#### File Operations--```go-// Upload file to S3--func (s *MinioService) UploadFile(file multipart.File, filename string) (string, error) {- // Generate object path- objectPath := fmt.Sprintf("uploads/%s/%s", userId, filename)-- // Upload to MinIO- info, err := s.client.PutObject(- context.Background(),- s.bucketName,- objectPath,- file,- fileSize,- minio.PutObjectOptions{- ContentType: contentType,- },- )-- return objectPath, err-}--// Generate presigned URL for download--func (s *MinioService) GetPresignedURL(objectPath string) (string, error) {- url, err := s.client.PresignedGetObject(- context.Background(),- s.bucketName,- objectPath,- time.Hour, // Valid for 1 hour- nil,- )-- return url.String(), err-}--// Delete file--func (s *MinioService) DeleteFile(objectPath string) error {- return s.client.RemoveObject(- context.Background(),- s.bucketName,- objectPath,- minio.RemoveObjectOptions{},- )-}-```--#### CDN Configuration--```-Frontend CDN URL: NUXT_PUBLIC_BASE_CDN-Example: https://cdn.alexandrie-hub.fr/alexandrie--Image access:- Full URL: {BASE_CDN}/{objectPath}- Example: https://cdn.alexandrie-hub.fr/alexandrie/uploads/123/image.jpg--For production, configure MinIO with:- - Custom domain (cdn.example.com)- - CloudFront or similar CDN in front- - Public read access for public files- - Presigned URLs for private files-```--### 7.3 SMTP Email Service--#### Configuration--```go-// SMTP client setup using go-mail--SMTP_HOST=smtp.example.com // SMTP server-SMTP_PORT=587 // SMTP port (587 for TLS)[email protected] // From address-SMTP_PASSWORD=yourpassword // SMTP password--// Initialize mail client-import "github.com/wneessen/go-mail"--mailClient, err := mail.NewClient(- smtpHost,- mail.WithPort(587),- mail.WithSMTPAuth(mail.SMTPAuthPlain),- mail.WithUsername(smtpMail),- mail.WithPassword(smtpPassword),- mail.WithTLSPolicy(mail.TLSMandatory),-)-```--#### Sending Emails--```go-// Password reset email example--func SendPasswordResetEmail(email, resetToken string) error {- m := mail.NewMsg()-- m.From(smtpMail)- m.To(email)- m.Subject("Password Reset - Alexandrie")-- resetURL := fmt.Sprintf("%s/auth/reset-password?token=%s",- frontendURL, resetToken)-- body := fmt.Sprintf(`- <h2>Password Reset Request</h2>- <p>Click the link below to reset your password:</p>- <a href="%s">Reset Password</a>- <p>This link expires in 1 hour.</p>- `, resetURL)-- m.SetBodyString(mail.TypeTextHTML, body)-- return mailClient.DialAndSend(m)-}-```--**Email Use Cases:**--- Password reset requests-- Collaboration invites (future)--### 7.4 Geolocation Service--#### IP Geolocation--Alexandrie includes MaxMind GeoLite2 database integration for tracking login locations:--```sql--- Geolocation tables--city_locations_fr -- City and region information-city_ipv4_complete -- IPv4 address ranges-city_ipv6_complete -- IPv6 address ranges-```--```go-// Get location from IP address--func GetLocationFromIP(ipAddress string) string {- // Parse IP- ip := net.ParseIP(ipAddress)-- // Query appropriate table based on IP version- var geonameId int- if ip.To4() != nil {- // IPv4 query- query := `- SELECT geoname_id- FROM city_ipv4_complete- WHERE INET_ATON(?) BETWEEN network_start_integer AND network_last_integer- `- db.QueryRow(query, ipAddress).Scan(&geonameId)- } else {- // IPv6 query (similar logic)- }-- // Get city information- var city, country string- query := `- SELECT city_name, country_name- FROM city_locations_fr- WHERE geoname_id = ?- `- db.QueryRow(query, geonameId).Scan(&city, &country)-- return fmt.Sprintf("%s, %s", city, country)-}-```--**Usage:**--- Log user login locations-- Security monitoring-- Suspicious activity detection (not implemented yet)--## 8. Security Implementation--### 8.1 Authentication Security--#### Password Hashing--```go-import "golang.org/x/crypto/bcrypt"--// Hash password with bcrypt (cost: 12)-func HashPassword(password string) (string, error) {- bytes, err := bcrypt.GenerateFromPassword([]byte(password), 12)- return string(bytes), err-}--// Verify password-func CheckPassword(password, hash string) bool {- err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))- return err == nil-}-```--**Security Features:**--- Bcrypt with cost factor 12 (secure against brute force)-- Salted hashing (built into bcrypt)-- Passwords never stored in plain text-- Passwords never logged or included in JSON responses--#### JWT Security--```go-import "github.com/golang-jwt/jwt/v5"--JWT_SECRET=your-secure-secret-key // Must be strong random string--// Generate token-func GenerateToken(userId Snowflake, role int, duration time.Duration) string {- claims := jwt.MapClaims{- "user_id": userId,- "role": role,- "exp": time.Now().Add(duration).Unix(),- "iat": time.Now().Unix(),- }-- token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)- signedToken, _ := token.SignedString([]byte(jwtSecret))- return signedToken-}--// Validate token-func ValidateToken(tokenString string) (*jwt.Token, error) {- return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {- // Verify signing method- if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {- return nil, fmt.Errorf("unexpected signing method")- }- return []byte(jwtSecret), nil- })-}-```--**Token Expiration:**--- Access Token: 15 minutes (short-lived)-- Refresh Token: 7 days (stored in database)--#### Session Management--```go-// Session tracking--type Session struct {- Id Snowflake- UserId Snowflake- RefreshToken string- Active bool- LoginTime int64- LogoutTime int64-}--// Invalidate session on logout-func Logout(sessionId Snowflake) {- db.Exec("UPDATE sessions SET active = 0, logout_timestamp = ? WHERE id = ?",- time.Now().Unix(), sessionId)-}--// Clean expired sessions (cron job)-func CleanExpiredSessions() {- db.Exec("DELETE FROM sessions WHERE expire_token < ?", time.Now().Unix())-}-```--### 8.2 Authorization--#### Role-Based Access Control (RBAC)--```go-// User roles-const (- RoleUser = 1 // Regular user- RoleAdmin = 2 // Administrator-)--// Admin middleware-func AdminOnly(c *gin.Context) {- user := c.MustGet("user").(User)-- if user.Role != RoleAdmin {- c.JSON(403, gin.H{"error": "Admin access required"})- c.Abort()- return- }-- c.Next()-}--// Apply to routes-adminRoutes := router.Group("/api/admin")-adminRoutes.Use(AuthMiddleware, AdminOnly)-{- adminRoutes.GET("/users", controllers.ListUsers)- adminRoutes.DELETE("/users/:id", controllers.DeleteUser)-}-```--#### Permission-Based Access Control--```go-// Check permission before node operation--func RequireNodePermission(action NodeAction) gin.HandlerFunc {- return func(c *gin.Context) {- nodeId := c.Param("id")- user := c.MustGet("user").(User)-- // Check if user can perform action- can := permissions.CanPerform(user.Id, nodeId, action)-- if !can {- c.JSON(403, gin.H{"error": "Permission denied"})- c.Abort()- return- }-- c.Next()- }-}--// Apply to routes-router.PATCH("/api/nodes/:id",- AuthMiddleware,- RequireNodePermission(ActionUpdate),- controllers.UpdateNode)-```--### 8.3 Input Validation--#### Backend Validation--```go-// Gin binding validation--type CreateNodeInput struct {- Name string `json:"name" binding:"required,min=1,max=50"`- Description *string `json:"description" binding:"omitempty,max=250"`- ParentId *string `json:"parent_id" binding:"omitempty"`- Role int `json:"role" binding:"required,min=1,max=3"`-}--// Validate in controller-func CreateNode(c *gin.Context) {- var input CreateNodeInput-- if err := c.ShouldBindJSON(&input); err != nil {- c.JSON(400, gin.H{"error": err.Error()})- return- }-- // Input is valid, proceed...-}-```--**Validation Rules:**--- Required fields checked-- String length limits enforced-- Email format validation-- Integer range validation-- Custom validators for complex rules--#### Frontend Validation--```typescript-// Vue form validation--const validateNodeName = (name: string): boolean => {- if (!name || name.trim().length === 0) {- return false;- }- if (name.length > 50) {- return false;- }- return true;-};--// Usage in form-const errors = ref<Record<string, string>>({});--const submitForm = () => {- errors.value = {};-- if (!validateNodeName(form.name)) {- errors.value.name = 'Name must be 1-50 characters';- return;- }-- // Submit if valid- api.createNode(form);-};-```--### 8.4 XSS Prevention--```go-import "github.com/microcosm-cc/bluemonday"--// HTML sanitization policy-policy := bluemonday.UGCPolicy()--// Sanitize user input before storing-func SanitizeHTML(input string) string {- return policy.Sanitize(input)-}--// Apply to content-node.Content = SanitizeHTML(userInput)-```--**Frontend XSS Protection:**--```vue-<!-- Vue automatically escapes content -->-<div>{{ userContent }}</div>-<!-- Safe: content escaped -->--<!-- For rendering HTML, use v-html with sanitized content -->-<div v-html="sanitizedHTML"></div>--<!-- Never use v-html with raw user input! -->-```--### 8.5 CORS Configuration--```go-// CORS middleware configuration--router.Use(cors.New(cors.Config{- AllowOrigins: []string{os.Getenv("FRONTEND_URL")},- AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},- AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},- ExposeHeaders: []string{"Content-Length"},- AllowCredentials: true, // Allow cookies- MaxAge: 12 * time.Hour,-}))-```--**Production CORS:**--- Only allow specific frontend domain-- No wildcards in production-- Credentials enabled for cookies-- Preflight caching for performance--### 8.6 SQL Injection Prevention--```go-// Always use parameterized queries--// β SAFE: Parameterized query-query := "SELECT * FROM users WHERE email = ?"-db.QueryRow(query, userEmail).Scan(&user)--// β UNSAFE: String concatenation-query := "SELECT * FROM users WHERE email = '" + userEmail + "'"-db.QueryRow(query).Scan(&user) // Vulnerable to SQL injection!-```--### 8.7 Rate Limiting (Recommended for Production)--```go-// Example rate limiting middleware (not currently implemented)--import "golang.org/x/time/rate"--var limiters = make(map[string]*rate.Limiter)--func RateLimitMiddleware() gin.HandlerFunc {- return func(c *gin.Context) {- ip := c.ClientIP()-- limiter, exists := limiters[ip]- if !exists {- // 100 requests per minute- limiter = rate.NewLimiter(rate.Every(time.Minute/100), 100)- limiters[ip] = limiter- }-- if !limiter.Allow() {- c.JSON(429, gin.H{"error": "Rate limit exceeded"})- c.Abort()- return- }-- c.Next()- }-}-```--### 8.8 HTTPS Enforcement--```go-ALLOW_UNSECURE=false // Enforce HTTPS--// Middleware to redirect HTTP to HTTPS-func HTTPSRedirect() gin.HandlerFunc {- return func(c *gin.Context) {- if c.Request.TLS == nil && !allowUnsecure {- c.Redirect(301, "https://"+c.Request.Host+c.Request.RequestURI)- c.Abort()- return- }- c.Next()- }-}-```--**Production Security Checklist:**--- β HTTPS enforced (TLS 1.2+)-- β HSTS header enabled-- β Secure cookie flags (httpOnly, secure, sameSite)-- β JWT secret is strong random string-- β Database passwords are strong-- β CORS restricted to frontend domain-- β All inputs validated and sanitized-- β SQL injection prevented (parameterized queries)-- β Rate limiting enabled-- β Security headers set (CSP, X-Frame-Options, etc.)-------## 9. Development Workflow--### 9.1 Prerequisites--**Required Software:**--- [Bun](https://bun.sh/) v1.0+ - Fast JavaScript runtime & package manager-- [Go](https://go.dev/) v1.24+ - Backend language-- [MySQL](https://www.mysql.com/) 8.0+ - Database server-- [Docker](https://www.docker.com/) (optional) - Containerization-- [Git](https://git-scm.com/) - Version control--### 9.2 Local Development Setup--#### Option 1: Docker (Recommended)--```bash-# Clone repository-git clone https://github.com/Smaug6739/Alexandrie.git-cd Alexandrie--# Start all services with hot reload-docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build--# Access points:-# - Frontend: http://localhost:8200-# - Backend: http://localhost:8201-# - MinIO Console: http://localhost:9001-# - MySQL: localhost:3307--# Stop services-docker compose down-```--#### Option 2: Manual Setup--```bash-# 1. Install dependencies--# Backend-cd backend-go mod download--# Frontend-cd frontend-bun install--# 2. Configure environment variables--# Backend: backend/.env-DATABASE_HOST=localhost-DATABASE_PORT=3306-DATABASE_NAME=alexandrie-DATABASE_USER=alexandrie-DATABASE_PASSWORD=password-BACKEND_PORT=8201-FRONTEND_URL=http://localhost:8200-JWT_SECRET=your-secret-key-ALLOW_UNSECURE=true-GIN_MODE=debug--# Frontend: frontend/.env-PORT=8200-NUXT_PUBLIC_BASE_API=http://localhost:8201-NUXT_PUBLIC_BASE_CDN=http://localhost:9000/alexandrie-NUXT_PUBLIC_BASE_URL=http://localhost:8200--# 3. Setup database--# Create MySQL database-mysql -u root -p-CREATE DATABASE alexandrie;-CREATE USER 'alexandrie'@'localhost' IDENTIFIED BY 'password';-GRANT ALL PRIVILEGES ON alexandrie.* TO 'alexandrie'@'localhost';-FLUSH PRIVILEGES;--# 4. Start MinIO (object storage)-minio server ./minio-data --console-address :9001 --address "localhost:9000"--# 5. Start backend-cd backend-go run main.go-# Migrations run automatically--# 6. Start frontend (in new terminal)-cd frontend-bun dev-```--### 9.3 Project Commands--#### Backend Commands--```bash-# Run development server-go run main.go--# Build binary-go build -o alexandrie main.go--# Run tests-go test ./tests/... -v--# Run specific test-go test ./tests/auth_test.go -v--# Format code-go fmt ./...--# Vet code (static analysis)-go vet ./...--# Install new dependency-go get github.com/package/name--# Update dependencies-go get -u ./...-go mod tidy-```--#### Frontend Commands--```bash-# Development server (with HMR)-bun dev--# Build for production-bun run build--# Preview production build-bun run preview--# Lint code-bun run lint--# Fix linting issues-bun run lint:fix--# Lint CSS-bun run lint:css--# Fix CSS issues-bun run lint:css:fix--# Install dependency-bun add package-name--# Install dev dependency-bun add -d package-name--# Update dependencies-bun update-```--#### Makefile Commands (Linux)+Download the `docker-compose.yml` file from the repository: [https://github.com/Smaug6739/Alexandrie/blob/main/docker-compose.yml](https://github.com/Smaug6739/Alexandrie/blob/main/docker-compose.yml) and run:```bash-# Start all services-make all--# Start backend only-make backend--# Start frontend only-make frontend--# Start MinIO only-make minio--# Stop all services-make stop-```--### 9.4 Database Migrations--#### Creating a Migration--```bash-# Install migrate CLI-go install -tags 'mysql' github.com/golang-migrate/migrate/v4/cmd/migrate@latest--# Create new migration-cd backend/migrations-migrate create -ext sql -dir . -seq migration_name--# This creates:-# - 000012_migration_name.up.sql-# - 000012_migration_name.down.sql+docker compose up```-_Note: This tool is optional you can create manually the file but please follow the naming conventions_+Once the containers are running:-#### Writing Migrations+- Frontend β http://localhost:8200+- Backend API β http://localhost:8201+- Object Storage (RustFS) β http://localhost:9000-```sql--- 000012_add_feature.up.sql-ALTER TABLE nodes ADD COLUMN new_field VARCHAR(100);-CREATE INDEX idx_new_field ON nodes(new_field);+_Note: No default account is created. You can register a new user directly from the frontend._--- 000012_add_feature.down.sql-DROP INDEX idx_new_field ON nodes;-ALTER TABLE nodes DROP COLUMN new_field;-```--#### Running Migrations+## Configuration (Environment Variables)-```bash-# Migrations run automatically on app start-# Or run manually:+To customize the setup (ports, domains, security, feature flags, production deployment), you can create a `.env` file next to `docker-compose.yml`.-# Apply all migrations-migrate -database "mysql://user:pass@tcp(localhost:3306)/alexandrie" -path migrations up+The `.env` file template can be found here: [https://github.com/Smaug6739/Alexandrie/blob/main/.env.example](https://github.com/Smaug6739/Alexandrie/blob/main/.env.example)-# Rollback last migration-migrate -database "..." -path migrations down 1+Only the variables defined in `.env.example` are officially supported.-# Goto specific version-migrate -database "..." -path migrations goto 10+### 1. Public URLs & Global Access-# Check current version-migrate -database "..." -path migrations version-```--> [!WARNING]-> Migrations down are not fully implemented yet--### 9.5 Code Quality--#### Linting--```bash-# Backend-go vet ./...-golangci-lint run # If installed--# Frontend-bun run lint # ESLint-bun run lint:css # Stylelint-```--#### Formatting--```bash-# Backend-go fmt ./...+```env+FRONTEND_URL=http://localhost:8200+API_URL=http://localhost:8201+CDN_URL=http://localhost:9005-# Frontend (automatic with ESLint)-bun run lint:fix # ESLint fix-bun run lint:css:fix # Stylelint fix+CDN_ENDPOINT=/alexandrie/```-### 9.6 Git Workflow--```bash-# Create feature branch-git checkout -b feature/new-feature--# Make changes and commit-git add .-git commit -m "feat: add new feature"+These variables define how clients (browsers) reach your services.-# Push to remote-git push origin feature/new-feature+- `FRONTEND_URL`: The public URL for the frontend service.+- `API_URL`: The public URL for the backend API service.+- `CDN_URL`: The public URL for the object storage service (RustFS).+- `CDN_ENDPOINT`: The path prefix under which files are exposed. You probably want to keep this as /alexandrie/ to match the bucket name, change it only if you changed the bucket name or if you have configured a reverse proxy path.+ Final URL are constructed as: `<CDN_URL><CDN_ENDPOINT><object-path>`+ If you have a problem with files URL just open devtools in your browser and check the actual URL used to load files and then adjust these variables accordingly.-# Create pull request on GitHub+### 2. Application Feature Flags-# After merge, update main-git checkout main-git pull origin main+```env+CONFIG_DISABLE_LANDING=false+CONFIG_DISABLE_SIGNUP=false```-**Commit Message Convention:**--```-feat: Add new feature-fix: Fix bug in authentication-docs: Update README-style: Format code-refactor: Refactor node service-test: Add tests for permissions-chore: Update dependencies-```--### 9.7 Debugging--#### Backend Debugging+These variables control specific features of the application (useful for private deployments, internal tools etc.).-```go-// Add debug logging-import "log"+- `CONFIG_DISABLE_LANDING`: If set to `true`, the landing page is disabled, and users are redirected to the login page. The default is `false`.+- `CONFIG_DISABLE_SIGNUP`: If set to `true`, new user registrations are disabled (in frontend + backend for security). The default is `false`.-log.Println("Debug:", variable)-log.Printf("User ID: %s", userId)+### 3. Backend API β Runtime & Security-// Use Delve debugger-go install github.com/go-delve/delve/cmd/dlv@latest--# Start with debugger-dlv debug main.go--# Set breakpoint-(dlv) break main.main-(dlv) continue+```env+BACKEND_EXTERNAL_PORT=8201+COOKIE_DOMAIN=localhost:8200+ALLOW_UNSECURE=true+JWT_SECRET=your-secure-jwt-secret-key-change-this-in-production```-#### Frontend Debugging+These variables configure the backend API service.-```typescript-// Console logging-console.log('Debug:', data);-console.table(array);+- `BACKEND_EXTERNAL_PORT`: The port exposed on your host machine for the Backend API service.+- `COOKIE_DOMAIN` (IMPORTANT): This variable defines where authentication cookies are valid.+ It should match with the common domain used by both frontend and backend services.+ Example: If your frontend is at `frontend.yourdomain.com` and your backend API is at `api.yourdomain.com`, then set `COOKIE_DOMAIN=yourdomain.com`.+ **Rules:**+ - Must match with the highest common domain between the frontend and the backend. See #286 for more details.+ - Must NOT include protocol (http:// or https://)+ - If misconfigured, login will appear to work but users will be instantly logged out+- `ALLOW_UNSECURE`: If set to `true`, HTTP connections are allowed (useful for local and dev). In production, it is recommended to set this to `false` to enforce HTTPS.+- `JWT_SECRET`: Secret key used to sign JWT tokens. You should change this to a random long string correcly generated (with openssl or similar) in production for security. Changing this value will invalidate all existing sessions.-// Vue DevTools (browser extension)-// Inspect component state, Pinia stores, routing+### 4. Database β MySQL-// Network tab (browser)-// Inspect API calls, responses, timing+```env+MYSQL_EXTERNAL_PORT=3307+MYSQL_DATABASE=alexandrie+MYSQL_USER=alexandrie+MYSQL_PASSWORD=password+MYSQL_ROOT_PASSWORD=rootpassword```-#### Database Debugging+These variables configure the MySQL database service.-```bash-# Connect to MySQL-mysql -u alexandrie -p alexandrie+- `MYSQL_EXTERNAL_PORT`: The port exposed on your host machine for the MySQL service.+- `MYSQL_DATABASE`: The name of the default database created for Alexandrie.+- `MYSQL_USER`: The username for the default Alexandrie database user.+- `MYSQL_PASSWORD`: The password for the default Alexandrie database user.+- `MYSQL_ROOT_PASSWORD`: The password for the MySQL root user.-# Check tables-SHOW TABLES;+### 5. Object Storage β S3 (RustFS / MinIO-compatible) (optional, leave empty to disable)-# Inspect data-SELECT * FROM users LIMIT 10;-SELECT * FROM nodes WHERE user_id = '123';+```env+RUSTFS_EXTERNAL_PORT=9005-# Check indexes-SHOW INDEX FROM nodes;+RUSTFS_ACCESS_KEY=alexandrie-key+RUSTFS_SECRET_KEY=alexandrie-secret-# Explain query performance-EXPLAIN SELECT * FROM nodes WHERE name LIKE '%search%';+MINIO_BUCKET=alexandrie```-### 9.9 Performance Monitoring+These variables configure the RustFS object storage service.-#### Backend Profiling+- `RUSTFS_EXTERNAL_PORT`: The port exposed on your host machine for the RustFS service.+- `RUSTFS_ACCESS_KEY`: The access key for the RustFS S3-compatible API.+- `RUSTFS_SECRET_KEY`: The secret key for the RustFS S3-compatible API.+- `MINIO_BUCKET`: The name of the default bucket created for Alexandrie. Note that this bucket name should match the `CDN_ENDPOINT` variable in the backend configuration. By default, it is set to `alexandrie` and the backend will create `alexandrie` and `alexandrie-backups` buckets.-```go-import _ "net/http/pprof"+### 6. Email β SMTP (optional)-// Enable profiling endpoint-go func() {- log.Println(http.ListenAndServe("localhost:6060", nil))-}()--// Access profiles:-// http://localhost:6060/debug/pprof/-// CPU: /debug/pprof/profile?seconds=30-// Memory: /debug/pprof/heap-// Goroutines: /debug/pprof/goroutine+```env+SMTP_HOST=+SMTP_MAIL=+SMTP_PASSWORD=```-#### Frontend Performance+Used only for password reset emails. Leave empty to disable email features (default).-```typescript-// Performance API-const perfData = performance.getEntriesByType('navigation')[0];-console.log('Load time:', perfData.loadEventEnd - perfData.fetchStart);+- `SMTP_HOST`: The SMTP server host.+- `SMTP_MAIL`: The email address used to send emails.+- `SMTP_PASSWORD`: The password for the SMTP email account.-// Lighthouse (Chrome DevTools)-// Run audit for performance, accessibility, SEO+### 7. Frontend β Nuxt-// Vue DevTools Performance tab-// Track component render time+```env+FRONTEND_EXTERNAL_PORT=8200```----+The port exposed on the host for the frontend container.-## 10. Configuration Reference+In production, this is usually only accessed by a reverse proxy.-### 10.1 Setup application+## Production Deployment Notes-For details please see [setup guide.md](./setup.md)+In production, you should:-### 10.2 Performance Tuning+- NOT expose MySQL or RustFS directly+- Use a reverse proxy (Nginx, Traefik, Caddy)+- Terminate HTTPS at the proxy-#### Caching Strategy+## FAQ β Common Issues & Troubleshooting-```go-// Example: Redis caching (not currently implemented)+### I am instantly logged out after logging in (login loop)-import "github.com/go-redis/redis/v8"+**Symptoms**-// Cache frequently accessed nodes-func GetNodeWithCache(nodeId Snowflake) (*Node, error) {- // Try cache first- cached, err := redis.Get(ctx, "node:"+nodeId).Result()- if err == nil {- return unmarshalNode(cached), nil- }+- Login succeeds (no error message).+- You are redirected correctly.+- You are immediately logged out or returned to the login page.+- Refreshing the page shows you as unauthenticated.- // Cache miss, query database- node := getNodeFromDB(nodeId)+**Cause**- // Store in cache (expire in 5 minutes)- redis.Set(ctx, "node:"+nodeId, marshal(node), 5*time.Minute)+This is usually caused by a misconfiguration of the `COOKIE_DOMAIN` environment variable in the backend service.- return node, nil-}-```+**Common mistakes**-## Other+- Including protocol (http:// or https://) in `COOKIE_DOMAIN`.+- Setting `COOKIE_DOMAIN` to a subdomain that does not match both frontend and backend domains.+- Setting `COOKIE_DOMAIN` to a domain that does not match the actual domain used to access the services.-### A. Glossary+**Correct configuration examples**-- **Node**: Unified entity representing workspace, category, document or resource-- **Snowflake**: Distributed unique ID generation algorithm (inspired from https://discord.com/developers/docs/reference#snowflakes)-- **Permission Level**: Numeric access level (0-4) determining user capabilities-- **S3**: Simple Storage Service, object storage protocol-- **JWT**: JSON Web Token, stateless authentication mechanism-- **CORS**: Cross-Origin Resource Sharing, browser security feature-- **PWA**: Progressive Web App, installable web application-- **SSR**: Server-Side Rendering-- **SPA**: Single-Page Application-- **ORM**: Object-Relational Mapping+- If your frontend is at `frontend.yourdomain.com` and your backend API is at `api.yourdomain.com`, then set `COOKIE_DOMAIN=yourdomain.com`.+- If your frontend is at `frontend.subdomain.yourdomain.com` and your backend API is at `api.subdomain.yourdomain.com`, then set `COOKIE_DOMAIN=subdomain.yourdomain.com`.+- If your frontend is at `yourdomain.com` and your backend API is at `api.yourdomain.com`, then set `COOKIE_DOMAIN=yourdomain.com`.-### B. Common Issues and Solutions+### Files are uploaded but cannot be accessed-#### Backend won't start+**Symptoms**-```bash-# Check MySQL connection-mysql -u alexandrie -p--# Check port availability-lsof -i :8201+- File uploads succeed without errors.+- You show files as uploaded in the frontend (for example on the cdn page, in the datatable or in cards)+- When trying to access the files, you get 404 errors or broken links.-# Check environment variables-go run main.go # Look for error messages+**Cause**+This is usually caused by a misconfiguration of the `CDN_URL` and/or `CDN_ENDPOINT` environment variables in the backend service.-# Reset database-DROP DATABASE alexandrie;-CREATE DATABASE alexandrie;-# Restart backend (migrations will recreate tables)-```+**Common mistakes**-#### Frontend build errors+- `CDN_URL` not matching the actual URL used to access to your S3 server storage (for example when using a reverse proxy with a different domain or path)+- `CDN_ENDPOINT` not matching the bucket name or the path used in the reverse proxy.-```bash-# Clear cache-rm -rf .nuxt node_modules bun.lock-bun install-bun dev--# Check Node version-node --version # Should be 18+--# Check environment variables-cat .env-```+**Correct configuration examples**-### C. External Resources+- If your RustFS S3 server is accessible at `http://cdn.yourdomain.com`, then set:+ - `CDN_URL=http://cdn.yourdomain.com`+ - `CDN_ENDPOINT=/alexandrie/` (/alexandrie/ is the default bucket name, change it only if you changed the bucket name or if your reverse proxy uses a different path)+- If your RustFS S3 server is accessible at `http://yourdomain.com/files/`, then set:+ - `CDN_URL=http://yourdomain.com`+ - `CDN_ENDPOINT=/files/` (change /files/ to match the path used in your reverse proxy or the bucket name)-- **Go Documentation**: https://go.dev/doc/-- **Gin Framework**: https://gin-gonic.com/docs/-- **Nuxt Documentation**: https://nuxt.com/docs-- **Vue.js Guide**: https://vuejs.org/guide/-- **MySQL Reference**: https://dev.mysql.com/doc/-- **MinIO Documentation**: https://min.io/docs/-- **JWT.io**: https://jwt.io/-- **CodeMirror**: https://codemirror.net/--### D. Contributing--See [CONTRIBUTING.md](../CONTRIBUTING.md) for development setup and contribution guidelines.--### E. License--This project is licensed under the MIT License. See [LICENSE](../LICENSE) for details.-----+Test the right url in your browser by combining `CDN_URL`, `CDN_ENDPOINT` and the object path (you can get the object path from the frontend interface, for example in the cdn page with devtools or by copying the link).-**Document Version**: 1.0-**Last Updated**: 2025-11-13+## Additional Resources-For questions or clarifications, please open an issue on GitHub or join our Discord community.+- [Official Alexandrie GitHub Repository](https://github.com/Smaug6739/alexandrie)+- [Discord Community](https://discord.gg/UPsEg6egPj)diff --git a/docs/setup.md b/docs/setup.mddeleted file mode 100644index ee2b5d6b..00000000--- a/docs/setup.md+++ /dev/null@@ -1,269 +0,0 @@-# Alexandrie Setup Guide--This guide explains how to set up, configure, and deploy the Alexandrie stack.--It covers both **local development** and **production deployment**, including how to configure environment variables, connect the different services, and handle HTTPS with a reverse proxy.-------## Overview of the Stack--The Alexandrie stack consists of four main services, defined in the `docker-compose.yml` file:--| Service | Description |-| ------------ | ------------------------------------------------------------------------------ |-| **MySQL** | Relational database used to store user data and metadata. |-| **RustFS** | S3-compatible object storage used for file and media storage. |-| **Backend** | The Go-based API server providing authentication, storage, and access control. |-| **Frontend** | A Nuxt 4 web app that communicates with the backend via REST API. |--All services are connected through a dedicated Docker network (`alexandrie-network`).-------## Quick Start--For local testing, you can run Alexandrie directly using the provided `docker-compose.yml`:--Download the `docker-compose.yml` file from the repository: [https://github.com/Smaug6739/Alexandrie/blob/main/docker-compose.yml](https://github.com/Smaug6739/Alexandrie/blob/main/docker-compose.yml) and run:--```bash-docker compose up-```--Once the containers are running:--- Frontend β http://localhost:8200-- Backend API β http://localhost:8201-- Object Storage (RustFS) β http://localhost:9000--_Default credentials and basic settings are automatically applied._--## Configuration (Environment Variables)--Each service can be configured using environment variables defined in the docker-compose file (or in a separate `.env` file, if you prefer but need to include the file in the docker compose config).--Key variables include:--### MySQL--```yml-MYSQL_ROOT_PASSWORD: rootpassword-MYSQL_DATABASE: alexandrie-MYSQL_USER: alexandrie-MYSQL_PASSWORD: password-```--**Notes:**--- Change all default passwords before deploying to production.-- The database is stored in a named Docker volume (mysql_data).-- You can access the MySQL shell with:--```bash-docker exec -it alexandrie-mysql mysql -u alexandrie -p-```--### RustFS (Object Storage)--```yml-RUSTFS_ACCESS_KEY: alexandrie-key-RUSTFS_SECRET_KEY: alexandrie-secret-RUSTFS_CONSOLE_ENABLE: 'false'-```--**Notes:**--RustFS acts like an S3-compatible object storage (similar to MinIO).--- All uploaded files like images, videos, or attachments are stored here.-- The `RUSTFS_CONSOLE_ENABLE` option enables a simple web console (useful in dev, disable in prod).-- Data is stored in the `rustfs_data` volume and logs in `rustfs_logs`.--### Backend--```yml-BACKEND_PORT: 8201-```--The port on which the backend API listens.--```yml-FRONTEND_URL: https://example.com-```--When `FRONTEND_URL` is defined, `FRONTEND_URL` and `COOKIE_DOMAIN` will be automatically derived at startup.--**Legacy variables (still supported, but not recommended):**--```yml-FRONTEND_URL: http://localhost:8200-COOKIE_DOMAIN: localhost-```--**Authentication and security:**--```yml-JWT_SECRET: your-secure-jwt-secret-key-change-this-in-production-ALLOW_UNSECURE: 'true'-```--- `JWT_SECRET`: Secret key used to sign JWT tokens. Change this in production.-- `ALLOW_UNSECURE`- - `true` allows non-HTTPS connections (for local testing).- - `false` enforces HTTPS (recommended in production).--**Database connection:**--```yml-DATABASE_HOST: mysql-DATABASE_PORT: 3306-DATABASE_NAME: alexandrie-DATABASE_USER: alexandrie-DATABASE_PASSWORD: password-```--These variables configure the connection to the MySQL database.--These should match the MySQL service configuration.--**Object Storage (RustFS / MinIO)** (OPTIONAL)--```yml-MINIO_ENDPOINT: rustfs:9000-MINIO_ACCESSKEY: alexandrie-key-MINIO_SECRETKEY: alexandrie-secret-MINIO_BUCKET: alexandrie-```--These variables configure the connection to the object storage server.--If you don't want to use the "CDN" feature, you can omit these variables.--**SMTP Email Settings** (OPTIONAL)--```yml-SMTP_HOST: smtp.example.com-SMTP_MAIL: [email protected]-SMTP_PASSWORD: yourpassword-```--These variables configure the SMTP server for sending emails (only for password resets).-If not set, email features will be disabled.--**Other settings:**--```yml-GIN_MODE: release-```--Sets the Gin framework mode. Use `release` in production for better performance.--### Frontend--```yml-PORT: 8200-NUXT_PUBLIC_BASE_API: http://localhost:8201-NUXT_PUBLIC_BASE_CDN: http://localhost:9000/alexandrie-NUXT_PUBLIC_BASE_URL: http://localhost:8200-```--These variables configure the frontend application:--- `PORT`: Port on which the frontend listens.-- `NUXT_PUBLIC_BASE_API`: Base URL for the backend API.-- `NUXT_PUBLIC_BASE_CDN`: Base URL for the object storage (CDN).-- `NUXT_PUBLIC_BASE_URL`: Base URL for the frontend.--When deploying to production, update these URLs to match your domain and ensure HTTPS is used.--## Production Deployment--For production, you **should not** expose MySQL, RustFS, or Backend ports publicly.-Instead, use a reverse proxy like Nginx or Apache to:--- route HTTPS traffic to frontend and backend,-- manage SSL certificates (e.g., via Let's Encrypt),-- add basic rate limiting or caching.--Ensure all default passwords and secrets are changed before going live.--**Example Nginx configuration:**--**Frontend configuration:**--```nginx-server {- listen 443 ssl http2;- listen [::]:443 ssl http2;- server_name alexandrie-hub.fr;-- # SSL- ssl_certificate /etc/nginx/ssl/alexandrie-hub.fr/alexandrie-hub.fr_ssl_certificate.cer;- ssl_trusted_certificate /etc/nginx/ssl/alexandrie-hub.fr/_.alexandrie-hub.fr_ssl_certificate_INTERMEDIATE.cer;- ssl_certificate_key /etc/nginx/ssl/alexandrie-hub.fr/_.alexandrie-hub.fr_private_key.key;-- # HSTS- add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;-- # logging- access_log /var/log/nginx/access.log combined buffer=512k flush=1m;- error_log /var/log/nginx/error.log warn;-- # reverse proxy- location / {- proxy_pass http://127.0.0.1:8200; # Frontend- proxy_set_header Host $host;- include nginxconfig.io/proxy.conf;- }--}--# HTTP redirect-server {- listen 80;- listen [::]:80;- server_name alexandrie-hub.fr;- return 301 https://alexandrie-hub.fr$request_uri;-}-```--**Backend configuration:**--```nginx-server {- listen 443 ssl http2;- listen [::]:443 ssl http2;- server_name api.alexandrie-hub.fr;-- # SSL- ssl_certificate /etc/nginx/ssl/alexandrie-hub.fr/alexandrie-hub.fr_ssl_certificate.cer;- ssl_trusted_certificate /etc/nginx/ssl/alexandrie-hub.fr/_.alexandrie-hub.fr_ssl_certificate_INTERMEDIATE.cer;- ssl_certificate_key /etc/nginx/ssl/alexandrie-hub.fr/_.alexandrie-hub.fr_private_key.key;-- # HSTS- add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;-- # logging- access_log /var/log/nginx/access.log combined buffer=512k flush=1m;- error_log /var/log/nginx/error.log warn;-- # reverse proxy- location / {- proxy_pass http://127.0.0.1:8201;- proxy_set_header Host $host;- include nginxconfig.io/proxy.conf;- }--}--# HTTP redirect-server {- listen 80;- listen [::]:80;- server_name api.alexandrie-hub.fr;- return 301 https://api.alexandrie-hub.fr$request_uri;-}-```--Same principles for CDN domain if used.