Skip to content

Corrigir autenticação WA.Auto e diagnóstico da automação - #45

Merged
W1CAPITAL merged 5 commits into
mainfrom
fix/waauto-shared-auth-health-20261010
Oct 10, 2026
Merged

W1CAPITAL merged 5 commits into
mainfrom
fix/waauto-shared-auth-health-20261010

Conversation

@W1CAPITAL

Copy link
Copy Markdown
Owner

Defeito observado

O LexisPredict enviava token de integração com x-lexis-user-id, mas o callback /api/integration/wa-auto/auth aceitava apenas JWT do Supabase ou tokens lexiswa1, rejeitando a identidade do serviço. Além disso, WA_AUTO_TOKEN (legado) prevalecia sobre WA_INTEGRATION_TOKEN.

Correção

  • Aceita token compartilhado forte apenas com identidade de usuário válida, verificação constante e autorização atual de cargo/empresa no Supabase; rejeita operadores e credenciais divergentes.
  • Prioriza WA_INTEGRATION_TOKEN ao identificar a credencial canônica.
  • Novo botão 'Testar automação' no WhatsApp, com probe sem envio usando exatamente o transport do cron/scanner, independente do estado da conexão visual.
  • Testes para autenticação e falhas.

Produção

Não reinicia filas nem envia aos clientes. Validação externa depende de as credenciais configuradas no Render e no LexisPredict corresponderem e de o serviço WA.Auto estar acessível. Não foi possível consultar os logs do Render sem conexão da conta.

@strix-security

Copy link
Copy Markdown

Strix is installed on this repository, but we couldn't run this PR security review because this workspace's trial has ended. Add a card to resume code reviews here.

@netlify

netlify Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for lexispredict ready!

Name Link
🔨 Latest commit 7596cda
🔍 Latest deploy log https://app.netlify.com/projects/lexispredict/deploys/6aca4e819a691d000808ae18
😎 Deploy Preview https://deploy-preview-45--lexispredict.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@vercel

vercel Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
private Ready Ready Preview Oct 10, 2026 2:44pm UTC

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-10T14:45:20.469600Z 7596cda PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@W1CAPITAL
W1CAPITAL merged commit ea35073 into main Oct 10, 2026
7 of 8 checks passed

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7596cdad8f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +87 to +89
const {data:profile,error:lookupError} = await db.from("usuarios")
.select("auth_user_id,empresa_id,cargo")
.eq("auth_user_id",actorId).maybeSingle();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Bind shared-token actors to the originating company

When an automation setting retains an owner who has since moved to another company, this lookup authenticates that user's current profile and returns the new empresa_id instead of rejecting the old company's request. waAutoForOwner(userId, empresaId, ...) validates but never transmits empresaId, and callers such as processOneDailyReturn can use a stored owner without rechecking membership, so an old tenant's customer message can be sent through a manager/session now belonging to another tenant. Carry the expected company in the authenticated request and include it in this lookup, as the existing signed-worker path does.

Useful? React with 👍 / 👎.

Comment on lines +74 to +77
const sharedMatch =
integrationToken.length >= 24 &&
token.length === integrationToken.length &&
timingSafeEqual(Buffer.from(token), Buffer.from(integrationToken));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Compare encoded byte lengths before timing-safe comparison

An unauthenticated caller can send a bearer token with the same JavaScript character length as the configured ASCII secret but with multibyte characters. The string-length guard then passes while the two Buffers have different byte lengths, causing timingSafeEqual to throw ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH and turn an invalid credential into an uncaught HTTP 500. Construct both buffers first and compare their byte lengths before invoking timingSafeEqual.

Useful? React with 👍 / 👎.

Comment on lines +43 to +44
const result = await waAutoAutomationReadinessAction();
setAutomationResult(result);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Clear the successful probe when connection state changes

After a successful automation check, automationResult remains successful indefinitely even if the user immediately disconnects or a subsequent refresh observes that the WA.Auto session is offline. The card then simultaneously shows a disconnected connection and the green message that the bridge is validated for automation, which can lead a manager to leave scheduled sends enabled under the false impression that they are operational. Clear or invalidate this result on logout and whenever refreshed connection state is no longer ready.

Useful? React with 👍 / 👎.

Comment on lines +91 to +93
const permission=resolveWaAutoPermissions(profile);
if (!profile?.empresa_id || !permission.canManage) {
return NextResponse.json({ok:false,error:"worker_not_authorized"},{status:403});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve WA.Auto access for ordinary operators

When WA_INTEGRATION_TOKEN is configured, every normal status/chat/send call uses this shared-token branch, not only background automation. sendWhatsAppAction explicitly permits authenticated non-viewer operators, but this branch returns 403 for them; because waAutoFetch retries with the user's JWT only after a 401, operators can no longer send messages or query WA.Auto even though the JWT path supports their non-manager identity. Either distinguish automated requests from interactive shared-token calls or return/fallback to JWT authentication for valid operators.

Useful? React with 👍 / 👎.

This branch was successfully deployed

1 active deployment
Preview — 7596cdad Deployed Oct 10, 2026 by vercel[bot]
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