Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
66 commits
Select commit Hold shift + click to select a range
14fefab
feat: implement authentication endpoint with validation for headers a…
devZenta Dec 17, 2025
255e06f
feat: enable tests in Dockerfile and update entrypoint in compose.yam…
devZenta Dec 18, 2025
2458df2
feat: enhance biome configuration with additional linter rules and fo…
devZenta Dec 18, 2025
360fe25
feat: update dependencies and scripts in package.json and bun.lock fo…
devZenta Dec 18, 2025
14f050f
feat: add authentication middleware for client validation and token d…
devZenta Dec 18, 2025
3b9d3b6
feat: add EventType enum for event categorization
devZenta Dec 18, 2025
4a6c300
feat: integrate CORS support and enhance server initialization with e…
devZenta Dec 19, 2025
dd09ae4
feat: update entrypoint in Docker Compose to include database seeding
devZenta Dec 19, 2025
297706e
feat: update Prisma schema to include History model and refine EventT…
devZenta Dec 19, 2025
caf4f28
feat: add migration for History table and EventType enum
devZenta Dec 19, 2025
320f63b
feat: add seed script for initial database setup and data seeding
devZenta Dec 19, 2025
9faaaa5
feat: implement event bus with initial event definitions
devZenta Dec 19, 2025
cfdbf7f
feat: add encryption and decryption utility functions
devZenta Dec 19, 2025
6b4120f
feat: add system health check route with database connection status
devZenta Dec 19, 2025
b206942
feat: implement client registration endpoint with database integration
devZenta Dec 19, 2025
4bc5dc2
feat: implement home state management and rule engine with WebSocket …
devZenta Dec 19, 2025
221a441
fix: handle token decryption errors and return appropriate response
devZenta Dec 19, 2025
365378e
refactor: clean up route middleware usage for better readability
devZenta Dec 19, 2025
b9bb414
refactor: remove unnecessary comments and clean up WebSocket connecti…
devZenta Dec 19, 2025
0ae64cb
feat: add Prisma generate command to Dockerfile for database setup
devZenta Dec 19, 2025
bd2f488
feat: add root client initialization to seed script
devZenta Dec 19, 2025
36c4b12
refactor: remove previewFeatures from Prisma client generator
devZenta Dec 19, 2025
770896f
feat: update server startup logs to include dynamic port configuration
devZenta Dec 19, 2025
bc2c0d2
refactor: remove unnecessary comments from homeState service
devZenta Dec 19, 2025
eca0a11
feat: enhance API responses with detailed error handling and add hist…
devZenta Dec 19, 2025
e54a7e5
fix: change noExplicitAny rule from warn to error in linter configura…
devZenta Dec 19, 2025
362e630
feat: add comprehensive test cases for authentication, check, feature…
devZenta Dec 19, 2025
fcf019b
feat: configure CORS settings for enhanced security and flexibility
devZenta Dec 21, 2025
5445546
refactor: streamline WebSocket connection handling and improve logging
devZenta Dec 21, 2025
ba5ef0c
feat: enhance rule descriptions and conditions for heating and lighti…
devZenta Dec 21, 2025
f1b6fa7
refactor: remove redundant comments in rule engine initialization
devZenta Dec 21, 2025
6f9a920
feat: allow dynamic salt configuration for encryption
devZenta Dec 21, 2025
dd8f2e4
feat: add example environment configuration and documentation
devZenta Dec 21, 2025
ba0085b
docs: add comprehensive documentation for BunServer setup and API usage
devZenta Dec 21, 2025
2aa54a9
refactor: restructure and enhance README documentation for better cla…
devZenta Dec 21, 2025
2738784
feat: add end-to-end integration tests for authentication and state m…
devZenta Dec 24, 2025
1d92f4f
feat: add unit tests for authentication middleware with various crede…
devZenta Dec 24, 2025
71eece5
feat: add comprehensive unit tests for HomeState service methods and …
devZenta Dec 24, 2025
471d849
test: add unit tests for eventBus functionality and event emission
devZenta Dec 24, 2025
5110ebe
feat: enhance authentication tests and add history route tests with e…
devZenta Dec 24, 2025
ff80ca8
feat: add snapshot tests for history route with various data scenarios
devZenta Dec 24, 2025
4a9c8ea
feat: add unit tests for rule definitions and enhance rule engine tests
devZenta Dec 24, 2025
c55ba07
feat: add CI and PR workflows for automated testing and linting
devZenta Dec 24, 2025
eab516e
feat: update biome check to enforce error on warnings for src and tests
devZenta Dec 24, 2025
5a73957
feat: enhance test setup with beforeEach for consistent mock state in…
devZenta Dec 24, 2025
1d34277
feat: add beforeEach hooks for consistent mock state initialization i…
devZenta Dec 24, 2025
3c5d692
feat: enhance mockPrisma setup in tests for improved route handling
devZenta Dec 24, 2025
974d724
feat: update mock state temperature and door status in tests for cons…
devZenta Dec 24, 2025
5e78035
refactor: centralize Prisma mock for test isolation
devZenta Dec 25, 2025
866aec1
chore: remove accidental error file
devZenta Dec 25, 2025
6ad6f78
chore: clean up test files for improved readability and maintainability
devZenta Dec 26, 2025
fc26c9c
feat: update mock state handling to prevent mutation without valid data
devZenta Dec 26, 2025
4bd34a9
feat: enhance CI workflow by adding Prisma Client generation step and…
devZenta Dec 27, 2025
678c2cd
feat: add DATABASE_URL environment variable for Prisma Client generat…
devZenta Dec 27, 2025
6c093c3
feat: enhance CI configuration with encryption keys and improve WebSo…
devZenta Dec 27, 2025
5c3eb06
refactor: update prisma mock module paths for cross-platform compatib…
devZenta Dec 27, 2025
37774dc
feat: enhance test environment setup by improving PrismaClient initia…
devZenta Dec 27, 2025
d53e8d7
feat: refactor Prisma initialization and enhance mock integration for…
devZenta Dec 27, 2025
0cdcf50
chore: skip flaky tests that fail in CI Linux environment
devZenta Dec 27, 2025
4bf09b0
fix: add missing token for Codecov action in CI workflow
devZenta Dec 27, 2025
9ae98c1
fix: add missing slug parameter to Codecov action in CI workflow
devZenta Dec 27, 2025
7dbfdd7
feat: add Docker workflow for building and pushing images
devZenta Dec 27, 2025
91a521a
fix: add Prisma generate and env vars to PR workflow
devZenta Dec 27, 2025
8095330
fix: add DATABASE_URL env var for Knip in PR workflow
devZenta Dec 27, 2025
059f8a8
fix: exclude ~/.bun cache from Knip scan
devZenta Dec 27, 2025
b56da21
chore: remove unused dotenv dependency and fix knip config
devZenta Dec 27, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
DATABASE_URL="postgresql://root:root@localhost:5432/myhouse"
DATABASE_URL="postgresql://root:root@localhost:5432/myhouse"

# Security
ENCRYPTION_KEY="MySuperSecretPasswordFixed123!"
ENCRYPTION_SALT="MyFixedSalt"

# Ports
PORT_BUN_SERVER=3000
PORT_WEB_SERVER=8080
63 changes: 63 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
name: CI

on:
push:
branches: [main, feature/*]
pull_request:
branches: [main]

jobs:
test:
name: Test & Coverage
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: latest

- name: Install dependencies
run: bun install

- name: Generate Prisma Client
run: bunx --bun prisma generate
env:
DATABASE_URL: postgresql://user:password@localhost:5432/test

- name: Run tests with coverage
run: bun test --coverage --coverage-reporter=lcov --timeout 5000
env:
ENCRYPTION_KEY: TestEncryptionKey12345678901234
ENCRYPTION_SALT: TestSalt

- name: Upload coverage to Codecov
uses: codecov/codecov-action@v4
if: always()
with:
token: ${{ secrets.CODECOV_TOKEN }}
slug: ${{ github.repository }}
files: ./coverage/lcov.info
fail_ci_if_error: false

lint:
name: Lint & Format Check
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: latest

- name: Install dependencies
run: bun install

- name: Run Biome check
run: bunx --bun biome check --error-on-warnings src tests
45 changes: 45 additions & 0 deletions .github/workflows/docker.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
name: Docker

on:
push:
branches: [main]

env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}

jobs:
build-and-push:
name: Build & Push Docker Image
runs-on: ubuntu-latest
permissions:
contents: read
packages: write

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Log in to Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Extract metadata (tags, labels)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=raw,value=latest
type=sha,prefix=

- name: Build and push Docker image
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
44 changes: 44 additions & 0 deletions .github/workflows/pr.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: Pull Request Checks

on:
pull_request:
types: [opened, synchronize, reopened]

jobs:
validate:
name: Validate PR
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0

- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: latest

- name: Install dependencies
run: bun install

- name: Generate Prisma Client
run: bunx --bun prisma generate
env:
DATABASE_URL: postgresql://user:password@localhost:5432/test

- name: Run all checks
run: |
echo "Running Biome checks..."
bunx --bun biome check --error-on-warnings src tests

echo "Running tests..."
bun test --timeout 5000

echo "Running Knip (unused dependencies check)..."
bun run knip
env:
ENCRYPTION_KEY: TestEncryptionKey12345678901234
ENCRYPTION_SALT: TestSalt
DATABASE_URL: postgresql://user:password@localhost:5432/test
5 changes: 4 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,19 @@ FROM base AS prerelease
COPY --from=install /temp/dev/node_modules node_modules
COPY . .

RUN DATABASE_URL="postgresql://dummy:dummy@localhost:5432/dummy" bunx prisma generate

# [optional] tests & build
ENV NODE_ENV=production
#RUN bun test
RUN bun test
#RUN bun run build

# copy production dependencies and source code into final image
FROM base AS release
COPY --from=install /temp/prod/node_modules node_modules
COPY --from=prerelease /usr/src/app/index.ts .
COPY --from=prerelease /usr/src/app/package.json .
COPY --from=prerelease /usr/src/app/prisma.config.ts .
Copy link

Copilot AI Dec 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Dockerfile attempts to copy a file prisma.config.ts that does not appear to exist in the repository. This will cause the Docker build to fail. Either create this file or remove this line from the Dockerfile.

Copilot uses AI. Check for mistakes.
COPY --from=prerelease /usr/src/app/src ./src
COPY --from=prerelease /usr/src/app/prisma ./prisma

Expand Down
141 changes: 108 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,51 +1,126 @@
# BunServer
# 🏠 BunServer - Backend Domotique (MyHouse OS)

To install dependencies:
Ce projet est un serveur backend pour un système domotique, conçu pour être rapide, modulaire et orienté événements. Il gère l'état de la maison (lumières, chauffage, portes, température), conserve un historique des événements et automatise certaines tâches via un moteur de règles intelligent.

```bash
bun install
```
## 🛠 Stack Technique

To install Lefthook git hooks:
* **Runtime:** [Bun](https://bun.sh/) (JavaScript/TypeScript runtime ultra-rapide)
* **Framework Web:** [ElysiaJS](https://elysiajs.com/)
* **Base de données:** PostgreSQL
* **ORM:** [Prisma](https://www.prisma.io/)
* **Outils:** Biome (Linter/Formatter), Lefthook (Git Hooks), Docker

```bash
bunx lefthook install
```
## 🚀 Installation et Démarrage

To run:
### Prérequis
* Bun installé (`curl -fsSL https://bun.sh/install | bash`)
* Docker et Docker Compose (pour la base de données)

```bash
bun run start
```
### Configuration

Or with Docker:
1. **Cloner le projet** et installer les dépendances :
```bash
bun install
```

```bash
docker compose up --build
```
2. **Configurer les variables d'environnement** :
Copiez le fichier d'exemple et adaptez-le (notamment l'URL de la base de données).
```bash
cp .env.example .env
```

To run knip to check for unused dependencies:
3. **Démarrer la base de données** :
```bash
docker compose up -d
```

```bash
bun knip
```
### Lancer le serveur

To format code:
* **Mode développement** (avec rechargement automatique) :
```bash
bun run dev
```
* **Mode production** :
```bash
bun start
```

```bash
bun format
```
## 🔐 Authentification

To lint code:
L'API utilise un système d'authentification personnalisé basé sur un couple `ClientID` et `ClientToken`.

```bash
bun lint
```
* **Header requis :** `Authorization`
* **Format :** `ClientID:ClientToken`
* **Validation :** Le serveur vérifie que le `ClientID` existe et que le token fourni correspond au token chiffré stocké en base.

> ⚠️ **Note :** La route `/status` est publique. Toutes les autres routes (`/check`, `/history`, `/temp`, `/toggle`, `/auth`) sont protégées par le middleware d'authentification.

## 📡 API Reference

### Endpoints REST

#### Système
* `GET /status` : Vérifier l'état du serveur (Public).
* `GET /check` : Vérification de santé avancée (Protégé).

#### Contrôle (Toggle)
Ces routes permettent de modifier l'état des appareils.
* `POST /toggle/light` : Allumer/Éteindre la lumière.
* `POST /toggle/door` : Ouvrir/Fermer la porte.
* `POST /toggle/heat` : Activer/Désactiver le chauffage.

#### Température
* `POST /temp` : Mettre à jour la température actuelle de la maison.
* *Body :* `{ "temp": "number" }`

To check code:
#### Historique
* `GET /history` : Récupérer l'historique des événements (changements d'état, règles déclenchées).

```bash
bun check
### WebSocket (`/ws`)

Le serveur expose un endpoint WebSocket pour les mises à jour en temps réel.
* **Topic :** `home-updates`
* **Fonctionnement :** Le dashboard reçoit automatiquement les changements d'état (nouvelle température, lumière allumée, etc.) dès qu'ils se produisent.

## 🧠 Moteur de Règles (Automation)

Le système intègre un moteur de règles (`src/rules/engine.ts`) qui réagit aux changements d'état (`EVENTS.STATE_CHANGE`).

### Règles Actives (`src/rules/definitions.ts`)

1. **HEAT_ON_COLD (Chauffage Auto)**
* *Condition :* Température < 19°C **ET** Porte fermée **ET** Chauffage éteint.
* *Action :* Allume le chauffage.

2. **HEAT_OFF_HOT (Économie Chauffage)**
* *Condition :* Température > 23°C **ET** Chauffage allumé.
* *Action :* Éteint le chauffage.

3. **LIGHT_ON_ENTRY (Lumière Entrée)**
* *Condition :* Porte ouverte **ET** Lumière éteinte.
* *Action :* Allume la lumière (Bienvenue !).

4. **ECO_GUARD_DOOR (Sécurité Énergie)**
* *Condition :* Porte ouverte **ET** Chauffage allumé.
* *Action :* Coupe le chauffage pour ne pas chauffer l'extérieur.

## 📂 Architecture du Code

```
.
├── prisma/ # Schéma DB, Migrations et Seeds
├── src/
│ ├── middleware/ # AuthMiddleware (vérification token)
│ ├── routes/ # Définition des routes API (Elysia)
│ ├── rules/ # Moteur de règles et définitions
│ ├── services/ # Logique métier (HomeStateService)
│ ├── utils/ # Utilitaires (Crypto, EventBus)
│ ├── enums.ts # Types d'événements (TEMPERATURE, LIGHT...)
│ └── index.ts # Point d'entrée serveur
└── tests/ # Tests unitaires et d'intégration
```

This project was created using `bun init` in bun v1.3.4. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
## ✅ Tests et Qualité

* **Linter le code :** `bun run lint` (via Biome)
* **Lancer les tests :** `bun test`
26 changes: 23 additions & 3 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,37 @@
},
"formatter": {
"enabled": true,
"indentStyle": "tab"
"indentStyle": "tab",
"lineWidth": 100
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
"recommended": true,
"complexity": {
"noExtraBooleanCast": "error",
"noUselessCatch": "error"
},
"correctness": {
"noUnusedVariables": "error",
"noUnusedImports": "error"
},
"style": {
"noNamespace": "error",
"useAsConstAssertion": "error",
"useBlockStatements": "off"
},
"suspicious": {
"noExplicitAny": "error",
"noConsole": "off"
}
}
},
"javascript": {
"formatter": {
"quoteStyle": "double"
"quoteStyle": "double",
"semicolons": "always",
"trailingCommas": "all"
}
},
"assist": {
Expand Down
Loading