Skip to content

fix(api): log why the login captcha rejected a request - #8

Merged
tulubyev merged 1 commit into
mainfrom
fix/captcha-failure-logging
Oct 14, 2026
Merged

tulubyev merged 1 commit into
mainfrom
fix/captcha-failure-logging

Conversation

@tulubyev

@tulubyev tulubyev commented Oct 14, 2026 •

Copy link
Copy Markdown
Owner

Что сделано

verifyCaptcha теперь пишет в лог одну строку [captcha] rejected reason=... на каждый отказ: причина, статус и безопасная выжимка ответа Aptogon (success, human, band, error, тип и место ошибки валидации, список ключей ответа) и время ответа провайдера. Раньше отказ входа не оставлял следов в docker logs, поэтому нельзя было отличить «капча сломана» от «отбит бот».

Заодно ответ провайдера с не-JSON телом (HTML ошибки прокси) больше не ломает проверку.
В CLAUDE.md добавлена команда для чтения этих строк и расшифровка причин.

Как проверено

Прогнал verifyCaptcha на подставных ответах fetch по всем путям: нет токена, 409, 422 с эхом токена, success=false, human=false, 502 без JSON, сетевая ошибка и успех. На каждой строке лога проверено, что в ней нет ни токена, ни секрета. tsc --noEmit без ошибок.

Важно

Сырое тело ответа не логируется намеренно: при ошибке валидации (422) провайдер возвращает присланные данные, то есть одноразовый токен.

Что осталось

  • Чтобы увидеть причины на проде, нужна пересборка API: sudo docker compose up -d --build api после merge.
  • Сама причина жалобы «капча не работает» пока неизвестна. После выкатки по строкам [captcha] rejected станет понятно, что происходит.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Captcha verification failures now include elapsed time and selected response details in API logs, without exposing raw provider errors. Invalid response data is handled safely, and existing failure outcomes are preserved.
  • Documentation
    • Added guidance for finding captcha failures in API logs, including the available failure reasons and confirmation that tokens and secrets are not logged.

verifyCaptcha returned a bare reason and logged nothing, so a refused login
left no trace in `docker logs`. Log one `[captcha] rejected reason=...` line
per refusal with a safe summary of the provider response (status, success,
human, band, error fields, validation error type/location, response keys)
and the provider round-trip time.

The raw provider body is never logged: on a 422 it echoes the submitted data
(`detail[].input`), i.e. the one-time token. The token and secret are not
logged anywhere. Non-JSON error bodies (proxy HTML) no longer throw.

Verified with a mocked fetch over all paths (no token, 409, 422 with echoed
token, success=false, human=false, 502 non-JSON, network error, success) and
asserting neither the token nor the secret appears in any log line.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4953d797-3fac-4132-babe-5a3e2e85fdc8
📥 Commits

Reviewing files that changed from the base of the PR and between 22872f1 and 70afb3a.

📒 Files selected for processing: 2
  • CLAUDE.md
  • apps/api/src/infrastructure/captcha/aptogon.client.ts

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

📝 Walkthrough

The Aptogon captcha client now logs rejected checks with elapsed time and bounded response details. The documentation describes how to filter captcha logs and lists rejection reason codes.

Changes: Captcha rejection diagnostics

Layer / File(s) Summary
Summarize and log captcha rejections
apps/api/src/infrastructure/captcha/aptogon.client.ts, CLAUDE.md
The client logs rejected checks with elapsed time and selected response details. It reads the response body once and preserves the existing acceptance rule and failure reasons. The documentation lists log filters, rejection codes, and the fact that tokens and secrets are not logged.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Feature

Merge Risk: ⚪ Minimal · up to 70afb

No actionable merge-blocking issue remains in the captcha diagnostics change. The production cause of captcha rejections still needs diagnosis after deployment.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 1 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: adding API logs that explain why login CAPTCHA verification rejects a request.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 1 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@tulubyev
tulubyev merged commit 6827d27 into main Oct 14, 2026
5 checks passed
@tulubyev
tulubyev deleted the fix/captcha-failure-logging branch October 14, 2026 00:21
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