Compare commits

..

1 Commits

Author SHA1 Message Date
David
7251fc8b18 fix spit backend 2026-06-23 10:04:12 +02:00
588 changed files with 16029 additions and 67476 deletions

View File

@ -1,43 +0,0 @@
---
name: "source-command-explore-and-plan"
description: "Explore codebase, create implementation plan, code, and test following EPCT workflow"
---
# source-command-explore-and-plan
Use this skill when the user asks to run the migrated source command `explore-and-plan`.
## Command Template
# Explore, Plan, Code, Test Workflow
At the end of this message, I will ask you to do something.
Please follow the "Explore, Plan, Code, Test" workflow when you start.
## Explore
First, use parallel subagents to find and read all files that may be useful for implementing the ticket, either as examples or as edit targets. The subagents should return relevant file paths, and any other info that may be useful.
## Plan
Next, think hard and write up a detailed implementation plan. Don't forget to include tests, lookbook components, and documentation. Use your judgement as to what is necessary, given the standards of this repo.
If there are things you are not sure about, use parallel subagents to do some web research. They should only return useful information, no noise.
If there are things you still do not understand or questions you have for the user, pause here to ask them before continuing.
## Code
When you have a thorough implementation plan, you are ready to start writing code. Follow the style of the existing codebase (e.g. we prefer clearly named variables and methods to extensive comments). Make sure to run our autoformatting script when you're done, and fix linter warnings that seem reasonable to you.
## Test
Use parallel subagents to run tests, and make sure they all pass.
If your changes touch the UX in a major way, use the browser to make sure that everything works correctly. Make a list of what to test for, and use a subagent for this step.
If your testing shows problems, go back to the planning stage and think ultrahard.
## Write up your work
When you are happy with your work, write up a short report that could be used as the PR description. Include what you set out to do, the choices you made with their brief justification, and any commands you ran in the process that may be useful for future developers to know about.

View File

@ -1,17 +0,0 @@
---
name: "source-command-fix-pr-comments"
description: "Fetch all comments for the current pull request and fix them."
---
# source-command-fix-pr-comments
Use this skill when the user asks to run the migrated source command `fix-pr-comments`.
## Command Template
Workflow:
1. Use `gh cli` to fetch the comments that are NOT resolved from the pull request.
2. Define all the modifications you should actually make.
3. Act and update the files.
4. Create a commit and push.

View File

@ -1,43 +0,0 @@
---
name: "source-command-quick-commit"
description: "Quickly commit all changes with an auto-generated message"
---
# source-command-quick-commit
Use this skill when the user asks to run the migrated source command `quick-commit`.
## Command Template
Workflow for quick Git commits:
1. Check git status to see what changes are present
2. Analyze changes to generate a short, clear commit message
3. Stage all changes (tracked and untracked files)
4. Create the commit with DH7789-dev signature
5. Optionally push to remote if tracking branch exists
The commit message will be automatically generated by analyzing:
- Modified files and their purposes (components, configs, tests, docs, etc.)
- New files added and their function
- Deleted files and cleanup operations
- Overall scope of changes to determine action verb (add, update, fix, refactor, remove, etc.)
Commit message format: `[action] [what was changed]`
Examples:
- `add user authentication system`
- `fix navigation menu responsive issues`
- `update API endpoints configuration`
- `refactor database connection logic`
- `remove deprecated utility functions`
This command is ideal for:
- Quick iteration cycles
- Work-in-progress commits
- Feature development checkpoints
- Bug fix commits
The commit will include your custom signature:
```
Signed-off-by: DH7789-dev
```

View File

@ -1,25 +0,0 @@
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bun /Users/david/.claude/scripts/validate-command.js"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "afplay /Users/david/.claude/song/finish.mp3"
}
]
}
]
}
}

View File

@ -1,2 +0,0 @@
# All jobs use the existing ubuntu-latest runner label.
{}

View File

@ -1,44 +0,0 @@
name: Notify security gate failure
description: Posts a Discord alert when the Security gate fails and stops the pipeline.
inputs:
webhook-url:
description: Discord webhook URL.
required: true
pipeline:
description: Human-readable pipeline name shown in the alert.
required: true
runs:
using: composite
steps:
- name: Discord
shell: bash
env:
WEBHOOK_URL: ${{ inputs.webhook-url }}
PIPELINE: ${{ inputs.pipeline }}
REF_NAME: ${{ github.ref_name }}
ACTOR: ${{ github.actor }}
SHA: ${{ github.sha }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
# Payload built with json.dumps: branch or author names cannot break the JSON.
payload=$(python3 - <<'PY'
import json, os
print(json.dumps({
"content": "@here Security gate en échec — pipeline arrêté",
"embeds": [{
"title": f"🔒 Security gate en échec — {os.environ['PIPELINE']}",
"description": "Aucun lint, test, build ni déploiement n'a été lancé. Consultez l'artefact `security-reports`.",
"color": 15158332,
"fields": [
{"name": "Branche", "value": f"`{os.environ['REF_NAME']}`", "inline": True},
{"name": "Auteur", "value": os.environ["ACTOR"], "inline": True},
{"name": "Commit", "value": f"`{os.environ['SHA'][:7]}`", "inline": True},
{"name": "Workflow", "value": f"[Voir le run]({os.environ['RUN_URL']})", "inline": False},
],
"footer": {"text": f"Xpeditis CI/CD • {os.environ['PIPELINE']}"},
}],
}))
PY
)
curl -fsS --max-time 15 -H "Content-Type: application/json" -d "$payload" "$WEBHOOK_URL" \
|| echo "::warning::Notification Discord non envoyée."

View File

@ -1,31 +0,0 @@
name: Security gate
description: Dependency, secrets, infrastructure and workflow checks for Gitea 1.22.
runs:
using: composite
steps:
- uses: ./.gitea/actions/setup-node
- name: Install Trivy
shell: bash
run: |
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
"$trivy_bin" --version
- name: Validate workflows and deployment checks
shell: bash
run: |
actionlint_bin=$(bash scripts/ci/install-tool.sh actionlint)
ACTIONLINT_BIN="$actionlint_bin" bash scripts/ci/validate-workflows.sh
- name: Audit dependencies, secrets and infrastructure
shell: bash
run: bash scripts/ci/security-audit.sh
- name: Show security results
if: always()
shell: bash
run: python3 scripts/ci/summarize-security.py
- name: Save security reports on Gitea
if: always()
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
with:
name: security-reports
path: ${{ runner.temp }}/security-reports/*.json
retention-days: 7
if-no-files-found: error

View File

@ -1,11 +0,0 @@
name: Install and activate Node 22
description: Set up Node and verify the executable selected by the Gitea runner.
runs:
using: composite
steps:
- uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: '22'
- name: Activate and verify Node 22
shell: bash
run: bash scripts/ci/activate-node.sh

View File

@ -1,9 +0,0 @@
name: Install verified Trivy
description: Install a pinned native scanner with a checked SHA256.
runs:
using: composite
steps:
- shell: bash
run: |
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
"$trivy_bin" --version

View File

@ -1,414 +0,0 @@
name: CD Production
# Pipeline de production — Hetzner k3s (infra/prod/).
#
# Enchaînement : sécurité → qualité → vérification → promotion/rebuild → déploiement → contrôle
#
# TROIS RÈGLES STRUCTURANTES
#
# 1. Le BACKEND est PROMU depuis la preprod, jamais reconstruit.
# Promouvoir garantit que le binaire déployé en production est exactement
# celui qui a passé la chaîne de preprod (lint, tests unitaires, tests
# d'intégration, build). Un rebuild casserait cette garantie.
#
# 2. Le FRONTEND est RECONSTRUIT pour la production.
# next.config.js fige NEXT_PUBLIC_API_URL au moment du build. Promouvoir
# l'image de preprod livrerait une application qui appelle
# api.preprod.xpeditis.com en production. C'est la raison pour laquelle ce
# workflow ne peut pas se contenter de re-taguer.
#
# 3. Le déploiement passe par SSH, pas par l'API Kubernetes.
# L'API k3s (6443) n'est ouverte qu'aux IP d'administration. Les runners
# Gitea n'ont pas d'IP fixe : le job ouvre le port 22 pour la seule IP du
# runner via un firewall Hetzner dédié, puis le referme systématiquement.
#
# Secrets, runners et limites Gitea : voir docs/CI-CD-SECURITY.md
on:
push:
branches: [main]
env:
REGISTRY: rg.fr-par.scw.cloud/weworkstudio
K8S_NAMESPACE: xpeditis-prod
jobs:
security:
name: Security gate
runs-on: ubuntu-latest
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- name: Install Trivy
shell: bash
run: |
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
"$trivy_bin" --version
- name: Validate workflows and deployment checks
shell: bash
run: |
actionlint_bin=$(bash scripts/ci/install-tool.sh actionlint)
ACTIONLINT_BIN="$actionlint_bin" bash scripts/ci/validate-workflows.sh
- name: Audit dependencies, secrets and infrastructure
shell: bash
run: bash scripts/ci/security-audit.sh
- name: Show security results
if: always()
shell: bash
run: python3 scripts/ci/summarize-security.py
- name: Save security reports on Gitea
if: always()
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
with:
name: security-reports
path: ${{ runner.temp }}/security-reports/*.json
retention-days: 7
if-no-files-found: error
- name: Notify Discord
if: failure()
uses: ./.gitea/actions/notify-security-failure
with:
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
pipeline: Production
# ═══ 1. Qualité ══════════════════════════════════════════════════════════
backend-quality:
name: Backend — Lint
runs-on: ubuntu-latest
needs: security
defaults:
run:
working-directory: apps/backend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm run lint -- --no-fix
frontend-quality:
name: Frontend — Lint & Type-check
runs-on: ubuntu-latest
needs: security
defaults:
run:
working-directory: apps/frontend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm run lint
- run: npm run type-check
backend-tests:
name: Backend — Tests unitaires
runs-on: ubuntu-latest
needs: backend-quality
defaults:
run:
working-directory: apps/backend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm test -- --ci --runInBand
frontend-tests:
name: Frontend — Tests unitaires
runs-on: ubuntu-latest
needs: frontend-quality
defaults:
run:
working-directory: apps/frontend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm test -- --ci --runInBand
# ═══ 2. Vérification de la provenance ════════════════════════════════════
# Exige un pipeline preprod réussi ET un arbre Git identique au code testé ici.
verify-image:
name: Vérifier l'image de preprod
runs-on: ubuntu-latest
needs: [security, backend-tests, frontend-tests]
outputs:
sha: ${{ steps.sha.outputs.short }}
backend_digest: ${{ steps.sha.outputs.backend_digest }}
log_exporter_digest: ${{ steps.sha.outputs.log_exporter_digest }}
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 0
persist-credentials: false
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Resolve validated preprod release
id: sha
run: bash scripts/ci/resolve-release.sh
# ═══ 3b. Reconstruction du frontend avec les URLs de production ══════════
build-frontend:
name: Reconstruire le frontend (URLs de production)
runs-on: ubuntu-latest
needs: verify-image
outputs:
digest: ${{ steps.build.outputs.digest }}
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
# Cet arbre Git est identique à celui de la release preprod vérifiée.
ref: ${{ github.sha }}
- uses: https://github.com/docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3
with:
platforms: amd64,arm64
cache-image: false
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- id: build
uses: https://github.com/docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
with:
context: ./apps/frontend
file: ./apps/frontend/Dockerfile
push: true
platforms: linux/amd64
tags: |
${{ env.REGISTRY }}/xpeditis-frontend:candidate-prod-${{ github.sha }}-${{ github.run_id }}
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache-prod
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache-prod,mode=max
build-args: |
NEXT_PUBLIC_API_URL=${{ secrets.NEXT_PUBLIC_API_URL_PROD }}
NEXT_PUBLIC_APP_URL=${{ secrets.NEXT_PUBLIC_APP_URL_PROD }}
- name: Contrôle — l'URL de preprod ne doit pas figurer dans le bundle
run: |
IMAGE="${{ env.REGISTRY }}/xpeditis-frontend@${{ steps.build.outputs.digest }}"
CID=$(docker create --platform linux/amd64 "$IMAGE")
trap 'docker rm "$CID" >/dev/null' EXIT
docker cp "$CID:/app/.next" /tmp/next-check
test -d /tmp/next-check
trap - EXIT
docker rm "$CID" >/dev/null
if grep -rq "api.preprod.xpeditis.com" /tmp/next-check 2>/dev/null; then
echo "::error::L'URL de preprod est figée dans le bundle de production."
echo "Vérifiez le secret NEXT_PUBLIC_API_URL_PROD."
exit 1
fi
echo "Aucune URL de preprod dans le bundle."
image-security:
name: Image security (${{ matrix.service }}, ${{ matrix.arch }})
runs-on: ubuntu-latest
needs: [verify-image, build-frontend]
strategy:
fail-fast: false
matrix:
service: [backend, frontend, log-exporter]
arch: [amd64]
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-trivy
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Scan the exact image before deployment
env:
IMAGE: ${{ env.REGISTRY }}/xpeditis-${{ matrix.service }}@${{ matrix.service == 'frontend' && needs.build-frontend.outputs.digest || (matrix.service == 'backend' && needs.verify-image.outputs.backend_digest || needs.verify-image.outputs.log_exporter_digest) }}
PLATFORM: linux/${{ matrix.arch }}
run: |
trivy image --platform "$PLATFORM" --scanners vuln --severity HIGH,CRITICAL \
--ignore-unfixed=false --exit-code 1 --timeout 15m --no-progress --format json \
--output "$RUNNER_TEMP/image-security.json" "$IMAGE"
- name: Show image scan results
if: always()
run: python3 scripts/ci/summarize-image-security.py
- name: Save image report
if: always()
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
with:
name: image-security-${{ matrix.service }}-${{ matrix.arch }}
path: ${{ runner.temp }}/image-security.json
retention-days: 14
if-no-files-found: error
# ═══ 4. Déploiement ══════════════════════════════════════════════════════
deploy:
name: Déployer en production
runs-on: ubuntu-latest
needs: [verify-image, build-frontend, image-security]
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Publish scanned production images
env:
IMAGE_SHA: ${{ needs.verify-image.outputs.sha }}
BACKEND_DIGEST: ${{ needs.verify-image.outputs.backend_digest }}
FRONTEND_DIGEST: ${{ needs.build-frontend.outputs.digest }}
LOG_EXPORTER_DIGEST: ${{ needs.verify-image.outputs.log_exporter_digest }}
run: |
for service in backend frontend log-exporter; do
case "$service" in
backend) digest="$BACKEND_DIGEST" ;;
frontend) digest="$FRONTEND_DIGEST" ;;
log-exporter) digest="$LOG_EXPORTER_DIGEST" ;;
esac
docker buildx imagetools create \
--tag "$REGISTRY/xpeditis-$service:prod-$IMAGE_SHA" \
--tag "$REGISTRY/xpeditis-$service:latest" \
"$REGISTRY/xpeditis-$service@$digest"
done
- name: Installer le client Hetzner
run: |
hcloud_bin=$(bash scripts/ci/install-tool.sh hcloud)
"$hcloud_bin" version
- name: Ouvrir le port 22 pour l'IP de ce runner
env:
HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN_CICD }}
run: |
RUNNER_IP="$(curl -fsS --max-time 10 https://ifconfig.me)"
echo "IP du runner : ${RUNNER_IP}"
cat > /tmp/fw-open.json <<JSON
[{
"direction": "in",
"protocol": "tcp",
"port": "22",
"source_ips": ["${RUNNER_IP}/32"],
"description": "Gitea Actions run ${{ github.run_id }}"
}]
JSON
hcloud firewall replace-rules "${{ vars.HCLOUD_CICD_FIREWALL }}" --rules-file /tmp/fw-open.json
- name: Préparer SSH
env:
DEPLOY_SSH_KEY: ${{ secrets.PROD_SSH_KEY }}
DEPLOY_KNOWN_HOSTS: ${{ secrets.PROD_SSH_KNOWN_HOSTS }}
run: |
mkdir -p "$RUNNER_TEMP/deploy-ssh" && chmod 700 "$RUNNER_TEMP/deploy-ssh"
printf '%s\n' "$DEPLOY_SSH_KEY" > "$RUNNER_TEMP/deploy-ssh/id_ed25519"
chmod 600 "$RUNNER_TEMP/deploy-ssh/id_ed25519"
# Empreinte épinglée : un détournement DNS ou BGP ne peut pas
# rediriger le déploiement vers une machine tierce.
printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > "$RUNNER_TEMP/deploy-ssh/known_hosts"
chmod 600 "$RUNNER_TEMP/deploy-ssh/known_hosts"
- name: Synchroniser infra/prod sur le serveur
run: |
rsync -az --delete \
--exclude '.terraform' --exclude '*.tfstate*' --exclude '*.tfvars' \
-e "ssh -o StrictHostKeyChecking=yes -o UserKnownHostsFile=\"$RUNNER_TEMP/deploy-ssh/known_hosts\" -i \"$RUNNER_TEMP/deploy-ssh/id_ed25519\"" \
infra/prod/ \
"${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }}:/opt/xpeditis/infra-prod/"
- name: Déployer
id: deploy
run: |
SHA="${{ needs.verify-image.outputs.sha }}"
ssh -o StrictHostKeyChecking=yes -o UserKnownHostsFile="$RUNNER_TEMP/deploy-ssh/known_hosts" -i "$RUNNER_TEMP/deploy-ssh/id_ed25519" \
"${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }}" \
"deploy prod-${SHA}"
- name: Tests de fumée depuis l'extérieur
id: smoke
env:
PROD_API_URL: ${{ vars.PROD_API_URL }}
PROD_APP_URL: ${{ vars.PROD_APP_URL }}
run: bash infra/prod/scripts/smoke-test.sh
- name: Retour arrière si le déploiement a échoué
if: failure() && (steps.deploy.conclusion == 'failure' || steps.smoke.conclusion == 'failure')
run: |
ssh -o StrictHostKeyChecking=yes -o UserKnownHostsFile="$RUNNER_TEMP/deploy-ssh/known_hosts" -i "$RUNNER_TEMP/deploy-ssh/id_ed25519" \
"${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }}" \
"rollback" || true
- name: Refermer le firewall
# `always()` : la fenêtre d'exposition se referme même si le
# déploiement a échoué, si le job a été annulé ou s'il a expiré.
if: always()
env:
HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN_CICD }}
run: |
echo '[]' > /tmp/fw-close.json
hcloud firewall replace-rules "${{ vars.HCLOUD_CICD_FIREWALL }}" --rules-file /tmp/fw-close.json
echo "Firewall CI refermé."
- name: Effacer la clé SSH
if: always()
run: shred -u "$RUNNER_TEMP/deploy-ssh/id_ed25519" 2>/dev/null || rm -f "$RUNNER_TEMP/deploy-ssh/id_ed25519"
# ═══ 5. Notifications ════════════════════════════════════════════════════
notify-success:
name: Notifier le succès
runs-on: ubuntu-latest
needs: [verify-image, deploy]
if: success()
steps:
- run: |
curl -sf -H "Content-Type: application/json" -d '{
"embeds": [{
"title": "Production déployée et saine",
"color": 3066993,
"fields": [
{"name": "Auteur", "value": "${{ github.actor }}", "inline": true},
{"name": "Version", "value": "`prod-${{ needs.verify-image.outputs.sha }}`", "inline": true},
{"name": "Cible", "value": "Hetzner k3s — xpeditis-prod", "inline": false},
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
],
"footer": {"text": "Xpeditis CI/CD - Production"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
notify-failure:
name: Notifier l'échec
runs-on: ubuntu-latest
needs: [security, backend-quality, frontend-quality, backend-tests, frontend-tests, verify-image, build-frontend, image-security, deploy]
# Security gate failures are already reported by the security job itself.
if: failure() && needs.security.result != 'failure'
steps:
- run: |
curl -sf -H "Content-Type: application/json" -d '{
"content": "@here ECHEC DU PIPELINE DE PRODUCTION",
"embeds": [{
"title": "Pipeline de production en échec",
"description": "Un retour arrière a été tenté si l échec est survenu pendant le déploiement. Vérifiez l état réel avant toute nouvelle tentative.",
"color": 15158332,
"fields": [
{"name": "Auteur", "value": "${{ github.actor }}", "inline": true},
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false},
{"name": "A vérifier", "value": "Le firewall CI est-il bien refermé ? `hcloud firewall describe xpeditis-prod-fw-cicd`", "inline": false}
],
"footer": {"text": "Xpeditis CI/CD - Production"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}

View File

@ -1,451 +0,0 @@
name: CD Preprod
# Full pipeline triggered on every push to preprod.
# Flow: security gate → lint → unit tests → integration tests → docker build → deploy → notify
#
# Secrets required:
# REGISTRY_TOKEN — Scaleway registry (read/write)
# NEXT_PUBLIC_API_URL — https://api.preprod.xpeditis.com
# NEXT_PUBLIC_APP_URL — https://preprod.xpeditis.com
# PORTAINER_WEBHOOK_BACKEND — Portainer webhook (preprod backend)
# PORTAINER_WEBHOOK_FRONTEND— Portainer webhook (preprod frontend)
# DISCORD_WEBHOOK_URL
# Optional health URL overrides (secrets, then repository variables):
# PREPROD_BACKEND_URL — defaults to https://api.preprod.xpeditis.com
# PREPROD_FRONTEND_URL — defaults to https://app.preprod.xpeditis.com
on:
push:
branches: [preprod]
env:
REGISTRY: rg.fr-par.scw.cloud/weworkstudio
jobs:
security:
name: Security gate
runs-on: ubuntu-latest
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- name: Install Trivy
shell: bash
run: |
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
"$trivy_bin" --version
- name: Validate workflows and deployment checks
shell: bash
run: |
actionlint_bin=$(bash scripts/ci/install-tool.sh actionlint)
ACTIONLINT_BIN="$actionlint_bin" bash scripts/ci/validate-workflows.sh
- name: Audit dependencies, secrets and infrastructure
shell: bash
run: bash scripts/ci/security-audit.sh
- name: Show security results
if: always()
shell: bash
run: python3 scripts/ci/summarize-security.py
- name: Save security reports on Gitea
if: always()
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
with:
name: security-reports
path: ${{ runner.temp }}/security-reports/*.json
retention-days: 7
if-no-files-found: error
- name: Notify Discord
if: failure()
uses: ./.gitea/actions/notify-security-failure
with:
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
pipeline: Preprod
# ── 1. Lint ─────────────────────────────────────────────────────────
backend-quality:
name: Backend — Lint
runs-on: ubuntu-latest
needs: security
defaults:
run:
working-directory: apps/backend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm run lint -- --no-fix
frontend-quality:
name: Frontend — Lint & Type-check
runs-on: ubuntu-latest
needs: security
defaults:
run:
working-directory: apps/frontend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm run lint
- run: npm run type-check
# ── 2. Unit Tests ────────────────────────────────────────────────────
backend-tests:
name: Backend — Unit Tests
runs-on: ubuntu-latest
needs: backend-quality
defaults:
run:
working-directory: apps/backend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm test -- --ci --runInBand
frontend-tests:
name: Frontend — Unit Tests
runs-on: ubuntu-latest
needs: frontend-quality
defaults:
run:
working-directory: apps/frontend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm test -- --ci --runInBand
# ── 3. Integration Tests ─────────────────────────────────────────────
integration-tests:
name: Backend — Integration Tests
runs-on: ubuntu-latest
needs: [backend-tests, frontend-tests]
defaults:
run:
working-directory: apps/backend
services:
postgres:
image: postgres:15-alpine
env:
POSTGRES_USER: xpeditis_test
POSTGRES_PASSWORD: xpeditis_test_password
POSTGRES_DB: xpeditis_test
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 10
redis:
image: redis:7-alpine
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 5s
--health-retries 10
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- name: Run integration tests
env:
NODE_ENV: test
TEST_DB_HOST: postgres
TEST_DB_PORT: 5432
TEST_DB_USER: xpeditis_test
TEST_DB_PASSWORD: xpeditis_test_password
TEST_DB_NAME: xpeditis_test
DATABASE_HOST: postgres
DATABASE_PORT: 5432
DATABASE_USER: xpeditis_test
DATABASE_PASSWORD: xpeditis_test_password
DATABASE_NAME: xpeditis_test
DATABASE_SYNCHRONIZE: 'false'
REDIS_HOST: redis
REDIS_PORT: 6379
REDIS_PASSWORD: ''
JWT_SECRET: test-secret-key-ci
SMTP_HOST: localhost
SMTP_PORT: 1025
SMTP_FROM: test@xpeditis.com
run: npm run test:integration -- --ci --runInBand
# ── 4. Docker Build & Push ───────────────────────────────────────────
# Tags: preprod (latest for this env) + preprod-SHA (used by prod for exact promotion)
build-backend:
name: Build Backend
runs-on: ubuntu-latest
needs: [security, integration-tests]
outputs:
sha: ${{ steps.sha.outputs.short }}
digest: ${{ steps.build.outputs.digest }}
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- name: Short SHA
id: sha
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
- uses: https://github.com/docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3
with:
platforms: amd64,arm64
cache-image: false
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- id: build
uses: https://github.com/docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
with:
context: ./apps/backend
file: ./apps/backend/Dockerfile
push: true
tags: |
${{ env.REGISTRY }}/xpeditis-backend:preprod-${{ steps.sha.outputs.short }}
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-backend:buildcache
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-backend:buildcache,mode=max
platforms: linux/amd64,linux/arm64
build-frontend:
name: Build Frontend
runs-on: ubuntu-latest
needs: [security, integration-tests]
outputs:
sha: ${{ steps.sha.outputs.short }}
digest: ${{ steps.build.outputs.digest }}
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- name: Short SHA
id: sha
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
- uses: https://github.com/docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3
with:
platforms: amd64,arm64
cache-image: false
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- id: build
uses: https://github.com/docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
with:
context: ./apps/frontend
file: ./apps/frontend/Dockerfile
push: true
tags: |
${{ env.REGISTRY }}/xpeditis-frontend:preprod-${{ steps.sha.outputs.short }}
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache,mode=max
platforms: linux/amd64,linux/arm64
build-args: |
NEXT_PUBLIC_API_URL=${{ secrets.NEXT_PUBLIC_API_URL }}
NEXT_PUBLIC_APP_URL=${{ secrets.NEXT_PUBLIC_APP_URL }}
build-log-exporter:
name: Build Log Exporter
runs-on: ubuntu-latest
needs: [security, integration-tests]
outputs:
sha: ${{ steps.sha.outputs.short }}
digest: ${{ steps.build.outputs.digest }}
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- name: Short SHA
id: sha
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
- uses: https://github.com/docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3
with:
platforms: amd64,arm64
cache-image: false
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- id: build
uses: https://github.com/docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
with:
context: ./apps/log-exporter
file: ./apps/log-exporter/Dockerfile
push: true
tags: |
${{ env.REGISTRY }}/xpeditis-log-exporter:preprod-${{ steps.sha.outputs.short }}
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-log-exporter:buildcache
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-log-exporter:buildcache,mode=max
platforms: linux/amd64,linux/arm64
image-security:
name: Image security (${{ matrix.service }}, ${{ matrix.arch }})
runs-on: ubuntu-latest
needs: [build-backend, build-frontend, build-log-exporter]
strategy:
fail-fast: false
matrix:
service: [backend, frontend, log-exporter]
arch: [amd64, arm64]
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-trivy
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Scan the exact image before deployment
env:
IMAGE: ${{ env.REGISTRY }}/xpeditis-${{ matrix.service }}@${{ needs[format('build-{0}', matrix.service)].outputs.digest }}
PLATFORM: linux/${{ matrix.arch }}
run: |
trivy image --platform "$PLATFORM" --scanners vuln --severity HIGH,CRITICAL \
--ignore-unfixed=false --exit-code 1 --timeout 15m --no-progress --format json \
--output "$RUNNER_TEMP/image-security.json" "$IMAGE"
- name: Show image scan results
if: always()
run: python3 scripts/ci/summarize-image-security.py
- name: Save image report
if: always()
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
with:
name: image-security-${{ matrix.service }}-${{ matrix.arch }}
path: ${{ runner.temp }}/image-security.json
retention-days: 14
if-no-files-found: error
# ── 5. Deploy via Portainer ──────────────────────────────────────────
deploy:
name: Deploy to Preprod
runs-on: ubuntu-latest
needs: [build-backend, build-frontend, build-log-exporter, image-security]
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Publish scanned preprod images
env:
BACKEND_DIGEST: ${{ needs.build-backend.outputs.digest }}
FRONTEND_DIGEST: ${{ needs.build-frontend.outputs.digest }}
LOG_EXPORTER_DIGEST: ${{ needs.build-log-exporter.outputs.digest }}
run: |
for service in backend frontend log-exporter; do
case "$service" in
backend) digest="$BACKEND_DIGEST" ;;
frontend) digest="$FRONTEND_DIGEST" ;;
log-exporter) digest="$LOG_EXPORTER_DIGEST" ;;
esac
docker buildx imagetools create \
--tag "$REGISTRY/xpeditis-$service:preprod" \
"$REGISTRY/xpeditis-$service@$digest"
done
- name: Deploy backend
run: |
HTTP_CODE=$(curl --connect-timeout 10 --max-time 30 -s -o /dev/null -w "%{http_code}" -X POST "${{ secrets.PORTAINER_WEBHOOK_BACKEND }}")
echo "Portainer response: HTTP $HTTP_CODE"
if [[ "$HTTP_CODE" != "2"* ]]; then
echo "ERROR: Portainer webhook failed with HTTP $HTTP_CODE"
exit 1
fi
echo "Backend webhook triggered."
- name: Wait for backend startup
run: sleep 20
- name: Deploy frontend
run: |
HTTP_CODE=$(curl --connect-timeout 10 --max-time 30 -s -o /dev/null -w "%{http_code}" -X POST "${{ secrets.PORTAINER_WEBHOOK_FRONTEND }}")
echo "Portainer response: HTTP $HTTP_CODE"
if [[ "$HTTP_CODE" != "2"* ]]; then
echo "ERROR: Portainer webhook failed with HTTP $HTTP_CODE"
exit 1
fi
echo "Frontend webhook triggered."
- name: Verify backend health
env:
BASE_URL: ${{ secrets.PREPROD_BACKEND_URL || vars.PREPROD_BACKEND_URL || 'https://api.preprod.xpeditis.com' }}
run: bash scripts/ci/health-check.sh "${BASE_URL%/}/api/v1/health"
- name: Verify frontend health
env:
BASE_URL: ${{ secrets.PREPROD_FRONTEND_URL || vars.PREPROD_FRONTEND_URL || 'https://app.preprod.xpeditis.com' }}
run: bash scripts/ci/health-check.sh "${BASE_URL%/}/api/health"
- name: Mark successfully deployed preprod images
env:
BACKEND_DIGEST: ${{ needs.build-backend.outputs.digest }}
LOG_EXPORTER_DIGEST: ${{ needs.build-log-exporter.outputs.digest }}
run: |
docker buildx imagetools create \
--tag "$REGISTRY/xpeditis-backend:validated-preprod-$GITHUB_SHA" \
"$REGISTRY/xpeditis-backend@$BACKEND_DIGEST"
docker buildx imagetools create \
--tag "$REGISTRY/xpeditis-log-exporter:validated-preprod-$GITHUB_SHA" \
"$REGISTRY/xpeditis-log-exporter@$LOG_EXPORTER_DIGEST"
# ── Notifications ────────────────────────────────────────────────────
notify-success:
name: Notify Success
runs-on: ubuntu-latest
needs: [build-backend, build-frontend, deploy]
if: success()
steps:
- run: |
curl -s -H "Content-Type: application/json" -d '{
"embeds": [{
"title": "✅ Preprod Deployed & Healthy",
"color": 3066993,
"fields": [
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
{"name": "SHA", "value": "`${{ needs.build-backend.outputs.sha }}`", "inline": true},
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
],
"footer": {"text": "Xpeditis CI/CD • Preprod"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
notify-failure:
name: Notify Failure
runs-on: ubuntu-latest
needs: [security, backend-quality, frontend-quality, backend-tests, frontend-tests, integration-tests, build-backend, build-frontend, build-log-exporter, image-security, deploy]
# Security gate failures are already reported by the security job itself.
if: failure() && needs.security.result != 'failure'
steps:
- run: |
curl -s -H "Content-Type: application/json" -d '{
"embeds": [{
"title": "❌ Preprod Pipeline Failed",
"description": "Pipeline en échec. Vérifiez les rapports et l état réel des services avant de relancer.",
"color": 15158332,
"fields": [
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
],
"footer": {"text": "Xpeditis CI/CD • Preprod"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}

View File

@ -1,131 +0,0 @@
name: Dev CI
on:
push:
branches: [dev]
pull_request:
branches: [dev]
jobs:
security:
name: Security gate
runs-on: ubuntu-latest
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- name: Install Trivy
shell: bash
run: |
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
"$trivy_bin" --version
- name: Validate workflows and deployment checks
shell: bash
run: |
actionlint_bin=$(bash scripts/ci/install-tool.sh actionlint)
ACTIONLINT_BIN="$actionlint_bin" bash scripts/ci/validate-workflows.sh
- name: Audit dependencies, secrets and infrastructure
shell: bash
run: bash scripts/ci/security-audit.sh
- name: Show security results
if: always()
shell: bash
run: python3 scripts/ci/summarize-security.py
- name: Save security reports on Gitea
if: always()
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
with:
name: security-reports
path: ${{ runner.temp }}/security-reports/*.json
retention-days: 7
if-no-files-found: error
- name: Notify Discord
if: failure()
uses: ./.gitea/actions/notify-security-failure
with:
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
pipeline: Dev
backend-quality:
name: Backend — Lint
runs-on: ubuntu-latest
needs: security
defaults:
run:
working-directory: apps/backend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm run lint -- --no-fix
frontend-quality:
name: Frontend — Lint & Type-check
runs-on: ubuntu-latest
needs: security
defaults:
run:
working-directory: apps/frontend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm run lint
- run: npm run type-check
backend-tests:
name: Backend — Unit Tests
runs-on: ubuntu-latest
needs: backend-quality
defaults:
run:
working-directory: apps/backend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm test -- --ci --runInBand
frontend-tests:
name: Frontend — Unit Tests
runs-on: ubuntu-latest
needs: frontend-quality
defaults:
run:
working-directory: apps/frontend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm test -- --ci --runInBand
notify-failure:
name: Notify Failure
runs-on: ubuntu-latest
needs: [security, backend-quality, frontend-quality, backend-tests, frontend-tests]
# Security gate failures are already reported by the security job itself.
if: failure() && needs.security.result != 'failure'
steps:
- name: Discord
run: |
curl -s -H "Content-Type: application/json" -d '{
"embeds": [{
"title": "❌ Dev CI Failed",
"color": 15158332,
"fields": [
{"name": "Branch", "value": "`${{ github.ref_name }}`", "inline": true},
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
],
"footer": {"text": "Xpeditis CI • Dev"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}

View File

@ -1,169 +0,0 @@
name: PR Checks
# Required status checks — configure these in branch protection rules.
# PRs to preprod : lint + type-check + unit tests + integration tests
# PRs to main : same checks, including integration and security
on:
pull_request:
branches: [preprod, main]
jobs:
security:
name: Security gate
runs-on: ubuntu-latest
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- name: Install Trivy
shell: bash
run: |
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
"$trivy_bin" --version
- name: Validate workflows and deployment checks
shell: bash
run: |
actionlint_bin=$(bash scripts/ci/install-tool.sh actionlint)
ACTIONLINT_BIN="$actionlint_bin" bash scripts/ci/validate-workflows.sh
- name: Audit dependencies, secrets and infrastructure
shell: bash
run: bash scripts/ci/security-audit.sh
- name: Show security results
if: always()
shell: bash
run: python3 scripts/ci/summarize-security.py
- name: Save security reports on Gitea
if: always()
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
with:
name: security-reports
path: ${{ runner.temp }}/security-reports/*.json
retention-days: 7
if-no-files-found: error
- name: Notify Discord
if: failure()
uses: ./.gitea/actions/notify-security-failure
with:
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
pipeline: PR Checks
backend-quality:
name: Backend — Lint
runs-on: ubuntu-latest
needs: security
defaults:
run:
working-directory: apps/backend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm run lint -- --no-fix
frontend-quality:
name: Frontend — Lint & Type-check
runs-on: ubuntu-latest
needs: security
defaults:
run:
working-directory: apps/frontend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm run lint
- run: npm run type-check
backend-tests:
name: Backend — Unit Tests
runs-on: ubuntu-latest
needs: backend-quality
defaults:
run:
working-directory: apps/backend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm test -- --ci --runInBand
frontend-tests:
name: Frontend — Unit Tests
runs-on: ubuntu-latest
needs: frontend-quality
defaults:
run:
working-directory: apps/frontend
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- run: npm test -- --ci --runInBand
# Integration tests validate the actual merge candidate for both branches.
integration-tests:
name: Backend — Integration Tests
runs-on: ubuntu-latest
needs: backend-tests
defaults:
run:
working-directory: apps/backend
services:
postgres:
image: postgres:15-alpine
env:
POSTGRES_USER: xpeditis_test
POSTGRES_PASSWORD: xpeditis_test_password
POSTGRES_DB: xpeditis_test
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 10
redis:
image: redis:7-alpine
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 5s
--health-retries 10
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: ./.gitea/actions/setup-node
- run: npm ci --legacy-peer-deps
- name: Run integration tests
env:
NODE_ENV: test
TEST_DB_HOST: postgres
TEST_DB_PORT: 5432
TEST_DB_USER: xpeditis_test
TEST_DB_PASSWORD: xpeditis_test_password
TEST_DB_NAME: xpeditis_test
DATABASE_HOST: postgres
DATABASE_PORT: 5432
DATABASE_USER: xpeditis_test
DATABASE_PASSWORD: xpeditis_test_password
DATABASE_NAME: xpeditis_test
DATABASE_SYNCHRONIZE: 'false'
REDIS_HOST: redis
REDIS_PORT: 6379
REDIS_PASSWORD: ''
JWT_SECRET: test-secret-key-ci
SMTP_HOST: localhost
SMTP_PORT: 1025
SMTP_FROM: test@xpeditis.com
run: npm run test:integration -- --ci --runInBand

276
.github/workflows/cd-main.yml vendored Normal file
View File

@ -0,0 +1,276 @@
name: CD Production
# Production pipeline — Hetzner k3s.
#
# SECURITY: Two mandatory gates before any production deployment:
# 1. quality-gate — lint + unit tests on the exact commit being deployed
# 2. verify-image — confirms preprod-SHA image EXISTS in registry,
# which proves this commit passed the full preprod
# pipeline (lint + unit + integration + docker build).
# If someone merges to main without going through preprod,
# this step fails and the deployment is blocked.
#
# Flow: quality-gate → verify-image → promote → deploy → notify
#
# Secrets required:
# REGISTRY_TOKEN — Scaleway registry (read/write)
# HETZNER_KUBECONFIG — base64: cat ~/.kube/kubeconfig-xpeditis-prod | base64 -w 0
# PROD_BACKEND_URL — https://api.xpeditis.com
# PROD_FRONTEND_URL — https://app.xpeditis.com
# DISCORD_WEBHOOK_URL
on:
push:
branches: [main]
concurrency:
group: cd-production
cancel-in-progress: false
env:
REGISTRY: rg.fr-par.scw.cloud/weworkstudio
NODE_VERSION: '20'
K8S_NAMESPACE: xpeditis-prod
jobs:
# ── 1. Quality Gate ──────────────────────────────────────────────────
# Runs on every prod deployment regardless of what happened in preprod.
backend-quality:
name: Backend — Lint
runs-on: ubuntu-latest
defaults:
run:
working-directory: apps/backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/backend/package-lock.json
- run: npm install --legacy-peer-deps
- run: npm run lint
frontend-quality:
name: Frontend — Lint & Type-check
runs-on: ubuntu-latest
defaults:
run:
working-directory: apps/frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/frontend/package-lock.json
- run: npm ci --legacy-peer-deps
- run: npm run lint
- run: npm run type-check
backend-tests:
name: Backend — Unit Tests
runs-on: ubuntu-latest
needs: backend-quality
defaults:
run:
working-directory: apps/backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/backend/package-lock.json
- run: npm install --legacy-peer-deps
- run: npm test -- --passWithNoTests
frontend-tests:
name: Frontend — Unit Tests
runs-on: ubuntu-latest
needs: frontend-quality
defaults:
run:
working-directory: apps/frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/frontend/package-lock.json
- run: npm ci --legacy-peer-deps
- run: npm test -- --passWithNoTests
# ── 2. Image Verification ────────────────────────────────────────────
# Checks that preprod-SHA tags exist for this EXACT commit.
# This is the security gate: if the preprod pipeline never ran for this
# commit (or failed before the docker build step), this job fails and
# the deployment is fully blocked.
verify-image:
name: Verify Preprod Image Exists
runs-on: ubuntu-latest
needs: [backend-tests, frontend-tests]
outputs:
sha: ${{ steps.sha.outputs.short }}
steps:
- name: Short SHA
id: sha
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Check backend image preprod-SHA
run: |
TAG="${{ env.REGISTRY }}/xpeditis-backend:preprod-${{ steps.sha.outputs.short }}"
echo "Verifying: $TAG"
docker buildx imagetools inspect "$TAG" || {
echo ""
echo "BLOCKED: Image $TAG not found in registry."
echo "This commit was not built by the preprod pipeline."
echo "Merge to preprod first and wait for the full pipeline to succeed."
exit 1
}
- name: Check frontend image preprod-SHA
run: |
TAG="${{ env.REGISTRY }}/xpeditis-frontend:preprod-${{ steps.sha.outputs.short }}"
echo "Verifying: $TAG"
docker buildx imagetools inspect "$TAG" || {
echo ""
echo "BLOCKED: Image $TAG not found in registry."
echo "This commit was not built by the preprod pipeline."
echo "Merge to preprod first and wait for the full pipeline to succeed."
exit 1
}
# ── 3. Promote Images ────────────────────────────────────────────────
# Re-tags preprod-SHA → latest + prod-SHA within Scaleway.
# No rebuild. No layer transfer. Manifest-level operation only.
promote-images:
name: Promote Images (preprod-SHA → prod)
runs-on: ubuntu-latest
needs: verify-image
steps:
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Promote backend
run: |
SHA="${{ needs.verify-image.outputs.sha }}"
docker buildx imagetools create \
--tag ${{ env.REGISTRY }}/xpeditis-backend:latest \
--tag ${{ env.REGISTRY }}/xpeditis-backend:prod-${SHA} \
${{ env.REGISTRY }}/xpeditis-backend:preprod-${SHA}
echo "Backend promoted: preprod-${SHA} → latest + prod-${SHA}"
- name: Promote frontend
run: |
SHA="${{ needs.verify-image.outputs.sha }}"
docker buildx imagetools create \
--tag ${{ env.REGISTRY }}/xpeditis-frontend:latest \
--tag ${{ env.REGISTRY }}/xpeditis-frontend:prod-${SHA} \
${{ env.REGISTRY }}/xpeditis-frontend:preprod-${SHA}
echo "Frontend promoted: preprod-${SHA} → latest + prod-${SHA}"
# ── 4. Deploy to k3s ─────────────────────────────────────────────────
deploy:
name: Deploy to Production (k3s)
runs-on: ubuntu-latest
needs: [verify-image, promote-images]
environment:
name: production
url: https://app.xpeditis.com
steps:
- name: Configure kubectl
run: |
mkdir -p ~/.kube
echo "${{ secrets.HETZNER_KUBECONFIG }}" | base64 -d > ~/.kube/config
chmod 600 ~/.kube/config
kubectl cluster-info
kubectl get nodes -o wide
- name: Deploy backend
id: deploy-backend
run: |
SHA="${{ needs.verify-image.outputs.sha }}"
IMAGE="${{ env.REGISTRY }}/xpeditis-backend:prod-${SHA}"
echo "Deploying: $IMAGE"
kubectl set image deployment/xpeditis-backend backend="$IMAGE" -n ${{ env.K8S_NAMESPACE }}
kubectl rollout status deployment/xpeditis-backend -n ${{ env.K8S_NAMESPACE }} --timeout=300s
echo "Backend rollout complete."
- name: Deploy frontend
id: deploy-frontend
run: |
SHA="${{ needs.verify-image.outputs.sha }}"
IMAGE="${{ env.REGISTRY }}/xpeditis-frontend:prod-${SHA}"
echo "Deploying: $IMAGE"
kubectl set image deployment/xpeditis-frontend frontend="$IMAGE" -n ${{ env.K8S_NAMESPACE }}
kubectl rollout status deployment/xpeditis-frontend -n ${{ env.K8S_NAMESPACE }} --timeout=300s
echo "Frontend rollout complete."
- name: Auto-rollback on deployment failure
if: failure()
run: |
echo "Deployment failed — initiating rollback..."
kubectl rollout undo deployment/xpeditis-backend -n ${{ env.K8S_NAMESPACE }}
kubectl rollout undo deployment/xpeditis-frontend -n ${{ env.K8S_NAMESPACE }}
kubectl rollout status deployment/xpeditis-backend -n ${{ env.K8S_NAMESPACE }} --timeout=120s
kubectl rollout status deployment/xpeditis-frontend -n ${{ env.K8S_NAMESPACE }} --timeout=120s
echo "Rollback complete. Previous version is live."
# ── Notifications ────────────────────────────────────────────────────
notify-success:
name: Notify Success
runs-on: ubuntu-latest
needs: [verify-image, deploy]
if: success()
steps:
- run: |
curl -s -H "Content-Type: application/json" -d '{
"embeds": [{
"title": "🚀 Production Deployed & Healthy",
"color": 3066993,
"fields": [
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
{"name": "Version", "value": "`prod-${{ needs.verify-image.outputs.sha }}`", "inline": true},
{"name": "Cluster", "value": "Hetzner k3s — `xpeditis-prod`", "inline": false},
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
],
"footer": {"text": "Xpeditis CI/CD • Production"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
notify-failure:
name: Notify Failure
runs-on: ubuntu-latest
needs: [backend-quality, frontend-quality, backend-tests, frontend-tests, verify-image, promote-images, deploy]
if: failure()
steps:
- run: |
curl -s -H "Content-Type: application/json" -d '{
"content": "@here PRODUCTION PIPELINE FAILED",
"embeds": [{
"title": "🔴 Production Pipeline Failed",
"description": "Check the workflow for details. Auto-rollback was triggered if the failure was during deploy.",
"color": 15158332,
"fields": [
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false},
{"name": "Rollback", "value": "[Run rollback workflow](${{ github.server_url }}/${{ github.repository }}/actions/workflows/rollback.yml)", "inline": false}
],
"footer": {"text": "Xpeditis CI/CD • Production"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}

316
.github/workflows/cd-preprod.yml vendored Normal file
View File

@ -0,0 +1,316 @@
name: CD Preprod
# Full pipeline triggered on every push to preprod.
# Flow: lint → unit tests → integration tests → docker build → deploy → notify
#
# Secrets required:
# REGISTRY_TOKEN — Scaleway registry (read/write)
# NEXT_PUBLIC_API_URL — https://api.preprod.xpeditis.com
# NEXT_PUBLIC_APP_URL — https://preprod.xpeditis.com
# PORTAINER_WEBHOOK_BACKEND — Portainer webhook (preprod backend)
# PORTAINER_WEBHOOK_FRONTEND— Portainer webhook (preprod frontend)
# PREPROD_BACKEND_URL — https://api.preprod.xpeditis.com
# PREPROD_FRONTEND_URL — https://preprod.xpeditis.com
# DISCORD_WEBHOOK_URL
on:
push:
branches: [preprod]
concurrency:
group: cd-preprod
cancel-in-progress: false
env:
REGISTRY: rg.fr-par.scw.cloud/weworkstudio
NODE_VERSION: '20'
jobs:
# ── 1. Lint ─────────────────────────────────────────────────────────
backend-quality:
name: Backend — Lint
runs-on: ubuntu-latest
defaults:
run:
working-directory: apps/backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/backend/package-lock.json
- run: npm install --legacy-peer-deps
- run: npm run lint
frontend-quality:
name: Frontend — Lint & Type-check
runs-on: ubuntu-latest
defaults:
run:
working-directory: apps/frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/frontend/package-lock.json
- run: npm ci --legacy-peer-deps
- run: npm run lint
- run: npm run type-check
# ── 2. Unit Tests ────────────────────────────────────────────────────
backend-tests:
name: Backend — Unit Tests
runs-on: ubuntu-latest
needs: backend-quality
defaults:
run:
working-directory: apps/backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/backend/package-lock.json
- run: npm install --legacy-peer-deps
- run: npm test -- --passWithNoTests
frontend-tests:
name: Frontend — Unit Tests
runs-on: ubuntu-latest
needs: frontend-quality
defaults:
run:
working-directory: apps/frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/frontend/package-lock.json
- run: npm ci --legacy-peer-deps
- run: npm test -- --passWithNoTests
# ── 3. Integration Tests ─────────────────────────────────────────────
integration-tests:
name: Backend — Integration Tests
runs-on: ubuntu-latest
needs: [backend-tests, frontend-tests]
defaults:
run:
working-directory: apps/backend
services:
postgres:
image: postgres:15-alpine
env:
POSTGRES_USER: xpeditis_test
POSTGRES_PASSWORD: xpeditis_test_password
POSTGRES_DB: xpeditis_test
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 10
ports:
- 5432:5432
redis:
image: redis:7-alpine
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 5s
--health-retries 10
ports:
- 6379:6379
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/backend/package-lock.json
- run: npm install --legacy-peer-deps
- name: Run integration tests
env:
NODE_ENV: test
DATABASE_HOST: localhost
DATABASE_PORT: 5432
DATABASE_USER: xpeditis_test
DATABASE_PASSWORD: xpeditis_test_password
DATABASE_NAME: xpeditis_test
DATABASE_SYNCHRONIZE: 'false'
REDIS_HOST: localhost
REDIS_PORT: 6379
REDIS_PASSWORD: ''
JWT_SECRET: test-secret-key-ci
SMTP_HOST: localhost
SMTP_PORT: 1025
SMTP_FROM: test@xpeditis.com
run: npm run test:integration -- --passWithNoTests
# ── 4. Docker Build & Push ───────────────────────────────────────────
# Tags: preprod (latest for this env) + preprod-SHA (used by prod for exact promotion)
build-backend:
name: Build Backend
runs-on: ubuntu-latest
needs: integration-tests
outputs:
sha: ${{ steps.sha.outputs.short }}
steps:
- uses: actions/checkout@v4
- name: Short SHA
id: sha
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- uses: docker/build-push-action@v5
with:
context: ./apps/backend
file: ./apps/backend/Dockerfile
push: true
tags: |
${{ env.REGISTRY }}/xpeditis-backend:preprod
${{ env.REGISTRY }}/xpeditis-backend:preprod-${{ steps.sha.outputs.short }}
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-backend:buildcache
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-backend:buildcache,mode=max
platforms: linux/amd64,linux/arm64
build-frontend:
name: Build Frontend
runs-on: ubuntu-latest
needs: integration-tests
outputs:
sha: ${{ steps.sha.outputs.short }}
steps:
- uses: actions/checkout@v4
- name: Short SHA
id: sha
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- uses: docker/build-push-action@v5
with:
context: ./apps/frontend
file: ./apps/frontend/Dockerfile
push: true
tags: |
${{ env.REGISTRY }}/xpeditis-frontend:preprod
${{ env.REGISTRY }}/xpeditis-frontend:preprod-${{ steps.sha.outputs.short }}
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache,mode=max
platforms: linux/amd64,linux/arm64
build-args: |
NEXT_PUBLIC_API_URL=${{ secrets.NEXT_PUBLIC_API_URL }}
NEXT_PUBLIC_APP_URL=${{ secrets.NEXT_PUBLIC_APP_URL }}
build-log-exporter:
name: Build Log Exporter
runs-on: ubuntu-latest
needs: integration-tests
outputs:
sha: ${{ steps.sha.outputs.short }}
steps:
- uses: actions/checkout@v4
- name: Short SHA
id: sha
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- uses: docker/build-push-action@v5
with:
context: ./apps/log-exporter
file: ./apps/log-exporter/Dockerfile
push: true
tags: |
${{ env.REGISTRY }}/xpeditis-log-exporter:preprod
${{ env.REGISTRY }}/xpeditis-log-exporter:preprod-${{ steps.sha.outputs.short }}
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-log-exporter:buildcache
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-log-exporter:buildcache,mode=max
platforms: linux/amd64,linux/arm64
# ── 5. Deploy via Portainer ──────────────────────────────────────────
deploy:
name: Deploy to Preprod
runs-on: ubuntu-latest
needs: [build-backend, build-frontend, build-log-exporter]
environment: preprod
steps:
- name: Deploy backend
run: |
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X POST "${{ secrets.PORTAINER_WEBHOOK_BACKEND }}")
echo "Portainer response: HTTP $HTTP_CODE"
if [[ "$HTTP_CODE" != "2"* ]]; then
echo "ERROR: Portainer webhook failed with HTTP $HTTP_CODE"
exit 1
fi
echo "Backend webhook triggered."
- name: Wait for backend startup
run: sleep 20
- name: Deploy frontend
run: |
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X POST "${{ secrets.PORTAINER_WEBHOOK_FRONTEND }}")
echo "Portainer response: HTTP $HTTP_CODE"
if [[ "$HTTP_CODE" != "2"* ]]; then
echo "ERROR: Portainer webhook failed with HTTP $HTTP_CODE"
exit 1
fi
echo "Frontend webhook triggered."
# ── Notifications ────────────────────────────────────────────────────
notify-success:
name: Notify Success
runs-on: ubuntu-latest
needs: [build-backend, build-frontend, deploy]
if: success()
steps:
- run: |
curl -s -H "Content-Type: application/json" -d '{
"embeds": [{
"title": "✅ Preprod Deployed & Healthy",
"color": 3066993,
"fields": [
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
{"name": "SHA", "value": "`${{ needs.build-backend.outputs.sha }}`", "inline": true},
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
],
"footer": {"text": "Xpeditis CI/CD • Preprod"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
notify-failure:
name: Notify Failure
runs-on: ubuntu-latest
needs: [backend-quality, frontend-quality, backend-tests, frontend-tests, integration-tests, build-backend, build-frontend, deploy]
if: failure()
steps:
- run: |
curl -s -H "Content-Type: application/json" -d '{
"embeds": [{
"title": "❌ Preprod Pipeline Failed",
"description": "Preprod was NOT deployed.",
"color": 15158332,
"fields": [
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
],
"footer": {"text": "Xpeditis CI/CD • Preprod"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}

103
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,103 @@
name: Dev CI
on:
push:
branches: [dev]
pull_request:
branches: [dev]
concurrency:
group: dev-ci-${{ github.ref }}
cancel-in-progress: true
env:
NODE_VERSION: '20'
jobs:
backend-quality:
name: Backend — Lint
runs-on: ubuntu-latest
defaults:
run:
working-directory: apps/backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/backend/package-lock.json
- run: npm install --legacy-peer-deps
- run: npm run lint
frontend-quality:
name: Frontend — Lint & Type-check
runs-on: ubuntu-latest
defaults:
run:
working-directory: apps/frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/frontend/package-lock.json
- run: npm ci --legacy-peer-deps
- run: npm run lint
- run: npm run type-check
backend-tests:
name: Backend — Unit Tests
runs-on: ubuntu-latest
needs: backend-quality
defaults:
run:
working-directory: apps/backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/backend/package-lock.json
- run: npm install --legacy-peer-deps
- run: npm test -- --passWithNoTests
frontend-tests:
name: Frontend — Unit Tests
runs-on: ubuntu-latest
needs: frontend-quality
defaults:
run:
working-directory: apps/frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/frontend/package-lock.json
- run: npm ci --legacy-peer-deps
- run: npm test -- --passWithNoTests
notify-failure:
name: Notify Failure
runs-on: ubuntu-latest
needs: [backend-quality, frontend-quality, backend-tests, frontend-tests]
if: failure()
steps:
- name: Discord
run: |
curl -s -H "Content-Type: application/json" -d '{
"embeds": [{
"title": "❌ Dev CI Failed",
"color": 15158332,
"fields": [
{"name": "Branch", "value": "`${{ github.ref_name }}`", "inline": true},
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
],
"footer": {"text": "Xpeditis CI • Dev"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}

145
.github/workflows/pr-checks.yml vendored Normal file
View File

@ -0,0 +1,145 @@
name: PR Checks
# Required status checks — configure these in branch protection rules.
# PRs to preprod : lint + type-check + unit tests + integration tests
# PRs to main : lint + type-check + unit tests only
on:
pull_request:
branches: [preprod, main]
concurrency:
group: pr-${{ github.event.pull_request.number }}
cancel-in-progress: true
env:
NODE_VERSION: '20'
jobs:
backend-quality:
name: Backend — Lint
runs-on: ubuntu-latest
defaults:
run:
working-directory: apps/backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/backend/package-lock.json
- run: npm install --legacy-peer-deps
- run: npm run lint
frontend-quality:
name: Frontend — Lint & Type-check
runs-on: ubuntu-latest
defaults:
run:
working-directory: apps/frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/frontend/package-lock.json
- run: npm ci --legacy-peer-deps
- run: npm run lint
- run: npm run type-check
backend-tests:
name: Backend — Unit Tests
runs-on: ubuntu-latest
needs: backend-quality
defaults:
run:
working-directory: apps/backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/backend/package-lock.json
- run: npm install --legacy-peer-deps
- run: npm test -- --passWithNoTests
frontend-tests:
name: Frontend — Unit Tests
runs-on: ubuntu-latest
needs: frontend-quality
defaults:
run:
working-directory: apps/frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/frontend/package-lock.json
- run: npm ci --legacy-peer-deps
- run: npm test -- --passWithNoTests
# Integration tests — PRs to preprod only
# Code going to main was already integration-tested when it passed through preprod
integration-tests:
name: Backend — Integration Tests
runs-on: ubuntu-latest
needs: backend-tests
if: github.base_ref == 'preprod'
defaults:
run:
working-directory: apps/backend
services:
postgres:
image: postgres:15-alpine
env:
POSTGRES_USER: xpeditis_test
POSTGRES_PASSWORD: xpeditis_test_password
POSTGRES_DB: xpeditis_test
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 10
ports:
- 5432:5432
redis:
image: redis:7-alpine
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 5s
--health-retries 10
ports:
- 6379:6379
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
cache-dependency-path: apps/backend/package-lock.json
- run: npm install --legacy-peer-deps
- name: Run integration tests
env:
NODE_ENV: test
DATABASE_HOST: localhost
DATABASE_PORT: 5432
DATABASE_USER: xpeditis_test
DATABASE_PASSWORD: xpeditis_test_password
DATABASE_NAME: xpeditis_test
DATABASE_SYNCHRONIZE: 'false'
REDIS_HOST: localhost
REDIS_PORT: 6379
REDIS_PASSWORD: ''
JWT_SECRET: test-secret-key-ci
SMTP_HOST: localhost
SMTP_PORT: 1025
SMTP_FROM: test@xpeditis.com
run: npm run test:integration -- --passWithNoTests

View File

@ -126,7 +126,7 @@ jobs:
docker buildx imagetools inspect "$BACKEND" || { echo "ERROR: $BACKEND not found"; exit 1; }
docker buildx imagetools inspect "$FRONTEND" || { echo "ERROR: $FRONTEND not found"; exit 1; }
kubectl set image deployment/xpeditis-backend backend="$BACKEND" seed-rates="$BACKEND" -n ${{ env.K8S_NAMESPACE }}
kubectl set image deployment/xpeditis-backend backend="$BACKEND" -n ${{ env.K8S_NAMESPACE }}
kubectl rollout status deployment/xpeditis-backend -n ${{ env.K8S_NAMESPACE }} --timeout=180s
kubectl set image deployment/xpeditis-frontend frontend="$FRONTEND" -n ${{ env.K8S_NAMESPACE }}

1
.gitignore vendored
View File

@ -46,7 +46,6 @@ lerna-debug.log*
docker-compose.override.yml
stack-portainer.yaml
tmp.stack-portainer.yaml
stack-portainer-preprod.yaml
# Uploads
uploads/

View File

@ -1,22 +0,0 @@
# Approved monitoring exceptions, reviewed 2026-09-24. No dependency/secret exclusions.
misconfigurations:
- id: AVD-KSV-0047
paths: [infra/prod/k8s/monitoring/03-prometheus.yaml]
expired_at: 2026-10-24
statement: Prometheus scrapes kubelet cAdvisor through the API server node proxy; retain until direct authenticated kubelet scraping is validated.
- id: AVD-KSV-0009
paths: [infra/prod/k8s/monitoring/04-node-exporter.yaml]
expired_at: 2026-10-24
statement: Node exporter observes host network metrics; isolated to the monitoring DaemonSet.
- id: AVD-KSV-0010
paths: [infra/prod/k8s/monitoring/04-node-exporter.yaml]
expired_at: 2026-10-24
statement: Node exporter observes host processes; runs as non-root with all capabilities dropped.
- id: AVD-KSV-0024
paths: [infra/prod/k8s/monitoring/04-node-exporter.yaml]
expired_at: 2026-10-24
statement: Existing host-network exporter listens on port 9101; access remains constrained by infrastructure firewall rules.
- id: AVD-KSV-0121
paths: [infra/prod/k8s/monitoring/04-node-exporter.yaml]
expired_at: 2026-10-24
statement: Host proc/sys/root mounts provide disk and system metrics and are read-only; required for disk-full alerts.

277
AGENTS.md
View File

@ -1,277 +0,0 @@
# AGENTS.md
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
## Project Overview
**Xpeditis** is a B2B SaaS maritime freight booking platform. Freight forwarders search and compare real-time shipping rates, book containers, and manage shipments. Monorepo with NestJS 10 backend (Hexagonal Architecture) and Next.js 14 frontend.
## Development Commands
All commands run from repo root unless noted otherwise.
```bash
# Infrastructure (PostgreSQL 15 + Redis 7 + MinIO)
docker-compose up -d
# Install all dependencies
npm run install:all
# Environment setup (required on first run)
cp apps/backend/.env.example apps/backend/.env
cp apps/frontend/.env.example apps/frontend/.env
# Database migrations (from apps/backend/)
cd apps/backend && npm run migration:run
# Development servers
npm run backend:dev # http://localhost:4000, Swagger: /api/docs
npm run frontend:dev # http://localhost:3000
```
### Testing
```bash
# Backend (from apps/backend/)
npm test # Unit tests (Jest)
npm test -- booking.entity.spec.ts # Single file
npm test -- --testNamePattern="should create" # Filter by test name
npm run test:cov # With coverage
npm run test:integration # Integration tests (needs DB/Redis, 30s timeout)
npm run test:e2e # E2E tests
# Frontend (from apps/frontend/)
npm test
npm run test:e2e # Playwright (chromium, firefox, webkit + mobile)
# From root
npm run backend:test
npm run frontend:test
```
Backend test config is in `apps/backend/package.json` (Jest). Integration test config: `apps/backend/jest-integration.json` (covers infrastructure layer, setup in `test/setup-integration.ts`). Frontend E2E config: `apps/frontend/playwright.config.ts`.
### Linting, Formatting & Type Checking
```bash
npm run backend:lint # ESLint backend
npm run frontend:lint # ESLint frontend
npm run format # Prettier (all files)
npm run format:check # Check formatting
# From apps/frontend/
npm run type-check # TypeScript checking (frontend only)
```
### Database Migrations
```bash
cd apps/backend
npm run migration:generate -- src/infrastructure/persistence/typeorm/migrations/MigrationName
npm run migration:run
npm run migration:revert
```
### Build
```bash
npm run backend:build # NestJS build with tsc-alias for path resolution
npm run frontend:build # Next.js production build (standalone output)
npm run clean # Remove all node_modules, dist, .next directories
```
## Local Infrastructure
Docker-compose defaults (no `.env` changes needed for local dev):
- **PostgreSQL**: `xpeditis:xpeditis_dev_password@localhost:5432/xpeditis_dev`
- **Redis**: password `xpeditis_redis_password`, port 6379
- **MinIO** (S3-compatible storage): `minioadmin:minioadmin`, API port 9000, console port 9001
Frontend env var: `NEXT_PUBLIC_API_URL` (defaults to `http://localhost:4000`) — configured in `next.config.js`.
## Architecture
### Hexagonal Architecture (Backend)
```
apps/backend/src/
├── domain/ # CORE - Pure TypeScript, NO framework imports
│ ├── entities/ # Booking, RateQuote, Carrier, Port, Container, Notification, Webhook,
│ │ # AuditLog, User, Organization, Subscription, License, CsvBooking,
│ │ # CsvRate, InvitationToken
│ ├── value-objects/ # Money, Email, BookingNumber, BookingStatus, PortCode, ContainerType,
│ │ # Volume, DateRange, Surcharge
│ ├── services/ # Pure domain services (csv-rate-price-calculator)
│ ├── ports/
│ │ ├── in/ # Use case interfaces with execute() method
│ │ └── out/ # Repository/SPI interfaces (token constants like BOOKING_REPOSITORY = 'BookingRepository')
│ └── exceptions/ # Domain-specific exceptions
├── application/ # Controllers, DTOs (class-validator), Guards, Decorators, Mappers
│ ├── [feature]/ # Feature modules: auth/, bookings/, csv-bookings, rates/, ports/,
│ │ # organizations/, users/, dashboard/, audit/, notifications/, webhooks/,
│ │ # gdpr/, admin/, subscriptions/
│ ├── controllers/ # REST controllers (also nested under feature folders)
│ ├── services/ # Application services: audit, notification, webhook,
│ │ # booking-automation, export, fuzzy-search, brute-force-protection
│ ├── gateways/ # WebSocket gateways (notifications.gateway.ts via Socket.IO)
│ ├── guards/ # JwtAuthGuard, RolesGuard, CustomThrottlerGuard
│ ├── decorators/ # @Public(), @Roles(), @CurrentUser()
│ ├── dto/ # Request/response DTOs with class-validator
│ ├── mappers/ # Domain ↔ DTO mappers
│ └── interceptors/ # PerformanceMonitoringInterceptor
└── infrastructure/ # TypeORM entities/repos/mappers, Redis cache, carrier APIs,
# MinIO/S3, email (MJML+Nodemailer), Stripe, Sentry,
# Pappers (French SIRET registry), PDF generation
```
**Critical dependency rules**:
- Domain layer: zero imports from NestJS, TypeORM, Redis, or any framework
- Dependencies flow inward only: Infrastructure → Application → Domain
- Path aliases: `@domain/*`, `@application/*`, `@infrastructure/*` (defined in `apps/backend/tsconfig.json`)
- Domain tests run without NestJS TestingModule
- Backend has strict TypeScript: `strict: true`, `strictNullChecks: true` (but `strictPropertyInitialization: false`)
- Env vars validated at startup via Joi schema in `app.module.ts` — required vars include DATABASE_*, REDIS_*, JWT_SECRET, SMTP_*
### NestJS Modules (app.module.ts)
Global guards: JwtAuthGuard (all routes protected by default), CustomThrottlerGuard.
Feature modules: Auth, Rates, Ports, Bookings, CsvBookings, Organizations, Users, Dashboard, Audit, Notifications, Webhooks, GDPR, Admin, Subscriptions.
Infrastructure modules: CacheModule, CarrierModule, SecurityModule, CsvRateModule, StripeModule, PdfModule, StorageModule, EmailModule.
Swagger plugin enabled in `nest-cli.json` — DTOs auto-documented. Logging via `nestjs-pino` (pino-pretty in dev).
### Frontend (Next.js 14 App Router)
```
apps/frontend/
├── app/ # App Router pages (root-level)
│ ├── dashboard/ # Protected routes (bookings, admin, settings, wiki, search)
│ ├── carrier/ # Carrier portal (magic link auth — accept/reject/documents)
│ ├── booking/ # Booking confirmation/rejection flows
│ └── [auth pages] # login, register, forgot-password, verify-email
└── src/
├── app/ # Additional app pages (e.g. rates/csv-search)
├── components/ # React components (ui/, layout/, bookings/, admin/, rate-search/, organization/)
├── hooks/ # useBookings, useNotifications, useCsvRateSearch, useCompanies, useFilterOptions
├── lib/
│ ├── api/ # Fetch-based API client with auto token refresh (client.ts + per-module files)
│ ├── context/ # Auth context, cookie context
│ ├── providers/ # QueryProvider (TanStack Query / React Query)
│ └── fonts.ts # Manrope (headings) + Montserrat (body)
├── types/ # TypeScript type definitions
├── utils/ # Export utilities (Excel, PDF)
└── legacy-pages/ # Archived page components (BookingsManagement, CarrierManagement, CarrierMonitoring)
```
Path aliases: `@/*` → `./src/*`, `@/components/*`, `@/lib/*`, `@/app/*` → `./app/*`, `@/types/*`, `@/hooks/*`, `@/utils/*`
**Note**: Frontend tsconfig has `strict: false`, `noImplicitAny: false`, `strictNullChecks: false` (unlike backend which is strict). Uses TanStack Query (React Query) for server state — wrap new data fetching in hooks, not bare `fetch` calls.
### Brand Design
Colors: Navy `#10183A` (primary), Turquoise `#34CCCD` (accent), Green `#067224` (success), Gray `#F2F2F2`.
Fonts: Manrope (headings), Montserrat (body).
Landing page is in French.
## Key Patterns
### Entity Pattern (Domain)
Private constructor + static `create()` factory. Immutable — mutation methods return new instances. Some entities also have `fromPersistence()` for reconstitution and `toObject()` for serialization.
```typescript
export class Booking {
private readonly props: BookingProps;
static create(props: Omit<BookingProps, 'bookingNumber' | 'status'>): Booking { ... }
updateStatus(newStatus: BookingStatus): Booking { // Returns new instance
return new Booking({ ...this.props, status: newStatus });
}
}
```
### Value Object Pattern
Immutable, self-validating via static `create()`. E.g. `Money` supports USD, EUR, GBP, CNY, JPY with arithmetic and formatting methods.
### Repository Pattern
- Interface in `domain/ports/out/` with token constant (e.g. `BOOKING_REPOSITORY = 'BookingRepository'`)
- Implementation in `infrastructure/persistence/typeorm/repositories/`
- ORM entities: `infrastructure/persistence/typeorm/entities/*.orm-entity.ts`
- Separate mapper classes (`infrastructure/persistence/typeorm/mappers/`) with static `toOrm()`, `toDomain()`, `toDomainMany()` methods
### Frontend API Client
Custom Fetch wrapper in `src/lib/api/client.ts` — exports `get()`, `post()`, `patch()`, `del()`, `upload()`, `download()`. Auto-refreshes JWT on 401. Tokens stored in localStorage **and synced to cookies** (`accessToken` cookie) so Next.js middleware can read them server-side. Per-module files (auth.ts, bookings.ts, rates.ts, etc.) import from client.
### Route Protection (Middleware)
`apps/frontend/middleware.ts` checks the `accessToken` cookie to protect routes. Public paths are defined in two lists:
- `exactPublicPaths`: exact matches (e.g. `/`)
- `prefixPublicPaths`: prefix matches including sub-paths (e.g. `/login`, `/carrier`, `/about`, etc.)
All other routes redirect to `/login?redirect=<pathname>` when the cookie is absent.
### Application Decorators
- `@Public()` — skip JWT auth
- `@Roles()` — role-based access control
- `@CurrentUser()` — inject authenticated user
### API Key Authentication
A second auth mechanism alongside JWT. `ApiKey` domain entity (`domain/entities/api-key.entity.ts`) — keys are hashed with Argon2. `ApiKeyGuard` in `application/guards/` checks the `x-api-key` header. Routes can accept either JWT or API key; see `admin.controller.ts` for examples.
### WebSocket (Real-time Notifications)
Socket.IO gateway at `application/gateways/notifications.gateway.ts`. Clients connect to `/` namespace with a JWT bearer token in the handshake auth. Server emits `notification` events. The frontend `useNotifications` hook handles subscriptions.
### Carrier Connectors
Five carrier connectors (Maersk, MSC, CMA CGM, Hapag-Lloyd, ONE) extending `base-carrier.connector.ts`, each with request/response mappers. Circuit breaker via `opossum` (5s timeout).
### Caching
Redis with 15-min TTL for rate quotes. Key format: `rate:{origin}:{destination}:{containerType}`.
## Business Rules
- Booking number format: `WCM-YYYY-XXXXXX`
- Booking status flow: draft → confirmed → shipped → delivered
- Rate quotes expire after 15 minutes
- Multi-currency: USD, EUR, GBP, CNY, JPY
- RBAC Roles: ADMIN, MANAGER, USER, VIEWER, CARRIER
- JWT: access token 15min, refresh token 7d
- Password hashing: Argon2
- OAuth providers: Google, Microsoft (configured via passport strategies)
- Organizations can be validated via Pappers API (French SIRET/company registry) at `infrastructure/external/pappers-siret.adapter.ts`
### Carrier Portal Workflow
1. Admin creates CSV booking → assigns carrier
2. Email with magic link sent (1-hour expiry)
3. Carrier auto-login → accept/reject booking
4. Activity logged in `carrier_activities` table (via `CarrierProfile` + `CarrierActivity` ORM entities)
## Common Pitfalls
- Never import NestJS/TypeORM in domain layer
- Never use `any` type in backend (strict mode enabled)
- Never modify applied migrations — create new ones
- Always validate DTOs with `class-validator` decorators
- Always create separate mappers for Domain ↔ ORM conversions
- ORM entity files must match pattern `*.orm-entity.{ts,js}` (auto-discovered by data-source)
- Migration files must be in `infrastructure/persistence/typeorm/migrations/`
- Database synchronize is hard-coded to `false` — always use migrations
## Adding a New Feature
1. **Domain Entity** → `domain/entities/*.entity.ts` (pure TS, unit tests)
2. **Value Objects** → `domain/value-objects/*.vo.ts` (immutable)
3. **In Port (Use Case)** → `domain/ports/in/*.use-case.ts` (interface with `execute()`)
4. **Out Port (Repository)** → `domain/ports/out/*.repository.ts` (with token constant)
5. **ORM Entity** → `infrastructure/persistence/typeorm/entities/*.orm-entity.ts`
6. **Migration** → `npm run migration:generate -- src/infrastructure/persistence/typeorm/migrations/MigrationName`
7. **Repository Impl** → `infrastructure/persistence/typeorm/repositories/`
8. **Mapper** → `infrastructure/persistence/typeorm/mappers/` (static toOrm/toDomain/toDomainMany)
9. **DTOs** → `application/dto/` (with class-validator decorators)
10. **Controller** → `application/controllers/` (with Swagger decorators)
11. **Module** → Register repository + use-case providers, import in `app.module.ts`
## Documentation
- API Docs: http://localhost:4000/api/docs (Swagger, when running)
- Setup guide: `docs/installation/START-HERE.md`
- Carrier Portal API: `apps/backend/docs/CARRIER_PORTAL_API.md`
- Full docs index: `docs/README.md`
- Development roadmap: `TODO.md`
- Infrastructure configs (CI/CD, Docker): `infra/`

View File

@ -24,7 +24,6 @@ e2e
# Environment files
.env
.env.*
.env.local
.env.development
.env.test

View File

@ -91,27 +91,3 @@ STRIPE_GOLD_MONTHLY_PRICE_ID=
STRIPE_GOLD_YEARLY_PRICE_ID=
STRIPE_PLATINIUM_MONTHLY_PRICE_ID=
STRIPE_PLATINIUM_YEARLY_PRICE_ID=
# Premier administrateur (amorcage) - migration BootstrapAdminFromEnv
# En developpement, laissez vide : SeedTestUsers cree deja admin@xpeditis.com.
# En production, renseignez une adresse RELEVABLE : le compte est cree sans
# mot de passe utilisable et vous definissez le votre via "mot de passe oublie".
# BOOTSTRAP_ADMIN_EMAIL=
# BOOTSTRAP_ADMIN_FIRST_NAME=Admin
# BOOTSTRAP_ADMIN_LAST_NAME=Xpeditis
# BOOTSTRAP_ADMIN_ORG_NAME=Xpeditis
# BOOTSTRAP_ADMIN_ORG_STREET=A completer
# BOOTSTRAP_ADMIN_ORG_CITY=A completer
# BOOTSTRAP_ADMIN_ORG_POSTAL_CODE=00000
# BOOTSTRAP_ADMIN_ORG_COUNTRY=FR
# Facultatif : hash Argon2id, si SMTP n'est pas encore operationnel.
# Generer avec : node scripts/setup/generate-admin-hash.js
# Jamais un mot de passe en clair - la migration le refuse.
# BOOTSTRAP_ADMIN_PASSWORD_HASH=
# Force la neutralisation des comptes de demonstration hors production.
# FORCE_NEUTRALIZE_SEED_ACCOUNTS=true
# Trade assistant — server only. Empty key enables guided help only.
OPENAI_API_KEY=
OPENAI_MODEL=gpt-4.1-mini

View File

@ -1,7 +1,7 @@
# ===============================================
# Stage 1: Dependencies Installation
# ===============================================
FROM node:22-alpine AS dependencies
FROM node:20-alpine AS dependencies
# Install build dependencies
RUN apk add --no-cache python3 make g++ libc6-compat
@ -19,7 +19,7 @@ RUN npm ci --legacy-peer-deps
# ===============================================
# Stage 2: Build Application
# ===============================================
FROM node:22-alpine AS builder
FROM node:20-alpine AS builder
WORKDIR /app
@ -38,11 +38,7 @@ RUN npm prune --production --legacy-peer-deps
# ===============================================
# Stage 3: Production Image
# ===============================================
FROM node:22-alpine AS production
# Runtime starts with node; remove the base image package manager and its dependencies.
# npm remains available in the dependency and build stages.
RUN npm uninstall --global npm
FROM node:20-alpine AS production
# Install dumb-init for proper signal handling
RUN apk add --no-cache dumb-init
@ -65,10 +61,6 @@ COPY --from=builder --chown=nestjs:nodejs /app/src ./src
# Copy startup script (includes migrations)
COPY --chown=nestjs:nodejs scripts/setup/startup.js ./startup.js
# Recovery command: set an admin password without SMTP
# docker exec -it <backend-container> node admin-password.js <email>
COPY --chown=nestjs:nodejs scripts/setup/admin-password.js ./admin-password.js
# Create logs and uploads directories
RUN mkdir -p /app/logs && \
mkdir -p /app/src/infrastructure/storage/csv-storage/rates && \

View File

@ -4,7 +4,7 @@ echo "Waiting for PostgreSQL..."
max_attempts=30
attempt=0
while [ $attempt -lt $max_attempts ]; do
if node -e "const { Client } = require('pg'); const { databaseTlsOptions } = require('/app/dist/infrastructure/persistence/typeorm/database-tls'); const client = new Client({ host: process.env.DATABASE_HOST, port: process.env.DATABASE_PORT, user: process.env.DATABASE_USER, password: process.env.DATABASE_PASSWORD, database: process.env.DATABASE_NAME, ssl: databaseTlsOptions(process.env.DATABASE_SSL, process.env.DATABASE_SSL_CA, process.env.DATABASE_HOST) }); client.connect().then(() => { client.end(); process.exit(0); }).catch(() => process.exit(1));" 2>/dev/null; then
if node -e "const { Client } = require('pg'); const client = new Client({ host: process.env.DATABASE_HOST, port: process.env.DATABASE_PORT, user: process.env.DATABASE_USER, password: process.env.DATABASE_PASSWORD, database: process.env.DATABASE_NAME }); client.connect().then(() => { client.end(); process.exit(0); }).catch(() => process.exit(1));" 2>/dev/null; then
echo "PostgreSQL is ready"
break
fi

View File

@ -7,10 +7,7 @@
"builder": "tsc",
"tsConfigPath": "tsconfig.build.json",
"plugins": ["@nestjs/swagger"],
"assets": [
{ "include": "i18n/**/*.json", "outDir": "dist" },
{ "include": "infrastructure/ai/knowledge/*.json", "outDir": "dist" }
],
"assets": [{ "include": "i18n/**/*.json", "outDir": "dist" }],
"watchAssets": true
}
}

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,6 @@
"scripts": {
"build": "nest build && tsc-alias -p tsconfig.build.json",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"knowledge:build": "node scripts/setup/build-knowledge-corpus.js",
"start": "nest start",
"dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
@ -29,21 +28,21 @@
"@aws-sdk/lib-storage": "^3.906.0",
"@aws-sdk/s3-request-presigner": "^3.906.0",
"@nestjs/axios": "^4.0.1",
"@nestjs/common": "^11.2.6",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.2.6",
"@nestjs/jwt": "^11.0.2",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.2.6",
"@nestjs/platform-socket.io": "^11.2.6",
"@nestjs/schedule": "^6.1.3",
"@nestjs/swagger": "^11.4.7",
"@nestjs/common": "^10.2.10",
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.2.10",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.2.10",
"@nestjs/platform-socket.io": "^10.4.20",
"@nestjs/swagger": "^7.1.16",
"@nestjs/throttler": "^6.4.0",
"@nestjs/typeorm": "^11.0.3",
"@nestjs/websockets": "^11.2.6",
"@nestjs/typeorm": "^10.0.1",
"@nestjs/websockets": "^10.4.20",
"@sentry/node": "^10.19.0",
"@sentry/profiling-node": "^10.19.0",
"@types/leaflet": "^1.9.21",
"@types/mjml": "^4.7.4",
"@types/nodemailer": "^7.0.2",
"@types/opossum": "^8.1.9",
"@types/pdfkit": "^0.17.3",
@ -60,10 +59,10 @@
"ioredis": "^5.8.1",
"joi": "^17.11.0",
"leaflet": "^1.9.4",
"mjml": "^5.4.1",
"mjml": "^4.16.1",
"nestjs-i18n": "^10.6.5",
"nestjs-pino": "^4.4.1",
"nodemailer": "^10.0.10",
"nodemailer": "^7.0.9",
"opossum": "^8.1.3",
"passport": "^0.7.0",
"passport-google-oauth20": "^2.0.0",
@ -77,7 +76,6 @@
"react-leaflet": "^5.0.0",
"reflect-metadata": "^0.1.14",
"rxjs": "^7.8.1",
"sharp": "^0.35.3",
"socket.io": "^4.8.1",
"stripe": "^14.14.0",
"typeorm": "^0.3.17",
@ -85,15 +83,14 @@
},
"devDependencies": {
"@faker-js/faker": "^10.0.0",
"@nestjs/cli": "^11.0.20",
"@nestjs/schematics": "^11.1.0",
"@nestjs/testing": "^11.2.6",
"@nestjs/cli": "^10.2.1",
"@nestjs/schematics": "^10.0.3",
"@nestjs/testing": "^10.2.10",
"@types/bcrypt": "^5.0.2",
"@types/compression": "^1.8.1",
"@types/cookie-parser": "^1.4.10",
"@types/express": "^5.0.6",
"@types/express": "^4.17.21",
"@types/jest": "^29.5.11",
"@types/mjml": "^5.0.0",
"@types/multer": "^2.0.0",
"@types/node": "^20.10.5",
"@types/passport-google-oauth20": "^2.0.14",

View File

@ -1,167 +0,0 @@
#!/usr/bin/env node
/**
* Commande de secours : définit le mot de passe d'un administrateur, sans SMTP.
*
* Dans le conteneur backend (le script est copié dans l'image) :
* docker exec -it <conteneur-backend> node admin-password.js admin@xpeditis.com
* En local :
* cd apps/backend && node scripts/setup/admin-password.js admin@xpeditis.com
*
* Le compte est créé s'il n'existe pas, sinon promu ADMIN et réactivé, puis son
* mot de passe est remplacé. Le mot de passe est saisi sans écho : ni argument
* de ligne de commande (visible dans `ps` et l'historique du shell), ni
* variable d'environnement. Il peut aussi être passé sur l'entrée standard
* pour une exécution scriptée.
*
* Connexion à la base : variables DATABASE_* déjà présentes dans le conteneur.
*/
'use strict';
const readline = require('readline');
const argon2 = require('argon2');
const { Client } = require('pg');
// Mêmes paramètres que auth.service.ts.
const ARGON2_OPTIONS = { type: argon2.argon2id, memoryCost: 65536, timeCost: 3, parallelism: 4 };
const MIN_LENGTH = 12;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
/** Saisie masquée sur un terminal ; lecture directe si l'entrée est redirigée. */
function readSecret(prompt) {
return new Promise((resolve, reject) => {
if (!process.stdin.isTTY) {
let data = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', chunk => (data += chunk));
process.stdin.on('end', () => resolve(data.replace(/\r?\n$/, '')));
process.stdin.on('error', reject);
return;
}
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const onKeypress = () => {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0);
process.stdout.write(prompt);
};
process.stdout.write(prompt);
process.stdin.on('data', onKeypress);
rl.question('', answer => {
process.stdin.removeListener('data', onKeypress);
rl.close();
process.stdout.write('\n');
resolve(answer);
});
});
}
function strengthProblems(password) {
const problems = [];
if (password.length < MIN_LENGTH) problems.push(`au moins ${MIN_LENGTH} caractères`);
if (!/[a-z]/.test(password)) problems.push('une minuscule');
if (!/[A-Z]/.test(password)) problems.push('une majuscule');
if (!/[0-9]/.test(password)) problems.push('un chiffre');
return problems;
}
function env(name, fallback) {
const value = (process.env[name] || '').trim();
return value || fallback;
}
async function main() {
const email = (process.argv[2] || '').trim().toLowerCase();
if (!EMAIL_PATTERN.test(email)) {
console.error('Usage : node admin-password.js <email-administrateur>');
process.exit(1);
}
const password = await readSecret(`Nouveau mot de passe pour ${email} : `);
if (process.stdin.isTTY) {
const confirmation = await readSecret('Confirmation : ');
if (confirmation !== password) {
console.error('Les deux saisies diffèrent.');
process.exit(1);
}
}
const problems = strengthProblems(password);
if (problems.length > 0) {
console.error(`Mot de passe refusé. Il manque : ${problems.join(', ')}.`);
process.exit(1);
}
const passwordHash = await argon2.hash(password, ARGON2_OPTIONS);
const client = new Client({
host: env('DATABASE_HOST', 'localhost'),
port: Number(env('DATABASE_PORT', '5432')),
user: env('DATABASE_USER', 'xpeditis'),
password: process.env.DATABASE_PASSWORD,
database: env('DATABASE_NAME', 'xpeditis_dev'),
// Même règle que data-source.ts : en production, pg_hba n'accepte que SSL.
ssl: process.env.DATABASE_SSL === 'true' ? { rejectUnauthorized: false } : false,
});
await client.connect();
try {
await client.query('BEGIN');
const existing = await client.query('SELECT "id" FROM "users" WHERE "email" = $1', [email]);
if (existing.rows.length > 0) {
// Réactiver ou promouvoir n'est jamais bloqué par le déclencheur
// « au moins un administrateur actif ».
await client.query(
`UPDATE "users"
SET "password_hash" = $2, "role" = 'ADMIN', "is_active" = true, "updated_at" = NOW()
WHERE "id" = $1`,
[existing.rows[0].id, passwordHash]
);
console.log(`Compte ${email} : mot de passe défini, rôle ADMIN, compte actif.`);
} else {
const organization = await client.query(
`INSERT INTO "organizations"
("name", "type", "address_street", "address_city", "address_postal_code", "address_country")
VALUES ($1, 'FREIGHT_FORWARDER', $2, $3, $4, $5)
ON CONFLICT ("name") DO UPDATE SET "updated_at" = NOW()
RETURNING "id"`,
[
env('BOOTSTRAP_ADMIN_ORG_NAME', 'Xpeditis'),
env('BOOTSTRAP_ADMIN_ORG_STREET', 'A completer'),
env('BOOTSTRAP_ADMIN_ORG_CITY', 'A completer'),
env('BOOTSTRAP_ADMIN_ORG_POSTAL_CODE', '00000'),
env('BOOTSTRAP_ADMIN_ORG_COUNTRY', 'FR').toUpperCase(),
]
);
await client.query(
`INSERT INTO "users"
("organization_id", "email", "password_hash", "role", "first_name", "last_name",
"is_email_verified", "is_active")
VALUES ($1, $2, $3, 'ADMIN', $4, $5, true, true)`,
[
organization.rows[0].id,
email,
passwordHash,
env('BOOTSTRAP_ADMIN_FIRST_NAME', 'Admin'),
env('BOOTSTRAP_ADMIN_LAST_NAME', 'Xpeditis'),
]
);
console.log(`Administrateur ${email} créé et actif.`);
}
await client.query('COMMIT');
console.log('Vous pouvez vous connecter. Changez ce mot de passe depuis l’interface si besoin.');
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
await client.end();
}
}
main().catch(error => {
console.error('Échec :', error.message);
process.exit(1);
});

View File

@ -1,127 +0,0 @@
#!/usr/bin/env node
/**
* Construit le corpus de connaissances de l'assistant a partir du wiki du site.
*
* Le wiki n'est pas ecrit en dur dans des pages : son contenu vit dans les
* fichiers de traduction du frontend, sous `dashboard.wikiPages`. C'est donc la
* source de verite, et la meme que celle que lit l'utilisateur — une reponse de
* l'assistant et la page wiki citee ne peuvent pas diverger.
*
* Le corpus est ecrit dans le backend et versionne : l'image backend ne doit
* pas dependre des fichiers du frontend a l'execution.
*
* Usage : npm run knowledge:build
*/
const fs = require('fs');
const path = require('path');
const ROOT = path.resolve(__dirname, '../../../..');
const MESSAGES = path.join(ROOT, 'apps/frontend/messages');
const OUT = path.resolve(__dirname, '../../src/infrastructure/ai/knowledge/wiki-corpus.json');
const LOCALES = ['fr', 'en'];
/** Les cles de mise en page ne portent aucune connaissance. */
const LAYOUT_KEYS = /^(col[A-Z]|.*Title$|.*Label$|backToWiki)/;
/** `documentsTransport` -> `documents-transport`, l'URL de la page wiki. */
const toSlug = key => key.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
const humanize = key =>
key
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.replace(/^./, c => c.toUpperCase())
.trim();
/**
* Nomme un champ d'objet dans la langue du wiki.
*
* Les cles de traduction sont en anglais (`code`, `name`, `description`) mais
* chaque sujet publie deja ses en-tetes de colonnes (`colCode`, `colName`...) :
* les reutiliser evite d'ecrire « Name: » au milieu d'un fragment francais.
*/
const labelFor = (topic, key) => topic[`col${key[0].toUpperCase()}${key.slice(1)}`] ?? humanize(key);
/** Aplatit une valeur de traduction en lignes lisibles par un modele. */
function toLines(value, topic) {
if (typeof value === 'string') return [value];
if (typeof value === 'number' || typeof value === 'boolean') return [String(value)];
if (Array.isArray(value)) return value.flatMap(item => toLines(item, topic));
if (value && typeof value === 'object') {
// Un objet de table se lit mieux sur une ligne qu'eclate en champs :
// « Code: 40 00 — Nom: Mise en Libre Pratique — Description: ... ».
const entries = Object.entries(value).filter(([, v]) => v !== null && v !== undefined);
const scalars = entries.filter(([, v]) => typeof v === 'string' || typeof v === 'number');
const rest = entries.filter(([, v]) => typeof v === 'object');
const head = scalars.map(([k, v]) => `${labelFor(topic, k)}: ${v}`).join(' — ');
return [
head,
...rest.flatMap(([k, v]) => toLines(v, topic).map(line => `${labelFor(topic, k)}: ${line}`)),
].filter(Boolean);
}
return [];
}
/**
* Un fragment par section du sujet. Une section = un champ de premier niveau,
* intitule par son `*Title` voisin quand il existe. Decouper plus finement
* casserait les tableaux (un Incoterm isole de sa colonne « risque ») ;
* decouper moins finement noierait la reponse sous 4 000 caracteres.
*/
function chunksForTopic(locale, topicKey, topic) {
const title = topic.title ?? humanize(topicKey);
const href = `/dashboard/wiki/${toSlug(topicKey)}`;
const chunks = [];
const header = [topic.title, topic.description].filter(Boolean).join('\n');
if (header) {
chunks.push({ section: title, text: header });
}
for (const [key, value] of Object.entries(topic)) {
if (key === 'title' || key === 'description') continue;
if (LAYOUT_KEYS.test(key)) continue;
const lines = toLines(value, topic).filter(Boolean);
if (!lines.length) continue;
const section = topic[`${key}Title`] ?? humanize(key);
chunks.push({ section, text: `${section}\n${lines.map(line => `- ${line}`).join('\n')}` });
}
return chunks.map((chunk, index) => ({
id: `${locale}:${topicKey}:${index}`,
locale,
topic: topicKey,
title,
section: chunk.section,
href,
text: chunk.text,
}));
}
const documents = [];
for (const locale of LOCALES) {
const file = path.join(MESSAGES, `${locale}.json`);
const wiki = JSON.parse(fs.readFileSync(file, 'utf8')).dashboard?.wikiPages;
if (!wiki) throw new Error(`dashboard.wikiPages introuvable dans ${file}`);
for (const [topicKey, topic] of Object.entries(wiki)) {
// Les libelles partages (`responsibleLabel`...) sont des chaines, pas des sujets.
if (!topic || typeof topic !== 'object' || Array.isArray(topic)) continue;
documents.push(...chunksForTopic(locale, topicKey, topic));
}
}
fs.mkdirSync(path.dirname(OUT), { recursive: true });
fs.writeFileSync(OUT, JSON.stringify({ documents }, null, 2) + '\n');
const byLocale = LOCALES.map(l => `${l}: ${documents.filter(d => d.locale === l).length}`).join(', ');
const chars = documents.reduce((sum, d) => sum + d.text.length, 0);
console.log(`${documents.length} fragments (${byLocale}) — ${chars} caracteres`);
console.log(`écrit dans ${path.relative(ROOT, OUT)}`);

View File

@ -1,132 +0,0 @@
#!/usr/bin/env node
/**
* Génère un hash Argon2id pour BOOTSTRAP_ADMIN_PASSWORD_HASH.
*
* cd apps/backend && node scripts/setup/generate-admin-hash.js
*
* Le mot de passe est saisi sans écho et ne quitte jamais votre poste : ni
* argument de ligne de commande (visible dans `ps` et dans l'historique du
* shell), ni variable d'environnement, ni fichier temporaire.
*
* Le hash est appliqué à CHAQUE lancement du backend (AdminBootstrapService) :
* - au compte BOOTSTRAP_ADMIN_EMAIL s'il ne s'est encore jamais connecté ;
* - à tout compte si BOOTSTRAP_ADMIN_RESET_PASSWORD=true (retirez ensuite
* les deux variables, sinon un mot de passe changé depuis l'interface
* serait remplacé au lancement suivant).
*
* Sans hash, le compte est créé sans mot de passe utilisable : il faut alors
* « mot de passe oublié » (SMTP requis) ou, sans SMTP, la commande de secours :
* docker exec -it <conteneur-backend> node admin-password.js <email>
*/
'use strict';
const argon2 = require('argon2');
const readline = require('readline');
// Mêmes paramètres que auth.service.ts : un hash produit ici est vérifiable
// par l'application sans aucune adaptation.
const ARGON2_OPTIONS = {
type: argon2.argon2id,
memoryCost: 65536, // 64 Mo
timeCost: 3,
parallelism: 4,
};
const MIN_LENGTH = 16;
/** Saisie masquée sur un terminal ; lecture directe si l'entrée est redirigée. */
function readSecret(prompt) {
return new Promise((resolve, reject) => {
if (!process.stdin.isTTY) {
let data = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', chunk => (data += chunk));
process.stdin.on('end', () => resolve(data.replace(/\r?\n$/, '')));
process.stdin.on('error', reject);
return;
}
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const onKeypress = () => {
// Réécrit la ligne sans révéler la longueur de la saisie.
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0);
process.stdout.write(prompt);
};
process.stdout.write(prompt);
process.stdin.on('data', onKeypress);
rl.question('', answer => {
process.stdin.removeListener('data', onKeypress);
rl.close();
process.stdout.write('\n');
resolve(answer);
});
});
}
function checkStrength(password) {
const problems = [];
if (password.length < MIN_LENGTH) {
problems.push(`au moins ${MIN_LENGTH} caractères (${password.length} fournis)`);
}
if (!/[a-z]/.test(password)) problems.push('une minuscule');
if (!/[A-Z]/.test(password)) problems.push('une majuscule');
if (!/[0-9]/.test(password)) problems.push('un chiffre');
if (!/[^A-Za-z0-9]/.test(password)) problems.push('un caractère spécial');
return problems;
}
async function main() {
console.log('');
console.log('Génération du hash Argon2id pour le premier administrateur.');
console.log('La saisie n’est pas affichée.');
console.log('');
const password = await readSecret('Mot de passe : ');
if (!password) {
console.error('Aucun mot de passe saisi.');
process.exit(1);
}
if (process.stdin.isTTY) {
const confirmation = await readSecret('Confirmation : ');
if (confirmation !== password) {
console.error('Les deux saisies diffèrent.');
process.exit(1);
}
}
const problems = checkStrength(password);
if (problems.length > 0) {
console.error('');
console.error('Mot de passe refusé. Il manque : ' + problems.join(', ') + '.');
console.error('Ce compte a tous les droits sur la plateforme : générez plutôt une');
console.error('phrase longue et aléatoire depuis votre gestionnaire de mots de passe.');
process.exit(1);
}
const hash = await argon2.hash(password, ARGON2_OPTIONS);
console.log('');
console.log('Hash à placer dans le Secret Kubernetes (jamais dans le ConfigMap) :');
console.log('');
console.log(' BOOTSTRAP_ADMIN_PASSWORD_HASH: ' + JSON.stringify(hash));
console.log('');
console.log(' cd infra/prod && sops k8s/base/03-secrets.sops.yaml');
console.log('');
console.log('Après votre première connexion :');
console.log(' 1. changez le mot de passe depuis l’interface ;');
console.log(' 2. retirez BOOTSTRAP_ADMIN_PASSWORD_HASH du Secret et réappliquez.');
console.log('');
console.log('Un hash reste attaquable hors ligne : il n’a plus aucune raison');
console.log('de rester stocké une fois le compte opérationnel.');
console.log('');
}
main().catch(error => {
console.error('Échec :', error.message);
process.exit(1);
});

View File

@ -5,10 +5,10 @@
const Stripe = require('stripe');
if (!process.env.STRIPE_SECRET_KEY) {
throw new Error('STRIPE_SECRET_KEY is required');
}
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const stripe = new Stripe(
process.env.STRIPE_SECRET_KEY ||
'sk_test_51R8p8R4atifoBlu1U9sMJh3rkQbO1G1xeguwFMQYMIMeaLNrTX7YFO5Ovu3P1VfbwcOoEmiy6I0UWi4DThNNzHG100YF75TnJr'
);
async function listPrices() {
console.log('Fetching Stripe prices...\n');

View File

@ -1,15 +1,5 @@
const { DataSource } = require('typeorm');
const path = require('path');
const { existsSync } = require('fs');
const applicationRoot = existsSync(path.join(__dirname, 'dist'))
? __dirname
: path.resolve(__dirname, '../..');
const { databaseTlsOptions } = require(
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/database-tls')
);
const { SafeDatabaseLogger } = require(
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/safe-database-logger')
);
const AppDataSource = new DataSource({
type: 'postgres',
@ -18,19 +8,10 @@ const AppDataSource = new DataSource({
username: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
ssl: databaseTlsOptions(
process.env.DATABASE_SSL,
process.env.DATABASE_SSL_CA,
process.env.DATABASE_HOST
),
entities: [path.join(applicationRoot, 'dist/**/*.orm-entity.js')],
migrations: [
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/migrations/*.js'),
],
entities: [path.join(__dirname, 'dist/**/*.orm-entity.js')],
migrations: [path.join(__dirname, 'dist/infrastructure/persistence/typeorm/migrations/*.js')],
synchronize: false,
logging: true,
logger: new SafeDatabaseLogger(true),
migrationsTransactionMode: 'all',
});
console.log('🚀 Starting Xpeditis Backend Migration Script...');
@ -58,6 +39,6 @@ AppDataSource.initialize()
})
.catch(error => {
console.error('❌ Error during migration:');
console.error('Check migration prerequisites and database availability.');
console.error(error);
process.exit(1);
});

View File

@ -4,17 +4,6 @@ const { Client } = require('pg');
const { DataSource } = require('typeorm');
const path = require('path');
const { spawn } = require('child_process');
const { existsSync } = require('fs');
// Docker copies this script to /app/startup.js; local copies stay in scripts/setup.
const applicationRoot = existsSync(path.join(__dirname, 'dist'))
? __dirname
: path.resolve(__dirname, '../..');
const { databaseTlsOptions } = require(
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/database-tls')
);
const { SafeDatabaseLogger } = require(
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/safe-database-logger')
);
async function waitForPostgres(maxAttempts = 30) {
console.log('⏳ Waiting for PostgreSQL to be ready...');
@ -27,11 +16,6 @@ async function waitForPostgres(maxAttempts = 30) {
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
ssl: databaseTlsOptions(
process.env.DATABASE_SSL,
process.env.DATABASE_SSL_CA,
process.env.DATABASE_HOST
),
});
await client.connect();
@ -58,19 +42,10 @@ async function runMigrations() {
username: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
ssl: databaseTlsOptions(
process.env.DATABASE_SSL,
process.env.DATABASE_SSL_CA,
process.env.DATABASE_HOST
),
entities: [path.join(applicationRoot, 'dist/**/*.orm-entity.js')],
migrations: [
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/migrations/*.js'),
],
entities: [path.join(__dirname, 'dist/**/*.orm-entity.js')],
migrations: [path.join(__dirname, 'dist/infrastructure/persistence/typeorm/migrations/*.js')],
synchronize: false,
logging: true,
logger: new SafeDatabaseLogger(true),
migrationsTransactionMode: 'all',
});
try {
@ -92,7 +67,7 @@ async function runMigrations() {
console.log('✅ Database migrations completed');
return true;
} catch (error) {
console.error('❌ Migration failed. Check migration prerequisites and database availability.');
console.error('❌ Error during migration:', error);
process.exit(1);
}
}
@ -103,7 +78,6 @@ function startApplication() {
const app = spawn('node', ['dist/main'], {
stdio: 'inherit',
env: process.env,
cwd: applicationRoot,
});
app.on('exit', code => {
@ -122,11 +96,7 @@ async function main() {
startApplication();
}
if (require.main === module) {
main().catch(error => {
console.error('❌ Startup failed. Check migration prerequisites and database availability.');
main().catch(error => {
console.error('❌ Startup failed:', error);
process.exit(1);
});
}
module.exports = { waitForPostgres, runMigrations };
});

View File

@ -1,9 +1,4 @@
import { SafeDatabaseLogger } from './infrastructure/persistence/typeorm/safe-database-logger';
import { safeHttpSerializers } from './application/logging/safe-http-log';
import { TradeAssistantModule } from './application/trade-assistant/trade-assistant.module';
import { McpModule } from './application/mcp/mcp.module';
import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LoggerModule } from 'nestjs-pino';
@ -18,7 +13,6 @@ import {
import * as path from 'path';
import * as Joi from 'joi';
import { UserPreferenceResolver } from './infrastructure/i18n/user-preference.resolver';
import { databaseTlsOptions } from './infrastructure/persistence/typeorm/database-tls';
// Import feature modules
import { AuthModule } from './application/auth/auth.module';
@ -42,7 +36,6 @@ import { CacheModule } from './infrastructure/cache/cache.module';
import { CarrierModule } from './infrastructure/carriers/carrier.module';
import { SecurityModule } from './infrastructure/security/security.module';
import { CsvRateModule } from './infrastructure/carriers/csv-loader/csv-rate.module';
import { AdminBootstrapModule } from './infrastructure/persistence/typeorm/admin-bootstrap.module';
// Import global guards
import { ApiKeyOrJwtGuard } from './application/guards/api-key-or-jwt.guard';
@ -51,7 +44,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
@Module({
imports: [
ScheduleModule.forRoot(),
// Configuration
ConfigModule.forRoot({
isGlobal: true,
@ -65,8 +57,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
DATABASE_USER: Joi.string().required(),
DATABASE_PASSWORD: Joi.string().required(),
DATABASE_NAME: Joi.string().required(),
DATABASE_SSL: Joi.boolean().default(false),
DATABASE_SSL_CA: Joi.string().optional(),
REDIS_HOST: Joi.string().required(),
REDIS_PORT: Joi.number().default(6379),
REDIS_PASSWORD: Joi.string().required(),
@ -86,14 +76,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
SMTP_FROM: Joi.string().email().default('noreply@xpeditis.com'),
SMTP_SECURE: Joi.boolean().default(false),
// Stripe Configuration (optional for development)
// Purge des donnees arrivees au terme de leur duree de
// conservation. Desactivee par defaut : elle supprime
// definitivement des lignes, l'activer est une decision
// d'exploitation.
RETENTION_PURGE_ENABLED: Joi.string().valid('true', 'false').default('false'),
OPENAI_API_KEY: Joi.string().allow('').optional(),
OPENAI_MODEL: Joi.string().default('gpt-4.1-mini'),
OPENAI_EMBEDDING_MODEL: Joi.string().default('text-embedding-3-small'),
STRIPE_SECRET_KEY: Joi.string().optional(),
STRIPE_WEBHOOK_SECRET: Joi.string().optional(),
STRIPE_SILVER_MONTHLY_PRICE_ID: Joi.string().optional(),
@ -103,13 +85,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
STRIPE_PLATINIUM_MONTHLY_PRICE_ID: Joi.string().optional(),
STRIPE_PLATINIUM_YEARLY_PRICE_ID: Joi.string().optional(),
LOG_EXPORTER_URL: Joi.string().uri().default('http://xpeditis-log-exporter:3200'),
// Administrateur garanti a chaque lancement (AdminBootstrapService).
// Pas de .email() ici : Joi rejette les TLD hors liste IANA et une
// adresse refusee empecherait l'API entiere de demarrer. Le service
// valide l'adresse et journalise une erreur sans bloquer.
BOOTSTRAP_ADMIN_EMAIL: Joi.string().allow('').optional(),
BOOTSTRAP_ADMIN_PASSWORD_HASH: Joi.string().allow('').optional(),
BOOTSTRAP_ADMIN_RESET_PASSWORD: Joi.string().valid('true', 'false', '').default('false'),
}),
}),
@ -123,7 +98,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
return {
pinoHttp: {
serializers: safeHttpSerializers,
transport: usePretty
? {
target: 'pino-pretty',
@ -184,15 +158,9 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
username: configService.get('DATABASE_USER'),
password: configService.get('DATABASE_PASSWORD'),
database: configService.get('DATABASE_NAME'),
ssl: databaseTlsOptions(
configService.get<boolean>('DATABASE_SSL'),
configService.get<string>('DATABASE_SSL_CA'),
configService.get<string>('DATABASE_HOST')
),
entities: [__dirname + '/**/*.orm-entity{.ts,.js}'],
synchronize: false, // ✅ Force false - use migrations instead
logging: configService.get('DATABASE_LOGGING', false),
logger: new SafeDatabaseLogger(configService.get('DATABASE_LOGGING', false)),
autoLoadEntities: true, // Auto-load entities from forFeature()
}),
inject: [ConfigService],
@ -203,8 +171,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
CacheModule,
CarrierModule,
CsvRateModule,
// Un administrateur exploitable a chaque lancement (base neuve comprise)
AdminBootstrapModule,
// Feature modules
AuthModule,
@ -222,8 +188,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
AdminModule,
BlogModule,
SubscriptionsModule,
TradeAssistantModule,
McpModule,
ApiKeysModule,
LogsModule,
],

View File

@ -35,9 +35,6 @@ import { BlogModule } from '../blog/blog.module';
// Storage
import { StorageModule } from '@infrastructure/storage/storage.module';
// User deletion (GDPR erasure)
import { GDPRModule } from '../gdpr/gdpr.module';
@Module({
imports: [
TypeOrmModule.forFeature([UserOrmEntity, OrganizationOrmEntity, CsvBookingOrmEntity]),
@ -46,7 +43,6 @@ import { GDPRModule } from '../gdpr/gdpr.module';
EmailModule,
BlogModule,
StorageModule,
GDPRModule,
],
controllers: [AdminController],
providers: [

View File

@ -1,88 +0,0 @@
import { ForbiddenException } from '@nestjs/common';
import { ApiKey } from '@domain/entities/api-key.entity';
import { Subscription } from '@domain/entities/subscription.entity';
import { SubscriptionPlan } from '@domain/value-objects/subscription-plan.vo';
import {
SubscriptionStatus,
SubscriptionStatusType,
} from '@domain/value-objects/subscription-status.vo';
import { ApiKeyRepository } from '@domain/ports/out/api-key.repository';
import { UserRepository } from '@domain/ports/out/user.repository';
import { SubscriptionRepository } from '@domain/ports/out/subscription.repository';
import { ApiKeysService } from './api-keys.service';
describe('API key current entitlement', () => {
const setup = () => {
let subscription = Subscription.create({
id: 'sub',
organizationId: 'org',
plan: SubscriptionPlan.gold(),
});
const key = ApiKey.create({
id: 'key',
userId: 'user',
organizationId: 'org',
name: 'test',
keyHash: 'hash',
keyPrefix: 'xped_live_test',
});
const keys = {
findByKeyHash: jest.fn().mockResolvedValue(key),
save: jest.fn().mockImplementation(async value => value),
};
const users = {
findById: jest
.fn()
.mockResolvedValue({ id: 'user', organizationId: 'org', isActive: true, role: 'MANAGER' }),
};
const subscriptions = {
findByOrganizationId: jest.fn().mockImplementation(async () => subscription),
};
return {
service: new ApiKeysService(
keys as unknown as ApiKeyRepository,
users as unknown as UserRepository,
subscriptions as unknown as SubscriptionRepository
),
keys,
setStatus: (status: SubscriptionStatusType) => {
subscription = subscription.updateStatus(SubscriptionStatus.create(status));
},
};
};
it.each<SubscriptionStatusType>([
'UNPAID',
'PAUSED',
'INCOMPLETE',
'INCOMPLETE_EXPIRED',
'CANCELED',
])('%s invalidates an existing key and forbids creation', async status => {
const { service, keys, setStatus } = setup();
await expect(service.validateAndGetUser('xped_live_test')).resolves.toMatchObject({
plan: 'GOLD',
});
keys.save.mockClear();
setStatus(status);
await expect(service.validateAndGetUser('xped_live_test')).resolves.toBeNull();
await expect(service.generateApiKey('user', 'org', { name: 'new' })).rejects.toBeInstanceOf(
ForbiddenException
);
expect(keys.save).not.toHaveBeenCalled();
});
it.each<SubscriptionStatusType>(['ACTIVE', 'TRIALING', 'PAST_DUE'])(
'%s permits keys',
async status => {
const { service, setStatus } = setup();
setStatus(status);
await expect(service.validateAndGetUser('xped_live_test')).resolves.toMatchObject({
plan: 'GOLD',
});
await expect(service.generateApiKey('user', 'org', { name: 'new' })).resolves.toMatchObject({
name: 'new',
isActive: true,
});
}
);
});

View File

@ -154,8 +154,8 @@ export class ApiKeysService {
organizationId: user.organizationId,
firstName: user.firstName,
lastName: user.lastName,
plan: subscription.accessPlan.value,
planFeatures: [...subscription.accessPlan.planFeatures],
plan: subscription.plan.value,
planFeatures: [...subscription.plan.planFeatures],
};
}

View File

@ -1,69 +0,0 @@
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Repository } from 'typeorm';
import { AuthService, JwtPayload } from './auth.service';
import { User, UserRole } from '@domain/entities/user.entity';
import { UserRepository } from '@domain/ports/out/user.repository';
import { OrganizationRepository } from '@domain/ports/out/organization.repository';
import { EmailPort } from '@domain/ports/out/email.port';
import { CachePort } from '@domain/ports/out/cache.port';
import { PasswordResetTokenOrmEntity } from '@infrastructure/persistence/typeorm/entities/password-reset-token.orm-entity';
import { SubscriptionService } from '../services/subscription.service';
jest.mock('argon2', () => ({ verify: jest.fn().mockResolvedValue(true) }));
describe('password-bound sessions', () => {
let user: User;
let auth: AuthService;
let jwt: JwtService;
beforeEach(() => {
user = User.create({
id: 'user-1',
organizationId: 'org-1',
email: 'test@example.org',
firstName: 'Test',
lastName: 'User',
role: UserRole.ADMIN,
passwordHash: 'old-salted-hash',
});
jwt = new JwtService({ secret: 'test-only-session-secret' });
auth = new AuthService(
{
findById: jest.fn(async () => user),
findByEmail: jest.fn(async () => user),
} as unknown as UserRepository,
{} as OrganizationRepository,
{} as EmailPort,
{ get: jest.fn(async () => null) } as unknown as CachePort,
{} as Repository<PasswordResetTokenOrmEntity>,
jwt,
new ConfigService({ JWT_SECRET: 'test-only-session-secret' }),
{} as SubscriptionService
);
});
it('rejects old access and refresh tokens after a password change, but accepts a new login', async () => {
const tokens = await auth.login(user.email, 'password');
const payload = jwt.verify<JwtPayload>(tokens.accessToken);
expect(await auth.validateUser(payload)).toBe(user);
expect(payload.credentialVersion).not.toContain(user.passwordHash);
user.updatePassword('new-salted-hash');
expect(await auth.validateUser(payload)).toBeNull();
await expect(auth.refreshAccessToken(tokens.refreshToken)).rejects.toThrow();
const fresh = await auth.login(user.email, 'new-password');
expect(await auth.validateUser(jwt.verify<JwtPayload>(fresh.accessToken))).toBe(user);
await expect(auth.refreshAccessToken(fresh.refreshToken)).resolves.toHaveProperty(
'accessToken'
);
});
it('preserves sessions after a profile change and rejects legacy or disabled sessions', async () => {
const tokens = await auth.login(user.email, 'password');
const payload = jwt.verify<JwtPayload>(tokens.accessToken);
user.updateFirstName('New name');
expect(await auth.validateUser(payload)).toBe(user);
expect(await auth.validateUser({ ...payload, credentialVersion: undefined })).toBeNull();
user.deactivate();
expect(await auth.validateUser(payload)).toBeNull();
});
});

View File

@ -1,5 +1,5 @@
import { Module } from '@nestjs/common';
import { JwtModule, JwtSignOptions } from '@nestjs/jwt';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
@ -36,7 +36,7 @@ import { AuditModule } from '../audit/audit.module';
useFactory: async (configService: ConfigService) => ({
secret: configService.get<string>('JWT_SECRET'),
signOptions: {
expiresIn: configService.get<JwtSignOptions['expiresIn']>('JWT_ACCESS_EXPIRATION', '15m'),
expiresIn: configService.get<string>('JWT_ACCESS_EXPIRATION', '15m'),
},
}),
}),

View File

@ -35,7 +35,6 @@ export interface JwtPayload {
plan?: string; // subscription plan (BRONZE, SILVER, GOLD, PLATINIUM)
planFeatures?: string[]; // plan feature flags
type: 'access' | 'refresh';
credentialVersion?: string;
rememberMe?: boolean; // drives auth cookie persistence across refreshes
}
@ -71,12 +70,6 @@ export class AuthService {
organizationData?: RegisterOrganizationDto,
invitationRole?: string
): Promise<{ accessToken: string; refreshToken: string; user: any }> {
// Emails are stored lowercase (enforced by the chk_users_email DB CHECK
// constraint), so normalize before any lookup or insert. Without this, an
// address containing uppercase letters fails the user INSERT after the
// organization has already been created — leaving an orphaned organization.
email = email.trim().toLowerCase();
this.logger.log(`Registering new user: ${email}`);
const existingUser = await this.userRepository.findByEmail(email);
@ -97,9 +90,6 @@ export class AuthService {
// 2. If organizationData is provided (new user), create a new organization
// 3. Otherwise, use default organization
const finalOrganizationId = await this.resolveOrganizationId(organizationId, organizationData);
// Track whether a brand-new organization was created for this registration,
// so it can be rolled back if the subsequent user creation fails.
const createdNewOrg = !organizationId && !!organizationData;
// Determine role:
// - If invitation role is provided (invited user), use it
@ -131,28 +121,7 @@ export class AuthService {
role: userRole,
});
let savedUser: User;
try {
savedUser = await this.userRepository.save(user);
} catch (err) {
// The organization is created before the user (non-atomic flow). If the
// user INSERT fails, roll the organization back so a retry isn't blocked
// by an orphaned organization ("name already exists").
if (createdNewOrg) {
try {
await this.organizationRepository.deleteById(finalOrganizationId);
this.logger.warn(
`Rolled back orphaned organization ${finalOrganizationId} after failed user creation`
);
} catch (cleanupErr) {
this.logger.error(
`Failed to roll back organization ${finalOrganizationId}`,
cleanupErr as Error
);
}
}
throw err;
}
const savedUser = await this.userRepository.save(user);
// Allocate a license for the new user
try {
@ -189,7 +158,6 @@ export class AuthService {
password: string,
rememberMe = false
): Promise<{ accessToken: string; refreshToken: string; user: any }> {
email = email.trim().toLowerCase();
this.logger.log(`Login attempt for: ${email}`);
const user = await this.userRepository.findByEmail(email);
@ -208,16 +176,6 @@ export class AuthService {
throw new UnauthorizedException('Invalid credentials');
}
// last_login_at n'etait jamais renseigne. L'amorcage de l'administrateur
// s'en sert pour ne jamais ecraser le mot de passe d'un compte deja utilise.
try {
user.recordLogin();
await this.userRepository.save(user);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
this.logger.warn(`Could not record last login for ${email}: ${message}`);
}
const tokens = await this.generateTokens(user, rememberMe);
this.logger.log(`User logged in successfully: ${email}`);
@ -254,7 +212,7 @@ export class AuthService {
throw new UnauthorizedException('Refresh token has been revoked');
}
const user = await this.validateUser(payload);
const user = await this.userRepository.findById(payload.sub);
if (!user || !user.isActive) {
throw new UnauthorizedException('User not found or inactive');
@ -414,22 +372,13 @@ export class AuthService {
async validateUser(payload: JwtPayload): Promise<User | null> {
const user = await this.userRepository.findById(payload.sub);
if (!user || !user.isActive || payload.credentialVersion !== this.credentialVersion(user)) {
if (!user || !user.isActive) {
return null;
}
return user;
}
// Bind sessions to the current password hash without exposing the hash in JWTs.
// Tokens minted before this binding was introduced require a fresh login.
private credentialVersion(user: User): string {
return crypto
.createHmac('sha256', this.configService.getOrThrow<string>('JWT_SECRET'))
.update(JSON.stringify(['credential-version-v1', user.id, user.passwordHash]))
.digest('hex');
}
/**
* Generate access and refresh tokens
*/
@ -457,8 +406,8 @@ export class AuthService {
const subscription = await this.subscriptionService.getOrCreateSubscription(
user.organizationId
);
plan = subscription.accessPlan.value;
planFeatures = [...subscription.accessPlan.planFeatures];
plan = subscription.plan.value;
planFeatures = [...subscription.plan.planFeatures];
} catch (error) {
this.logger.warn(`Failed to fetch subscription for JWT: ${error}`);
}
@ -472,7 +421,6 @@ export class AuthService {
plan,
planFeatures,
type: 'access',
credentialVersion: this.credentialVersion(user),
};
const refreshPayload: JwtPayload = {
@ -483,7 +431,6 @@ export class AuthService {
plan,
planFeatures,
type: 'refresh',
credentialVersion: this.credentialVersion(user),
rememberMe,
};

View File

@ -13,7 +13,6 @@ export interface JwtPayload {
role: string;
organizationId: string;
type: 'access' | 'refresh';
credentialVersion?: string;
iat?: number; // issued at
exp?: number; // expiration
}

View File

@ -24,7 +24,6 @@ import { FileInterceptor } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';
import { v4 as uuidv4 } from 'uuid';
import * as path from 'path';
import sharp from 'sharp';
import {
ApiTags,
ApiOperation,
@ -75,11 +74,6 @@ import type { BlogPostCategory } from '@domain/entities/blog-post.entity';
// Storage imports
import { StoragePort, STORAGE_PORT } from '@domain/ports/out/storage.port';
// User deletion
import { UserDeletionService } from '../services/user-deletion.service';
import { AdminContinuityService } from '../services/admin-continuity.service';
import { isAnonymisedEmail } from '@domain/services/data-retention';
const BLOG_IMAGES_BUCKET = 'xpeditis-blog';
const ALLOWED_IMAGE_MIMETYPES = [
'image/jpeg',
@ -116,9 +110,7 @@ export class AdminController {
private readonly siretVerificationPort: SiretVerificationPort,
@Inject(EMAIL_PORT) private readonly emailPort: EmailPort,
private readonly blogService: BlogService,
@Inject(STORAGE_PORT) private readonly storage: StoragePort,
private readonly userDeletionService: UserDeletionService,
private readonly adminContinuity: AdminContinuityService
@Inject(STORAGE_PORT) private readonly storage: StoragePort
) {}
// ==================== USERS ENDPOINTS ====================
@ -150,9 +142,7 @@ export class AdminController {
async getAllUsers(@CurrentUser() user: UserPayload): Promise<UserListResponseDto> {
this.logger.log(`[ADMIN: ${user.email}] Fetching ALL users from database`);
// Erased accounts stay in the table (their bookings reference them) but are
// no longer users: they must not come back in the list after a deletion.
let users = (await this.userRepository.findAll()).filter(u => !isAnonymisedEmail(u.email));
let users = await this.userRepository.findAll();
// Security: Non-admin users (MANAGER and below) cannot see ADMIN users
if (user.role !== 'ADMIN') {
@ -246,12 +236,6 @@ export class AdminController {
throw new BadRequestException('You cannot change your own role');
}
// At least one active admin must remain: refuse demoting or deactivating the last one
await this.adminContinuity.assertKeepsAnActiveAdmin(foundUser, {
role: dto.role ?? foundUser.role,
isActive: dto.isActive ?? foundUser.isActive,
});
// Apply updates
if (dto.firstName) {
foundUser.updateFirstName(dto.firstName);
@ -283,10 +267,7 @@ export class AdminController {
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({
summary: 'Delete user (Admin only)',
description:
'Erase a user (any role, including another ADMIN): personal data is deleted or anonymised, ' +
'the account is disabled and its license revoked. Bookings are kept. ' +
'An admin cannot delete their own account here, nor the last active admin.',
description: 'Permanently delete a user from the database',
})
@ApiParam({
name: 'id',
@ -305,7 +286,12 @@ export class AdminController {
): Promise<void> {
this.logger.log(`[ADMIN: ${user.email}] Deleting user: ${id}`);
await this.userDeletionService.deleteByAdmin(id, user);
const foundUser = await this.userRepository.findById(id);
if (!foundUser) {
throw new NotFoundException(`User ${id} not found`);
}
await this.userRepository.deleteById(id);
this.logger.log(`[ADMIN] User deleted successfully: ${id}`);
}
@ -770,12 +756,6 @@ export class AdminController {
routeDescription: booking.getRouteDescription(),
isExpired: booking.isExpired(),
price: booking.getPriceInCurrency(primaryCurrency),
commissionRate: booking.commissionRate,
commissionAmountEur: booking.commissionAmountEur,
freightTotal: booking.freightTotal,
freightCurrency: booking.freightCurrency,
fobTotal: booking.fobTotal,
fobCurrency: booking.fobCurrency,
};
}
@ -802,8 +782,12 @@ export class AdminController {
this.logger.log(`[ADMIN: ${user.email}] Sending test email to ${body.to}`);
try {
// Même gabarit que les vrais emails : le test valide aussi leur affichage.
await this.emailPort.sendSmtpTest(body.to, user.email);
await this.emailPort.send({
to: body.to,
subject: '[Xpeditis] Test SMTP',
html: `<p>Email de test envoyé depuis le panel admin par <strong>${user.email}</strong>.</p><p>Si vous lisez ceci, la configuration SMTP fonctionne correctement.</p>`,
text: `Email de test envoyé par ${user.email}. Si vous lisez ceci, le SMTP fonctionne.`,
});
this.logger.log(`[ADMIN] Test email sent successfully to ${body.to}`);
return { success: true, message: `Email envoyé avec succès à ${body.to}` };
@ -1011,79 +995,17 @@ export class AdminController {
return { url: `/api/v1/blog/images/${filename}`, filename };
}
@Post('blog/cover-images')
@UseInterceptors(
FileInterceptor('image', {
storage: memoryStorage(),
limits: { fileSize: MAX_IMAGE_SIZE },
fileFilter: (_req, file, cb) => {
// SVG cannot be raster-cropped; restrict to raster formats.
if (['image/jpeg', 'image/png', 'image/webp', 'image/gif'].includes(file.mimetype)) {
cb(null, true);
} else {
cb(new BadRequestException('Only JPG, PNG, WebP or GIF images are allowed'), false);
}
},
})
)
@ApiConsumes('multipart/form-data')
@ApiOperation({
summary: 'Upload and auto-crop a blog cover image (Admin only)',
description:
'Resizes and crops the image to the public 16:9 card ratio (1280x720) so covers are never distorted or cut off on the public site.',
})
@ApiResponse({
status: 201,
schema: { properties: { url: { type: 'string' }, filename: { type: 'string' } } },
})
async uploadBlogCoverImage(
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: UserPayload
): Promise<{ url: string; filename: string }> {
if (!file) throw new BadRequestException('No image file provided');
this.logger.log(`[ADMIN: ${user.email}] Uploading blog cover image: ${file.originalname}`);
// Crop to the public blog card ratio (16:9). "attention" focuses on the most
// salient region so important content is preserved.
let processed: Buffer;
try {
processed = await sharp(file.buffer)
.resize(1280, 720, { fit: 'cover', position: sharp.strategy.attention })
.webp({ quality: 82 })
.toBuffer();
} catch (err: any) {
this.logger.error(`Failed to process cover image: ${err?.message}`);
throw new BadRequestException("Impossible de traiter l'image");
}
const filename = `${uuidv4()}-cover.webp`;
const key = `blog-images/${filename}`;
await this.storage.upload({
bucket: BLOG_IMAGES_BUCKET,
key,
body: processed,
contentType: 'image/webp',
});
this.logger.log(`[ADMIN] Blog cover image uploaded: ${key}`);
return { url: `/api/v1/blog/images/${filename}`, filename };
}
@Get('blog')
@ApiOperation({ summary: 'List all blog posts (Admin only)' })
@ApiQuery({ name: 'status', required: false })
@ApiQuery({ name: 'category', required: false })
@ApiQuery({ name: 'search', required: false })
@ApiQuery({ name: 'trashed', required: false, type: Boolean })
@ApiQuery({ name: 'limit', required: false, type: Number })
@ApiQuery({ name: 'offset', required: false, type: Number })
async listBlogPosts(
@Query('status') status?: any,
@Query('category') category?: BlogPostCategory,
@Query('search') search?: string,
@Query('trashed') trashed?: string,
@Query('limit') limit = 50,
@Query('offset') offset = 0,
@CurrentUser() user?: UserPayload
@ -1093,7 +1015,6 @@ export class AdminController {
status,
category,
search,
trashed: trashed === 'true',
limit: Number(limit),
offset: Number(offset),
});
@ -1124,45 +1045,15 @@ export class AdminController {
@Delete('blog/:id')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Move a blog post to the trash (Admin only)' })
@ApiOperation({ summary: 'Delete a blog post (Admin only)' })
async deleteBlogPost(
@Param('id', ParseUUIDPipe) id: string,
@CurrentUser() user: UserPayload
): Promise<void> {
this.logger.log(`[ADMIN: ${user.email}] Trashing blog post: ${id}`);
this.logger.log(`[ADMIN: ${user.email}] Deleting blog post: ${id}`);
await this.blogService.deletePost(id);
}
@Post('blog/:id/restore')
@ApiOperation({ summary: 'Restore a blog post from the trash (Admin only)' })
async restoreBlogPost(@Param('id', ParseUUIDPipe) id: string, @CurrentUser() user: UserPayload) {
this.logger.log(`[ADMIN: ${user.email}] Restoring blog post: ${id}`);
const post = await this.blogService.restorePost(id);
return this.mapBlogPostToDto(post);
}
@Delete('blog/:id/permanent')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Permanently delete a blog post (Admin only)' })
async permanentlyDeleteBlogPost(
@Param('id', ParseUUIDPipe) id: string,
@CurrentUser() user: UserPayload
): Promise<void> {
this.logger.log(`[ADMIN: ${user.email}] Permanently deleting blog post: ${id}`);
await this.blogService.permanentlyDeletePost(id);
}
@Post('blog/:id/duplicate')
@ApiOperation({ summary: 'Duplicate a blog post as a new draft (Admin only)' })
async duplicateBlogPost(
@Param('id', ParseUUIDPipe) id: string,
@CurrentUser() user: UserPayload
) {
this.logger.log(`[ADMIN: ${user.email}] Duplicating blog post: ${id}`);
const post = await this.blogService.duplicatePost(id);
return this.mapBlogPostToDto(post);
}
private mapBlogPostToDto(post: BlogPost) {
return {
id: post.id,
@ -1181,10 +1072,6 @@ export class AdminController {
metaDescription: post.metaDescription,
primaryKeyword: post.primaryKeyword,
secondaryKeywords: post.secondaryKeywords,
aiSummary: post.aiSummary,
faq: post.faq,
keyTakeaways: post.keyTakeaways,
aiEntities: post.aiEntities,
createdAt: post.createdAt,
updatedAt: post.updatedAt,
};

View File

@ -4,7 +4,6 @@ import {
Get,
Delete,
Param,
Query,
Body,
UseGuards,
UseInterceptors,
@ -22,7 +21,6 @@ import {
ApiBearerAuth,
ApiConsumes,
ApiBody,
ApiQuery,
} from '@nestjs/swagger';
import { diskStorage } from 'multer';
import { extname } from 'path';
@ -174,15 +172,12 @@ export class CsvRatesAdminController {
}
try {
const direction = dto.direction ?? 'EXPORT';
// Generate final filename based on company name + direction
// (a company can have one export grid and one import grid)
// Generate final filename based on company name
const sanitizedCompanyName = dto.companyName
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^a-z0-9-]/g, '');
const finalFilename = `${sanitizedCompanyName}-${direction.toLowerCase()}.csv`;
const finalFilename = `${sanitizedCompanyName}.csv`;
// Auto-convert CSV if needed (FOB FRET → Standard format)
const conversionResult = await this.csvConverter.autoConvert(file.path, dto.companyName);
@ -212,8 +207,7 @@ export class CsvRatesAdminController {
const rates = await this.csvLoader.loadRatesFromCsv(
filePathToValidate,
dto.companyEmail,
dto.companyName,
direction
dto.companyName
);
const ratesCount = rates.length;
@ -247,7 +241,6 @@ export class CsvRatesAdminController {
metadata: {
companyName: dto.companyName,
companyEmail: dto.companyEmail,
direction,
uploadedBy: user.email,
uploadedAt: new Date().toISOString(),
},
@ -263,17 +256,13 @@ export class CsvRatesAdminController {
// The file is still available locally
}
// Check if config exists for this company + direction
const existingConfig = await this.csvConfigRepository.findByCompanyName(
dto.companyName,
direction
);
// Check if config exists for this company
const existingConfig = await this.csvConfigRepository.findByCompanyName(dto.companyName);
if (existingConfig) {
// Update existing configuration
await this.csvConfigRepository.update(existingConfig.id, {
csvFilePath: finalFilename,
direction,
uploadedAt: new Date(),
uploadedBy: user.id,
rowCount: ratesCount,
@ -296,7 +285,6 @@ export class CsvRatesAdminController {
await this.csvConfigRepository.create({
companyName: dto.companyName,
csvFilePath: finalFilename,
direction,
type: 'CSV_ONLY',
hasApi: false,
apiConnector: null,
@ -422,13 +410,7 @@ export class CsvRatesAdminController {
@ApiOperation({
summary: 'Delete CSV rate configuration (ADMIN only)',
description:
'Deletes the CSV rate configuration for a company. Without a direction, both the export and import grids of that company are deleted. Note: This does not delete the actual CSV file.',
})
@ApiQuery({
name: 'direction',
required: false,
enum: ['EXPORT', 'IMPORT'],
description: 'Only delete the grid of this direction',
'Deletes the CSV rate configuration for a company. Note: This does not delete the actual CSV file.',
})
@ApiResponse({
status: HttpStatus.NO_CONTENT,
@ -440,14 +422,11 @@ export class CsvRatesAdminController {
})
async deleteConfig(
@Param('companyName') companyName: string,
@CurrentUser() user: UserPayload,
@Query('direction') direction?: string
@CurrentUser() user: UserPayload
): Promise<void> {
this.logger.warn(`[Admin: ${user.email}] Deleting CSV config for company: ${companyName}`);
const upper = direction?.trim().toUpperCase();
const scoped = upper === 'EXPORT' || upper === 'IMPORT' ? upper : undefined;
await this.csvConfigRepository.delete(companyName, scoped);
await this.csvConfigRepository.delete(companyName);
this.logger.log(`Deleted CSV config for company: ${companyName}`);
}
@ -474,12 +453,10 @@ export class CsvRatesAdminController {
items: {
type: 'object',
properties: {
filename: { type: 'string', example: 'ssc-consolidation-export.csv' },
filename: { type: 'string', example: 'ssc-consolidation.csv' },
size: { type: 'number', example: 2048 },
uploadedAt: { type: 'string', format: 'date-time' },
rowCount: { type: 'number', example: 150 },
companyName: { type: 'string', example: 'SSC Consolidation' },
direction: { type: 'string', enum: ['EXPORT', 'IMPORT'], example: 'EXPORT' },
},
},
},
@ -491,34 +468,21 @@ export class CsvRatesAdminController {
const configs = await this.csvConfigRepository.findAll();
// Sizes come from MinIO, which is where the grids actually live; the local
// csv-storage copy is only a fallback and is often absent.
const sizeByKey = new Map<string, number>();
try {
const bucket = this.configService.get<string>('AWS_S3_BUCKET', 'xpeditis-csv-rates');
const objects = await this.s3Storage.list(bucket, 'csv-rates/');
objects.forEach(o => sizeByKey.set(o.key, o.size));
} catch (error: any) {
this.logger.warn(`Could not list CSV objects from MinIO: ${error.message}`);
}
// Map configs to file info format expected by frontend
const files = configs.map(config => {
const minioKey = config.metadata?.minioObjectKey as string | undefined;
let fileSize = (minioKey && sizeByKey.get(minioKey)) || 0;
if (!fileSize) {
const filePath = path.join(
process.cwd(),
'apps/backend/src/infrastructure/storage/csv-storage/rates',
config.csvFilePath
);
let fileSize = 0;
try {
fileSize = fs.statSync(filePath).size;
const stats = fs.statSync(filePath);
fileSize = stats.size;
} catch (error) {
this.logger.warn(`Could not get file size for ${config.csvFilePath}`);
}
}
return {
filename: config.csvFilePath,
@ -526,9 +490,6 @@ export class CsvRatesAdminController {
uploadedAt: config.uploadedAt.toISOString(),
rowCount: config.rowCount,
companyEmail: config.metadata?.companyEmail ?? null,
companyName: config.companyName,
direction: config.direction ?? 'EXPORT',
isActive: config.isActive,
};
});
@ -603,11 +564,10 @@ export class CsvRatesAdminController {
}
}
// Delete the configuration — scoped to this grid's direction, otherwise the
// company's other grid (export vs import) would be deleted too.
await this.csvConfigRepository.delete(config.companyName, config.direction);
// Delete the configuration
await this.csvConfigRepository.delete(config.companyName);
this.logger.log(`Deleted CSV config and file for: ${config.companyName} (${config.direction})`);
this.logger.log(`Deleted CSV config and file for: ${config.companyName}`);
return {
success: true,

View File

@ -25,9 +25,9 @@ class AuditLogResponseDto {
id: string;
action: string;
status: string;
userId: string | null;
userId: string;
userEmail: string;
organizationId: string | null;
organizationId: string;
resourceType?: string;
resourceId?: string;
resourceName?: string;

View File

@ -43,6 +43,18 @@ import {
const REFRESH_COOKIE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
/**
* Escape user-provided text before interpolating it into HTML emails
*/
function escapeHtml(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
/**
* Authentication Controller
*
@ -250,13 +262,12 @@ export class AuthController {
};
} catch (error: any) {
// Audit log: record failed login attempts (the attempted email is the
// only identity we have — the credentials did not match a valid user,
// so user and organization are recorded as null)
// only identity we have — the credentials did not match a valid user)
await this.auditService.logFailure(
AuditAction.USER_LOGIN,
null,
'unknown',
dto.email,
null,
'unknown',
error?.message || 'Invalid credentials',
{
resourceType: 'user',
@ -314,16 +325,7 @@ export class AuthController {
throw new UnauthorizedException('No refresh token provided');
}
let result: Awaited<ReturnType<typeof this.authService.refreshAccessToken>>;
try {
result = await this.authService.refreshAccessToken(refreshToken);
} catch (error) {
// The refresh token is expired/revoked: wipe every auth cookie (including
// the readable session flag) so the client stops believing a session
// exists. Without this the frontend keeps retrying and reloading.
this.clearAuthCookies(res);
throw error;
}
const result = await this.authService.refreshAccessToken(refreshToken);
this.setAuthCookies(res, result, result.rememberMe);
@ -402,16 +404,53 @@ export class AuthController {
other: 'Autre',
};
// Le gabarit échappe lui-même chaque champ saisi par le visiteur.
const subjectLabel = escapeHtml(subjectLabels[dto.subject] || dto.subject);
const firstName = escapeHtml(dto.firstName);
const lastName = escapeHtml(dto.lastName);
const email = escapeHtml(dto.email);
const company = dto.company ? escapeHtml(dto.company) : undefined;
const phone = dto.phone ? escapeHtml(dto.phone) : undefined;
const message = escapeHtml(dto.message);
const html = `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
<div style="background: #10183A; padding: 24px; border-radius: 8px 8px 0 0;">
<h1 style="color: #34CCCD; margin: 0; font-size: 20px;">Nouveau message de contact</h1>
</div>
<div style="background: #f9f9f9; padding: 24px; border: 1px solid #e0e0e0;">
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 8px 0; color: #666; width: 130px; font-size: 14px;">Nom</td>
<td style="padding: 8px 0; color: #222; font-weight: bold; font-size: 14px;">${firstName} ${lastName}</td>
</tr>
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Email</td>
<td style="padding: 8px 0; font-size: 14px;"><a href="mailto:${email}" style="color: #34CCCD;">${email}</a></td>
</tr>
${company ? `<tr><td style="padding: 8px 0; color: #666; font-size: 14px;">Entreprise</td><td style="padding: 8px 0; color: #222; font-size: 14px;">${company}</td></tr>` : ''}
${phone ? `<tr><td style="padding: 8px 0; color: #666; font-size: 14px;">Téléphone</td><td style="padding: 8px 0; color: #222; font-size: 14px;">${phone}</td></tr>` : ''}
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Sujet</td>
<td style="padding: 8px 0; color: #222; font-size: 14px;">${subjectLabel}</td>
</tr>
</table>
<div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid #ddd;">
<p style="color: #666; font-size: 14px; margin: 0 0 8px 0;">Message :</p>
<p style="color: #222; font-size: 14px; white-space: pre-wrap; margin: 0;">${message}</p>
</div>
</div>
<div style="background: #f0f0f0; padding: 12px 24px; border-radius: 0 0 8px 8px; text-align: center;">
<p style="color: #999; font-size: 12px; margin: 0;">Xpeditis — Formulaire de contact</p>
</div>
</div>
`;
try {
await this.emailService.sendContactMessage('contact@xpeditis.com', {
firstName: dto.firstName,
lastName: dto.lastName,
email: dto.email,
company: dto.company || undefined,
phone: dto.phone || undefined,
subjectLabel: subjectLabels[dto.subject] || dto.subject,
message: dto.message,
await this.emailService.send({
to: 'contact@xpeditis.com',
replyTo: dto.email,
subject: `[Contact] ${subjectLabels[dto.subject] || dto.subject} — ${dto.firstName} ${dto.lastName}`,
html,
});
} catch (error) {
this.logger.error(`Failed to send contact email: ${error}`);

View File

@ -117,7 +117,7 @@ export class BlogController {
slug: post.slug,
excerpt: post.excerpt,
content: post.content,
coverImageUrl: post.coverImageUrl ?? undefined,
coverImageUrl: post.coverImageUrl,
category: post.category,
tags: post.tags,
authorName: post.authorName,
@ -128,10 +128,6 @@ export class BlogController {
metaDescription: post.metaDescription,
primaryKeyword: post.primaryKeyword,
secondaryKeywords: post.secondaryKeywords,
aiSummary: post.aiSummary ?? undefined,
faq: post.faq,
keyTakeaways: post.keyTakeaways,
aiEntities: post.aiEntities,
createdAt: post.createdAt,
updatedAt: post.updatedAt,
};

View File

@ -117,7 +117,7 @@ export class BookingsController {
const subscription = await this.subscriptionService.getOrCreateSubscription(
user.organizationId
);
const maxShipments = subscription.maxShipmentsPerYear;
const maxShipments = subscription.plan.maxShipmentsPerYear;
if (maxShipments !== -1) {
const currentYear = new Date().getFullYear();
const count = await this.shipmentCounter.countShipmentsForOrganizationInYear(

View File

@ -1,5 +1,4 @@
import { Controller, Get, Post, Param, Query, Body, Res, StreamableFile } from '@nestjs/common';
import { Response } from 'express';
import { Controller, Get, Post, Param, Query, Body } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery, ApiBody } from '@nestjs/swagger';
import { Public } from '../decorators/public.decorator';
import { CsvBookingService } from '../services/csv-booking.service';
@ -174,75 +173,4 @@ export class CsvBookingActionsController {
async getBookingDocuments(@Param('token') token: string): Promise<CarrierDocumentsResponseDto> {
return this.csvBookingService.getDocumentsForCarrier(token);
}
/**
* Download a single booking document, streamed through the API (PUBLIC - token-based).
*
* Password-protected bookings must use POST with the password in the body.
*
* POST /api/v1/csv-booking-actions/documents/:token/:documentId/download
*/
@Public()
@Post('documents/:token/:documentId/download')
@ApiOperation({
summary: 'Download a booking document with password (public)',
description:
'Streams a single booking document to the carrier. Applies the same access rules as the documents list (booking accepted + password when protected).',
})
@ApiParam({ name: 'token', description: 'Booking confirmation token (UUID)' })
@ApiParam({ name: 'documentId', description: 'Document ID' })
@ApiBody({ type: VerifyDocumentAccessDto })
@ApiResponse({ status: 200, description: 'Document streamed successfully.' })
@ApiResponse({ status: 401, description: 'Invalid or missing password' })
@ApiResponse({ status: 404, description: 'Booking or document not found' })
async downloadBookingDocumentWithPassword(
@Param('token') token: string,
@Param('documentId') documentId: string,
@Body() dto: VerifyDocumentAccessDto,
@Res({ passthrough: true }) res: Response
): Promise<StreamableFile> {
return this.streamDocument(token, documentId, dto?.password, res);
}
/**
* Download a single booking document (PUBLIC - token-based) - Legacy without password.
*
* GET /api/v1/csv-booking-actions/documents/:token/:documentId/download
*/
@Public()
@Get('documents/:token/:documentId/download')
@ApiOperation({
summary: 'Download a booking document (public) - Legacy',
description:
'Streams a single booking document for bookings without password protection. Protected bookings must use the POST variant.',
})
@ApiParam({ name: 'token', description: 'Booking confirmation token (UUID)' })
@ApiParam({ name: 'documentId', description: 'Document ID' })
@ApiResponse({ status: 200, description: 'Document streamed successfully.' })
@ApiResponse({ status: 401, description: 'Password required for this booking' })
@ApiResponse({ status: 404, description: 'Booking or document not found' })
async downloadBookingDocument(
@Param('token') token: string,
@Param('documentId') documentId: string,
@Res({ passthrough: true }) res: Response
): Promise<StreamableFile> {
return this.streamDocument(token, documentId, undefined, res);
}
private async streamDocument(
token: string,
documentId: string,
password: string | undefined,
res: Response
): Promise<StreamableFile> {
const { buffer, fileName, mimeType } = await this.csvBookingService.streamDocumentForCarrier(
token,
documentId,
password
);
res.setHeader('Content-Type', mimeType);
res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(fileName)}"`);
return new StreamableFile(buffer);
}
}

View File

@ -14,7 +14,6 @@ import {
BadRequestException,
ForbiddenException,
ParseIntPipe,
ParseUUIDPipe,
DefaultValuePipe,
Inject,
} from '@nestjs/common';
@ -31,8 +30,6 @@ import {
ApiParam,
} from '@nestjs/swagger';
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
import { RolesGuard } from '../guards/roles.guard';
import { Roles } from '../decorators/roles.decorator';
import { Public } from '../decorators/public.decorator';
import { CsvBookingService } from '../services/csv-booking.service';
import { SubscriptionService } from '../services/subscription.service';
@ -50,8 +47,6 @@ import {
CsvBookingResponseDto,
CsvBookingListResponseDto,
CsvBookingStatsDto,
UpdateCsvBookingDetailsDto,
UpdateCsvBookingRateDto,
} from '../dto/csv-booking.dto';
/**
@ -86,20 +81,8 @@ export class CsvBookingsController {
* POST /api/v1/csv-bookings
*/
@Post()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'MANAGER', 'USER')
@ApiBearerAuth()
@UseInterceptors(
FilesInterceptor('documents', 10, {
limits: {
fileSize: 10 * 1024 * 1024,
files: 10,
fields: 40,
parts: 50,
fieldSize: 64 * 1024,
},
})
)
@UseInterceptors(FilesInterceptor('documents', 10))
@ApiConsumes('multipart/form-data')
@ApiOperation({
summary: 'Create a new CSV booking request',
@ -158,6 +141,13 @@ export class CsvBookingsController {
@Request() req: any
): Promise<CsvBookingResponseDto> {
// Debug: Log request details
console.log('=== CSV Booking Request Debug ===');
console.log('req.user:', req.user);
console.log('req.body:', req.body);
console.log('dto:', dto);
console.log('files:', files?.length);
console.log('================================');
if (!files || files.length === 0) {
throw new BadRequestException('At least one document is required');
}
@ -176,12 +166,12 @@ export class CsvBookingsController {
// ADMIN users bypass shipment limits
if (req.user.role !== 'ADMIN') {
// Check the paid-reservation limit (free/Bronze plan = 5 paid shipments/year)
// Check shipment limit (Bronze plan = 12/year)
const subscription = await this.subscriptionService.getOrCreateSubscription(organizationId);
const maxShipments = subscription.maxShipmentsPerYear;
const maxShipments = subscription.plan.maxShipmentsPerYear;
if (maxShipments !== -1) {
const currentYear = new Date().getFullYear();
const count = await this.shipmentCounter.countPaidShipmentsForOrganizationInYear(
const count = await this.shipmentCounter.countShipmentsForOrganizationInYear(
organizationId,
currentYear
);
@ -236,35 +226,6 @@ export class CsvBookingsController {
return await this.csvBookingService.getUserBookings(userId, page, limit);
}
/**
* Get the reservation (paid shipment) quota for the current organization.
*
* Uses the organization's real plan (not the ADMIN PLATINIUM override) and
* counts only PAID shipments this year, so the UI can show an upgrade prompt.
*
* GET /api/v1/csv-bookings/reservation-quota
*/
@Get('reservation-quota')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: 'Get the paid-reservation quota for the current organization' })
@ApiResponse({ status: 200, description: 'Quota retrieved successfully' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
async getReservationQuota(
@Request() req: any
): Promise<{ max: number; used: number; unlimited: boolean; limitReached: boolean }> {
const organizationId = req.user.organizationId;
const subscription = await this.subscriptionService.getOrCreateSubscription(organizationId);
const max = subscription.maxShipmentsPerYear;
const unlimited = max === -1;
const currentYear = new Date().getFullYear();
const used = await this.shipmentCounter.countPaidShipmentsForOrganizationInYear(
organizationId,
currentYear
);
return { max, used, unlimited, limitReached: !unlimited && used >= max };
}
/**
* Get booking statistics for user
*
@ -295,8 +256,6 @@ export class CsvBookingsController {
* GET /api/v1/csv-bookings/stats/organization
*/
@Get('stats/organization')
@UseGuards(RolesGuard)
@Roles('ADMIN', 'MANAGER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({
@ -320,15 +279,12 @@ export class CsvBookingsController {
* GET /api/v1/csv-bookings/organization/all
*/
@Get('organization/all')
@UseGuards(RolesGuard)
@Roles('ADMIN', 'MANAGER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({
summary: 'Get organization bookings',
description:
"Retrieve all bookings and quotes of the user's organization, whoever created them, " +
'with the name of their creator. Available to every member of the organization.',
"Retrieve all bookings for the user's organization with pagination. For managers/admins.",
})
@ApiQuery({ name: 'page', required: false, type: Number, example: 1 })
@ApiQuery({ name: 'limit', required: false, type: Number, example: 10 })
@ -428,8 +384,6 @@ export class CsvBookingsController {
* POST /api/v1/csv-bookings/:id/pay
*/
@Post(':id/pay')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'MANAGER', 'USER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({
@ -450,7 +404,7 @@ export class CsvBookingsController {
},
},
})
@ApiResponse({ status: 400, description: 'Booking not in QUOTE status' })
@ApiResponse({ status: 400, description: 'Booking not in PENDING_PAYMENT status' })
@ApiResponse({ status: 404, description: 'Booking not found' })
async payCommission(@Param('id') id: string, @Request() req: any) {
const userId = req.user.id;
@ -478,8 +432,6 @@ export class CsvBookingsController {
* POST /api/v1/csv-bookings/:id/confirm-payment
*/
@Post(':id/confirm-payment')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'MANAGER', 'USER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({
@ -523,8 +475,6 @@ export class CsvBookingsController {
* POST /api/v1/csv-bookings/:id/declare-transfer
*/
@Post(':id/declare-transfer')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'MANAGER', 'USER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({
@ -538,7 +488,7 @@ export class CsvBookingsController {
description: 'Bank transfer declared, booking awaiting admin validation',
type: CsvBookingResponseDto,
})
@ApiResponse({ status: 400, description: 'Booking not in QUOTE status' })
@ApiResponse({ status: 400, description: 'Booking not in PENDING_PAYMENT status' })
@ApiResponse({ status: 404, description: 'Booking not found' })
async declareTransfer(
@Param('id') id: string,
@ -565,9 +515,7 @@ export class CsvBookingsController {
@ApiBearerAuth()
@ApiOperation({
summary: 'Get booking by ID',
description:
'Retrieve a specific CSV booking by its ID. Readable by any member of the booking organization ' +
'and by the assigned carrier; changes remain reserved to the booking owner.',
description: 'Retrieve a specific CSV booking by its ID. Only accessible by the booking owner.',
})
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
@ApiResponse({
@ -580,12 +528,7 @@ export class CsvBookingsController {
async getBooking(@Param('id') id: string, @Request() req: any): Promise<CsvBookingResponseDto> {
const userId = req.user.id;
const carrierId = req.user.carrierId; // May be undefined if not a carrier
return await this.csvBookingService.getBookingById(
id,
userId,
carrierId,
req.user.organizationId
);
return await this.csvBookingService.getBookingById(id, userId, carrierId);
}
/**
@ -594,8 +537,6 @@ export class CsvBookingsController {
* PATCH /api/v1/csv-bookings/:id/cancel
*/
@Patch(':id/cancel')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'MANAGER', 'USER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({
@ -619,120 +560,15 @@ export class CsvBookingsController {
return await this.csvBookingService.cancelBooking(id, userId);
}
/**
* Delete an unpaid booking
*
* DELETE /api/v1/csv-bookings/:id
*/
@Delete(':id')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'MANAGER', 'USER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({
summary: 'Delete an unpaid booking',
description:
'Permanently deletes a booking whose commission has not been paid. Only accessible by the booking owner. A paid booking has been sent to the carrier and can only be cancelled.',
})
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
@ApiResponse({ status: 200, description: 'Booking deleted successfully' })
@ApiResponse({ status: 400, description: 'Booking has been paid and cannot be deleted' })
@ApiResponse({ status: 404, description: 'Booking not found' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
async deleteBooking(
@Param('id', ParseUUIDPipe) id: string,
@Request() req: any
): Promise<{ success: boolean; message: string }> {
return await this.csvBookingService.deleteBooking(id, req.user.id);
}
/**
* Update booking cargo details before payment
*
* PATCH /api/v1/csv-bookings/:id/details
*/
@Patch(':id/details')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'MANAGER', 'USER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({
summary: 'Update booking details before payment',
description:
'Edit cargo characteristics (volume, weight, pallets, notes) of a booking awaiting payment. Only the owner can edit, and only while the booking is QUOTE.',
})
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
@ApiResponse({
status: 200,
description: 'Booking details updated successfully',
type: CsvBookingResponseDto,
})
@ApiResponse({ status: 400, description: 'Booking cannot be edited (invalid status or values)' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 404, description: 'Booking not found' })
async updateBookingDetails(
@Param('id') id: string,
@Body() dto: UpdateCsvBookingDetailsDto,
@Request() req: any
): Promise<CsvBookingResponseDto> {
const userId = req.user.id;
return await this.csvBookingService.updateBookingDetails(id, userId, dto);
}
/**
* Re-apply a full rate selection before payment
*
* PATCH /api/v1/csv-bookings/:id/rate
*/
@Patch(':id/rate')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'MANAGER', 'USER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({
summary: 'Update booking rate/route before payment',
description:
'Re-apply a rate selection (carrier, route, container, transit, cargo, price) to a QUOTE booking. Only the owner can edit.',
})
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
@ApiResponse({
status: 200,
description: 'Booking rate updated successfully',
type: CsvBookingResponseDto,
})
@ApiResponse({ status: 400, description: 'Booking cannot be edited (invalid status or values)' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 404, description: 'Booking not found' })
async updateBookingRate(
@Param('id') id: string,
@Body() dto: UpdateCsvBookingRateDto,
@Request() req: any
): Promise<CsvBookingResponseDto> {
const userId = req.user.id;
return await this.csvBookingService.updateBookingRate(id, userId, dto);
}
/**
* Add documents to an existing booking
*
* POST /api/v1/csv-bookings/:id/documents
*/
@Post(':id/documents')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'MANAGER', 'USER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@UseInterceptors(
FilesInterceptor('documents', 10, {
limits: {
fileSize: 10 * 1024 * 1024,
files: 10,
fields: 40,
parts: 50,
fieldSize: 64 * 1024,
},
})
)
@UseInterceptors(FilesInterceptor('documents', 10))
@ApiConsumes('multipart/form-data')
@ApiOperation({
summary: 'Add documents to an existing booking',
@ -786,15 +622,9 @@ export class CsvBookingsController {
* PUT /api/v1/csv-bookings/:bookingId/documents/:documentId
*/
@Patch(':bookingId/documents/:documentId')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'MANAGER', 'USER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@UseInterceptors(
FilesInterceptor('document', 1, {
limits: { fileSize: 10 * 1024 * 1024, files: 1, fields: 10, parts: 11, fieldSize: 64 * 1024 },
})
)
@UseInterceptors(FilesInterceptor('document', 1))
@ApiConsumes('multipart/form-data')
@ApiOperation({
summary: 'Replace a document in a booking',
@ -861,8 +691,6 @@ export class CsvBookingsController {
* DELETE /api/v1/csv-bookings/:bookingId/documents/:documentId
*/
@Delete(':bookingId/documents/:documentId')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'MANAGER', 'USER')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({

View File

@ -1,119 +0,0 @@
import { ExecutionContext, INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { ConfigService } from '@nestjs/config';
import request from 'supertest';
import { Subscription } from '@domain/entities/subscription.entity';
import { SubscriptionPlan } from '@domain/value-objects/subscription-plan.vo';
import { ShipmentLimitExceededException } from '@domain/exceptions/shipment-limit-exceeded.exception';
import { CreateCsvBookingDto } from '../dto/csv-booking.dto';
import { SubscriptionStatus } from '@domain/value-objects/subscription-status.vo';
import { CsvBookingsController } from './csv-bookings.controller';
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
import { CsvBookingService } from '../services/csv-booking.service';
import { SubscriptionService } from '../services/subscription.service';
import { SHIPMENT_COUNTER_PORT } from '@domain/ports/out/shipment-counter.port';
import { ORGANIZATION_REPOSITORY } from '@domain/ports/out/organization.repository';
describe('CSV booking HTTP security', () => {
let app: INestApplication;
let subscription: Subscription;
const countPaidShipmentsForOrganizationInYear = jest.fn().mockResolvedValue(0);
const createBooking = jest.fn(async () => ({ id: 'booking' }));
const getUserBookings = jest.fn(async () => ({ bookings: [] }));
beforeAll(async () => {
const module = await Test.createTestingModule({
controllers: [CsvBookingsController],
providers: [
{ provide: CsvBookingService, useValue: { createBooking, getUserBookings } },
{
provide: SubscriptionService,
useValue: {
getOrCreateSubscription: async () => subscription,
},
},
{ provide: ConfigService, useValue: {} },
{ provide: SHIPMENT_COUNTER_PORT, useValue: { countPaidShipmentsForOrganizationInYear } },
{ provide: ORGANIZATION_REPOSITORY, useValue: {} },
],
})
.overrideGuard(JwtAuthGuard)
.useValue({
canActivate: (context: ExecutionContext) => {
const req = context.switchToHttp().getRequest();
req.user = {
id: 'user',
organizationId: 'org',
role: req.headers['x-test-role'] || 'USER',
};
return true;
},
})
.compile();
app = module.createNestApplication({ logger: false });
await app.init();
await app.listen(0, '127.0.0.1');
});
afterAll(async () => {
await app?.close();
});
beforeEach(() => {
jest.clearAllMocks();
subscription = Subscription.create({
id: 'sub',
organizationId: 'org',
plan: SubscriptionPlan.gold(),
});
countPaidShipmentsForOrganizationInYear.mockResolvedValue(0);
});
it('rejects VIEWER mutations before invoking the booking service', async () => {
await request(app.getHttpServer())
.post('/csv-bookings')
.set('x-test-role', 'VIEWER')
.attach('documents', Buffer.from('document'), 'test.pdf')
.expect(403);
expect(createBooking).not.toHaveBeenCalled();
});
it('preserves VIEWER reads', async () => {
await request(app.getHttpServer())
.get('/csv-bookings')
.set('x-test-role', 'VIEWER')
.expect(200);
expect(getUserBookings).toHaveBeenCalled();
});
it('rejects organization-wide reads for an ordinary member', async () => {
await request(app.getHttpServer()).get('/csv-bookings/organization/all').expect(403);
});
it('rejects oversized documents before invoking the service', async () => {
await request(app.getHttpServer())
.post('/csv-bookings')
.attach('documents', Buffer.alloc(10 * 1024 * 1024 + 1), 'large.pdf')
.expect(413);
expect(createBooking).not.toHaveBeenCalled();
});
it('applies the Bronze quota after a paid subscription is suspended', async () => {
subscription = subscription.updateStatus(SubscriptionStatus.create('UNPAID'));
countPaidShipmentsForOrganizationInYear.mockResolvedValue(
SubscriptionPlan.bronze().maxShipmentsPerYear
);
await expect(
app
.get(CsvBookingsController)
.createBooking({} as CreateCsvBookingDto, [{} as Express.Multer.File], {
user: { id: 'user', organizationId: 'org', role: 'USER' },
})
).rejects.toBeInstanceOf(ShipmentLimitExceededException);
expect(createBooking).not.toHaveBeenCalled();
expect(countPaidShipmentsForOrganizationInYear).toHaveBeenCalledWith(
'org',
new Date().getFullYear()
);
});
it('preserves permitted uploads', async () => {
await request(app.getHttpServer())
.post('/csv-bookings')
.attach('documents', Buffer.from('document'), 'test.pdf')
.expect(201);
expect(createBooking).toHaveBeenCalledTimes(1);
});
});

View File

@ -1,189 +1,169 @@
/**
* Droits des personnes (RGPD) : accès et portabilité, effacement, consentement.
* GDPR Controller
*
* Endpoints for GDPR compliance (data export, deletion, consent)
*/
import {
BadRequestException,
Body,
Controller,
Delete,
Get,
Post,
Delete,
Body,
UseGuards,
HttpCode,
HttpStatus,
Post,
Req,
Res,
UseGuards,
Req,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiResponse } from '@nestjs/swagger';
import { Response, Request } from 'express';
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
import { RolesGuard } from '../guards/roles.guard';
import { Roles } from '../decorators/roles.decorator';
import { CurrentUser, UserPayload } from '../decorators/current-user.decorator';
import { GDPRService, GDPRDataExport, GDPRErasureReport } from '../services/gdpr.service';
import { CurrentUser } from '../decorators/current-user.decorator';
import { UserPayload } from '../decorators/current-user.decorator';
import { GDPRService } from '../services/gdpr.service';
import { UpdateConsentDto, ConsentResponseDto, WithdrawConsentDto } from '../dto/consent.dto';
import { DeleteAccountDto } from '../dto/delete-account.dto';
import { RetentionService, RetentionReport } from '../services/retention.service';
import { AdminContinuityService } from '../services/admin-continuity.service';
import { RETENTION_RULES } from '@domain/services/data-retention';
@ApiTags('GDPR')
@Controller('gdpr')
@UseGuards(JwtAuthGuard, RolesGuard)
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class GDPRController {
constructor(
private readonly gdprService: GDPRService,
private readonly retentionService: RetentionService,
private readonly adminContinuity: AdminContinuityService
) {}
constructor(private readonly gdprService: GDPRService) {}
/** Export de portabilité au format JSON (art. 20). */
/**
* Export user data (GDPR Right to Data Portability)
*/
@Get('export')
@ApiOperation({ summary: 'Exporter ses données personnelles (JSON)' })
@ApiResponse({ status: 200, description: 'Export produit' })
@ApiOperation({
summary: 'Export all user data',
description: 'Export all personal data in JSON format (GDPR Article 20)',
})
@ApiResponse({
status: 200,
description: 'Data export successful',
})
async exportData(@CurrentUser() user: UserPayload, @Res() res: Response): Promise<void> {
const data = await this.gdprService.exportUserData(user.id);
const day = new Date().toISOString().slice(0, 10);
const exportData = await this.gdprService.exportUserData(user.id);
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="xpeditis-donnees-${day}.json"`);
res.json(data);
// Set headers for file download
res.setHeader('Content-Type', 'application/json');
res.setHeader(
'Content-Disposition',
`attachment; filename="xpeditis-data-export-${user.id}-${Date.now()}.json"`
);
res.json(exportData);
}
/**
* Même export, en tableur.
*
* Il ne reprenait que le profil et le consentement cookies, ce qui donnait
* deux exports au contenu différent selon le format demandé. Il aplatit
* désormais l'export complet.
* Export user data as CSV
*/
@Get('export/csv')
@ApiOperation({ summary: 'Exporter ses données personnelles (CSV)' })
@ApiResponse({ status: 200, description: 'Export produit' })
@ApiOperation({
summary: 'Export user data as CSV',
description: 'Export personal data in CSV format for easy viewing',
})
@ApiResponse({
status: 200,
description: 'CSV export successful',
})
async exportDataCSV(@CurrentUser() user: UserPayload, @Res() res: Response): Promise<void> {
const data = await this.gdprService.exportUserData(user.id);
const day = new Date().toISOString().slice(0, 10);
const exportData = await this.gdprService.exportUserData(user.id);
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="xpeditis-donnees-${day}.csv"`);
// BOM : sans lui Excel lit l'UTF-8 comme du latin-1 et casse les accents.
res.send('' + toCsv(data));
}
// Convert to CSV (simplified version)
let csv = 'Category,Field,Value\n';
/**
* Effacement (art. 17).
*
* Renvoie le détail de ce qui a été effacé et de ce qui a été anonymisé.
* L'endpoint répondait 204 : la personne obtenait une page blanche pour
* seule réponse à une demande d'effacement, sans moyen de vérifier ce qui
* avait effectivement été traité.
*/
@Delete('delete-account')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Effacer son compte et ses données' })
@ApiResponse({ status: 200, description: 'Effacement appliqué' })
async deleteAccount(
@CurrentUser() user: UserPayload,
@Body() body: DeleteAccountDto
): Promise<GDPRErasureReport> {
// Confirmation par saisie de l'adresse : l'effacement est irréversible.
// `new Error` remontait ici en « Internal server error » — une erreur de
// saisie affichée comme une panne du service.
if (body.confirmEmail.trim().toLowerCase() !== user.email.toLowerCase()) {
throw new BadRequestException({
code: 'email_mismatch',
message: "L'adresse saisie ne correspond pas à celle du compte.",
// User data
Object.entries(exportData.userData).forEach(([key, value]) => {
csv += `User Data,${key},"${value}"\n`;
});
// Cookie consent data
if (exportData.cookieConsent) {
Object.entries(exportData.cookieConsent).forEach(([key, value]) => {
csv += `Cookie Consent,${key},"${value}"\n`;
});
}
// Le dernier administrateur actif ne peut pas effacer son propre compte :
// la plateforme resterait sans personne pour l'administrer.
await this.adminContinuity.assertCanErase(user.id);
// Set headers
res.setHeader('Content-Type', 'text/csv');
res.setHeader(
'Content-Disposition',
`attachment; filename="xpeditis-data-export-${user.id}-${Date.now()}.csv"`
);
return this.gdprService.deleteUserData(user.id, body.reason);
res.send(csv);
}
/**
* Politique de conservation appliquée (art. 13.2.a).
*
* L'information sur les durées doit être accessible à la personne, pas
* seulement écrite dans une politique de confidentialité : elle est servie
* ici depuis la règle réellement appliquée par le code.
* Delete user data (GDPR Right to Erasure)
*/
@Get('retention')
@ApiOperation({ summary: 'Durées de conservation appliquées' })
@ApiResponse({ status: 200, description: 'Politique de conservation' })
getRetentionPolicy(): { rules: typeof RETENTION_RULES } {
return { rules: RETENTION_RULES };
@Delete('delete-account')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({
summary: 'Delete user account and data',
description: 'Permanently delete or anonymize user data (GDPR Article 17)',
})
@ApiResponse({
status: 204,
description: 'Account deletion initiated',
})
async deleteAccount(
@CurrentUser() user: UserPayload,
@Body() body: { reason?: string; confirmEmail: string }
): Promise<void> {
// Verify email confirmation (security measure)
if (body.confirmEmail !== user.email) {
throw new Error('Email confirmation does not match');
}
await this.gdprService.deleteUserData(user.id, body.reason);
}
/**
* Journal des demandes de droits, pour la console de conformité.
*
* Réservé aux administrateurs : c'est l'élément qu'on présente à une
* autorité de contrôle pour démontrer que les demandes sont traitées
* (art. 5.2). Les effacements y figurent sous une adresse anonymisée.
* Record consent
*/
@Get('admin/requests')
@Roles('admin')
@ApiOperation({ summary: 'Journal des demandes de droits (administration)' })
@ApiResponse({ status: 200, description: 'Demandes récentes' })
async listRightsRequests(): Promise<{ requests: Record<string, unknown>[] }> {
return { requests: await this.gdprService.listRightsRequests() };
}
/**
* Ce que la purge supprimerait, sans rien supprimer.
*
* Une purge est irréversible : la console la montre avant de l'autoriser.
*/
@Get('admin/retention/preview')
@Roles('admin')
@ApiOperation({ summary: 'Aperçu de la purge de conservation (administration)' })
@ApiResponse({ status: 200, description: 'Lignes arrivées à échéance' })
async previewRetention(): Promise<RetentionReport> {
return this.retentionService.preview();
}
/**
* Déclenche la purge immédiatement.
*
* Le POST est délibéré : la purge supprime définitivement des lignes, elle
* ne peut pas être déclenchée par une simple navigation.
*/
@Post('admin/retention/purge')
@Roles('admin')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Appliquer les durées de conservation (administration)' })
@ApiResponse({ status: 200, description: 'Purge appliquée' })
async runRetention(): Promise<RetentionReport> {
return this.retentionService.purge();
}
/** Recueil du consentement cookies (art. 7). */
@Post('consent')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Enregistrer ses préférences de cookies' })
@ApiResponse({ status: 200, type: ConsentResponseDto })
@ApiOperation({
summary: 'Record user consent',
description: 'Record consent for cookies (GDPR Article 7)',
})
@ApiResponse({
status: 200,
description: 'Consent recorded',
type: ConsentResponseDto,
})
async recordConsent(
@CurrentUser() user: UserPayload,
@Body() body: UpdateConsentDto,
@Req() req: Request
): Promise<ConsentResponseDto> {
return this.gdprService.recordConsent(user.id, {
// Add IP and user agent from request if not provided
const consentData: UpdateConsentDto = {
...body,
ipAddress: body.ipAddress || req.ip || req.socket.remoteAddress,
userAgent: body.userAgent || req.headers['user-agent'],
});
};
return this.gdprService.recordConsent(user.id, consentData);
}
/** Retrait du consentement (art. 7.3). */
/**
* Withdraw consent
*/
@Post('consent/withdraw')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Retirer un consentement' })
@ApiResponse({ status: 200, type: ConsentResponseDto })
@ApiOperation({
summary: 'Withdraw consent',
description: 'Withdraw consent for functional, analytics, or marketing (GDPR Article 7.3)',
})
@ApiResponse({
status: 200,
description: 'Consent withdrawn',
type: ConsentResponseDto,
})
async withdrawConsent(
@CurrentUser() user: UserPayload,
@Body() body: WithdrawConsentDto
@ -191,51 +171,20 @@ export class GDPRController {
return this.gdprService.withdrawConsent(user.id, body.consentType);
}
/**
* Get consent status
*/
@Get('consent')
@ApiOperation({ summary: 'Consulter ses préférences de cookies' })
@ApiResponse({ status: 200, type: ConsentResponseDto })
@ApiOperation({
summary: 'Get current consent status',
description: 'Retrieve current consent preferences',
})
@ApiResponse({
status: 200,
description: 'Consent status retrieved',
type: ConsentResponseDto,
})
async getConsentStatus(@CurrentUser() user: UserPayload): Promise<ConsentResponseDto | null> {
return this.gdprService.getConsentStatus(user.id);
}
}
/** Échappement CSV : guillemets doublés, valeur toujours encadrée. */
const cell = (value: unknown): string => {
if (value === null || value === undefined) return '""';
const text = typeof value === 'object' ? JSON.stringify(value) : String(value);
return `"${text.replace(/"/g, '""')}"`;
};
/**
* Aplatit l'export en trois colonnes (section, champ, valeur).
*
* Un CSV par section serait plus lisible mais imposerait une archive ; la
* personne qui demande un CSV veut ouvrir un fichier, pas un zip.
*/
function toCsv(data: GDPRDataExport): string {
const lines = ['Section,Champ,Valeur'];
const flat = (section: string, record: Record<string, unknown>) => {
for (const [key, value] of Object.entries(record)) {
lines.push([cell(section), cell(key), cell(value)].join(','));
}
};
flat('Compte', data.userData);
if (data.organisation) flat('Organisation', data.organisation);
if (data.cookieConsent) flat('Consentement cookies', data.cookieConsent);
const collections: [string, Record<string, unknown>[]][] = [
['Réservations', data.bookings],
['Notifications', data.notifications],
['Conversations assistant', data.assistantConversations],
["Clés d'API", data.apiKeys],
['Journal d activite', data.activityLog],
];
for (const [section, rows] of collections) {
rows.forEach((row, index) => flat(`${section} ${index + 1}`, row));
}
return lines.join('\n');
}

View File

@ -119,7 +119,7 @@ export class InvitationsController {
description: 'Invitation expired or already used',
})
async verifyInvitation(@Param('token') token: string): Promise<InvitationResponseDto> {
this.logger.log('Verifying invitation token');
this.logger.log(`Verifying invitation token: ${token}`);
const invitation = await this.invitationService.verifyInvitation(token);

View File

@ -22,7 +22,6 @@ import { NotificationService } from '../services/notification.service';
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
import { CurrentUser, UserPayload } from '../decorators/current-user.decorator';
import { Notification } from '@domain/entities/notification.entity';
import { notificationTarget } from '@domain/services/notification-target';
class NotificationResponseDto {
id: string;
@ -152,7 +151,7 @@ export class NotificationsController {
throw new NotFoundException('Notification not found');
}
await this.notificationService.markAsRead(id, user.id);
await this.notificationService.markAsRead(id);
return { success: true };
}
@ -201,12 +200,7 @@ export class NotificationsController {
metadata: notification.metadata,
read: notification.read,
readAt: notification.readAt?.toISOString(),
// La destination est derivee du type et des metadonnees : les liens
// ecrits a la main visaient des routes inexistantes.
actionUrl:
notification.actionUrl ??
notificationTarget(notification.type, notification.metadata) ??
undefined,
actionUrl: notification.actionUrl,
createdAt: notification.createdAt.toISOString(),
};
}

View File

@ -1,67 +0,0 @@
import { ForbiddenException, NotFoundException } from '@nestjs/common';
import { Organization, OrganizationType } from '@domain/entities/organization.entity';
import { OrganizationRepository } from '@domain/ports/out/organization.repository';
import { UserRepository } from '@domain/ports/out/user.repository';
import { OrganizationsController } from './organizations.controller';
import { NotificationService } from '../services/notification.service';
import { UserPayload } from '../decorators/current-user.decorator';
describe('OrganizationsController tenant authorization', () => {
const actor = (role: string): UserPayload => ({
id: 'user-id',
email: 'manager@example.org',
role,
organizationId: 'own-org',
firstName: 'Test',
lastName: 'User',
});
const makeOrganization = (id: string) =>
Organization.create({
id,
name: 'Original',
type: OrganizationType.FREIGHT_FORWARDER,
address: { street: '1 rue Test', city: 'Paris', postalCode: '75001', country: 'FR' },
documents: [],
isActive: true,
});
const findById = jest.fn();
const save = jest.fn(async (organization: Organization) => organization);
const controller = new OrganizationsController(
{ findById, save } as unknown as OrganizationRepository,
{} as UserRepository,
{} as NotificationService
);
beforeEach(() => jest.clearAllMocks());
it.each(['MANAGER', 'manager', 'USER', 'VIEWER'])(
'rejects foreign organization for %s',
async role => {
const target = makeOrganization('other-org');
findById.mockResolvedValue(target);
await expect(
controller.updateOrganization(target.id, { name: 'Changed' }, actor(role))
).rejects.toBeInstanceOf(ForbiddenException);
expect(target.name).toBe('Original');
expect(save).not.toHaveBeenCalled();
}
);
it.each([
['MANAGER', 'own-org'],
['ADMIN', 'other-org'],
])('allows %s to update %s', async (role, id) => {
findById.mockResolvedValue(makeOrganization(id));
const result = await controller.updateOrganization(id, { name: 'Changed' }, actor(role));
expect(result.name).toBe('Changed');
expect(save).toHaveBeenCalledTimes(1);
});
it('preserves missing organization response', async () => {
findById.mockResolvedValue(null);
await expect(
controller.updateOrganization('missing', {}, actor('ADMIN'))
).rejects.toBeInstanceOf(NotFoundException);
expect(save).not.toHaveBeenCalled();
});
});

View File

@ -42,8 +42,10 @@ import {
ORGANIZATION_REPOSITORY,
} from '@domain/ports/out/organization.repository';
import { Organization, OrganizationType } from '@domain/entities/organization.entity';
import { UserRole } from '@domain/entities/user.entity';
import { NotificationType, NotificationPriority } from '@domain/entities/notification.entity';
import {
NotificationType,
NotificationPriority,
} from '@domain/entities/notification.entity';
import { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
import { RolesGuard } from '../guards/roles.guard';
@ -69,8 +71,7 @@ export class OrganizationsController {
private readonly logger = new Logger(OrganizationsController.name);
constructor(
@Inject(ORGANIZATION_REPOSITORY)
private readonly organizationRepository: OrganizationRepository,
@Inject(ORGANIZATION_REPOSITORY) private readonly organizationRepository: OrganizationRepository,
@Inject(USER_REPOSITORY) private readonly userRepository: UserRepository,
private readonly notificationService: NotificationService
) {}
@ -252,7 +253,7 @@ export class OrganizationsController {
}
// Authorization: Managers can only update their own organization
if (user.role !== UserRole.ADMIN && organization.id !== user.organizationId) {
if (user.role === 'manager' && organization.id !== user.organizationId) {
throw new ForbiddenException('You can only update your own organization');
}
@ -319,7 +320,9 @@ export class OrganizationsController {
})
@ApiResponse({ status: 200, description: 'Approval request sent to admins' })
@ApiResponse({ status: 400, description: 'No SIRET/SIREN registered or already verified' })
async requestSiretApproval(@CurrentUser() user: UserPayload): Promise<{ message: string }> {
async requestSiretApproval(
@CurrentUser() user: UserPayload
): Promise<{ message: string }> {
const organization = await this.organizationRepository.findById(user.organizationId);
if (!organization) {
throw new NotFoundException('Organization not found');
@ -357,6 +360,7 @@ export class OrganizationsController {
siren: organization.siren,
requestedBy: user.email,
},
actionUrl: `/dashboard/admin/organizations`,
})
)
);

View File

@ -33,7 +33,6 @@ import {
FilterOptionsDto,
AvailableOriginsDto,
AvailableDestinationsDto,
AvailableDirectionsDto,
RoutePortInfoDto,
} from '../dto/csv-rate-upload.dto';
import { CsvRateMapper } from '../mappers/csv-rate.mapper';
@ -174,7 +173,6 @@ export class RatesController {
weightKG: dto.weightKG,
containerType: dto.containerType,
hasDangerousGoods: dto.hasDangerousGoods ?? false,
direction: dto.direction,
filters: this.csvRateMapper.mapFiltersDtoToDomain(dto.filters),
};
@ -239,7 +237,6 @@ export class RatesController {
weightKG: dto.weightKG,
containerType: dto.containerType,
hasDangerousGoods: dto.hasDangerousGoods ?? false,
direction: dto.direction,
filters: this.csvRateMapper.mapFiltersDtoToDomain(dto.filters),
};
@ -263,42 +260,6 @@ export class RatesController {
}
}
/**
* Get the trade directions that currently have usable rate grids.
* Lets the booking wizard skip the import/export step when only one applies.
*/
@Get('available-routes/directions')
@UseGuards(JwtAuthGuard)
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: 'Get available trade directions',
description:
'Returns the trade directions (EXPORT / IMPORT) for which at least one usable rate grid exists. An empty or single-entry list means the direction choice can be skipped in the UI.',
})
@ApiResponse({
status: HttpStatus.OK,
description: 'List of available trade directions',
type: AvailableDirectionsDto,
})
@ApiResponse({
status: 401,
description: 'Unauthorized - missing or invalid token',
})
async getAvailableDirections(): Promise<AvailableDirectionsDto> {
this.logger.log('Fetching available trade directions from CSV rates');
try {
const directions = await this.csvRateSearchService.getAvailableDirections();
return { directions };
} catch (error: any) {
this.logger.error(
`Failed to fetch available directions: ${error?.message || 'Unknown error'}`,
error?.stack
);
throw error;
}
}
/**
* Get available origin ports from CSV rates
* Returns only ports that have routes defined in CSV files
@ -311,12 +272,6 @@ export class RatesController {
description:
'Returns list of origin ports that have shipping routes defined in CSV rate files. Use this to populate origin port selection dropdown.',
})
@ApiQuery({
name: 'direction',
required: false,
enum: ['EXPORT', 'IMPORT'],
description: 'Restrict to grids of this trade direction (EXPORT = French origins)',
})
@ApiResponse({
status: HttpStatus.OK,
description: 'List of available origin ports with details',
@ -326,16 +281,12 @@ export class RatesController {
status: 401,
description: 'Unauthorized - missing or invalid token',
})
async getAvailableOrigins(@Query('direction') direction?: string): Promise<AvailableOriginsDto> {
this.logger.log(
`Fetching available origin ports from CSV rates${direction ? ` (${direction})` : ''}`
);
async getAvailableOrigins(): Promise<AvailableOriginsDto> {
this.logger.log('Fetching available origin ports from CSV rates');
try {
// Get unique origin port codes from CSV rates
const originCodes = await this.csvRateSearchService.getAvailableOrigins(
this.parseDirection(direction)
);
const originCodes = await this.csvRateSearchService.getAvailableOrigins();
// Fetch port details from database
const ports = await this.portRepository.findByCodes(originCodes);
@ -409,18 +360,11 @@ export class RatesController {
status: 401,
description: 'Unauthorized - missing or invalid token',
})
@ApiQuery({
name: 'direction',
required: false,
enum: ['EXPORT', 'IMPORT'],
description: 'Restrict to grids of this trade direction (EXPORT = French origins)',
})
@ApiBadRequestResponse({
description: 'Origin port code is required',
})
async getAvailableDestinations(
@Query('origin') origin: string,
@Query('direction') direction?: string
@Query('origin') origin: string
): Promise<AvailableDestinationsDto> {
this.logger.log(`Fetching available destinations for origin: ${origin}`);
@ -430,10 +374,7 @@ export class RatesController {
try {
// Get destination port codes for this origin from CSV rates
const destinationCodes = await this.csvRateSearchService.getAvailableDestinations(
origin,
this.parseDirection(direction)
);
const destinationCodes = await this.csvRateSearchService.getAvailableDestinations(origin);
// Fetch port details from database
const ports = await this.portRepository.findByCodes(destinationCodes);
@ -553,10 +494,4 @@ export class RatesController {
throw error;
}
}
/** Normalize the direction query param; anything unrecognized means "no filter". */
private parseDirection(direction?: string): 'EXPORT' | 'IMPORT' | undefined {
const upper = direction?.trim().toUpperCase();
return upper === 'EXPORT' || upper === 'IMPORT' ? upper : undefined;
}
}

View File

@ -24,8 +24,6 @@ import {
Req,
Inject,
ForbiddenException,
BadRequestException,
InternalServerErrorException,
} from '@nestjs/common';
import {
ApiTags,
@ -271,7 +269,7 @@ export class SubscriptionsController {
const rawBody = req.rawBody;
if (!rawBody) {
this.logger.error('No raw body found in request');
throw new BadRequestException('Missing webhook body');
return { received: false };
}
try {
@ -279,7 +277,7 @@ export class SubscriptionsController {
return { received: true };
} catch (error) {
this.logger.error('Webhook processing failed', error);
throw new InternalServerErrorException('Webhook processing failed');
return { received: false };
}
}
}

View File

@ -1,96 +0,0 @@
import { Logger } from '@nestjs/common';
import { UsersController } from './users.controller';
/**
* Creation d'un compte depuis le panel admin : l'email d'acces n'etait jamais
* envoye (TODO), et le mot de passe temporaire etait ecrit dans les journaux.
*/
const ADMIN = {
id: 'admin-1',
email: 'admin@xpeditis.com',
role: 'ADMIN',
organizationId: 'org-1',
} as never;
function buildController(options: { emailFails?: boolean } = {}) {
const userRepository = {
findByEmail: jest.fn(async () => null),
save: jest.fn(async (user: unknown) => user),
findById: jest.fn(async () => ({ firstName: 'Paul', lastName: 'Martin' })),
};
const emailPort = {
sendUserInvitation: jest.fn(async () => {
if (options.emailFails) throw new Error('550 sender not valid');
}),
};
const organizationRepository = { findById: jest.fn(async () => ({ name: 'Acme' })) };
const unused = {} as never;
const controller = new UsersController(
userRepository as never,
unused,
unused,
unused,
emailPort as never,
organizationRepository as never
);
return { controller, emailPort };
}
const dto = {
email: 'marie@acme.test',
firstName: 'Marie',
lastName: 'Dupont',
role: 'USER',
organizationId: '550e8400-e29b-41d4-a716-446655440000',
password: 'Temp-Password-42',
} as never;
describe('UsersController.createUser — email d’acces', () => {
let logs: string[];
beforeEach(() => {
logs = [];
const capture = (message: unknown) => {
logs.push(String(message));
};
jest.spyOn(Logger.prototype, 'log').mockImplementation(capture);
jest.spyOn(Logger.prototype, 'warn').mockImplementation(capture);
jest.spyOn(Logger.prototype, 'error').mockImplementation(capture);
});
afterEach(() => jest.restoreAllMocks());
it("envoie l'email d'acces au compte cree", async () => {
const { controller, emailPort } = buildController();
const result = await controller.createUser(dto, ADMIN);
expect(emailPort.sendUserInvitation).toHaveBeenCalledWith(
'marie@acme.test',
'Acme',
'Paul Martin',
'Temp-Password-42'
);
expect(result.invitationEmailSent).toBe(true);
}, 20000);
it("n'ecrit jamais le mot de passe temporaire dans les journaux", async () => {
const { controller } = buildController();
await controller.createUser(dto, ADMIN);
expect(logs.join('\n')).not.toContain('Temp-Password-42');
}, 20000);
it("cree le compte meme si l'email echoue, et le signale", async () => {
const { controller } = buildController({ emailFails: true });
const result = await controller.createUser(dto, ADMIN);
expect(result.email).toBe('marie@acme.test');
expect(result.invitationEmailSent).toBe(false);
expect(logs.join('\n')).not.toContain('Temp-Password-42');
}, 20000);
});

View File

@ -52,14 +52,6 @@ import { v4 as uuidv4 } from 'uuid';
import * as argon2 from 'argon2';
import * as crypto from 'crypto';
import { SubscriptionService } from '../services/subscription.service';
import { UserDeletionService } from '../services/user-deletion.service';
import { AdminContinuityService } from '../services/admin-continuity.service';
import { EmailPort, EMAIL_PORT } from '@domain/ports/out/email.port';
import {
OrganizationRepository,
ORGANIZATION_REPOSITORY,
} from '@domain/ports/out/organization.repository';
import { isAnonymisedEmail } from '@domain/services/data-retention';
/**
* Users Controller
@ -82,12 +74,7 @@ export class UsersController {
constructor(
@Inject(USER_REPOSITORY) private readonly userRepository: UserRepository,
private readonly subscriptionService: SubscriptionService,
private readonly userDeletionService: UserDeletionService,
private readonly adminContinuity: AdminContinuityService,
@Inject(EMAIL_PORT) private readonly emailPort: EmailPort,
@Inject(ORGANIZATION_REPOSITORY)
private readonly organizationRepository: OrganizationRepository
private readonly subscriptionService: SubscriptionService
) {}
/**
@ -124,7 +111,7 @@ export class UsersController {
async createUser(
@Body() dto: CreateUserDto,
@CurrentUser() user: UserPayload
): Promise<UserResponseDto & { invitationEmailSent: boolean }> {
): Promise<UserResponseDto> {
this.logger.log(`[User: ${user.email}] Creating user: ${dto.email} (${dto.role})`);
// Authorization: Only ADMIN can assign ADMIN role
@ -173,44 +160,12 @@ export class UsersController {
this.logger.log(`User created successfully: ${savedUser.id}`);
// L'email d'accès n'etait jamais envoye (TODO), et le mot de passe
// temporaire etait ecrit en clair dans les journaux. Il part desormais par
// email, et n'apparait plus nulle part ailleurs.
const invitationEmailSent = await this.sendAccountCreatedEmail(savedUser, tempPassword, user);
return { ...UserMapper.toDto(savedUser), invitationEmailSent };
}
/**
* Envoie au nouveau compte ses identifiants et le lien de connexion.
* Un echec n'annule pas la creation : il est signale a l'administrateur.
*/
private async sendAccountCreatedEmail(
newUser: User,
tempPassword: string,
creator: UserPayload
): Promise<boolean> {
try {
const [organization, creatorAccount] = await Promise.all([
this.organizationRepository.findById(newUser.organizationId),
this.userRepository.findById(creator.id),
]);
const inviterName = creatorAccount
? `${creatorAccount.firstName} ${creatorAccount.lastName}`.trim()
: creator.email;
await this.emailPort.sendUserInvitation(
newUser.email,
organization?.name ?? 'Xpeditis',
inviterName || creator.email,
tempPassword
// TODO: Send invitation email with temporary password
this.logger.warn(
`TODO: Send invitation email to ${dto.email} with temp password: ${tempPassword}`
);
this.logger.log(`Access email sent to new user ${newUser.email}`);
return true;
} catch (error: unknown) {
this.logger.error('User created but the access email failed');
return false;
}
return UserMapper.toDto(savedUser);
}
/**
@ -298,10 +253,6 @@ export class UsersController {
throw new BadRequestException('You cannot change your own role');
}
if (user.role === DomainUserRole.ADMIN && currentUser.role !== DomainUserRole.ADMIN) {
throw new ForbiddenException('Only platform administrators can update ADMIN users');
}
// Authorization: Only ADMIN can assign ADMIN role
if (dto.role === 'ADMIN' && currentUser.role !== 'ADMIN') {
throw new ForbiddenException('Only platform administrators can assign ADMIN role');
@ -312,13 +263,6 @@ export class UsersController {
throw new ForbiddenException('You can only update users in your own organization');
}
// At least one active admin must remain. Checked before any write — the
// license would otherwise be revoked for a change that is then refused.
await this.adminContinuity.assertKeepsAnActiveAdmin(user, {
role: dto.role ?? user.role,
isActive: dto.isActive ?? user.isActive,
});
// Update fields
if (dto.firstName) {
user.updateFirstName(dto.firstName);
@ -369,10 +313,7 @@ export class UsersController {
@Roles('admin')
@ApiOperation({
summary: 'Delete user',
description:
'Erase a user (any role, including another ADMIN): personal data is deleted or anonymised, ' +
'the account is disabled and its license revoked. Bookings are kept. Admin only; ' +
'an admin cannot delete their own account here, nor the last active admin.',
description: 'Deactivate a user account. Admin only.',
})
@ApiParam({
name: 'id',
@ -395,8 +336,17 @@ export class UsersController {
): Promise<void> {
this.logger.log(`[Admin: ${currentUser.email}] Deleting user: ${id}`);
// GDPR erasure (bookings kept) + license revocation — see UserDeletionService
await this.userDeletionService.deleteByAdmin(id, currentUser);
const user = await this.userRepository.findById(id);
if (!user) {
throw new NotFoundException(`User ${id} not found`);
}
// Revoke license before deleting user
await this.subscriptionService.revokeLicense(id);
this.logger.log(`License revoked for user being deleted: ${id}`);
// Permanently delete user from database
await this.userRepository.deleteById(id);
this.logger.log(`User deleted successfully: ${id}`);
}
@ -448,11 +398,7 @@ export class UsersController {
this.logger.log(
`[User: ${currentUser.email}] Fetching users from organization: ${currentUser.organizationId}`
);
// Erased accounts stay in the table (their bookings reference them) but are
// no longer users: hide them from the list.
let users = (await this.userRepository.findByOrganization(currentUser.organizationId)).filter(
u => !isAnonymisedEmail(u.email)
);
let users = await this.userRepository.findByOrganization(currentUser.organizationId);
// Security: Non-admin users cannot see ADMIN users
if (currentUser.role !== 'ADMIN') {

View File

@ -1,88 +0,0 @@
import { ForbiddenException, Logger } from '@nestjs/common';
import { User, UserRole } from '@domain/entities/user.entity';
import { UserRepository } from '@domain/ports/out/user.repository';
import { UsersController } from './users.controller';
import { SubscriptionService } from '../services/subscription.service';
import { UserPayload } from '../decorators/current-user.decorator';
import { UserRole as DtoUserRole } from '../dto/user.dto';
describe('administrator target protection', () => {
it('does not log a temporary password when creating an account', async () => {
const log = jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
try {
const controller = new UsersController(
{
findByEmail: async () => null,
save: async (user: User) => user,
} as unknown as UserRepository,
{} as SubscriptionService,
{} as never,
{ assertKeepsAnActiveAdmin: jest.fn() } as never,
{ sendUserInvitation: jest.fn().mockResolvedValue(undefined) } as never,
{ findById: jest.fn().mockResolvedValue(null) } as never
);
await controller.createUser(
{
email: 'new@example.org',
firstName: 'New',
lastName: 'User',
organizationId: 'org-1',
role: DtoUserRole.USER,
password: 'test-only-Temporary-password-42',
},
{
id: 'admin',
email: 'admin@example.org',
role: 'ADMIN',
organizationId: 'org-1',
firstName: 'A',
lastName: 'B',
}
);
expect(JSON.stringify([...log.mock.calls, ...warn.mock.calls])).not.toContain(
'test-only-Temporary-password-42'
);
} finally {
log.mockRestore();
warn.mockRestore();
}
});
const actor: UserPayload = {
id: 'manager',
role: 'MANAGER',
organizationId: 'org-1',
email: 'manager@example.org',
firstName: 'Test',
lastName: 'Manager',
};
it.each([UserRole.ADMIN, UserRole.USER])('enforces target hierarchy for %s', async role => {
const user = User.create({
id: 'target',
role,
organizationId: actor.organizationId,
email: 'target@example.org',
firstName: 'Original',
lastName: 'User',
passwordHash: 'test-hash',
});
const save = jest.fn(async () => user);
const controller = new UsersController(
{ findById: jest.fn(async () => user), save } as unknown as UserRepository,
{} as SubscriptionService,
{} as never,
{ assertKeepsAnActiveAdmin: jest.fn() } as never,
{ sendUserInvitation: jest.fn().mockResolvedValue(undefined) } as never,
{ findById: jest.fn().mockResolvedValue(null) } as never
);
const result = controller.updateUser(user.id, { firstName: 'Changed' }, actor);
if (role === UserRole.ADMIN) {
await expect(result).rejects.toBeInstanceOf(ForbiddenException);
expect(save).not.toHaveBeenCalled();
expect(user.firstName).toBe('Original');
} else {
await expect(result).resolves.toHaveProperty('firstName', 'Changed');
expect(save).toHaveBeenCalled();
}
});
});

View File

@ -1,28 +0,0 @@
import 'reflect-metadata';
import { I18nValidationPipe } from 'nestjs-i18n';
import { WebhooksController } from './webhooks.controller';
describe('Current webhook configuration boundary (OBS-02)', () => {
it.each([
['createWebhook', 0],
['updateWebhook', 1],
])('%s rejects an unvalidated destination at the global pipe', async (method, index) => {
const types = Reflect.getMetadata(
'design:paramtypes',
WebhooksController.prototype,
method as string
);
const pipe = new I18nValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: { enableImplicitConversion: true },
});
await expect(
pipe.transform(
{ url: 'http://127.0.0.1/internal', events: ['booking.created'] },
{ type: 'body', metatype: types[index as number] }
)
).rejects.toMatchObject({ status: 400 });
});
});

View File

@ -10,64 +10,12 @@ import {
MaxLength,
MinLength,
Matches,
ValidateIf,
ValidateNested,
} from 'class-validator';
import { Type } from 'class-transformer';
import {
BlogPostStatus,
type BlogPostCategory,
type BlogFaqItem,
} from '@domain/entities/blog-post.entity';
import { BlogPostStatus, type BlogPostCategory } from '@domain/entities/blog-post.entity';
const CATEGORIES: BlogPostCategory[] = ['industry', 'technology', 'guides', 'news'];
export class BlogFaqItemDto implements BlogFaqItem {
@ApiProperty()
@IsString()
@IsNotEmpty()
@MaxLength(500)
question: string;
@ApiProperty()
@IsString()
@IsNotEmpty()
@MaxLength(4000)
answer: string;
}
/**
* GEO (Generative Engine Optimisation) fields, shared by create/update DTOs.
*/
export class BlogGeoFields {
@ApiPropertyOptional({ description: 'AI summary / TL;DR of the article' })
@IsOptional()
@ValidateIf((_, value) => value !== null)
@IsString()
@MaxLength(2000)
aiSummary?: string | null;
@ApiPropertyOptional({ type: [BlogFaqItemDto], description: 'FAQ (question/answer pairs)' })
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => BlogFaqItemDto)
faq?: BlogFaqItemDto[];
@ApiPropertyOptional({ type: [String], description: 'Key takeaways' })
@IsOptional()
@IsArray()
@IsString({ each: true })
keyTakeaways?: string[];
@ApiPropertyOptional({ type: [String], description: 'Related entities / topics' })
@IsOptional()
@IsArray()
@IsString({ each: true })
aiEntities?: string[];
}
export class CreateBlogPostDto extends BlogGeoFields {
export class CreateBlogPostDto {
@ApiProperty()
@IsString()
@IsNotEmpty()
@ -146,7 +94,7 @@ export class CreateBlogPostDto extends BlogGeoFields {
secondaryKeywords?: string[];
}
export class UpdateBlogPostDto extends BlogGeoFields {
export class UpdateBlogPostDto {
@ApiPropertyOptional()
@IsOptional()
@IsString()
@ -173,15 +121,11 @@ export class UpdateBlogPostDto extends BlogGeoFields {
@IsString()
content?: string;
@ApiPropertyOptional({
nullable: true,
description: 'Cover image URL. Pass null to remove the current cover image.',
})
@ApiPropertyOptional()
@IsOptional()
@ValidateIf((_, value) => value !== null)
@IsString()
@MaxLength(500)
coverImageUrl?: string | null;
coverImageUrl?: string;
@ApiPropertyOptional({ enum: CATEGORIES })
@IsOptional()
@ -257,10 +201,6 @@ export class BlogPostResponseDto {
@ApiPropertyOptional() metaDescription?: string;
@ApiPropertyOptional() primaryKeyword?: string;
@ApiProperty({ type: [String] }) secondaryKeywords: string[];
@ApiPropertyOptional() aiSummary?: string | null;
@ApiProperty({ type: [BlogFaqItemDto] }) faq: BlogFaqItemDto[];
@ApiProperty({ type: [String] }) keyTakeaways: string[];
@ApiProperty({ type: [String] }) aiEntities: string[];
@ApiProperty() createdAt: Date;
@ApiProperty() updatedAt: Date;
}

View File

@ -6,7 +6,6 @@ import {
Min,
IsOptional,
IsEnum,
IsObject,
MinLength,
MaxLength,
} from 'class-validator';
@ -105,44 +104,6 @@ export class CreateCsvBookingDto {
@IsEnum(['USD', 'EUR'])
primaryCurrency: string;
@ApiPropertyOptional({
description: 'Freight charge total (in freightCurrency)',
example: 420.0,
minimum: 0,
})
@IsOptional()
@IsNumber()
@Min(0)
freightTotal?: number;
@ApiPropertyOptional({
description: 'Currency of the freight charge',
enum: ['USD', 'EUR'],
example: 'USD',
})
@IsOptional()
@IsEnum(['USD', 'EUR'])
freightCurrency?: string;
@ApiPropertyOptional({
description: 'FOB charges total (in fobCurrency)',
example: 245.0,
minimum: 0,
})
@IsOptional()
@IsNumber()
@Min(0)
fobTotal?: number;
@ApiPropertyOptional({
description: 'Currency of the FOB charges',
enum: ['USD', 'EUR'],
example: 'EUR',
})
@IsOptional()
@IsEnum(['USD', 'EUR'])
fobCurrency?: string;
@ApiProperty({
description: 'Transit time in days',
example: 28,
@ -170,203 +131,10 @@ export class CreateCsvBookingDto {
@MaxLength(1000)
notes?: string;
@ApiPropertyOptional({
description:
'Selected options & services as a JSON string (multipart), e.g. {"insurance":true}',
example: '{"insurance":true,"customsStop":true}',
})
@IsOptional()
@IsString()
@MaxLength(2000)
options?: string;
// Documents will be handled via file upload interceptor
// Not included in DTO validation but processed separately
}
/**
* Update CSV Booking Details DTO
*
* Editable cargo characteristics before payment. Carrier, route and price are
* derived from the selected rate and cannot be changed here.
*/
export class UpdateCsvBookingDetailsDto {
@ApiPropertyOptional({ description: 'Total volume in cubic meters (CBM)', example: 12.5 })
@IsOptional()
@IsNumber()
@Min(0.01)
volumeCBM?: number;
@ApiPropertyOptional({ description: 'Total weight in kilograms', example: 1500 })
@IsOptional()
@IsNumber()
@Min(0.01)
weightKG?: number;
@ApiPropertyOptional({ description: 'Number of pallets', example: 5 })
@IsOptional()
@IsNumber()
@Min(0)
palletCount?: number;
@ApiPropertyOptional({ description: 'Additional notes', example: 'Please handle with care' })
@IsOptional()
@IsString()
@MaxLength(2000)
notes?: string;
// Recomputed pricing (sent when cargo details change). Optional; when omitted
// the price is left unchanged.
@ApiPropertyOptional({ description: 'Recomputed total price in USD' })
@IsOptional()
@IsNumber()
@Min(0)
priceUSD?: number;
@ApiPropertyOptional({ description: 'Recomputed total price in EUR' })
@IsOptional()
@IsNumber()
@Min(0)
priceEUR?: number;
@ApiPropertyOptional({ description: 'Primary currency (USD/EUR)' })
@IsOptional()
@IsString()
@MaxLength(3)
primaryCurrency?: string;
@ApiPropertyOptional({ description: 'Recomputed freight total' })
@IsOptional()
@IsNumber()
@Min(0)
freightTotal?: number;
@ApiPropertyOptional({ description: 'Freight currency' })
@IsOptional()
@IsString()
@MaxLength(3)
freightCurrency?: string;
@ApiPropertyOptional({ description: 'Recomputed FOB total' })
@IsOptional()
@IsNumber()
@Min(0)
fobTotal?: number;
@ApiPropertyOptional({ description: 'FOB currency' })
@IsOptional()
@IsString()
@MaxLength(3)
fobCurrency?: string;
}
/**
* Update CSV Booking Rate DTO
*
* Full re-selection of a rate before payment (carrier + route + container +
* transit + cargo + price). Used when the user re-runs the search and picks a
* (possibly different) rate for a QUOTE booking.
*/
export class UpdateCsvBookingRateDto {
@ApiProperty({ example: 'SSC Consolidation' })
@IsString()
@MinLength(2)
@MaxLength(200)
carrierName: string;
@ApiProperty({ example: 'bookings@example.com' })
@IsEmail()
carrierEmail: string;
@ApiProperty({ example: 'FRLIO' })
@IsString()
@MaxLength(5)
origin: string;
@ApiProperty({ example: 'AUADL' })
@IsString()
@MaxLength(5)
destination: string;
@ApiProperty({ example: 'LCL' })
@IsString()
@MaxLength(50)
containerType: string;
@ApiProperty({ example: 46 })
@IsNumber()
@Min(1)
transitDays: number;
@ApiProperty({ example: 12.5 })
@IsNumber()
@Min(0.01)
volumeCBM: number;
@ApiProperty({ example: 1500 })
@IsNumber()
@Min(0.01)
weightKG: number;
@ApiProperty({ example: 5 })
@IsNumber()
@Min(0)
palletCount: number;
@ApiProperty({ example: 0 })
@IsNumber()
@Min(0)
priceUSD: number;
@ApiProperty({ example: 258 })
@IsNumber()
@Min(0)
priceEUR: number;
@ApiProperty({ example: 'EUR' })
@IsString()
@MaxLength(3)
primaryCurrency: string;
@ApiPropertyOptional({ example: 150 })
@IsOptional()
@IsNumber()
@Min(0)
freightTotal?: number;
@ApiPropertyOptional({ example: 'EUR' })
@IsOptional()
@IsString()
@MaxLength(3)
freightCurrency?: string;
@ApiPropertyOptional({ example: 108 })
@IsOptional()
@IsNumber()
@Min(0)
fobTotal?: number;
@ApiPropertyOptional({ example: 'EUR' })
@IsOptional()
@IsString()
@MaxLength(3)
fobCurrency?: string;
@ApiPropertyOptional({ example: 'Handle with care' })
@IsOptional()
@IsString()
@MaxLength(2000)
notes?: string;
@ApiPropertyOptional({
description: 'Selected options & services (customs, insurance, DG, handling…)',
example: { insurance: true, customsStop: true },
})
@IsOptional()
@IsObject()
options?: Record<string, boolean>;
}
/**
* Document DTO for response
*/
@ -451,23 +219,6 @@ export class CsvBookingResponseDto {
})
organizationId: string;
@ApiPropertyOptional({
description:
'Full name of the user who created the booking (organization listing). ' +
'Null when that account has been deleted.',
example: 'Marie Dupont',
nullable: true,
})
createdByName?: string | null;
@ApiPropertyOptional({
description:
'Bank transfer validation only: whether the booking request email reached the SMTP relay. ' +
'When false, the booking is active but the admin should resend the carrier email.',
example: true,
})
carrierEmailSent?: boolean;
@ApiProperty({
description: 'Carrier/Company name',
example: 'SSC Consolidation',
@ -543,8 +294,8 @@ export class CsvBookingResponseDto {
@ApiProperty({
description: 'Booking status',
enum: ['QUOTE', 'PENDING', 'ACCEPTED', 'REJECTED', 'CANCELLED'],
example: 'QUOTE',
enum: ['PENDING_PAYMENT', 'PENDING', 'ACCEPTED', 'REJECTED', 'CANCELLED'],
example: 'PENDING_PAYMENT',
})
status: string;
@ -554,6 +305,12 @@ export class CsvBookingResponseDto {
})
documents: CsvBookingDocumentDto[];
@ApiProperty({
description: 'Confirmation token for accept/reject actions',
example: 'abc123-def456-ghi789',
})
confirmationToken: string;
@ApiProperty({
description: 'Booking request timestamp',
example: '2025-10-23T14:30:00Z',
@ -608,36 +365,6 @@ export class CsvBookingResponseDto {
example: 313.27,
})
commissionAmountEur?: number;
@ApiPropertyOptional({
description: 'Freight charge total (in freightCurrency)',
example: 420.0,
})
freightTotal?: number;
@ApiPropertyOptional({
description: 'Currency of the freight charge',
example: 'USD',
})
freightCurrency?: string;
@ApiPropertyOptional({
description: 'FOB charges total (in fobCurrency)',
example: 245.0,
})
fobTotal?: number;
@ApiPropertyOptional({
description: 'Currency of the FOB charges',
example: 'EUR',
})
fobCurrency?: string;
@ApiPropertyOptional({
description: 'Selected options & services (customs, insurance, DG, handling…)',
example: { insurance: true },
})
options?: Record<string, boolean>;
}
/**
@ -700,10 +427,10 @@ export class CsvBookingListResponseDto {
*/
export class CsvBookingStatsDto {
@ApiProperty({
description: 'Number of quotes (bookings whose booking fee is unpaid)',
description: 'Number of bookings awaiting payment',
example: 1,
})
quote: number;
pendingPayment: number;
@ApiProperty({
description: 'Number of pending bookings',

View File

@ -7,7 +7,6 @@ import {
IsOptional,
ValidateNested,
IsBoolean,
IsIn,
} from 'class-validator';
import { Type } from 'class-transformer';
import { RateSearchFiltersDto } from './rate-search-filters.dto';
@ -45,15 +44,6 @@ export class CsvRateSearchDto {
@IsBoolean()
hasDangerousGoods?: boolean;
@ApiPropertyOptional({
description: 'Trade direction: EXPORT (French origin) or IMPORT (French destination)',
enum: ['EXPORT', 'IMPORT'],
example: 'EXPORT',
})
@IsOptional()
@IsIn(['EXPORT', 'IMPORT'])
direction?: 'EXPORT' | 'IMPORT';
@ApiPropertyOptional({ description: 'Advanced filters', type: RateSearchFiltersDto })
@IsOptional()
@ValidateNested()

View File

@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, MaxLength, IsEmail, IsOptional, IsIn } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString, MaxLength, IsEmail } from 'class-validator';
/**
* CSV Rate Upload DTO
@ -27,16 +27,6 @@ export class CsvRateUploadDto {
@MaxLength(255)
companyEmail: string;
@ApiPropertyOptional({
description:
'Trade direction of the grid: EXPORT (French origins) or IMPORT (French destinations). Defaults to EXPORT.',
enum: ['EXPORT', 'IMPORT'],
example: 'EXPORT',
})
@IsOptional()
@IsIn(['EXPORT', 'IMPORT'])
direction?: 'EXPORT' | 'IMPORT';
@ApiProperty({
description: 'CSV file containing shipping rates',
type: 'string',
@ -100,17 +90,10 @@ export class CsvRateConfigDto {
@ApiProperty({
description: 'CSV file path',
example: 'ssc-consolidation-export.csv',
example: 'ssc-consolidation.csv',
})
csvFilePath: string;
@ApiProperty({
description: 'Trade direction of the grid',
enum: ['EXPORT', 'IMPORT'],
example: 'EXPORT',
})
direction: 'EXPORT' | 'IMPORT';
@ApiProperty({
description: 'Integration type',
enum: ['CSV_ONLY', 'CSV_AND_API'],
@ -201,19 +184,6 @@ export class AvailableCompaniesDto {
total: number;
}
/**
* Available Directions Response DTO
*/
export class AvailableDirectionsDto {
@ApiProperty({
description: 'Trade directions that currently have usable rate grids',
type: [String],
enum: ['EXPORT', 'IMPORT'],
example: ['EXPORT'],
})
directions: ('EXPORT' | 'IMPORT')[];
}
/**
* Filter Options Response DTO
*/

View File

@ -1,27 +0,0 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsEmail, IsOptional, IsString, MaxLength } from 'class-validator';
/**
* Demande d'effacement (RGPD art. 17).
*
* Le corps de la requête n'était pas validé : `confirmEmail` arrivait en
* `any`, et une valeur absente déclenchait une comparaison sur `undefined`
* remontée en erreur 500.
*/
export class DeleteAccountDto {
@ApiProperty({
example: 'personne@example.com',
description: 'Adresse du compte, ressaisie pour confirmer un acte irréversible',
})
@IsEmail({}, { message: 'Une adresse email valide est requise pour confirmer.' })
confirmEmail: string;
@ApiPropertyOptional({
example: "Je n'utilise plus le service",
description: "Motif facultatif. La personne n'a pas à le justifier (art. 17.1).",
})
@IsOptional()
@IsString()
@MaxLength(500)
reason?: string;
}

View File

@ -207,14 +207,14 @@ export class PlanDetailsDto {
maxLicenses: number;
@ApiProperty({
example: 299,
example: 249,
description: 'Monthly price in EUR',
})
monthlyPriceEur: number;
@ApiProperty({
example: 3289,
description: 'Yearly price in EUR (11 months — 1 month deducted)',
example: 2739,
description: 'Yearly price in EUR (11 months)',
})
yearlyPriceEur: number;
@ -225,10 +225,10 @@ export class PlanDetailsDto {
maxShipmentsPerYear: number;
@ApiProperty({
example: 10,
description: 'Per-booking fee in EUR (-1 for custom / on quote)',
example: 3,
description: 'Commission rate percentage on shipments',
})
bookingFeeEur: number;
commissionRatePercent: number;
@ApiProperty({
example: 'email',

View File

@ -1,4 +1,3 @@
import { safeRequestRoute } from '../logging/safe-http-log';
/**
* DomainExceptionFilter
*
@ -39,7 +38,7 @@ export class DomainExceptionFilter implements ExceptionFilter {
error: exception.name,
message: typeof translated === 'string' ? translated : exception.message,
timestamp: new Date().toISOString(),
path: safeRequestRoute(request),
path: request.url,
});
}
}

View File

@ -1,196 +0,0 @@
import { ArgumentsHost, BadRequestException, HttpStatus, NotFoundException } from '@nestjs/common';
import { UnhandledExceptionFilter, isDependencyUnavailable } from './unhandled-exception.filter';
const i18n = {
translate: jest.fn((key: string) => `translated:${key}`),
};
/** Le double garde son type ; seul le passage au filtre est force. */
const filterWith = () => new UnhandledExceptionFilter(i18n as never);
function hostFor(headers: Record<string, string> = {}, url = '/api/v1/auth/register') {
const json = jest.fn();
const status = jest.fn().mockReturnValue({ json });
const host = {
switchToHttp: () => ({
getResponse: () => ({ status }),
getRequest: () => ({ url, method: 'POST', headers }),
}),
} as unknown as ArgumentsHost;
return { host, status, json, body: () => json.mock.calls[0][0] };
}
describe('UnhandledExceptionFilter', () => {
const filter = filterWith();
beforeEach(() => jest.clearAllMocks());
it('lets a deliberate HTTP response through untouched', () => {
const { host, status, body } = hostFor();
filter.catch(new NotFoundException('Réservation introuvable'), host);
expect(status).toHaveBeenCalledWith(HttpStatus.NOT_FOUND);
expect(body()).toMatchObject({ message: 'Réservation introuvable' });
});
it('keeps a validation response intact, fields included', () => {
const { host, status, body } = hostFor();
filter.catch(new BadRequestException({ message: ['email must be an email'] }), host);
expect(status).toHaveBeenCalledWith(HttpStatus.BAD_REQUEST);
expect(body()).toMatchObject({ message: ['email must be an email'] });
});
it('turns a database outage into a 503 that invites a retry', () => {
// C'est l'erreur exacte qu'a renvoyee l'inscription pendant que PostgreSQL
// redemarrait, disque plein : un 500 laissait croire a une donnee refusee.
const { host, status, body } = hostFor();
filter.catch(new Error('the database system is not yet accepting connections'), host);
expect(status).toHaveBeenCalledWith(HttpStatus.SERVICE_UNAVAILABLE);
expect(body()).toMatchObject({
code: 'service_unavailable',
message: 'translated:error.SERVICE_UNAVAILABLE',
});
});
it('gives an unexpected failure a reference instead of a stack trace', () => {
const { host, status, body } = hostFor();
filter.catch(new TypeError("Cannot read properties of undefined (reading 'id')"), host);
expect(status).toHaveBeenCalledWith(HttpStatus.INTERNAL_SERVER_ERROR);
const payload = body();
expect(payload).toMatchObject({
code: 'unexpected_error',
message: 'translated:error.UNEXPECTED_ERROR',
});
expect(payload.reference).toMatch(/^[0-9a-f]{8}$/);
// Le detail technique reste dans le journal, jamais dans la reponse.
expect(JSON.stringify(payload)).not.toContain('Cannot read properties');
expect(JSON.stringify(payload)).not.toContain('stack');
});
it('turns the last-active-admin trigger refusal into an explained 409', () => {
// Deux admins qui se suppriment l'un l'autre au meme instant : le controle
// applicatif passe des deux cotes, le declencheur PostgreSQL refuse le second.
const { host, status, body } = hostFor({}, '/api/v1/admin/users/abc');
const triggerError = Object.assign(
new Error('Au moins un administrateur actif doit subsister'),
{
code: 'XP001',
}
);
filter.catch(triggerError, host);
expect(status).toHaveBeenCalledWith(HttpStatus.CONFLICT);
expect(body()).toMatchObject({
code: 'last_active_admin',
message: 'translated:error.LAST_ACTIVE_ADMIN',
});
expect(body().reference).toBeUndefined();
});
it('recognises the trigger refusal through driverError as well', () => {
const { host, status } = hostFor();
filter.catch(
Object.assign(new Error('query failed'), { driverError: { code: 'XP001' } }),
host
);
expect(status).toHaveBeenCalledWith(HttpStatus.CONFLICT);
});
it('gives each incident its own reference', () => {
const first = hostFor();
const second = hostFor();
filter.catch(new Error('boom'), first.host);
filter.catch(new Error('boom'), second.host);
expect(first.body().reference).not.toBe(second.body().reference);
});
it('classifies a DNS failure as an outage, not as a bug', () => {
// C'est l'erreur observee quand le conteneur PostgreSQL est arrete :
// `getaddrinfo ENOTFOUND postgres`. Elle sortait en 500.
const { host, status, body } = hostFor();
filter.catch(new Error('getaddrinfo ENOTFOUND postgres'), host);
expect(status).toHaveBeenCalledWith(HttpStatus.SERVICE_UNAVAILABLE);
expect(body()).toMatchObject({ code: 'service_unavailable' });
});
it('answers in the language of the request', () => {
// `I18nContext.current()` n'est pas garanti dans un filtre : sans relecture
// des en-tetes, la reponse repartait toujours en francais.
filter.catch(new Error('boom'), hostFor({ 'x-lang': 'en' }).host);
expect(i18n.translate).toHaveBeenLastCalledWith(
'error.UNEXPECTED_ERROR',
expect.objectContaining({ lang: 'en' })
);
filter.catch(new Error('boom'), hostFor({ 'accept-language': 'en-GB,en;q=0.8' }).host);
expect(i18n.translate).toHaveBeenLastCalledWith(
'error.UNEXPECTED_ERROR',
expect.objectContaining({ lang: 'en' })
);
});
it('falls back to French for an unsupported language', () => {
filter.catch(new Error('boom'), hostFor({ 'x-lang': 'de' }).host);
expect(i18n.translate).toHaveBeenLastCalledWith(
'error.UNEXPECTED_ERROR',
expect.objectContaining({ lang: 'fr' })
);
});
it('rethrows outside an HTTP context rather than writing nowhere', () => {
const host = {
switchToHttp: () => ({ getResponse: () => ({}), getRequest: () => ({}) }),
} as unknown as ArgumentsHost;
expect(() => filter.catch(new Error('boom'), host)).toThrow('boom');
});
});
describe('isDependencyUnavailable', () => {
it.each([
'the database system is not yet accepting connections',
'the database system is in recovery mode',
'terminating connection due to administrator command',
'connect ECONNREFUSED 127.0.0.1:5432',
'Connection terminated unexpectedly',
'getaddrinfo ENOTFOUND postgres',
'socket hang up',
])('recognises %p', message => {
expect(isDependencyUnavailable(new Error(message))).toBe(true);
});
it.each(['57P03', '08006', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN'])(
'recognises the driver code %p',
code => {
expect(isDependencyUnavailable(Object.assign(new Error('nope'), { code }))).toBe(true);
}
);
it.each([
'duplicate key value violates unique constraint',
"Cannot read properties of undefined (reading 'id')",
'null value in column "email" violates not-null constraint',
])('does not mistake the application fault %p for an outage', message => {
expect(isDependencyUnavailable(new Error(message))).toBe(false);
});
it('ignores a non-error throw', () => {
expect(isDependencyUnavailable('boom')).toBe(false);
});
});

View File

@ -1,189 +0,0 @@
import { safeRequestRoute } from '../logging/safe-http-log';
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import { Request, Response } from 'express';
import { I18nContext, I18nService } from 'nestjs-i18n';
import { DEFAULT_LOCALE, Locale, isLocale } from '@domain/value-objects/locale.vo';
import {
LAST_ACTIVE_ADMIN_CODE,
LAST_ACTIVE_ADMIN_SQLSTATE,
} from '@domain/services/admin-continuity';
/**
* Dernier recours avant la reponse HTTP.
*
* Sans lui, toute exception non prevue sortait avec le message par defaut de
* NestJS — « Internal server error » — affiche tel quel dans le navigateur. Ce
* message ne dit rien de ce qui s'est passe, rien de ce qu'il faut faire, et
* n'existe dans aucune langue.
*
* Trois cas, dans cet ordre :
*
* 1. **Une `HttpException`** est une reponse deliberee (404, 400, 409...) :
* elle passe telle quelle, avec son statut et son message.
* 2. **Une base de donnees indisponible** n'est pas une erreur du client ni un
* bogue : c'est un `503` temporaire, et le message invite a reessayer. Le
* 500 precedent laissait croire a une donnee refusee.
* 3. **Tout le reste** est un defaut : `500`, message generique — le detail
* technique ne sort jamais — et une **reference** courte, journalisee avec
* la trace. L'utilisateur peut la donner au support, qui retrouve l'incident.
*/
@Catch()
export class UnhandledExceptionFilter implements ExceptionFilter {
private readonly logger = new Logger('UnhandledException');
constructor(private readonly i18n: I18nService<Record<string, unknown>>) {}
catch(exception: unknown, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
// Hors contexte HTTP (WebSocket, tache planifiee), il n'y a pas de reponse
// a former : laisser remonter plutot que d'ecrire dans le vide.
if (!response?.status) throw exception;
if (exception instanceof HttpException) {
response.status(exception.getStatus()).json(exception.getResponse());
return;
}
const lang = resolveLocale(request);
// Le declencheur PostgreSQL a refuse de retirer le dernier administrateur
// actif (cas concurrent que le controle applicatif ne peut pas voir) : c'est
// un conflit explicable, pas une panne.
if (isLastActiveAdminViolation(exception)) {
response.status(HttpStatus.CONFLICT).json({
statusCode: HttpStatus.CONFLICT,
error: 'Conflict',
code: LAST_ACTIVE_ADMIN_CODE,
message: this.translate('error.LAST_ACTIVE_ADMIN', lang),
timestamp: new Date().toISOString(),
path: request.url,
});
return;
}
const unavailable = isDependencyUnavailable(exception);
const status = unavailable ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.INTERNAL_SERVER_ERROR;
const key = unavailable ? 'error.SERVICE_UNAVAILABLE' : 'error.UNEXPECTED_ERROR';
// La reference relie ce que voit l'utilisateur a la trace du journal ; elle
// n'apprend rien a un attaquant et evite de lui montrer la pile.
const reference = randomUUID().slice(0, 8);
this.logger.error(
`[${reference}] ${request.method} ${safeRequestRoute(request)} — ${unavailable ? 'dependency unavailable' : 'unexpected error'}`
);
response.status(status).json({
statusCode: status,
error: unavailable ? 'ServiceUnavailable' : 'UnexpectedError',
code: unavailable ? 'service_unavailable' : 'unexpected_error',
message: this.translate(key, lang),
reference,
timestamp: new Date().toISOString(),
path: safeRequestRoute(request),
});
}
private translate(key: string, lang: Locale): string {
const translated = this.i18n.translate(key, { lang, defaultValue: key });
return typeof translated === 'string' ? translated : key;
}
}
/**
* L'erreur est-elle le refus du declencheur `trg_users_keep_active_admin` ?
* TypeORM recopie le code du pilote sur QueryFailedError ; `driverError` est
* verifie aussi, au cas ou cette recopie changerait.
*/
export function isLastActiveAdminViolation(exception: unknown): boolean {
if (!(exception instanceof Error)) return false;
const { code, driverError } = exception as { code?: string; driverError?: { code?: string } };
return code === LAST_ACTIVE_ADMIN_SQLSTATE || driverError?.code === LAST_ACTIVE_ADMIN_SQLSTATE;
}
/**
* L'erreur vient-elle d'une dependance injoignable, plutot que d'une requete
* fautive ou d'un defaut du code ?
*
* Le perimetre n'est pas la seule base de donnees : Redis, le stockage objet,
* le SMTP ou le fournisseur d'IA produisent les memes symptomes, et appellent
* la meme reponse — « reessayez dans un instant » — la ou un `500` laisserait
* croire a une donnee refusee.
*
* Les codes couvrent la resolution DNS (`ENOTFOUND`, observe quand le conteneur
* PostgreSQL est arrete), le refus de connexion, les coupures, et les etats de
* demarrage ou d'arret de PostgreSQL (`57P03` : la base n'accepte pas encore de
* connexions — exactement ce qu'a renvoye l'inscription pendant que le serveur
* redemarrait apres saturation du disque).
*/
export function isDependencyUnavailable(exception: unknown): boolean {
if (!(exception instanceof Error)) return false;
const code = (exception as { code?: string }).code;
if (code && UNAVAILABLE_CODES.has(code)) return true;
return /not yet accepting connections|in recovery mode|terminating connection|Connection terminated|getaddrinfo|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up|Client has encountered a connection error/i.test(
exception.message
);
}
const UNAVAILABLE_CODES = new Set([
// PostgreSQL
'57P01', // admin_shutdown
'57P02', // crash_shutdown
'57P03', // cannot_connect_now
'08000', // connection_exception
'08003', // connection_does_not_exist
'08006', // connection_failure
// Reseau et DNS
'ENOTFOUND',
'EAI_AGAIN',
'ECONNREFUSED',
'ECONNRESET',
'ETIMEDOUT',
'EHOSTUNREACH',
'ENETUNREACH',
'EPIPE',
]);
/**
* Langue de la reponse.
*
* `I18nContext.current()` n'est pas garanti dans un filtre d'exception : le
* contexte asynchrone peut avoir ete quitte, et la reponse repartait alors
* toujours en francais. La chaine est donc relue depuis la requete, dans le
* meme ordre que les resolveurs de l'application — sans la preference
* utilisateur, qui demanderait la base, parfois justement indisponible.
*/
function resolveLocale(request: Request): Locale {
const header = request.headers['x-lang'] ?? request.headers['x-locale'];
const cookie = (request as { cookies?: Record<string, string> }).cookies?.NEXT_LOCALE;
const accept = request.headers['accept-language']?.split(',')[0];
const candidates = [
I18nContext.current()?.lang,
typeof header === 'string' ? header : header?.[0],
cookie,
accept,
];
// `isLocale` et non `toLocale` : ce dernier retombe sur le francais des le
// premier candidat absent, et la chaine ne serait jamais parcourue.
for (const candidate of candidates) {
const short = candidate?.slice(0, 2).toLowerCase();
if (isLocale(short)) return short;
}
return DEFAULT_LOCALE;
}

View File

@ -1,70 +0,0 @@
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Socket } from 'socket.io';
import { NotificationsGateway } from './notifications.gateway';
import { JwtStrategy } from '../auth/jwt.strategy';
import { AuthService } from '../auth/auth.service';
import { NotificationService } from '../services/notification.service';
describe('notification socket sessions', () => {
const jwt = new JwtService({ secret: 'test-only-socket-secret' });
const validateUser = jest.fn();
const notifications = {
getUnreadCount: jest.fn(async () => 0),
getRecentNotifications: jest.fn(async () => []),
markAllAsRead: jest.fn(),
};
let gateway: NotificationsGateway;
const socket = (token: string) =>
({
id: 'socket-1',
data: {},
handshake: { headers: {}, query: {}, auth: { token } },
join: jest.fn(),
emit: jest.fn(),
disconnect: jest.fn(),
}) as unknown as Socket;
const token = (type = 'access', expiresIn = 300) =>
jwt.sign({ sub: 'user-1', type }, { expiresIn });
beforeEach(() => {
jest.clearAllMocks();
validateUser.mockResolvedValue({ id: 'user-1', organizationId: 'org-1' });
const strategy = new JwtStrategy(new ConfigService({ JWT_SECRET: 'test-only-socket-secret' }), {
validateUser,
} as unknown as AuthService);
gateway = new NotificationsGateway(
jwt,
notifications as unknown as NotificationService,
strategy
);
});
it.each(['refresh', 'unknown'])('rejects %s tokens before any data is sent', async type => {
const client = socket(token(type));
await gateway.handleConnection(client);
expect(client.disconnect).toHaveBeenCalled();
expect(client.emit).not.toHaveBeenCalled();
});
it('rejects expired and disabled sessions', async () => {
const expired = socket(token('access', -1));
await gateway.handleConnection(expired);
expect(expired.emit).not.toHaveBeenCalled();
validateUser.mockResolvedValue(null);
const disabled = socket(token());
await gateway.handleConnection(disabled);
expect(disabled.emit).not.toHaveBeenCalled();
});
it('rechecks the account on messages after a valid connection', async () => {
const client = socket(token());
await gateway.handleConnection(client);
expect(client.emit).toHaveBeenCalledWith('unread_count', { count: 0 });
validateUser.mockResolvedValue(null);
const result = await gateway.handleMarkAllAsRead(client);
expect(result.success).toBe(false);
expect(notifications.markAllAsRead).not.toHaveBeenCalled();
expect(client.disconnect).toHaveBeenCalled();
});
});

View File

@ -14,12 +14,10 @@ import {
MessageBody,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { Logger, UseGuards, UnauthorizedException } from '@nestjs/common';
import { Logger, UseGuards } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { JwtStrategy, JwtPayload } from '../auth/jwt.strategy';
import { NotificationService } from '../services/notification.service';
import { Notification } from '@domain/entities/notification.entity';
import { notificationTarget } from '@domain/services/notification-target';
/**
* WebSocket authentication guard
@ -37,13 +35,11 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
server: Server;
private readonly logger = new Logger(NotificationsGateway.name);
private readonly connections = new Map<string, Socket>();
private userSockets: Map<string, Set<string>> = new Map(); // userId -> Set of socket IDs
constructor(
private readonly jwtService: JwtService,
private readonly notificationService: NotificationService,
private readonly jwtStrategy: JwtStrategy
private readonly notificationService: NotificationService
) {}
/**
@ -60,9 +56,8 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
}
// Verify JWT token
const user = await this.authenticate(client);
const userId = user.id;
this.connections.set(client.id, client);
const payload = await this.jwtService.verifyAsync(token);
const userId = payload.sub;
// Store socket connection for user
if (!this.userSockets.has(userId)) {
@ -72,7 +67,7 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
// Store user ID in socket data for later use
client.data.userId = userId;
client.data.organizationId = user.organizationId;
client.data.organizationId = payload.organizationId;
// Join user-specific room
client.join(`user:${userId}`);
@ -101,7 +96,6 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
* Handle client disconnection
*/
handleDisconnect(client: Socket) {
this.connections.delete(client.id);
const userId = client.data.userId;
if (userId && this.userSockets.has(userId)) {
this.userSockets.get(userId)!.delete(client.id);
@ -121,12 +115,12 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
@MessageBody() data: { notificationId: string }
) {
try {
const userId = (await this.authenticate(client)).id;
await this.notificationService.markAsRead(data.notificationId, userId);
const userId = client.data.userId;
await this.notificationService.markAsRead(data.notificationId);
// Send updated unread count
const unreadCount = await this.notificationService.getUnreadCount(userId);
await this.emitToUser(userId, 'unread_count', { count: unreadCount });
this.emitToUser(userId, 'unread_count', { count: unreadCount });
return { success: true };
} catch (error: any) {
@ -141,11 +135,11 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
@SubscribeMessage('mark_all_as_read')
async handleMarkAllAsRead(@ConnectedSocket() client: Socket) {
try {
const userId = (await this.authenticate(client)).id;
const userId = client.data.userId;
await this.notificationService.markAllAsRead(userId);
// Send updated unread count (should be 0)
await this.emitToUser(userId, 'unread_count', { count: 0 });
this.emitToUser(userId, 'unread_count', { count: 0 });
return { success: true };
} catch (error: any) {
@ -160,7 +154,7 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
@SubscribeMessage('get_unread_count')
async handleGetUnreadCount(@ConnectedSocket() client: Socket) {
try {
const userId = (await this.authenticate(client)).id;
const userId = client.data.userId;
const unreadCount = await this.notificationService.getUnreadCount(userId);
return { count: unreadCount };
} catch (error: any) {
@ -176,11 +170,11 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
const notificationDto = this.mapNotificationToDto(notification);
// Emit to all connected sockets for this user
await this.emitToUser(userId, 'new_notification', { notification: notificationDto });
this.emitToUser(userId, 'new_notification', { notification: notificationDto });
// Update unread count
const unreadCount = await this.notificationService.getUnreadCount(userId);
await this.emitToUser(userId, 'unread_count', { count: unreadCount });
this.emitToUser(userId, 'unread_count', { count: unreadCount });
this.logger.log(`Notification sent to user ${userId}: ${notification.title}`);
}
@ -190,16 +184,9 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
*/
async broadcastToOrganization(organizationId: string, notification: Notification) {
const notificationDto = this.mapNotificationToDto(notification);
for (const client of this.connections.values()) {
try {
const user = await this.authenticate(client);
if (user.organizationId === organizationId) {
client.emit('new_notification', { notification: notificationDto });
}
} catch {
client.disconnect();
}
}
this.server.to(`org:${organizationId}`).emit('new_notification', {
notification: notificationDto,
});
this.logger.log(`Notification broadcasted to organization ${organizationId}`);
}
@ -207,36 +194,8 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
/**
* Helper: Emit event to all sockets of a user
*/
private async emitToUser(userId: string, event: string, data: unknown) {
for (const socketId of this.userSockets.get(userId) ?? []) {
const client = this.connections.get(socketId);
if (!client) continue;
try {
const user = await this.authenticate(client);
if (user.id === userId) client.emit(event, data);
} catch {
client.disconnect();
}
}
}
private async authenticate(client: Socket) {
try {
const token = this.extractToken(client);
if (!token) throw new UnauthorizedException();
const payload = await this.jwtService.verifyAsync<JwtPayload>(token);
if (
typeof payload.sub !== 'string' ||
!Number.isFinite(payload.exp) ||
payload.exp! * 1000 <= Date.now()
) {
throw new UnauthorizedException();
}
return await this.jwtStrategy.validate(payload);
} catch {
client.disconnect();
throw new UnauthorizedException('Invalid or expired session');
}
private emitToUser(userId: string, event: string, data: any) {
this.server.to(`user:${userId}`).emit(event, data);
}
/**
@ -277,10 +236,7 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
metadata: notification.metadata,
read: notification.read,
readAt: notification.readAt?.toISOString(),
actionUrl:
notification.actionUrl ??
notificationTarget(notification.type, notification.metadata) ??
undefined,
actionUrl: notification.actionUrl,
createdAt: notification.createdAt.toISOString(),
};
}

View File

@ -6,41 +6,26 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuditModule } from '../audit/audit.module';
import { GDPRController } from '../controllers/gdpr.controller';
import { GDPRService } from '../services/gdpr.service';
import { RetentionService } from '../services/retention.service';
import { UserDeletionService } from '../services/user-deletion.service';
import { AdminContinuityService } from '../services/admin-continuity.service';
import { SubscriptionsModule } from '../subscriptions/subscriptions.module';
import { UserOrmEntity } from '../../infrastructure/persistence/typeorm/entities/user.orm-entity';
import { BookingOrmEntity } from '../../infrastructure/persistence/typeorm/entities/booking.orm-entity';
import { AuditLogOrmEntity } from '../../infrastructure/persistence/typeorm/entities/audit-log.orm-entity';
import { NotificationOrmEntity } from '../../infrastructure/persistence/typeorm/entities/notification.orm-entity';
import { CookieConsentOrmEntity } from '../../infrastructure/persistence/typeorm/entities/cookie-consent.orm-entity';
import { USER_REPOSITORY } from '@domain/ports/out/user.repository';
import { TypeOrmUserRepository } from '../../infrastructure/persistence/typeorm/repositories/typeorm-user.repository';
@Module({
imports: [
// Les autres tables touchees par l'effacement (csv_bookings, audit_logs,
// notifications, trade_conversations, password_reset_tokens) sont lues en
// SQL via DataSource : la moitie d'entre elles n'a pas d'entite ORM, et
// BookingOrmEntity pointait vers une table `bookings` qui n'existe pas.
TypeOrmModule.forFeature([UserOrmEntity, CookieConsentOrmEntity]),
// Les demandes de droits sont journalisees : l'article 5.2 impose de
// pouvoir demontrer qu'elles ont ete traitees.
AuditModule,
// Suppression par un administrateur : la licence est revoquee apres
// l'effacement.
SubscriptionsModule,
TypeOrmModule.forFeature([
UserOrmEntity,
BookingOrmEntity,
AuditLogOrmEntity,
NotificationOrmEntity,
CookieConsentOrmEntity,
]),
],
controllers: [GDPRController],
providers: [
GDPRService,
RetentionService,
UserDeletionService,
// Au moins un administrateur actif : partage avec Admin et Users.
AdminContinuityService,
{ provide: USER_REPOSITORY, useClass: TypeOrmUserRepository },
],
exports: [GDPRService, RetentionService, UserDeletionService, AdminContinuityService],
providers: [GDPRService],
exports: [GDPRService],
})
export class GDPRModule {}

View File

@ -18,7 +18,7 @@ import { REQUIRED_FEATURES_KEY } from '../decorators/requires-feature.decorator'
* Feature Flag Guard
*
* Checks if the user's subscription plan includes the required features.
* Uses current subscription data so stale token claims cannot preserve revoked rights.
* First tries to read plan from JWT payload (fast path), falls back to DB lookup.
*
* Usage:
* @UseGuards(JwtAuthGuard, RolesGuard, FeatureFlagGuard)
@ -58,7 +58,19 @@ export class FeatureFlagGuard implements CanActivate {
return true;
}
// Always resolve current rights, including after suspension or downgrade.
// Fast path: check plan features from JWT payload
if (user.planFeatures && Array.isArray(user.planFeatures)) {
const hasAllFeatures = requiredFeatures.every(feature => user.planFeatures.includes(feature));
if (hasAllFeatures) {
return true;
}
// JWT says no — but JWT might be stale after an upgrade.
// Fall through to DB check.
}
// Slow path: DB lookup for fresh subscription data
try {
const subscription = await this.subscriptionRepository.findByOrganizationId(
user.organizationId
@ -69,9 +81,8 @@ export class FeatureFlagGuard implements CanActivate {
this.throwFeatureRequired(requiredFeatures);
}
const missingFeatures = requiredFeatures.filter(
feature => !subscription!.hasFeature(feature)
);
const plan = subscription!.plan;
const missingFeatures = requiredFeatures.filter(feature => !plan.hasFeature(feature));
if (missingFeatures.length > 0) {
this.throwFeatureRequired(requiredFeatures);

View File

@ -1,90 +0,0 @@
import { ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Subscription } from '@domain/entities/subscription.entity';
import { SubscriptionPlan } from '@domain/value-objects/subscription-plan.vo';
import {
SubscriptionStatus,
SubscriptionStatusType,
} from '@domain/value-objects/subscription-status.vo';
import { SubscriptionRepository } from '@domain/ports/out/subscription.repository';
import { FeatureFlagGuard } from './feature-flag.guard';
const subscriptionFor = (status: SubscriptionStatusType) =>
Subscription.create({
id: 'sub',
organizationId: 'org',
plan: SubscriptionPlan.gold(),
}).updateStatus(SubscriptionStatus.create(status));
const denied: SubscriptionStatusType[] = [
'UNPAID',
'PAUSED',
'INCOMPLETE',
'INCOMPLETE_EXPIRED',
'CANCELED',
];
const allowed: SubscriptionStatusType[] = ['ACTIVE', 'TRIALING', 'PAST_DUE'];
describe('Current subscription entitlement', () => {
it.each(denied)('%s removes paid benefits without erasing billing plan', status => {
const subscription = subscriptionFor(status);
expect(subscription.hasFeature('api_access')).toBe(false);
expect(subscription.maxShipmentsPerYear).toBe(SubscriptionPlan.bronze().maxShipmentsPerYear);
expect(subscription.bookingFeeEur).toBe(SubscriptionPlan.bronze().bookingFeeEur);
expect(subscription.plan.value).toBe('GOLD');
});
it.each(allowed)('%s retains paid benefits', status => {
const subscription = subscriptionFor(status);
expect(subscription.hasFeature('api_access')).toBe(true);
expect(subscription.maxShipmentsPerYear).toBe(SubscriptionPlan.gold().maxShipmentsPerYear);
});
const setup = (
subscription: Subscription | null,
role = 'MANAGER',
planFeatures = ['user_management']
) => {
const findByOrganizationId = jest.fn().mockResolvedValue(subscription);
const reflector = { getAllAndOverride: jest.fn().mockReturnValue(['user_management']) };
const guard = new FeatureFlagGuard(
reflector as unknown as Reflector,
{ findByOrganizationId } as unknown as SubscriptionRepository
);
const context = {
getHandler: () => undefined,
getClass: () => undefined,
switchToHttp: () => ({
getRequest: () => ({ user: { organizationId: 'org', role, planFeatures } }),
}),
} as unknown as ExecutionContext;
return { guard, context, findByOrganizationId };
};
it.each(denied)('%s cannot be bypassed by stale token features', async status => {
const { guard, context } = setup(subscriptionFor(status));
await expect(guard.canActivate(context)).rejects.toBeInstanceOf(ForbiddenException);
});
it('denies a deleted subscription even with paid token features', async () => {
const { guard, context } = setup(null);
await expect(guard.canActivate(context)).rejects.toBeInstanceOf(ForbiddenException);
});
it.each(allowed)('%s allows current rights despite an old Bronze token', async status => {
const { guard, context } = setup(subscriptionFor(status), 'MANAGER', []);
await expect(guard.canActivate(context)).resolves.toBe(true);
});
it('preserves the platform ADMIN override', async () => {
const { guard, context, findByOrganizationId } = setup(null, 'ADMIN');
await expect(guard.canActivate(context)).resolves.toBe(true);
expect(findByOrganizationId).not.toHaveBeenCalled();
});
it('fails closed when current rights cannot be loaded', async () => {
const { guard, context, findByOrganizationId } = setup(subscriptionFor('ACTIVE'));
findByOrganizationId.mockRejectedValue(new Error('unavailable'));
await expect(guard.canActivate(context)).rejects.toBeInstanceOf(ForbiddenException);
});
});

View File

@ -1,4 +1,3 @@
import { safeRequestRoute } from '../logging/safe-http-log';
/**
* Performance Monitoring Interceptor
*
@ -16,8 +15,7 @@ export class PerformanceMonitoringInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const request = context.switchToHttp().getRequest();
const { method, user } = request;
const url = safeRequestRoute(request);
const { method, url, user } = request;
const startTime = Date.now();
return next.handle().pipe(
@ -41,7 +39,10 @@ export class PerformanceMonitoringInterceptor implements NestInterceptor {
const duration = Date.now() - startTime;
// Log error
this.logger.error(`Request error: ${method} ${url} (${duration}ms)`);
this.logger.error(
`Request error: ${method} ${url} (${duration}ms) - ${error.message}`,
error.stack
);
// Capture exception in Sentry
Sentry.withScope(scope => {
@ -51,7 +52,7 @@ export class PerformanceMonitoringInterceptor implements NestInterceptor {
userId: user?.sub,
duration,
});
Sentry.captureException(new Error('Request failed; sensitive error details omitted'));
Sentry.captureException(error);
});
throw error;

View File

@ -1,103 +0,0 @@
import pino from 'pino';
import { Logger, ArgumentsHost, NotFoundException } from '@nestjs/common';
import { safeHttpSerializers, safeRequestRoute } from './safe-http-log';
import { UnhandledExceptionFilter } from '../filters/unhandled-exception.filter';
import { CsvBookingService } from '../services/csv-booking.service';
import { InvitationsController } from '../controllers/invitations.controller';
import { TypeOrmCsvBookingRepository } from '@infrastructure/persistence/typeorm/repositories/csv-booking.repository';
const secret = 'test-secret-not-for-logs';
describe('Capability-safe logs', () => {
afterEach(() => jest.restoreAllMocks());
it('serializes real Pino events without request, response or driver secrets', () => {
let output = '';
const logger = pino(
{ serializers: safeHttpSerializers },
{
write: (line: string) => {
output += line;
},
}
);
logger.error(
{
req: {
method: 'GET',
url: `/api/v1/invitations/verify/${secret}?password=${secret}`,
headers: { cookie: secret, referer: secret },
params: { token: secret },
body: { password: secret },
raw: { route: { path: '/api/v1/invitations/verify/:token' } },
},
res: { statusCode: 500, headers: { 'set-cookie': secret } },
err: Object.assign(new Error(secret), {
query: secret,
parameters: [secret],
cause: new Error(secret),
}),
},
'request failed'
);
expect(output).not.toContain(secret);
expect(JSON.parse(output)).toMatchObject({
req: { method: 'GET', route: '/api/v1/invitations/verify/:token' },
res: { statusCode: 500 },
});
});
it('does not fall back to a raw or encoded path on an unmatched request', () => {
expect(safeRequestRoute({ url: `/api/v1/%69nvitations/verify/${secret}` })).toBe(
'[unmatched route]'
);
});
it('keeps correlation without raw exception details or URL in the global filter', () => {
const errorLog = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
const json = jest.fn();
const status = jest.fn().mockReturnValue({ json });
const host = {
switchToHttp: () => ({
getRequest: () => ({ method: 'GET', url: `/${secret}`, headers: {} }),
getResponse: () => ({ status }),
}),
} as unknown as ArgumentsHost;
new UnhandledExceptionFilter({ translate: () => 'Please retry' } as never).catch(
new Error(secret),
host
);
expect(JSON.stringify(errorLog.mock.calls)).not.toContain(secret);
expect(JSON.stringify(json.mock.calls)).not.toContain(secret);
expect(json.mock.calls[0][0].reference).toBeTruthy();
});
it('does not log tokens across controller, service and repository lookup paths', async () => {
const logs = jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
const orm = { findOne: jest.fn().mockResolvedValue(null) };
const repository = new TypeOrmCsvBookingRepository(orm as never);
const service = new CsvBookingService(
repository,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never
);
for (const call of [
() => service.getBookingByToken(secret),
() => service.acceptBooking(secret),
() => service.rejectBooking(secret),
]) {
await expect(call()).rejects.toBeInstanceOf(NotFoundException);
}
await expect(service.getBookingByToken(secret)).rejects.not.toThrow(secret);
const controller = new InvitationsController({
verifyInvitation: jest.fn().mockRejectedValue(new NotFoundException('not found')),
} as never);
await expect(controller.verifyInvitation(secret)).rejects.toBeInstanceOf(NotFoundException);
expect(JSON.stringify(logs.mock.calls)).not.toContain(secret);
expect(orm.findOne).toHaveBeenCalledWith({ where: { confirmationToken: secret } });
});
});

View File

@ -1,24 +0,0 @@
/** Log server-owned routing metadata, never credentials carried by URLs or headers. */
export function safeRequestRoute(request: unknown): string {
if (!request || typeof request !== 'object') return '[unmatched route]';
const req = request as { route?: { path?: unknown }; raw?: { route?: { path?: unknown } } };
const path = req.route?.path ?? req.raw?.route?.path;
return typeof path === 'string' ? path : '[unmatched route]';
}
export const safeHttpSerializers = {
req(request: {
method?: string;
route?: { path?: unknown };
raw?: { route?: { path?: unknown } };
}) {
return { method: request.method, route: safeRequestRoute(request) };
},
res(response: { statusCode?: number }) {
return { statusCode: response.statusCode };
},
err(_error: unknown) {
// Driver/SMTP errors can contain SQL parameters, tokens, headers or message bodies.
return { type: 'Error', message: 'Request failed; sensitive error details omitted' };
},
};

View File

@ -105,7 +105,6 @@ export class CsvRateMapper {
id: entity.id,
companyName: entity.companyName,
csvFilePath: entity.csvFilePath,
direction: entity.direction ?? 'EXPORT',
type: entity.type,
hasApi: entity.hasApi,
apiConnector: entity.apiConnector,

View File

@ -1,48 +0,0 @@
import { SubscriptionService } from '../../services/subscription.service';
import { actorPlan } from '@domain/services/capability-access';
import { Capability } from '../capability';
/**
* Compte et abonnement.
*
* `whoami` n'est pas un gadget : c'est ce qui permet a un agent d'annoncer
* honnetement ce qu'il peut faire, au lieu de proposer une action puis de se
* heurter a un refus.
*/
export function accountCapabilities(subscriptions: SubscriptionService): Capability[] {
return [
{
policy: { name: 'whoami', scope: 'read' },
description:
"Identité de l'appelant : identifiant, organisation, rôle et offre effective. À appeler en premier pour savoir ce qui est permis.",
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
handler: async (_input, actor) => ({
userId: actor.id,
organizationId: actor.organizationId,
role: actor.role,
plan: actorPlan(actor),
}),
},
{
policy: { name: 'get_subscription', scope: 'read', roles: ['ADMIN', 'MANAGER'] },
description:
"Abonnement de l'organisation : offre, statut, licences utilisées et disponibles. Réservé aux rôles ADMIN et MANAGER.",
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
handler: async (_input, actor) => {
const overview = await subscriptions.getSubscriptionOverview(
actor.organizationId,
actor.role
);
return {
plan: overview.plan,
status: overview.status,
usedLicenses: overview.usedLicenses,
maxLicenses: overview.maxLicenses,
availableLicenses: overview.availableLicenses,
currentPeriodEnd: overview.currentPeriodEnd,
};
},
},
];
}

View File

@ -1,126 +0,0 @@
import { UserRepository } from '@domain/ports/out/user.repository';
import { OrganizationRepository } from '@domain/ports/out/organization.repository';
import { CsvRateSearchService } from '@domain/services/csv-rate-search.service';
import { Capability } from '../capability';
/** Role d'administration de la plateforme. Les inscriptions creent des MANAGER. */
const ADMIN_ONLY = ['ADMIN'] as const;
/**
* Capacites d'administration de la plateforme.
*
* Elles franchissent la frontiere de l'organisation — c'est precisement ce qui
* les distingue du reste du catalogue — et sont donc reservees au role ADMIN,
* verifie dans le processus et non dans un prompt.
*
* Elles sont **en lecture seule**. Modifier un utilisateur, valider un SIRET ou
* remplacer une grille tarifaire touche des comptes clients et de l'argent :
* ces actions restent a la main d'une personne, dans l'espace d'administration,
* tant qu'un mecanisme de confirmation explicite n'existe pas cote agent.
*/
export function adminCapabilities(
users: UserRepository,
organizations: OrganizationRepository,
rateSearch: CsvRateSearchService
): Capability[] {
return [
{
policy: { name: 'admin_list_users', scope: 'read', roles: ADMIN_ONLY },
description:
"Liste les comptes de la plateforme, toutes organisations confondues. Réservé à l'administration.",
inputSchema: {
type: 'object',
properties: {
role: {
type: 'string',
description: 'Ne garder que ce rôle.',
enum: ['ADMIN', 'MANAGER', 'USER', 'VIEWER', 'CARRIER'],
},
search: {
type: 'string',
description: 'Filtre sur l’adresse e-mail ou le nom.',
maxLength: 120,
},
limit: {
type: 'integer',
description: 'Nombre maximum de comptes.',
minimum: 1,
maximum: 100,
default: 25,
},
},
additionalProperties: false,
},
handler: async input => {
const all = input.role
? await users.findByRole(input.role as string)
: await users.findAll();
const term = (input.search as string | undefined)?.toLowerCase();
const matching = term
? all.filter(user =>
`${user.email} ${user.firstName} ${user.lastName}`.toLowerCase().includes(term)
)
: all;
return {
total: matching.length,
users: matching.slice(0, (input.limit as number) ?? 25).map(user => ({
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
role: user.role,
organizationId: user.organizationId,
isActive: user.isActive,
})),
};
},
},
{
policy: { name: 'admin_list_organizations', scope: 'read', roles: ADMIN_ONLY },
description:
"Liste les organisations de la plateforme, avec leur nombre de comptes. Réservé à l'administration.",
inputSchema: {
type: 'object',
properties: {
limit: {
type: 'integer',
description: "Nombre maximum d'organisations.",
minimum: 1,
maximum: 100,
default: 25,
},
},
additionalProperties: false,
},
handler: async input => {
const all = await organizations.findAll();
const page = all.slice(0, (input.limit as number) ?? 25);
return {
total: all.length,
organizations: await Promise.all(
page.map(async organization => ({
id: organization.id,
name: organization.name,
userCount: await users.countByOrganization(organization.id),
}))
),
};
},
},
{
policy: { name: 'admin_rate_grid_overview', scope: 'read', roles: ADMIN_ONLY },
description:
"État des grilles tarifaires chargées : transporteurs et types de conteneurs disponibles. Réservé à l'administration.",
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
handler: async () => ({
carriers: await rateSearch.getAvailableCompanies(),
containerTypes: await rateSearch.getAvailableContainerTypes(),
}),
},
];
}

View File

@ -1,113 +0,0 @@
import { CsvBookingService } from '../../services/csv-booking.service';
import { Capability } from '../capability';
/**
* Reservations.
*
* Les lectures restent cantonnees a l'appelant, sauf `list_organization_bookings`
* qui demande un role d'encadrement — c'est la meme frontiere que dans
* l'interface, ou seuls ADMIN et MANAGER voient l'onglet organisation.
*
* Les ecritures sont volontairement limitees aux actions reversibles ou
* inoffensives : annuler, et supprimer une reservation impayee. Payer une
* commission, envoyer une demande a un transporteur ou televerser un document
* engagent un tiers ou de l'argent et restent hors de portee d'un agent.
*/
export function bookingsCapabilities(bookings: CsvBookingService): Capability[] {
return [
{
policy: { name: 'list_my_bookings', scope: 'read' },
description:
"Liste les réservations de l'utilisateur authentifié, de la plus récente à la plus ancienne.",
inputSchema: {
type: 'object',
properties: {
limit: {
type: 'integer',
description: 'Nombre maximum de réservations.',
minimum: 1,
maximum: 50,
default: 20,
},
},
additionalProperties: false,
},
handler: async (input, actor) =>
bookings.getUserBookings(actor.id, 1, (input.limit as number) ?? 20),
},
{
policy: { name: 'list_organization_bookings', scope: 'read', roles: ['ADMIN', 'MANAGER'] },
description:
"Liste les réservations de toute l'organisation. Réservé aux rôles ADMIN et MANAGER.",
inputSchema: {
type: 'object',
properties: {
limit: {
type: 'integer',
description: 'Nombre maximum de réservations.',
minimum: 1,
maximum: 50,
default: 20,
},
},
additionalProperties: false,
},
handler: async (input, actor) =>
bookings.getOrganizationBookings(actor.organizationId, 1, (input.limit as number) ?? 20),
},
{
policy: { name: 'get_booking', scope: 'read' },
description:
"Détail d'une réservation : route, marchandise, transporteur, statut, documents.",
inputSchema: {
type: 'object',
properties: {
bookingId: { type: 'string', description: 'Identifiant de la réservation (UUID).' },
},
required: ['bookingId'],
additionalProperties: false,
},
handler: async (input, actor) => bookings.getBookingById(input.bookingId as string, actor.id),
},
{
policy: { name: 'booking_statistics', scope: 'read' },
description:
"Répartition des réservations de l'utilisateur par statut (en attente de paiement, en attente, acceptées, refusées).",
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
handler: async (_input, actor) => bookings.getUserStats(actor.id),
},
{
policy: { name: 'cancel_booking', scope: 'write' },
description:
"Annule une réservation de l'utilisateur qui n'a pas encore été acceptée par le transporteur. La réservation est conservée avec le statut annulé.",
inputSchema: {
type: 'object',
properties: {
bookingId: { type: 'string', description: 'Identifiant de la réservation (UUID).' },
},
required: ['bookingId'],
additionalProperties: false,
},
handler: async (input, actor) => bookings.cancelBooking(input.bookingId as string, actor.id),
},
{
policy: { name: 'delete_unpaid_booking', scope: 'write' },
description:
"Supprime définitivement une réservation dont la commission n'a pas été payée. Sans effet sur une réservation payée, qui ne peut être qu'annulée.",
inputSchema: {
type: 'object',
properties: {
bookingId: { type: 'string', description: 'Identifiant de la réservation (UUID).' },
},
required: ['bookingId'],
additionalProperties: false,
},
handler: async (input, actor) => bookings.deleteBooking(input.bookingId as string, actor.id),
},
];
}

View File

@ -1,148 +0,0 @@
import { TradePassage, TradeRetrievalPort } from '@domain/ports/out/trade-assistant.port';
import {
WikiContribution,
WikiContributionStatus,
} from '@domain/entities/wiki-contribution.entity';
import { WikiContributionRepository } from '@domain/ports/out/wiki-contribution.repository';
import { CapabilityActor } from '@domain/services/capability-access';
import { Capability, CapabilityInputError, parseInput } from '../capability';
import { knowledgeCapabilities } from './knowledge.capabilities';
const actor: CapabilityActor = { id: 'user', organizationId: 'org', role: 'MANAGER' };
const BODY = `La règle du 24 heures impose de transmettre le manifeste de cargaison aux douanes du pays de destination avant le chargement du navire au port d'embarquement. Elle s'applique au transport maritime international et conditionne l'autorisation de charger. Un dépôt tardif expose l'expéditeur à un refus d'embarquement et à une immobilisation du conteneur au terminal.`;
const page = {
topic: 'douanes',
title: 'La règle des 24 heures',
section: 'Dépôt du manifeste',
body: BODY,
};
/** Passe l'entree par le meme schema que le registre, comme en production. */
const invoke = (capability: Capability, input: Record<string, unknown>) =>
capability.handler(parseInput(capability.inputSchema, input), actor);
describe('knowledgeCapabilities', () => {
let retrieval: jest.Mocked<TradeRetrievalPort>;
let contributions: jest.Mocked<WikiContributionRepository>;
const contribute = () => {
const capability = knowledgeCapabilities(retrieval, contributions).find(
c => c.policy.name === 'contribute_wiki_page'
);
if (!capability) throw new Error('contribute_wiki_page is not published');
return capability;
};
beforeEach(() => {
retrieval = { search: jest.fn().mockResolvedValue([]) };
contributions = {
findPublished: jest.fn().mockResolvedValue([]),
findForReview: jest.fn().mockResolvedValue([]),
findById: jest.fn().mockResolvedValue(null),
findByTitle: jest.fn().mockResolvedValue(null),
save: jest.fn().mockImplementation((c: WikiContribution) => Promise.resolve(c)),
revision: jest.fn().mockResolvedValue('0:none'),
};
});
it('keeps the wiki read-only when no repository is wired', () => {
expect(knowledgeCapabilities(retrieval).map(c => c.policy.name)).toEqual([
'search_documentation',
]);
});
it('declares the contribution as a write', () => {
expect(contribute().policy).toEqual({ name: 'contribute_wiki_page', scope: 'write' });
});
it('proposes a page the wiki does not cover, without publishing it', async () => {
const result = await invoke(contribute(), page);
expect(contributions.save).toHaveBeenCalledTimes(1);
const saved: WikiContribution = contributions.save.mock.calls[0][0];
expect(saved.title).toBe(page.title);
expect(saved.locale).toBe('fr');
expect(saved.authorUserId).toBe('user');
// Rien n'entre dans le wiki sans relecture : ni le statut, ni le resultat
// rendu au modele ne doivent laisser croire le contraire.
expect(saved.status).toBe(WikiContributionStatus.PENDING);
expect(result).toMatchObject({ status: 'pending_review' });
expect(result).not.toHaveProperty('url');
expect((result as { message: string }).message).toMatch(/validation par un administrateur/);
});
it('refuses a page the wiki already covers', async () => {
const covered: TradePassage = {
id: 'fr:douanes:2',
title: 'Procédures Douanières',
section: 'Manifeste',
href: '/dashboard/wiki/douanes',
text: 'La règle des 24 heures…',
score: 0.71,
};
retrieval.search.mockResolvedValue([covered]);
await expect(invoke(contribute(), page)).rejects.toThrow(CapabilityInputError);
expect(contributions.save).not.toHaveBeenCalled();
});
it('updates the existing page instead of duplicating the subject', async () => {
const existing = WikiContribution.create({
id: 'w1',
locale: 'fr',
...page,
authorUserId: 'user',
authorOrganizationId: 'org',
});
contributions.findByTitle.mockResolvedValue(existing);
const result = await invoke(contribute(), {
...page,
body: `${BODY} Le manifeste est déposé par le transitaire.`,
});
// Une revision ne repasse pas par le test de couverture : la page qu'elle
// remplace est justement celle que la recherche remonterait.
expect(retrieval.search).not.toHaveBeenCalled();
expect(contributions.save.mock.calls[0][0].id).toBe('w1');
expect(result).toMatchObject({ status: 'pending_review' });
});
it('does not withdraw a published page even for its original author', async () => {
const published = WikiContribution.create({
id: 'w1',
locale: 'fr',
...page,
authorUserId: actor.id,
authorOrganizationId: actor.organizationId,
}).publish('admin');
contributions.findByTitle.mockResolvedValue(published);
await expect(invoke(contribute(), page)).rejects.toThrow(CapabilityInputError);
expect(contributions.save).not.toHaveBeenCalled();
});
it('refuses content that recommends FCL, with a message the assistant can relay', async () => {
const body = `${BODY} Au-delà de 15 m³, nous recommandons le FCL.`;
await expect(invoke(contribute(), { ...page, body })).rejects.toThrow(
/ne publie pas de contenu qui recommande le FCL/
);
expect(contributions.save).not.toHaveBeenCalled();
});
it('refuses account-specific content', async () => {
const body = `${BODY} Pour votre dossier, le manifeste est parti le 3 mars.`;
await expect(invoke(contribute(), { ...page, body })).rejects.toThrow(/wiki est global/);
expect(contributions.save).not.toHaveBeenCalled();
});
it('rejects an unknown topic at the schema, before reaching the domain', () => {
expect(() => parseInput(contribute().inputSchema, { ...page, topic: 'divers' })).toThrow(
CapabilityInputError
);
});
});

View File

@ -1,247 +0,0 @@
import { randomUUID } from 'crypto';
import { TradeRetrievalPort } from '@domain/ports/out/trade-assistant.port';
import {
WikiContributionConflict,
WikiContributionRepository,
} from '@domain/ports/out/wiki-contribution.repository';
import {
WikiContribution,
WikiContributionRejected,
WikiContributionStatus,
} from '@domain/entities/wiki-contribution.entity';
import {
WIKI_REFUSAL_MESSAGES,
WIKI_TOPICS,
WikiRefusal,
} from '@domain/services/wiki-contribution-policy';
import { Capability, CapabilityInputError } from '../capability';
/**
* Le wiki Xpeditis, en lecture et en ecriture.
*
* **Lecture.** Le meme index que l'assistant integre : un agent externe repond
* a partir de la documentation interne, avec les liens vers les pages, plutot
* que de ses propres souvenirs sur le fret maritime.
*
* **Ecriture.** Le wiki a des trous, et ils se voient a l'usage : une question
* revient, la recherche ne remonte rien, l'assistant repond de memoire et la
* reponse n'est citable nulle part. `contribute_wiki_page` ferme ce trou au
* moment ou il apparait — mais seulement pour du savoir general sur le
* transport international, jamais pour un cas client. Les regles sont dans le
* domaine (`wiki-contribution-policy`), pas dans la description ci-dessous :
* le modele lit la description, il ne franchit que la politique.
*
* L'ecriture **propose**, elle ne publie pas. Une heuristique ecarte la faute
* franche, elle ne juge pas la justesse : la page part en relecture, et c'est
* un administrateur qui la fait entrer dans le wiki. Le nom de la capacite dit
* « contribuer », son resultat dit « en attente » — le modele doit annoncer une
* proposition, pas une publication.
*/
export function knowledgeCapabilities(
retrieval: TradeRetrievalPort,
contributions?: WikiContributionRepository
): Capability[] {
return [
{
policy: { name: 'search_documentation', scope: 'read' },
description:
"Recherche dans le wiki Xpeditis (Incoterms, douanes, conteneurs, IMDG, VGM, calcul du fret, transit times). Renvoie les extraits pertinents et le lien de la page d'origine.",
inputSchema: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'La question ou les mots-clés à rechercher.',
minLength: 2,
maxLength: 500,
},
language: {
type: 'string',
description: 'Langue de la documentation.',
enum: ['fr', 'en'],
default: 'fr',
},
limit: {
type: 'integer',
description: "Nombre maximum d'extraits.",
minimum: 1,
maximum: 10,
default: 4,
},
},
required: ['query'],
additionalProperties: false,
},
handler: async input => {
const passages = await retrieval.search(
input.query as string,
(input.language as string) ?? 'fr',
input.limit as number
);
return {
matches: passages.map(passage => ({
title: passage.title,
section: passage.section,
url: passage.href,
excerpt: passage.text,
score: passage.score,
})),
};
},
},
...(contributions ? [contributeWikiPage(retrieval, contributions)] : []),
];
}
/**
* Au-dessus de ce score, la recherche a trouve une page qui traite deja le
* sujet : contribuer reviendrait a ecrire une seconde version de ce que le
* wiki dit deja. Le seuil est au-dessus de celui de la recherche (0,45, voir
* `wiki-retriever`) : « en rapport avec » n'est pas « deja couvert ».
*/
const ALREADY_COVERED_SCORE = 0.62;
function contributeWikiPage(
retrieval: TradeRetrievalPort,
contributions: WikiContributionRepository
): Capability {
return {
policy: { name: 'contribute_wiki_page', scope: 'write' },
description:
"Propose au wiki Xpeditis une page d'information générale sur le transport international, quand la documentation ne couvre pas le sujet. La page part en relecture : elle n'est publiée qu'après validation par un administrateur. Réservé au savoir durable et valable pour tous les clients : jamais un cas client, un dossier, un tarif, un contenu recommandant le FCL, ni un sujet de transport national. Met à jour uniquement votre propre proposition non publiée si le titre est déjà pris.",
inputSchema: {
type: 'object',
properties: {
topic: {
type: 'string',
description: 'Sujet du wiki auquel rattacher la page.',
enum: WIKI_TOPICS,
},
title: {
type: 'string',
description: 'Titre de la page, court et descriptif.',
minLength: 5,
maxLength: 120,
},
section: {
type: 'string',
description: 'Intitulé de la section documentée.',
minLength: 3,
maxLength: 120,
},
body: {
type: 'string',
description:
'Le contenu, rédigé comme une page de documentation : autonome, factuel, sans cas client ni tarif.',
minLength: 200,
maxLength: 6000,
},
language: {
type: 'string',
description: 'Langue de rédaction.',
enum: ['fr', 'en'],
default: 'fr',
},
},
required: ['topic', 'title', 'section', 'body'],
additionalProperties: false,
},
handler: async (input, actor) => {
const locale = (input.language as string) ?? 'fr';
const topic = input.topic as string;
const title = input.title as string;
const section = input.section as string;
const body = input.body as string;
const existing = await contributions.findByTitle(locale, topic, title);
if (
existing &&
(existing.authorUserId !== actor.id ||
existing.authorOrganizationId !== actor.organizationId ||
existing.status === WikiContributionStatus.PUBLISHED)
) {
throw new CapabilityInputError(
'Cette page ne peut pas être modifiée par cette contribution.'
);
}
// Le doublon n'est teste que pour une page nouvelle : reviser un
// complement existant se heurterait sinon a ce complement lui-meme.
if (!existing) {
const covered = await alreadyCovered(retrieval, `${title} ${section}`, locale);
if (covered) {
throw new CapabilityInputError(
`Le wiki traite déjà ce sujet : « ${covered} ». Citez cette page au lieu d'en créer une autre.`
);
}
}
const page = reject(() =>
existing
? existing.revise(section, body)
: WikiContribution.create({
id: randomUUID(),
locale,
topic,
title,
section,
body,
authorUserId: actor.id,
authorOrganizationId: actor.organizationId,
})
);
let saved: WikiContribution;
try {
saved = await contributions.save(page, actor);
} catch (error) {
if (error instanceof WikiContributionConflict) {
throw new CapabilityInputError(
'La proposition a changé ou ce titre est déjà utilisé. Relisez la page avant de réessayer.'
);
}
throw error;
}
return {
// Le resultat dit l'etat reel, pas l'intention : le modele annonce une
// proposition en attente, jamais une page publiee.
status: 'pending_review' as const,
title: saved.title,
section: saved.section,
message: existing
? 'Proposition mise à jour. Elle sera publiée après validation par un administrateur Xpeditis.'
: 'Proposition enregistrée. Elle sera publiée après validation par un administrateur Xpeditis.',
};
},
};
}
/** Titre de la page qui couvre deja le sujet, s'il y en a une. */
async function alreadyCovered(
retrieval: TradeRetrievalPort,
query: string,
locale: string
): Promise<string | null> {
const [best] = await retrieval.search(query, locale, 1);
return best && best.score >= ALREADY_COVERED_SCORE ? `${best.title} — ${best.section}` : null;
}
/**
* Traduit un refus du domaine en erreur d'entree.
*
* `CapabilityInputError` revient au modele avec son message : il peut
* l'expliquer a l'utilisateur, ce qu'une exception technique ne permettrait
* pas.
*/
function reject(build: () => WikiContribution): WikiContribution {
try {
return build();
} catch (error) {
if (error instanceof WikiContributionRejected) {
throw new CapabilityInputError(WIKI_REFUSAL_MESSAGES[error.message as WikiRefusal]);
}
throw error;
}
}

View File

@ -1,111 +0,0 @@
import { CsvRateSearchService } from '@domain/services/csv-rate-search.service';
import { RateDirection } from '@domain/entities/csv-rate.entity';
import { Capability } from '../capability';
/** Au-dela, la reponse devient illisible pour un agent et couteuse en contexte. */
const MAX_RESULTS = 10;
/**
* Recherche tarifaire LCL — le coeur du produit.
*
* Le resultat est resume : un agent a besoin du transporteur, du delai et du
* total, pas de la structure complete des surcharges. Le detail reste
* accessible dans l'application, dont le lien est renvoye.
*/
export function ratesCapabilities(search: CsvRateSearchService): Capability[] {
return [
{
policy: { name: 'search_rates', scope: 'read' },
description:
'Recherche des tarifs de fret maritime LCL entre deux ports (codes UN/LOCODE, ex. FRLIO, CNSHA). Renvoie les offres disponibles avec transporteur, temps de transit et prix.',
inputSchema: {
type: 'object',
properties: {
origin: {
type: 'string',
description: 'Port de départ, code UN/LOCODE à 5 lettres (ex. FRLIO).',
minLength: 5,
maxLength: 5,
},
destination: {
type: 'string',
description: "Port d'arrivée, code UN/LOCODE à 5 lettres (ex. CNSHA).",
minLength: 5,
maxLength: 5,
},
volumeCBM: {
type: 'number',
description: 'Volume de la marchandise en mètres cubes.',
minimum: 0.01,
maximum: 1000,
},
weightKG: {
type: 'number',
description: 'Poids brut de la marchandise en kilogrammes.',
minimum: 1,
maximum: 1000000,
},
direction: {
type: 'string',
description: 'Sens de la grille tarifaire.',
enum: ['EXPORT', 'IMPORT'],
},
hasDangerousGoods: {
type: 'boolean',
description: 'La marchandise relève-t-elle de la réglementation IMDG ?',
default: false,
},
limit: {
type: 'integer',
description: "Nombre maximum d'offres renvoyées.",
minimum: 1,
maximum: MAX_RESULTS,
default: 5,
},
},
required: ['origin', 'destination', 'volumeCBM', 'weightKG'],
additionalProperties: false,
},
handler: async input => {
const output = await search.execute({
origin: (input.origin as string).toUpperCase(),
destination: (input.destination as string).toUpperCase(),
volumeCBM: input.volumeCBM as number,
weightKG: input.weightKG as number,
hasDangerousGoods: (input.hasDangerousGoods as boolean) ?? false,
direction: input.direction as RateDirection | undefined,
});
const limit = (input.limit as number) ?? 5;
return {
totalResults: output.totalResults,
offers: output.results.slice(0, limit).map(({ rate, priceBreakdown }) => ({
carrier: rate.companyName,
route: `${rate.originCode.toString()} → ${rate.destinationCode.toString()}`,
routing: rate.routing,
transitDays: rate.transitDays,
frequency: rate.frequency,
freight: {
amount: priceBreakdown.totalFreight,
currency: priceBreakdown.freightCurrency,
},
destinationCharges: {
amount: priceBreakdown.totalFob,
currency: priceBreakdown.fobCurrency,
},
dangerousGoods: priceBreakdown.dgSurchargeStatus,
validUntil: rate.validity.getEndDate(),
})),
bookInApp: '/dashboard/search-advanced',
};
},
},
{
policy: { name: 'list_carriers', scope: 'read' },
description: 'Liste les transporteurs dont les grilles tarifaires sont chargées.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
handler: async () => ({ carriers: await search.getAvailableCompanies() }),
},
];
}

View File

@ -1,237 +0,0 @@
import { ForbiddenException, NotFoundException } from '@nestjs/common';
import { CapabilityActor } from '@domain/services/capability-access';
import { CapabilityRegistry } from './capability.registry';
import { CapabilityInputError } from './capability';
/**
* Le registre est construit avec les vraies capacites : le test verifie donc le
* catalogue reellement expose, pas un catalogue de laboratoire.
*/
const retrieval = { search: jest.fn().mockResolvedValue([]) };
const rateSearch = {
execute: jest.fn().mockResolvedValue({ totalResults: 0, results: [] }),
getAvailableCompanies: jest.fn().mockResolvedValue(['CMA CGM']),
};
const bookings = {
getUserBookings: jest.fn().mockResolvedValue({ bookings: [], total: 0 }),
getOrganizationBookings: jest.fn().mockResolvedValue({ bookings: [], total: 0 }),
getBookingById: jest.fn().mockResolvedValue({ id: 'b1' }),
getUserStats: jest.fn().mockResolvedValue({ pending: 0 }),
cancelBooking: jest.fn().mockResolvedValue({ id: 'b1' }),
deleteBooking: jest.fn().mockResolvedValue({ success: true }),
};
const subscriptions = {
getSubscriptionOverview: jest.fn().mockResolvedValue({ plan: 'GOLD', status: 'ACTIVE' }),
};
const usersRepo = {
findAll: jest.fn().mockResolvedValue([]),
findByRole: jest.fn().mockResolvedValue([]),
countByOrganization: jest.fn().mockResolvedValue(0),
};
const organizationsRepo = { findAll: jest.fn().mockResolvedValue([]) };
const audit = { log: jest.fn().mockResolvedValue(undefined) };
/** Les doubles portent leurs propres types ; seul le passage au registre est force. */
const build = () =>
new CapabilityRegistry(
retrieval as never,
rateSearch as never,
bookings as never,
subscriptions as never,
usersRepo as never,
organizationsRepo as never,
audit as never
);
const registry = build();
const actor = (overrides: Partial<CapabilityActor> = {}): CapabilityActor => ({
id: 'u1',
organizationId: 'o1',
role: 'USER',
plan: 'BRONZE',
...overrides,
});
const names = (a: CapabilityActor) => registry.listFor(a).map(c => c.policy.name);
describe('CapabilityRegistry', () => {
beforeEach(() => jest.clearAllMocks());
it('exposes every capability under a unique name', () => {
const all = names(actor({ role: 'ADMIN' }));
expect(new Set(all).size).toBe(all.length);
expect(all).toEqual(expect.arrayContaining(['whoami', 'search_rates', 'list_my_bookings']));
});
it('hides organisation-wide capabilities from a plain user', () => {
expect(names(actor({ role: 'USER' }))).not.toContain('list_organization_bookings');
expect(names(actor({ role: 'USER' }))).not.toContain('get_subscription');
expect(names(actor({ role: 'MANAGER' }))).toContain('list_organization_bookings');
});
it('answers "unknown" for a capability the caller has no role for', async () => {
// Ne pas distinguer « interdit » de « inexistant » : sinon la liste filtree
// ne sert a rien, il suffirait de deviner les noms.
await expect(
registry.invoke('list_organization_bookings', {}, actor({ role: 'USER' }))
).rejects.toThrow(NotFoundException);
});
it('scopes every read to the caller, never to a requested identity', async () => {
await registry.invoke('list_my_bookings', { limit: 5 }, actor({ id: 'u42' }));
expect(bookings.getUserBookings).toHaveBeenCalledWith('u42', 1, 5);
});
it('routes organisation reads to the caller organisation', async () => {
await registry.invoke(
'list_organization_bookings',
{},
actor({ role: 'ADMIN', organizationId: 'o9' })
);
expect(bookings.getOrganizationBookings).toHaveBeenCalledWith('o9', 1, 20);
});
it('validates arguments before touching a service', async () => {
await expect(
registry.invoke('search_rates', { origin: 'FR', destination: 'CNSHA' }, actor())
).rejects.toThrow(CapabilityInputError);
expect(rateSearch.execute).not.toHaveBeenCalled();
});
it('normalises port codes to upper case before searching', async () => {
await registry.invoke(
'search_rates',
{ origin: 'frlio', destination: 'cnsha', volumeCBM: 4, weightKG: 500 },
actor()
);
expect(rateSearch.execute).toHaveBeenCalledWith(
expect.objectContaining({ origin: 'FRLIO', destination: 'CNSHA', volumeCBM: 4 })
);
});
it('reports the effective plan through whoami', async () => {
await expect(registry.invoke('whoami', {}, actor({ role: 'ADMIN' }))).resolves.toMatchObject({
role: 'ADMIN',
plan: 'PLATINIUM',
});
});
it('marks read capabilities as read-only and writes as not', () => {
const catalogue = registry.listFor(actor({ role: 'ADMIN' }));
const scopeOf = (name: string) => catalogue.find(c => c.policy.name === name)?.policy.scope;
expect(scopeOf('search_rates')).toBe('read');
expect(scopeOf('delete_unpaid_booking')).toBe('write');
});
it('lets a delete reach the service, which enforces the unpaid rule', async () => {
await registry.invoke('delete_unpaid_booking', { bookingId: 'b1' }, actor({ id: 'u1' }));
// Le registre ne redecide pas la regle metier : il transmet l'appelant et
// laisse le service refuser une reservation payee.
expect(bookings.deleteBooking).toHaveBeenCalledWith('b1', 'u1');
});
});
describe('journal des appels', () => {
beforeEach(() => jest.clearAllMocks());
it('records a successful invocation with its surface and scope', async () => {
await registry.invoke('whoami', {}, actor({ email: 'd@x.com' }), 'assistant');
expect(audit.log).toHaveBeenCalledWith(
expect.objectContaining({
action: 'agent_capability_invoked',
status: 'success',
userId: 'u1',
userEmail: 'd@x.com',
resourceName: 'whoami',
metadata: expect.objectContaining({ surface: 'assistant', scope: 'read' }),
})
);
});
it('records a refusal too — a repeated attempt is what a journal must reveal', async () => {
await expect(
registry.invoke('admin_list_users', {}, actor({ role: 'USER' }), 'mcp')
).rejects.toThrow();
expect(audit.log).toHaveBeenCalledWith(
expect.objectContaining({ status: 'failure', resourceName: 'admin_list_users' })
);
});
it('records a handler failure with its message', async () => {
bookings.getUserStats.mockRejectedValueOnce(new Error('database unavailable'));
await expect(registry.invoke('booking_statistics', {}, actor())).rejects.toThrow();
expect(audit.log).toHaveBeenCalledWith(
expect.objectContaining({ status: 'failure', errorMessage: 'database unavailable' })
);
});
it('defaults the surface to mcp when the caller does not say', async () => {
await registry.invoke('whoami', {}, actor());
expect(audit.log.mock.calls[0][0].metadata).toMatchObject({ surface: 'mcp' });
});
});
describe('capacites d administration', () => {
it('are visible to an ADMIN only', () => {
const adminNames = names(actor({ role: 'ADMIN' }));
expect(adminNames).toEqual(
expect.arrayContaining([
'admin_list_users',
'admin_list_organizations',
'admin_rate_grid_overview',
])
);
for (const role of ['MANAGER', 'USER', 'VIEWER']) {
expect(names(actor({ role }))).not.toContain('admin_list_users');
}
});
it('stay read-only until an explicit confirmation mechanism exists', () => {
const adminOnes = registry
.listFor(actor({ role: 'ADMIN' }))
.filter(c => c.policy.name.startsWith('admin_'));
expect(adminOnes.length).toBeGreaterThan(0);
expect(adminOnes.every(c => c.policy.scope === 'read')).toBe(true);
});
});
describe('plan-gated capabilities', () => {
/** Capacite fictive soumise a une fonctionnalite d'offre. */
const gated = build();
beforeAll(() => {
(gated as unknown as { capabilities: unknown[] }).capabilities = [
{
policy: { name: 'export_everything', scope: 'read', feature: 'api_access' },
description: '',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
handler: async () => ({ ok: true }),
},
];
});
it('says plainly that the plan is missing, because the feature can be bought', async () => {
await expect(gated.invoke('export_everything', {}, actor({ plan: 'SILVER' }))).rejects.toThrow(
ForbiddenException
);
});
it('allows it once the plan includes the feature', async () => {
await expect(gated.invoke('export_everything', {}, actor({ plan: 'GOLD' }))).resolves.toEqual({
ok: true,
});
});
});

View File

@ -1,170 +0,0 @@
import {
ForbiddenException,
Inject,
Injectable,
NotFoundException,
Optional,
} from '@nestjs/common';
import { TRADE_RETRIEVAL, TradeRetrievalPort } from '@domain/ports/out/trade-assistant.port';
import { CsvRateSearchService } from '@domain/services/csv-rate-search.service';
import {
CapabilityActor,
denialReason,
grantedCapabilities,
} from '@domain/services/capability-access';
import { AuditAction, AuditStatus } from '@domain/entities/audit-log.entity';
import { USER_REPOSITORY, UserRepository } from '@domain/ports/out/user.repository';
import {
ORGANIZATION_REPOSITORY,
OrganizationRepository,
} from '@domain/ports/out/organization.repository';
import {
WIKI_CONTRIBUTION_REPOSITORY,
WikiContributionRepository,
} from '@domain/ports/out/wiki-contribution.repository';
import { AuditService } from '../services/audit.service';
import { CsvBookingService } from '../services/csv-booking.service';
import { SubscriptionService } from '../services/subscription.service';
import { Capability, CapabilityInputError, parseInput } from './capability';
import { accountCapabilities } from './capabilities/account.capabilities';
import { adminCapabilities } from './capabilities/admin.capabilities';
import { bookingsCapabilities } from './capabilities/bookings.capabilities';
import { knowledgeCapabilities } from './capabilities/knowledge.capabilities';
import { ratesCapabilities } from './capabilities/rates.capabilities';
/**
* Catalogue des capacites du produit.
*
* Un seul endroit declare ce qu'un agent peut faire et sous quelles conditions.
* Les deux consommateurs — le serveur MCP pour les clients externes, l'assistant
* integre pour l'appel de fonctions — lisent ce meme catalogue : une capacite
* ajoutee ici devient disponible des deux cotes, avec les memes droits, sans
* qu'aucune des deux surfaces n'ait a etre modifiee.
*
* Ce registre n'implemente rien : chaque capacite delegue au service applicatif
* qui sert deja l'interface. Le produit n'a pas de seconde logique metier pour
* les agents, donc pas de seconde verite a maintenir.
*/
@Injectable()
export class CapabilityRegistry {
private readonly capabilities: Capability[];
constructor(
@Inject(TRADE_RETRIEVAL) retrieval: TradeRetrievalPort,
rateSearch: CsvRateSearchService,
bookings: CsvBookingService,
subscriptions: SubscriptionService,
@Inject(USER_REPOSITORY) users: UserRepository,
@Inject(ORGANIZATION_REPOSITORY) organizations: OrganizationRepository,
private readonly audit: AuditService,
// Optionnel : sans depot, le wiki reste en lecture seule pour les agents.
@Optional()
@Inject(WIKI_CONTRIBUTION_REPOSITORY)
wikiContributions?: WikiContributionRepository
) {
this.capabilities = [
...accountCapabilities(subscriptions),
...knowledgeCapabilities(retrieval, wikiContributions),
...ratesCapabilities(rateSearch),
...bookingsCapabilities(bookings),
...adminCapabilities(users, organizations, rateSearch),
];
const duplicate = findDuplicate(this.capabilities.map(c => c.policy.name));
if (duplicate) {
// Deux capacites homonymes rendraient l'appel ambigu : mieux vaut
// empecher le demarrage que resoudre au hasard.
throw new Error(`Duplicate capability name: ${duplicate}`);
}
}
/** Capacites visibles par cet appelant, dans l'ordre du catalogue. */
listFor(actor: CapabilityActor): Capability[] {
return grantedCapabilities(actor, this.capabilities);
}
/**
* Execute une capacite au nom de l'appelant.
*
* Une capacite hors droits repond « inconnue », comme si elle n'existait pas :
* la liste ne l'expose deja pas, et distinguer les deux cas revelerait
* l'existence de fonctions reservees.
*/
async invoke(
name: string,
rawInput: Record<string, unknown> | undefined,
actor: CapabilityActor,
surface: CapabilitySurface = 'mcp'
): Promise<unknown> {
const capability = this.capabilities.find(c => c.policy.name === name);
if (!capability || denialReason(actor, capability.policy) === 'role') {
await this.record(actor, surface, name, 'read', false, 'Unknown or forbidden capability');
throw new NotFoundException(`Unknown capability "${name}".`);
}
// Un refus lie a l'offre se dit, lui : la fonction existe, elle s'achete.
if (denialReason(actor, capability.policy) === 'plan') {
const message = `Capability "${name}" requires the "${capability.policy.feature}" feature, not included in your plan.`;
await this.record(actor, surface, name, capability.policy.scope, false, message);
throw new ForbiddenException(message);
}
try {
const input = parseInput(capability.inputSchema, rawInput);
const result = await capability.handler(input, actor);
await this.record(actor, surface, name, capability.policy.scope, true);
return result;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
await this.record(actor, surface, name, capability.policy.scope, false, message);
throw error;
}
}
/**
* Journalise l'appel.
*
* L'audit est pose ici, et non dans chaque adaptateur : le registre est le
* seul passage oblige des deux surfaces, donc le seul endroit ou la trace ne
* peut pas etre oubliee en ajoutant une capacite. Les refus sont journalises
* autant que les succes — c'est ce qui revele une tentative repetee.
*
* `AuditService.log` n'echoue jamais vers l'appelant : une panne du journal
* ne doit pas empecher une action deja autorisee.
*/
private async record(
actor: CapabilityActor,
surface: CapabilitySurface,
name: string,
scope: string,
success: boolean,
errorMessage?: string
): Promise<void> {
await this.audit.log({
action: AuditAction.AGENT_CAPABILITY_INVOKED,
status: success ? AuditStatus.SUCCESS : AuditStatus.FAILURE,
userId: actor.id,
userEmail: actor.email ?? 'unknown',
organizationId: actor.organizationId,
resourceType: 'capability',
resourceName: name,
metadata: { surface, scope, role: actor.role },
...(errorMessage ? { errorMessage } : {}),
});
}
}
/** D'ou vient l'appel : sert a distinguer les usages dans le journal. */
export type CapabilitySurface = 'mcp' | 'assistant';
export { CapabilityInputError };
function findDuplicate(names: string[]): string | null {
const seen = new Set<string>();
for (const name of names) {
if (seen.has(name)) return name;
seen.add(name);
}
return null;
}

View File

@ -1,84 +0,0 @@
import { CapabilityInputError, CapabilitySchema, parseInput } from './capability';
const schema: CapabilitySchema = {
type: 'object',
properties: {
origin: { type: 'string', description: '', minLength: 5, maxLength: 5 },
volumeCBM: { type: 'number', description: '', minimum: 0.01, maximum: 1000 },
limit: { type: 'integer', description: '', minimum: 1, maximum: 10, default: 5 },
direction: { type: 'string', description: '', enum: ['EXPORT', 'IMPORT'] },
dangerous: { type: 'boolean', description: '', default: false },
companies: { type: 'array', description: '', items: { type: 'string' } },
},
required: ['origin', 'volumeCBM'],
additionalProperties: false,
};
describe('parseInput', () => {
it('accepts a well-formed call and applies defaults', () => {
expect(parseInput(schema, { origin: 'FRLIO', volumeCBM: 4 })).toEqual({
origin: 'FRLIO',
volumeCBM: 4,
limit: 5,
dangerous: false,
});
});
it('coerces the numeric strings a language model tends to produce', () => {
const parsed = parseInput(schema, { origin: ' FRLIO ', volumeCBM: '4.5', limit: '3' });
expect(parsed).toMatchObject({ origin: 'FRLIO', volumeCBM: 4.5, limit: 3 });
});
it('treats null and empty string as absent', () => {
expect(
parseInput(schema, { origin: 'FRLIO', volumeCBM: 4, direction: null })
).not.toHaveProperty('direction');
expect(parseInput(schema, { origin: 'FRLIO', volumeCBM: 4, direction: '' })).not.toHaveProperty(
'direction'
);
});
it.each([
[{ volumeCBM: 4 }, 'Missing required parameter "origin"'],
[{ origin: 'FRLIO' }, 'Missing required parameter "volumeCBM"'],
[{ origin: 'FR', volumeCBM: 4 }, 'at least 5 characters'],
[{ origin: 'FRLIO', volumeCBM: 'beaucoup' }, 'must be a number'],
[{ origin: 'FRLIO', volumeCBM: 0 }, 'must be >= 0.01'],
[{ origin: 'FRLIO', volumeCBM: 4, limit: 2.5 }, 'whole number'],
[{ origin: 'FRLIO', volumeCBM: 4, limit: 99 }, 'must be <= 10'],
[{ origin: 'FRLIO', volumeCBM: 4, direction: 'BOTH' }, 'must be one of: EXPORT, IMPORT'],
[{ origin: 'FRLIO', volumeCBM: 4, dangerous: 'peut-être' }, 'must be true or false'],
[{ origin: 'FRLIO', volumeCBM: 4, companies: 'CMA' }, 'must be an array'],
])('rejects %p', (input, message) => {
expect(() => parseInput(schema, input as Record<string, unknown>)).toThrow(
CapabilityInputError
);
expect(() => parseInput(schema, input as Record<string, unknown>)).toThrow(
expect.objectContaining({ message: expect.stringContaining(message) })
);
});
it('refuses an invented parameter instead of passing it through', () => {
// Un modele improvise volontiers un champ : le laisser filer jusqu'au
// service reviendrait a lui laisser choisir la signature de l'appel.
expect(() => parseInput(schema, { origin: 'FRLIO', volumeCBM: 4, orgId: 'autre-org' })).toThrow(
'Unknown parameter "orgId"'
);
});
it('accepts a call with no arguments at all', () => {
const empty: CapabilitySchema = { type: 'object', properties: {}, additionalProperties: false };
expect(parseInput(empty, undefined)).toEqual({});
});
it('accepts booleans and arrays in their natural form', () => {
expect(
parseInput(schema, {
origin: 'FRLIO',
volumeCBM: 4,
dangerous: true,
companies: ['CMA CGM', 'MSC'],
})
).toMatchObject({ dangerous: true, companies: ['CMA CGM', 'MSC'] });
});
});

View File

@ -1,146 +0,0 @@
import { CapabilityActor, CapabilityPolicy } from '@domain/services/capability-access';
/**
* Sous-ensemble de JSON Schema utilise par les capacites.
*
* Le schema est ecrit une seule fois : il sert a la fois de contrat annonce aux
* clients MCP (`inputSchema`) et de regle de validation a l'entree. Deux
* sources auraient fini par diverger, et c'est la validation qui aurait perdu.
*/
export interface SchemaProperty {
type: 'string' | 'number' | 'integer' | 'boolean' | 'array';
description: string;
enum?: readonly string[];
minimum?: number;
maximum?: number;
minLength?: number;
maxLength?: number;
/** Pour `type: 'array'` uniquement. */
items?: { type: 'string' | 'number' };
default?: unknown;
}
export interface CapabilitySchema {
type: 'object';
properties: Record<string, SchemaProperty>;
required?: readonly string[];
additionalProperties: false;
}
export interface Capability {
policy: CapabilityPolicy;
/** Une phrase : ce que fait l'action, du point de vue de l'utilisateur. */
description: string;
inputSchema: CapabilitySchema;
handler: (input: Record<string, unknown>, actor: CapabilityActor) => Promise<unknown>;
}
/** Schema sans aucun parametre, pour les capacites qui n'en prennent pas. */
export const NO_INPUT: CapabilitySchema = {
type: 'object',
properties: {},
additionalProperties: false,
};
export class CapabilityInputError extends Error {}
/**
* Valide et normalise une entree contre son schema.
*
* Les entrees viennent d'un modele de langage : elles sont plausibles, pas
* fiables. Un nombre arrive en chaine, un champ facultatif arrive a `null`, un
* champ invente arrive en plus. La validation est donc stricte sur ce qui
* compte (types, valeurs autorisees, bornes) et refuse ce qu'elle ne connait
* pas, plutot que de le transmettre au service.
*/
export function parseInput(
schema: CapabilitySchema,
raw: Record<string, unknown> | undefined
): Record<string, unknown> {
const input = raw ?? {};
const parsed: Record<string, unknown> = {};
for (const key of Object.keys(input)) {
if (!(key in schema.properties)) {
throw new CapabilityInputError(`Unknown parameter "${key}".`);
}
}
for (const [key, property] of Object.entries(schema.properties)) {
const required = schema.required?.includes(key) ?? false;
const value = input[key];
if (value === undefined || value === null || value === '') {
if (required) throw new CapabilityInputError(`Missing required parameter "${key}".`);
if (property.default !== undefined) parsed[key] = property.default;
continue;
}
parsed[key] = coerce(key, property, value);
}
return parsed;
}
function coerce(key: string, property: SchemaProperty, value: unknown): unknown {
switch (property.type) {
case 'string': {
if (typeof value !== 'string') {
throw new CapabilityInputError(`Parameter "${key}" must be a string.`);
}
const text = value.trim();
if (property.enum && !property.enum.includes(text)) {
throw new CapabilityInputError(
`Parameter "${key}" must be one of: ${property.enum.join(', ')}.`
);
}
if (property.minLength !== undefined && text.length < property.minLength) {
throw new CapabilityInputError(
`Parameter "${key}" must be at least ${property.minLength} characters.`
);
}
if (property.maxLength !== undefined && text.length > property.maxLength) {
throw new CapabilityInputError(
`Parameter "${key}" must be at most ${property.maxLength} characters.`
);
}
return text;
}
case 'number':
case 'integer': {
// Un modele ecrit volontiers « 12.5 » plutot que 12.5 : la chaine
// numerique est acceptee, le texte non numerique refuse.
const numeric = typeof value === 'number' ? value : Number(String(value).trim());
if (!Number.isFinite(numeric)) {
throw new CapabilityInputError(`Parameter "${key}" must be a number.`);
}
if (property.type === 'integer' && !Number.isInteger(numeric)) {
throw new CapabilityInputError(`Parameter "${key}" must be a whole number.`);
}
if (property.minimum !== undefined && numeric < property.minimum) {
throw new CapabilityInputError(`Parameter "${key}" must be >= ${property.minimum}.`);
}
if (property.maximum !== undefined && numeric > property.maximum) {
throw new CapabilityInputError(`Parameter "${key}" must be <= ${property.maximum}.`);
}
return numeric;
}
case 'boolean': {
if (typeof value === 'boolean') return value;
const text = String(value).trim().toLowerCase();
if (text === 'true') return true;
if (text === 'false') return false;
throw new CapabilityInputError(`Parameter "${key}" must be true or false.`);
}
case 'array': {
if (!Array.isArray(value)) {
throw new CapabilityInputError(`Parameter "${key}" must be an array.`);
}
const itemType = property.items?.type ?? 'string';
return value.map(item => coerce(`${key}[]`, { type: itemType, description: '' }, item));
}
}
}

View File

@ -1,69 +0,0 @@
import { Subscription } from '@domain/entities/subscription.entity';
import { SubscriptionPlan } from '@domain/value-objects/subscription-plan.vo';
import {
SubscriptionStatus,
SubscriptionStatusType,
} from '@domain/value-objects/subscription-status.vo';
import { McpController } from './mcp.controller';
import { CapabilityRegistry } from './capability.registry';
import { SubscriptionService } from '../services/subscription.service';
// Real registry and account capability: stale client claims must not be echoed as rights.
describe('MCP current entitlement', () => {
it.each<[SubscriptionStatusType, string, string]>([
['UNPAID', 'MANAGER', 'BRONZE'],
['PAUSED', 'MANAGER', 'BRONZE'],
['ACTIVE', 'MANAGER', 'GOLD'],
['TRIALING', 'MANAGER', 'GOLD'],
['PAST_DUE', 'MANAGER', 'GOLD'],
['UNPAID', 'ADMIN', 'PLATINIUM'],
])('%s resolves live rights for %s', async (status, role, expected) => {
const subscription = Subscription.create({
id: 'sub',
organizationId: 'org',
plan: SubscriptionPlan.gold(),
}).updateStatus(SubscriptionStatus.create(status));
const subscriptions = { getOrCreateSubscription: jest.fn().mockResolvedValue(subscription) };
const registry = new CapabilityRegistry(
{} as never,
{} as never,
{} as never,
subscriptions as unknown as SubscriptionService,
{} as never,
{} as never,
{ log: jest.fn().mockResolvedValue(undefined) } as never
);
const controller = new McpController(registry, subscriptions as unknown as SubscriptionService);
const user = {
id: 'user',
organizationId: 'org',
email: 'test@example.test',
firstName: 'Test',
lastName: 'User',
role,
plan: 'GOLD',
};
const result = await controller.rpc(user, {
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name: 'whoami' },
});
expect(result).toMatchObject({
result: {
isError: false,
content: [
{
type: 'text',
text: JSON.stringify(
{ userId: 'user', organizationId: 'org', role, plan: expected },
null,
2
),
},
],
},
});
expect(subscriptions.getOrCreateSubscription).toHaveBeenCalledWith('org');
});
});

View File

@ -1,179 +0,0 @@
import { Body, Controller, HttpCode, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { CapabilityActor } from '@domain/services/capability-access';
import { CurrentUser, UserPayload } from '../decorators/current-user.decorator';
import { SubscriptionService } from '../services/subscription.service';
import { CapabilityInputError } from './capability';
import { CapabilityRegistry } from './capability.registry';
/**
* Serveur MCP d'Xpeditis.
*
* Expose les capacites du produit au protocole Model Context Protocol, sur une
* unique route HTTP. Le transport est volontairement minimal : un POST
* JSON-RPC, sans session ni flux SSE. Un serveur qui n'expose que des outils
* n'a rien a diffuser au client entre deux appels, et l'absence d'etat rend
* chaque requete authentifiable independamment — ce qui compte ici, puisque
* deux appels consecutifs peuvent venir de deux comptes differents.
*
* L'authentification n'est pas reimplementee : la route passe par le garde
* global `ApiKeyOrJwtGuard`, donc une cle API `X-API-Key` (offres Gold et
* Platinium) ou un jeton JWT. L'identite obtenue porte le role et l'offre, qui
* decident ensuite de ce que le catalogue laisse voir.
*
* Non couvert a ce stade : les ressources et les invites MCP, la negociation
* SSE, et les notifications serveur → client.
*/
const PROTOCOL_VERSION = '2025-06-18';
const SERVER_INFO = { name: 'xpeditis', version: '1.0.0' };
/** Codes d'erreur JSON-RPC 2.0. */
const enum RpcError {
InvalidRequest = -32600,
MethodNotFound = -32601,
InvalidParams = -32602,
InternalError = -32603,
}
interface RpcRequest {
jsonrpc?: string;
id?: string | number | null;
method?: string;
params?: Record<string, unknown>;
}
@ApiTags('MCP')
@ApiBearerAuth()
@Controller('mcp')
export class McpController {
constructor(
private readonly registry: CapabilityRegistry,
private readonly subscriptions: SubscriptionService
) {}
@Post()
@HttpCode(200)
@ApiOperation({
summary: 'Model Context Protocol endpoint',
description:
'JSON-RPC 2.0 endpoint exposing Xpeditis capabilities as MCP tools. Authenticate with an X-API-Key header (Gold and Platinium plans) or a JWT bearer token. Supported methods: initialize, tools/list, tools/call, ping.',
})
@ApiResponse({ status: 200, description: 'JSON-RPC response' })
@ApiResponse({ status: 401, description: 'Unauthorized' })
async rpc(@CurrentUser() user: UserPayload, @Body() body: RpcRequest | RpcRequest[]) {
// Un lot JSON-RPC est traite element par element, dans l'ordre reçu.
if (Array.isArray(body)) {
const responses = await Promise.all(body.map(entry => this.handle(user, entry)));
return responses.filter(response => response !== null);
}
return this.handle(user, body);
}
private async handle(user: UserPayload, request: RpcRequest) {
const id = request?.id ?? null;
// Une notification (sans `id`) n'attend pas de reponse : `notifications/initialized`
// arrive juste apres la poignee de main de tout client MCP.
if (id === null && request?.method?.startsWith('notifications/')) return null;
if (request?.jsonrpc !== '2.0' || typeof request.method !== 'string') {
return fail(id, RpcError.InvalidRequest, 'Invalid JSON-RPC 2.0 request.');
}
try {
switch (request.method) {
case 'initialize':
return ok(id, {
protocolVersion: PROTOCOL_VERSION,
capabilities: { tools: { listChanged: false } },
serverInfo: SERVER_INFO,
instructions:
"Xpeditis est une plateforme de réservation de fret maritime LCL. Les outils disponibles dépendent du rôle et de l'offre du compte authentifié : appelez `whoami` pour connaître les droits en cours. Pour une question de connaissance métier, préférez `search_documentation`, qui répond à partir du wiki Xpeditis.",
});
case 'ping':
return ok(id, {});
case 'tools/list': {
const actor = await this.actorOf(user);
return ok(id, {
tools: this.registry.listFor(actor).map(capability => ({
name: capability.policy.name,
description: capability.description,
inputSchema: capability.inputSchema,
annotations: { readOnlyHint: capability.policy.scope === 'read' },
})),
});
}
case 'tools/call': {
const name = request.params?.name;
if (typeof name !== 'string') {
return fail(id, RpcError.InvalidParams, 'Missing tool name.');
}
const actor = await this.actorOf(user);
const result = await this.registry.invoke(
name,
request.params?.arguments as Record<string, unknown> | undefined,
actor
);
return ok(id, {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
isError: false,
});
}
default:
return fail(id, RpcError.MethodNotFound, `Unknown method "${request.method}".`);
}
} catch (error) {
return this.toRpcError(id, request.method, error);
}
}
/**
* Une erreur d'outil se rend au modele, pas au transport : MCP demande de
* repondre `isError` dans le resultat pour qu'un agent puisse corriger son
* appel, la ou une erreur JSON-RPC interromprait l'echange.
*/
private toRpcError(id: string | number | null, method: string | undefined, error: unknown) {
const message = error instanceof Error ? error.message : String(error);
if (method === 'tools/call') {
const invalid = error instanceof CapabilityInputError;
return ok(id, {
content: [{ type: 'text', text: message }],
isError: true,
...(invalid ? {} : {}),
});
}
return fail(id, RpcError.InternalError, message);
}
/**
* Identite de l'appelant, completee de son offre.
*
* L'offre est relue a chaque appel pour appliquer les suspensions et les
* changements de droits, meme si un jeton porte encore une ancienne offre.
*/
private async actorOf(user: UserPayload & { plan?: string }): Promise<CapabilityActor> {
const subscription = await this.subscriptions.getOrCreateSubscription(user.organizationId);
return {
id: user.id,
organizationId: user.organizationId,
role: user.role,
email: user.email,
plan: subscription.accessPlan.value,
};
}
}
const ok = (id: string | number | null, result: unknown) => ({ jsonrpc: '2.0', id, result });
const fail = (id: string | number | null, code: number, message: string) => ({
jsonrpc: '2.0',
id,
error: { code, message },
});

View File

@ -1,41 +0,0 @@
import { Module } from '@nestjs/common';
import { TRADE_RETRIEVAL, TRADE_EMBEDDINGS } from '@domain/ports/out/trade-assistant.port';
import { OpenAiEmbeddingAdapter } from '@infrastructure/ai/openai-embedding.adapter';
import { WIKI_CONTRIBUTION_REPOSITORY } from '@domain/ports/out/wiki-contribution.repository';
import { WikiRetriever } from '@infrastructure/ai/wiki-retriever';
import { TypeOrmWikiContributionRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-wiki-contribution.repository';
import { CsvRateModule } from '@infrastructure/carriers/csv-loader/csv-rate.module';
import { AuditModule } from '../audit/audit.module';
import { CsvBookingsModule } from '../csv-bookings/csv-bookings.module';
import { OrganizationsModule } from '../organizations/organizations.module';
import { SubscriptionsModule } from '../subscriptions/subscriptions.module';
import { UsersModule } from '../users/users.module';
import { CapabilityRegistry } from './capability.registry';
import { McpController } from './mcp.controller';
/**
* Serveur MCP et registre de capacites.
*
* Le module n'apporte aucune logique metier : il assemble des services deja
* exposes ailleurs. C'est le point de la conception — les agents passent par
* les memes chemins que l'interface.
*/
@Module({
imports: [
CsvRateModule,
CsvBookingsModule,
SubscriptionsModule,
UsersModule,
OrganizationsModule,
AuditModule,
],
controllers: [McpController],
providers: [
CapabilityRegistry,
{ provide: TRADE_EMBEDDINGS, useClass: OpenAiEmbeddingAdapter },
{ provide: TRADE_RETRIEVAL, useClass: WikiRetriever },
{ provide: WIKI_CONTRIBUTION_REPOSITORY, useClass: TypeOrmWikiContributionRepository },
],
exports: [CapabilityRegistry],
})
export class McpModule {}

View File

@ -5,9 +5,8 @@
*/
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { JwtModule, JwtSignOptions } from '@nestjs/jwt';
import { JwtModule } from '@nestjs/jwt';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { NotificationsController } from '../controllers/notifications.controller';
import { NotificationsGateway } from '../gateways/notifications.gateway';
@ -18,14 +17,13 @@ import { NOTIFICATION_REPOSITORY } from '@domain/ports/out/notification.reposito
@Module({
imports: [
AuthModule,
TypeOrmModule.forFeature([NotificationOrmEntity]),
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
secret: configService.get<string>('JWT_SECRET'),
signOptions: {
expiresIn: configService.get<JwtSignOptions['expiresIn']>('JWT_ACCESS_EXPIRATION', '15m'),
expiresIn: configService.get<string>('JWT_ACCESS_EXPIRATION', '15m'),
},
}),
inject: [ConfigService],

View File

@ -9,7 +9,11 @@ import { TypeOrmOrganizationRepository } from '../../infrastructure/persistence/
import { OrganizationOrmEntity } from '../../infrastructure/persistence/typeorm/entities/organization.orm-entity';
@Module({
imports: [TypeOrmModule.forFeature([OrganizationOrmEntity]), UsersModule, NotificationsModule],
imports: [
TypeOrmModule.forFeature([OrganizationOrmEntity]),
UsersModule,
NotificationsModule,
],
controllers: [OrganizationsController],
providers: [
{

View File

@ -50,17 +50,11 @@ import { CarrierOrmEntity } from '../../infrastructure/persistence/typeorm/entit
cache: any,
rateQuoteRepo: any,
portRepo: any,
carrierRepo: any
carrierRepo: any,
) => {
return new RateSearchService(connectors, cache, rateQuoteRepo, portRepo, carrierRepo);
},
inject: [
'CarrierConnectors',
CACHE_PORT,
RATE_QUOTE_REPOSITORY,
PORT_REPOSITORY,
CARRIER_REPOSITORY,
],
inject: ['CarrierConnectors', CACHE_PORT, RATE_QUOTE_REPOSITORY, PORT_REPOSITORY, CARRIER_REPOSITORY],
},
],
exports: [RATE_QUOTE_REPOSITORY, RateSearchService],

View File

@ -1,56 +0,0 @@
import { ConflictException } from '@nestjs/common';
import { UserRepository } from '@domain/ports/out/user.repository';
import { User, UserRole } from '@domain/entities/user.entity';
import { AdminContinuityService } from './admin-continuity.service';
const user = (id: string, role: UserRole, isActive = true) =>
({ id, role, isActive, email: `${id}@xpeditis.com` }) as unknown as User;
function serviceWith(users: User[]) {
const userRepository = {
findAllActive: jest.fn(async () => users.filter(u => u.isActive)),
findById: jest.fn(async (id: string) => users.find(u => u.id === id) ?? null),
} as unknown as UserRepository;
return new AdminContinuityService(userRepository);
}
describe('AdminContinuityService', () => {
it('refuse de retirer le dernier admin actif, quelle que soit la maniere', async () => {
const onlyAdmin = user('a1', UserRole.ADMIN);
const service = serviceWith([onlyAdmin, user('u1', UserRole.USER)]);
await expect(service.assertKeepsAnActiveAdmin(onlyAdmin, null)).rejects.toBeInstanceOf(
ConflictException
);
await expect(
service.assertKeepsAnActiveAdmin(onlyAdmin, { role: UserRole.MANAGER, isActive: true })
).rejects.toBeInstanceOf(ConflictException);
await expect(
service.assertKeepsAnActiveAdmin(onlyAdmin, { role: UserRole.ADMIN, isActive: false })
).rejects.toBeInstanceOf(ConflictException);
await expect(service.assertCanErase('a1')).rejects.toBeInstanceOf(ConflictException);
});
it("autorise l'operation tant qu'un autre admin actif subsiste", async () => {
const first = user('a1', UserRole.ADMIN);
const service = serviceWith([first, user('a2', UserRole.ADMIN)]);
await expect(service.assertKeepsAnActiveAdmin(first, null)).resolves.toBeUndefined();
});
it('ne compte pas un admin desactive comme remplacant', async () => {
const first = user('a1', UserRole.ADMIN);
const service = serviceWith([first, user('a2', UserRole.ADMIN, false)]);
await expect(service.assertKeepsAnActiveAdmin(first, null)).rejects.toBeInstanceOf(
ConflictException
);
});
it("ne controle rien pour un compte qui n'est pas admin actif", async () => {
const service = serviceWith([user('u1', UserRole.USER)]);
await expect(service.assertCanErase('u1')).resolves.toBeUndefined();
await expect(service.assertCanErase('inconnu')).resolves.toBeUndefined();
});
});

View File

@ -1,61 +0,0 @@
/**
* Refuse, avant toute écriture, une opération qui laisserait la plateforme sans
* administrateur actif (suppression, rétrogradation, désactivation,
* auto-effacement RGPD).
*
* Ce contrôle donne un message clair ; il ne suffit pas seul : deux requêtes
* simultanées peuvent chacune voir l'autre administrateur encore actif. Le
* déclencheur PostgreSQL `trg_users_keep_active_admin` ferme ce cas — voir
* domain/services/admin-continuity.ts.
*/
import { ConflictException, Inject, Injectable } from '@nestjs/common';
import { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
import { User, UserRole } from '@domain/entities/user.entity';
import {
AdminState,
LAST_ACTIVE_ADMIN_CODE,
removesActiveAdmin,
} from '@domain/services/admin-continuity';
export function lastActiveAdminException(): ConflictException {
return new ConflictException({
statusCode: 409,
error: 'Conflict',
code: LAST_ACTIVE_ADMIN_CODE,
message:
'Impossible : la plateforme doit garder au moins un administrateur actif. ' +
'Promouvez ou réactivez d’abord un autre administrateur.',
});
}
@Injectable()
export class AdminContinuityService {
constructor(@Inject(USER_REPOSITORY) private readonly userRepository: UserRepository) {}
/**
* @param target compte modifié, dans son état actuel
* @param after état visé, ou `null` si le compte est effacé
*/
async assertKeepsAnActiveAdmin(target: User, after: AdminState | null): Promise<void> {
if (!removesActiveAdmin({ role: target.role, isActive: target.isActive }, after)) {
return;
}
const otherActiveAdmins = (await this.userRepository.findAllActive()).filter(
u => u.role === UserRole.ADMIN && u.id !== target.id
);
if (otherActiveAdmins.length === 0) {
throw lastActiveAdminException();
}
}
/** Variante pour un effacement dont on ne connaît que l'identifiant. */
async assertCanErase(userId: string): Promise<void> {
const target = await this.userRepository.findById(userId);
if (target) {
await this.assertKeepsAnActiveAdmin(target, null);
}
}
}

View File

@ -4,26 +4,27 @@
* Calculates KPIs and analytics data for dashboard
*/
import { Injectable } from '@nestjs/common';
import { Injectable, Inject } from '@nestjs/common';
import { BOOKING_REPOSITORY } from '@domain/ports/out/booking.repository';
import { BookingRepository } from '@domain/ports/out/booking.repository';
import { RATE_QUOTE_REPOSITORY } from '@domain/ports/out/rate-quote.repository';
import { RateQuoteRepository } from '@domain/ports/out/rate-quote.repository';
import { TypeOrmCsvBookingRepository } from '../../infrastructure/persistence/typeorm/repositories/csv-booking.repository';
import { CsvBooking, CsvBookingStatus } from '@domain/entities/csv-booking.entity';
export interface DashboardKPIs {
bookingsThisMonth: number;
/** Volume LCL du mois, en CBM. */
volumeCBM: number;
/** Commission Xpeditis encaissee sur les reservations acceptees, en EUR. */
totalTEUs: number;
estimatedRevenue: number;
pendingConfirmations: number;
bookingsThisMonthChange: number; // % change from last month
volumeCBMChange: number;
totalTEUsChange: number;
estimatedRevenueChange: number;
pendingConfirmationsChange: number;
}
export interface BookingsChartData {
/** Cles de mois ISO `YYYY-MM` ; la mise en forme revient au client. */
labels: string[];
labels: string[]; // Month names
data: number[]; // Booking counts
}
@ -32,7 +33,7 @@ export interface TopTradeLane {
originPort: string;
destinationPort: string;
bookingCount: number;
totalVolumeCBM: number;
totalTEUs: number;
avgPrice: number;
}
@ -40,10 +41,8 @@ export interface DashboardAlert {
id: string;
type: 'delay' | 'confirmation' | 'document' | 'payment' | 'info';
severity: 'low' | 'medium' | 'high' | 'critical';
/** Cle de traduction, resolue par le client. */
titleKey: string;
messageKey: string;
messageParams?: Record<string, string | number>;
title: string;
message: string;
bookingId?: string;
bookingNumber?: string;
createdAt: Date;
@ -74,94 +73,125 @@ export interface TopCarrier {
@Injectable()
export class AnalyticsService {
constructor(private readonly csvBookingRepository: TypeOrmCsvBookingRepository) {}
constructor(
@Inject(BOOKING_REPOSITORY)
private readonly bookingRepository: BookingRepository,
@Inject(RATE_QUOTE_REPOSITORY)
private readonly rateQuoteRepository: RateQuoteRepository,
private readonly csvBookingRepository: TypeOrmCsvBookingRepository
) {}
/**
* Calculate dashboard KPIs
*
* Source : `csv_bookings`. Les quatre methodes de ce bloc lisaient
* auparavant `bookingRepository.findByOrganization()`, c'est-a-dire la table
* `bookings` — absente du schema (aucune migration ne la cree). Les quatre
* endpoints repondaient donc 500 en permanence. Les reservations reelles du
* produit sont des reservations LCL portees par `csv_bookings`.
* Cached for 1 hour
*/
async calculateKPIs(organizationId: string): Promise<DashboardKPIs> {
const bookings = await this.csvBookingRepository.findByOrganizationId(organizationId);
const now = new Date();
const thisMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
const lastMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59);
const thisMonth = bookings.filter((b: CsvBooking) => b.requestedAt >= thisMonthStart);
const lastMonth = bookings.filter(
(b: CsvBooking) => b.requestedAt >= lastMonthStart && b.requestedAt < thisMonthStart
// Get all bookings for organization
const allBookings = await this.bookingRepository.findByOrganization(organizationId);
// This month bookings
const thisMonthBookings = allBookings.filter(b => b.createdAt >= thisMonthStart);
// Last month bookings
const lastMonthBookings = allBookings.filter(
b => b.createdAt >= lastMonthStart && b.createdAt <= lastMonthEnd
);
// LCL : le volume se mesure en CBM. Le TEU, unite du conteneur complet, ne
// veut rien dire ici — c'est ce que l'ancienne version calculait.
const volumeOf = (list: CsvBooking[]): number =>
list.reduce((sum, b) => sum + (Number(b.volumeCBM) || 0), 0);
// Calculate total TEUs (20' = 1 TEU, 40' = 2 TEU)
// Each container is an individual entity, so we count them
const calculateTEUs = (bookings: typeof allBookings): number => {
return bookings.reduce((total, booking) => {
return (
total +
booking.containers.reduce((containerTotal, container) => {
const teu = container.type.startsWith('20') ? 1 : 2;
return containerTotal + teu; // Each container counts as 1 or 2 TEU
}, 0)
);
}, 0);
};
// Le chiffre d'affaires est celui d'Xpeditis : la commission percue, pas le
// montant du fret qui revient au transporteur. Seules les reservations
// acceptees comptent.
const revenueOf = (list: CsvBooking[]): number =>
list
.filter(b => b.status === CsvBookingStatus.ACCEPTED)
.reduce((sum, b) => sum + (Number(b.commissionAmountEur) || 0), 0);
const totalTEUsThisMonth = calculateTEUs(thisMonthBookings);
const totalTEUsLastMonth = calculateTEUs(lastMonthBookings);
const pendingOf = (list: CsvBooking[]): number =>
list.filter(b => b.status === CsvBookingStatus.PENDING).length;
// Calculate estimated revenue (from rate quotes)
const calculateRevenue = async (bookings: typeof allBookings): Promise<number> => {
let total = 0;
for (const booking of bookings) {
try {
const rateQuote = await this.rateQuoteRepository.findById(booking.rateQuoteId);
if (rateQuote) {
total += rateQuote.pricing.totalAmount;
}
} catch (error) {
// Skip if rate quote not found
continue;
}
}
return total;
};
const volumeThisMonth = volumeOf(thisMonth);
const volumeLastMonth = volumeOf(lastMonth);
const revenueThisMonth = revenueOf(thisMonth);
const revenueLastMonth = revenueOf(lastMonth);
const pendingThisMonth = pendingOf(thisMonth);
const pendingLastMonth = pendingOf(lastMonth);
const estimatedRevenueThisMonth = await calculateRevenue(thisMonthBookings);
const estimatedRevenueLastMonth = await calculateRevenue(lastMonthBookings);
const change = (current: number, previous: number): number => {
// Pending confirmations (status = pending_confirmation)
const pendingThisMonth = thisMonthBookings.filter(
b => b.status.value === 'pending_confirmation'
).length;
const pendingLastMonth = lastMonthBookings.filter(
b => b.status.value === 'pending_confirmation'
).length;
// Calculate percentage changes
const calculateChange = (current: number, previous: number): number => {
if (previous === 0) return current > 0 ? 100 : 0;
return ((current - previous) / previous) * 100;
};
return {
bookingsThisMonth: thisMonth.length,
volumeCBM: volumeThisMonth,
estimatedRevenue: revenueThisMonth,
bookingsThisMonth: thisMonthBookings.length,
totalTEUs: totalTEUsThisMonth,
estimatedRevenue: estimatedRevenueThisMonth,
pendingConfirmations: pendingThisMonth,
bookingsThisMonthChange: change(thisMonth.length, lastMonth.length),
volumeCBMChange: change(volumeThisMonth, volumeLastMonth),
estimatedRevenueChange: change(revenueThisMonth, revenueLastMonth),
pendingConfirmationsChange: change(pendingThisMonth, pendingLastMonth),
bookingsThisMonthChange: calculateChange(thisMonthBookings.length, lastMonthBookings.length),
totalTEUsChange: calculateChange(totalTEUsThisMonth, totalTEUsLastMonth),
estimatedRevenueChange: calculateChange(estimatedRevenueThisMonth, estimatedRevenueLastMonth),
pendingConfirmationsChange: calculateChange(pendingThisMonth, pendingLastMonth),
};
}
/**
* Get bookings chart data for last 6 months
*
* Les etiquettes sont des cles ISO `YYYY-MM` : le service ignore la langue de
* l'utilisateur, la mise en forme du mois revient au client.
*/
async getBookingsChartData(organizationId: string): Promise<BookingsChartData> {
const bookings = await this.csvBookingRepository.findByOrganizationId(organizationId);
const now = new Date();
const labels: string[] = [];
const data: number[] = [];
for (let i = 5; i >= 0; i--) {
const monthStart = new Date(now.getFullYear(), now.getMonth() - i, 1);
const nextMonthStart = new Date(now.getFullYear(), now.getMonth() - i + 1, 1);
// Get bookings for last 6 months
const allBookings = await this.bookingRepository.findByOrganization(organizationId);
labels.push(
`${monthStart.getFullYear()}-${String(monthStart.getMonth() + 1).padStart(2, '0')}`
);
data.push(
bookings.filter(
(b: CsvBooking) => b.requestedAt >= monthStart && b.requestedAt < nextMonthStart
).length
);
for (let i = 5; i >= 0; i--) {
const monthDate = new Date(now.getFullYear(), now.getMonth() - i, 1);
const monthEnd = new Date(now.getFullYear(), now.getMonth() - i + 1, 0, 23, 59, 59);
// Month label (e.g., "Jan 2025")
const monthLabel = monthDate.toLocaleDateString('en-US', {
month: 'short',
year: 'numeric',
});
labels.push(monthLabel);
// Count bookings in this month
const count = allBookings.filter(
b => b.createdAt >= monthDate && b.createdAt <= monthEnd
).length;
data.push(count);
}
return { labels, data };
@ -171,115 +201,136 @@ export class AnalyticsService {
* Get top 5 trade lanes
*/
async getTopTradeLanes(organizationId: string): Promise<TopTradeLane[]> {
const bookings = await this.csvBookingRepository.findByOrganizationId(organizationId);
const allBookings = await this.bookingRepository.findByOrganization(organizationId);
// Group by route (origin-destination)
const routeMap = new Map<
string,
{
originPort: string;
destinationPort: string;
bookingCount: number;
totalVolumeCBM: number;
totalTEUs: number;
totalPrice: number;
}
>();
for (const booking of bookings) {
const originPort = booking.origin.getValue();
const destinationPort = booking.destination.getValue();
const routeKey = `${originPort} → ${destinationPort}`;
for (const booking of allBookings) {
try {
const rateQuote = await this.rateQuoteRepository.findById(booking.rateQuoteId);
if (!rateQuote) continue;
const entry = routeMap.get(routeKey) ?? {
// Get first and last ports from route
const originPort = rateQuote.route[0]?.portCode || 'UNKNOWN';
const destinationPort = rateQuote.route[rateQuote.route.length - 1]?.portCode || 'UNKNOWN';
const routeKey = `${originPort}-${destinationPort}`;
if (!routeMap.has(routeKey)) {
routeMap.set(routeKey, {
originPort,
destinationPort,
bookingCount: 0,
totalVolumeCBM: 0,
totalTEUs: 0,
totalPrice: 0,
};
entry.bookingCount++;
entry.totalVolumeCBM += Number(booking.volumeCBM) || 0;
entry.totalPrice += Number(booking.priceEUR) || 0;
routeMap.set(routeKey, entry);
});
}
return Array.from(routeMap.entries())
.map(([route, entry]) => ({
const route = routeMap.get(routeKey)!;
route.bookingCount++;
route.totalPrice += rateQuote.pricing.totalAmount;
// Calculate TEUs
const teus = booking.containers.reduce((total, container) => {
const teu = container.type.startsWith('20') ? 1 : 2;
return total + teu;
}, 0);
route.totalTEUs += teus;
} catch (error) {
continue;
}
}
// Convert to array and sort by booking count
const tradeLanes: TopTradeLane[] = Array.from(routeMap.entries()).map(([route, data]) => ({
route,
originPort: entry.originPort,
destinationPort: entry.destinationPort,
bookingCount: entry.bookingCount,
totalVolumeCBM: entry.totalVolumeCBM,
avgPrice: entry.bookingCount > 0 ? entry.totalPrice / entry.bookingCount : 0,
}))
.sort((a, b) => b.bookingCount - a.bookingCount)
.slice(0, 5);
originPort: data.originPort,
destinationPort: data.destinationPort,
bookingCount: data.bookingCount,
totalTEUs: data.totalTEUs,
avgPrice: data.totalPrice / data.bookingCount,
}));
// Sort by booking count and return top 5
return tradeLanes.sort((a, b) => b.bookingCount - a.bookingCount).slice(0, 5);
}
/**
* Get dashboard alerts
*
* Uniquement ce sur quoi l'utilisateur peut agir. Les libelles sont des cles
* de traduction resolues cote client : le service ne connait pas la langue.
*/
async getAlerts(organizationId: string): Promise<DashboardAlert[]> {
const bookings = await this.csvBookingRepository.findByOrganizationId(organizationId);
const alerts: DashboardAlert[] = [];
const allBookings = await this.bookingRepository.findByOrganization(organizationId);
const now = Date.now();
const oneDay = 24 * 60 * 60 * 1000;
// Check for pending confirmations (older than 24h)
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
const oldPendingBookings = allBookings.filter(
b => b.status.value === 'pending_confirmation' && b.createdAt < oneDayAgo
);
for (const booking of bookings) {
const waitedMs = now - booking.requestedAt.getTime();
const waitedDays = Math.floor(waitedMs / oneDay);
// En attente du transporteur au-dela de 48 h : la demande decroche.
if (booking.status === CsvBookingStatus.PENDING && waitedMs > 2 * oneDay) {
for (const booking of oldPendingBookings) {
alerts.push({
id: `pending-${booking.id}`,
type: 'confirmation',
severity: waitedDays >= 5 ? 'high' : 'medium',
titleKey: 'awaitingCarrier',
messageKey: 'awaitingCarrierSince',
messageParams: { days: waitedDays, carrier: booking.carrierName },
severity: 'medium',
title: 'Pending Confirmation',
message: `Booking ${booking.bookingNumber.value} is awaiting carrier confirmation for over 24 hours`,
bookingId: booking.id,
bookingNumber: booking.bookingNumber,
createdAt: booking.requestedAt,
bookingNumber: booking.bookingNumber.value,
createdAt: booking.createdAt,
isRead: false,
});
continue;
}
// Les devis non regles ne remontent plus ici : ils vivent dans
// « Historique des devis » et ne bloquent aucun envoi en cours.
// Refus recent : il faut replacer la marchandise.
// Check for bookings departing soon (within 7 days) with pending status
const sevenDaysFromNow = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
for (const booking of allBookings) {
try {
const rateQuote = await this.rateQuoteRepository.findById(booking.rateQuoteId);
if (rateQuote && rateQuote.route.length > 0) {
const etd = rateQuote.route[0].departure;
if (etd) {
const etdDate = new Date(etd);
if (
booking.status === CsvBookingStatus.REJECTED &&
booking.respondedAt &&
now - booking.respondedAt.getTime() < 7 * oneDay
etdDate <= sevenDaysFromNow &&
etdDate >= new Date() &&
booking.status.value === 'pending_confirmation'
) {
alerts.push({
id: `rejected-${booking.id}`,
type: 'info',
severity: 'medium',
titleKey: 'rejected',
messageKey: 'rejectedBy',
messageParams: { carrier: booking.carrierName },
id: `departure-${booking.id}`,
type: 'delay',
severity: 'high',
title: 'Departure Soon - Not Confirmed',
message: `Booking ${booking.bookingNumber.value} departs in ${Math.ceil(
(etdDate.getTime() - Date.now()) / (24 * 60 * 60 * 1000)
)} days but is not confirmed yet`,
bookingId: booking.id,
bookingNumber: booking.bookingNumber,
createdAt: booking.respondedAt,
bookingNumber: booking.bookingNumber.value,
createdAt: booking.createdAt,
isRead: false,
});
}
}
}
} catch (error) {
continue;
}
}
// Sort by severity (critical > high > medium > low)
const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
return alerts.sort(
(a, b) =>
severityOrder[a.severity] - severityOrder[b.severity] ||
b.createdAt.getTime() - a.createdAt.getTime()
);
alerts.sort((a, b) => severityOrder[a.severity] - severityOrder[b.severity]);
return alerts;
}
/**

View File

@ -17,9 +17,9 @@ import {
export interface LogAuditInput {
action: AuditAction;
status: AuditStatus;
userId: string | null;
userId: string;
userEmail: string;
organizationId: string | null;
organizationId: string;
resourceType?: string;
resourceId?: string;
resourceName?: string;
@ -89,15 +89,12 @@ export class AuditService {
/**
* Log failed action
*
* userId / organizationId are null when no user could be identified
* (e.g. a failed login) — never a placeholder string, the columns are uuid.
*/
async logFailure(
action: AuditAction,
userId: string | null,
userId: string,
userEmail: string,
organizationId: string | null,
organizationId: string,
errorMessage: string,
options?: {
resourceType?: string;

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