Skip to content

Update dependencies, improve upload handling, and add workflows#4

Merged
Mouette03 merged 13 commits into
mainfrom
cve
Mar 25, 2026
Merged

Update dependencies, improve upload handling, and add workflows#4
Mouette03 merged 13 commits into
mainfrom
cve

Conversation

@Mouette03

@Mouette03 Mouette03 commented Mar 25, 2026

Copy link
Copy Markdown
Owner

This pull request introduces several important improvements to file upload handling and dependency management in both the backend and frontend. The main focus is on adding server-side file size limits for avatar, logo, and upload request files, improving error handling for oversized uploads, and updating dependencies to their latest major versions for better compatibility and security.

Backend: File upload size limits and streaming improvements

  • Implemented server-side streaming with file size limits for avatar uploads (3 MB) in auth.ts to prevent excessive memory usage and large file uploads.
  • Added streaming upload with a 2 MB file size limit for logo uploads in settings.ts, ensuring large files are rejected early and efficiently.
  • Improved upload request file handling to enforce maxSizeBytes during streaming, aborting and cleaning up if the file is too large, and removed redundant post-upload size checks.

Frontend: User feedback for oversized uploads

  • Enhanced error handling in ProfilePage.tsx and SettingsPage.tsx to display specific toast messages when an uploaded image exceeds the allowed size, improving user experience. [1] [2]

Backend: Dependency and environment updates

  • Updated major dependencies in backend/package.json (including fastify, @fastify/*, and nodemailer) and added required Node.js and npm engine versions for better reliability and compatibility. [1] [2]

CI/CD: Docker build cache optimization

  • Scoped Docker build cache to workflow and database provider in .github/workflows/docker.yml to improve CI build efficiency and avoid cache collisions. [1] [2]

Summary by CodeRabbit

  • Corrections de bogues

    • Limites de taille appliquées côté serveur pour avatars (3 Mo), logos (2 Mo) et uploads par token — fichiers trop volumineux renvoient 413 et les fichiers partiels sont supprimés.
    • Messages d'erreur d'upload affinés : toasts dédiés quand le fichier dépasse la taille autorisée.
  • Améliorations

    • Uploads streamés vers le disque avec gestion du flux et du backpressure pour réduire l'utilisation mémoire et améliorer la fiabilité.
  • Chores

    • Mises à jour des dépendances backend et contrainte d'exécution Node/NPM; ajustement de la configuration du cache de build Docker.

update CVE

Signed-off-by: Damien <mouette03@yahoo.fr>
Signed-off-by: Damien <mouette03@yahoo.fr>
Signed-off-by: Damien <mouette03@yahoo.fr>
Updated Node.js and npm engine requirements and upgraded nodemailer types.

Signed-off-by: Damien <mouette03@yahoo.fr>
Signed-off-by: Damien <mouette03@yahoo.fr>
Signed-off-by: Damien <mouette03@yahoo.fr>
Signed-off-by: Damien <mouette03@yahoo.fr>
Signed-off-by: Damien <mouette03@yahoo.fr>
* Add avatar upload with size limit and streaming

Implemented streaming upload for avatar with size limit.

Signed-off-by: Damien <mouette03@yahoo.fr>

* Update settings.ts

Signed-off-by: Damien <mouette03@yahoo.fr>

* Improve error handling for avatar upload

Handle specific error cases for avatar upload.

Signed-off-by: Damien <mouette03@yahoo.fr>

* Improve error handling for logo upload

Enhance error handling for logo upload by checking response status and code.

Signed-off-by: Damien <mouette03@yahoo.fr>

* Improve file upload size validation and error handling

Refactor file upload handling to check size limits during write process and handle errors more gracefully.

Signed-off-by: Damien <mouette03@yahoo.fr>

---------

Signed-off-by: Damien <mouette03@yahoo.fr>
@coderabbitai

coderabbitai Bot commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Les handlers d'upload backend passent du buffering en mémoire au streaming vers disque avec limites (avatar 3 MB, logo 2 MB, uploads selon token), gestion du backpressure et nettoyage des fichiers partiels; le frontend détecte 413/FILE_TOO_LARGE; scoping du cache BuildKit par workflow; mise à jour des dépendances Node/Fastify et champ engines ajouté.

Changes

Cohort / File(s) Summary
CI/CD — Docker Build
\.github/workflows/docker.yml
Remplacement des entrées BuildKit partagées par des scopes workflow distincts (${{ github.workflow }}-sqlite, ${{ github.workflow }}-mariadb) pour cache-from / cache-to.
Backend deps & engines
backend/package.json
Ajout de engines (node >=20.8.0, npm >=10.0.0) et mise à jour de dépendances majeures (fastify 4→5, @fastify/* 8/9.x, nodemailer 6→7, types mis à jour).
Uploads — streaming & limits
backend/src/routes/auth.ts, backend/src/routes/settings.ts, backend/src/routes/uploadRequests.ts
Remplacement du buffering par écriture en stream vers disque, gestion du backpressure (attente de drain), vérification incrémentale des tailles (avatar 3 MB, logo 2 MB, uploadRequests selon maxSizeBytes), suppression des fichiers partiels et retour HTTP 413 { code: "FILE_TOO_LARGE" } en cas de dépassement ou d'erreur; gestion d'erreurs structurée autour des streams.
Frontend — erreurs d’upload
frontend/src/pages/ProfilePage.tsx, frontend/src/pages/SettingsPage.tsx
Catch paramétré pour inspecter err.response.status / err.response.data.code et afficher des toasts localisés distincts quand l’upload dépasse la taille (413 / FILE_TOO_LARGE), comportement utilisateur inchangé sinon.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client (navigateur)
    participant Frontend as Frontend (React)
    participant Server as API (Fastify)
    participant FS as Filesystem
    participant DB as Database (Prisma)

    Client->>Frontend: sélectionne fichier et POST /upload
    Frontend->>Server: POST multipart/form-data
    Server->>FS: crée WriteStream vers fichier temporaire
    Server-->>Server: lit chunks et appelle write(chunk)
    alt write() retourne false (backpressure)
        Server->>Server: attend événement "drain"
    end
    Server->>Server: accumulateur de taille vérifié après chaque chunk
    alt taille cumulée > maxBytes
        Server->>FS: destroy stream et supprime fichier partiel
        Server->>Frontend: HTTP 413 { code: "FILE_TOO_LARGE" }
    else succès
        Server->>DB: mise à jour (avatarUrl / appSettings / metadata)
        Server->>Frontend: HTTP 200 (success)
    end
    Frontend->>Client: affiche toast (success ou imageTooLarge)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

🐰 J'ai trotté des bytes sans tout garder en mémoire,
J'ai mâché les limites — trois méga pour l'avatar, deux pour le logo.
Si l'octet déborde, 413 chante son refrain.
Le cache se sépare par workflow, les builds reprennent leur saut.
Hop, un toast pour l'utilisateur, et je replante une carotte.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Le titre couvre les principaux changements du PR : mises à jour de dépendances, amélioration de la gestion des uploads et ajout/modifications de workflows.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • ✅ Generated successfully - (🔄 Check to regenerate)
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cve

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/src/routes/auth.ts`:
- Around line 127-146: The write stream (ws) is ended with ws.end() but not
awaited, so prisma.user.update may set avatarUrl before the file is flushed;
change the logic around ws.end() in backend/src/routes/auth.ts to await the
stream completion by attaching 'finish'/'error' listeners (the same pattern used
in uploadRequests.ts) and only proceed to call prisma.user.update(...) after the
promise resolves successfully; ensure you still destroy/remove the file on error
and propagate the error so late stream errors are caught.

In `@backend/src/routes/settings.ts`:
- Around line 207-227: The stream write in settings.ts uses ws.end() but does
not wait for the stream to finish, so the subsequent upsert may record logoUrl
before the file is fully written and late stream errors won't be caught; change
the logic after ws.end() to await a Promise that resolves on ws.once('finish')
and rejects on ws.once('error') (mirroring the safe pattern in
backend/src/routes/uploadRequests.ts lines ~145-149), ensuring you still destroy
and remove the file on error and only proceed to the upsert after the finish
event completes.

In `@backend/src/routes/uploadRequests.ts`:
- Around line 133-139: When a part exceeds maxBytes inside the for-await loop
(in uploadRequests.ts, the loop reading part.file and the variables size,
maxBytes, writeStream, savedFiles), ensure you clean up all already-written
files before returning 413: destroy/close the current writeStream, iterate
savedFiles and remove each path (use fs.remove and catch errors), and optionally
remove the request directory (UPLOAD_DIR/received/<request.id>) before sending
reply.code(413). Also ensure savedFiles is updated only after a successful write
so cleanup covers only actual files on disk.
- Around line 130-136: Change maxSizeBytes to remain a BigInt (do not Number()
it); set const maxBytes = request.maxSizeBytes === null ? null :
request.maxSizeBytes and initialize let size = 0n, then inside the loop add size
+= BigInt(chunk.length) and check explicitly if (maxBytes !== null && size >
maxBytes) to enforce limits (handle 0n correctly). Also when triggering the 413
response in the part.file loop, ensure you clean up previously written files in
savedFiles (same cleanup used in the password-failure branch) before returning
so no temporary files remain orphaned.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5dad2d49-6eec-4cf2-abb8-a7d94ea9943d

📥 Commits

Reviewing files that changed from the base of the PR and between d4bee1b and 832e8f2.

📒 Files selected for processing (7)
  • .github/workflows/docker.yml
  • backend/package.json
  • backend/src/routes/auth.ts
  • backend/src/routes/settings.ts
  • backend/src/routes/uploadRequests.ts
  • frontend/src/pages/ProfilePage.tsx
  • frontend/src/pages/SettingsPage.tsx

Comment thread backend/src/routes/auth.ts
Comment thread backend/src/routes/settings.ts
Comment thread backend/src/routes/uploadRequests.ts Outdated
Comment thread backend/src/routes/uploadRequests.ts
Mouette03 and others added 4 commits March 25, 2026 21:40
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Damien <mouette03@yahoo.fr>
Signed-off-by: Damien <mouette03@yahoo.fr>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
backend/src/routes/settings.ts (1)

207-231: Implémentation de streaming bien réalisée, correctif du finish appliqué.

La gestion du backpressure avec drain et l'attente de finish avant l'upsert sont correctes. Le nettoyage dans le catch est approprié.

Suggestion mineure : pendant la boucle for await (lignes 213-221), aucun listener error n'est attaché à ws. Si une erreur d'écriture survient (ex: disque plein), l'événement serait non géré, ce qui pourrait causer un crash ou un blocage si on attend drain. Pour plus de robustesse :

♻️ Proposition pour capturer les erreurs du write stream pendant l'itération
       const ws = fs.createWriteStream(filePath)
       let received = 0
+      let writeError: Error | null = null
+      ws.on('error', (err) => { writeError = err })
       try {
         for await (const chunk of data.file) {
+          if (writeError) throw writeError
           received += chunk.length
           if (received > MAX_BYTES) {
             ws.destroy()
             await fs.remove(filePath).catch(() => {})
             return reply.code(413).send({ code: 'FILE_TOO_LARGE', maxBytes: MAX_BYTES })
           }
           if (!ws.write(chunk)) await new Promise<void>(r => ws.once('drain', r))
         }
+        if (writeError) throw writeError
         await new Promise<void>((resolve, reject) => {

Note : fs.ensureFile(filePath) (ligne 209) est redondant car createWriteStream crée automatiquement le fichier, mais ce n'est pas problématique.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/routes/settings.ts` around lines 207 - 231, Attach an 'error'
listener to the write stream (ws) before entering the for-await loop to catch
write failures (e.g., disk full) and propagate them to the existing
cleanup/exception path; ensure this listener rejects/throws so the outer
try/catch can remove the partial file and respond appropriately, and remove the
listener when the stream finishes or errors to avoid leaks. Specifically, add a
handler on ws (used in the for-await over data.file and referenced alongside
MAX_BYTES and the 'drain' wait) that signals/throws on write errors, so awaiting
the 'drain' or the final 'finish' cannot deadlock on an unhandled write error.
Ensure the handler is cleaned up after ws.once('finish')/ws.once('error')
resolution.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@backend/src/routes/settings.ts`:
- Around line 207-231: Attach an 'error' listener to the write stream (ws)
before entering the for-await loop to catch write failures (e.g., disk full) and
propagate them to the existing cleanup/exception path; ensure this listener
rejects/throws so the outer try/catch can remove the partial file and respond
appropriately, and remove the listener when the stream finishes or errors to
avoid leaks. Specifically, add a handler on ws (used in the for-await over
data.file and referenced alongside MAX_BYTES and the 'drain' wait) that
signals/throws on write errors, so awaiting the 'drain' or the final 'finish'
cannot deadlock on an unhandled write error. Ensure the handler is cleaned up
after ws.once('finish')/ws.once('error') resolution.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e8f3dafc-ff10-43eb-98bb-e246c3351860

📥 Commits

Reviewing files that changed from the base of the PR and between d28cac7 and 6b63923.

📒 Files selected for processing (1)
  • backend/src/routes/settings.ts

@Mouette03 Mouette03 merged commit eb62065 into main Mar 25, 2026
1 check passed
@coderabbitai

coderabbitai Bot commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

Note

Docstrings generation - SUCCESS
Generated docstrings for this pull request at #5

coderabbitai Bot added a commit that referenced this pull request Mar 25, 2026
Docstrings generation was requested by @Mouette03.

* #4 (comment)

The following files were modified:

* `backend/src/routes/auth.ts`
* `backend/src/routes/settings.ts`
* `backend/src/routes/uploadRequests.ts`
* `frontend/src/pages/ProfilePage.tsx`
* `frontend/src/pages/SettingsPage.tsx`
@coderabbitai coderabbitai Bot mentioned this pull request Mar 25, 2026
Mouette03 pushed a commit that referenced this pull request Mar 25, 2026
Docstrings generation was requested by @Mouette03.

* #4 (comment)

The following files were modified:

* `backend/src/routes/auth.ts`
* `backend/src/routes/settings.ts`
* `backend/src/routes/uploadRequests.ts`
* `frontend/src/pages/ProfilePage.tsx`
* `frontend/src/pages/SettingsPage.tsx`

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Mouette03 added a commit that referenced this pull request Mar 25, 2026
* Update dependencies in package.json

update CVE

Signed-off-by: Damien <mouette03@yahoo.fr>

* Update Fastify dependencies to latest versions

Signed-off-by: Damien <mouette03@yahoo.fr>

* Update caching strategy for Docker builds

Signed-off-by: Damien <mouette03@yahoo.fr>

* Modify package.json for engine versions and types

Updated Node.js and npm engine requirements and upgraded nodemailer types.

Signed-off-by: Damien <mouette03@yahoo.fr>

* Update Node.js engine version requirement

Signed-off-by: Damien <mouette03@yahoo.fr>

* Add license scanning workflow for frontend and backend

Signed-off-by: Damien <mouette03@yahoo.fr>

* Rename licences check .yml to license-checker.yml

Signed-off-by: Damien <mouette03@yahoo.fr>

* Delete .github/workflows/license-checker.yml

Signed-off-by: Damien <mouette03@yahoo.fr>

* Limite upload logo avatar (#3)

* Add avatar upload with size limit and streaming

Implemented streaming upload for avatar with size limit.

Signed-off-by: Damien <mouette03@yahoo.fr>

* Update settings.ts

Signed-off-by: Damien <mouette03@yahoo.fr>

* Improve error handling for avatar upload

Handle specific error cases for avatar upload.

Signed-off-by: Damien <mouette03@yahoo.fr>

* Improve error handling for logo upload

Enhance error handling for logo upload by checking response status and code.

Signed-off-by: Damien <mouette03@yahoo.fr>

* Improve file upload size validation and error handling

Refactor file upload handling to check size limits during write process and handle errors more gracefully.

Signed-off-by: Damien <mouette03@yahoo.fr>

---------

Signed-off-by: Damien <mouette03@yahoo.fr>

* Update backend/src/routes/auth.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Damien <mouette03@yahoo.fr>

* Update uploadRequests.ts

Signed-off-by: Damien <mouette03@yahoo.fr>

* Update uploadRequests.ts

* Update settings.ts

* 📝 Add docstrings to `cve` (#5)

Docstrings generation was requested by @Mouette03.

* #4 (comment)

The following files were modified:

* `backend/src/routes/auth.ts`
* `backend/src/routes/settings.ts`
* `backend/src/routes/uploadRequests.ts`
* `frontend/src/pages/ProfilePage.tsx`
* `frontend/src/pages/SettingsPage.tsx`

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Signed-off-by: Damien <mouette03@yahoo.fr>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant