Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(session): route the not-started guards through engines.require
Yudhi Armyndharis315724148068
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5c568e919..30d395939 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- The twelve hand-rolled "Session is not started" guards in the session service route through the engine registry's `require()` (wire contract unchanged), and three routes drop an OpenAPI 404 declaration no code path can produce.- import-data restores an active session status from the backup as `disconnected` (scoped to claimable rows; a notice counts them), so migrated sessions are startable without a process restart.- The engine parity gate reads any single-quoted throw literal (a parenthesized site like sendText(customPreview) escaped the identifier-only regex), rejects construction sites it cannot see (template literals, variable arguments, literals naming no method), and pins conditional refusals in an explicit list; docs/29 states the refinements.- The Baileys adapter builds one shared host object for its nine delegates instead of nine overlapping closure bags; a new cross-cutting member is added once. No behavior change.diff --git a/openapi.json b/openapi.jsonindex 7ac315e78..52896a910 100644--- a/openapi.json+++ b/openapi.json@@ -2295,9 +2295,6 @@"400": {"description": "Session not active or invalid request"},- "404": {- "description": "Session not found"- },"409": {"description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."},@@ -4314,9 +4311,6 @@"400": {"description": "Session not ready"},- "404": {- "description": "Session not found"- },"409": {"description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."}@@ -6273,9 +6267,6 @@"400": {"description": "Session not ready or not a business account"},- "404": {- "description": "Session not found"- },"409": {"description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."},diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.tsindex 520b91f4a..e37532b0b 100644--- a/src/modules/contact/contact.controller.ts+++ b/src/modules/contact/contact.controller.ts@@ -28,7 +28,6 @@ export class ContactController {type: [ContactDto],})@ApiResponse({ status: 400, description: 'Session not ready' })- @ApiResponse({ status: 404, description: 'Session not found' })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiQuery({ name: 'limit', required: false, description: 'Max contacts to return (1–1000, default 1000)' })@ApiQuery({ name: 'offset', required: false, description: 'Number of contacts to skip (for paging)' })diff --git a/src/modules/label/label.controller.ts b/src/modules/label/label.controller.tsindex 45ba41efe..d401d9ef3 100644--- a/src/modules/label/label.controller.ts+++ b/src/modules/label/label.controller.ts@@ -22,7 +22,6 @@ export class LabelController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiResponse({ status: 200, description: 'List of labels', type: [LabelDto] })@ApiResponse({ status: 400, description: 'Session not ready or not a business account' })- @ApiResponse({ status: 404, description: 'Session not found' })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 501, description: ENGINE_NOT_SUPPORTED_501 })async findAll(@Param('sessionId') sessionId: string) {diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex 141bea3d6..bb746e038 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -112,7 +112,6 @@ export class MessageController {status: 400,description: 'Session not active or invalid request',})- @ApiResponse({ status: 404, description: 'Session not found' })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 501, description: CUSTOM_LINK_PREVIEW_501 })async sendText(@Param('sessionId') sessionId: string, @Body() dto: SendTextMessageDto): Promise<MessageResponseDto> {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex b26b9cac9..0f95872cd 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -480,11 +480,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatasync getQRCode(id: string): Promise<{ qrCode: string; status: SessionStatus }> {const session = await this.findOne(id);- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started. Call POST /sessions/:sessionId/start first.');- }+ const engine = this.engines.require(+ id,+ () => new BadRequestException('Session is not started. Call POST /sessions/:sessionId/start first.'),+ );const qrCode = engine.getQRCode();@@ -507,11 +506,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat*/async requestPairingCode(id: string, phoneNumber: string): Promise<{ pairingCode: string; status: SessionStatus }> {const session = await this.findOne(id);- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started. Call POST /sessions/:sessionId/start first.');- }+ const engine = this.engines.require(+ id,+ () => new BadRequestException('Session is not started. Call POST /sessions/:sessionId/start first.'),+ );if (session.status === SessionStatus.READY) {throw new BadRequestException('Session is already authenticated, no pairing needed');}@@ -524,16 +522,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn this.engines.get(id);}+ /**+ * The engine for a started session, or the documented 400. Routes through engines.require's+ * default onMissing so the wire contract stays byte-identical to the hand-rolled guards this+ * replaces ('Session is not started', exactly as each API surface documented it).+ */+ private requireEngine(id: string): IWhatsAppEngine {+ return this.engines.require(id);+ }+async getGroups(id: string,opts: ListOptions = {},): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {await this.findOne(id); // Verify session exists- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);const groups = await engine.getGroups();const mapped = groups.map(g => ({@@ -546,11 +549,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatasync getChats(id: string, opts: ListOptions = {}): Promise<ChatSummary[]> {await this.findOne(id); // Verify session exists- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);// Most-recent first, then bound the response window. Sorting before the cap means a capped// response is the N newest chats (what clients show first) rather than an arbitrary slice.@@ -569,11 +568,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat*/async subscribeToPresence(id: string, chatId: string): Promise<void> {await this.findOne(id);- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);return engine.subscribeToPresence(chatId);}@@ -584,11 +579,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat*/async setOnlinePresence(id: string, available: boolean): Promise<void> {await this.findOne(id);- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);return engine.setOnlinePresence(available);}@@ -605,22 +596,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatasync sendSeen(id: string, chatId: string): Promise<boolean> {await this.findOne(id); // Verify session exists- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);return engine.sendSeen(chatId);}async markUnread(id: string, chatId: string): Promise<boolean> {await this.findOne(id); // Verify session exists- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);return engine.markUnread(chatId);}@@ -631,11 +614,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat*/async clearChatMessages(id: string, chatId: string): Promise<boolean> {await this.findOne(id); // Verify session exists- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);return engine.clearChatMessages(chatId);}@@ -647,11 +626,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat*/async archiveChat(id: string, chatId: string, archive: boolean): Promise<boolean> {await this.findOne(id); // Verify session exists- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);return engine.archiveChat(chatId, archive);}@@ -663,11 +638,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat*/async muteChat(id: string, chatId: string, muteUntil: number | null): Promise<void> {await this.findOne(id); // Verify session exists- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);return engine.muteChat(chatId, muteUntil);}@@ -678,33 +649,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat*/async pinChat(id: string, chatId: string, pin: boolean): Promise<boolean> {await this.findOne(id); // Verify session exists- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);return engine.pinChat(chatId, pin);}async deleteChat(id: string, chatId: string): Promise<boolean> {await this.findOne(id); // Verify session exists- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);return engine.deleteChat(chatId);}async sendChatState(id: string, chatId: string, state: ChatState): Promise<void> {await this.findOne(id); // Verify session exists- const engine = this.engines.get(id);-- if (!engine) {- throw new BadRequestException('Session is not started');- }+ const engine = this.requireEngine(id);await engine.sendChatState(chatId, state);}