Compare commits
No commits in common. "main" and "bug_reload_infini" have entirely different histories.
main
...
bug_reload
@ -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.
|
||||
@ -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.
|
||||
@ -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
|
||||
```
|
||||
@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@ -1,2 +0,0 @@
|
||||
# All jobs use the existing ubuntu-latest runner label.
|
||||
{}
|
||||
@ -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."
|
||||
@ -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
|
||||
@ -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
|
||||
@ -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
|
||||
@ -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 }}
|
||||
@ -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 }}
|
||||
@ -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 }}
|
||||
@ -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
276
.github/workflows/cd-main.yml
vendored
Normal 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
316
.github/workflows/cd-preprod.yml
vendored
Normal 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
103
.github/workflows/ci.yml
vendored
Normal 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
145
.github/workflows/pr-checks.yml
vendored
Normal 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
|
||||
@ -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
1
.gitignore
vendored
@ -46,7 +46,6 @@ lerna-debug.log*
|
||||
docker-compose.override.yml
|
||||
stack-portainer.yaml
|
||||
tmp.stack-portainer.yaml
|
||||
stack-portainer-preprod.yaml
|
||||
|
||||
# Uploads
|
||||
uploads/
|
||||
|
||||
@ -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
277
AGENTS.md
@ -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/`
|
||||
@ -24,7 +24,6 @@ e2e
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
.env.*
|
||||
.env.local
|
||||
.env.development
|
||||
.env.test
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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 && \
|
||||
|
||||
@ -1,26 +1,26 @@
|
||||
#!/bin/sh
|
||||
echo "Starting Xpeditis Backend..."
|
||||
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
|
||||
echo "PostgreSQL is ready"
|
||||
break
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
echo "Attempt $attempt/$max_attempts - Retrying..."
|
||||
sleep 2
|
||||
done
|
||||
if [ $attempt -eq $max_attempts ]; then
|
||||
echo "Failed to connect to PostgreSQL"
|
||||
exit 1
|
||||
fi
|
||||
echo "Running database migrations..."
|
||||
node /app/run-migrations.js
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Migrations failed"
|
||||
exit 1
|
||||
fi
|
||||
echo "Starting NestJS application..."
|
||||
exec "$@"
|
||||
#!/bin/sh
|
||||
echo "Starting Xpeditis Backend..."
|
||||
echo "Waiting for PostgreSQL..."
|
||||
max_attempts=30
|
||||
attempt=0
|
||||
while [ $attempt -lt $max_attempts ]; do
|
||||
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
|
||||
attempt=$((attempt + 1))
|
||||
echo "Attempt $attempt/$max_attempts - Retrying..."
|
||||
sleep 2
|
||||
done
|
||||
if [ $attempt -eq $max_attempts ]; then
|
||||
echo "Failed to connect to PostgreSQL"
|
||||
exit 1
|
||||
fi
|
||||
echo "Running database migrations..."
|
||||
node /app/run-migrations.js
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Migrations failed"
|
||||
exit 1
|
||||
fi
|
||||
echo "Starting NestJS application..."
|
||||
exec "$@"
|
||||
|
||||
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
5189
apps/backend/package-lock.json
generated
5189
apps/backend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -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",
|
||||
@ -85,15 +84,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",
|
||||
|
||||
@ -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);
|
||||
});
|
||||
@ -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)}`);
|
||||
@ -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);
|
||||
});
|
||||
@ -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');
|
||||
|
||||
@ -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);
|
||||
});
|
||||
|
||||
@ -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.');
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { waitForPostgres, runMigrations };
|
||||
main().catch(error => {
|
||||
console.error('❌ Startup failed:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@ -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,
|
||||
],
|
||||
|
||||
@ -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: [
|
||||
|
||||
@ -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,
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
@ -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],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@ -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();
|
||||
});
|
||||
});
|
||||
@ -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'),
|
||||
},
|
||||
}),
|
||||
}),
|
||||
|
||||
@ -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
|
||||
}
|
||||
|
||||
@ -208,16 +207,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 +243,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 +403,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 +437,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 +452,6 @@ export class AuthService {
|
||||
plan,
|
||||
planFeatures,
|
||||
type: 'access',
|
||||
credentialVersion: this.credentialVersion(user),
|
||||
};
|
||||
|
||||
const refreshPayload: JwtPayload = {
|
||||
@ -483,7 +462,6 @@ export class AuthService {
|
||||
plan,
|
||||
planFeatures,
|
||||
type: 'refresh',
|
||||
credentialVersion: this.credentialVersion(user),
|
||||
rememberMe,
|
||||
};
|
||||
|
||||
|
||||
@ -13,7 +13,6 @@ export interface JwtPayload {
|
||||
role: string;
|
||||
organizationId: string;
|
||||
type: 'access' | 'refresh';
|
||||
credentialVersion?: string;
|
||||
iat?: number; // issued at
|
||||
exp?: number; // expiration
|
||||
}
|
||||
|
||||
@ -75,11 +75,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 +111,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 +143,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 +237,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 +268,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 +287,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}`);
|
||||
}
|
||||
|
||||
@ -802,8 +789,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}` };
|
||||
|
||||
@ -607,7 +607,9 @@ export class CsvRatesAdminController {
|
||||
// company's other grid (export vs import) would be deleted too.
|
||||
await this.csvConfigRepository.delete(config.companyName, config.direction);
|
||||
|
||||
this.logger.log(`Deleted CSV config and file for: ${config.companyName} (${config.direction})`);
|
||||
this.logger.log(
|
||||
`Deleted CSV config and file for: ${config.companyName} (${config.direction})`
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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',
|
||||
@ -402,16 +413,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}`);
|
||||
|
||||
@ -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(
|
||||
|
||||
@ -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';
|
||||
@ -86,20 +83,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 +143,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');
|
||||
}
|
||||
@ -178,7 +170,7 @@ export class CsvBookingsController {
|
||||
if (req.user.role !== 'ADMIN') {
|
||||
// Check the paid-reservation limit (free/Bronze plan = 5 paid shipments/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(
|
||||
@ -255,7 +247,7 @@ export class CsvBookingsController {
|
||||
): 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 max = subscription.plan.maxShipmentsPerYear;
|
||||
const unlimited = max === -1;
|
||||
const currentYear = new Date().getFullYear();
|
||||
const used = await this.shipmentCounter.countPaidShipmentsForOrganizationInYear(
|
||||
@ -295,8 +287,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 +310,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 +415,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 +435,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 +463,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 +506,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 +519,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 +546,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 +559,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 +568,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,47 +591,18 @@ 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.',
|
||||
'Edit cargo characteristics (volume, weight, pallets, notes) of a booking awaiting payment. Only the owner can edit, and only while the booking is PENDING_PAYMENT.',
|
||||
})
|
||||
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
|
||||
@ApiResponse({
|
||||
@ -685,14 +628,12 @@ export class CsvBookingsController {
|
||||
* 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.',
|
||||
'Re-apply a rate selection (carrier, route, container, transit, cargo, price) to a PENDING_PAYMENT booking. Only the owner can edit.',
|
||||
})
|
||||
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
|
||||
@ApiResponse({
|
||||
@ -718,21 +659,9 @@ export class CsvBookingsController {
|
||||
* 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 +715,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 +784,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({
|
||||
|
||||
@ -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);
|
||||
});
|
||||
});
|
||||
@ -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');
|
||||
}
|
||||
|
||||
@ -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);
|
||||
|
||||
|
||||
@ -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(),
|
||||
};
|
||||
}
|
||||
|
||||
@ -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();
|
||||
});
|
||||
});
|
||||
@ -42,7 +42,6 @@ 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 { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
|
||||
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
|
||||
@ -252,7 +251,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');
|
||||
}
|
||||
|
||||
@ -357,6 +356,7 @@ export class OrganizationsController {
|
||||
siren: organization.siren,
|
||||
requestedBy: user.email,
|
||||
},
|
||||
actionUrl: `/dashboard/admin/organizations`,
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
@ -326,7 +326,9 @@ export class RatesController {
|
||||
status: 401,
|
||||
description: 'Unauthorized - missing or invalid token',
|
||||
})
|
||||
async getAvailableOrigins(@Query('direction') direction?: string): Promise<AvailableOriginsDto> {
|
||||
async getAvailableOrigins(
|
||||
@Query('direction') direction?: string
|
||||
): Promise<AvailableOriginsDto> {
|
||||
this.logger.log(
|
||||
`Fetching available origin ports from CSV rates${direction ? ` (${direction})` : ''}`
|
||||
);
|
||||
|
||||
@ -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 };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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);
|
||||
});
|
||||
@ -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);
|
||||
// TODO: Send invitation email with temporary password
|
||||
this.logger.warn(
|
||||
`TODO: Send invitation email to ${dto.email} with temp password: ${tempPassword}`
|
||||
);
|
||||
|
||||
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
|
||||
);
|
||||
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') {
|
||||
|
||||
@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -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 });
|
||||
});
|
||||
});
|
||||
@ -265,7 +265,7 @@ export class UpdateCsvBookingDetailsDto {
|
||||
*
|
||||
* 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.
|
||||
* (possibly different) rate for a PENDING_PAYMENT booking.
|
||||
*/
|
||||
export class UpdateCsvBookingRateDto {
|
||||
@ApiProperty({ example: 'SSC Consolidation' })
|
||||
@ -451,23 +451,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 +526,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 +537,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',
|
||||
@ -700,10 +689,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',
|
||||
|
||||
@ -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;
|
||||
}
|
||||
@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -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);
|
||||
});
|
||||
});
|
||||
@ -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;
|
||||
}
|
||||
@ -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();
|
||||
});
|
||||
});
|
||||
@ -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(),
|
||||
};
|
||||
}
|
||||
|
||||
@ -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 {}
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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);
|
||||
});
|
||||
});
|
||||
@ -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;
|
||||
|
||||
@ -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 } });
|
||||
});
|
||||
});
|
||||
@ -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' };
|
||||
},
|
||||
};
|
||||
@ -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,
|
||||
};
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@ -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(),
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@ -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),
|
||||
},
|
||||
];
|
||||
}
|
||||
@ -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
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
@ -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() }),
|
||||
},
|
||||
];
|
||||
}
|
||||
@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -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;
|
||||
}
|
||||
@ -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'] });
|
||||
});
|
||||
});
|
||||
@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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');
|
||||
});
|
||||
});
|
||||
@ -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 },
|
||||
});
|
||||
@ -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 {}
|
||||
@ -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],
|
||||
|
||||
@ -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();
|
||||
});
|
||||
});
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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) ?? {
|
||||
originPort,
|
||||
destinationPort,
|
||||
bookingCount: 0,
|
||||
totalVolumeCBM: 0,
|
||||
totalPrice: 0,
|
||||
};
|
||||
// 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}`;
|
||||
|
||||
entry.bookingCount++;
|
||||
entry.totalVolumeCBM += Number(booking.volumeCBM) || 0;
|
||||
entry.totalPrice += Number(booking.priceEUR) || 0;
|
||||
routeMap.set(routeKey, entry);
|
||||
if (!routeMap.has(routeKey)) {
|
||||
routeMap.set(routeKey, {
|
||||
originPort,
|
||||
destinationPort,
|
||||
bookingCount: 0,
|
||||
totalTEUs: 0,
|
||||
totalPrice: 0,
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(routeMap.entries())
|
||||
.map(([route, entry]) => ({
|
||||
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);
|
||||
// Convert to array and sort by booking count
|
||||
const tradeLanes: TopTradeLane[] = Array.from(routeMap.entries()).map(([route, data]) => ({
|
||||
route,
|
||||
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);
|
||||
for (const booking of oldPendingBookings) {
|
||||
alerts.push({
|
||||
id: `pending-${booking.id}`,
|
||||
type: 'confirmation',
|
||||
severity: 'medium',
|
||||
title: 'Pending Confirmation',
|
||||
message: `Booking ${booking.bookingNumber.value} is awaiting carrier confirmation for over 24 hours`,
|
||||
bookingId: booking.id,
|
||||
bookingNumber: booking.bookingNumber.value,
|
||||
createdAt: booking.createdAt,
|
||||
isRead: false,
|
||||
});
|
||||
}
|
||||
|
||||
// En attente du transporteur au-dela de 48 h : la demande decroche.
|
||||
if (booking.status === CsvBookingStatus.PENDING && waitedMs > 2 * oneDay) {
|
||||
alerts.push({
|
||||
id: `pending-${booking.id}`,
|
||||
type: 'confirmation',
|
||||
severity: waitedDays >= 5 ? 'high' : 'medium',
|
||||
titleKey: 'awaitingCarrier',
|
||||
messageKey: 'awaitingCarrierSince',
|
||||
messageParams: { days: waitedDays, carrier: booking.carrierName },
|
||||
bookingId: booking.id,
|
||||
bookingNumber: booking.bookingNumber,
|
||||
createdAt: booking.requestedAt,
|
||||
isRead: false,
|
||||
});
|
||||
// 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 (
|
||||
etdDate <= sevenDaysFromNow &&
|
||||
etdDate >= new Date() &&
|
||||
booking.status.value === 'pending_confirmation'
|
||||
) {
|
||||
alerts.push({
|
||||
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.value,
|
||||
createdAt: booking.createdAt,
|
||||
isRead: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
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.
|
||||
if (
|
||||
booking.status === CsvBookingStatus.REJECTED &&
|
||||
booking.respondedAt &&
|
||||
now - booking.respondedAt.getTime() < 7 * oneDay
|
||||
) {
|
||||
alerts.push({
|
||||
id: `rejected-${booking.id}`,
|
||||
type: 'info',
|
||||
severity: 'medium',
|
||||
titleKey: 'rejected',
|
||||
messageKey: 'rejectedBy',
|
||||
messageParams: { carrier: booking.carrierName },
|
||||
bookingId: booking.id,
|
||||
bookingNumber: booking.bookingNumber,
|
||||
createdAt: booking.respondedAt,
|
||||
isRead: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -1,133 +0,0 @@
|
||||
import { ServiceUnavailableException } from '@nestjs/common';
|
||||
import { CsvBookingService } from './csv-booking.service';
|
||||
import { CreateCsvBookingDto } from '../dto/csv-booking.dto';
|
||||
|
||||
describe('Booking fee failure boundary', () => {
|
||||
const setup = () => {
|
||||
const subscriptionService = { getOrCreateSubscription: jest.fn() };
|
||||
const booking = {
|
||||
id: 'booking',
|
||||
organizationId: 'org',
|
||||
accept: jest.fn(),
|
||||
applyBookingFee: jest.fn(),
|
||||
};
|
||||
const repo = {
|
||||
findByToken: jest.fn().mockResolvedValue(booking),
|
||||
repository: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
};
|
||||
const service = new CsvBookingService(
|
||||
repo as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
subscriptionService as never,
|
||||
{} as never
|
||||
);
|
||||
const upload = jest
|
||||
.spyOn(service as unknown as { uploadDocuments: () => Promise<unknown[]> }, 'uploadDocuments')
|
||||
.mockResolvedValue([]);
|
||||
return { service, subscriptionService, repo, booking, upload };
|
||||
};
|
||||
|
||||
it('refuses creation before uploading or saving when the fee is unknown', async () => {
|
||||
const { service, subscriptionService, repo, upload } = setup();
|
||||
subscriptionService.getOrCreateSubscription.mockRejectedValue(
|
||||
new Error('dependency unavailable')
|
||||
);
|
||||
await expect(
|
||||
service.createBooking({} as CreateCsvBookingDto, [{} as Express.Multer.File], 'user', 'org')
|
||||
).rejects.toBeInstanceOf(ServiceUnavailableException);
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
expect(repo.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not accept or save a booking when the fee lookup fails', async () => {
|
||||
const { service, subscriptionService, repo, booking } = setup();
|
||||
subscriptionService.getOrCreateSubscription.mockRejectedValue(
|
||||
new Error('dependency unavailable')
|
||||
);
|
||||
await expect(service.acceptBooking('test-token')).rejects.toBeInstanceOf(
|
||||
ServiceUnavailableException
|
||||
);
|
||||
expect(booking.accept).not.toHaveBeenCalled();
|
||||
expect(repo.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[15, 'QUOTE'],
|
||||
[-1, 'PENDING'],
|
||||
])('preserves creation for a known fee %s', async (fee, expectedStatus) => {
|
||||
const { service, subscriptionService, repo, upload } = setup();
|
||||
subscriptionService.getOrCreateSubscription.mockResolvedValue({ bookingFeeEur: fee });
|
||||
upload.mockResolvedValue([
|
||||
{
|
||||
id: 'doc',
|
||||
type: 'OTHER',
|
||||
fileName: 'test.pdf',
|
||||
filePath: 'test',
|
||||
mimeType: 'application/pdf',
|
||||
size: 1,
|
||||
uploadedAt: new Date(),
|
||||
},
|
||||
]);
|
||||
repo.create.mockImplementation(async value => value);
|
||||
const mail = jest
|
||||
.spyOn(
|
||||
service as unknown as { sendCarrierBookingRequest: () => Promise<void> },
|
||||
'sendCarrierBookingRequest'
|
||||
)
|
||||
.mockResolvedValue(undefined);
|
||||
jest
|
||||
.spyOn(
|
||||
service as unknown as { notifyBookingRequestSent: () => Promise<void> },
|
||||
'notifyBookingRequestSent'
|
||||
)
|
||||
.mockResolvedValue(undefined);
|
||||
const result = await service.createBooking(
|
||||
{
|
||||
carrierName: 'Carrier',
|
||||
carrierEmail: 'carrier@example.test',
|
||||
origin: 'FRLEH',
|
||||
destination: 'CNSHA',
|
||||
volumeCBM: 1,
|
||||
weightKG: 100,
|
||||
palletCount: 1,
|
||||
priceUSD: 100,
|
||||
priceEUR: 90,
|
||||
primaryCurrency: 'EUR',
|
||||
transitDays: 10,
|
||||
containerType: 'LCL',
|
||||
} as CreateCsvBookingDto,
|
||||
[{} as Express.Multer.File],
|
||||
'user',
|
||||
'org'
|
||||
);
|
||||
expect(result.status).toBe(expectedStatus);
|
||||
expect(result.commissionAmountEur).toBe(fee === -1 ? 0 : fee);
|
||||
expect(repo.create).toHaveBeenCalledTimes(1);
|
||||
expect(mail).toHaveBeenCalledTimes(fee === -1 ? 1 : 0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[15, 15],
|
||||
[10, 10],
|
||||
[5, 5],
|
||||
[-1, 0],
|
||||
[0, 0],
|
||||
])('preserves fee %s as %s', async (fee, expected) => {
|
||||
const { service, subscriptionService } = setup();
|
||||
subscriptionService.getOrCreateSubscription.mockResolvedValue({ bookingFeeEur: fee });
|
||||
await expect(service['resolveBookingFeeEur']('org')).resolves.toBe(expected);
|
||||
});
|
||||
|
||||
it.each([undefined, NaN, Infinity, -2])('rejects an invalid fee %s', async fee => {
|
||||
const { service, subscriptionService } = setup();
|
||||
subscriptionService.getOrCreateSubscription.mockResolvedValue({ bookingFeeEur: fee });
|
||||
await expect(service['resolveBookingFeeEur']('org')).rejects.toBeInstanceOf(
|
||||
ServiceUnavailableException
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -1,24 +0,0 @@
|
||||
import { CsvBookingService } from './csv-booking.service';
|
||||
import { CsvBooking } from '@domain/entities/csv-booking.entity';
|
||||
|
||||
describe('customer booking response', () => {
|
||||
it('omits carrier capabilities while preserving booking information', () => {
|
||||
const booking = {
|
||||
id: 'booking-1',
|
||||
primaryCurrency: 'EUR',
|
||||
confirmationToken: 'carrier-secret',
|
||||
origin: { getValue: () => 'FRLEH' },
|
||||
destination: { getValue: () => 'CNSHA' },
|
||||
documents: [],
|
||||
getRouteDescription: () => 'FRLEH → CNSHA',
|
||||
isExpired: () => false,
|
||||
getPriceInCurrency: () => 100,
|
||||
} as unknown as CsvBooking;
|
||||
const service = Object.create(CsvBookingService.prototype) as CsvBookingService;
|
||||
const response = service['toResponseDto'](booking);
|
||||
expect(response.id).toBe('booking-1');
|
||||
expect(response.price).toBe(100);
|
||||
expect(response).not.toHaveProperty('confirmationToken');
|
||||
expect(JSON.stringify(response)).not.toContain('carrier-secret');
|
||||
});
|
||||
});
|
||||
@ -1,104 +0,0 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { CsvBookingService } from './csv-booking.service';
|
||||
import { CsvBookingStatus } from '@domain/entities/csv-booking.entity';
|
||||
|
||||
/**
|
||||
* Validation d'un virement par un administrateur : le booking passe en PENDING
|
||||
* et la demande part chez le transporteur. Un echec de cet email etait avale
|
||||
* sans que l'administrateur le sache.
|
||||
*/
|
||||
|
||||
function pendingTransferBooking() {
|
||||
const booking = {
|
||||
id: 'b-1',
|
||||
bookingNumber: 'XPD-2026-AAAAAA',
|
||||
userId: 'u-1',
|
||||
organizationId: 'org-1',
|
||||
carrierName: 'SSC Consolidation',
|
||||
carrierEmail: 'booking@ssc.test',
|
||||
origin: { getValue: () => 'FRLEH' },
|
||||
destination: { getValue: () => 'EGEDK' },
|
||||
volumeCBM: 2.4,
|
||||
weightKG: 850,
|
||||
palletCount: 2,
|
||||
priceUSD: 200,
|
||||
priceEUR: 180,
|
||||
primaryCurrency: 'EUR',
|
||||
transitDays: 11,
|
||||
containerType: 'LCL',
|
||||
status: CsvBookingStatus.PENDING_BANK_TRANSFER as CsvBookingStatus,
|
||||
documents: [],
|
||||
confirmationToken: 'token',
|
||||
requestedAt: new Date('2026-09-01T10:00:00Z'),
|
||||
notes: undefined,
|
||||
getRouteDescription: () => 'FRLEH → EGEDK',
|
||||
isExpired: () => false,
|
||||
getPriceInCurrency: () => 180,
|
||||
options: {},
|
||||
markBankTransferValidated() {
|
||||
booking.status = CsvBookingStatus.PENDING;
|
||||
},
|
||||
};
|
||||
return booking;
|
||||
}
|
||||
|
||||
function buildService(options: { emailFails: boolean }) {
|
||||
const booking = pendingTransferBooking();
|
||||
const csvBookingRepository = {
|
||||
findById: jest.fn(async () => booking),
|
||||
update: jest.fn(async (b: unknown) => b),
|
||||
repository: {
|
||||
findOne: jest.fn(async () => ({ bookingNumber: booking.bookingNumber, passwordHash: null })),
|
||||
save: jest.fn(async (b: unknown) => b),
|
||||
},
|
||||
};
|
||||
const emailAdapter = {
|
||||
sendCsvBookingRequest: jest.fn(async () => {
|
||||
if (options.emailFails) throw new Error('550 sender not valid');
|
||||
}),
|
||||
};
|
||||
const notificationRepository = { save: jest.fn(async () => undefined) };
|
||||
const unused = {} as never;
|
||||
|
||||
const service = new CsvBookingService(
|
||||
csvBookingRepository as never,
|
||||
notificationRepository as never,
|
||||
emailAdapter as never,
|
||||
unused,
|
||||
unused,
|
||||
unused,
|
||||
unused
|
||||
);
|
||||
return { service, booking, emailAdapter };
|
||||
}
|
||||
|
||||
describe('CsvBookingService.validateBankTransfer', () => {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
|
||||
jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
it('active le booking et envoie la demande au transporteur', async () => {
|
||||
const { service, booking, emailAdapter } = buildService({ emailFails: false });
|
||||
|
||||
const result = await service.validateBankTransfer('b-1');
|
||||
|
||||
expect(booking.status).toBe(CsvBookingStatus.PENDING);
|
||||
expect(emailAdapter.sendCsvBookingRequest).toHaveBeenCalledWith(
|
||||
'booking@ssc.test',
|
||||
expect.objectContaining({ bookingNumber: 'XPD-2026-AAAAAA', confirmationToken: 'token' })
|
||||
);
|
||||
expect(result.carrierEmailSent).toBe(true);
|
||||
}, 20000);
|
||||
|
||||
it("signale l'echec de l'email au lieu de l'avaler, sans annuler la validation", async () => {
|
||||
const { service, booking } = buildService({ emailFails: true });
|
||||
|
||||
const result = await service.validateBankTransfer('b-1');
|
||||
|
||||
expect(booking.status).toBe(CsvBookingStatus.PENDING);
|
||||
expect(result.carrierEmailSent).toBe(false);
|
||||
}, 20000);
|
||||
});
|
||||
@ -1,118 +0,0 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { CsvBookingService } from './csv-booking.service';
|
||||
import { anonymisedEmail } from '@domain/services/data-retention';
|
||||
|
||||
/**
|
||||
* Reservations et devis partages au sein d'une entreprise : chaque membre voit
|
||||
* les lignes de ses collegues, avec le nom de leur auteur.
|
||||
*/
|
||||
|
||||
const ORG = 'org-1';
|
||||
|
||||
const booking = (id: string, userId: string, organizationId = ORG) => ({
|
||||
id,
|
||||
bookingNumber: `XPD-2026-${id.toUpperCase()}`,
|
||||
userId,
|
||||
organizationId,
|
||||
carrierName: 'SSC Consolidation',
|
||||
carrierEmail: 'booking@ssc.test',
|
||||
origin: { getValue: () => 'FRLEH' },
|
||||
destination: { getValue: () => 'EGEDK' },
|
||||
volumeCBM: 2.4,
|
||||
weightKG: 850,
|
||||
palletCount: 2,
|
||||
priceUSD: 200,
|
||||
priceEUR: 180,
|
||||
primaryCurrency: 'EUR',
|
||||
transitDays: 11,
|
||||
containerType: 'LCL',
|
||||
status: 'QUOTE',
|
||||
documents: [],
|
||||
confirmationToken: 'token',
|
||||
requestedAt: new Date('2026-09-01T10:00:00Z'),
|
||||
getRouteDescription: () => 'FRLEH → EGEDK',
|
||||
isExpired: () => false,
|
||||
getPriceInCurrency: () => 180,
|
||||
options: {},
|
||||
});
|
||||
|
||||
const member = (id: string, firstName: string, lastName: string, email = `${id}@acme.test`) => ({
|
||||
id,
|
||||
email,
|
||||
firstName,
|
||||
lastName,
|
||||
});
|
||||
|
||||
function buildService(
|
||||
bookings: ReturnType<typeof booking>[],
|
||||
members: ReturnType<typeof member>[]
|
||||
) {
|
||||
const csvBookingRepository = {
|
||||
findByOrganizationId: jest.fn(async (orgId: string) =>
|
||||
bookings.filter(b => b.organizationId === orgId)
|
||||
),
|
||||
findById: jest.fn(async (id: string) => bookings.find(b => b.id === id) ?? null),
|
||||
repository: { findOne: jest.fn(async () => null) },
|
||||
};
|
||||
const userRepository = {
|
||||
findByOrganization: jest.fn(async () => members),
|
||||
findById: jest.fn(async (id: string) => members.find(m => m.id === id) ?? null),
|
||||
};
|
||||
const unused = {} as never;
|
||||
|
||||
const service = new CsvBookingService(
|
||||
csvBookingRepository as never,
|
||||
unused,
|
||||
unused,
|
||||
unused,
|
||||
unused,
|
||||
unused,
|
||||
userRepository as never
|
||||
);
|
||||
return { service, userRepository };
|
||||
}
|
||||
|
||||
describe('CsvBookingService — reservations de l’entreprise', () => {
|
||||
it('liste les reservations de tous les membres, avec le nom de leur auteur', async () => {
|
||||
const { service, userRepository } = buildService(
|
||||
[booking('a', 'marie'), booking('b', 'paul'), booking('c', 'erased'), booking('d', 'gone')],
|
||||
[
|
||||
member('marie', 'Marie', 'Dupont'),
|
||||
member('paul', '', '', 'paul@acme.test'),
|
||||
member('erased', 'anonymised', 'anonymised', anonymisedEmail('erased')),
|
||||
]
|
||||
);
|
||||
|
||||
const result = await service.getOrganizationBookings(ORG, 1, 100);
|
||||
|
||||
expect(result.total).toBe(4);
|
||||
expect(result.bookings.map(b => [b.userId, b.createdByName])).toEqual([
|
||||
['marie', 'Marie Dupont'],
|
||||
// Sans nom renseigne, l'adresse sert de libelle.
|
||||
['paul', 'paul@acme.test'],
|
||||
// Compte efface : aucune identite ne ressort.
|
||||
['erased', null],
|
||||
['gone', null],
|
||||
]);
|
||||
// Une seule requete pour les membres, pas une par reservation.
|
||||
expect(userRepository.findByOrganization).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('laisse un collegue de la meme entreprise consulter une reservation', async () => {
|
||||
const { service } = buildService([booking('a', 'marie')], [member('marie', 'Marie', 'Dupont')]);
|
||||
|
||||
const dto = await service.getBookingById('a', 'paul', undefined, ORG);
|
||||
|
||||
expect(dto.id).toBe('a');
|
||||
expect(dto.createdByName).toBe('Marie Dupont');
|
||||
});
|
||||
|
||||
it("refuse la consultation a un utilisateur d'une autre entreprise", async () => {
|
||||
const { service } = buildService([booking('a', 'marie')], [member('marie', 'Marie', 'Dupont')]);
|
||||
|
||||
await expect(service.getBookingById('a', 'intrus', undefined, 'org-2')).rejects.toBeInstanceOf(
|
||||
NotFoundException
|
||||
);
|
||||
await expect(service.getBookingById('a', 'intrus')).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
});
|
||||
@ -5,7 +5,6 @@ import {
|
||||
BadRequestException,
|
||||
Inject,
|
||||
UnauthorizedException,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import * as argon2 from 'argon2';
|
||||
@ -19,7 +18,6 @@ import {
|
||||
} from '@domain/ports/out/notification.repository';
|
||||
import { EmailPort, EMAIL_PORT } from '@domain/ports/out/email.port';
|
||||
import { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
|
||||
import { isAnonymisedEmail } from '@domain/services/data-retention';
|
||||
import { StoragePort, STORAGE_PORT } from '@domain/ports/out/storage.port';
|
||||
import { StripePort, STRIPE_PORT } from '@domain/ports/out/stripe.port';
|
||||
import {
|
||||
@ -152,9 +150,6 @@ export class CsvBookingService {
|
||||
throw new BadRequestException('At least one document is required');
|
||||
}
|
||||
|
||||
// Resolve pricing before uploads or any persistent side effect.
|
||||
const bookingFeeEur = await this.resolveBookingFeeEur(organizationId);
|
||||
|
||||
// Generate unique confirmation token and booking number
|
||||
const confirmationToken = uuidv4();
|
||||
const bookingId = uuidv4();
|
||||
@ -170,8 +165,11 @@ export class CsvBookingService {
|
||||
// Flat per-booking service fee (forfait par booking) based on the org's plan.
|
||||
// A fee <= 0 (e.g. Platinium "sur mesure") means no automatic charge: the
|
||||
// booking skips the payment gate and the carrier is notified immediately.
|
||||
const bookingFeeEur = await this.resolveBookingFeeEur(organizationId);
|
||||
const requiresPayment = bookingFeeEur > 0;
|
||||
const initialStatus = requiresPayment ? CsvBookingStatus.QUOTE : CsvBookingStatus.PENDING;
|
||||
const initialStatus = requiresPayment
|
||||
? CsvBookingStatus.PENDING_PAYMENT
|
||||
: CsvBookingStatus.PENDING;
|
||||
|
||||
// Create domain entity (no email sent yet when a payment is required)
|
||||
let parsedOptions: Record<string, boolean> = {};
|
||||
@ -249,20 +247,17 @@ export class CsvBookingService {
|
||||
/**
|
||||
* Resolve the flat per-booking fee (forfait par booking) for an organization
|
||||
* from its subscription plan. Returns the plan's bookingFeeEur, or 0 when the
|
||||
* plan has a custom fee (-1, e.g. Platinium "sur mesure").
|
||||
* An unknown fee must never be interpreted as a free booking.
|
||||
* plan has a custom fee (-1, e.g. Platinium "sur mesure") or on error — such
|
||||
* bookings are not auto-charged.
|
||||
*/
|
||||
private async resolveBookingFeeEur(organizationId: string): Promise<number> {
|
||||
try {
|
||||
const subscription = await this.subscriptionService.getOrCreateSubscription(organizationId);
|
||||
const fee = subscription.bookingFeeEur;
|
||||
if (!Number.isFinite(fee) || (fee < 0 && fee !== -1)) {
|
||||
throw new Error('Invalid booking fee');
|
||||
}
|
||||
const fee = subscription.plan.bookingFeeEur;
|
||||
return fee > 0 ? fee : 0;
|
||||
} catch {
|
||||
this.logger.error('Failed to resolve booking fee');
|
||||
throw new ServiceUnavailableException('Booking fee unavailable. Please retry later.');
|
||||
} catch (error: any) {
|
||||
this.logger.error(`Failed to resolve booking fee: ${error?.message}`);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@ -285,9 +280,9 @@ export class CsvBookingService {
|
||||
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
||||
}
|
||||
|
||||
if (booking.status !== CsvBookingStatus.QUOTE) {
|
||||
if (booking.status !== CsvBookingStatus.PENDING_PAYMENT) {
|
||||
throw new BadRequestException(
|
||||
`Booking is not a quote awaiting payment. Current status: ${booking.status}`
|
||||
`Booking is not awaiting payment. Current status: ${booking.status}`
|
||||
);
|
||||
}
|
||||
|
||||
@ -339,13 +334,13 @@ export class CsvBookingService {
|
||||
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
||||
}
|
||||
|
||||
if (booking.status !== CsvBookingStatus.QUOTE) {
|
||||
if (booking.status !== CsvBookingStatus.PENDING_PAYMENT) {
|
||||
// Already confirmed - return current state
|
||||
if (booking.status === CsvBookingStatus.PENDING) {
|
||||
return this.toResponseDto(booking);
|
||||
}
|
||||
throw new BadRequestException(
|
||||
`Booking is not a quote awaiting payment. Current status: ${booking.status}`
|
||||
`Booking is not awaiting payment. Current status: ${booking.status}`
|
||||
);
|
||||
}
|
||||
|
||||
@ -415,7 +410,7 @@ export class CsvBookingService {
|
||||
});
|
||||
this.logger.log(`Email sent to carrier: ${booking.carrierEmail}`);
|
||||
} catch (error: any) {
|
||||
this.logger.error('Failed to send email to carrier');
|
||||
this.logger.error(`Failed to send email to carrier: ${error?.message}`, error?.stack);
|
||||
}
|
||||
}
|
||||
|
||||
@ -442,7 +437,7 @@ export class CsvBookingService {
|
||||
|
||||
/**
|
||||
* Declare bank transfer — user confirms they have sent the wire transfer
|
||||
* Transitions booking from QUOTE → PENDING_BANK_TRANSFER
|
||||
* Transitions booking from PENDING_PAYMENT → PENDING_BANK_TRANSFER
|
||||
* Sends an email notification to all ADMIN users
|
||||
*/
|
||||
async declareBankTransfer(bookingId: string, userId: string): Promise<CsvBookingResponseDto> {
|
||||
@ -456,9 +451,9 @@ export class CsvBookingService {
|
||||
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
||||
}
|
||||
|
||||
if (booking.status !== CsvBookingStatus.QUOTE) {
|
||||
if (booking.status !== CsvBookingStatus.PENDING_PAYMENT) {
|
||||
throw new BadRequestException(
|
||||
`Booking is not a quote awaiting payment. Current status: ${booking.status}`
|
||||
`Booking is not awaiting payment. Current status: ${booking.status}`
|
||||
);
|
||||
}
|
||||
|
||||
@ -486,18 +481,43 @@ export class CsvBookingService {
|
||||
)
|
||||
: 'N/A';
|
||||
|
||||
// Gabarit commun ; le lien pointe vers /admin/bookings (l'ancien
|
||||
// /dashboard/admin/bookings n'existe pas).
|
||||
await this.emailAdapter.sendBankTransferToValidate(adminEmails, {
|
||||
bookingNumber,
|
||||
carrierName: booking.carrierName,
|
||||
routeDescription: booking.getRouteDescription(),
|
||||
commissionAmount,
|
||||
await this.emailAdapter.send({
|
||||
to: adminEmails,
|
||||
subject: `[XPEDITIS] Virement à valider — ${bookingNumber}`,
|
||||
html: `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h2 style="color: #10183A;">Nouveau virement à valider</h2>
|
||||
<p>Un client a déclaré avoir effectué un virement bancaire pour le booking suivant :</p>
|
||||
<table style="width: 100%; border-collapse: collapse; margin: 16px 0;">
|
||||
<tr style="background: #f5f5f5;">
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Numéro de booking</td>
|
||||
<td style="padding: 8px 12px;">${bookingNumber}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Transporteur</td>
|
||||
<td style="padding: 8px 12px;">${booking.carrierName}</td>
|
||||
</tr>
|
||||
<tr style="background: #f5f5f5;">
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Trajet</td>
|
||||
<td style="padding: 8px 12px;">${booking.getRouteDescription()}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Montant commission</td>
|
||||
<td style="padding: 8px 12px; color: #10183A; font-weight: bold;">${commissionAmount}</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p>Rendez-vous dans la <strong>console d'administration</strong> pour valider ce virement et activer le booking.</p>
|
||||
<a href="${process.env.APP_URL || 'http://localhost:3000'}/dashboard/admin/bookings"
|
||||
style="display: inline-block; background: #10183A; color: white; padding: 12px 24px; border-radius: 6px; text-decoration: none; margin-top: 8px;">
|
||||
Voir les bookings en attente
|
||||
</a>
|
||||
</div>
|
||||
`,
|
||||
});
|
||||
this.logger.log(`Admin notification email sent to: ${adminEmails.join(', ')}`);
|
||||
}
|
||||
} catch (error: any) {
|
||||
this.logger.error('Failed to send admin notification email');
|
||||
this.logger.error(`Failed to send admin notification email: ${error?.message}`, error?.stack);
|
||||
}
|
||||
|
||||
// In-app notification for the user
|
||||
@ -590,13 +610,10 @@ export class CsvBookingService {
|
||||
where: { id: bookingId },
|
||||
});
|
||||
const bookingNumber = ormBooking?.bookingNumber;
|
||||
const documentPassword = await this.syncDocumentPassword(booking.id);
|
||||
|
||||
// Send email to carrier. The transfer stays validated even if the email
|
||||
// fails, but the admin is told (carrierEmailSent) so they can resend it —
|
||||
// the failure used to be silent.
|
||||
let carrierEmailSent = false;
|
||||
// Send email to carrier
|
||||
try {
|
||||
const documentPassword = await this.syncDocumentPassword(booking.id);
|
||||
await this.emailAdapter.sendCsvBookingRequest(booking.carrierEmail, {
|
||||
bookingId: booking.id,
|
||||
bookingNumber: bookingNumber || '',
|
||||
@ -618,12 +635,11 @@ export class CsvBookingService {
|
||||
confirmationToken: booking.confirmationToken,
|
||||
notes: booking.notes,
|
||||
});
|
||||
carrierEmailSent = true;
|
||||
this.logger.log(
|
||||
`Email sent to carrier after bank transfer validation: ${booking.carrierEmail}`
|
||||
);
|
||||
} catch (error: any) {
|
||||
this.logger.error('Failed to send email to carrier');
|
||||
this.logger.error(`Failed to send email to carrier: ${error?.message}`, error?.stack);
|
||||
}
|
||||
|
||||
// In-app notification for the user
|
||||
@ -643,19 +659,17 @@ export class CsvBookingService {
|
||||
this.logger.error(`Failed to create user notification: ${error?.message}`, error?.stack);
|
||||
}
|
||||
|
||||
return { ...this.toResponseDto(updatedBooking), carrierEmailSent };
|
||||
return this.toResponseDto(updatedBooking);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get booking by ID
|
||||
* Readable by: booking owner, any member of the booking's organization, or
|
||||
* the assigned carrier. Changes (pay, edit, cancel, documents) stay owner-only.
|
||||
* Accessible by: booking owner OR assigned carrier
|
||||
*/
|
||||
async getBookingById(
|
||||
id: string,
|
||||
userId: string,
|
||||
carrierId?: string,
|
||||
organizationId?: string
|
||||
carrierId?: string
|
||||
): Promise<CsvBookingResponseDto> {
|
||||
const booking = await this.csvBookingRepository.findById(id);
|
||||
|
||||
@ -668,33 +682,15 @@ export class CsvBookingService {
|
||||
where: { id },
|
||||
});
|
||||
|
||||
// Verify user owns this booking, belongs to its organization, OR is the assigned carrier
|
||||
// Verify user owns this booking OR is the assigned carrier
|
||||
const isOwner = booking.userId === userId;
|
||||
const isSameOrganization = !!organizationId && booking.organizationId === organizationId;
|
||||
const isAssignedCarrier = carrierId && ormBooking?.carrierId === carrierId;
|
||||
|
||||
if (!isOwner && !isSameOrganization && !isAssignedCarrier) {
|
||||
if (!isOwner && !isAssignedCarrier) {
|
||||
throw new NotFoundException(`Booking with ID ${id} not found`);
|
||||
}
|
||||
|
||||
return {
|
||||
...this.toResponseDto(booking),
|
||||
createdByName: this.creatorName(await this.userRepository.findById(booking.userId)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Display name of a booking's creator, or null when the account no longer
|
||||
* exists or has been erased (its identity is anonymised).
|
||||
*/
|
||||
private creatorName(
|
||||
user: { email: string; firstName?: string; lastName?: string } | null | undefined
|
||||
): string | null {
|
||||
if (!user || isAnonymisedEmail(user.email)) {
|
||||
return null;
|
||||
}
|
||||
const fullName = `${user.firstName ?? ''} ${user.lastName ?? ''}`.trim();
|
||||
return fullName || user.email;
|
||||
return this.toResponseDto(booking);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -704,7 +700,7 @@ export class CsvBookingService {
|
||||
const booking = await this.csvBookingRepository.findByToken(token);
|
||||
|
||||
if (!booking) {
|
||||
throw new NotFoundException('Booking not found');
|
||||
throw new NotFoundException(`Booking with token ${token} not found`);
|
||||
}
|
||||
|
||||
return this.toResponseDto(booking);
|
||||
@ -718,7 +714,7 @@ export class CsvBookingService {
|
||||
token: string,
|
||||
password?: string
|
||||
): Promise<CarrierDocumentsResponseDto> {
|
||||
this.logger.log('Getting documents for carrier');
|
||||
this.logger.log(`Getting documents for carrier with token: ${token}`);
|
||||
|
||||
// Get ORM entity to access passwordHash
|
||||
const ormBooking = await this.csvBookingRepository['repository'].findOne({
|
||||
@ -888,7 +884,7 @@ export class CsvBookingService {
|
||||
* Accept a booking request
|
||||
*/
|
||||
async acceptBooking(token: string): Promise<CsvBookingResponseDto> {
|
||||
this.logger.log('Accepting booking');
|
||||
this.logger.log(`Accepting booking with token: ${token}`);
|
||||
|
||||
const booking = await this.csvBookingRepository.findByToken(token);
|
||||
|
||||
@ -901,9 +897,11 @@ export class CsvBookingService {
|
||||
where: { confirmationToken: token },
|
||||
});
|
||||
|
||||
// Resolve pricing before mutating the booking.
|
||||
const bookingFeeEur = await this.resolveBookingFeeEur(booking.organizationId);
|
||||
// Accept the booking (domain logic validates status)
|
||||
booking.accept();
|
||||
|
||||
// Apply the flat per-booking service fee (forfait par booking) from the org's plan
|
||||
const bookingFeeEur = await this.resolveBookingFeeEur(booking.organizationId);
|
||||
booking.applyBookingFee(bookingFeeEur);
|
||||
this.logger.log(
|
||||
`Booking fee applied: ${bookingFeeEur > 0 ? `${bookingFeeEur}€ (flat)` : 'none (custom)'} on booking ${booking.id}`
|
||||
@ -933,7 +931,7 @@ export class CsvBookingService {
|
||||
});
|
||||
this.logger.log(`Document access email sent to carrier: ${booking.carrierEmail}`);
|
||||
} catch (error: any) {
|
||||
this.logger.error('Failed to send document access email');
|
||||
this.logger.error(`Failed to send document access email: ${error?.message}`, error?.stack);
|
||||
}
|
||||
|
||||
// Create notification for user
|
||||
@ -960,7 +958,7 @@ export class CsvBookingService {
|
||||
* Reject a booking request
|
||||
*/
|
||||
async rejectBooking(token: string, reason?: string): Promise<CsvBookingResponseDto> {
|
||||
this.logger.log('Rejecting booking');
|
||||
this.logger.log(`Rejecting booking with token: ${token}`);
|
||||
|
||||
const booking = await this.csvBookingRepository.findByToken(token);
|
||||
|
||||
@ -1026,48 +1024,10 @@ export class CsvBookingService {
|
||||
return this.toResponseDto(updatedBooking);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an unpaid booking (user action).
|
||||
*
|
||||
* Seul le proprietaire peut supprimer, et seulement tant qu'aucun paiement
|
||||
* n'a ete encaisse — voir `CsvBooking.isDeletable()`. Une reservation payee
|
||||
* est partie chez le transporteur : elle s'annule, elle ne s'efface pas.
|
||||
*
|
||||
* Les documents deja televerses restent dans le stockage objet, comme lors de
|
||||
* la suppression d'un document isole : la politique du projet est de les
|
||||
* conserver pour l'audit.
|
||||
*/
|
||||
async deleteBooking(id: string, userId: string): Promise<{ success: boolean; message: string }> {
|
||||
this.logger.log(`Deleting booking ${id} by user ${userId}`);
|
||||
|
||||
const booking = await this.csvBookingRepository.findById(id);
|
||||
|
||||
if (!booking) {
|
||||
throw new NotFoundException('Booking not found');
|
||||
}
|
||||
|
||||
// Meme reponse qu'une reservation inexistante : appartenir a quelqu'un
|
||||
// d'autre ne doit pas etre distinguable de ne pas exister.
|
||||
if (booking.userId !== userId) {
|
||||
throw new NotFoundException('Booking not found');
|
||||
}
|
||||
|
||||
if (!booking.isDeletable()) {
|
||||
throw new BadRequestException(
|
||||
`Cannot delete a booking with status ${booking.status}. Only unpaid bookings can be deleted.`
|
||||
);
|
||||
}
|
||||
|
||||
await this.csvBookingRepository.delete(id);
|
||||
this.logger.log(`Booking ${id} deleted`);
|
||||
|
||||
return { success: true, message: 'Booking deleted successfully' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the cargo details of a booking before payment (user action).
|
||||
*
|
||||
* Only the owner can edit, and only while the booking is QUOTE.
|
||||
* Only the owner can edit, and only while the booking is PENDING_PAYMENT.
|
||||
*/
|
||||
async updateBookingDetails(
|
||||
id: string,
|
||||
@ -1131,7 +1091,7 @@ export class CsvBookingService {
|
||||
*
|
||||
* Used when the user re-runs the search and picks a (possibly different) rate:
|
||||
* carrier, route, container, transit, cargo and price are all replaced. Only
|
||||
* the owner can edit, and only while the booking is QUOTE.
|
||||
* the owner can edit, and only while the booking is PENDING_PAYMENT.
|
||||
*/
|
||||
async updateBookingRate(
|
||||
id: string,
|
||||
@ -1206,20 +1166,14 @@ export class CsvBookingService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get bookings for an organization (paginated), whoever created them, each
|
||||
* with the name of its creator so the list can show and filter by author.
|
||||
* Get bookings for an organization (paginated)
|
||||
*/
|
||||
async getOrganizationBookings(
|
||||
organizationId: string,
|
||||
page: number = 1,
|
||||
limit: number = 10
|
||||
): Promise<CsvBookingListResponseDto> {
|
||||
// One query for the members instead of one lookup per booking.
|
||||
const [bookings, members] = await Promise.all([
|
||||
this.csvBookingRepository.findByOrganizationId(organizationId),
|
||||
this.userRepository.findByOrganization(organizationId),
|
||||
]);
|
||||
const creatorNames = new Map(members.map(member => [member.id, this.creatorName(member)]));
|
||||
const bookings = await this.csvBookingRepository.findByOrganizationId(organizationId);
|
||||
|
||||
// Simple pagination (in-memory)
|
||||
const start = (page - 1) * limit;
|
||||
@ -1227,10 +1181,7 @@ export class CsvBookingService {
|
||||
const paginatedBookings = bookings.slice(start, end);
|
||||
|
||||
return {
|
||||
bookings: paginatedBookings.map(b => ({
|
||||
...this.toResponseDto(b),
|
||||
createdByName: creatorNames.get(b.userId) ?? null,
|
||||
})),
|
||||
bookings: paginatedBookings.map(b => this.toResponseDto(b)),
|
||||
total: bookings.length,
|
||||
page,
|
||||
limit,
|
||||
@ -1245,7 +1196,7 @@ export class CsvBookingService {
|
||||
const stats = await this.csvBookingRepository.countByStatusForUser(userId);
|
||||
|
||||
return {
|
||||
quote: stats[CsvBookingStatus.QUOTE] || 0,
|
||||
pendingPayment: stats[CsvBookingStatus.PENDING_PAYMENT] || 0,
|
||||
pending: stats[CsvBookingStatus.PENDING] || 0,
|
||||
accepted: stats[CsvBookingStatus.ACCEPTED] || 0,
|
||||
rejected: stats[CsvBookingStatus.REJECTED] || 0,
|
||||
@ -1261,7 +1212,7 @@ export class CsvBookingService {
|
||||
const stats = await this.csvBookingRepository.countByStatusForOrganization(organizationId);
|
||||
|
||||
return {
|
||||
quote: stats[CsvBookingStatus.QUOTE] || 0,
|
||||
pendingPayment: stats[CsvBookingStatus.PENDING_PAYMENT] || 0,
|
||||
pending: stats[CsvBookingStatus.PENDING] || 0,
|
||||
accepted: stats[CsvBookingStatus.ACCEPTED] || 0,
|
||||
rejected: stats[CsvBookingStatus.REJECTED] || 0,
|
||||
@ -1359,9 +1310,9 @@ export class CsvBookingService {
|
||||
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
||||
}
|
||||
|
||||
// Allow adding documents to QUOTE, PENDING_BANK_TRANSFER, PENDING, or ACCEPTED bookings
|
||||
// Allow adding documents to PENDING_PAYMENT, PENDING_BANK_TRANSFER, PENDING, or ACCEPTED bookings
|
||||
if (
|
||||
booking.status !== CsvBookingStatus.QUOTE &&
|
||||
booking.status !== CsvBookingStatus.PENDING_PAYMENT &&
|
||||
booking.status !== CsvBookingStatus.PENDING_BANK_TRANSFER &&
|
||||
booking.status !== CsvBookingStatus.PENDING &&
|
||||
booking.status !== CsvBookingStatus.ACCEPTED
|
||||
@ -1411,7 +1362,10 @@ export class CsvBookingService {
|
||||
});
|
||||
this.logger.log(`New documents notification sent to carrier: ${booking.carrierEmail}`);
|
||||
} catch (error: any) {
|
||||
this.logger.error('Failed to send new documents notification');
|
||||
this.logger.error(
|
||||
`Failed to send new documents notification: ${error?.message}`,
|
||||
error?.stack
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1615,6 +1569,7 @@ export class CsvBookingService {
|
||||
containerType: booking.containerType,
|
||||
status: booking.status,
|
||||
documents: booking.documents.map(this.toDocumentDto),
|
||||
confirmationToken: booking.confirmationToken,
|
||||
requestedAt: booking.requestedAt,
|
||||
respondedAt: booking.respondedAt || null,
|
||||
notes: booking.notes,
|
||||
|
||||
@ -1,251 +0,0 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { DataSource, EntityManager, Repository } from 'typeorm';
|
||||
import { GDPRService } from './gdpr.service';
|
||||
import { UserOrmEntity } from '../../infrastructure/persistence/typeorm/entities/user.orm-entity';
|
||||
import { CookieConsentOrmEntity } from '../../infrastructure/persistence/typeorm/entities/cookie-consent.orm-entity';
|
||||
import { AuditService } from './audit.service';
|
||||
import { RETENTION_RULES, ANONYMISED } from '@domain/services/data-retention';
|
||||
import { AuditAction } from '@domain/entities/audit-log.entity';
|
||||
|
||||
/**
|
||||
* Ces tests portent sur une promesse faite à une personne : « vos données sont
|
||||
* effacées ». La version précédente la faisait sans rien effacer. Ils vérifient
|
||||
* donc d'abord ce qui est réellement exécuté en base, table par table.
|
||||
*/
|
||||
|
||||
interface ExecutedQuery {
|
||||
sql: string;
|
||||
parameters: unknown[];
|
||||
}
|
||||
|
||||
const USER_ID = '11111111-2222-3333-4444-555555555555';
|
||||
|
||||
const buildUser = (): UserOrmEntity =>
|
||||
({
|
||||
id: USER_ID,
|
||||
organizationId: 'org-1',
|
||||
email: 'jean@example.com',
|
||||
firstName: 'Jean',
|
||||
lastName: 'Durand',
|
||||
phoneNumber: '+33600000000',
|
||||
passwordHash: 'argon2-hash',
|
||||
totpSecret: 'TOTPSECRET',
|
||||
role: 'USER',
|
||||
preferredLanguage: 'fr',
|
||||
isEmailVerified: true,
|
||||
isActive: true,
|
||||
lastLoginAt: new Date('2026-09-01T10:00:00Z'),
|
||||
createdAt: new Date('2026-01-01T10:00:00Z'),
|
||||
updatedAt: new Date('2026-09-01T10:00:00Z'),
|
||||
}) as unknown as UserOrmEntity;
|
||||
|
||||
/** Nombre de lignes renvoyé par le pilote PostgreSQL pour chaque écriture. */
|
||||
const ROWS_TOUCHED = 3;
|
||||
|
||||
function buildService(options: { user?: UserOrmEntity | null } = {}) {
|
||||
const executed: ExecutedQuery[] = [];
|
||||
|
||||
const manager = {
|
||||
// Forme réelle du pilote pour UPDATE et DELETE : [lignes, nombre].
|
||||
query: jest.fn(async (sql: string, parameters: unknown[]) => {
|
||||
executed.push({ sql, parameters });
|
||||
return [[], ROWS_TOUCHED];
|
||||
}),
|
||||
} as unknown as EntityManager;
|
||||
|
||||
const dataSource = {
|
||||
transaction: jest.fn(async (callback: (m: EntityManager) => Promise<void>) =>
|
||||
callback(manager)
|
||||
),
|
||||
query: jest.fn(async (sql: string, parameters: unknown[]) => {
|
||||
executed.push({ sql, parameters });
|
||||
return [];
|
||||
}),
|
||||
} as unknown as DataSource;
|
||||
|
||||
const user = options.user === undefined ? buildUser() : options.user;
|
||||
|
||||
const userRepository = {
|
||||
findOne: jest.fn(async () => user),
|
||||
} as unknown as Repository<UserOrmEntity>;
|
||||
|
||||
const consentRepository = {
|
||||
findOne: jest.fn(async () => null),
|
||||
create: jest.fn((value: Partial<CookieConsentOrmEntity>) => ({ ...value })),
|
||||
save: jest.fn(async (value: CookieConsentOrmEntity) => value),
|
||||
} as unknown as Repository<CookieConsentOrmEntity>;
|
||||
|
||||
const audit = { log: jest.fn(async () => undefined) } as unknown as AuditService;
|
||||
|
||||
const service = new GDPRService(userRepository, consentRepository, dataSource, audit);
|
||||
|
||||
return { service, executed, manager, dataSource, consentRepository, audit };
|
||||
}
|
||||
|
||||
/** Toutes les instructions écrites contre une table donnée. */
|
||||
const statementsFor = (executed: ExecutedQuery[], table: string, verb: 'DELETE' | 'UPDATE') =>
|
||||
executed.filter(query => query.sql.includes(verb) && query.sql.includes(table));
|
||||
|
||||
describe('GDPRService — effacement (art. 17)', () => {
|
||||
it('applique à chaque table le traitement décrit par la politique de conservation', async () => {
|
||||
const { service, executed } = buildService();
|
||||
|
||||
await service.deleteUserData(USER_ID, 'Fin de collaboration');
|
||||
|
||||
// La politique et le code ne peuvent pas diverger sans faire échouer ce
|
||||
// test : c'est la politique qui pilote l'assertion, pas une liste recopiée.
|
||||
for (const rule of RETENTION_RULES) {
|
||||
if (rule.onErasure === 'delete') {
|
||||
expect(statementsFor(executed, rule.table, 'DELETE').length).toBeGreaterThan(0);
|
||||
}
|
||||
if (rule.onErasure === 'anonymise') {
|
||||
expect(statementsFor(executed, rule.table, 'UPDATE').length).toBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('ne supprime jamais la ligne du compte : les réservations la référencent en cascade', async () => {
|
||||
const { service, executed } = buildService();
|
||||
|
||||
await service.deleteUserData(USER_ID);
|
||||
|
||||
expect(statementsFor(executed, 'FROM users', 'DELETE')).toHaveLength(0);
|
||||
expect(statementsFor(executed, 'csv_bookings', 'DELETE')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("remplace l'identité et rend le compte inutilisable", async () => {
|
||||
const { service, executed } = buildService();
|
||||
|
||||
await service.deleteUserData(USER_ID);
|
||||
|
||||
const [update] = statementsFor(executed, 'UPDATE users', 'UPDATE');
|
||||
expect(update.sql).toContain('is_active = false');
|
||||
expect(update.sql).toContain('totp_secret = NULL');
|
||||
expect(update.parameters[1]).toBe(`${ANONYMISED}+${USER_ID}@invalid.local`);
|
||||
// Mot de passe remplacé par une valeur aléatoire : la colonne est NOT NULL,
|
||||
// et une constante partagée signerait tous les comptes effacés.
|
||||
expect(update.parameters[3]).toMatch(/^erased-/);
|
||||
});
|
||||
|
||||
it('compte les lignes réellement touchées, pas la forme du résultat', async () => {
|
||||
const { service } = buildService();
|
||||
|
||||
const report = await service.deleteUserData(USER_ID);
|
||||
|
||||
// Le pilote renvoie `[lignes, nombre]` : mesurer la longueur du tableau
|
||||
// renverrait 2 partout, quel que soit le contenu de la base.
|
||||
expect(report.deleted.notifications).toBe(ROWS_TOUCHED);
|
||||
expect(report.anonymised.user).toBe(ROWS_TOUCHED);
|
||||
expect(Object.values(report.deleted)).not.toContain(2);
|
||||
});
|
||||
|
||||
it("journalise l'effacement sans y réinscrire l'identité effacée", async () => {
|
||||
const { service, audit } = buildService();
|
||||
|
||||
await service.deleteUserData(USER_ID, 'Fin de collaboration');
|
||||
|
||||
const [entry] = (audit.log as jest.Mock).mock.calls[0];
|
||||
expect(entry.action).toBe(AuditAction.GDPR_ERASURE_EXECUTED);
|
||||
// Journaliser avant l'effacement effacerait la trace ; y écrire l'adresse
|
||||
// réelle réintroduirait l'identité qu'on vient de supprimer.
|
||||
expect(entry.userEmail).toBe(`${ANONYMISED}+${USER_ID}@invalid.local`);
|
||||
expect(entry.userEmail).not.toContain('jean@example.com');
|
||||
});
|
||||
|
||||
it('opère dans une transaction', async () => {
|
||||
const { service, dataSource } = buildService();
|
||||
|
||||
await service.deleteUserData(USER_ID);
|
||||
|
||||
expect(dataSource.transaction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("n'écrit rien si le compte n'existe pas", async () => {
|
||||
const { service, executed } = buildService({ user: null });
|
||||
|
||||
await expect(service.deleteUserData(USER_ID)).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(executed).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GDPRService — portabilité (art. 20)', () => {
|
||||
it("couvre l'ensemble des données rattachées au compte", async () => {
|
||||
const { service, executed } = buildService();
|
||||
|
||||
const data = await service.exportUserData(USER_ID);
|
||||
|
||||
const read = executed.map(query => query.sql).join(' ');
|
||||
for (const table of [
|
||||
'organizations',
|
||||
'csv_bookings',
|
||||
'notifications',
|
||||
'trade_conversations',
|
||||
'api_keys',
|
||||
'audit_logs',
|
||||
]) {
|
||||
expect(read).toContain(table);
|
||||
}
|
||||
expect(data.userId).toBe(USER_ID);
|
||||
});
|
||||
|
||||
it("n'expose aucun secret d'authentification", async () => {
|
||||
const { service, executed } = buildService();
|
||||
|
||||
const data = await service.exportUserData(USER_ID);
|
||||
|
||||
const serialised = JSON.stringify(data);
|
||||
expect(serialised).not.toContain('argon2-hash');
|
||||
expect(serialised).not.toContain('TOTPSECRET');
|
||||
// Le condensat d'une clé d'API reste un secret d'accès.
|
||||
expect(executed.map(query => query.sql).join(' ')).not.toContain('key_hash');
|
||||
});
|
||||
|
||||
it("refuse d'exporter pour un compte inconnu", async () => {
|
||||
const { service } = buildService({ user: null });
|
||||
|
||||
await expect(service.exportUserData(USER_ID)).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GDPRService — consentement (art. 7)', () => {
|
||||
it('force les cookies essentiels et horodate le recueil', async () => {
|
||||
const { service } = buildService();
|
||||
|
||||
const consent = await service.recordConsent(USER_ID, {
|
||||
essential: false,
|
||||
functional: true,
|
||||
analytics: false,
|
||||
marketing: false,
|
||||
});
|
||||
|
||||
expect(consent.essential).toBe(true);
|
||||
expect(consent.functional).toBe(true);
|
||||
expect(consent.consentDate).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('retire tout ce qui est facultatif quand aucune catégorie n’est précisée', async () => {
|
||||
const { service } = buildService();
|
||||
|
||||
const consent = await service.withdrawConsent(USER_ID);
|
||||
|
||||
expect(consent).toMatchObject({ functional: false, analytics: false, marketing: false });
|
||||
expect(consent.essential).toBe(true);
|
||||
});
|
||||
|
||||
it('ne retire que la catégorie visée', async () => {
|
||||
const { service, consentRepository } = buildService();
|
||||
(consentRepository.findOne as jest.Mock).mockResolvedValue({
|
||||
userId: USER_ID,
|
||||
essential: true,
|
||||
functional: true,
|
||||
analytics: true,
|
||||
marketing: true,
|
||||
});
|
||||
|
||||
const consent = await service.withdrawConsent(USER_ID, 'marketing');
|
||||
|
||||
expect(consent.marketing).toBe(false);
|
||||
expect(consent.analytics).toBe(true);
|
||||
expect(consent.functional).toBe(true);
|
||||
});
|
||||
});
|
||||
@ -1,53 +1,26 @@
|
||||
/**
|
||||
* Droits des personnes (RGPD).
|
||||
* GDPR Compliance Service
|
||||
*
|
||||
* Portabilité (art. 20), effacement (art. 17), preuve du consentement (art. 7).
|
||||
*
|
||||
* Les requêtes sont écrites en SQL plutôt qu'en repositories : la moitié des
|
||||
* tables concernées (`trade_conversations`, `trade_messages`,
|
||||
* `password_reset_tokens`) n'a pas d'entité ORM, et un effacement doit couvrir
|
||||
* la base réelle, pas la partie qui a été modélisée.
|
||||
* Handles data export, deletion, and consent management
|
||||
* with full database persistence
|
||||
*/
|
||||
|
||||
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { DataSource, EntityManager, Repository } from 'typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { UserOrmEntity } from '../../infrastructure/persistence/typeorm/entities/user.orm-entity';
|
||||
import { CookieConsentOrmEntity } from '../../infrastructure/persistence/typeorm/entities/cookie-consent.orm-entity';
|
||||
import { UpdateConsentDto, ConsentResponseDto } from '../dto/consent.dto';
|
||||
import { AuditService } from './audit.service';
|
||||
import { AuditAction, AuditStatus } from '@domain/entities/audit-log.entity';
|
||||
import { ANONYMISED, anonymisedEmail } from '@domain/services/data-retention';
|
||||
|
||||
export interface GDPRDataExport {
|
||||
exportDate: string;
|
||||
userId: string;
|
||||
userData: Record<string, unknown>;
|
||||
organisation: Record<string, unknown> | null;
|
||||
bookings: Record<string, unknown>[];
|
||||
notifications: Record<string, unknown>[];
|
||||
assistantConversations: Record<string, unknown>[];
|
||||
apiKeys: Record<string, unknown>[];
|
||||
activityLog: Record<string, unknown>[];
|
||||
cookieConsent: Record<string, unknown> | null;
|
||||
notice: string;
|
||||
userData: any;
|
||||
cookieConsent: any;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** Ce qui a été effacé ou anonymisé, rendu à la personne comme preuve. */
|
||||
export interface GDPRErasureReport {
|
||||
userId: string;
|
||||
erasedAt: string;
|
||||
deleted: Record<string, number>;
|
||||
anonymised: Record<string, number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Borne de l'export : seuls les journaux d'activité peuvent atteindre des
|
||||
* volumes qui transformeraient l'export en vidage de base.
|
||||
*/
|
||||
const MAX_LOG_ROWS = 5000;
|
||||
|
||||
@Injectable()
|
||||
export class GDPRService {
|
||||
private readonly logger = new Logger(GDPRService.name);
|
||||
@ -56,119 +29,41 @@ export class GDPRService {
|
||||
@InjectRepository(UserOrmEntity)
|
||||
private readonly userRepository: Repository<UserOrmEntity>,
|
||||
@InjectRepository(CookieConsentOrmEntity)
|
||||
private readonly consentRepository: Repository<CookieConsentOrmEntity>,
|
||||
private readonly dataSource: DataSource,
|
||||
private readonly audit: AuditService
|
||||
private readonly consentRepository: Repository<CookieConsentOrmEntity>
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Export de portabilité (art. 20).
|
||||
*
|
||||
* L'export précédent ne contenait que le profil et le consentement cookies,
|
||||
* en renvoyant la personne vers « les endpoints respectifs » pour le reste.
|
||||
* Ce n'était pas un export : l'art. 20 porte sur l'ensemble des données
|
||||
* fournies par la personne, pas sur l'échantillon le plus simple à produire.
|
||||
*
|
||||
* Restent volontairement dehors le hachage du mot de passe et le secret TOTP :
|
||||
* ce sont des secrets d'authentification, les livrer affaiblirait le compte
|
||||
* sans rien apporter à la portabilité.
|
||||
* Export all user data (GDPR Article 20 - Right to Data Portability)
|
||||
*/
|
||||
async exportUserData(userId: string): Promise<GDPRDataExport> {
|
||||
const user = await this.userRepository.findOne({ where: { id: userId } });
|
||||
if (!user) throw new NotFoundException('User not found');
|
||||
this.logger.log(`Exporting data for user ${userId}`);
|
||||
|
||||
// Fetch user data
|
||||
const user = await this.userRepository.findOne({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
// Fetch consent data
|
||||
const consent = await this.consentRepository.findOne({ where: { userId } });
|
||||
|
||||
const [organisation] = await this.dataSource.query(
|
||||
`SELECT id, name, type, siren, siret, eori, contact_email, contact_phone,
|
||||
address_street, address_city, address_postal_code, address_country
|
||||
FROM organizations WHERE id = $1`,
|
||||
[user.organizationId]
|
||||
);
|
||||
|
||||
const bookings = await this.dataSource.query(
|
||||
`SELECT id, booking_number, carrier_name, origin, destination, volume_cbm, weight_kg,
|
||||
pallet_count, container_type, status, price_eur, price_usd, primary_currency,
|
||||
freight_total, freight_currency, fob_total, fob_currency, commission_amount_eur,
|
||||
transit_days, notes, rejection_reason, requested_at, responded_at, created_at
|
||||
FROM csv_bookings WHERE user_id = $1 ORDER BY created_at DESC`,
|
||||
[userId]
|
||||
);
|
||||
|
||||
const notifications = await this.dataSource.query(
|
||||
`SELECT type, priority, title, message, read, read_at, action_url, created_at
|
||||
FROM notifications WHERE user_id = $1 ORDER BY created_at DESC`,
|
||||
[userId]
|
||||
);
|
||||
|
||||
const assistantConversations = await this.dataSource.query(
|
||||
`SELECT c.id, c.title, c.created_at,
|
||||
COALESCE((
|
||||
SELECT json_agg(json_build_object(
|
||||
'role', m.role, 'content', m.content, 'createdAt', m.created_at)
|
||||
ORDER BY m.created_at)
|
||||
FROM trade_messages m WHERE m.conversation_id = c.id
|
||||
), '[]'::json) AS messages
|
||||
FROM trade_conversations c WHERE c.user_id = $1 ORDER BY c.created_at DESC`,
|
||||
[userId]
|
||||
);
|
||||
|
||||
// Jamais `key_hash` : seule la trace de l'existence de la clé est utile,
|
||||
// et le condensat resterait un secret d'accès.
|
||||
const apiKeys = await this.dataSource.query(
|
||||
`SELECT name, key_prefix, is_active, last_used_at, expires_at, created_at
|
||||
FROM api_keys WHERE user_id = $1 ORDER BY created_at DESC`,
|
||||
[userId]
|
||||
);
|
||||
|
||||
const activityLog = await this.dataSource.query(
|
||||
`SELECT action, status, resource_type, resource_name, ip_address, timestamp
|
||||
FROM audit_logs WHERE user_id = $1 ORDER BY timestamp DESC LIMIT $2`,
|
||||
[userId, MAX_LOG_ROWS]
|
||||
);
|
||||
|
||||
this.logger.log(`GDPR export produced for user ${userId}`);
|
||||
|
||||
// Trace d'accountability (art. 5.2) : pouvoir démontrer que la demande a
|
||||
// été honorée, et quand.
|
||||
await this.audit.log({
|
||||
action: AuditAction.GDPR_DATA_EXPORTED,
|
||||
status: AuditStatus.SUCCESS,
|
||||
userId,
|
||||
userEmail: user.email,
|
||||
// Sanitize user data (remove password hash)
|
||||
const sanitizedUser = {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
role: user.role,
|
||||
organizationId: user.organizationId,
|
||||
resourceType: 'gdpr_request',
|
||||
metadata: {
|
||||
bookings: bookings.length,
|
||||
notifications: notifications.length,
|
||||
assistantConversations: assistantConversations.length,
|
||||
activityLogEntries: activityLog.length,
|
||||
},
|
||||
});
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
// Password hash explicitly excluded for security
|
||||
};
|
||||
|
||||
return {
|
||||
const exportData: GDPRDataExport = {
|
||||
exportDate: new Date().toISOString(),
|
||||
userId,
|
||||
userData: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
phoneNumber: user.phoneNumber,
|
||||
role: user.role,
|
||||
preferredLanguage: user.preferredLanguage,
|
||||
isEmailVerified: user.isEmailVerified,
|
||||
isActive: user.isActive,
|
||||
lastLoginAt: user.lastLoginAt,
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
},
|
||||
organisation: organisation ?? null,
|
||||
bookings,
|
||||
notifications,
|
||||
assistantConversations,
|
||||
apiKeys,
|
||||
activityLog,
|
||||
userData: sanitizedUser,
|
||||
cookieConsent: consent
|
||||
? {
|
||||
essential: consent.essential,
|
||||
@ -178,211 +73,175 @@ export class GDPRService {
|
||||
consentDate: consent.consentDate,
|
||||
}
|
||||
: null,
|
||||
notice:
|
||||
"Ensemble des données personnelles rattachées à ce compte. Les secrets d'authentification (mot de passe, second facteur, condensats de clés d'API) en sont exclus par sécurité. Le journal d'activité est limité aux " +
|
||||
`${MAX_LOG_ROWS} entrées les plus récentes.`,
|
||||
message:
|
||||
'User data exported successfully. Additional data (bookings, notifications) can be exported from respective endpoints.',
|
||||
};
|
||||
|
||||
this.logger.log(`Data export completed for user ${userId}`);
|
||||
|
||||
return exportData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete user data (GDPR Article 17 - Right to Erasure)
|
||||
* Note: This is a simplified version. In production, implement full anonymization logic.
|
||||
*/
|
||||
async deleteUserData(userId: string, reason?: string): Promise<void> {
|
||||
this.logger.warn(
|
||||
`Initiating data deletion for user ${userId}. Reason: ${reason || 'User request'}`
|
||||
);
|
||||
|
||||
// Verify user exists
|
||||
const user = await this.userRepository.findOne({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
try {
|
||||
// Delete consent data first (will cascade with user deletion)
|
||||
await this.consentRepository.delete({ userId });
|
||||
|
||||
// IMPORTANT: In production, implement full data anonymization
|
||||
// For now, we just mark the account for deletion
|
||||
// Real implementation should:
|
||||
// 1. Anonymize bookings (keep for legal retention)
|
||||
// 2. Delete notifications
|
||||
// 3. Anonymize audit logs
|
||||
// 4. Anonymize user record
|
||||
|
||||
this.logger.warn(`User ${userId} marked for deletion. Full implementation pending.`);
|
||||
this.logger.log(`Data deletion initiated for user ${userId}`);
|
||||
} catch (error: any) {
|
||||
this.logger.error(`Data deletion failed for user ${userId}: ${error.message}`, error.stack);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record or update consent (GDPR Article 7 - Conditions for consent)
|
||||
*/
|
||||
async recordConsent(userId: string, consentData: UpdateConsentDto): Promise<ConsentResponseDto> {
|
||||
this.logger.log(`Recording consent for user ${userId}`);
|
||||
|
||||
// Verify user exists
|
||||
const user = await this.userRepository.findOne({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
// Check if consent already exists
|
||||
let consent = await this.consentRepository.findOne({ where: { userId } });
|
||||
|
||||
if (consent) {
|
||||
// Update existing consent
|
||||
consent.essential = true; // Always true
|
||||
consent.functional = consentData.functional;
|
||||
consent.analytics = consentData.analytics;
|
||||
consent.marketing = consentData.marketing;
|
||||
consent.ipAddress = consentData.ipAddress || consent.ipAddress;
|
||||
consent.userAgent = consentData.userAgent || consent.userAgent;
|
||||
consent.consentDate = new Date();
|
||||
|
||||
await this.consentRepository.save(consent);
|
||||
this.logger.log(`Consent updated for user ${userId}`);
|
||||
} else {
|
||||
// Create new consent record
|
||||
consent = this.consentRepository.create({
|
||||
id: uuidv4(),
|
||||
userId,
|
||||
essential: true, // Always true
|
||||
functional: consentData.functional,
|
||||
analytics: consentData.analytics,
|
||||
marketing: consentData.marketing,
|
||||
ipAddress: consentData.ipAddress,
|
||||
userAgent: consentData.userAgent,
|
||||
consentDate: new Date(),
|
||||
});
|
||||
|
||||
await this.consentRepository.save(consent);
|
||||
this.logger.log(`New consent created for user ${userId}`);
|
||||
}
|
||||
|
||||
return {
|
||||
userId,
|
||||
essential: consent.essential,
|
||||
functional: consent.functional,
|
||||
analytics: consent.analytics,
|
||||
marketing: consent.marketing,
|
||||
consentDate: consent.consentDate,
|
||||
updatedAt: consent.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Effacement (art. 17).
|
||||
*
|
||||
* L'implémentation précédente supprimait la ligne de consentement cookies,
|
||||
* écrivait « Full implementation pending » dans les logs, et renvoyait un
|
||||
* succès : la personne était informée que ses données étaient effacées alors
|
||||
* que rien ne l'était.
|
||||
*
|
||||
* Deux traitements, décrits dans `domain/services/data-retention.ts` :
|
||||
* ce qui n'existe que pour le confort du service est supprimé ; ce qui répond
|
||||
* à une obligation de conservation (art. 17.3.b) est anonymisé, et sort donc
|
||||
* du champ des données personnelles.
|
||||
*
|
||||
* La ligne `users` est neutralisée plutôt que supprimée : `csv_bookings`,
|
||||
* `licenses` et `api_keys` la référencent en `ON DELETE CASCADE`, un vrai
|
||||
* DELETE emporterait dix ans de pièces comptables avec lui.
|
||||
*
|
||||
* Le tout en transaction : un effacement à moitié appliqué laisserait un
|
||||
* compte ni actif ni effacé, c'est-à-dire un état que rien ne rattrape.
|
||||
*/
|
||||
async deleteUserData(userId: string, reason?: string): Promise<GDPRErasureReport> {
|
||||
const user = await this.userRepository.findOne({ where: { id: userId } });
|
||||
if (!user) throw new NotFoundException('User not found');
|
||||
|
||||
this.logger.warn(
|
||||
`GDPR erasure starting for user ${userId} — reason: ${reason ?? 'unspecified'}`
|
||||
);
|
||||
|
||||
const deleted: Record<string, number> = {};
|
||||
const anonymised: Record<string, number> = {};
|
||||
const email = user.email;
|
||||
|
||||
await this.dataSource.transaction(async manager => {
|
||||
const rows = (sql: string, parameters: unknown[]) => this.affected(manager, sql, parameters);
|
||||
|
||||
// Supprimé : rien n'impose de le conserver.
|
||||
deleted.notifications = await rows('DELETE FROM notifications WHERE user_id = $1', [userId]);
|
||||
// Les messages suivent par cascade sur `conversation_id`.
|
||||
deleted.assistantConversations = await rows(
|
||||
'DELETE FROM trade_conversations WHERE user_id = $1',
|
||||
[userId]
|
||||
);
|
||||
deleted.assistantUsage = await rows('DELETE FROM trade_assistant_usage WHERE user_id = $1', [
|
||||
userId,
|
||||
]);
|
||||
deleted.apiKeys = await rows('DELETE FROM api_keys WHERE user_id = $1', [userId]);
|
||||
deleted.cookieConsent = await rows('DELETE FROM cookie_consents WHERE user_id = $1', [
|
||||
userId,
|
||||
]);
|
||||
deleted.passwordResetTokens = await rows(
|
||||
'DELETE FROM password_reset_tokens WHERE user_id = $1',
|
||||
[userId]
|
||||
);
|
||||
// Une invitation non consommée porte le nom et l'adresse de la personne
|
||||
// sans qu'aucun compte n'en dépende.
|
||||
deleted.pendingInvitations = await rows(
|
||||
'DELETE FROM invitation_tokens WHERE lower(email) = lower($1) AND is_used = false',
|
||||
[email]
|
||||
);
|
||||
|
||||
// Anonymisé : conservé, sans rattachement à la personne.
|
||||
// Les notes sont un champ libre : c'est le seul endroit d'une
|
||||
// réservation où une donnée personnelle peut avoir été saisie.
|
||||
anonymised.bookings = await rows('UPDATE csv_bookings SET notes = NULL WHERE user_id = $1', [
|
||||
userId,
|
||||
]);
|
||||
anonymised.auditLogs = await rows(
|
||||
`UPDATE audit_logs SET user_email = $2, ip_address = NULL, user_agent = NULL
|
||||
WHERE user_id = $1`,
|
||||
[userId, anonymisedEmail(userId)]
|
||||
);
|
||||
// Un profil transporteur mêle données d'entreprise (conservées) et
|
||||
// coordonnées d'une personne (effacées).
|
||||
anonymised.carrierProfile = await rows(
|
||||
`UPDATE carrier_profiles SET phone = NULL, notification_email = NULL, is_active = false
|
||||
WHERE user_id = $1`,
|
||||
[userId]
|
||||
);
|
||||
|
||||
// Le compte : identité remplacée, accès rendu impossible.
|
||||
// Le mot de passe reçoit une valeur aléatoire plutôt que NULL — la
|
||||
// colonne est NOT NULL, et une valeur constante partagée par tous les
|
||||
// comptes effacés serait un motif reconnaissable.
|
||||
anonymised.user = await rows(
|
||||
`UPDATE users SET
|
||||
email = $2, first_name = $3, last_name = $3, phone_number = NULL,
|
||||
password_hash = $4, totp_secret = NULL,
|
||||
is_active = false, is_email_verified = false, updated_at = now()
|
||||
WHERE id = $1`,
|
||||
[userId, anonymisedEmail(userId), ANONYMISED, `erased-${uuidv4()}`]
|
||||
);
|
||||
});
|
||||
|
||||
this.logger.warn(
|
||||
`GDPR erasure completed for user ${userId}: ${JSON.stringify({ deleted, anonymised })}`
|
||||
);
|
||||
|
||||
// Écrite après la transaction, et avec l'adresse anonymisée : journaliser
|
||||
// avant l'effacement ferait disparaître la trace par l'anonymisation des
|
||||
// journaux, et y inscrire l'adresse réelle réintroduirait l'identité qu'on
|
||||
// vient d'effacer. Ce qu'il faut pouvoir démontrer, c'est que la demande a
|
||||
// été traitée — pas de qui elle émanait.
|
||||
await this.audit.log({
|
||||
action: AuditAction.GDPR_ERASURE_EXECUTED,
|
||||
status: AuditStatus.SUCCESS,
|
||||
userId,
|
||||
userEmail: anonymisedEmail(userId),
|
||||
organizationId: user.organizationId,
|
||||
resourceType: 'gdpr_request',
|
||||
metadata: { reason: reason ?? null, deleted, anonymised },
|
||||
});
|
||||
|
||||
return { userId, erasedAt: new Date().toISOString(), deleted, anonymised };
|
||||
}
|
||||
|
||||
/**
|
||||
* Nombre de lignes réellement touchées.
|
||||
*
|
||||
* Le pilote PostgreSQL de TypeORM renvoie `[lignes, nombre]` pour un UPDATE
|
||||
* ou un DELETE, et la seule liste de lignes pour un SELECT. Compter la
|
||||
* longueur du résultat donnerait donc « 2 » à chaque effacement, quel que
|
||||
* soit le nombre réel — un rapport de conformité faux.
|
||||
*/
|
||||
private async affected(
|
||||
manager: EntityManager,
|
||||
sql: string,
|
||||
parameters: unknown[]
|
||||
): Promise<number> {
|
||||
const result = await manager.query(sql, parameters);
|
||||
return Array.isArray(result) && typeof result[1] === 'number' ? result[1] : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Journal des demandes de droits, pour la console de conformité.
|
||||
*
|
||||
* Lu en SQL depuis `audit_logs` plutôt que via le dépôt d'audit : le filtre
|
||||
* porte sur un préfixe d'action, que l'interface de dépôt n'expose pas.
|
||||
*/
|
||||
async listRightsRequests(limit = 100): Promise<Record<string, unknown>[]> {
|
||||
return this.dataSource.query(
|
||||
`SELECT action, status, user_id, user_email, organization_id, metadata, timestamp
|
||||
FROM audit_logs WHERE action LIKE 'gdpr\\_%' ORDER BY timestamp DESC LIMIT $1`,
|
||||
[limit]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enregistre le consentement et sa date (art. 7.1 — preuve du consentement).
|
||||
*
|
||||
* Sans entrée d'audit : la ligne de consentement porte déjà l'horodatage,
|
||||
* l'adresse IP et le navigateur, c'est-à-dire exactement la preuve attendue.
|
||||
* Un second enregistrement n'ajouterait rien qu'une écriture par visite.
|
||||
*/
|
||||
async recordConsent(userId: string, consentData: UpdateConsentDto): Promise<ConsentResponseDto> {
|
||||
const existing = await this.consentRepository.findOne({ where: { userId } });
|
||||
const consent = existing ?? this.consentRepository.create({ id: uuidv4(), userId });
|
||||
|
||||
consent.essential = true; // Sans elles le service ne fonctionne pas : pas de choix à recueillir.
|
||||
consent.functional = consentData.functional ?? false;
|
||||
consent.analytics = consentData.analytics ?? false;
|
||||
consent.marketing = consentData.marketing ?? false;
|
||||
consent.ipAddress = consentData.ipAddress ?? consent.ipAddress;
|
||||
consent.userAgent = consentData.userAgent ?? consent.userAgent;
|
||||
consent.consentDate = new Date();
|
||||
|
||||
await this.consentRepository.save(consent);
|
||||
return this.toConsentDto(consent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrait du consentement (art. 7.3) : aussi simple à retirer qu'à donner.
|
||||
* Sans catégorie précisée, tout ce qui est facultatif est retiré.
|
||||
* Withdraw specific consent (GDPR Article 7.3 - Withdrawal of consent)
|
||||
*/
|
||||
async withdrawConsent(
|
||||
userId: string,
|
||||
consentType?: 'functional' | 'analytics' | 'marketing'
|
||||
consentType: 'functional' | 'analytics' | 'marketing'
|
||||
): Promise<ConsentResponseDto> {
|
||||
const current = await this.consentRepository.findOne({ where: { userId } });
|
||||
this.logger.log(`Withdrawing ${consentType} consent for user ${userId}`);
|
||||
|
||||
const next: UpdateConsentDto = {
|
||||
essential: true,
|
||||
functional: consentType
|
||||
? consentType !== 'functional' && (current?.functional ?? false)
|
||||
: false,
|
||||
analytics: consentType ? consentType !== 'analytics' && (current?.analytics ?? false) : false,
|
||||
marketing: consentType ? consentType !== 'marketing' && (current?.marketing ?? false) : false,
|
||||
};
|
||||
// Verify user exists
|
||||
const user = await this.userRepository.findOne({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
return this.recordConsent(userId, next);
|
||||
}
|
||||
// Find consent record
|
||||
let consent = await this.consentRepository.findOne({ where: { userId } });
|
||||
|
||||
async getConsentStatus(userId: string): Promise<ConsentResponseDto | null> {
|
||||
const consent = await this.consentRepository.findOne({ where: { userId } });
|
||||
return consent ? this.toConsentDto(consent) : null;
|
||||
}
|
||||
if (!consent) {
|
||||
// Create default consent with withdrawn type
|
||||
consent = this.consentRepository.create({
|
||||
id: uuidv4(),
|
||||
userId,
|
||||
essential: true,
|
||||
functional: consentType === 'functional' ? false : false,
|
||||
analytics: consentType === 'analytics' ? false : false,
|
||||
marketing: consentType === 'marketing' ? false : false,
|
||||
consentDate: new Date(),
|
||||
});
|
||||
} else {
|
||||
// Update specific consent type
|
||||
consent[consentType] = false;
|
||||
consent.consentDate = new Date();
|
||||
}
|
||||
|
||||
await this.consentRepository.save(consent);
|
||||
this.logger.log(`${consentType} consent withdrawn for user ${userId}`);
|
||||
|
||||
private toConsentDto(consent: CookieConsentOrmEntity): ConsentResponseDto {
|
||||
return {
|
||||
userId: consent.userId,
|
||||
userId,
|
||||
essential: consent.essential,
|
||||
functional: consent.functional,
|
||||
analytics: consent.analytics,
|
||||
marketing: consent.marketing,
|
||||
consentDate: consent.consentDate,
|
||||
updatedAt: consent.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current consent status
|
||||
*/
|
||||
async getConsentStatus(userId: string): Promise<ConsentResponseDto | null> {
|
||||
// Verify user exists
|
||||
const user = await this.userRepository.findOne({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
// Find consent record
|
||||
const consent = await this.consentRepository.findOne({ where: { userId } });
|
||||
|
||||
if (!consent) {
|
||||
// No consent recorded yet - return null to indicate user should provide consent
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
userId,
|
||||
essential: consent.essential,
|
||||
functional: consent.functional,
|
||||
analytics: consent.analytics,
|
||||
|
||||
@ -1,57 +0,0 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { InvitationService } from './invitation.service';
|
||||
import { SubscriptionService } from './subscription.service';
|
||||
import { InvitationToken } from '@domain/entities/invitation-token.entity';
|
||||
import { UserRole } from '@domain/entities/user.entity';
|
||||
import { InvitationTokenRepository } from '@domain/ports/out/invitation-token.repository';
|
||||
import { UserRepository } from '@domain/ports/out/user.repository';
|
||||
import { OrganizationRepository } from '@domain/ports/out/organization.repository';
|
||||
import { EmailPort } from '@domain/ports/out/email.port';
|
||||
|
||||
describe('invitation secret handling', () => {
|
||||
it('keeps the token in the email but out of success and failure logs', async () => {
|
||||
const log = jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
|
||||
const error = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||
try {
|
||||
const invitation = InvitationToken.create({
|
||||
id: 'invite-id',
|
||||
token: 'test-only-invitation-secret',
|
||||
email: 'user@example.org',
|
||||
firstName: 'Test',
|
||||
lastName: 'User',
|
||||
role: UserRole.USER,
|
||||
organizationId: 'org',
|
||||
invitedById: 'admin',
|
||||
expiresAt: new Date(Date.now() + 60_000),
|
||||
});
|
||||
const send = jest.fn().mockResolvedValue(undefined);
|
||||
const service = new InvitationService(
|
||||
{
|
||||
findByToken: async () => invitation,
|
||||
update: async () => invitation,
|
||||
} as unknown as InvitationTokenRepository,
|
||||
{
|
||||
findById: async () => ({ firstName: 'Test', lastName: 'Admin' }),
|
||||
} as unknown as UserRepository,
|
||||
{ findById: async () => ({ name: 'Company' }) } as unknown as OrganizationRepository,
|
||||
{ sendInvitationWithToken: send } as unknown as EmailPort,
|
||||
new ConfigService({ FRONTEND_URL: 'https://example.org' }),
|
||||
{} as SubscriptionService
|
||||
);
|
||||
await service['sendInvitationEmail'](invitation);
|
||||
expect(send.mock.calls[0][5]).toBe(
|
||||
'https://example.org/register?token=test-only-invitation-secret'
|
||||
);
|
||||
send.mockRejectedValue(new Error('test-only-invitation-secret'));
|
||||
await expect(service['sendInvitationEmail'](invitation)).rejects.toThrow();
|
||||
await service.markInvitationAsUsed(invitation.token);
|
||||
expect(JSON.stringify([...log.mock.calls, ...error.mock.calls])).not.toContain(
|
||||
invitation.token
|
||||
);
|
||||
} finally {
|
||||
log.mockRestore();
|
||||
error.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -109,8 +109,10 @@ export class InvitationService {
|
||||
|
||||
// Send invitation email (async - don't block on email sending)
|
||||
this.logger.log(`[INVITATION] About to send email to ${email}...`);
|
||||
this.sendInvitationEmail(savedInvitation).catch(() => {
|
||||
this.logger.error(`Invitation email delivery failed: ${savedInvitation.id}`);
|
||||
this.sendInvitationEmail(savedInvitation).catch(err => {
|
||||
this.logger.error(`[INVITATION] ❌ Failed to send invitation email to ${email}`, err);
|
||||
this.logger.error(`[INVITATION] Error message: ${err?.message}`);
|
||||
this.logger.error(`[INVITATION] Error stack: ${err?.stack?.substring(0, 500)}`);
|
||||
});
|
||||
|
||||
this.logger.log(`Invitation created successfully for ${email}`);
|
||||
@ -149,7 +151,7 @@ export class InvitationService {
|
||||
|
||||
await this.invitationRepository.update(invitation);
|
||||
|
||||
this.logger.log(`Invitation ${invitation.id} marked as used`);
|
||||
this.logger.log(`Invitation ${token} marked as used`);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -176,6 +178,7 @@ export class InvitationService {
|
||||
const invitationLink = `${frontendUrl}/register?token=${invitation.token}`;
|
||||
|
||||
this.logger.log(`[INVITATION] Frontend URL: ${frontendUrl}`);
|
||||
this.logger.log(`[INVITATION] Invitation link: ${invitationLink}`);
|
||||
|
||||
// Get organization details
|
||||
this.logger.log(`[INVITATION] Fetching organization ${invitation.organizationId}...`);
|
||||
@ -211,7 +214,11 @@ export class InvitationService {
|
||||
|
||||
this.logger.log(`[INVITATION] ✅ Email sent successfully to ${invitation.email}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Invitation email delivery failed: ${invitation.id}`);
|
||||
this.logger.error(
|
||||
`[INVITATION] ❌ Failed to send invitation email to ${invitation.email}`,
|
||||
error
|
||||
);
|
||||
this.logger.error(`[INVITATION] Error details: ${JSON.stringify(error, null, 2)}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user