fix(instagram): sign and validate OAuth state with nonce and TTL to prevent CSRF account linking

Abierto
#37 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
54/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
redis, typescript

Línea de trabajo

Start with apps/api/src/instagram/services/instagram-auth.service.ts and the initiateAuth and callback paths in apps/api/src/instagram/instagram.controller.ts. Trace how OAuth state is created and how the callback exchanges the code; check the existing Redis setup and available secret configuration. Done means the callback rejects invalid, expired, and replayed state before token exchange or account linking, with tests covering those cases.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

backend bug
Problem Description

In apps/api/src/instagram/services/instagram-auth.service.ts, getOAuthUrl sets the OAuth state parameter to raw ${userId}:new or ${userId} with no HMAC signature, random nonce, expiration, or session/cookie binding.

Meanwhile, @Public() @Get('callback') in apps/api/src/instagram/instagram.controller.ts calls handleOAuthCallback, which splits state.split(':') and trusts the userId directly to link the Instagram account to user.company.id and overwrite Company.instagramHandle.

An attacker who knows or guesses a userId can complete OAuth with their own Instagram account and replay /api/instagram/callback?code=<attacker_code>&state=<victim_userId> (or CSRF a logged-in victim) to link their Instagram account to the victim's workspace, hijacking instagramHandle, automations, and leads.


Expected Behavior
  1. The OAuth state parameter must be cryptographically signed (HMAC-SHA256) and bound to a short-lived, single-use random nonce (e.g., 10-minute TTL on the OAuth handshake only — connected Instagram accounts and long-lived tokens are unaffected).
  2. handleOAuthCallback must verify the signature, expiration, and single-use nonce (atomically deleting it) before exchanging code or linking any InstagramAccount.
  3. Invalid, expired, tampered, or replayed state values must be rejected with 400/401.

Where to Look
  • apps/api/src/instagram/instagram.controller.ts (initiateAuth, callback)
  • apps/api/src/instagram/services/instagram-auth.service.ts (getOAuthUrl, handleOAuthCallback)

Solution / Implementation Guide
  1. Sign & store state in getOAuthUrl:

    • Generate a random nonce (crypto.randomBytes(16).toString('hex')) and payload { userId, setupMode, nonce, exp: Date.now() + 10 * 60 * 1000 }.
    • Store oauth:state:${nonce} in Redis with a 10-minute TTL (or bind nonce to an HttpOnly; SameSite=Lax cookie).
    • Encode base64url(JSON.stringify(payload)) and append an HMAC-SHA256 signature using AUTH_SECRET / NEXTAUTH_SECRET (<encoded>.<sig>).
  2. Verify & consume state in handleOAuthCallback:

    • Split <encoded>.<sig>, verify the HMAC with crypto.timingSafeEqual, parse the payload, and check Date.now() <= payload.exp.
    • Atomically verify and delete oauth:state:${payload.nonce} in Redis (or verify the HttpOnly cookie nonce) so the callback URL cannot be replayed.
    • Only after verification passes, proceed with token exchange and InstagramAccount linking.
Lenguaje dominante
TypeScript
Estrellas
2
Forks
1
Merge medio
6 min
PR fusionados (30 d)
27

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de sumamakhan761/tryinstance

Todos los issues de sumamakhan761/tryinstance

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.