Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
/**
* Sessions resource — lifecycle management for WhatsApp sessions.
*
* Backed by `src/modules/session/session.controller.ts`.
* @packageDocumentation
*/
import { encodeSegment } from '../http.js';
import type { OpenWAClient } from '../client.js';
import type {
CreateSessionRequest,
PairingCodeResponse,
QrCodeResponse,
RequestPairingCodeRequest,
SessionConfig,
SessionProxy,
SessionResponse,
UpdateSessionConfigRequest,
UpdateSessionProxyRequest,
SessionStatsOverview,
SetOwnPresenceRequest,
SuccessResult,
} from '../types.js';
/** Pagination for {@link SessionsResource.list}. The server applies its own default when omitted. */
export interface ListSessionsQuery {
limit?: number;
offset?: number;
/** Return only the session with exactly this name (case-sensitive). */
name?: string;
}
export class SessionsResource {
constructor(private readonly client: OpenWAClient) {}
/** List all sessions (scoped to the API key's `allowedSessions`). */
list(query?: ListSessionsQuery): Promise<SessionResponse[]> {
return this.client.request<SessionResponse[]>({ method: 'GET', path: '/api/sessions', query });
}
/** Read a session's effective configuration. */
getConfig(id: string): Promise<SessionConfig> {
return this.client.request<SessionConfig>({
method: 'GET',
path: `/api/sessions/${encodeSegment(id)}/config`,
});
}
/**
* Update a session's configuration, in any state, without a restart or re-linking the account (all
* three fields were fixed at creation before this route existed). `autoRejectCalls` applies
* immediately; `maxReconnectAttempts` and `reconnectBaseDelay` apply on the next start.
*/
updateConfig(id: string, body: UpdateSessionConfigRequest): Promise<SessionConfig> {
return this.client.request<SessionConfig>({
method: 'PATCH',
path: `/api/sessions/${encodeSegment(id)}/config`,
body,
});
}
/** Read a session's masked proxy configuration (credentials never returned). */
getProxy(id: string): Promise<SessionProxy> {
return this.client.request<SessionProxy>({
method: 'GET',
path: `/api/sessions/${encodeSegment(id)}/proxy`,
});
}
/**
* Update per-session proxy settings. No restart is performed — changes apply on the next start.
* Send `proxyUrl: null` to clear the proxy. **ADMIN** (unscoped key)
*/
updateProxy(id: string, body: UpdateSessionProxyRequest): Promise<SessionProxy> {
return this.client.request<SessionProxy>({
method: 'PATCH',
path: `/api/sessions/${encodeSegment(id)}/proxy`,
body,
});
}
/** Get a single session by id. */
get(id: string): Promise<SessionResponse> {
return this.client.request<SessionResponse>({ method: 'GET', path: `/api/sessions/${encodeSegment(id)}` });
}
/** Create a new session. Requires an OPERATOR-level key; setting proxyUrl requires an ADMIN key. */
create(body: CreateSessionRequest): Promise<SessionResponse> {
return this.client.request<SessionResponse>({ method: 'POST', path: '/api/sessions', body });
}
/** Delete a session. Requires an OPERATOR-level key. */
delete(id: string): Promise<void> {
return this.client.request<void>({ method: 'DELETE', path: `/api/sessions/${encodeSegment(id)}` });
}
/** Start a session and initialize the WhatsApp connection. */
start(id: string): Promise<SessionResponse> {
return this.client.request<SessionResponse>({ method: 'POST', path: `/api/sessions/${encodeSegment(id)}/start` });
}
/**
* Stop a session and disconnect gracefully. Rejects with HTTP `502` and
* `code: 'SESSION_STOP_INCOMPLETE'` when the session was stopped locally but the engine
* teardown did not complete (the graceful disconnect and the force-destroy escalation both
* failed, so the engine process may still be running); the status is settled to
* `disconnected` and no success audit is written. Retry the stop; restart the node to reap
* a leaked process.
*/
stop(id: string): Promise<SessionResponse> {
return this.client.request<SessionResponse>({ method: 'POST', path: `/api/sessions/${encodeSegment(id)}/stop` });
}
/**
* Attempt an engine-native unlink of this device, then stop the session. A `200` means the
* unlink operation AND the required local credential cleanup completed — it is not an
* independent observation that the handset UI no longer shows the linked device. Because a
* completed unlink wipes the stored credentials, a later `start` requires a fresh QR scan or
* pairing code. Requires a running session. Rejects with HTTP `502` and
* `code: 'SESSION_LOGOUT_INCOMPLETE'` when the session was stopped locally but the logout
* operation did not complete (no send, no acknowledgement, timeout/transport error, or local
* cleanup failure); `phone` is cleared and no success audit is written. Start the session again
* and retry the logout; do not assume the retry reconnects automatically or lands in a
* guaranteed QR state.
*/
logout(id: string): Promise<SessionResponse> {
return this.client.request<SessionResponse>({ method: 'POST', path: `/api/sessions/${encodeSegment(id)}/logout` });
}
/**
* Force-kill a stuck session (SIGKILL + teardown). Rejects with HTTP `502` and
* `code: 'SESSION_FORCE_KILL_INCOMPLETE'` when the session was stopped locally but the
* force-destroy threw or timed out, so the engine process may still be running; the status is
* settled to `disconnected`, no success audit is written, and a retry answers `400` because no
* engine is left to kill. Restart the node to reap a leaked process.
*/
forceKill(id: string): Promise<SessionResponse> {
return this.client.request<SessionResponse>({
method: 'POST',
path: `/api/sessions/${encodeSegment(id)}/force-kill`,
});
}
/** Get the current QR code for authentication (live from the engine, not the DB). */
getQrCode(id: string): Promise<QrCodeResponse> {
return this.client.request<QrCodeResponse>({ method: 'GET', path: `/api/sessions/${encodeSegment(id)}/qr` });
}
/**
* Request an 8-character pairing code for phone-based login. On whatsapp-web.js, never request one for a
* number that already has a linked session: WhatsApp can revoke that device. Link it by QR instead.
*/
requestPairingCode(id: string, body: RequestPairingCodeRequest): Promise<PairingCodeResponse> {
return this.client.request<PairingCodeResponse>({
method: 'POST',
path: `/api/sessions/${encodeSegment(id)}/pairing-code`,
body,
});
}
/** Aggregate statistics across the API key's sessions. */
stats(): Promise<SessionStatsOverview> {
return this.client.request<SessionStatsOverview>({
method: 'GET',
path: '/api/sessions/stats/overview',
});
}
/**
* Set the account's own global presence — appear online, or offline.
*
* `available: false` hands notifications back to the phone: a linked device that stays online
* suppresses the phone's own alerts. This is the ACCOUNT's presence, not a chat's — see
* {@link ChatsResource.sendState} for per-chat typing/recording.
*/
setOnlinePresence(sessionId: string, body: SetOwnPresenceRequest): Promise<SuccessResult> {
return this.client.request<SuccessResult>({
method: 'PUT',
path: `/api/sessions/${encodeSegment(sessionId)}/presence`,
body,
});
}
}