zaileys 4.0.5 → 4.1.0

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/dist/index.d.cts CHANGED
@@ -319,6 +319,27 @@ declare class ZaileysDomainError extends Error {
319
319
  });
320
320
  }
321
321
 
322
+ type OperationGuardClock = {
323
+ now?: () => number;
324
+ sleep?: (ms: number) => Promise<void>;
325
+ };
326
+ /**
327
+ * Per-category minimum-interval throttle for sensitive account operations
328
+ * (group/community/newsletter create, join, member changes). Spacing these out
329
+ * avoids the rapid-fire pattern WhatsApp flags as automated/bulk abuse.
330
+ */
331
+ type OperationCategory = 'group.create' | 'group.join' | 'group.participants' | 'group.update' | 'community.create' | 'community.join' | 'community.update' | 'newsletter.create' | 'newsletter.follow' | 'newsletter.update';
332
+ interface OperationGuardOptions {
333
+ /** Master switch. When `false` operations run with no spacing. Default `true`. */
334
+ enabled?: boolean;
335
+ /** Per-category minimum interval in ms, overriding the built-in defaults. */
336
+ intervalsMs?: Partial<Record<OperationCategory, number>>;
337
+ }
338
+ interface OperationGuard {
339
+ run<T>(category: OperationCategory, op: () => Promise<T>): Promise<T>;
340
+ }
341
+ declare function createOperationGuard(options?: OperationGuardOptions, clock?: OperationGuardClock): OperationGuard;
342
+
322
343
  interface DomainSocketLike {
323
344
  groupCreate(subject: string, participants: string[]): Promise<GroupMetadata>;
324
345
  groupParticipantsUpdate(jid: string, participants: string[], action: ParticipantAction): Promise<{
@@ -377,9 +398,11 @@ interface DomainSocketLike {
377
398
 
378
399
  declare class GroupModule {
379
400
  private readonly getSocket;
380
- constructor(getSocket: () => DomainSocketLike | undefined);
401
+ private readonly guard?;
402
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
381
403
  protected requireSocket(): DomainSocketLike;
382
404
  private mapParticipants;
405
+ private run;
383
406
  create(subject: string, participants: string[]): Promise<GroupMetadata>;
384
407
  addMember(groupId: string, jids: string[]): Promise<ParticipantUpdateResult[]>;
385
408
  removeMember(groupId: string, jids: string[]): Promise<ParticipantUpdateResult[]>;
@@ -413,8 +436,10 @@ declare class PrivacyModule {
413
436
 
414
437
  declare class NewsletterModule {
415
438
  private readonly getSocket;
416
- constructor(getSocket: () => DomainSocketLike | undefined);
439
+ private readonly guard?;
440
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
417
441
  protected requireSocket(): DomainSocketLike;
442
+ private run;
418
443
  create(name: string, opts?: {
419
444
  description?: string;
420
445
  picture?: Buffer;
@@ -432,8 +457,10 @@ declare class NewsletterModule {
432
457
 
433
458
  declare class CommunityModule {
434
459
  private readonly getSocket;
435
- constructor(getSocket: () => DomainSocketLike | undefined);
460
+ private readonly guard?;
461
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
436
462
  protected requireSocket(): DomainSocketLike;
463
+ private run;
437
464
  create(subject: string, body: string): Promise<GroupMetadata>;
438
465
  createGroup(subject: string, participants: string[], communityId: string): Promise<GroupMetadata>;
439
466
  linkGroup(communityId: string, groupId: string): Promise<void>;
@@ -798,9 +825,76 @@ interface AuthStoreBundle {
798
825
  readonly signal: AuthStore;
799
826
  }
800
827
 
801
- type DisconnectReasonDomain = 'logged-out' | 'connection-replaced' | 'forbidden' | 'restart-required' | 'bad-session' | 'connection-closed' | 'connection-lost' | 'multi-device-mismatch' | 'unavailable-service' | 'unknown';
828
+ type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
829
+ interface AutomationSocketLike {
830
+ sendPresenceUpdate(type: WAPresence, toJid?: string): Promise<void>;
831
+ }
832
+ /** Drops presence updates that repeat the same (type, chat) inside `minIntervalMs`. */
833
+ interface PresenceThrottleOptions {
834
+ enabled?: boolean;
835
+ minIntervalMs?: number;
836
+ }
837
+ type PresenceClock = {
838
+ now?: () => number;
839
+ };
840
+ declare class PresenceModule {
841
+ private readonly getSocket;
842
+ private readonly throttleEnabled;
843
+ private readonly minIntervalMs;
844
+ private readonly now;
845
+ private readonly lastSent;
846
+ constructor(getSocket: () => AutomationSocketLike | undefined, throttle?: PresenceThrottleOptions, clock?: PresenceClock);
847
+ protected requireSocket(): AutomationSocketLike;
848
+ private throttled;
849
+ private update;
850
+ private scheduleClear;
851
+ online(): Promise<void>;
852
+ offline(): Promise<void>;
853
+ typing(jid: string, ms?: number): Promise<void>;
854
+ recording(jid: string, ms?: number): Promise<void>;
855
+ }
856
+
857
+ /**
858
+ * Bounds QR and pairing-code regeneration across a client's lifetime to avoid
859
+ * tripping WhatsApp's spam/automation restriction. Each reconnect creates a fresh
860
+ * socket which re-emits a QR or requests a new pairing code; without a budget and
861
+ * cooldown this loops unbounded and gets the account restricted.
862
+ */
863
+ interface AuthGuardOptions {
864
+ /** Master switch. When `false` the guard never blocks (legacy behaviour). Default `true`. */
865
+ enabled?: boolean;
866
+ /** Total QR codes emitted before the guard stops and signals exhaustion. Default `5`. */
867
+ maxQrAttempts?: number;
868
+ /** Total pairing-code requests before the guard stops and signals exhaustion. Default `3`. */
869
+ maxPairingAttempts?: number;
870
+ /** Base cooldown between pairing-code requests; escalates per attempt. Default `60000`. */
871
+ pairingCooldownMs?: number;
872
+ }
873
+ type AuthAttemptBlockReason = 'budget-exhausted' | 'cooldown';
874
+ interface AuthAttemptDecision {
875
+ allowed: boolean;
876
+ reason?: AuthAttemptBlockReason;
877
+ waitMs: number;
878
+ attempts: number;
879
+ max: number;
880
+ }
881
+ interface AuthGuard {
882
+ /** Decide whether a new auth attempt of `kind` is permitted at time `now` (does not mutate). */
883
+ evaluate(kind: ConnectionAuthType, now: number): AuthAttemptDecision;
884
+ /** Record that an attempt of `kind` was actually issued at time `now`. */
885
+ record(kind: ConnectionAuthType, now: number): void;
886
+ /** Clear all counters and cooldowns (call on a successful connection or manual restart). */
887
+ reset(): void;
888
+ readonly enabled: boolean;
889
+ readonly qrAttempts: number;
890
+ readonly pairingAttempts: number;
891
+ }
892
+ declare function createAuthGuard(options?: AuthGuardOptions): AuthGuard;
893
+
894
+ type DisconnectReasonDomain = 'logged-out' | 'connection-replaced' | 'forbidden' | 'restart-required' | 'bad-session' | 'connection-closed' | 'connection-lost' | 'multi-device-mismatch' | 'unavailable-service' | 'rate-limited' | 'unknown';
802
895
  declare function mapDisconnectReason(code: number | undefined): DisconnectReasonDomain;
803
896
  declare function isFatalDisconnect(reason: DisconnectReasonDomain): boolean;
897
+ declare function isRateLimited(reason: DisconnectReasonDomain): boolean;
804
898
  declare function shouldClearAuth(reason: DisconnectReasonDomain): boolean;
805
899
  declare function shouldReconnect(reason: DisconnectReasonDomain): boolean;
806
900
 
@@ -819,6 +913,8 @@ interface ReconnectOptions {
819
913
  initialDelayMs?: number;
820
914
  maxDelayMs?: number;
821
915
  jitterFactor?: number;
916
+ /** Fixed backoff applied when the disconnect reason is `rate-limited` (429). Default `300000`. */
917
+ rateLimitedDelayMs?: number;
822
918
  }
823
919
  interface ClientOptions {
824
920
  sessionId?: string;
@@ -836,6 +932,14 @@ interface ClientOptions {
836
932
  commandPrefix?: string | string[];
837
933
  citation?: CitationConfig;
838
934
  ignoreMe?: boolean;
935
+ /** Bounds QR/pairing regeneration to avoid spam restriction. ON by default; `{ enabled: false }` to opt out. */
936
+ authGuard?: AuthGuardOptions;
937
+ /** Spaces out sensitive group/community/newsletter operations. ON by default; `{ enabled: false }` to opt out. */
938
+ operationGuard?: OperationGuardOptions;
939
+ /** Drops duplicate presence (typing/recording/online) updates within a window. ON by default. */
940
+ presence?: PresenceThrottleOptions;
941
+ /** Max scheduled messages dispatched per second, smoothing backlog bursts. Default `1`; `0` disables. */
942
+ scheduleRateLimitPerSec?: number;
839
943
  }
840
944
  type ConnectionEventMap = {
841
945
  connect: {
@@ -867,6 +971,12 @@ type ConnectionEventMap = {
867
971
  delayMs: number;
868
972
  reason: DisconnectReasonDomain;
869
973
  };
974
+ 'auth-exhausted': {
975
+ sessionId: string;
976
+ kind: ConnectionAuthType;
977
+ attempts: number;
978
+ max: number;
979
+ };
870
980
  error: {
871
981
  sessionId: string;
872
982
  error: Error;
@@ -983,22 +1093,6 @@ type BroadcastDeps = {
983
1093
  };
984
1094
  declare function runBroadcast(jids: string[], build: (b: MessageBuilder<'init'>) => MessageBuilder<'content-set'>, deps: BroadcastDeps, options?: BroadcastOptions): Promise<BroadcastResult>;
985
1095
 
986
- type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
987
- interface AutomationSocketLike {
988
- sendPresenceUpdate(type: WAPresence, toJid?: string): Promise<void>;
989
- }
990
- declare class PresenceModule {
991
- private readonly getSocket;
992
- constructor(getSocket: () => AutomationSocketLike | undefined);
993
- protected requireSocket(): AutomationSocketLike;
994
- private update;
995
- private scheduleClear;
996
- online(): Promise<void>;
997
- offline(): Promise<void>;
998
- typing(jid: string, ms?: number): Promise<void>;
999
- recording(jid: string, ms?: number): Promise<void>;
1000
- }
1001
-
1002
1096
  type ScheduledContentSnapshot = {
1003
1097
  recipient: string;
1004
1098
  content: AnyMessageContent;
@@ -1014,6 +1108,7 @@ type SchedulerDeps = {
1014
1108
  now?: () => number;
1015
1109
  timer?: SchedulerTimer;
1016
1110
  logger?: Logger;
1111
+ acquire?: () => Promise<void>;
1017
1112
  };
1018
1113
  type ScheduleHandle = {
1019
1114
  id: string;
@@ -1025,6 +1120,7 @@ declare class Scheduler {
1025
1120
  private readonly now;
1026
1121
  private readonly timer;
1027
1122
  private readonly logger;
1123
+ private readonly acquire;
1028
1124
  private readonly memory;
1029
1125
  private readonly timers;
1030
1126
  constructor(deps: SchedulerDeps);
@@ -1072,6 +1168,11 @@ declare class Client extends TypedEventEmitter<ClientEventMap> {
1072
1168
  private readonly baileysExtra;
1073
1169
  private readonly machine;
1074
1170
  private reconnectStrategy;
1171
+ private readonly authGuard;
1172
+ private readonly operationGuard;
1173
+ private readonly presenceThrottle;
1174
+ private readonly scheduleLimiter;
1175
+ private authExhausted;
1075
1176
  private _socket;
1076
1177
  private reconnectTimer;
1077
1178
  private listenerCleanup;
@@ -1137,6 +1238,7 @@ declare class Client extends TypedEventEmitter<ClientEventMap> {
1137
1238
  private wireSocket;
1138
1239
  private handleConnectionUpdate;
1139
1240
  private handleQrUpdate;
1241
+ private handleAuthExhausted;
1140
1242
  private handleOpen;
1141
1243
  private lookupQuoted;
1142
1244
  private handleClose;
@@ -1670,4 +1772,4 @@ declare class Media {
1670
1772
  toBuffer(): Promise<Buffer>;
1671
1773
  }
1672
1774
 
1673
- export { type AddressButton, type AlbumItem, type AudioOptions, AudioProcessor, type AudioType, type AuthCredsStore, type AuthStore, type AuthStoreBundle, type AuthStoreKey, type AuthStoreValue, type AutomationErrorCode, type AutomationSocketLike, type BaileysSocket, type BaileysSocketLike, type BottomSheetOptions, type BroadcastDeps, type BroadcastOptions, type BroadcastResult, BufferConverter, type BuildContextInput, type BuilderContext, type BuilderErrorCode, type BuilderSocketLike, type BuilderState, type ButtonClickPayload, type ButtonDef, type CacheableAuthStoreOptions, type CallBase, type CallButton, type CallPayload, type CancelReminderButton, type ChatType, type CitationConfig, type CitationPredicates, Client, type ClientEventMap, type ClientEventName, type ClientOptions, type CommandContext, type CommandDefinition, type CommandErrorCode, type CommandHandler, type CommandPrefix, CommandRegistry, CommunityModule, type ConnectionAuthType, type ConnectionEventHandler, type ConnectionEventMap, type ConnectionEventName, type ConnectionState, type ConnectionStateMachine, type ContextMedia, ConvexAuthStore, type ConvexAuthStoreOptions, ConvexMessageStore, type ConvexMessageStoreOptions, type CopyButton, type CreateLoggerOptions, type DeleteOptions, type DeletePayload, type DisconnectReasonDomain, type DispatcherDeps, type DispatcherHandle, type DocumentOptions, DocumentProcessor, type DomainErrorCode, type DomainSocketLike, EditBuilder, type EditPayload, FFMPEG_CONSTANTS, type FFmpegConfig, FFmpegProcessor, FileAuthStore, type FileAuthStoreOptions, type FileExtension, FileManager, type GroupJoinPayload, type GroupLeavePayload, GroupModule, type GroupParticipantInfo, type GroupUpdatePayload, type HistorySyncPayload, type ImageOptions, ImageProcessor, type InboundEventMap, type InboundEventName, type InteractiveButton, type LIDMapping, type LIDMappingUpdatePayload, type LimitedPayload, type LimitedTimeOfferOptions, type LinkedGroup, type ListOptions, type ListSection, type ListSelectPayload, type LocationOptions, type LocationRequestButton, type Logger, type LoggerLevel, Media, type MediaDescriptor, type MediaDownloadResult, type MediaInput, type MediaKind, type MediaSource, type MemberTagPayload, MemoryAuthStore, MemoryMessageStore, type MentionAllContext, type MentionContext, MessageBuilder, type MessageContext, type MessageStore, type MessageStoreListOptions, type Middleware, MimeValidator, NewsletterModule, type NewsletterPayload, type PairingFlow, type PairingFlowOptions, type PairingFlowResult, type ParsedArgs, type ParticipantUpdateResult, type PollOptions, type PollVotePayload, PostgresAuthStore, type PostgresAuthStoreOptions, PostgresMessageStore, type PostgresMessageStoreOptions, PresenceModule, type PresencePayload, type PrivacyConfig, PrivacyModule, type PrivacySettings, type QuotedRef, RateLimiter, type RateLimiterClock, type RateLimiterOptions, type ReactionPayload, type ReconnectDecision, type ReconnectOptions, type ReconnectStrategy, type ReconnectStrategyDeps, RedisAuthStore, type RedisAuthStoreOptions, RedisMessageStore, type RedisMessageStoreOptions, type ReminderButton, type ReplyButton, type ResolvedCommand, type RetryPolicy, SELF_ONLY_PROTOCOL_TYPES, type ScheduleHandle, type ScheduledContentSnapshot, type ScheduledJob, type ScheduledJobRecord, Scheduler, type SchedulerDeps, type SchedulerTimer, type SelfOnlyProtocolType, type SenderDevice, type SenderInfo, SqliteAuthStore, type SqliteAuthStoreOptions, SqliteMessageStore, type SqliteMessageStoreOptions, type StateTransitionListener, type StickerMetadataType, type StickerOptions, StickerProcessor, type StickerShapeType, type StoreErrorCode, TaskQueue, type TaskQueueClock, type TaskQueueOptions, type TemplateOptions, type TextOptions, TypedEventEmitter, type TypedEventEmitterOptions, type UpsertPayload, type UrlButton, type UsernameResolveSocketLike, type VideoOptions, VideoProcessor, type WAPresence, ZaileysAutomationError, ZaileysBuilderError, ZaileysCommandError, ZaileysDomainError, type ZaileysLogger, ZaileysStoreError, adoptLogger, attachCommandDispatcher, buildMessageContext, chunk, createConnectionStateMachine, createLogger, createPairingFlow, createReconnectStrategy, deleteMessage, detectFileType, dropSpoofedSelfOnly, ffmpegTransform, forwardMessage, generateId, initializeFFmpeg, isFatalDisconnect, isJid, makeCacheableAuthStore, mapDisconnectReason, normalizePhoneNumber, parseCommand, printQrToTerminal, reactToMessage, renderQrInTerminal, resolveUsername, runBroadcast, runMiddleware, shouldClearAuth, shouldReconnect, signalKeyStoreFromAuthStore, validateE164 };
1775
+ export { type AddressButton, type AlbumItem, type AudioOptions, AudioProcessor, type AudioType, type AuthAttemptBlockReason, type AuthAttemptDecision, type AuthCredsStore, type AuthGuard, type AuthGuardOptions, type AuthStore, type AuthStoreBundle, type AuthStoreKey, type AuthStoreValue, type AutomationErrorCode, type AutomationSocketLike, type BaileysSocket, type BaileysSocketLike, type BottomSheetOptions, type BroadcastDeps, type BroadcastOptions, type BroadcastResult, BufferConverter, type BuildContextInput, type BuilderContext, type BuilderErrorCode, type BuilderSocketLike, type BuilderState, type ButtonClickPayload, type ButtonDef, type CacheableAuthStoreOptions, type CallBase, type CallButton, type CallPayload, type CancelReminderButton, type ChatType, type CitationConfig, type CitationPredicates, Client, type ClientEventMap, type ClientEventName, type ClientOptions, type CommandContext, type CommandDefinition, type CommandErrorCode, type CommandHandler, type CommandPrefix, CommandRegistry, CommunityModule, type ConnectionAuthType, type ConnectionEventHandler, type ConnectionEventMap, type ConnectionEventName, type ConnectionState, type ConnectionStateMachine, type ContextMedia, ConvexAuthStore, type ConvexAuthStoreOptions, ConvexMessageStore, type ConvexMessageStoreOptions, type CopyButton, type CreateLoggerOptions, type DeleteOptions, type DeletePayload, type DisconnectReasonDomain, type DispatcherDeps, type DispatcherHandle, type DocumentOptions, DocumentProcessor, type DomainErrorCode, type DomainSocketLike, EditBuilder, type EditPayload, FFMPEG_CONSTANTS, type FFmpegConfig, FFmpegProcessor, FileAuthStore, type FileAuthStoreOptions, type FileExtension, FileManager, type GroupJoinPayload, type GroupLeavePayload, GroupModule, type GroupParticipantInfo, type GroupUpdatePayload, type HistorySyncPayload, type ImageOptions, ImageProcessor, type InboundEventMap, type InboundEventName, type InteractiveButton, type LIDMapping, type LIDMappingUpdatePayload, type LimitedPayload, type LimitedTimeOfferOptions, type LinkedGroup, type ListOptions, type ListSection, type ListSelectPayload, type LocationOptions, type LocationRequestButton, type Logger, type LoggerLevel, Media, type MediaDescriptor, type MediaDownloadResult, type MediaInput, type MediaKind, type MediaSource, type MemberTagPayload, MemoryAuthStore, MemoryMessageStore, type MentionAllContext, type MentionContext, MessageBuilder, type MessageContext, type MessageStore, type MessageStoreListOptions, type Middleware, MimeValidator, NewsletterModule, type NewsletterPayload, type OperationCategory, type OperationGuard, type OperationGuardClock, type OperationGuardOptions, type PairingFlow, type PairingFlowOptions, type PairingFlowResult, type ParsedArgs, type ParticipantUpdateResult, type PollOptions, type PollVotePayload, PostgresAuthStore, type PostgresAuthStoreOptions, PostgresMessageStore, type PostgresMessageStoreOptions, type PresenceClock, PresenceModule, type PresencePayload, type PresenceThrottleOptions, type PrivacyConfig, PrivacyModule, type PrivacySettings, type QuotedRef, RateLimiter, type RateLimiterClock, type RateLimiterOptions, type ReactionPayload, type ReconnectDecision, type ReconnectOptions, type ReconnectStrategy, type ReconnectStrategyDeps, RedisAuthStore, type RedisAuthStoreOptions, RedisMessageStore, type RedisMessageStoreOptions, type ReminderButton, type ReplyButton, type ResolvedCommand, type RetryPolicy, SELF_ONLY_PROTOCOL_TYPES, type ScheduleHandle, type ScheduledContentSnapshot, type ScheduledJob, type ScheduledJobRecord, Scheduler, type SchedulerDeps, type SchedulerTimer, type SelfOnlyProtocolType, type SenderDevice, type SenderInfo, SqliteAuthStore, type SqliteAuthStoreOptions, SqliteMessageStore, type SqliteMessageStoreOptions, type StateTransitionListener, type StickerMetadataType, type StickerOptions, StickerProcessor, type StickerShapeType, type StoreErrorCode, TaskQueue, type TaskQueueClock, type TaskQueueOptions, type TemplateOptions, type TextOptions, TypedEventEmitter, type TypedEventEmitterOptions, type UpsertPayload, type UrlButton, type UsernameResolveSocketLike, type VideoOptions, VideoProcessor, type WAPresence, ZaileysAutomationError, ZaileysBuilderError, ZaileysCommandError, ZaileysDomainError, type ZaileysLogger, ZaileysStoreError, adoptLogger, attachCommandDispatcher, buildMessageContext, chunk, createAuthGuard, createConnectionStateMachine, createLogger, createOperationGuard, createPairingFlow, createReconnectStrategy, deleteMessage, detectFileType, dropSpoofedSelfOnly, ffmpegTransform, forwardMessage, generateId, initializeFFmpeg, isFatalDisconnect, isJid, isRateLimited, makeCacheableAuthStore, mapDisconnectReason, normalizePhoneNumber, parseCommand, printQrToTerminal, reactToMessage, renderQrInTerminal, resolveUsername, runBroadcast, runMiddleware, shouldClearAuth, shouldReconnect, signalKeyStoreFromAuthStore, validateE164 };
package/dist/index.d.ts CHANGED
@@ -319,6 +319,27 @@ declare class ZaileysDomainError extends Error {
319
319
  });
320
320
  }
321
321
 
322
+ type OperationGuardClock = {
323
+ now?: () => number;
324
+ sleep?: (ms: number) => Promise<void>;
325
+ };
326
+ /**
327
+ * Per-category minimum-interval throttle for sensitive account operations
328
+ * (group/community/newsletter create, join, member changes). Spacing these out
329
+ * avoids the rapid-fire pattern WhatsApp flags as automated/bulk abuse.
330
+ */
331
+ type OperationCategory = 'group.create' | 'group.join' | 'group.participants' | 'group.update' | 'community.create' | 'community.join' | 'community.update' | 'newsletter.create' | 'newsletter.follow' | 'newsletter.update';
332
+ interface OperationGuardOptions {
333
+ /** Master switch. When `false` operations run with no spacing. Default `true`. */
334
+ enabled?: boolean;
335
+ /** Per-category minimum interval in ms, overriding the built-in defaults. */
336
+ intervalsMs?: Partial<Record<OperationCategory, number>>;
337
+ }
338
+ interface OperationGuard {
339
+ run<T>(category: OperationCategory, op: () => Promise<T>): Promise<T>;
340
+ }
341
+ declare function createOperationGuard(options?: OperationGuardOptions, clock?: OperationGuardClock): OperationGuard;
342
+
322
343
  interface DomainSocketLike {
323
344
  groupCreate(subject: string, participants: string[]): Promise<GroupMetadata>;
324
345
  groupParticipantsUpdate(jid: string, participants: string[], action: ParticipantAction): Promise<{
@@ -377,9 +398,11 @@ interface DomainSocketLike {
377
398
 
378
399
  declare class GroupModule {
379
400
  private readonly getSocket;
380
- constructor(getSocket: () => DomainSocketLike | undefined);
401
+ private readonly guard?;
402
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
381
403
  protected requireSocket(): DomainSocketLike;
382
404
  private mapParticipants;
405
+ private run;
383
406
  create(subject: string, participants: string[]): Promise<GroupMetadata>;
384
407
  addMember(groupId: string, jids: string[]): Promise<ParticipantUpdateResult[]>;
385
408
  removeMember(groupId: string, jids: string[]): Promise<ParticipantUpdateResult[]>;
@@ -413,8 +436,10 @@ declare class PrivacyModule {
413
436
 
414
437
  declare class NewsletterModule {
415
438
  private readonly getSocket;
416
- constructor(getSocket: () => DomainSocketLike | undefined);
439
+ private readonly guard?;
440
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
417
441
  protected requireSocket(): DomainSocketLike;
442
+ private run;
418
443
  create(name: string, opts?: {
419
444
  description?: string;
420
445
  picture?: Buffer;
@@ -432,8 +457,10 @@ declare class NewsletterModule {
432
457
 
433
458
  declare class CommunityModule {
434
459
  private readonly getSocket;
435
- constructor(getSocket: () => DomainSocketLike | undefined);
460
+ private readonly guard?;
461
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
436
462
  protected requireSocket(): DomainSocketLike;
463
+ private run;
437
464
  create(subject: string, body: string): Promise<GroupMetadata>;
438
465
  createGroup(subject: string, participants: string[], communityId: string): Promise<GroupMetadata>;
439
466
  linkGroup(communityId: string, groupId: string): Promise<void>;
@@ -798,9 +825,76 @@ interface AuthStoreBundle {
798
825
  readonly signal: AuthStore;
799
826
  }
800
827
 
801
- type DisconnectReasonDomain = 'logged-out' | 'connection-replaced' | 'forbidden' | 'restart-required' | 'bad-session' | 'connection-closed' | 'connection-lost' | 'multi-device-mismatch' | 'unavailable-service' | 'unknown';
828
+ type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
829
+ interface AutomationSocketLike {
830
+ sendPresenceUpdate(type: WAPresence, toJid?: string): Promise<void>;
831
+ }
832
+ /** Drops presence updates that repeat the same (type, chat) inside `minIntervalMs`. */
833
+ interface PresenceThrottleOptions {
834
+ enabled?: boolean;
835
+ minIntervalMs?: number;
836
+ }
837
+ type PresenceClock = {
838
+ now?: () => number;
839
+ };
840
+ declare class PresenceModule {
841
+ private readonly getSocket;
842
+ private readonly throttleEnabled;
843
+ private readonly minIntervalMs;
844
+ private readonly now;
845
+ private readonly lastSent;
846
+ constructor(getSocket: () => AutomationSocketLike | undefined, throttle?: PresenceThrottleOptions, clock?: PresenceClock);
847
+ protected requireSocket(): AutomationSocketLike;
848
+ private throttled;
849
+ private update;
850
+ private scheduleClear;
851
+ online(): Promise<void>;
852
+ offline(): Promise<void>;
853
+ typing(jid: string, ms?: number): Promise<void>;
854
+ recording(jid: string, ms?: number): Promise<void>;
855
+ }
856
+
857
+ /**
858
+ * Bounds QR and pairing-code regeneration across a client's lifetime to avoid
859
+ * tripping WhatsApp's spam/automation restriction. Each reconnect creates a fresh
860
+ * socket which re-emits a QR or requests a new pairing code; without a budget and
861
+ * cooldown this loops unbounded and gets the account restricted.
862
+ */
863
+ interface AuthGuardOptions {
864
+ /** Master switch. When `false` the guard never blocks (legacy behaviour). Default `true`. */
865
+ enabled?: boolean;
866
+ /** Total QR codes emitted before the guard stops and signals exhaustion. Default `5`. */
867
+ maxQrAttempts?: number;
868
+ /** Total pairing-code requests before the guard stops and signals exhaustion. Default `3`. */
869
+ maxPairingAttempts?: number;
870
+ /** Base cooldown between pairing-code requests; escalates per attempt. Default `60000`. */
871
+ pairingCooldownMs?: number;
872
+ }
873
+ type AuthAttemptBlockReason = 'budget-exhausted' | 'cooldown';
874
+ interface AuthAttemptDecision {
875
+ allowed: boolean;
876
+ reason?: AuthAttemptBlockReason;
877
+ waitMs: number;
878
+ attempts: number;
879
+ max: number;
880
+ }
881
+ interface AuthGuard {
882
+ /** Decide whether a new auth attempt of `kind` is permitted at time `now` (does not mutate). */
883
+ evaluate(kind: ConnectionAuthType, now: number): AuthAttemptDecision;
884
+ /** Record that an attempt of `kind` was actually issued at time `now`. */
885
+ record(kind: ConnectionAuthType, now: number): void;
886
+ /** Clear all counters and cooldowns (call on a successful connection or manual restart). */
887
+ reset(): void;
888
+ readonly enabled: boolean;
889
+ readonly qrAttempts: number;
890
+ readonly pairingAttempts: number;
891
+ }
892
+ declare function createAuthGuard(options?: AuthGuardOptions): AuthGuard;
893
+
894
+ type DisconnectReasonDomain = 'logged-out' | 'connection-replaced' | 'forbidden' | 'restart-required' | 'bad-session' | 'connection-closed' | 'connection-lost' | 'multi-device-mismatch' | 'unavailable-service' | 'rate-limited' | 'unknown';
802
895
  declare function mapDisconnectReason(code: number | undefined): DisconnectReasonDomain;
803
896
  declare function isFatalDisconnect(reason: DisconnectReasonDomain): boolean;
897
+ declare function isRateLimited(reason: DisconnectReasonDomain): boolean;
804
898
  declare function shouldClearAuth(reason: DisconnectReasonDomain): boolean;
805
899
  declare function shouldReconnect(reason: DisconnectReasonDomain): boolean;
806
900
 
@@ -819,6 +913,8 @@ interface ReconnectOptions {
819
913
  initialDelayMs?: number;
820
914
  maxDelayMs?: number;
821
915
  jitterFactor?: number;
916
+ /** Fixed backoff applied when the disconnect reason is `rate-limited` (429). Default `300000`. */
917
+ rateLimitedDelayMs?: number;
822
918
  }
823
919
  interface ClientOptions {
824
920
  sessionId?: string;
@@ -836,6 +932,14 @@ interface ClientOptions {
836
932
  commandPrefix?: string | string[];
837
933
  citation?: CitationConfig;
838
934
  ignoreMe?: boolean;
935
+ /** Bounds QR/pairing regeneration to avoid spam restriction. ON by default; `{ enabled: false }` to opt out. */
936
+ authGuard?: AuthGuardOptions;
937
+ /** Spaces out sensitive group/community/newsletter operations. ON by default; `{ enabled: false }` to opt out. */
938
+ operationGuard?: OperationGuardOptions;
939
+ /** Drops duplicate presence (typing/recording/online) updates within a window. ON by default. */
940
+ presence?: PresenceThrottleOptions;
941
+ /** Max scheduled messages dispatched per second, smoothing backlog bursts. Default `1`; `0` disables. */
942
+ scheduleRateLimitPerSec?: number;
839
943
  }
840
944
  type ConnectionEventMap = {
841
945
  connect: {
@@ -867,6 +971,12 @@ type ConnectionEventMap = {
867
971
  delayMs: number;
868
972
  reason: DisconnectReasonDomain;
869
973
  };
974
+ 'auth-exhausted': {
975
+ sessionId: string;
976
+ kind: ConnectionAuthType;
977
+ attempts: number;
978
+ max: number;
979
+ };
870
980
  error: {
871
981
  sessionId: string;
872
982
  error: Error;
@@ -983,22 +1093,6 @@ type BroadcastDeps = {
983
1093
  };
984
1094
  declare function runBroadcast(jids: string[], build: (b: MessageBuilder<'init'>) => MessageBuilder<'content-set'>, deps: BroadcastDeps, options?: BroadcastOptions): Promise<BroadcastResult>;
985
1095
 
986
- type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
987
- interface AutomationSocketLike {
988
- sendPresenceUpdate(type: WAPresence, toJid?: string): Promise<void>;
989
- }
990
- declare class PresenceModule {
991
- private readonly getSocket;
992
- constructor(getSocket: () => AutomationSocketLike | undefined);
993
- protected requireSocket(): AutomationSocketLike;
994
- private update;
995
- private scheduleClear;
996
- online(): Promise<void>;
997
- offline(): Promise<void>;
998
- typing(jid: string, ms?: number): Promise<void>;
999
- recording(jid: string, ms?: number): Promise<void>;
1000
- }
1001
-
1002
1096
  type ScheduledContentSnapshot = {
1003
1097
  recipient: string;
1004
1098
  content: AnyMessageContent;
@@ -1014,6 +1108,7 @@ type SchedulerDeps = {
1014
1108
  now?: () => number;
1015
1109
  timer?: SchedulerTimer;
1016
1110
  logger?: Logger;
1111
+ acquire?: () => Promise<void>;
1017
1112
  };
1018
1113
  type ScheduleHandle = {
1019
1114
  id: string;
@@ -1025,6 +1120,7 @@ declare class Scheduler {
1025
1120
  private readonly now;
1026
1121
  private readonly timer;
1027
1122
  private readonly logger;
1123
+ private readonly acquire;
1028
1124
  private readonly memory;
1029
1125
  private readonly timers;
1030
1126
  constructor(deps: SchedulerDeps);
@@ -1072,6 +1168,11 @@ declare class Client extends TypedEventEmitter<ClientEventMap> {
1072
1168
  private readonly baileysExtra;
1073
1169
  private readonly machine;
1074
1170
  private reconnectStrategy;
1171
+ private readonly authGuard;
1172
+ private readonly operationGuard;
1173
+ private readonly presenceThrottle;
1174
+ private readonly scheduleLimiter;
1175
+ private authExhausted;
1075
1176
  private _socket;
1076
1177
  private reconnectTimer;
1077
1178
  private listenerCleanup;
@@ -1137,6 +1238,7 @@ declare class Client extends TypedEventEmitter<ClientEventMap> {
1137
1238
  private wireSocket;
1138
1239
  private handleConnectionUpdate;
1139
1240
  private handleQrUpdate;
1241
+ private handleAuthExhausted;
1140
1242
  private handleOpen;
1141
1243
  private lookupQuoted;
1142
1244
  private handleClose;
@@ -1670,4 +1772,4 @@ declare class Media {
1670
1772
  toBuffer(): Promise<Buffer>;
1671
1773
  }
1672
1774
 
1673
- export { type AddressButton, type AlbumItem, type AudioOptions, AudioProcessor, type AudioType, type AuthCredsStore, type AuthStore, type AuthStoreBundle, type AuthStoreKey, type AuthStoreValue, type AutomationErrorCode, type AutomationSocketLike, type BaileysSocket, type BaileysSocketLike, type BottomSheetOptions, type BroadcastDeps, type BroadcastOptions, type BroadcastResult, BufferConverter, type BuildContextInput, type BuilderContext, type BuilderErrorCode, type BuilderSocketLike, type BuilderState, type ButtonClickPayload, type ButtonDef, type CacheableAuthStoreOptions, type CallBase, type CallButton, type CallPayload, type CancelReminderButton, type ChatType, type CitationConfig, type CitationPredicates, Client, type ClientEventMap, type ClientEventName, type ClientOptions, type CommandContext, type CommandDefinition, type CommandErrorCode, type CommandHandler, type CommandPrefix, CommandRegistry, CommunityModule, type ConnectionAuthType, type ConnectionEventHandler, type ConnectionEventMap, type ConnectionEventName, type ConnectionState, type ConnectionStateMachine, type ContextMedia, ConvexAuthStore, type ConvexAuthStoreOptions, ConvexMessageStore, type ConvexMessageStoreOptions, type CopyButton, type CreateLoggerOptions, type DeleteOptions, type DeletePayload, type DisconnectReasonDomain, type DispatcherDeps, type DispatcherHandle, type DocumentOptions, DocumentProcessor, type DomainErrorCode, type DomainSocketLike, EditBuilder, type EditPayload, FFMPEG_CONSTANTS, type FFmpegConfig, FFmpegProcessor, FileAuthStore, type FileAuthStoreOptions, type FileExtension, FileManager, type GroupJoinPayload, type GroupLeavePayload, GroupModule, type GroupParticipantInfo, type GroupUpdatePayload, type HistorySyncPayload, type ImageOptions, ImageProcessor, type InboundEventMap, type InboundEventName, type InteractiveButton, type LIDMapping, type LIDMappingUpdatePayload, type LimitedPayload, type LimitedTimeOfferOptions, type LinkedGroup, type ListOptions, type ListSection, type ListSelectPayload, type LocationOptions, type LocationRequestButton, type Logger, type LoggerLevel, Media, type MediaDescriptor, type MediaDownloadResult, type MediaInput, type MediaKind, type MediaSource, type MemberTagPayload, MemoryAuthStore, MemoryMessageStore, type MentionAllContext, type MentionContext, MessageBuilder, type MessageContext, type MessageStore, type MessageStoreListOptions, type Middleware, MimeValidator, NewsletterModule, type NewsletterPayload, type PairingFlow, type PairingFlowOptions, type PairingFlowResult, type ParsedArgs, type ParticipantUpdateResult, type PollOptions, type PollVotePayload, PostgresAuthStore, type PostgresAuthStoreOptions, PostgresMessageStore, type PostgresMessageStoreOptions, PresenceModule, type PresencePayload, type PrivacyConfig, PrivacyModule, type PrivacySettings, type QuotedRef, RateLimiter, type RateLimiterClock, type RateLimiterOptions, type ReactionPayload, type ReconnectDecision, type ReconnectOptions, type ReconnectStrategy, type ReconnectStrategyDeps, RedisAuthStore, type RedisAuthStoreOptions, RedisMessageStore, type RedisMessageStoreOptions, type ReminderButton, type ReplyButton, type ResolvedCommand, type RetryPolicy, SELF_ONLY_PROTOCOL_TYPES, type ScheduleHandle, type ScheduledContentSnapshot, type ScheduledJob, type ScheduledJobRecord, Scheduler, type SchedulerDeps, type SchedulerTimer, type SelfOnlyProtocolType, type SenderDevice, type SenderInfo, SqliteAuthStore, type SqliteAuthStoreOptions, SqliteMessageStore, type SqliteMessageStoreOptions, type StateTransitionListener, type StickerMetadataType, type StickerOptions, StickerProcessor, type StickerShapeType, type StoreErrorCode, TaskQueue, type TaskQueueClock, type TaskQueueOptions, type TemplateOptions, type TextOptions, TypedEventEmitter, type TypedEventEmitterOptions, type UpsertPayload, type UrlButton, type UsernameResolveSocketLike, type VideoOptions, VideoProcessor, type WAPresence, ZaileysAutomationError, ZaileysBuilderError, ZaileysCommandError, ZaileysDomainError, type ZaileysLogger, ZaileysStoreError, adoptLogger, attachCommandDispatcher, buildMessageContext, chunk, createConnectionStateMachine, createLogger, createPairingFlow, createReconnectStrategy, deleteMessage, detectFileType, dropSpoofedSelfOnly, ffmpegTransform, forwardMessage, generateId, initializeFFmpeg, isFatalDisconnect, isJid, makeCacheableAuthStore, mapDisconnectReason, normalizePhoneNumber, parseCommand, printQrToTerminal, reactToMessage, renderQrInTerminal, resolveUsername, runBroadcast, runMiddleware, shouldClearAuth, shouldReconnect, signalKeyStoreFromAuthStore, validateE164 };
1775
+ export { type AddressButton, type AlbumItem, type AudioOptions, AudioProcessor, type AudioType, type AuthAttemptBlockReason, type AuthAttemptDecision, type AuthCredsStore, type AuthGuard, type AuthGuardOptions, type AuthStore, type AuthStoreBundle, type AuthStoreKey, type AuthStoreValue, type AutomationErrorCode, type AutomationSocketLike, type BaileysSocket, type BaileysSocketLike, type BottomSheetOptions, type BroadcastDeps, type BroadcastOptions, type BroadcastResult, BufferConverter, type BuildContextInput, type BuilderContext, type BuilderErrorCode, type BuilderSocketLike, type BuilderState, type ButtonClickPayload, type ButtonDef, type CacheableAuthStoreOptions, type CallBase, type CallButton, type CallPayload, type CancelReminderButton, type ChatType, type CitationConfig, type CitationPredicates, Client, type ClientEventMap, type ClientEventName, type ClientOptions, type CommandContext, type CommandDefinition, type CommandErrorCode, type CommandHandler, type CommandPrefix, CommandRegistry, CommunityModule, type ConnectionAuthType, type ConnectionEventHandler, type ConnectionEventMap, type ConnectionEventName, type ConnectionState, type ConnectionStateMachine, type ContextMedia, ConvexAuthStore, type ConvexAuthStoreOptions, ConvexMessageStore, type ConvexMessageStoreOptions, type CopyButton, type CreateLoggerOptions, type DeleteOptions, type DeletePayload, type DisconnectReasonDomain, type DispatcherDeps, type DispatcherHandle, type DocumentOptions, DocumentProcessor, type DomainErrorCode, type DomainSocketLike, EditBuilder, type EditPayload, FFMPEG_CONSTANTS, type FFmpegConfig, FFmpegProcessor, FileAuthStore, type FileAuthStoreOptions, type FileExtension, FileManager, type GroupJoinPayload, type GroupLeavePayload, GroupModule, type GroupParticipantInfo, type GroupUpdatePayload, type HistorySyncPayload, type ImageOptions, ImageProcessor, type InboundEventMap, type InboundEventName, type InteractiveButton, type LIDMapping, type LIDMappingUpdatePayload, type LimitedPayload, type LimitedTimeOfferOptions, type LinkedGroup, type ListOptions, type ListSection, type ListSelectPayload, type LocationOptions, type LocationRequestButton, type Logger, type LoggerLevel, Media, type MediaDescriptor, type MediaDownloadResult, type MediaInput, type MediaKind, type MediaSource, type MemberTagPayload, MemoryAuthStore, MemoryMessageStore, type MentionAllContext, type MentionContext, MessageBuilder, type MessageContext, type MessageStore, type MessageStoreListOptions, type Middleware, MimeValidator, NewsletterModule, type NewsletterPayload, type OperationCategory, type OperationGuard, type OperationGuardClock, type OperationGuardOptions, type PairingFlow, type PairingFlowOptions, type PairingFlowResult, type ParsedArgs, type ParticipantUpdateResult, type PollOptions, type PollVotePayload, PostgresAuthStore, type PostgresAuthStoreOptions, PostgresMessageStore, type PostgresMessageStoreOptions, type PresenceClock, PresenceModule, type PresencePayload, type PresenceThrottleOptions, type PrivacyConfig, PrivacyModule, type PrivacySettings, type QuotedRef, RateLimiter, type RateLimiterClock, type RateLimiterOptions, type ReactionPayload, type ReconnectDecision, type ReconnectOptions, type ReconnectStrategy, type ReconnectStrategyDeps, RedisAuthStore, type RedisAuthStoreOptions, RedisMessageStore, type RedisMessageStoreOptions, type ReminderButton, type ReplyButton, type ResolvedCommand, type RetryPolicy, SELF_ONLY_PROTOCOL_TYPES, type ScheduleHandle, type ScheduledContentSnapshot, type ScheduledJob, type ScheduledJobRecord, Scheduler, type SchedulerDeps, type SchedulerTimer, type SelfOnlyProtocolType, type SenderDevice, type SenderInfo, SqliteAuthStore, type SqliteAuthStoreOptions, SqliteMessageStore, type SqliteMessageStoreOptions, type StateTransitionListener, type StickerMetadataType, type StickerOptions, StickerProcessor, type StickerShapeType, type StoreErrorCode, TaskQueue, type TaskQueueClock, type TaskQueueOptions, type TemplateOptions, type TextOptions, TypedEventEmitter, type TypedEventEmitterOptions, type UpsertPayload, type UrlButton, type UsernameResolveSocketLike, type VideoOptions, VideoProcessor, type WAPresence, ZaileysAutomationError, ZaileysBuilderError, ZaileysCommandError, ZaileysDomainError, type ZaileysLogger, ZaileysStoreError, adoptLogger, attachCommandDispatcher, buildMessageContext, chunk, createAuthGuard, createConnectionStateMachine, createLogger, createOperationGuard, createPairingFlow, createReconnectStrategy, deleteMessage, detectFileType, dropSpoofedSelfOnly, ffmpegTransform, forwardMessage, generateId, initializeFFmpeg, isFatalDisconnect, isJid, isRateLimited, makeCacheableAuthStore, mapDisconnectReason, normalizePhoneNumber, parseCommand, printQrToTerminal, reactToMessage, renderQrInTerminal, resolveUsername, runBroadcast, runMiddleware, shouldClearAuth, shouldReconnect, signalKeyStoreFromAuthStore, validateE164 };