baileys-antiban 3.8.4 → 3.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,17 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [3.8.5] - 2026-05-09
9
+
10
+ ### Added
11
+ - **Observability module** (`src/observability.ts`) — Prometheus metrics export and pluggable structured logging.
12
+ - `exportPrometheusMetrics(stats, labels?)` — exports 27 metrics (3 counters, 24 gauges) in Prometheus text exposition format v0.0.4. Covers health score/risk, warmup progress, rate limiter windows, known chats, reply ratio, contact graph, retry spirals, reconnect throttle. Accepts custom labels (`instance`, `region`, etc.).
13
+ - `createMetricsHandler(getStats, labels?)` — returns Express/Fastify-compatible `handle(req, res)` + `text()` helpers for a `/metrics` endpoint.
14
+ - `createPeriodicExporter(getStats, config)` — push-based exporter that calls `onMetrics(text)` on a configurable interval (default 30s). Returns `stop()` handle.
15
+ - `createConsoleLogger(prefix?)` — structured console logger compatible with winston/pino interface (`debug`, `info`, `warn`, `error` with ISO timestamps and JSON meta).
16
+ - `AntiBanLogger` interface — plug in any logger: `winston`, `pino`, or the built-in console logger.
17
+ - New exports: `createConsoleLogger`, `exportPrometheusMetrics`, `createMetricsHandler`, `createPeriodicExporter`, `AntiBanLogger`, `PeriodicExporterConfig`, `PeriodicExporterHandle`.
18
+
8
19
  ## [3.8.4] - 2026-05-09
9
20
 
10
21
  ### Added
package/dist/index.d.ts CHANGED
@@ -38,3 +38,4 @@ export { readReceiptVariance, type ReadReceiptVariance, type ReadReceiptVariance
38
38
  export { proxyRotator, type ProxyEndpoint, type ProxyRotatorConfig, type ProxyRotatorStats, type ProxyRotatorHandle, } from './proxyRotator.js';
39
39
  export { generateSessionFingerprint, applySessionFingerprint, getMessageSendJitter, getTypingJitter, getRetryJitter, getVoiceNoteMetadata, getBatteryState, createStealthFingerprint, type SessionFingerprint, type SessionFingerprintConfig, } from './sessionFingerprint.js';
40
40
  export { getStealthSocketConfig, rampPresenceAfterConnect, STEALTH_BROWSER_POOL, AbortError, type BrowserTuple, type StealthSocketConfig, type GetStealthSocketConfigOptions, type RampPresenceOptions, type PresenceCapableSocket, } from './stealthConnect.js';
41
+ export { createConsoleLogger, exportPrometheusMetrics, createMetricsHandler, createPeriodicExporter, type AntiBanLogger, type PeriodicExporterConfig, type PeriodicExporterHandle, } from './observability.js';
package/dist/index.js CHANGED
@@ -53,3 +53,5 @@ export { proxyRotator, } from './proxyRotator.js';
53
53
  export { generateSessionFingerprint, applySessionFingerprint, getMessageSendJitter, getTypingJitter, getRetryJitter, getVoiceNoteMetadata, getBatteryState, createStealthFingerprint, } from './sessionFingerprint.js';
54
54
  // v3.8 new modules
55
55
  export { getStealthSocketConfig, rampPresenceAfterConnect, STEALTH_BROWSER_POOL, AbortError, } from './stealthConnect.js';
56
+ // Observability
57
+ export { createConsoleLogger, exportPrometheusMetrics, createMetricsHandler, createPeriodicExporter, } from './observability.js';
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Observability — Prometheus metrics export + pluggable structured logging
3
+ *
4
+ * Usage:
5
+ * // Logging
6
+ * import { createConsoleLogger } from 'baileys-antiban';
7
+ * const logger = createConsoleLogger('[my-bot]');
8
+ * logger.info('Message sent', { recipient: jid });
9
+ *
10
+ * // Metrics export for Express
11
+ * import { createMetricsHandler } from 'baileys-antiban';
12
+ * const metricsHandler = createMetricsHandler(() => antiban.getStats());
13
+ * app.get('/metrics', metricsHandler.handle);
14
+ *
15
+ * // Periodic push to external system
16
+ * import { createPeriodicExporter } from 'baileys-antiban';
17
+ * const exporter = createPeriodicExporter(() => antiban.getStats(), {
18
+ * intervalMs: 30_000,
19
+ * onMetrics: (text) => pushToVictoriaMetrics(text),
20
+ * });
21
+ */
22
+ import type { AntiBanStats } from './antiban.js';
23
+ /**
24
+ * Pluggable logger interface compatible with winston, pino, console
25
+ */
26
+ export interface AntiBanLogger {
27
+ debug(msg: string, meta?: Record<string, unknown>): void;
28
+ info(msg: string, meta?: Record<string, unknown>): void;
29
+ warn(msg: string, meta?: Record<string, unknown>): void;
30
+ error(msg: string, meta?: Record<string, unknown>): void;
31
+ }
32
+ /**
33
+ * Create a simple console logger with timestamps and prefix
34
+ */
35
+ export declare function createConsoleLogger(prefix?: string): AntiBanLogger;
36
+ /**
37
+ * Export AntiBan stats as Prometheus text format (exposition format v0.0.4)
38
+ */
39
+ export declare function exportPrometheusMetrics(stats: AntiBanStats, labels?: Record<string, string>): string;
40
+ /**
41
+ * Create an HTTP handler for Prometheus metrics (Express/Fastify compatible)
42
+ */
43
+ export declare function createMetricsHandler(getStats: () => AntiBanStats, labels?: Record<string, string>): {
44
+ /**
45
+ * HTTP request handler (Express/Fastify compatible)
46
+ */
47
+ handle: (_req: unknown, res: {
48
+ setHeader: (name: string, value: string) => void;
49
+ end: (data: string) => void;
50
+ }) => void;
51
+ /**
52
+ * Get metrics as plain text (for non-HTTP usage)
53
+ */
54
+ text: () => string;
55
+ };
56
+ /**
57
+ * Configuration for periodic metrics export
58
+ */
59
+ export interface PeriodicExporterConfig {
60
+ /**
61
+ * Export interval in milliseconds (default: 30000)
62
+ */
63
+ intervalMs?: number;
64
+ /**
65
+ * Callback invoked with Prometheus text on each interval
66
+ */
67
+ onMetrics: (text: string) => void;
68
+ /**
69
+ * Additional labels to attach to all metrics
70
+ */
71
+ labels?: Record<string, string>;
72
+ }
73
+ /**
74
+ * Handle for controlling periodic export
75
+ */
76
+ export interface PeriodicExporterHandle {
77
+ /**
78
+ * Stop the periodic exporter
79
+ */
80
+ stop(): void;
81
+ }
82
+ /**
83
+ * Create a periodic metrics exporter that calls onMetrics on an interval
84
+ */
85
+ export declare function createPeriodicExporter(getStats: () => AntiBanStats, config: PeriodicExporterConfig): PeriodicExporterHandle;
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Observability — Prometheus metrics export + pluggable structured logging
3
+ *
4
+ * Usage:
5
+ * // Logging
6
+ * import { createConsoleLogger } from 'baileys-antiban';
7
+ * const logger = createConsoleLogger('[my-bot]');
8
+ * logger.info('Message sent', { recipient: jid });
9
+ *
10
+ * // Metrics export for Express
11
+ * import { createMetricsHandler } from 'baileys-antiban';
12
+ * const metricsHandler = createMetricsHandler(() => antiban.getStats());
13
+ * app.get('/metrics', metricsHandler.handle);
14
+ *
15
+ * // Periodic push to external system
16
+ * import { createPeriodicExporter } from 'baileys-antiban';
17
+ * const exporter = createPeriodicExporter(() => antiban.getStats(), {
18
+ * intervalMs: 30_000,
19
+ * onMetrics: (text) => pushToVictoriaMetrics(text),
20
+ * });
21
+ */
22
+ /**
23
+ * Create a simple console logger with timestamps and prefix
24
+ */
25
+ export function createConsoleLogger(prefix = '[baileys-antiban]') {
26
+ const format = (level, msg, meta) => {
27
+ const timestamp = new Date().toISOString();
28
+ const metaStr = meta ? ' ' + JSON.stringify(meta) : '';
29
+ return `${timestamp} ${level} ${prefix} ${msg}${metaStr}`;
30
+ };
31
+ return {
32
+ debug: (msg, meta) => console.log(format('DEBUG', msg, meta)),
33
+ info: (msg, meta) => console.log(format('INFO', msg, meta)),
34
+ warn: (msg, meta) => console.warn(format('WARN', msg, meta)),
35
+ error: (msg, meta) => console.error(format('ERROR', msg, meta)),
36
+ };
37
+ }
38
+ /**
39
+ * Export AntiBan stats as Prometheus text format (exposition format v0.0.4)
40
+ */
41
+ export function exportPrometheusMetrics(stats, labels) {
42
+ const labelMap = { instance: 'default', ...labels };
43
+ const labelStr = Object.entries(labelMap)
44
+ .map(([k, v]) => `${k}="${v}"`)
45
+ .join(',');
46
+ const lines = [];
47
+ const addMetric = (name, type, help, value) => {
48
+ lines.push(`# HELP ${name} ${help}`);
49
+ lines.push(`# TYPE ${name} ${type}`);
50
+ lines.push(`${name}{${labelStr}} ${value}`);
51
+ };
52
+ // Counters
53
+ addMetric('antiban_messages_allowed_total', 'counter', 'Total messages allowed by AntiBan', stats.messagesAllowed);
54
+ addMetric('antiban_messages_blocked_total', 'counter', 'Total messages blocked by AntiBan', stats.messagesBlocked);
55
+ addMetric('antiban_total_delay_ms_total', 'counter', 'Total delay imposed (milliseconds)', stats.totalDelayMs);
56
+ // Health gauges
57
+ const riskMap = { low: 0, medium: 1, high: 2, critical: 3 };
58
+ addMetric('antiban_health_score', 'gauge', 'Current health score (0=best, 100=worst)', stats.health.score);
59
+ addMetric('antiban_health_risk', 'gauge', 'Risk level encoded as number (0=low, 1=medium, 2=high, 3=critical)', riskMap[stats.health.risk] ?? 0);
60
+ addMetric('antiban_disconnects_last_hour', 'gauge', 'Disconnects in last hour', stats.health.stats.disconnectsLastHour);
61
+ addMetric('antiban_failed_messages_last_hour', 'gauge', 'Failed messages in last hour', stats.health.stats.failedMessagesLastHour);
62
+ addMetric('antiban_uptime_ms', 'gauge', 'Session uptime in milliseconds', stats.health.stats.uptimeMs);
63
+ // Warm-up gauges
64
+ addMetric('antiban_warmup_progress', 'gauge', 'Warm-up progress (0.0 to 1.0)', stats.warmUp.progress);
65
+ addMetric('antiban_warmup_day', 'gauge', 'Current warm-up day', stats.warmUp.day);
66
+ addMetric('antiban_warmup_today_sent', 'gauge', 'Messages sent today during warm-up', stats.warmUp.todaySent);
67
+ addMetric('antiban_warmup_today_limit', 'gauge', 'Message limit for today during warm-up', stats.warmUp.todayLimit);
68
+ // Rate limiter gauges
69
+ addMetric('antiban_rate_last_minute', 'gauge', 'Messages sent in last minute', stats.rateLimiter.lastMinute);
70
+ addMetric('antiban_rate_last_hour', 'gauge', 'Messages sent in last hour', stats.rateLimiter.lastHour);
71
+ addMetric('antiban_rate_last_day', 'gauge', 'Messages sent in last day', stats.rateLimiter.lastDay);
72
+ addMetric('antiban_rate_limit_per_minute', 'gauge', 'Rate limit per minute', stats.rateLimiter.limits.perMinute);
73
+ addMetric('antiban_rate_limit_per_hour', 'gauge', 'Rate limit per hour', stats.rateLimiter.limits.perHour);
74
+ addMetric('antiban_rate_limit_per_day', 'gauge', 'Rate limit per day', stats.rateLimiter.limits.perDay);
75
+ addMetric('antiban_known_chats', 'gauge', 'Number of known chats', stats.rateLimiter.knownChats);
76
+ // Reply ratio gauges (optional)
77
+ if (stats.replyRatio) {
78
+ addMetric('antiban_contacts_on_cooldown', 'gauge', 'Contacts currently on reply cooldown', stats.replyRatio.contactsOnCooldown);
79
+ }
80
+ else {
81
+ addMetric('antiban_contacts_on_cooldown', 'gauge', 'Contacts currently on reply cooldown', 0);
82
+ }
83
+ // Contact graph gauges (optional)
84
+ if (stats.contactGraph) {
85
+ addMetric('antiban_known_contacts', 'gauge', 'Number of known contacts', stats.contactGraph.knownContacts);
86
+ addMetric('antiban_pending_handshakes', 'gauge', 'Pending handshakes', stats.contactGraph.pendingHandshakes);
87
+ }
88
+ else {
89
+ addMetric('antiban_known_contacts', 'gauge', 'Number of known contacts', 0);
90
+ addMetric('antiban_pending_handshakes', 'gauge', 'Pending handshakes', 0);
91
+ }
92
+ // Retry tracker gauges (optional)
93
+ if (stats.retryTracker) {
94
+ addMetric('antiban_retry_spirals', 'gauge', 'Number of retry spirals detected', stats.retryTracker.spiralsDetected);
95
+ addMetric('antiban_active_retries', 'gauge', 'Currently active retries', stats.retryTracker.activeRetries);
96
+ }
97
+ else {
98
+ addMetric('antiban_retry_spirals', 'gauge', 'Number of retry spirals detected', 0);
99
+ addMetric('antiban_active_retries', 'gauge', 'Currently active retries', 0);
100
+ }
101
+ // Reconnect throttle gauges (optional)
102
+ if (stats.reconnectThrottle) {
103
+ addMetric('antiban_reconnect_throttled', 'gauge', 'Whether reconnect is currently throttled (0=no, 1=yes)', stats.reconnectThrottle.isThrottled ? 1 : 0);
104
+ addMetric('antiban_lifetime_reconnects', 'gauge', 'Total reconnects in session lifetime', stats.reconnectThrottle.lifetimeReconnects);
105
+ }
106
+ else {
107
+ addMetric('antiban_reconnect_throttled', 'gauge', 'Whether reconnect is currently throttled (0=no, 1=yes)', 0);
108
+ addMetric('antiban_lifetime_reconnects', 'gauge', 'Total reconnects in session lifetime', 0);
109
+ }
110
+ return lines.join('\n') + '\n';
111
+ }
112
+ /**
113
+ * Create an HTTP handler for Prometheus metrics (Express/Fastify compatible)
114
+ */
115
+ export function createMetricsHandler(getStats, labels) {
116
+ return {
117
+ /**
118
+ * HTTP request handler (Express/Fastify compatible)
119
+ */
120
+ handle: (_req, res) => {
121
+ const metrics = exportPrometheusMetrics(getStats(), labels);
122
+ res.setHeader('Content-Type', 'text/plain; version=0.0.4; charset=utf-8');
123
+ res.end(metrics);
124
+ },
125
+ /**
126
+ * Get metrics as plain text (for non-HTTP usage)
127
+ */
128
+ text: () => {
129
+ return exportPrometheusMetrics(getStats(), labels);
130
+ },
131
+ };
132
+ }
133
+ /**
134
+ * Create a periodic metrics exporter that calls onMetrics on an interval
135
+ */
136
+ export function createPeriodicExporter(getStats, config) {
137
+ const intervalMs = config.intervalMs ?? 30_000;
138
+ const intervalId = setInterval(() => {
139
+ const metrics = exportPrometheusMetrics(getStats(), config.labels);
140
+ config.onMetrics(metrics);
141
+ }, intervalMs);
142
+ return {
143
+ stop: () => clearInterval(intervalId),
144
+ };
145
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "baileys-antiban",
3
- "version": "3.8.4",
3
+ "version": "3.8.5",
4
4
  "description": "Anti-ban middleware for Baileys WhatsApp bots. Rate limiting, warmup, health monitor, LID resolver, disconnect classifier. Free Whapi.Cloud alternative.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",