zaileys 4.0.5 → 4.1.1

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
@@ -180,6 +180,7 @@ interface BuilderSocketLike {
180
180
  messageId: string;
181
181
  additionalNodes?: unknown[];
182
182
  }): Promise<string>;
183
+ chatModify?(mod: unknown, jid: string): Promise<void>;
183
184
  user?: {
184
185
  id?: string | null;
185
186
  } | null;
@@ -319,6 +320,27 @@ declare class ZaileysDomainError extends Error {
319
320
  });
320
321
  }
321
322
 
323
+ type OperationGuardClock = {
324
+ now?: () => number;
325
+ sleep?: (ms: number) => Promise<void>;
326
+ };
327
+ /**
328
+ * Per-category minimum-interval throttle for sensitive account operations
329
+ * (group/community/newsletter create, join, member changes). Spacing these out
330
+ * avoids the rapid-fire pattern WhatsApp flags as automated/bulk abuse.
331
+ */
332
+ type OperationCategory = 'group.create' | 'group.join' | 'group.participants' | 'group.update' | 'community.create' | 'community.join' | 'community.update' | 'newsletter.create' | 'newsletter.follow' | 'newsletter.update';
333
+ interface OperationGuardOptions {
334
+ /** Master switch. When `false` operations run with no spacing. Default `true`. */
335
+ enabled?: boolean;
336
+ /** Per-category minimum interval in ms, overriding the built-in defaults. */
337
+ intervalsMs?: Partial<Record<OperationCategory, number>>;
338
+ }
339
+ interface OperationGuard {
340
+ run<T>(category: OperationCategory, op: () => Promise<T>): Promise<T>;
341
+ }
342
+ declare function createOperationGuard(options?: OperationGuardOptions, clock?: OperationGuardClock): OperationGuard;
343
+
322
344
  interface DomainSocketLike {
323
345
  groupCreate(subject: string, participants: string[]): Promise<GroupMetadata>;
324
346
  groupParticipantsUpdate(jid: string, participants: string[], action: ParticipantAction): Promise<{
@@ -377,9 +399,11 @@ interface DomainSocketLike {
377
399
 
378
400
  declare class GroupModule {
379
401
  private readonly getSocket;
380
- constructor(getSocket: () => DomainSocketLike | undefined);
402
+ private readonly guard?;
403
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
381
404
  protected requireSocket(): DomainSocketLike;
382
405
  private mapParticipants;
406
+ private run;
383
407
  create(subject: string, participants: string[]): Promise<GroupMetadata>;
384
408
  addMember(groupId: string, jids: string[]): Promise<ParticipantUpdateResult[]>;
385
409
  removeMember(groupId: string, jids: string[]): Promise<ParticipantUpdateResult[]>;
@@ -413,8 +437,10 @@ declare class PrivacyModule {
413
437
 
414
438
  declare class NewsletterModule {
415
439
  private readonly getSocket;
416
- constructor(getSocket: () => DomainSocketLike | undefined);
440
+ private readonly guard?;
441
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
417
442
  protected requireSocket(): DomainSocketLike;
443
+ private run;
418
444
  create(name: string, opts?: {
419
445
  description?: string;
420
446
  picture?: Buffer;
@@ -432,8 +458,10 @@ declare class NewsletterModule {
432
458
 
433
459
  declare class CommunityModule {
434
460
  private readonly getSocket;
435
- constructor(getSocket: () => DomainSocketLike | undefined);
461
+ private readonly guard?;
462
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
436
463
  protected requireSocket(): DomainSocketLike;
464
+ private run;
437
465
  create(subject: string, body: string): Promise<GroupMetadata>;
438
466
  createGroup(subject: string, participants: string[], communityId: string): Promise<GroupMetadata>;
439
467
  linkGroup(communityId: string, groupId: string): Promise<void>;
@@ -798,9 +826,76 @@ interface AuthStoreBundle {
798
826
  readonly signal: AuthStore;
799
827
  }
800
828
 
801
- type DisconnectReasonDomain = 'logged-out' | 'connection-replaced' | 'forbidden' | 'restart-required' | 'bad-session' | 'connection-closed' | 'connection-lost' | 'multi-device-mismatch' | 'unavailable-service' | 'unknown';
829
+ type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
830
+ interface AutomationSocketLike {
831
+ sendPresenceUpdate(type: WAPresence, toJid?: string): Promise<void>;
832
+ }
833
+ /** Drops presence updates that repeat the same (type, chat) inside `minIntervalMs`. */
834
+ interface PresenceThrottleOptions {
835
+ enabled?: boolean;
836
+ minIntervalMs?: number;
837
+ }
838
+ type PresenceClock = {
839
+ now?: () => number;
840
+ };
841
+ declare class PresenceModule {
842
+ private readonly getSocket;
843
+ private readonly throttleEnabled;
844
+ private readonly minIntervalMs;
845
+ private readonly now;
846
+ private readonly lastSent;
847
+ constructor(getSocket: () => AutomationSocketLike | undefined, throttle?: PresenceThrottleOptions, clock?: PresenceClock);
848
+ protected requireSocket(): AutomationSocketLike;
849
+ private throttled;
850
+ private update;
851
+ private scheduleClear;
852
+ online(): Promise<void>;
853
+ offline(): Promise<void>;
854
+ typing(jid: string, ms?: number): Promise<void>;
855
+ recording(jid: string, ms?: number): Promise<void>;
856
+ }
857
+
858
+ /**
859
+ * Bounds QR and pairing-code regeneration across a client's lifetime to avoid
860
+ * tripping WhatsApp's spam/automation restriction. Each reconnect creates a fresh
861
+ * socket which re-emits a QR or requests a new pairing code; without a budget and
862
+ * cooldown this loops unbounded and gets the account restricted.
863
+ */
864
+ interface AuthGuardOptions {
865
+ /** Master switch. When `false` the guard never blocks (legacy behaviour). Default `true`. */
866
+ enabled?: boolean;
867
+ /** Total QR codes emitted before the guard stops and signals exhaustion. Default `5`. */
868
+ maxQrAttempts?: number;
869
+ /** Total pairing-code requests before the guard stops and signals exhaustion. Default `3`. */
870
+ maxPairingAttempts?: number;
871
+ /** Base cooldown between pairing-code requests; escalates per attempt. Default `60000`. */
872
+ pairingCooldownMs?: number;
873
+ }
874
+ type AuthAttemptBlockReason = 'budget-exhausted' | 'cooldown';
875
+ interface AuthAttemptDecision {
876
+ allowed: boolean;
877
+ reason?: AuthAttemptBlockReason;
878
+ waitMs: number;
879
+ attempts: number;
880
+ max: number;
881
+ }
882
+ interface AuthGuard {
883
+ /** Decide whether a new auth attempt of `kind` is permitted at time `now` (does not mutate). */
884
+ evaluate(kind: ConnectionAuthType, now: number): AuthAttemptDecision;
885
+ /** Record that an attempt of `kind` was actually issued at time `now`. */
886
+ record(kind: ConnectionAuthType, now: number): void;
887
+ /** Clear all counters and cooldowns (call on a successful connection or manual restart). */
888
+ reset(): void;
889
+ readonly enabled: boolean;
890
+ readonly qrAttempts: number;
891
+ readonly pairingAttempts: number;
892
+ }
893
+ declare function createAuthGuard(options?: AuthGuardOptions): AuthGuard;
894
+
895
+ type DisconnectReasonDomain = 'logged-out' | 'connection-replaced' | 'forbidden' | 'restart-required' | 'bad-session' | 'connection-closed' | 'connection-lost' | 'multi-device-mismatch' | 'unavailable-service' | 'rate-limited' | 'unknown';
802
896
  declare function mapDisconnectReason(code: number | undefined): DisconnectReasonDomain;
803
897
  declare function isFatalDisconnect(reason: DisconnectReasonDomain): boolean;
898
+ declare function isRateLimited(reason: DisconnectReasonDomain): boolean;
804
899
  declare function shouldClearAuth(reason: DisconnectReasonDomain): boolean;
805
900
  declare function shouldReconnect(reason: DisconnectReasonDomain): boolean;
806
901
 
@@ -819,6 +914,8 @@ interface ReconnectOptions {
819
914
  initialDelayMs?: number;
820
915
  maxDelayMs?: number;
821
916
  jitterFactor?: number;
917
+ /** Fixed backoff applied when the disconnect reason is `rate-limited` (429). Default `300000`. */
918
+ rateLimitedDelayMs?: number;
822
919
  }
823
920
  interface ClientOptions {
824
921
  sessionId?: string;
@@ -836,6 +933,14 @@ interface ClientOptions {
836
933
  commandPrefix?: string | string[];
837
934
  citation?: CitationConfig;
838
935
  ignoreMe?: boolean;
936
+ /** Bounds QR/pairing regeneration to avoid spam restriction. ON by default; `{ enabled: false }` to opt out. */
937
+ authGuard?: AuthGuardOptions;
938
+ /** Spaces out sensitive group/community/newsletter operations. ON by default; `{ enabled: false }` to opt out. */
939
+ operationGuard?: OperationGuardOptions;
940
+ /** Drops duplicate presence (typing/recording/online) updates within a window. ON by default. */
941
+ presence?: PresenceThrottleOptions;
942
+ /** Max scheduled messages dispatched per second, smoothing backlog bursts. Default `1`; `0` disables. */
943
+ scheduleRateLimitPerSec?: number;
839
944
  }
840
945
  type ConnectionEventMap = {
841
946
  connect: {
@@ -867,6 +972,12 @@ type ConnectionEventMap = {
867
972
  delayMs: number;
868
973
  reason: DisconnectReasonDomain;
869
974
  };
975
+ 'auth-exhausted': {
976
+ sessionId: string;
977
+ kind: ConnectionAuthType;
978
+ attempts: number;
979
+ max: number;
980
+ };
870
981
  error: {
871
982
  sessionId: string;
872
983
  error: Error;
@@ -983,22 +1094,6 @@ type BroadcastDeps = {
983
1094
  };
984
1095
  declare function runBroadcast(jids: string[], build: (b: MessageBuilder<'init'>) => MessageBuilder<'content-set'>, deps: BroadcastDeps, options?: BroadcastOptions): Promise<BroadcastResult>;
985
1096
 
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
1097
  type ScheduledContentSnapshot = {
1003
1098
  recipient: string;
1004
1099
  content: AnyMessageContent;
@@ -1014,6 +1109,7 @@ type SchedulerDeps = {
1014
1109
  now?: () => number;
1015
1110
  timer?: SchedulerTimer;
1016
1111
  logger?: Logger;
1112
+ acquire?: () => Promise<void>;
1017
1113
  };
1018
1114
  type ScheduleHandle = {
1019
1115
  id: string;
@@ -1025,6 +1121,7 @@ declare class Scheduler {
1025
1121
  private readonly now;
1026
1122
  private readonly timer;
1027
1123
  private readonly logger;
1124
+ private readonly acquire;
1028
1125
  private readonly memory;
1029
1126
  private readonly timers;
1030
1127
  constructor(deps: SchedulerDeps);
@@ -1072,6 +1169,11 @@ declare class Client extends TypedEventEmitter<ClientEventMap> {
1072
1169
  private readonly baileysExtra;
1073
1170
  private readonly machine;
1074
1171
  private reconnectStrategy;
1172
+ private readonly authGuard;
1173
+ private readonly operationGuard;
1174
+ private readonly presenceThrottle;
1175
+ private readonly scheduleLimiter;
1176
+ private authExhausted;
1075
1177
  private _socket;
1076
1178
  private reconnectTimer;
1077
1179
  private listenerCleanup;
@@ -1137,7 +1239,9 @@ declare class Client extends TypedEventEmitter<ClientEventMap> {
1137
1239
  private wireSocket;
1138
1240
  private handleConnectionUpdate;
1139
1241
  private handleQrUpdate;
1242
+ private handleAuthExhausted;
1140
1243
  private handleOpen;
1244
+ private resolveMessageForResend;
1141
1245
  private lookupQuoted;
1142
1246
  private handleClose;
1143
1247
  private rejectPendingConnect;
@@ -1258,8 +1362,6 @@ interface CacheableAuthStoreOptions {
1258
1362
  warn?: (msg: unknown) => void;
1259
1363
  error?: (msg: unknown) => void;
1260
1364
  };
1261
- cacheSize?: number;
1262
- cacheTtlSeconds?: number;
1263
1365
  }
1264
1366
  declare function makeCacheableAuthStore(bundle: AuthStoreBundle, options?: CacheableAuthStoreOptions): AuthStoreBundle;
1265
1367
 
@@ -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
@@ -180,6 +180,7 @@ interface BuilderSocketLike {
180
180
  messageId: string;
181
181
  additionalNodes?: unknown[];
182
182
  }): Promise<string>;
183
+ chatModify?(mod: unknown, jid: string): Promise<void>;
183
184
  user?: {
184
185
  id?: string | null;
185
186
  } | null;
@@ -319,6 +320,27 @@ declare class ZaileysDomainError extends Error {
319
320
  });
320
321
  }
321
322
 
323
+ type OperationGuardClock = {
324
+ now?: () => number;
325
+ sleep?: (ms: number) => Promise<void>;
326
+ };
327
+ /**
328
+ * Per-category minimum-interval throttle for sensitive account operations
329
+ * (group/community/newsletter create, join, member changes). Spacing these out
330
+ * avoids the rapid-fire pattern WhatsApp flags as automated/bulk abuse.
331
+ */
332
+ type OperationCategory = 'group.create' | 'group.join' | 'group.participants' | 'group.update' | 'community.create' | 'community.join' | 'community.update' | 'newsletter.create' | 'newsletter.follow' | 'newsletter.update';
333
+ interface OperationGuardOptions {
334
+ /** Master switch. When `false` operations run with no spacing. Default `true`. */
335
+ enabled?: boolean;
336
+ /** Per-category minimum interval in ms, overriding the built-in defaults. */
337
+ intervalsMs?: Partial<Record<OperationCategory, number>>;
338
+ }
339
+ interface OperationGuard {
340
+ run<T>(category: OperationCategory, op: () => Promise<T>): Promise<T>;
341
+ }
342
+ declare function createOperationGuard(options?: OperationGuardOptions, clock?: OperationGuardClock): OperationGuard;
343
+
322
344
  interface DomainSocketLike {
323
345
  groupCreate(subject: string, participants: string[]): Promise<GroupMetadata>;
324
346
  groupParticipantsUpdate(jid: string, participants: string[], action: ParticipantAction): Promise<{
@@ -377,9 +399,11 @@ interface DomainSocketLike {
377
399
 
378
400
  declare class GroupModule {
379
401
  private readonly getSocket;
380
- constructor(getSocket: () => DomainSocketLike | undefined);
402
+ private readonly guard?;
403
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
381
404
  protected requireSocket(): DomainSocketLike;
382
405
  private mapParticipants;
406
+ private run;
383
407
  create(subject: string, participants: string[]): Promise<GroupMetadata>;
384
408
  addMember(groupId: string, jids: string[]): Promise<ParticipantUpdateResult[]>;
385
409
  removeMember(groupId: string, jids: string[]): Promise<ParticipantUpdateResult[]>;
@@ -413,8 +437,10 @@ declare class PrivacyModule {
413
437
 
414
438
  declare class NewsletterModule {
415
439
  private readonly getSocket;
416
- constructor(getSocket: () => DomainSocketLike | undefined);
440
+ private readonly guard?;
441
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
417
442
  protected requireSocket(): DomainSocketLike;
443
+ private run;
418
444
  create(name: string, opts?: {
419
445
  description?: string;
420
446
  picture?: Buffer;
@@ -432,8 +458,10 @@ declare class NewsletterModule {
432
458
 
433
459
  declare class CommunityModule {
434
460
  private readonly getSocket;
435
- constructor(getSocket: () => DomainSocketLike | undefined);
461
+ private readonly guard?;
462
+ constructor(getSocket: () => DomainSocketLike | undefined, guard?: OperationGuard | undefined);
436
463
  protected requireSocket(): DomainSocketLike;
464
+ private run;
437
465
  create(subject: string, body: string): Promise<GroupMetadata>;
438
466
  createGroup(subject: string, participants: string[], communityId: string): Promise<GroupMetadata>;
439
467
  linkGroup(communityId: string, groupId: string): Promise<void>;
@@ -798,9 +826,76 @@ interface AuthStoreBundle {
798
826
  readonly signal: AuthStore;
799
827
  }
800
828
 
801
- type DisconnectReasonDomain = 'logged-out' | 'connection-replaced' | 'forbidden' | 'restart-required' | 'bad-session' | 'connection-closed' | 'connection-lost' | 'multi-device-mismatch' | 'unavailable-service' | 'unknown';
829
+ type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
830
+ interface AutomationSocketLike {
831
+ sendPresenceUpdate(type: WAPresence, toJid?: string): Promise<void>;
832
+ }
833
+ /** Drops presence updates that repeat the same (type, chat) inside `minIntervalMs`. */
834
+ interface PresenceThrottleOptions {
835
+ enabled?: boolean;
836
+ minIntervalMs?: number;
837
+ }
838
+ type PresenceClock = {
839
+ now?: () => number;
840
+ };
841
+ declare class PresenceModule {
842
+ private readonly getSocket;
843
+ private readonly throttleEnabled;
844
+ private readonly minIntervalMs;
845
+ private readonly now;
846
+ private readonly lastSent;
847
+ constructor(getSocket: () => AutomationSocketLike | undefined, throttle?: PresenceThrottleOptions, clock?: PresenceClock);
848
+ protected requireSocket(): AutomationSocketLike;
849
+ private throttled;
850
+ private update;
851
+ private scheduleClear;
852
+ online(): Promise<void>;
853
+ offline(): Promise<void>;
854
+ typing(jid: string, ms?: number): Promise<void>;
855
+ recording(jid: string, ms?: number): Promise<void>;
856
+ }
857
+
858
+ /**
859
+ * Bounds QR and pairing-code regeneration across a client's lifetime to avoid
860
+ * tripping WhatsApp's spam/automation restriction. Each reconnect creates a fresh
861
+ * socket which re-emits a QR or requests a new pairing code; without a budget and
862
+ * cooldown this loops unbounded and gets the account restricted.
863
+ */
864
+ interface AuthGuardOptions {
865
+ /** Master switch. When `false` the guard never blocks (legacy behaviour). Default `true`. */
866
+ enabled?: boolean;
867
+ /** Total QR codes emitted before the guard stops and signals exhaustion. Default `5`. */
868
+ maxQrAttempts?: number;
869
+ /** Total pairing-code requests before the guard stops and signals exhaustion. Default `3`. */
870
+ maxPairingAttempts?: number;
871
+ /** Base cooldown between pairing-code requests; escalates per attempt. Default `60000`. */
872
+ pairingCooldownMs?: number;
873
+ }
874
+ type AuthAttemptBlockReason = 'budget-exhausted' | 'cooldown';
875
+ interface AuthAttemptDecision {
876
+ allowed: boolean;
877
+ reason?: AuthAttemptBlockReason;
878
+ waitMs: number;
879
+ attempts: number;
880
+ max: number;
881
+ }
882
+ interface AuthGuard {
883
+ /** Decide whether a new auth attempt of `kind` is permitted at time `now` (does not mutate). */
884
+ evaluate(kind: ConnectionAuthType, now: number): AuthAttemptDecision;
885
+ /** Record that an attempt of `kind` was actually issued at time `now`. */
886
+ record(kind: ConnectionAuthType, now: number): void;
887
+ /** Clear all counters and cooldowns (call on a successful connection or manual restart). */
888
+ reset(): void;
889
+ readonly enabled: boolean;
890
+ readonly qrAttempts: number;
891
+ readonly pairingAttempts: number;
892
+ }
893
+ declare function createAuthGuard(options?: AuthGuardOptions): AuthGuard;
894
+
895
+ type DisconnectReasonDomain = 'logged-out' | 'connection-replaced' | 'forbidden' | 'restart-required' | 'bad-session' | 'connection-closed' | 'connection-lost' | 'multi-device-mismatch' | 'unavailable-service' | 'rate-limited' | 'unknown';
802
896
  declare function mapDisconnectReason(code: number | undefined): DisconnectReasonDomain;
803
897
  declare function isFatalDisconnect(reason: DisconnectReasonDomain): boolean;
898
+ declare function isRateLimited(reason: DisconnectReasonDomain): boolean;
804
899
  declare function shouldClearAuth(reason: DisconnectReasonDomain): boolean;
805
900
  declare function shouldReconnect(reason: DisconnectReasonDomain): boolean;
806
901
 
@@ -819,6 +914,8 @@ interface ReconnectOptions {
819
914
  initialDelayMs?: number;
820
915
  maxDelayMs?: number;
821
916
  jitterFactor?: number;
917
+ /** Fixed backoff applied when the disconnect reason is `rate-limited` (429). Default `300000`. */
918
+ rateLimitedDelayMs?: number;
822
919
  }
823
920
  interface ClientOptions {
824
921
  sessionId?: string;
@@ -836,6 +933,14 @@ interface ClientOptions {
836
933
  commandPrefix?: string | string[];
837
934
  citation?: CitationConfig;
838
935
  ignoreMe?: boolean;
936
+ /** Bounds QR/pairing regeneration to avoid spam restriction. ON by default; `{ enabled: false }` to opt out. */
937
+ authGuard?: AuthGuardOptions;
938
+ /** Spaces out sensitive group/community/newsletter operations. ON by default; `{ enabled: false }` to opt out. */
939
+ operationGuard?: OperationGuardOptions;
940
+ /** Drops duplicate presence (typing/recording/online) updates within a window. ON by default. */
941
+ presence?: PresenceThrottleOptions;
942
+ /** Max scheduled messages dispatched per second, smoothing backlog bursts. Default `1`; `0` disables. */
943
+ scheduleRateLimitPerSec?: number;
839
944
  }
840
945
  type ConnectionEventMap = {
841
946
  connect: {
@@ -867,6 +972,12 @@ type ConnectionEventMap = {
867
972
  delayMs: number;
868
973
  reason: DisconnectReasonDomain;
869
974
  };
975
+ 'auth-exhausted': {
976
+ sessionId: string;
977
+ kind: ConnectionAuthType;
978
+ attempts: number;
979
+ max: number;
980
+ };
870
981
  error: {
871
982
  sessionId: string;
872
983
  error: Error;
@@ -983,22 +1094,6 @@ type BroadcastDeps = {
983
1094
  };
984
1095
  declare function runBroadcast(jids: string[], build: (b: MessageBuilder<'init'>) => MessageBuilder<'content-set'>, deps: BroadcastDeps, options?: BroadcastOptions): Promise<BroadcastResult>;
985
1096
 
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
1097
  type ScheduledContentSnapshot = {
1003
1098
  recipient: string;
1004
1099
  content: AnyMessageContent;
@@ -1014,6 +1109,7 @@ type SchedulerDeps = {
1014
1109
  now?: () => number;
1015
1110
  timer?: SchedulerTimer;
1016
1111
  logger?: Logger;
1112
+ acquire?: () => Promise<void>;
1017
1113
  };
1018
1114
  type ScheduleHandle = {
1019
1115
  id: string;
@@ -1025,6 +1121,7 @@ declare class Scheduler {
1025
1121
  private readonly now;
1026
1122
  private readonly timer;
1027
1123
  private readonly logger;
1124
+ private readonly acquire;
1028
1125
  private readonly memory;
1029
1126
  private readonly timers;
1030
1127
  constructor(deps: SchedulerDeps);
@@ -1072,6 +1169,11 @@ declare class Client extends TypedEventEmitter<ClientEventMap> {
1072
1169
  private readonly baileysExtra;
1073
1170
  private readonly machine;
1074
1171
  private reconnectStrategy;
1172
+ private readonly authGuard;
1173
+ private readonly operationGuard;
1174
+ private readonly presenceThrottle;
1175
+ private readonly scheduleLimiter;
1176
+ private authExhausted;
1075
1177
  private _socket;
1076
1178
  private reconnectTimer;
1077
1179
  private listenerCleanup;
@@ -1137,7 +1239,9 @@ declare class Client extends TypedEventEmitter<ClientEventMap> {
1137
1239
  private wireSocket;
1138
1240
  private handleConnectionUpdate;
1139
1241
  private handleQrUpdate;
1242
+ private handleAuthExhausted;
1140
1243
  private handleOpen;
1244
+ private resolveMessageForResend;
1141
1245
  private lookupQuoted;
1142
1246
  private handleClose;
1143
1247
  private rejectPendingConnect;
@@ -1258,8 +1362,6 @@ interface CacheableAuthStoreOptions {
1258
1362
  warn?: (msg: unknown) => void;
1259
1363
  error?: (msg: unknown) => void;
1260
1364
  };
1261
- cacheSize?: number;
1262
- cacheTtlSeconds?: number;
1263
1365
  }
1264
1366
  declare function makeCacheableAuthStore(bundle: AuthStoreBundle, options?: CacheableAuthStoreOptions): AuthStoreBundle;
1265
1367
 
@@ -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 };