feature/5-mfa-support #8

Merged
MiauRizius merged 6 commits from feature/5-mfa-support into main 2026-06-10 01:46:56 +02:00
22 changed files with 1897 additions and 537 deletions
Showing only changes of commit ae41b96fa4 - Show all commits

388
README.md
View File

@@ -1,65 +1,111 @@
# MiauInv - Inventory and Project Management System
# MiauInv
MiauInv is a secure, light-weight inventory, stock, and project allocation tracking system written in Go. It utilizes HTMX for a dynamic, reactive single-page experience over traditional server-rendered HTML blocks, backed by an encrypted JWT and dual-token refresh architecture alongside an embedded SQLite instance.
MiauInv is a lightweight inventory, stock, and project allocation management system written in Go. It provides a server-rendered dashboard with HTMX-style page composition, vanilla JavaScript for API interactions, SQLite for persistence, JWT-based sessions, refresh-token rotation, account settings, and optional TOTP-based two-factor authentication.
## Table of Contents
The project is designed for self-hosted/private deployments. It is not a full enterprise asset-management platform, but it already covers the main workflows needed for tracking items, locations, stock distribution, and project allocations.
* [Technical Specifications](#technical-specifications)
* [Architecture Overview](#architecture-overview)
* [Detailed Documentation](#detailed-documentation)
* [Configuration](#configuration)
* [Configuration File (config.yaml)](#configuration-file-configyaml)
* [Environment Variables](#environment-variables)
* [Route and Endpoint Matrix](#route-and-endpoint-matrix)
* [Frontend Web Routes (HTML Views)](#frontend-web-routes-html-views)
* [Backend API Endpoints (JSON Serialization)](#backend-api-endpoints-json-serialization)
* [Setup and Deployment Tutorial](#setup-and-deployment-tutorial)
* [Prerequisites](#prerequisites)
* [Option 1: Native Local Deployment](#option-1-native-local-deployment)
* [Option 2: Docker Deployment (Recommended)](#option-2-docker-deployment-recommended)
* [Reverse Proxy Integration with Caddy](#reverse-proxy-integration-with-caddy)
* [Images](#images)
## Contents
## Technical Specifications
- [Features](#features)
- [Current Status](#current-status)
- [Technical Stack](#technical-stack)
- [Architecture](#architecture)
- [Documentation](#documentation)
- [Configuration](#configuration)
- [Routes and API Endpoints](#routes-and-api-endpoints)
- [Setup](#setup)
- [Docker Deployment](#docker-deployment)
- [Reverse Proxy Deployment](#reverse-proxy-deployment)
- [Security Notes](#security-notes)
- [Screenshots](#screenshots)
* **Backend Language:** Go (Golang 1.22+)
* **Frontend Interactivity:** HTMX (v2.0.4) & Vanilla JavaScript (API Client integration)
* **Database Engine:** SQLite (via standard driver dependencies)
* **Security & Session Layer:** JSON Web Tokens (JWT) with HTTP-Only/Secure dual cookie strategy (Access and Refresh Token Rotation)
* **Styling Architecture:** Modern dark-theme customized native CSS variables (`--bg`, `--card`, `--accent`, `--border`)
* **Transport Security:** Compulsory HTTPS / Native TLS Listener implementation
## Features
---
### Inventory and allocation
## Architecture Overview
- Item management with name, category, description, and total quantity.
- Location management for physical or logical storage places.
- Stock mapping between items and locations.
- Project management for allocating items to projects.
- Association tracking between projects and item quantities.
- Dashboard statistics for items, locations, and projects.
MiauInv splits responsibility cleanly across modularized architecture packages:
### Account and authentication
* **`main.go`**: Entrypoint initializing components and connecting layers.
* **`server/`**: Configures variables, spins up TLS mechanisms, and exposes route endpoints.
* **`auth/`**: Custom HTTP Middleware interceptors validating JWT signatures and parsing sub-claims.
* **`handlers/`**: Core API Controller actions processing CRUD functions on database entities.
* **`storage/`**: Direct abstraction queries interacting with the underlying SQLite database schema.
* **`frontend/`**: Serving standard static assets and injecting structural data into components.
- User registration, if enabled in the configuration.
- Password hashing with bcrypt.
- Signed JWT access tokens.
- Database-backed refresh tokens with rotation.
- HTTP-only secure cookies for access and refresh tokens.
- Account settings page at `/profile/settings`.
- Username change with password confirmation.
- Password change with old-password verification and session refresh.
- Avatar placeholder in the account settings UI for a later avatar implementation.
---
### Two-factor authentication
---
- Optional TOTP 2FA using authenticator apps.
- QR-code based setup from the account settings page.
- Manual setup key fallback if QR scanning is not available.
- Two-step login flow for accounts with 2FA enabled.
- Recovery codes generated when 2FA is enabled.
- Recovery codes are stored only as hashes.
- Recovery codes can be downloaded as a text file after generation.
- Recovery codes can be regenerated from account settings.
- Recovery codes are one-time use.
## Detailed Documentation
## Current Status
For deep dives into specific subsystems, database layouts, and security mechanisms, please refer to the dedicated documentation files:
MiauInv is an active private project. The current version supports core inventory workflows and account-level security settings. Some areas are intentionally still basic:
* **[Database Schema & Integrity](docs/DATABASE.md):** Comprehensive breakdown of the SQLite table structures, fields, and foreign key relations.
* **[Authentication Architecture](docs/AUTHENTICATION.md):** Detailed explanation of the dual-token rotation flow, JWT lifecycle, and frontend loop protection.
- Avatar support is currently only represented by a placeholder in the UI.
- There is no dedicated admin panel yet.
- There is no rate limiting yet for login, 2FA, or recovery-code attempts.
- Automated test coverage is still incomplete and should be expanded around authentication, 2FA, recovery codes, and inventory handlers.
- The application currently uses native TLS. If deployed behind a reverse proxy, the proxy must connect to the backend over HTTPS or the backend TLS behavior must be adjusted intentionally.
## Technical Stack
| Area | Technology |
| --- | --- |
| Backend | Go 1.26 |
| Routing | Go standard library `net/http` |
| Database | SQLite via `github.com/glebarez/go-sqlite` |
| Authentication | JWT via `github.com/golang-jwt/jwt/v5` |
| Password hashing | bcrypt via `golang.org/x/crypto/bcrypt` |
| 2FA | TOTP via `github.com/pquerna/otp/totp` |
| Frontend | Server-rendered HTML, HTMX-style structure, vanilla JavaScript |
| Styling | Custom CSS with dark theme variables |
| Deployment | Docker / Docker Compose |
## Architecture
The codebase is split into small packages with mostly direct responsibilities:
| Path | Responsibility |
| --- | --- |
| `main.go` | Application entrypoint. Initializes configuration, database, and server startup. |
| `server/` | HTTP route registration, TLS listener, and server-level configuration. |
| `config/` | Runtime configuration file creation and loading. |
| `auth/` | JWT generation, JWT validation, middleware, role middleware, and password helpers. |
| `handlers/` | JSON API handlers for authentication, account settings, inventory, locations, projects, stock, and associations. |
| `storage/` | SQLite schema setup, migrations, and database access helpers. |
| `models/` | Shared data structures and constants. |
| `frontend/` | HTML template rendering and static asset serving. |
| `frontend/assets/js/` | Frontend API client, login flow, token refresh logic, account settings logic, and dashboard actions. |
| `frontend/htmx/` | HTML views and dashboard content templates. |
## Documentation
More detailed documentation is available in:
- [Authentication](docs/AUTHENTICATION.md)
- [Database](docs/DATABASE.md)
- [Testing](docs/TESTING.md)
## Configuration
The system uses a combination of a structural JSON configuration file and environment variables for system runtime flags.
### Configuration File (`config.yaml`)
The application automatically creates or reads a configuration file named `config.json` in the working directory on startup.
MiauInv reads `./appdata/config.yaml`. If the file does not exist, the application creates a default configuration on startup.
```yaml
port: "8080"
@@ -69,101 +115,132 @@ private_key_path: ./appdata/key.pem
allow_registration: true
```
### Environment Variables
### Configuration fields
For cryptographic functions, a mandatory environment variable must be exported before executing the binary:
| Field | Description |
| --- | --- |
| `port` | HTTPS listen port. |
| `database_path` | SQLite database path. |
| `certificate_path` | TLS certificate path. |
| `private_key_path` | TLS private key path. |
| `allow_registration` | Enables or disables public registration. If false, `/register` renders a blocked-registration page and `/api/register` is not registered. |
| Variable | Type | Description | Minimum Requirement |
### Environment variables
| Variable | Required | Description |
| --- | --- | --- |
| `JWT_SECRET` | Yes | Symmetric signing secret for JWTs. Must be at least 32 characters. |
Generate a local development secret with:
```bash
openssl rand -base64 48
```
## Routes and API Endpoints
### Frontend routes
| Route | Method | Auth required | Description |
| --- | --- | --- | --- |
| `JWT_SECRET` | String | Symmetric secret signature key used to sign access tokens | Minimum 32 characters |
| `/` | `GET` | No | Landing page. |
| `/login` | `GET` | No | Login page. Supports password login and the second 2FA step. |
| `/register` | `GET` | No | Registration page or blocked-registration page, depending on configuration. |
| `/dashboard` | `GET` | Yes | Dashboard overview. |
| `/inventory` | `GET` | Yes | Stock and inventory overview. |
| `/items` | `GET` | Yes | Item management view. |
| `/locations` | `GET` | Yes | Location management view. |
| `/projects` | `GET` | Yes | Project management view. |
| `/profile/settings` | `GET` | Yes | Account settings, password changes, 2FA setup, 2FA disable, and recovery-code management. |
| `/profile/` | `GET` | No | Placeholder page for unfinished profile subpages. |
| `/assets/*` | `GET` | No | Static CSS/JS assets. Minified CSS/JS variants are generated on request. |
---
### Authentication and account API
## Route and Endpoint Matrix
All communication with the application happens over defined HTTP transport interfaces. The routes are divided into User-Facing Views (HTML renders) and programmatic Data Hooks (JSON APIs).
### Frontend Web Routes (HTML Views)
| Route Path | HTTP Method | Auth Required | Description |
| Endpoint | Method | Auth required | Description |
| --- | --- | --- | --- |
| `/` | `GET` | No | Root index landing view. |
| `/login` | `GET` | No | Renders login page component. |
| `/register` | `GET` | No | Registration layout or block alert based on authorization properties. |
| `/dashboard` | `GET` | **Yes** | Aggregated stats layout covering items, projects, and locations. |
| `/inventory` | `GET` | **Yes** | General overview interface managing stock quantities. |
| `/items` | `GET` | **Yes** | Standard component interface targeting primary atomic assets. |
| `/locations` | `GET` | **Yes** | Physical or logical facility structures view. |
| `/projects` | `GET` | **Yes** | Overview interface listing active construction and logistics operations. |
| `/profile/` | `GET` | **Yes** | Component context under development. |
| `/assets/*` | `GET` | No | Serves global minified system design files (`.css`, `.js`). |
| `/api/register` | `POST` | No | Creates a user if registration is enabled. |
| `/api/login` | `POST` | No | Validates username/password. Returns a full session if 2FA is disabled; otherwise returns a short-lived 2FA challenge token. |
| `/api/login/2fa` | `POST` | No | Completes login using the 2FA challenge token plus either a TOTP code or a recovery code. |
| `/api/refresh` | `POST` | No | Rotates a refresh token. Accepts the token from JSON or the `refresh_token` cookie. |
| `/api/logout` | `POST` | Yes | Revokes refresh tokens for the current user and clears auth cookies. |
| `/api/profile` | `GET` | Yes | Returns current user metadata, 2FA state, and unused recovery-code count. |
| `/api/userinfo` | `GET` | Yes | Same user information handler as `/api/profile`. |
| `/api/account/username` | `POST` | Yes | Changes the current username after password confirmation. |
| `/api/account/password` | `POST` | Yes | Changes the current password, revokes old refresh tokens, and issues a new session. |
| `/api/2fa/setup` | `POST` | Yes | Creates a pending TOTP secret and returns `secret`, `otpauth_url`, and a base64 PNG QR code. |
| `/api/2fa/enable` | `POST` | Yes | Enables 2FA after validating a TOTP code. Returns one-time recovery codes. |
| `/api/2fa/disable` | `POST` | Yes | Disables 2FA after password and TOTP confirmation. Revokes sessions and clears auth cookies. |
| `/api/2fa/recovery-codes/regenerate` | `POST` | Yes | Invalidates existing recovery codes and returns a new set after password and TOTP confirmation. |
### Backend API Endpoints (JSON Serialization)
### Inventory API
| Endpoint Path | Method | Auth | Query Parameters | Request/Response Behavior |
| Endpoint | Method | Auth required | Query parameters | Description |
| --- | --- | --- | --- | --- |
| `/api/register` | `POST` | No | None | Creates a new user record. Requires plain JSON payload containing raw `username` and `password`. Returns status code `201 Created`. |
| `/api/login` | `POST` | No | None | Performs credential authentication. Sets `access_token` and `refresh_token` as secure, HTTP-Only cookies, and returns user identity metadata. |
| `/api/refresh` | `POST` | No | None | Accepts JSON containing `refresh_token`. Invalidates previous token structures, rotates identities, and hands over a newly active pair. |
| `/api/logout` | `POST` | **Yes** | None | Revokes active database-linked refresh session IDs for the user context and drops current browser state tracking. Returns status `204`. |
| `/api/profile` | `GET` | **Yes** | `id` *(Optional)* | Returns `id`, `username`, and metadata of either the target parameter or active identity mapped from token signatures. |
| `/api/item` | `GET` | **Yes** | `id` *(Optional)* | Empty parameters fetch all available items with aggregated `allocated` and `available` calculations. Providing `id` isolates a specific item. |
| `/api/item` | `POST` | **Yes** | None | Inserts a new tracked inventory item schema definition. |
| `/api/item` | `PUT` | **Yes** | `id` *(Required)* | Modifies values (`name`, `category`, `description`, `total_quantity`) of an active asset by primary key. |
| `/api/item` | `DELETE` | **Yes** | `id` *(Required)* | Removes an entry. SQLite blocks cascade execution if foreign key assignments still exist in stock or project tracking. |
| `/api/location` | `GET` | **Yes** | `id`, `content` | Fetching with `id` and `content=true` extracts an array of items grouped at the facility (`item_id`, `name`, `quantity`). Without `content`, returns details or global catalogs. |
| `/api/location` | `POST` | **Yes** | None | Instantiates a singular distinct location boundary identifier. |
| `/api/location` | `PUT` | **Yes** | `id` *(Required)* | Renames a location while maintaining foreign keys. |
| `/api/location` | `DELETE` | **Yes** | `id` *(Required)* | Destroys location configurations if currently cleared of active items. |
| `/api/project` | `GET` | **Yes** | `id`, `details` | Providing `id` with `details=true` unrolls associated items allocated to that project context. |
| `/api/project` | `POST` | **Yes** | None | Inserts a tracking context entity for targeted hardware allocation. |
| `/api/project` | `PUT` | **Yes** | `id` *(Required)* | Updates a project metadata record definition. |
| `/api/project` | `DELETE` | **Yes** | `id` *(Required)* | Drops an empty project wrapper. |
| `/api/stock` | `GET` | **Yes** | `id` *(Optional)* | Obtains exact relationship matrices between location nodes and items. |
| `/api/stock` | `POST` | **Yes** | None | Links allocations across specific site nodes. |
| `/api/stock` | `PUT` | **Yes** | `id` *(Required)* | Modifies stock metrics directly on specified maps. |
| `/api/stock` | `DELETE` | **Yes** | `id` *(Required)* | Completely severs relationship entry allocations between nodes. |
| `/api/association` | `GET` | **Yes** | `id`, `project_id` | Dumps general configuration links, isolated optionally by operational `project_id`. |
| `/api/association` | `POST` | **Yes** | None | Allocates an inventory batch to a dedicated project infrastructure requirement. |
| `/api/association` | `PUT` | **Yes** | `id` *(Required)* | Alters active quantity indicators inside a specific deployment matrix. |
| `/api/association` | `DELETE` | **Yes** | `id` *(Required)* | Frees up allocations, returning tracking variables back to unassigned states. |
| `/api/item` | `GET` | Yes | `id` optional | Returns all items with aggregate quantities, or one item by ID. |
| `/api/item` | `POST` | Yes | None | Creates an item. |
| `/api/item` | `PUT` | Yes | `id` required | Updates item fields. |
| `/api/item` | `DELETE` | Yes | `id` required | Deletes an item if no dependent rows block it. |
| `/api/location` | `GET` | Yes | `id`, `content` optional | Returns all locations, one location, or location contents with `content=true`. |
| `/api/location` | `POST` | Yes | None | Creates a location. |
| `/api/location` | `PUT` | Yes | `id` required | Renames a location. |
| `/api/location` | `DELETE` | Yes | `id` required | Deletes a location if no dependent rows block it. |
| `/api/project` | `GET` | Yes | `id`, `details` optional | Returns all projects, one project, or project allocations with `details=true`. |
| `/api/project` | `POST` | Yes | None | Creates a project. |
| `/api/project` | `PUT` | Yes | `id` required | Updates a project. |
| `/api/project` | `DELETE` | Yes | `id` required | Deletes a project if no dependent rows block it. |
| `/api/stock` | `GET` | Yes | `id` optional | Returns stock entries. |
| `/api/stock` | `POST` | Yes | None | Creates a stock entry. |
| `/api/stock` | `PUT` | Yes | `id` required | Updates a stock entry. |
| `/api/stock` | `DELETE` | Yes | `id` required | Deletes a stock entry. |
| `/api/association` | `GET` | Yes | `id`, `project_id` optional | Returns project-item associations. |
| `/api/association` | `POST` | Yes | None | Allocates item quantity to a project. |
| `/api/association` | `PUT` | Yes | `id` required | Updates a project allocation. |
| `/api/association` | `DELETE` | Yes | `id` required | Removes a project allocation. |
---
## Setup and Deployment Tutorial
## Setup
### Prerequisites
Before deployment, you must generate SSL/TLS certificates since MiauInv enforces native transport encryption layer communication (or use a bought one).
- Go 1.26.
- SQLite-compatible environment.
- OpenSSL or another way to generate TLS certificates for local development.
- A `JWT_SECRET` with at least 32 characters.
### Generate development TLS files
The server uses `http.ListenAndServeTLS`, so TLS files must exist before startup.
```bash
# Create directory for certs
mkdir -p appdata
# Generate self-signed certificate and private key
openssl req -x509 -newkey rsa:4096 -keyout appdata/key.pem -out appdata/cert.pem -sha256 -days 365 -nodes
openssl req -x509 -newkey rsa:4096 \
-keyout appdata/key.pem \
-out appdata/cert.pem \
-days 365 \
-nodes \
-subj "/CN=localhost"
```
### Option 1: Native Local Deployment
1. Make sure your Go environment path variable properties are populated (Go 1.22+).
2. Create your environmental token and execute the initialization routine task:
### Native local run
```bash
export JWT_SECRET="your_minimum_thirty_two_char_secret_key_here"
go build -o miauinv main.go
export JWT_SECRET="replace-this-with-a-random-secret-of-at-least-32-chars"
go mod tidy
go build -o miauinv .
./miauinv
```
---
Then open:
### Option 2: Docker Deployment (Recommended)
```text
https://localhost:8080
```
MiauInv includes container definition orchestrations to package configurations cleanly, binding storage databases outside running containers into persistent volumes.
## Docker Deployment
#### 1. Create the Docker Compose Descriptor
The repository contains a multi-stage Dockerfile. The final image is based on `scratch` and contains the compiled binary plus frontend assets.
Write the configuration definition mapping layer blocks directly inside a standard file named `docker-compose.yaml`:
Example `docker-compose.yaml`:
```yaml
services:
@@ -174,59 +251,31 @@ services:
ports:
- "8080:8080"
environment:
- JWT_SECRET=SECURE_RANDOM_STRING # Must be at least 32 characters long
volumes:
- ./appdata:/appdata # To edit your configuration files
```
#### 2. Execution Commands
To bring up your background container image instance pipelines, execute the compose environment controls:
```bash
# Build and execute the container in background detached mode
docker-compose up --build -d
# Verify container operation statuses
docker-compose ps
# Monitor execution system logs
docker-compose logs -f
```
Once running successfully via Docker orchestration loops, navigate your web browser context safely to `https://localhost:8080` to interact with your MiauInv control panel workspace.
## Reverse Proxy Integration with Caddy
If you deploy MiauInv behind a global Caddy server, Caddy must act as an HTTPS reverse proxy. Since the MiauInv binary enforces native TLS transport, Caddy needs to be configured to establish a secure backend connection and bypass verification for self-signed backend certificates.
### 1. Docker Compose Network Configuration
Ensure your MiauInv container shares an external network with your Caddy container (e.g., a network named `proxy`). The container does not need to expose public ports since Caddy communicates with it internally over port `8080`.
```yaml
services:
miauinv:
image: git.miaurizius.de/miaurizius/miauinv:latest
container_name: MiauInv
restart: unless-stopped
networks:
- proxy
environment:
- JWT_SECRET=SECURE_RANDOM_STRING
- JWT_SECRET=replace-this-with-a-random-secret-of-at-least-32-chars
volumes:
- ./appdata:/appdata
networks:
proxy:
external: true
```
### 2. Caddyfile Configuration
Start the container:
Add the following block to your server's `Caddyfile`. The `https://` prefix forces Caddy to use TLS for the backend connection, and `tls_insecure_skip_verify` allows the proxy to accept the internal self-signed certificate generated during the prerequisites step.
```bash
docker compose up -d
```
View logs:
```bash
docker compose logs -f
```
## Reverse Proxy Deployment
MiauInv currently listens with native TLS. If it is deployed behind Caddy or another reverse proxy, the proxy must connect to the backend using HTTPS unless the server code is changed to listen without TLS.
Example Caddy configuration with a self-signed backend certificate:
```caddy
inv.yourdomain.com {
inv.example.com {
encode zstd gzip
reverse_proxy https://miauinv:8080 {
@@ -238,20 +287,27 @@ inv.yourdomain.com {
header {
X-Content-Type-Options nosniff
Referrer-Policy strict-origin-when-cross-origin
Strict-Transport-Security "max-age=31536000; includeSubDomains"
}
}
```
### 3. Apply Configuration
For Docker deployments, place Caddy and MiauInv on the same Docker network and reverse proxy to the service name.
Reload your Caddy instance to apply the reverse proxy routing rules:
## Security Notes
```bash
docker compose exec -w /etc/caddy caddy caddy reload
```
- JWTs are signed, not encrypted. Do not put secrets into JWT claims.
- `JWT_SECRET` must be random and private.
- Access tokens expire after 15 minutes.
- Refresh tokens expire after 7 days and are rotated on refresh.
- Refresh tokens and recovery codes are stored in the database as hashes.
- TOTP secrets are currently stored in the database because the server must validate codes. Protect the database file accordingly.
- Recovery codes are only shown when generated. Users should download or copy them immediately.
- 2FA disable and recovery-code regeneration require both the current password and a valid TOTP code.
- The project should add rate limiting before being exposed to untrusted public traffic.
- The project should add more automated tests around login, 2FA, recovery codes, and account settings before being considered production-ready.
## Screenshots
## Images
#### Dashboard
<img src="docs/img/dashboard.png">

View File

@@ -1,51 +1,213 @@
# Authentication Architecture
MiauInv implements a stateless JSON Web Token (JWT) architecture combined with a persistent database-backed Refresh Token mechanism to provide high security alongside seamless session retention.
MiauInv uses signed JWT access tokens, database-backed refresh tokens, and optional TOTP-based two-factor authentication. The authentication flow is implemented in the `auth/`, `handlers/`, `storage/`, and `frontend/assets/js/` packages.
## Token Lifetime and Properties
JWTs are signed with a symmetric secret from the `JWT_SECRET` environment variable. They are not encrypted. Claims should therefore contain identity and authorization metadata only, not secrets.
| Token Type | Transport Vector | Storage Location | Lifetime | Purpose |
| --- | --- | --- | --- | --- |
| **Access Token** | HTTP-Only Cookie & Auth Header | Memory / Browser Cookies | 15 Minutes | Signed payload validating current session identity for immediate API interaction. |
| **Refresh Token** | Secure Cookie & JSON Payload | LocalStorage / Secure Cookies | 7 Days | Long-lived high-entropy string used to request a new token pair when the Access Token expires. |
## Components
---
| Component | Location | Responsibility |
| --- | --- | --- |
| JWT helpers | `auth/jwt.go` | Access-token and purpose-token generation/validation. |
| Middleware | `auth/middleware.go` | Extracts access tokens from bearer headers or cookies and injects claims into the request context. |
| Password helpers | `auth/password.go` | bcrypt hashing and verification. |
| Login/account handlers | `handlers/account.go` | Register, login, 2FA, refresh, logout, account settings, and user metadata. |
| Persistent session storage | `storage/storage.go` | Refresh tokens, 2FA state, TOTP secret, and recovery-code hashes. |
| Frontend auth logic | `frontend/assets/js/auth.js`, `frontend/assets/js/login.js`, `frontend/assets/js/api.js` | Login UI, token refresh, account settings, and 2FA UI interactions. |
## Token Rotation and Flow
## Token Types
The application coordinates token validation through cooperative interactions between Go authentication middlewares and the frontend runtime environment.
| Token | Storage/Transport | Lifetime | Purpose |
| --- | --- | --- | --- |
| Access token | `access_token` HTTP-only secure cookie and JSON response body | 15 minutes | Authenticates normal API and page requests. |
| Refresh token | `refresh_token` HTTP-only secure cookie and JSON response body | 7 days | Rotates sessions after access-token expiry. Stored in the database only as a hash. |
| 2FA challenge token | JSON response from `/api/login` | 5 minutes | Allows `/api/login/2fa` to complete login after password verification. It is purpose-bound to `2fa_login`. |
### 1. Normal Authenticated Requests
During standard interaction loops, the Go server intercepts requests via auth middleware. It checks the incoming context for validity in the following order:
1. `Authorization: Bearer <token>` request header.
2. `access_token` cookie values.
## Normal Login Flow Without 2FA
If a valid, unexpired Access Token is recovered, the middleware parses the claims (ID, username, role) and injects them into the request context before execution routes fire.
1. Client sends `POST /api/login` with `username` and `password`.
2. Server loads the user by username.
3. Server verifies the bcrypt password hash.
4. If 2FA is disabled, the server issues:
- a signed access token,
- a high-entropy refresh token,
- HTTP-only secure cookies for both tokens,
- a JSON response containing the same token values and user metadata.
5. The refresh token is hashed before being stored in the `refresh_tokens` table.
### 2. Token Refresh Flow
When an Access Token expires mid-session, the following workflow occurs automatically:
1. The backend rejects an API call or routing intent with an HTTP state indicating token expiration.
2. The frontend execution scope identifies the expiration status and reads the `refresh_token` from storage assets.
3. The client submits a POST request containing the token payload to `/api/refresh`.
4. The backend verifies the signature, looks up the hash inside the `refresh_tokens` table, and verifies that `revoked == 0` and `expires_at > now`.
5. If the validation succeeds, a brand-new Access Token and a rotated Refresh Token pair are generated, saved to secure cookies/storage, and the user session continues without explicit re-authentication.
---
## Security Mitigations
### Loop Protection
To prevent broken, expired, or malformed credentials from triggering infinite network refresh loops (which degrade browser performance and strain backend lookup performance), the frontend utilizes an explicit safety lock.
## Login Flow With 2FA Enabled
1. Client sends `POST /api/login` with `username` and `password`.
2. Server verifies the password.
3. If `two_factor_enabled` is true, the server does not issue a full session.
4. Instead, the server returns:
```json
{
"requires_2fa": true,
"two_factor_token": "..."
}
```
Token Expired -> Check 'is_refreshing' flag -> True -> Clear Auth & Force Login
-> False -> Set flag 'true' -> Send Request
5. The frontend shows the second login step.
6. Client sends `POST /api/login/2fa` with:
```json
{
"two_factor_token": "...",
"code": "123456"
}
```
Before issuing an evaluation request to `/api/refresh`, the application checks a temporary session variable (`is_refreshing` within `sessionStorage`). If the flag is already set to `true`, the loop protection triggers a hard clearance routine via `clearAllAuth()`, drops all token storage records, and routes the user back to the primary login view safely.
7. The server validates the purpose token against the expected purpose `2fa_login`.
8. The server loads the user from the purpose-token claim.
9. The supplied code is checked as a TOTP code first.
10. If the TOTP check fails, the supplied value is normalized and checked as a recovery code.
11. If either check succeeds, the server issues the normal access/refresh token session.
12. If a recovery code was used, it is marked as used and cannot be used again.
### Database Revocation
Refresh sessions can be killed immediately from the server side. When a user requests `/api/logout`, the backend switches the corresponding row state within the `refresh_tokens` database container to `revoked = 1`. Any subsequent rotation requests relying on that token family are automatically dropped, protecting against stolen credential replay attacks.
## TOTP Setup Flow
The account settings page at `/profile/settings` exposes the UI for TOTP setup.
1. Authenticated user calls `POST /api/2fa/setup`.
2. Server creates a TOTP secret using issuer `MiauInv` and the current username as the account name.
3. Server stores the secret in `users.two_factor_secret`, but does not enable 2FA yet.
4. Server returns:
```json
{
"secret": "BASE32SECRET",
"otpauth_url": "otpauth://totp/...",
"qr_code": "data:image/png;base64,..."
}
```
5. The frontend displays the QR code and the manual setup key.
6. User scans the QR code or enters the secret manually into an authenticator app.
7. User submits a current TOTP code to `POST /api/2fa/enable`.
8. Server validates the code.
9. Server enables 2FA and generates recovery codes.
10. Recovery codes are returned once to the client for download/copying.
## Recovery Codes
Recovery codes are generated when 2FA is enabled and when the user regenerates them.
Properties:
- Generated with cryptographically secure randomness.
- Formatted as four groups of five hexadecimal characters.
- Normalized before hashing by removing spaces and hyphens and lowercasing the value.
- Stored only as hashes in `two_factor_recovery_codes`.
- Single-use only.
- Displayed only immediately after generation/regeneration.
- Downloaded client-side from the account settings page as `miauinv-recovery-codes.txt`.
Recovery-code login flow:
1. User enters a recovery code in the same field as the TOTP code during the second login step.
2. Server first attempts normal TOTP validation.
3. If TOTP validation fails, server hashes the normalized recovery code.
4. Server updates the matching unused row with `used_at = now`.
5. If exactly one row was updated, the recovery-code login succeeds.
## Recovery-Code Regeneration
`POST /api/2fa/recovery-codes/regenerate` requires:
```json
{
"password": "current-password",
"code": "123456"
}
```
The server verifies the current password and a current TOTP code. If both are valid, all previous recovery codes are deleted and a new set is inserted. The new plaintext codes are returned once.
## Disabling 2FA
`POST /api/2fa/disable` requires:
```json
{
"password": "current-password",
"code": "123456"
}
```
If the password and TOTP code are valid, the server:
1. Sets `two_factor_enabled = 0`.
2. Clears `two_factor_secret`.
3. Deletes recovery codes for the user.
4. Revokes refresh tokens for the user.
5. Clears authentication cookies.
The frontend redirects the user to `/login` after disabling 2FA because existing sessions are revoked.
## Refresh Token Rotation
`POST /api/refresh` accepts the refresh token either from JSON:
```json
{
"refresh_token": "..."
}
```
or from the `refresh_token` cookie.
The server:
1. Hashes the supplied token.
2. Looks it up in `refresh_tokens`.
3. Rejects revoked or expired tokens.
4. Marks the used refresh token as revoked.
5. Issues a new access token and refresh token.
6. Stores the new refresh token hash.
7. Updates the auth cookies.
## Account Settings Security
The account settings page currently supports:
- username changes,
- password changes,
- TOTP 2FA setup,
- TOTP 2FA disable,
- recovery-code download after generation,
- recovery-code regeneration.
Username changes require the current password.
Password changes require the current password, reject passwords longer than bcrypt's 72-byte effective limit, revoke existing refresh tokens, and issue a new session.
## Middleware Behavior
Protected routes use `AuthMiddleware`.
The middleware checks tokens in this order:
1. `Authorization: Bearer <token>` header.
2. `access_token` cookie.
If no token is found:
- `/api/*` routes receive `401 Unauthorized`.
- non-API routes redirect to `/login`.
If token validation fails:
- `/api/*` routes receive `401 Unauthorized`.
- non-API routes clear the access cookie and redirect to `/login`.
## Security Limitations and Follow-up Work
The current implementation is usable for private/self-hosted deployments, but these improvements should be prioritized before exposing it to untrusted public traffic:
- Add rate limiting for login, 2FA, refresh, and recovery-code attempts.
- Add audit logging for account security changes.
- Add optional session/device management UI.
- Consider encrypting TOTP secrets at rest if the deployment threat model includes database disclosure.
- Expand tests for all authentication and account settings handlers.

View File

@@ -1,97 +1,194 @@
# Database Documentation
MiauInv utilizes an embedded SQLite database instance for persistent data storage. Foreign key constraints are strictly enforced at the database level.
MiauInv uses SQLite for persistent storage. The schema is initialized in `storage.InitDB` and foreign-key enforcement is explicitly enabled with:
## Configuration
To ensure data integrity, every database connection initialization explicitly executes the following command before handling queries:
```sql
PRAGMA foreign_keys = ON;
```
---
The database stores users, refresh tokens, 2FA recovery codes, inventory items, locations, projects, stock mappings, and project allocations.
## Schema Architecture
## Entity Overview
### Entity-Relationship Summary
```text
[users] 1 ──── N [refresh_tokens]
[users] 1 ──── N [two_factor_recovery_codes]
The database consists of primary entity tables (`users`, `items`, `locations`, `projects`) and relational junction tables (`stock`, `project_items`, `refresh_tokens`) designed to track stock distribution and access sessions.
```
[users] <--- (1:N) ---> [refresh_tokens]
[items] <--- (1:N) ---> [stock] <--- (N:1) ---> [locations]
[items] <--- (1:N) ---> [project_items] <--- (N:1) ---> [projects]
[items] 1 ──── N [stock] N ──── 1 [locations]
[items] 1 ──── N [project_items] N ──── 1 [projects]
```
---
## Tables
## Table Definitions
### `users`
### 1. users
Stores account credentials, roles, and 2FA state.
Stores user credentials and operational roles within the system.
| Column | Type | Constraints | Description |
| --- | --- | --- | --- |
| `id` | `TEXT` | Primary key | User UUID. |
| `username` | `TEXT` | Not null, unique | Lowercased account name. |
| `password` | `TEXT` | Not null | bcrypt password hash. |
| `role` | `TEXT` | Not null | User role, for example `user` or `admin`. |
| `two_factor_enabled` | `INTEGER` | Not null, default `0` | Boolean flag for TOTP 2FA state. |
| `two_factor_secret` | `TEXT` | Not null, default `''` | TOTP secret used to validate authenticator codes. Empty when 2FA is disabled. |
* **id (TEXT, PK):** Unique UUID
* **username (TEXT, Unique):** Unique account identifier.
* **password (TEXT):** Hashed user password.
* **role (TEXT):** Access control flag (e.g., admin, user).
Migration note: existing databases are migrated with `ALTER TABLE` statements for `two_factor_enabled` and `two_factor_secret` if those columns do not exist yet.
### 2. refresh_tokens
### `refresh_tokens`
Tracks valid extended sessions linked to specific user accounts.
Stores refresh-token sessions. Tokens are stored as hashes, not plaintext.
* **id (TEXT, PK):** Unique identifier.
* **user_id (TEXT, FK):** References `users(id)`.
* **token_hash (TEXT):** Cryptographic hash of the active refresh token.
* **expires_at (INTEGER):** Unix timestamp indicating token expiration.
* **created_at (INTEGER):** Unix timestamp indicating session creation.
* **revoked (INTEGER):** Boolean flag (0 or 1) indicating if the session was manually invalidated.
* **device_info (TEXT, Optional):** Client metadata for auditing.
| Column | Type | Constraints | Description |
| --- | --- | --- | --- |
| `id` | `TEXT` | Primary key | Refresh-token row UUID. |
| `user_id` | `TEXT` | Not null, foreign key to `users(id)` | Owning user. |
| `token_hash` | `TEXT` | Not null | Hash of the refresh token. |
| `expires_at` | `INTEGER` | Not null | Unix timestamp for expiry. |
| `created_at` | `INTEGER` | Not null | Unix timestamp for creation. |
| `revoked` | `INTEGER` | Not null, default `0` | Boolean revocation flag. |
| `device_info` | `TEXT` | Optional | User-Agent string recorded when the session is created. |
### 3. items
Refresh-token rotation revokes the used refresh token and inserts a new row for the next token.
Represents individual tracked assets.
### `two_factor_recovery_codes`
* **id (INTEGER, PK, Autoincrement):** Primary key.
* **name (TEXT):** Asset designation.
* **category (TEXT, Optional):** Grouping classification.
* **description (TEXT, Optional):** Detailed asset context.
* **total_quantity (INTEGER):** Absolute global stock baseline counter.
Stores recovery-code hashes for 2FA fallback login.
### 4. locations
| Column | Type | Constraints | Description |
| --- | --- | --- | --- |
| `id` | `TEXT` | Primary key | Recovery-code row UUID. |
| `user_id` | `TEXT` | Not null, foreign key to `users(id)` with `ON DELETE CASCADE` | Owning user. |
| `code_hash` | `TEXT` | Not null, unique with `user_id` | Hash of the normalized recovery code. |
| `created_at` | `INTEGER` | Not null | Unix timestamp for creation. |
| `used_at` | `INTEGER` | Nullable | Unix timestamp when the code was consumed. `NULL` means unused. |
Defines logical or physical facilities.
Recovery codes are deleted and replaced when the user regenerates them. A recovery code is consumed with an atomic update that only matches unused codes.
* **id (INTEGER, PK, Autoincrement):** Primary key.
* **name (TEXT, Unique):** Unique facility naming constraint.
### `items`
### 5. projects
Stores tracked inventory items.
Defines distinct tasks or allocation targets.
| Column | Type | Constraints | Description |
| --- | --- | --- | --- |
| `id` | `INTEGER` | Primary key, autoincrement | Item ID. |
| `name` | `TEXT` | Not null | Item name. |
| `category` | `TEXT` | Optional | Category label. |
| `description` | `TEXT` | Optional | Item description. |
| `total_quantity` | `INTEGER` | Not null, default `0` | Global quantity baseline. |
* **id (INTEGER, PK, Autoincrement):** Primary key.
* **name (TEXT, Unique):** Unique operational tracking name.
* **description (TEXT, Optional):** Scope description.
### `locations`
### 6. stock
Stores physical or logical storage locations.
Junction table mapping physical asset distributions across facilities.
| Column | Type | Constraints | Description |
| --- | --- | --- | --- |
| `id` | `INTEGER` | Primary key, autoincrement | Location ID. |
| `name` | `TEXT` | Not null, unique | Location name. |
* **id (INTEGER, PK, Autoincrement):** Primary key.
* **item_id (INTEGER, FK):** References `items(id)`.
* **location_id (INTEGER, FK):** References `locations(id)`.
* **quantity (INTEGER):** Specific quantity present at this location node.
### `projects`
### 7. project_items
Stores project contexts for item allocation.
Junction table tracking asset assignments dedicated to specific ongoing project environments.
| Column | Type | Constraints | Description |
| --- | --- | --- | --- |
| `id` | `INTEGER` | Primary key, autoincrement | Project ID. |
| `name` | `TEXT` | Not null, unique | Project name. |
| `description` | `TEXT` | Optional | Project description. |
* **id (INTEGER, PK, Autoincrement):** Primary key.
* **item_id (INTEGER, FK):** References `items(id)`.
* **project_id (INTEGER, FK):** References `projects(id)`.
* **quantity (INTEGER):** Quantity allocated to this project context.
---
### `stock`
## Data Integrity Constraints
Maps item quantities to locations.
* **Foreign Keys:** Because standard `ON DELETE` cascades are not defined explicitly in the schema rules, SQLite blocks parent deletion actions if dependent rows exist in `stock` or `project_items`. You must clear out stock allocations and project associations manually before deleting an item, location, or project.
* **Uniqueness:** String uniqueness constraints protect against duplicate namespace registration on `users(username)`, `locations(name)`, and `projects(name)`.
| Column | Type | Constraints | Description |
| --- | --- | --- | --- |
| `id` | `INTEGER` | Primary key, autoincrement | Stock row ID. |
| `item_id` | `INTEGER` | Not null, foreign key to `items(id)` | Item reference. |
| `location_id` | `INTEGER` | Not null, foreign key to `locations(id)` | Location reference. |
| `quantity` | `INTEGER` | Not null | Quantity at this location. |
### `project_items`
Maps item quantities to projects.
| Column | Type | Constraints | Description |
| --- | --- | --- | --- |
| `id` | `INTEGER` | Primary key, autoincrement | Association row ID. |
| `item_id` | `INTEGER` | Not null, foreign key to `items(id)` | Item reference. |
| `project_id` | `INTEGER` | Not null, foreign key to `projects(id)` | Project reference. |
| `quantity` | `INTEGER` | Not null | Quantity allocated to the project. |
## Data Integrity
### Foreign keys
Foreign keys are enabled per connection. Because most inventory foreign keys do not define explicit cascade behavior, SQLite blocks deletion of referenced items, locations, or projects while dependent rows exist.
`two_factor_recovery_codes.user_id` uses `ON DELETE CASCADE`, so deleting a user also deletes their recovery-code rows.
### Uniqueness
The following values are unique:
- `users.username`
- `locations.name`
- `projects.name`
- `two_factor_recovery_codes(user_id, code_hash)`
### Current schema limitations
The current schema does not yet enforce all business rules at the database level. In particular:
- `items.total_quantity` has no explicit `CHECK(total_quantity >= 0)` constraint.
- `stock.quantity` has no explicit `CHECK(quantity >= 0)` constraint.
- `project_items.quantity` has no explicit `CHECK(quantity >= 0)` constraint.
- Duplicate stock rows for the same `(item_id, location_id)` pair are not prevented by a unique constraint.
- Duplicate project allocations for the same `(item_id, project_id)` pair are not prevented by a unique constraint.
These constraints should be added in a future migration once the desired application behavior is finalized.
## Important Queries and Behaviors
### User lookup
Users can be loaded by lowercased username or ID. Username updates store the new username lowercased.
### Password update
When the password is updated:
1. The new password is bcrypt-hashed.
2. The `users.password` field is updated.
3. Existing refresh tokens for that user are revoked.
4. A new session is issued.
### 2FA enable
When 2FA is enabled:
1. The TOTP secret must already exist from `/api/2fa/setup`.
2. The supplied TOTP code is validated.
3. Existing recovery codes are deleted.
4. New recovery-code hashes are inserted.
5. `users.two_factor_enabled` is set to `1`.
### 2FA disable
When 2FA is disabled:
1. `two_factor_enabled` is set to `0`.
2. `two_factor_secret` is cleared.
3. Recovery-code rows for the user are deleted.
4. Refresh tokens for the user are revoked.
### Recovery-code use
A recovery code is consumed with an update equivalent to:
```sql
UPDATE two_factor_recovery_codes
SET used_at = ?
WHERE user_id = ? AND code_hash = ? AND used_at IS NULL;
```
The login succeeds only if exactly one row is updated.