npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@digitalsac/digisocket

v8.0.10

Published

DigiSocket — WebSockets library para WhatsApp Web (Digitalsac)

Downloads

417

Readme

DigiSocket (@digitalsac/digisocket)

Biblioteca TypeScript para integração com WhatsApp Web (multi-device), mantida pela Digitalsac.

O que esta versão inclui

  • Conexão WhatsApp Web sem navegador (WebSocket direto)
  • API única de envio com suporte a vários tipos de conteúdo
  • Recursos funcionais para:
    • botões interativos (interactiveMessage / native flow)
    • listas (listMessage / single_select)
    • carousel (nativeCarousel e interactiveMessage.carouselMessage)
  • Tratamento automático de falhas de privacidade com retry no erro 463
  • Tipagem forte para mensagens, eventos, auth e configuração de socket

Instalação

npm i @digitalsac/digisocket

ou

yarn add @digitalsac/digisocket

Import principal:

import makeWASocket from '@digitalsac/digisocket'

Quick start

import makeWASocket, {
  Browsers,
  DisconnectReason,
  useMultiFileAuthState
} from '@digitalsac/digisocket'
import { Boom } from '@hapi/boom'

async function startSock() {
  const { state, saveCreds } = await useMultiFileAuthState('auth_info')

  const sock = makeWASocket({
    auth: state,
    browser: Browsers.ubuntu('Digitalsac Bot'),
    // descontinuado no WA web moderno: prefira ler connection.update.qr
    printQRInTerminal: false
  })

  sock.ev.on('creds.update', saveCreds)

  sock.ev.on('connection.update', ({ connection, qr, lastDisconnect }) => {
    if (qr) {
      console.log('QR recebido, exiba no terminal/frontend:', qr)
    }

    if (connection === 'close') {
      const status = (lastDisconnect?.error as Boom)?.output?.statusCode
      const shouldReconnect = status !== DisconnectReason.loggedOut
      if (shouldReconnect) startSock()
    }

    if (connection === 'open') {
      console.log('Conectado com sucesso')
    }
  })
}

startSock()

Pareamento por código

if (!sock.authState.creds.registered) {
  const phone = '5511999999999' // sem +, sem espaços
  const code = await sock.requestPairingCode(phone)
  console.log('Pairing code:', code)
}

Envio de mensagens

Assinatura padrão:

await sock.sendMessage(jid, content, options)

Texto simples

await sock.sendMessage(jid, { text: 'Olá! Tudo bem?' })

Com citação (quoted)

await sock.sendMessage(jid, { text: 'Respondendo sua mensagem' }, { quoted: originalMsg })

Mídia

await sock.sendMessage(jid, {
  image: { url: './media/banner.png' },
  caption: 'Imagem de exemplo'
})

Áudio (MP3 -> OGG/OPUS automático)

Se você precisa enviar áudio de forma compatível com WhatsApp (PTT/voz), pode habilitar a transformação automática. No código, a conversão é aplicada para áudio com ptt: true quando transformAudio está ativo.

Habilitar globalmente no socket

const sock = makeWASocket({
  auth: state,
  transformAudio: true
})

Exemplo de envio convertendo automaticamente

await sock.sendMessage(
  jid,
  {
    audio: { url: './media/audio.mp3' },
    ptt: true,
    // pode entrar mp3/mp4; a lib converte para ogg/opus no fluxo PTT
    mimetype: 'audio/mp4'
  },
  {
    // override por mensagem (opcional)
    transformAudio: true
  }
)

Requisito: FFmpeg disponível no ambiente (a biblioteca usa fluent-ffmpeg + ffmpeg-static no pipeline).

Enquete

await sock.sendMessage(jid, {
  poll: {
    name: 'Qual opção você prefere?',
    values: ['Opção A', 'Opção B'],
    selectableCount: 1
  }
})

Botões interativos (Native Flow)

import { proto } from '@digitalsac/digisocket'

const interactive: proto.Message.IInteractiveMessage = {
  body: { text: 'Escolha uma ação' },
  header: { title: 'Menu rápido' },
  footer: { text: 'Digitalsac' },
  nativeFlowMessage: {
    buttons: [
      {
        name: 'quick_reply',
        buttonParamsJson: JSON.stringify({
          display_text: 'Atendimento',
          id: 'menu_atendimento',
          disabled: false
        })
      },
      {
        name: 'cta_url',
        buttonParamsJson: JSON.stringify({
          display_text: 'Abrir site',
          id: 'menu_site',
          url: 'https://digitalsac.com.br',
          disabled: false
        })
      },
      {
        name: 'cta_copy',
        buttonParamsJson: JSON.stringify({
          display_text: 'Copiar cupom',
          id: 'menu_coupon',
          copy_code: 'DIGI10',
          disabled: false
        })
      },
      {
        name: 'cta_call',
        buttonParamsJson: JSON.stringify({
          display_text: 'Ligar agora',
          id: 'menu_call',
          phone_number: '5511999999999',
          disabled: false
        })
      }
    ]
  }
}

await sock.sendMessage(jid, { interactiveMessage: interactive })

Lista (listMessage / single_select)

import { proto } from '@digitalsac/digisocket'

await sock.sendMessage(jid, {
  title: 'Atendimento Digitalsac',
  text: 'Escolha uma opção:',
  footer: 'Use a lista para navegar',
  buttonText: 'Abrir opções',
  listType: proto.Message.ListMessage.ListType.SINGLE_SELECT,
  sections: [
    {
      title: 'Financeiro',
      rows: [
        { title: '2ª via boleto', description: 'Gerar boleto atualizado', rowId: 'financeiro_boleto' },
        { title: 'Comprovante', description: 'Enviar comprovante', rowId: 'financeiro_comprovante' }
      ]
    },
    {
      title: 'Suporte',
      rows: [
        { title: 'Instabilidade', description: 'Reportar problema técnico', rowId: 'suporte_instabilidade' }
      ]
    }
  ]
})

Carousel

A fork Digitalsac suporta envio com nativeCarousel (tipado) e payload interativo nativo.

await sock.sendMessage(jid, {
  title: 'Ofertas Digitalsac',
  text: 'Selecione um card:',
  footer: 'Campanha de hoje',
  nativeCarousel: {
    title: 'Produtos em destaque',
    cards: [
      {
        title: 'Plano Start',
        body: 'Ideal para times pequenos',
        footer: 'R$ 99/mês',
        image: { url: './media/plan-start.png' },
        buttons: [
          { type: 'reply', text: 'Tenho interesse', id: 'card_start_interest' },
          { type: 'url', text: 'Detalhes', url: 'https://digitalsac.com.br/planos/start' }
        ]
      },
      {
        title: 'Plano Pro',
        body: 'Automação avançada',
        footer: 'R$ 199/mês',
        image: { url: './media/plan-pro.png' },
        buttons: [{ type: 'reply', text: 'Falar com vendas', id: 'card_pro_sales' }]
      }
    ]
  }
})

Recebimento de respostas (lista/botão/flow)

sock.ev.on('messages.upsert', async ({ messages }) => {
  const m = messages[0]
  const msg = m.message
  if (!msg) return

  if (msg.listResponseMessage) {
    const rowId = msg.listResponseMessage.singleSelectReply?.selectedRowId
    console.log('Resposta de lista:', rowId)
  }

  if (msg.buttonsResponseMessage) {
    const selected = msg.buttonsResponseMessage.selectedButtonId
    console.log('Resposta de botão:', selected)
  }

  if (msg.interactiveResponseMessage) {
    console.log('Resposta de native flow recebida')
  }
})

Erro 463 (privacy token inválido) - tratamento embutido

A DigiSocket já trata automaticamente ACK com erro 463:

  1. invalida estado de privacidade do contato (tctoken/cstoken)
  2. evita loop com retry único por msgId
  3. tenta reenvio automático da mensagem (cache recente)
  4. se falhar, marca mensagem como ERROR em messages.update

Requisitos para funcionar bem

  • manter persistência correta de auth/keys
  • deixar enableRecentMessageCache ativo

Observabilidade recomendada

sock.ev.on('messages.update', updates => {
  for (const u of updates) {
    if (u.update?.status != null) {
      console.log('status=', u.update.status, 'id=', u.key.id, 'stub=', u.update.messageStubParameters)
    }
  }
})

Tipos mais usados (TypeScript)

A biblioteca exporta muitos tipos úteis. Os mais comuns:

  • AnyMessageContent
  • AnyRegularMessageContent
  • WAMessage
  • WAMessageKey
  • WAMessageContent
  • PollMessageOptions
  • NativeButton
  • NativeCarouselOptions
  • MiscMessageGenerationOptions
  • MessageRelayOptions
  • SocketConfig
  • UserFacingSocketConfig
  • DisconnectReason

Exemplo de imports:

import type {
  AnyMessageContent,
  WAMessage,
  WAMessageKey,
  SocketConfig,
  UserFacingSocketConfig
} from '@digitalsac/digisocket'

Flags importantes da fork Digitalsac

Além das opções tradicionais, esta versão traz controles extras:

  • interactiveCarouselEnabled
  • tctokenEnabled
  • tctokenCacheTtlMs
  • cstokenEnabled
  • enableCTWARecovery
  • enableAutoSessionRecreation
  • enableRecentMessageCache
  • maxWebSocketListeners
  • maxSocketClientListeners
  • compatV6GroupSend
  • decryptCacheEnabled
  • reportingMetadataEnabled
  • presenceDebounceEnabled
  • wssFailoverEnabled

Configuração real usada no backend (backend/src/libs/wbot.ts)

No backend da Digitalsac, o makeWASocket é inicializado com um conjunto de parâmetros já validados em produção.

Principais opções ativas hoje

| Campo | Valor usado | Objetivo | |---|---:|---| | browser | [connectName, "Chrome", "140.0.7339.127"] | Fingerprint consistente para sessão Web | | transformAudio | true | Converte áudio PTT para formato compatível | | markOnlineOnConnect | true | Mantém sessão com presença online ao conectar | | tctokenEnabled | true | Habilita token de privacidade por contato | | cstokenEnabled | true | Habilita fallback de token de sessão por contato | | decryptCacheEnabled | true | Reduz CPU em mensagens repetidas/reprocessadas | | decryptCacheMaxSize | 20000 | Limite do cache de decrypt | | decryptCacheTtlMs | 120000 | TTL do cache de decrypt (2 min) | | communityRulesEnabled | true | Regras para canais/comunidades | | groupCacheMaxSize | 5000 | Cache de metadados de grupos | | groupCacheTtlMs | 300000 | TTL cache de grupos (5 min) | | retryRequestDelayMs | 350 | Delay de retry de envio | | maxMsgRetryCount | 4 | Máximo de retries por mensagem | | defaultQueryTimeoutMs | 60000 | Timeout padrão de queries | | connectTimeoutMs | 60000 | Timeout de conexão | | keepAliveIntervalMs | 30000 | Intervalo de keepalive | | fireInitQueries | true | Inicialização completa da sessão | | syncFullHistory | shouldDownloadHistory | Sync completo quando importação pede | | inboundQueueYieldThreshold | 256 | Controle de alívio da fila inbound | | inboundQueueYieldMs | 2 | Yield entre lotes inbound | | historySyncThrottleMs | 100 | Throttle de histórico | | appStateMutationYieldMs | 2 | Yield de mutações app-state | | socketReadyGateEnabled | false | Evita travas de gate de prontidão | | gracefulShutdownEnabled | false | Evita shutdown gracioso interferir em restart | | enableCTWARecovery | true | Recuperação de placeholder/CTWA | | maxWebSocketListeners | 20 | Limite seguro de listeners no WS | | maxSocketClientListeners | 50 | Limite seguro de listeners no client |

Também são usados:

  • getMessage com cache local (msgDB) para retry e reconstrução de envio.
  • cachedGroupMetadata com Redis + banco (GroupCache) para reduzir chamadas ao WA.
  • makeCacheableSignalKeyStore para acelerar authState.keys.

Persistência e rotação de tctoken / cstoken no backend

Além do tratamento automático do erro 463 na lib, o backend da Digitalsac já possui helpers para persistir/invalidar privacy state:

  • backend/src/helpers/baileys-privacy-state.ts
  • storage real via state.keys (Dragonfly/Mongo/File auth store)

Como persistir manualmente (quando necessário)

import {
  setStoredTcToken,
  setStoredCsToken,
  setStoredNctSalt
} from '../helpers/baileys-privacy-state'

// keys = auth state da sessão: wbot.authState.keys
await setStoredTcToken(keys, '[email protected]', {
  token: Buffer.from('...'),
  timestamp: new Date().toISOString(),
  source: 'server'
})

await setStoredCsToken(keys, '[email protected]', {
  token: Buffer.from('...'),
  timestamp: new Date().toISOString(),
  source: 'fallback'
})

await setStoredNctSalt(keys, {
  salt: Buffer.from('...'),
  timestamp: new Date().toISOString(),
  source: 'server'
})

Como invalidar e forçar troca de token

Use quando houver troca de identidade, erro de privacidade recorrente, ou reciclagem de sessão:

import {
  invalidatePrivacyStateForJid,
  invalidateTcTokenForJid,
  invalidateCsTokenForJid,
  invalidateAllPrivacyStateForSession
} from '../helpers/baileys-privacy-state'

// Invalida os dois tokens do contato
await invalidatePrivacyStateForJid(keys, '[email protected]')

// Ou granular:
await invalidateTcTokenForJid(keys, '[email protected]')
await invalidateCsTokenForJid(keys, '[email protected]')

// Invalida o salt global da sessão (nctsalt)
await invalidateAllPrivacyStateForSession(keys)

Onde isso fica salvo

No auth state da sessão (ex.: DragonflyAuth), com chaves por prefixo de sessão:

  • whatsapp:session:${sessionId}:tctoken-${jidNormalizado}
  • whatsapp:session:${sessionId}:cstoken-${jidNormalizado}
  • whatsapp:session:${sessionId}:nctsalt-global

Isso permite persistir entre reconexões, reinício de processo e troca de nó.


Build e publicação (com ofuscação seletiva)

Neste repositório:

  • npm run build -> compila TypeScript
  • npm run build:release -> compila + ofusca arquivos definidos
  • prepack/prepare -> configurados para garantir pacote publicado já ofuscado

Arquivos de controle:

  • scripts/obfuscate-targets.json
  • scripts/obfuscate-lib.mjs
  • build-info.json

Boas práticas de produção

  • Persistir sessões/chaves fora de memória volátil
  • Reconectar com base em connection.update
  • Tratar DisconnectReason.loggedOut sem reconnect automático cego
  • Evitar spam e respeitar os termos de uso do WhatsApp
  • Logar messages.update e eventos de ACK/erro

Aviso legal

Este projeto não é afiliado ao WhatsApp. Use com responsabilidade e em conformidade com os termos da plataforma.


License

Copyright (c) 2025 Silvio Erick/Digitalsac

Licensed under the MIT License.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.