Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

chore: harden runtime gaps and sync project documentation (#496)

Yudhi Armyndharis27feb512b691
diff --git a/.env.example b/.env.example
index e3d626a1c..7fe692eb0 100644
--- a/.env.example
+++ b/.env.example
@@ -16,6 +16,9 @@ LOG_LEVEL=info # error | warn | info | debug
# Auto-start previously authenticated sessions on server boot
AUTO_START_SESSIONS=false
+# 0 = unlimited. Set a positive integer to cap concurrently running/initializing sessions.
+# Failed sessions still hold a slot until stopped (their engine stays resident); stop them to free capacity.
+MAX_CONCURRENT_SESSIONS=0
# Domain Configuration
DOMAIN=localhost
@@ -146,6 +149,8 @@ REDIS_BUILTIN=false # Use built-in Redis container?
# Redis settings (auto-configured if REDIS_BUILTIN=true)
REDIS_HOST=localhost
REDIS_PORT=6379
+# Fail Redis queue/cache connection attempts after this many ms.
+REDIS_CONNECT_TIMEOUT_MS=5000
# REDIS_PASSWORD=
# =============================================================================
diff --git a/dashboard/src/hooks/useChatMessages.ts b/dashboard/src/hooks/useChatMessages.ts
index 28f9c3b5d..98e78649e 100644
--- a/dashboard/src/hooks/useChatMessages.ts
+++ b/dashboard/src/hooks/useChatMessages.ts
@@ -21,10 +21,7 @@ export function messagesQueryKey(sessionId: string, chatId: string): MessagesQue
* not through refetches. Cache eviction happens 30 min after the chat stops
* being observed (gcTime).
*/
-export function useChatMessages(
- sessionId: string,
- chatId: string | null,
-): UseQueryResult<ChatMessageView[], Error> {
+export function useChatMessages(sessionId: string, chatId: string | null): UseQueryResult<ChatMessageView[], Error> {
return useQuery<ChatMessageView[], Error>({
queryKey: messagesQueryKey(sessionId, chatId ?? ''),
queryFn: async () => {
@@ -62,16 +59,12 @@ export function useChatMessagesActions() {
);
},
updateMessage(sessionId: string, chatId: string, id: string, patch: Partial<ChatMessageView>) {
- qc.setQueryData<ChatMessageView[]>(
- messagesQueryKey(sessionId, chatId),
- (old = []) => updateMessageById(old, id, patch),
+ qc.setQueryData<ChatMessageView[]>(messagesQueryKey(sessionId, chatId), (old = []) =>
+ updateMessageById(old, id, patch),
);
},
removeMessage(sessionId: string, chatId: string, id: string) {
- qc.setQueryData<ChatMessageView[]>(
- messagesQueryKey(sessionId, chatId),
- (old = []) => removeMessageById(old, id),
- );
+ qc.setQueryData<ChatMessageView[]>(messagesQueryKey(sessionId, chatId), (old = []) => removeMessageById(old, id));
},
};
}
diff --git a/docs/01-project-overview.md b/docs/01-project-overview.md
index 3742eb212..f2922c3e0 100644
--- a/docs/01-project-overview.md
+++ b/docs/01-project-overview.md
@@ -135,7 +135,7 @@ Phase 3 (Advanced)
├── Label management
├── Status/Stories
├── Proxy per session
-├── Horizontal scaling
+├── Horizontal scaling design reference
└── Metrics & monitoring
```
@@ -237,8 +237,8 @@ flowchart TB
subgraph Frontend["Dashboard"]
R[React] --> V[Vite]
- V --> S[shadcn/ui]
- S --> L[Lucide Icons]
+ V --> C[Bespoke CSS]
+ C --> L[Lucide Icons]
L --> UI[Modern UI]
end
```
@@ -256,8 +256,8 @@ flowchart TB
| Cache | Redis | Fast, pub/sub support |
| Queue | Bull | Reliable job processing |
| Dashboard | React + Vite | Fast, modern |
-| Styling | Tailwind CSS | Utility-first CSS |
-| UI Components | shadcn/ui + Lucide | Accessible, polished |
+| Styling | Bespoke CSS modules/stylesheets | Lightweight dashboard styling without Tailwind |
+| UI Components | Custom React components + Lucide | Accessible, polished |
| Container | Docker | Portable, consistent |
## 1.9 Constraints & Assumptions
diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.md
index f52883640..94284528f 100644
--- a/docs/03-system-architecture.md
+++ b/docs/03-system-architecture.md
@@ -1482,8 +1482,9 @@ flowchart LR
| **Standard** | PostgreSQL | Local | Redis | 5-10 | 2GB | Small business |
| **Enterprise** | PostgreSQL | S3/MinIO | Redis | 10+ | 4GB+ | Agency, high volume |
-> Session counts are guidance only — there is **no enforced session cap** in the code
-> (no `MAX_SESSIONS` env var is read anywhere).
+> Session counts are guidance only by default. Set `MAX_CONCURRENT_SESSIONS` to a positive integer
+> to cap concurrently running or initializing engines; the default `0` keeps the historical
+> unlimited behavior.
### Configuration Examples
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index c35460738..616da8623 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -167,6 +167,13 @@ List all sessions, scoped to the API key's `allowedSessions`, ordered `createdAt
**Auth:** API key · **Scope:** session-scoped (a scoped key sees only its `allowedSessions`; an ADMIN / null-allowlist key lists all)
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| `limit` | integer (1-1000) | No | `1000` | Max sessions to return; oversized/non-finite values are clamped/fallback to the default window. |
+| `offset` | integer | No | `0` | Sessions to skip for paging; negative/non-finite values resolve to `0`. |
+
**Response** `200`
```json
@@ -2900,6 +2907,13 @@ List webhooks visible to the calling API key, scoped to its allowed sessions.
**Auth:** API key (OPERATOR) · **Scope:** session-scoped — derived from the authenticated key, not from any param/query
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| `limit` | integer (1-1000) | No | `1000` | Max webhooks to return; oversized/non-finite values are clamped/fallback to the default window. |
+| `offset` | integer | No | `0` | Webhooks to skip for paging; negative/non-finite values resolve to `0`. |
+
**Response** `200`
```json
@@ -2919,7 +2933,7 @@ List webhooks visible to the calling API key, scoped to its allowed sessions.
]
```
-Bare array, ordered by `createdAt` descending. If the calling key has a non-empty `allowedSessions` list, results are filtered to `WHERE sessionId IN (allowedSessions)`; a key with null/empty `allowedSessions` (e.g. an unrestricted ADMIN key) sees **all** webhooks. This is the cross-session list; the per-session list lives at `GET /api/sessions/:sessionId/webhooks`.
+Bare array, ordered by `createdAt` descending, bounded by `limit`/`offset`. If the calling key has a non-empty `allowedSessions` list, results are filtered to `WHERE sessionId IN (allowedSessions)`; a key with null/empty `allowedSessions` (e.g. an unrestricted ADMIN key) sees **all** webhooks. This is the cross-session list; the per-session list lives at `GET /api/sessions/:sessionId/webhooks`.
**Errors:** `401` missing/invalid API key · `403` insufficient role
@@ -4545,7 +4559,7 @@ Recurring lifecycle events (and `message.reaction`) carry the same content acros
### Retries with exponential backoff
-When the queue is enabled, a non-2xx response, timeout (`WEBHOOK_TIMEOUT`, default `10000` ms), or network error schedules a retry. The number of attempts comes from the webhook's `retryCount` (default `3`) and the delay grows **exponentially** from a base of `WEBHOOK_RETRY_DELAY` (default `5000` ms). Each retry reuses the same `idempotencyKey` and increments `X-OpenWA-Retry-Count`. When the queue is disabled, delivery is direct with the same retry budget applied inline.
+When the queue is enabled, a non-2xx response, timeout (`WEBHOOK_TIMEOUT`, default `10000` ms), or network error schedules a retry. The number of attempts comes from the webhook's `retryCount` (default `3`) and the delay grows **exponentially** from a base of `WEBHOOK_RETRY_DELAY` (default `5000` ms). Each retry reuses the same `idempotencyKey` and increments `X-OpenWA-Retry-Count`. If Redis/BullMQ rejects the initial enqueue, OpenWA logs a `webhook:error` hook event and falls back to direct delivery with the same inline retry budget. When the queue is disabled, delivery is direct with the same retry budget applied inline.
### SSRF guard on registration
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index ec1e78786..aa297c245 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -38,10 +38,10 @@ All routes are under `$BASE/api/sessions` and require `X-API-Key: $API_KEY` (som
#### GET /api/sessions
-List all sessions visible to the key.
+List all sessions visible to the key. Add `limit`/`offset` to page large installations.
```bash
-curl -X GET "$BASE/api/sessions" \
+curl -X GET "$BASE/api/sessions?limit=100&offset=0" \
-H "X-API-Key: $API_KEY"
```
@@ -851,10 +851,10 @@ curl -X GET "$BASE/api/sessions/my-session/webhooks/f1e2d3c4-b5a6-7890-1234-5678
#### GET /api/webhooks
-List webhooks visible to the calling key (scoped to its allowed sessions).
+List webhooks visible to the calling key (scoped to its allowed sessions). Add `limit`/`offset` to page large lists.
```bash
-curl -X GET "$BASE/api/webhooks" \
+curl -X GET "$BASE/api/webhooks?limit=100&offset=0" \
-H "X-API-Key: $API_KEY"
```
diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.md
index d1c16e4c9..3b8afd8db 100644
--- a/docs/09-testing-strategy.md
+++ b/docs/09-testing-strategy.md
@@ -6,14 +6,14 @@ OpenWA now has an active Jest test suite covering the backend core, engine adapt
database migrations, plugin hooks, and smoke-level e2e boot paths. This document describes the current
test layout and the expected testing workflow for contributors.
-Status snapshot from the repository state on 2026-06-21:
+Status snapshot from the repository state on 2026-06-28:
| Area | Current state |
|------|---------------|
-| Backend unit tests | 89 Jest suites / 987 tests passing with `npm test -- --runInBand` |
-| E2E smoke tests | 3 Jest suites / 11 tests passing with `npm run test:e2e -- --runInBand` |
-| Test files | 92 `*.spec.ts` / `*.e2e-spec.ts` files under `src/` and `test/` |
-| Dashboard checks | CI runs dashboard lint, i18n parity check, and dashboard build |
+| Backend unit tests | 113 Jest suites / 1481 tests passing with `npm test -- --runInBand` |
+| E2E smoke tests | 5 Jest suites / 31 tests passing plus 3 todo with `npm run test:e2e -- --runInBand` |
+| Dashboard checks | Dashboard lint, unit tests, i18n parity check, and build |
+| Coverage baseline | 66.87% line coverage; active target is 80% (see `docs/superpowers/specs/2025-01-28-test-coverage-improvement-design.md`) |
| Coverage gate | Jest global thresholds plus stricter thresholds for security-sensitive modules |
The exact counts will change as the project evolves. Use the commands below as the source of truth.
@@ -22,6 +22,7 @@ The exact counts will change as the project evolves. Use the commands below as t
find src test -name '*.spec.ts' -o -name '*.e2e-spec.ts' | wc -l
npm test -- --runInBand
npm run test:e2e -- --runInBand
+npm --prefix dashboard run test:unit
```
## 09.2 Test Commands
@@ -34,6 +35,7 @@ npm run test:e2e -- --runInBand
| `npm run test:e2e` | Run smoke-level e2e tests from `test/` |
| `npm run lint` | Run backend ESLint with type-aware rules |
| `cd dashboard && npm run lint` | Run dashboard ESLint |
+| `cd dashboard && npm run test:unit` | Run dashboard pure utility/unit tests |
| `cd dashboard && npm run i18n:check` | Verify dashboard locale key parity |
| `cd dashboard && npm run build` | Type-check and build the dashboard |
@@ -138,7 +140,7 @@ CI is defined in `.github/workflows/ci.yml`.
|-----|--------|
| `lint` | `npm audit --audit-level=critical`, backend ESLint, formatting check |
| `test` | backend coverage run, e2e smoke tests, Codecov upload |
-| `dashboard` | dashboard install, lint, i18n parity, build |
+| `dashboard` | dashboard install, lint, unit tests, i18n parity, build |
| `build` | backend build after lint/test/dashboard jobs pass |
| `docker` | multi-arch Docker build and push on branch pushes |
@@ -217,7 +219,7 @@ Live WhatsApp checks require an operator-owned account and should not be part of
- No default CI job exercises a real WhatsApp connection.
- No default CI job exercises real PostgreSQL, Redis, S3/MinIO, or Docker socket proxy integration.
- Performance testing is not automated.
-- Dashboard UI tests are not currently automated beyond lint, i18n parity, and build.
+- Dashboard browser/visual UI tests are not currently automated; dashboard pure utility tests run via `npm --prefix dashboard run test:unit`.
These gaps are intentional for the default suite because the project prioritizes deterministic tests that
run without external services. Add opt-in integration jobs only when they are isolated, documented, and do
diff --git a/docs/15-project-roadmap.md b/docs/15-project-roadmap.md
index b9c454cbd..3799f2f35 100644
--- a/docs/15-project-roadmap.md
+++ b/docs/15-project-roadmap.md
@@ -67,6 +67,9 @@ timeline
| v0.2.10 | Dashboard/CI follow-ups (MessageTester JID, neutral MessageType, qemu v4) | ✅ Released |
| v0.3.0 | Engine pluggability (Baileys engine, plugin layer) | ✅ Released |
| v0.4.0 | Single-port deployment (dashboard on API port, Traefik removed) | ✅ Released |
+| v0.5.x | Plugin/dashboard hardening and SDK/docs increments | ✅ Released |
+| v0.6.x | Operational hardening, API surface refinements, dashboard follow-ups | ✅ Released |
+| v0.7.x | Dashboard chat UX, infra backup/restore, media-download toggle, infra follow-ups | ✅ Released |
| v1.0.0 | Enterprise Ready (K8s Operator, multi-tenant) | 📋 Planned |
> SDK / docs-site / observability features (Node & Python SDK, Postman collection, Grafana, OpenTelemetry)
@@ -459,8 +462,8 @@ gantt
| Feature | Priority | Status |
| ------------------ | -------- | ------ |
-| Horizontal scaling | P2 | ✅ |
-| Session affinity | P2 | ✅ |
+| Horizontal scaling | P2 | 📄 Design reference only; single active owner per session remains required |
+| Session affinity | P2 | 📄 Documented for future topology, not implemented as multi-replica runtime |
| Security audit | P0 | ✅ |
#### Community & Tooling
@@ -491,7 +494,7 @@ v0.1.0 Release Package:
## 15.6 Future Roadmap (v0.3.0+)
> **Note:** Version 0.1.0 is the initial stable release including all features from Phases 1-3.
-> Versions 0.1.7 through 0.4.6 have since shipped (see the CHANGELOG); v1.0.0
+> Versions 0.1.7 through 0.7.8 have since shipped (see the CHANGELOG); v1.0.0
> onward is forward-looking.
```mermaid
@@ -659,7 +662,7 @@ flowchart TB
| Dashboard functional | All features | ✅ Achieved | Internal |
| PostgreSQL stable | ✅ | ✅ Achieved | Internal |
| Webhook delivery rate | > 99% | ✅ Achieved | Internal |
-| Test coverage | > 70% | ⚠️ ~5% (deferred) | Internal |
+| Test coverage | > 70% | ⚠️ 66.87% line coverage; 80% improvement plan active | Internal |
| GitHub stars | 100+ | 📋 Pending | External |
### Phase 3 Success Criteria
@@ -668,7 +671,7 @@ flowchart TB
| ----------------------------- | ------- | ----------------- | -------- |
| Feature parity with WAHA Plus | 90%+ | ✅ Achieved | Internal |
| API response time (p95) | < 200ms | ✅ Achieved | Internal |
-| Test coverage | > 80% | ⚠️ ~5% (deferred) | Internal |
+| Test coverage | > 80% | ⚠️ 66.87% line coverage; in progress | Internal |
| Documentation coverage | 100% | ✅ 95%+ | Internal |
| Production users | 50+ | 📋 Pending | External |
| GitHub stars | 500+ | 📋 Pending | External |
diff --git a/docs/README.md b/docs/README.md
index cb0184610..ac0662923 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -56,6 +56,8 @@
| 21 | [Glossary](./21-glossary.md) | Terms and definitions |
| 22 | [n8n Integration](./22-n8n-integration.md) | n8n community nodes for OpenWA |
| 23 | [Community Integrations](./23-community-integrations.md) | Third-party adapters built on the OpenWA API |
+| 23-S| [Plugin Sandboxing](./23-plugin-sandboxing.md) | Worker isolation, capabilities, and plugin limits |
+| 24 | [MCP Integration](./24-mcp-integration.md) | Model Context Protocol tools and auth model |
**Examples**
diff --git a/src/common/cache/cache.service.ts b/src/common/cache/cache.service.ts
index d45084a5f..3aa8a8dbe 100644
--- a/src/common/cache/cache.service.ts
+++ b/src/common/cache/cache.service.ts
@@ -75,7 +75,7 @@ export class CacheService implements OnModuleDestroy {
db: this.configService.get<number>('REDIS_CACHE_DB', 1),
lazyConnect: true,
maxRetriesPerRequest: 3,
- connectTimeout: 5000,
+ connectTimeout: this.configService.get<number>('redis.connectTimeoutMs', 5000),
retryStrategy: times => {
if (times > 3) return null;
return Math.min(times * 500, 3000);
diff --git a/src/common/utils/paginate.spec.ts b/src/common/utils/paginate.spec.ts
index 1dfa72240..fa2000978 100644
--- a/src/common/utils/paginate.spec.ts
+++ b/src/common/utils/paginate.spec.ts
@@ -1,4 +1,4 @@
-import { paginate } from './paginate';
+import { paginate, resolveListWindow } from './paginate';
describe('paginate', () => {
const items = Array.from({ length: 1500 }, (_, i) => i);
@@ -29,3 +29,27 @@ describe('paginate', () => {
expect(paginate([1, 2, 3])).toEqual([1, 2, 3]);
});
});
+
+describe('resolveListWindow', () => {
+ it('defaults a missing/non-finite window to { limit: 1000, offset: 0 }', () => {
+ expect(resolveListWindow()).toEqual({ limit: 1000, offset: 0 });
+ expect(resolveListWindow(NaN, NaN)).toEqual({ limit: 1000, offset: 0 });
+ expect(resolveListWindow(Infinity, -Infinity)).toEqual({ limit: 1000, offset: 0 });
+ });
+
+ it('clamps limit to [1, 1000] and offset to >= 0', () => {
+ expect(resolveListWindow(5000, -5)).toEqual({ limit: 1000, offset: 0 });
+ expect(resolveListWindow(0, 25)).toEqual({ limit: 1, offset: 25 });
+ expect(resolveListWindow(50, 10)).toEqual({ limit: 50, offset: 10 });
+ });
+
+ it('truncates fractional limit/offset toward zero', () => {
+ expect(resolveListWindow(10.9, 4.7)).toEqual({ limit: 10, offset: 4 });
+ });
+
+ it('keeps the boundary values exactly', () => {
+ expect(resolveListWindow(1, 0)).toEqual({ limit: 1, offset: 0 });
+ expect(resolveListWindow(1000, 0)).toEqual({ limit: 1000, offset: 0 });
+ expect(resolveListWindow(1001, 0)).toEqual({ limit: 1000, offset: 0 });
+ });
+});
diff --git a/src/common/utils/paginate.ts b/src/common/utils/paginate.ts
index c4fc27a77..f38b77f37 100644
--- a/src/common/utils/paginate.ts
+++ b/src/common/utils/paginate.ts
@@ -7,6 +7,16 @@ export interface ListOptions {
offset?: number;
}
+/** Normalize a query/list window for both in-memory slicing and database skip/take. */
+export function resolveListWindow(limit?: number, offset?: number): { limit: number; offset: number } {
+ const normalizedOffset = typeof offset === 'number' && Number.isFinite(offset) ? Math.max(Math.trunc(offset), 0) : 0;
+ const normalizedLimit =
+ typeof limit === 'number' && Number.isFinite(limit)
+ ? Math.min(Math.max(Math.trunc(limit), 1), DEFAULT_LIST_LIMIT)
+ : DEFAULT_LIST_LIMIT;
+ return { limit: normalizedLimit, offset: normalizedOffset };
+}
+
/**
* Bound an in-memory list for an HTTP response.
*
@@ -21,10 +31,6 @@ export interface ListOptions {
* to in-process callers (e.g. plugins), so this never narrows what those consumers see.
*/
export function paginate<T>(items: T[], limit?: number, offset?: number): T[] {
- const off = typeof offset === 'number' && Number.isFinite(offset) ? Math.max(Math.trunc(offset), 0) : 0;
- const lim =
- typeof limit === 'number' && Number.isFinite(limit)
- ? Math.min(Math.max(Math.trunc(limit), 1), DEFAULT_LIST_LIMIT)
- : DEFAULT_LIST_LIMIT;
+ const { limit: lim, offset: off } = resolveListWindow(limit, offset);
return items.slice(off, off + lim);
}
diff --git a/src/common/utils/secret-file.spec.ts b/src/common/utils/secret-file.spec.ts
index 36843daa6..2daab685a 100644
--- a/src/common/utils/secret-file.spec.ts
+++ b/src/common/utils/secret-file.spec.ts
@@ -1,4 +1,4 @@
-import { mkdtempSync, rmSync, statSync, writeFileSync } from 'fs';
+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { writeSecretFile } from './secret-file';
@@ -13,19 +13,29 @@ describe('writeSecretFile', () => {
});
const mode = (p: string): number => statSync(p).mode & 0o777;
+ const expectOwnerOnly = (p: string): void => {
+ expect(existsSync(p)).toBe(true);
+ if (process.platform !== 'win32') {
+ expect(mode(p) & 0o077).toBe(0);
+ }
+ };
it('writes a new secret file owner-only (no group/other access)', () => {
const p = join(dir, 'secret');
writeSecretFile(p, 'topsecret');
- expect(mode(p) & 0o077).toBe(0);
+ expectOwnerOnly(p);
+ expect(readFileSync(p, 'utf8')).toBe('topsecret');
});
it('tightens an already-existing world-readable file (writeFileSync mode only applies on create)', () => {
const p = join(dir, 'legacy');
writeFileSync(p, 'old', { mode: 0o644 });
- expect(mode(p) & 0o077).not.toBe(0); // precondition: loose
+ if (process.platform !== 'win32') {
+ expect(mode(p) & 0o077).not.toBe(0); // precondition: loose
+ }
writeSecretFile(p, 'new');
- expect(mode(p) & 0o077).toBe(0);
+ expectOwnerOnly(p);
+ expect(readFileSync(p, 'utf8')).toBe('new');
});
});
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index 33f8fd9f1..ee87b91ba 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -6,6 +6,7 @@ export default () => ({
host: process.env.REDIS_HOST || 'localhost',
port: parseInt(process.env.REDIS_PORT || '6379', 10),
password: process.env.REDIS_PASSWORD,
+ connectTimeoutMs: parseInt(process.env.REDIS_CONNECT_TIMEOUT_MS || '5000', 10),
},
// Queue configuration
@@ -84,6 +85,12 @@ export default () => ({
},
},
+ sessions: {
+ // 0 = unlimited/backwards-compatible. Set to a positive integer to cap concurrently running or
+ // initializing WhatsApp engines, which protects memory/Chromium-constrained deployments.
+ maxConcurrent: parseInt(process.env.MAX_CONCURRENT_SESSIONS || '0', 10),
+ },
+
// Webhook configuration
webhook: {
timeout: parseInt(process.env.WEBHOOK_TIMEOUT || '10000', 10),
diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.ts
index 4936696fc..b04e6f285 100644
--- a/src/config/env.validation.spec.ts
+++ b/src/config/env.validation.spec.ts
@@ -36,14 +36,22 @@ describe('validateEnv', () => {
expect(() => validateEnv({ STORAGE_TYPE: 's3' })).not.toThrow();
});
- it('rejects a non-integer rate-limit / webhook / pool-size value (a NaN silently disables throttling)', () => {
+ it('rejects a non-integer rate-limit / webhook / pool-size / redis-timeout / session-cap value', () => {
expect(() => validateEnv({ RATE_LIMIT_SHORT_LIMIT: 'abc' })).toThrow(/RATE_LIMIT_SHORT_LIMIT/);
expect(() => validateEnv({ WEBHOOK_TIMEOUT: '10s' })).toThrow(/WEBHOOK_TIMEOUT/);
expect(() => validateEnv({ DATABASE_POOL_SIZE: '1.5' })).toThrow(/DATABASE_POOL_SIZE/);
+ expect(() => validateEnv({ REDIS_CONNECT_TIMEOUT_MS: 'soon' })).toThrow(/REDIS_CONNECT_TIMEOUT_MS/);
+ expect(() => validateEnv({ MAX_CONCURRENT_SESSIONS: 'many' })).toThrow(/MAX_CONCURRENT_SESSIONS/);
expect(() => validateEnv({ RATE_LIMIT_LONG_TTL: '-5' })).toThrow(/RATE_LIMIT_LONG_TTL/);
// valid integers (and unset) still pass
expect(() =>
- validateEnv({ RATE_LIMIT_SHORT_LIMIT: '10', WEBHOOK_TIMEOUT: '10000', DATABASE_POOL_SIZE: '10' }),
+ validateEnv({
+ RATE_LIMIT_SHORT_LIMIT: '10',
+ WEBHOOK_TIMEOUT: '10000',
+ DATABASE_POOL_SIZE: '10',
+ REDIS_CONNECT_TIMEOUT_MS: '5000',
+ MAX_CONCURRENT_SESSIONS: '0',
+ }),
).not.toThrow();
expect(() => validateEnv({})).not.toThrow();
});
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index 2e2a4f497..8e08b602e 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -89,6 +89,8 @@ export function validateEnv(config: EnvConfig): EnvConfig {
'WEBHOOK_MAX_RETRIES',
'WEBHOOK_RETRY_DELAY',
'DATABASE_POOL_SIZE',
+ 'REDIS_CONNECT_TIMEOUT_MS',
+ 'MAX_CONCURRENT_SESSIONS',
]) {
checkNonNegativeInt(key);
}
diff --git a/src/core/agent-tools/tools/session.tools.ts b/src/core/agent-tools/tools/session.tools.ts
index 50df4e1d6..5507a86df 100644
--- a/src/core/agent-tools/tools/session.tools.ts
+++ b/src/core/agent-tools/tools/session.tools.ts
@@ -12,11 +12,16 @@ export function sessionTools(session: SessionService): ToolDescriptor[] {
{
name: 'SessionFindAll',
description:
- 'List the WhatsApp sessions this API key may access (id, name, status). Use to discover available sessions before calling session-scoped tools.',
+ 'List the WhatsApp sessions this API key may access (id, name, status). Use to discover available sessions before calling session-scoped tools. Supports limit/offset paging.',
tier: 'read',
- inputSchema: z.object({}),
- handler: (_input, apiKey) =>
- session.findAll(apiKey.allowedSessions).then(ss => ss.map(s => SessionResponseDto.fromEntity(s))),
+ inputSchema: z.object({
+ limit: z.number().int().min(1).max(1000).optional(),
+ offset: z.number().int().min(0).optional(),
+ }),
+ handler: (input: { limit?: number; offset?: number }, apiKey) =>
+ session
+ .findAll(apiKey.allowedSessions, { limit: input.limit, offset: input.offset })
+ .then(ss => ss.map(s => SessionResponseDto.fromEntity(s))),
},
{
name: 'SessionFindOne',
diff --git a/src/core/agent-tools/tools/webhook.tools.ts b/src/core/agent-tools/tools/webhook.tools.ts
index f6b643c97..87f9c58cb 100644
--- a/src/core/agent-tools/tools/webhook.tools.ts
+++ b/src/core/agent-tools/tools/webhook.tools.ts
@@ -10,12 +10,18 @@ export function webhookTools(webhook: WebhookService): ToolDescriptor[] {
return [
{
name: 'WebhooksList',
- description: 'List all webhooks the API key is allowed to see, across all its accessible sessions.',
+ description:
+ 'List all webhooks the API key is allowed to see, across all its accessible sessions. Supports limit/offset paging.',
tier: 'read',
requiredRole: ApiKeyRole.OPERATOR,
- inputSchema: z.object({}),
- handler: (_input, apiKey) =>
- webhook.findAll(apiKey.allowedSessions).then(ws => WebhookResponseDto.fromEntities(ws)),
+ inputSchema: z.object({
+ limit: z.number().int().min(1).max(1000).optional(),
+ offset: z.number().int().min(0).optional(),
+ }),
+ handler: (input: { limit?: number; offset?: number }, apiKey) =>
+ webhook
+ .findAll(apiKey.allowedSessions, { limit: input.limit, offset: input.offset })
+ .then(ws => WebhookResponseDto.fromEntities(ws)),
},
{
name: 'WebhookFindBySession',
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index 1f4736331..b62cecd88 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -180,8 +180,12 @@ describe('PluginLoaderService — enable/config persistence', () => {
it('writes registry.json without group/other access (plugin config can hold secrets)', () => {
loader.registerBuiltInPlugin(manifest, {}, { apiKey: 'secret' });
- const mode = fs.statSync(path.join(tmpDir, 'plugins', 'registry.json')).mode & 0o777;
- expect(mode & 0o077).toBe(0);
+ const registryPath = path.join(tmpDir, 'plugins', 'registry.json');
+ expect(fs.existsSync(registryPath)).toBe(true);
+ if (process.platform !== 'win32') {
+ const mode = fs.statSync(registryPath).mode & 0o777;
+ expect(mode & 0o077).toBe(0);
+ }
});
it('restores the operator config on the next load instead of resetting to the default', () => {
diff --git a/src/core/plugins/plugin-storage.service.spec.ts b/src/core/plugins/plugin-storage.service.spec.ts
index 3eec8fcb9..188d1779b 100644
--- a/src/core/plugins/plugin-storage.service.spec.ts
+++ b/src/core/plugins/plugin-storage.service.spec.ts
@@ -27,6 +27,13 @@ describe('PluginStorageService sandboxed per-plugin storage containment', () =>
fs.rmSync(dataDir, { recursive: true, force: true });
});
+ const expectOwnerOnly = (p: string, expected: number): void => {
+ expect(fs.existsSync(p)).toBe(true);
+ if (process.platform !== 'win32') {
+ expect(fs.statSync(p).mode & 0o777).toBe(expected);
+ }
+ };
+
it('round-trips a normal key', async () => {
await storage.set('state', { a: 1 });
expect(await storage.get('state')).toEqual({ a: 1 });
@@ -37,8 +44,10 @@ describe('PluginStorageService sandboxed per-plugin storage containment', () =>
it('creates the per-plugin dir 0o700 and data files 0o600 (persisted secrets not world-readable)', async () => {
await storage.set('secret', { token: 'shh' });
const pluginDataDir = path.join(dataDir, 'plugins', pluginId);
- expect(fs.statSync(pluginDataDir).mode & 0o777).toBe(0o700);
- expect(fs.statSync(path.join(pluginDataDir, 'secret.json')).mode & 0o777).toBe(0o600);
+ const secretFile = fs.readdirSync(pluginDataDir).find(f => f.endsWith('.json'));
+ expect(secretFile).toBeDefined();
+ expectOwnerOnly(pluginDataDir, 0o700);
+ expectOwnerOnly(path.join(pluginDataDir, secretFile as string), 0o600);
});
it('is atomic: a write that fails mid-way leaves the previous file intact (no partial overwrite)', async () => {
@@ -67,6 +76,55 @@ describe('PluginStorageService sandboxed per-plugin storage containment', () =>
it('preserves JID-style keys containing : @ . -', async () => {
await storage.set('group:sess-1:[email protected]', { announced: true });
expect(await storage.get('group:sess-1:[email protected]')).toEqual({ announced: true });
+ expect(await storage.list()).toContain('group:sess-1:[email protected]');
+
+ const pluginDataDir = path.join(dataDir, 'plugins', pluginId);
+ const files = fs.readdirSync(pluginDataDir).filter(f => f.endsWith('.json'));
+ expect(files.some(f => f.includes(':'))).toBe(false);
+ });
+
+ it('reads legacy plain-key files for backwards compatibility', async () => {
+ const pluginDataDir = path.join(dataDir, 'plugins', pluginId);
+ fs.writeFileSync(path.join(pluginDataDir, 'legacy.json'), JSON.stringify({ old: true }));
+
+ expect(await storage.get('legacy')).toEqual({ old: true });
+ expect(await storage.list()).toContain('legacy');
+ });
+
+ it('migrates a legacy plain-key file off on the next set (no stale shadow copy)', async () => {
+ const pluginDataDir = path.join(dataDir, 'plugins', pluginId);
+ const legacyFile = path.join(pluginDataDir, 'legacy.json');
+ fs.writeFileSync(legacyFile, JSON.stringify({ old: true }));
+
+ await storage.set('legacy', { fresh: true });
+
+ expect(fs.existsSync(legacyFile)).toBe(false); // stale legacy copy removed
+ expect(await storage.get('legacy')).toEqual({ fresh: true });
+ const jsonFiles = fs.readdirSync(pluginDataDir).filter(f => f.endsWith('.json'));
+ expect(jsonFiles).toHaveLength(1); // only the encoded file remains
+ });
+
+ it('deletes a legacy plain-key file', async () => {
+ const pluginDataDir = path.join(dataDir, 'plugins', pluginId);
+ fs.writeFileSync(path.join(pluginDataDir, 'legacy.json'), JSON.stringify({ old: true }));
+
+ await storage.delete('legacy');
+
+ expect(fs.existsSync(path.join(pluginDataDir, 'legacy.json'))).toBe(false);
+ expect(await storage.get('legacy')).toBeNull();
+ });
+
+ it('does not mangle a literal legacy filename that happens to start with "key-"', async () => {
+ const pluginDataDir = path.join(dataDir, 'plugins', pluginId);
+ // A pre-encoding plugin could have stored a key literally named "key-zzz" -> key-zzz.json.
+ fs.writeFileSync(path.join(pluginDataDir, 'key-zzz.json'), JSON.stringify({ v: 1 }));
+
+ expect(await storage.list()).toContain('key-zzz'); // returned verbatim, not base64-decoded into garbage
+ expect(await storage.get('key-zzz')).toEqual({ v: 1 });
+ });
+
+ it('rejects a key containing a control character (NUL) on set', async () => {
+ await expect(storage.set('a\u0000b', { x: 1 })).rejects.toThrow(/Unsafe plugin storage key/);
});
it('rejects a traversing set and writes nothing outside the plugin dir', async () => {
diff --git a/src/core/plugins/plugin-storage.service.ts b/src/core/plugins/plugin-storage.service.ts
index 954e42d4b..ec10c5806 100644
--- a/src/core/plugins/plugin-storage.service.ts
+++ b/src/core/plugins/plugin-storage.service.ts
@@ -3,7 +3,7 @@ import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';
import { createLogger } from '../../common/services/logger.service';
-import { isPathWithin } from '../../common/utils/path-safety';
+import { isPathWithin, isSafeStorageKey } from '../../common/utils/path-safety';
import { PluginStatus, PluginStorage, PluginRegistryEntry } from './plugin.interfaces';
/** Unique-per-write counter so concurrent writes to the same key don't collide on the temp file. */
@@ -29,6 +29,29 @@ function atomicWriteFileSync(filePath: string, data: string, options?: { mode?:
}
}
+const ENCODED_KEY_PREFIX = 'key-';
+
+function encodeStorageKey(key: string): string {
+ return (
+ ENCODED_KEY_PREFIX +
+ Buffer.from(key, 'utf8').toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '')
+ );
+}
+
+function decodeStorageFileName(stem: string): string | null {
+ if (!stem.startsWith(ENCODED_KEY_PREFIX)) return null;
+ const encoded = stem.slice(ENCODED_KEY_PREFIX.length);
+ const padded = encoded.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (encoded.length % 4)) % 4);
+ try {
+ const decoded = Buffer.from(padded, 'base64').toString('utf8');
+ // Only accept it as one of our base64url-encoded names if it round-trips exactly. A literal legacy
+ // filename that merely starts with `key-` would otherwise be mis-decoded into a garbage key.
+ return encodeStorageKey(decoded) === stem ? decoded : null;
+ } catch {
+ return null;
+ }
+}
+
@Injectable()
export class PluginStorageService {
private readonly logger = createLogger('PluginStorageService');
@@ -185,11 +208,21 @@ export class PluginStorageService {
const logger = this.logger;
- // Containment: a plugin storage key must resolve INSIDE its own sandbox dir. path.join normalizes
- // `..`, so a key like `../../x` would otherwise escape and clobber another plugin's data, the
- // registry, or .env.generated. Reject anything that escapes; JID chars (`:`,`@`,`.`,`-`) are fine.
- const resolveKeyPath = (key: string): string | null =>
- isPathWithin(pluginDataDir, `${key}.json`) ? path.join(pluginDataDir, `${key}.json`) : null;
+ // Containment: validate the logical key, then encode it to a filesystem-safe filename. This keeps
+ // JID-style keys (`group:sess-1:[email protected]`) portable on Windows while still rejecting traversal.
+ const resolveKeyPath = (key: string): string | null => {
+ if (!isSafeStorageKey(key)) return null;
+ const fileName = `${encodeStorageKey(key)}.json`;
+ return isPathWithin(pluginDataDir, fileName) ? path.join(pluginDataDir, fileName) : null;
+ };
+
+ // Backward compatibility for pre-encoded storage files (`state.json`). Reads/deletes consult it,
+ // but new writes always use the encoded filename above.
+ const resolveLegacyKeyPath = (key: string): string | null => {
+ if (!isSafeStorageKey(key)) return null;
+ const fileName = `${key}.json`;
+ return isPathWithin(pluginDataDir, fileName) ? path.join(pluginDataDir, fileName) : null;
+ };
return {
get: <T = unknown>(key: string): Promise<T | null> => {
@@ -199,9 +232,13 @@ export class PluginStorageService {
return Promise.resolve(null);
}
try {
- if (fs.existsSync(filePath)) {
- const content = fs.readFileSync(filePath, 'utf-8');
- return Promise.resolve(JSON.parse(content) as T);
+ const legacyPath = resolveLegacyKeyPath(key);
+ const candidates = legacyPath && legacyPath !== filePath ? [filePath, legacyPath] : [filePath];
+ for (const candidate of candidates) {
+ if (fs.existsSync(candidate)) {
+ const content = fs.readFileSync(candidate, 'utf-8');
+ return Promise.resolve(JSON.parse(content) as T);
+ }
}
} catch (error) {
logger.error(`Failed to read plugin data: ${pluginId}/${key}`, String(error));
@@ -212,7 +249,7 @@ export class PluginStorageService {
set: <T = unknown>(key: string, value: T): Promise<void> => {
const filePath = resolveKeyPath(key);
if (!filePath) {
- return Promise.reject(new Error(`Unsafe plugin storage key (escapes sandbox): ${key}`));
+ return Promise.reject(new Error(`Unsafe plugin storage key: ${key}`));
}
try {
// 0o600 (owner-only): a plugin-persisted secret must not land in a group/other-readable file.
@@ -220,6 +257,11 @@ export class PluginStorageService {
// pre-existed (writeFileSync mode only applies on create). Mirrors saveRegistry's hardening.
atomicWriteFileSync(filePath, JSON.stringify(value, null, 2), { mode: 0o600 });
fs.chmodSync(filePath, 0o600);
+ // Migrate off any pre-encoding legacy file for this key so a stale copy can't shadow reads/lists.
+ const legacyPath = resolveLegacyKeyPath(key);
+ if (legacyPath && legacyPath !== filePath && fs.existsSync(legacyPath)) {
+ fs.unlinkSync(legacyPath);
+ }
return Promise.resolve();
} catch (error) {
logger.error(`Failed to write plugin data: ${pluginId}/${key}`, String(error));
@@ -230,11 +272,15 @@ export class PluginStorageService {
delete: (key: string): Promise<void> => {
const filePath = resolveKeyPath(key);
if (!filePath) {
- return Promise.reject(new Error(`Unsafe plugin storage key (escapes sandbox): ${key}`));
+ return Promise.reject(new Error(`Unsafe plugin storage key: ${key}`));
}
try {
- if (fs.existsSync(filePath)) {
- fs.unlinkSync(filePath);
+ const legacyPath = resolveLegacyKeyPath(key);
+ const candidates = legacyPath && legacyPath !== filePath ? [filePath, legacyPath] : [filePath];
+ for (const candidate of candidates) {
+ if (fs.existsSync(candidate)) {
+ fs.unlinkSync(candidate);
+ }
}
return Promise.resolve();
} catch (error) {
@@ -246,7 +292,14 @@ export class PluginStorageService {
list: (prefix?: string): Promise<string[]> => {
try {
const files = fs.readdirSync(pluginDataDir);
- let keys = files.filter(f => f.endsWith('.json')).map(f => f.replace('.json', ''));
+ let keys = Array.from(
+ new Set(
+ files
+ .filter(f => f.endsWith('.json'))
+ .map(f => f.slice(0, -'.json'.length))
+ .map(stem => decodeStorageFileName(stem) ?? stem),
+ ),
+ );
if (prefix) {
keys = keys.filter(k => k.startsWith(prefix));
diff --git a/src/database/data-source.ts b/src/database/data-source.ts
index b099e8674..1d0f7f225 100644
--- a/src/database/data-source.ts
+++ b/src/database/data-source.ts
@@ -1,4 +1,5 @@
import { DataSource } from 'typeorm';
+import * as path from 'path';
import { loadCliEnv } from './load-cli-env';
// Load env with the same precedence as the app (process.env > .env > data/.env.generated), so the
@@ -7,6 +8,8 @@ loadCliEnv();
const dbType = process.env.DATABASE_TYPE || 'sqlite';
+const sourceGlob = (...segments: string[]): string => path.join(__dirname, ...segments).replace(/\\/g, '/');
+
// SQLite configuration
const sqliteDataSource = new DataSource({
type: 'sqlite',
@@ -15,13 +18,13 @@ const sqliteDataSource = new DataSource({
// runtime data connection (app.module.ts). A broad '**' glob would also sweep in the main-owned
// auth/audit entities and pollute `migration:generate` against the data DB with their DDL.
entities: [
- __dirname + '/../modules/session/**/*.entity{.ts,.js}',
- __dirname + '/../modules/webhook/**/*.entity{.ts,.js}',
- __dirname + '/../modules/message/**/*.entity{.ts,.js}',
- __dirname + '/../modules/template/**/*.entity{.ts,.js}',
- __dirname + '/../engine/**/*.entity{.ts,.js}',
+ sourceGlob('..', 'modules', 'session', '**', '*.entity{.ts,.js}'),
+ sourceGlob('..', 'modules', 'webhook', '**', '*.entity{.ts,.js}'),
+ sourceGlob('..', 'modules', 'message', '**', '*.entity{.ts,.js}'),
+ sourceGlob('..', 'modules', 'template', '**', '*.entity{.ts,.js}'),
+ sourceGlob('..', 'engine', '**', '*.entity{.ts,.js}'),
],
- migrations: [__dirname + '/migrations/*{.ts,.js}'],
+ migrations: [sourceGlob('migrations', '*{.ts,.js}')],
synchronize: false,
logging: process.env.DATABASE_LOGGING === 'true',
});
@@ -38,13 +41,13 @@ export const postgresDataSource = new DataSource({
// runtime data connection (app.module.ts). A broad '**' glob would also sweep in the main-owned
// auth/audit entities and pollute `migration:generate` against the data DB with their DDL.
entities: [
- __dirname + '/../modules/session/**/*.entity{.ts,.js}',
- __dirname + '/../modules/webhook/**/*.entity{.ts,.js}',
- __dirname + '/../modules/message/**/*.entity{.ts,.js}',
- __dirname + '/../modules/template/**/*.entity{.ts,.js}',
- __dirname + '/../engine/**/*.entity{.ts,.js}',
+ sourceGlob('..', 'modules', 'session', '**', '*.entity{.ts,.js}'),
+ sourceGlob('..', 'modules', 'webhook', '**', '*.entity{.ts,.js}'),
+ sourceGlob('..', 'modules', 'message', '**', '*.entity{.ts,.js}'),
+ sourceGlob('..', 'modules', 'template', '**', '*.entity{.ts,.js}'),
+ sourceGlob('..', 'engine', '**', '*.entity{.ts,.js}'),
],
- migrations: [__dirname + '/migrations/*{.ts,.js}'],
+ migrations: [sourceGlob('migrations', '*{.ts,.js}')],
synchronize: false, // Never auto-sync in production
logging: process.env.DATABASE_LOGGING === 'true',
ssl:
diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.ts
index 034db296a..118730ac1 100644
--- a/src/modules/queue/processors/webhook.processor.ts
+++ b/src/modules/queue/processors/webhook.processor.ts
@@ -5,6 +5,7 @@ import { ConfigService } from '@nestjs/config';
import { Repository } from 'typeorm';
import { createLogger } from '../../../common/services/logger.service';
import { QUEUE_NAMES } from '../queue-names';
+import { workerConnectionOptions } from '../redis-connection';
import { WebhookJobData } from '../../webhook/webhook.service';
import { Webhook } from '../../webhook/entities/webhook.entity';
import { HookManager } from '../../../core/hooks';
@@ -17,7 +18,9 @@ export interface WebhookJobResult {
responseTime: number;
}
-@Processor(QUEUE_NAMES.WEBHOOK)
+// Override the Worker's connection so it does NOT inherit the producer's `enableOfflineQueue: false`
+// from the shared BullModule connection — the Worker must tolerate a brief Redis reconnect.
+@Processor(QUEUE_NAMES.WEBHOOK, { connection: workerConnectionOptions() })
export class WebhookProcessor extends WorkerHost {
private readonly logger = createLogger('WebhookProcessor');
diff --git a/src/modules/queue/queue.module.ts b/src/modules/queue/queue.module.ts
index b7bc1a5ce..b2bc1f227 100644
--- a/src/modules/queue/queue.module.ts
+++ b/src/modules/queue/queue.module.ts
@@ -27,6 +27,8 @@ export { QUEUE_NAMES } from './queue-names';
host: configService.get<string>('redis.host', 'localhost'),
port: configService.get<number>('redis.port', 6379),
password: configService.get<string>('redis.password'),
+ connectTimeout: configService.get<number>('redis.connectTimeoutMs', 5000),
+ enableOfflineQueue: false,
},
}),
}),
diff --git a/src/modules/queue/redis-connection.spec.ts b/src/modules/queue/redis-connection.spec.ts
new file mode 100644
index 000000000..7cb87b4ee
--- /dev/null
+++ b/src/modules/queue/redis-connection.spec.ts
@@ -0,0 +1,42 @@
+import { workerConnectionOptions } from './redis-connection';
+
+describe('workerConnectionOptions (webhook Worker connection)', () => {
+ const ORIGINAL_ENV = process.env;
+
+ afterEach(() => {
+ process.env = ORIGINAL_ENV;
+ });
+
+ it('does NOT disable the offline queue — the Worker must tolerate a brief Redis reconnect', () => {
+ // The producer sets enableOfflineQueue:false for fast-fail; the Worker must keep ioredis's default
+ // (true). Asserting it is absent guards against the regression where the Worker inherited the
+ // producer-only fast-fail from the shared connection and threw "Stream isn't writeable" on a blip.
+ const opts = workerConnectionOptions() as Record<string, unknown>;
+ expect(opts.enableOfflineQueue).toBeUndefined();
+ });
+
+ it('reads host/port/password/connectTimeout from env with safe defaults', () => {
+ process.env = { ...ORIGINAL_ENV };
+ delete process.env.REDIS_HOST;
+ delete process.env.REDIS_PORT;
+ delete process.env.REDIS_PASSWORD;
+ delete process.env.REDIS_CONNECT_TIMEOUT_MS;
+ expect(workerConnectionOptions()).toEqual({
+ host: 'localhost',
+ port: 6379,
+ password: undefined,
+ connectTimeout: 5000,
+ });
+
+ process.env.REDIS_HOST = 'redis.internal';
+ process.env.REDIS_PORT = '6380';
+ process.env.REDIS_PASSWORD = 'secret';
+ process.env.REDIS_CONNECT_TIMEOUT_MS = '1234';
+ expect(workerConnectionOptions()).toEqual({
+ host: 'redis.internal',
+ port: 6380,
+ password: 'secret',
+ connectTimeout: 1234,
+ });
+ });
+});
diff --git a/src/modules/queue/redis-connection.ts b/src/modules/queue/redis-connection.ts
new file mode 100644
index 000000000..c0d9acf38
--- /dev/null
+++ b/src/modules/queue/redis-connection.ts
@@ -0,0 +1,30 @@
+/**
+ * BullMQ Redis connection options for the WEBHOOK queue's Worker.
+ *
+ * The webhook PRODUCER (the Queue) is configured on the shared `BullModule.forRootAsync` connection
+ * with `enableOfflineQueue: false`, so `queue.add()` fails fast when Redis is unreachable and the
+ * dispatch path can fall back to direct delivery instead of buffering forever.
+ *
+ * The WORKER must NOT inherit that producer-only fast-fail. Its blocking/internal commands
+ * (moveToActive, lock renewal) need to tolerate a brief reconnect during a Redis blip/failover;
+ * BullMQ explicitly recommends leaving the offline queue enabled for Worker connections. Because
+ * @nestjs/bullmq otherwise builds the Worker from the same shared connection, the WebhookProcessor
+ * overrides its connection with these options — host/port/password/timeout identical to the producer
+ * (same env vars, same defaults as configuration.ts), but with the offline queue left at ioredis's
+ * default of `true` so a transient outage no longer throws "Stream isn't writeable" and stalls jobs.
+ */
+export interface WorkerConnectionOptions {
+ host: string;
+ port: number;
+ password?: string;
+ connectTimeout: number;
+}
+
+export function workerConnectionOptions(): WorkerConnectionOptions {
+ return {
+ host: process.env.REDIS_HOST || 'localhost',
+ port: parseInt(process.env.REDIS_PORT || '6379', 10),
+ password: process.env.REDIS_PASSWORD,
+ connectTimeout: parseInt(process.env.REDIS_CONNECT_TIMEOUT_MS || '5000', 10),
+ };
+}
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 72f9a90b2..619b604e7 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -58,10 +58,19 @@ export class SessionController {
description: 'List of sessions',
type: [SessionResponseDto],
})
- async findAll(@CurrentApiKey() apiKey?: ApiKey): Promise<SessionResponseDto[]> {
+ @ApiQuery({ name: 'limit', required: false, description: 'Max sessions to return (1-1000, default 1000)' })
+ @ApiQuery({ name: 'offset', required: false, description: 'Number of sessions to skip (for paging)' })
+ async findAll(
+ @CurrentApiKey() apiKey?: ApiKey,
+ @Query('limit') limit?: string,
+ @Query('offset') offset?: string,
+ ): Promise<SessionResponseDto[]> {
// Scope to the key's allowedSessions so a session-restricted key cannot enumerate every
// session. A null/empty allowlist (e.g. ADMIN) still lists all.
- const sessions = await this.sessionService.findAll(apiKey?.allowedSessions);
+ const sessions = await this.sessionService.findAll(apiKey?.allowedSessions, {
+ limit: limit ? parseInt(limit, 10) : undefined,
+ offset: offset ? parseInt(offset, 10) : undefined,
+ });
return sessions.map(s => this.transformSession(s));
}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 6ebbdacd6..36ec5fce0 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -2,6 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';
import { Repository, DataSource, In } from 'typeorm';
import { NotFoundException, ConflictException, BadRequestException } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
import { SessionService, ACK_RECONCILE_DELAY_MS } from './session.service';
import { Session, SessionStatus } from './entities/session.entity';
import { Message, MessageStatus } from '../message/entities/message.entity';
@@ -39,6 +40,7 @@ describe('SessionService', () => {
let eventsGateway: jest.Mocked<Partial<EventsGateway>>;
let webhookService: jest.Mocked<Partial<WebhookService>>;
let hookManager: jest.Mocked<Partial<HookManager>>;
+ let configService: jest.Mocked<Partial<ConfigService>>;
let mockEngine: Record<string, jest.Mock>;
beforeEach(async () => {
@@ -109,6 +111,10 @@ describe('SessionService', () => {
execute: jest.fn().mockResolvedValue({ continue: true, data: {} }),
};
+ configService = {
+ get: jest.fn().mockImplementation(<T>(_key: string, def?: T): T => def as T),
+ };
+
const module: TestingModule = await Test.createTestingModule({
providers: [
SessionService,
@@ -128,6 +134,7 @@ describe('SessionService', () => {
{ provide: EventsGateway, useValue: eventsGateway },
{ provide: WebhookService, useValue: webhookService },
{ provide: HookManager, useValue: hookManager },
+ { provide: ConfigService, useValue: configService },
],
}).compile();
@@ -261,7 +268,7 @@ describe('SessionService', () => {
const result = await service.findAll();
expect(result).toHaveLength(2);
- expect(repository.find).toHaveBeenCalledWith({ order: { createdAt: 'DESC' } });
+ expect(repository.find).toHaveBeenCalledWith({ order: { createdAt: 'DESC' }, take: 1000, skip: 0 });
});
it('scopes results to a session-restricted key', async () => {
@@ -272,6 +279,8 @@ describe('SessionService', () => {
expect(repository.find).toHaveBeenCalledWith({
where: { id: In(['sess-1', 'sess-2']) },
order: { createdAt: 'DESC' },
+ take: 1000,
+ skip: 0,
});
});
@@ -282,8 +291,21 @@ describe('SessionService', () => {
await service.findAll([]);
expect(repository.find).toHaveBeenCalledTimes(2);
- expect(repository.find).toHaveBeenNthCalledWith(1, { order: { createdAt: 'DESC' } });
- expect(repository.find).toHaveBeenNthCalledWith(2, { order: { createdAt: 'DESC' } });
+ expect(repository.find).toHaveBeenNthCalledWith(1, { order: { createdAt: 'DESC' }, take: 1000, skip: 0 });
+ expect(repository.find).toHaveBeenNthCalledWith(2, { order: { createdAt: 'DESC' }, take: 1000, skip: 0 });
+ });
+
+ it('applies bounded pagination to the database query', async () => {
+ (repository.find as jest.Mock).mockResolvedValue([]);
+
+ await service.findAll(['sess-1'], { limit: 5000, offset: -5 });
+
+ expect(repository.find).toHaveBeenCalledWith({
+ where: { id: In(['sess-1']) },
+ order: { createdAt: 'DESC' },
+ take: 1000,
+ skip: 0,
+ });
});
});
@@ -332,6 +354,45 @@ describe('SessionService', () => {
// Engine is now in the map, so a second start is 'already started' (not wedged at 'starting').
await expect(service.start('sess-uuid-1')).rejects.toBeInstanceOf(BadRequestException);
});
+
+ it('rejects starting a new session when MAX_CONCURRENT_SESSIONS is reached', async () => {
+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | number => {
+ if (key === 'sessions.maxConcurrent') return 1;
+ return def as T;
+ });
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ id: 'sess-2' }));
+ const engines = (service as unknown as { engines: Map<string, unknown> }).engines;
+ engines.set('sess-1', mockEngine);
+
+ await expect(service.start('sess-2')).rejects.toThrow(/Maximum concurrent sessions reached/);
+ expect(engineFactory.create).not.toHaveBeenCalled();
+ });
+
+ it('does not double-count a still-initializing session against MAX_CONCURRENT_SESSIONS', async () => {
+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | number => {
+ if (key === 'sessions.maxConcurrent') return 2;
+ return def as T;
+ });
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ id: 'sess-2' }));
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (engineFactory.create as jest.Mock).mockClear().mockReturnValue(mockEngine);
+
+ const internals = service as unknown as {
+ engines: Map<string, unknown>;
+ initializingSessions: Set<string>;
+ };
+ // 'sess-1' is mid-initialize: present in BOTH sets (the real overlap window). Deduplicated active
+ // count is 1, below the cap of 2 — so starting 'sess-2' must be allowed. The old summed-size
+ // logic counted it as 2 (engines.size + initializingSessions.size) and would wrongly reject.
+ internals.engines.set('sess-1', mockEngine);
+ internals.initializingSessions.add('sess-1');
+
+ await expect(service.start('sess-2')).resolves.toBeDefined();
+ expect(engineFactory.create).toHaveBeenCalled();
+
+ internals.engines.clear();
+ internals.initializingSessions.clear();
+ });
});
describe('findByName', () => {
@@ -1416,13 +1477,21 @@ describe('SessionService', () => {
// ── getStats ──────────────────────────────────────────────────────
describe('getStats', () => {
+ const makeStatsQb = (rows: Array<{ status: string; count: string }>) => ({
+ select: jest.fn().mockReturnThis(),
+ addSelect: jest.fn().mockReturnThis(),
+ where: jest.fn().mockReturnThis(),
+ groupBy: jest.fn().mockReturnThis(),
+ getRawMany: jest.fn().mockResolvedValue(rows),
+ });
+
it('should return correct session statistics', async () => {
- const sessions = [
- createMockSession({ status: SessionStatus.READY }),
- createMockSession({ id: 'sess-2', status: SessionStatus.READY }),
- createMockSession({ id: 'sess-3', status: SessionStatus.DISCONNECTED }),
- ];
- (repository.find as jest.Mock).mockResolvedValue(sessions);
+ (repository.createQueryBuilder as jest.Mock) = jest.fn().mockReturnValue(
+ makeStatsQb([
+ { status: SessionStatus.READY, count: '2' },
+ { status: SessionStatus.DISCONNECTED, count: '1' },
+ ]),
+ );
const stats = await service.getStats();
@@ -1433,17 +1502,31 @@ describe('SessionService', () => {
expect(stats.memoryUsage).toBeDefined();
});
+ it('counts every session via a grouped COUNT, not the bounded findAll (no undercount past the cap)', async () => {
+ const findSpy = repository.find as jest.Mock;
+ findSpy.mockClear();
+ (repository.createQueryBuilder as jest.Mock) = jest
+ .fn()
+ .mockReturnValue(makeStatsQb([{ status: SessionStatus.READY, count: '1500' }]));
+
+ const stats = await service.getStats();
+
+ // 1500 > DEFAULT_LIST_LIMIT (1000): the old findAll-based path would have capped total at 1000.
+ expect(stats.total).toBe(1500);
+ expect(stats.ready).toBe(1500);
+ expect(findSpy).not.toHaveBeenCalled();
+ });
+
it('scopes the stats to a restricted key (active counts only in-scope engines)', async () => {
- const findSpy = (repository.find as jest.Mock).mockResolvedValue([
- createMockSession({ id: 'sess-A', status: SessionStatus.READY }),
- ]);
+ const qb = makeStatsQb([{ status: SessionStatus.READY, count: '1' }]);
+ (repository.createQueryBuilder as jest.Mock) = jest.fn().mockReturnValue(qb);
const engines = (service as unknown as { engines: Map<string, unknown> }).engines;
engines.set('sess-A', {});
engines.set('sess-B', {}); // global engine the scoped key must NOT see counted
const stats = await service.getStats(['sess-A']);
- expect(findSpy).toHaveBeenCalled(); // scope threaded into findAll
+ expect(qb.where).toHaveBeenCalledWith('session.id IN (:...scope)', { scope: ['sess-A'] });
expect(stats.total).toBe(1);
expect(stats.active).toBe(1); // not 2 (global engines.size)
engines.clear();
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index d86b9becf..e59fe957b 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -6,7 +6,9 @@ import {
OnModuleDestroy,
OnModuleInit,
OnApplicationBootstrap,
+ Optional,
} from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
import { InjectRepository, InjectDataSource } from '@nestjs/typeorm';
import { Repository, In, Not, IsNull, DataSource, FindManyOptions } from 'typeorm';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
@@ -14,7 +16,7 @@ import { Session, SessionStatus } from './entities/session.entity';
import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';
import { CreateSessionDto } from './dto';
import { EngineFactory } from '../../engine/engine.factory';
-import { paginate, ListOptions } from '../../common/utils/paginate';
+import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
import {
IWhatsAppEngine,
@@ -82,6 +84,12 @@ export function clampReconnectDelay(rawDelay: number, baseDelay: number): number
return clampNumber(Number.isFinite(rawDelay) ? rawDelay : baseDelay, 0, RECONNECT_DELAY_CAP_MS);
}
+export function resolveMaxConcurrentSessions(configService?: Pick<ConfigService, 'get'>): number | null {
+ const configured = configService?.get<number>('sessions.maxConcurrent', 0) ?? 0;
+ if (!Number.isFinite(configured) || configured <= 0) return null;
+ return Math.floor(configured);
+}
+
@Injectable()
export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicationBootstrap {
private readonly logger = createLogger('SessionService');
@@ -133,6 +141,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
private readonly eventsGateway: EventsGateway,
private readonly webhookService: WebhookService,
private readonly hookManager: HookManager,
+ @Optional()
+ private readonly configService?: ConfigService,
) {}
/**
@@ -284,11 +294,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return saved;
}
- async findAll(allowedSessions?: string[] | null): Promise<Session[]> {
+ async findAll(allowedSessions?: string[] | null, opts: ListOptions = {}): Promise<Session[]> {
// A session-restricted key only lists its own sessions; an unrestricted key (null/empty
// allowlist) lists all — mirroring the ApiKeyGuard allowedSessions model so a scoped key
// cannot enumerate every session through this aggregate route.
- const options: FindManyOptions<Session> = { order: { createdAt: 'DESC' } };
+ const { limit, offset } = resolveListWindow(opts.limit, opts.offset);
+ const options: FindManyOptions<Session> = { order: { createdAt: 'DESC' }, take: limit, skip: offset };
if (allowedSessions && allowedSessions.length > 0) {
options.where = { id: In(allowedSessions) };
}
@@ -382,6 +393,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
if (this.initializingSessions.has(id)) {
throw new BadRequestException('Session is already starting');
}
+ const maxConcurrentSessions = resolveMaxConcurrentSessions(this.configService);
+ if (maxConcurrentSessions !== null) {
+ // Count each session once. A session mid-initialization is transiently in BOTH `engines` (set at
+ // the start of initializeEngine) and `initializingSessions` (until start()'s finally), so summing
+ // the two sizes would double-count it and falsely reject new starts at ~half the configured cap.
+ const activeCount = new Set<string>([...this.engines.keys(), ...this.initializingSessions]).size;
+ if (activeCount >= maxConcurrentSessions) {
+ throw new BadRequestException(`Maximum concurrent sessions reached (${maxConcurrentSessions})`);
+ }
+ }
this.initializingSessions.add(id);
try {
@@ -1298,17 +1319,31 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Scope to the caller's allowedSessions so a session-restricted key cannot enumerate the count /
// status distribution of sessions it has no rights to (matches the scoped GET /sessions route).
const scope = allowedSessions && allowedSessions.length > 0 ? allowedSessions : null;
- const sessions = await this.findAll(scope);
- const byStatus: Record<string, number> = {};
+ // Aggregate status counts in the database instead of loading every row. findAll() is bounded by
+ // DEFAULT_LIST_LIMIT for the HTTP routes, so reusing it here would silently undercount `total` and
+ // `byStatus` on deployments with more sessions than that cap. A grouped COUNT is correct at any
+ // scale and cheaper (no entity hydration).
+ const qb = this.sessionRepository
+ .createQueryBuilder('session')
+ .select('session.status', 'status')
+ .addSelect('COUNT(session.id)', 'count');
+ if (scope) {
+ qb.where('session.id IN (:...scope)', { scope });
+ }
+ const rows = await qb.groupBy('session.status').getRawMany<{ status: string; count: string }>();
- for (const session of sessions) {
- byStatus[session.status] = (byStatus[session.status] || 0) + 1;
+ const byStatus: Record<string, number> = {};
+ let total = 0;
+ for (const row of rows) {
+ const count = Number(row.count) || 0;
+ byStatus[row.status] = count;
+ total += count;
}
const memory = process.memoryUsage();
return {
- total: sessions.length,
+ total,
// engines is keyed by session id; a scoped key sees only its own running engines, not the global count.
active: scope ? [...this.engines.keys()].filter(id => scope.includes(id)).length : this.engines.size,
ready: byStatus[SessionStatus.READY] || 0,
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
index 071342be8..8933d4b06 100644
--- a/src/modules/webhook/webhook.service.spec.ts
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -13,7 +13,7 @@ jest.mock('undici', () => {
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { getQueueToken } from '@nestjs/bullmq';
-import { Repository } from 'typeorm';
+import { In, Repository } from 'typeorm';
import { NotFoundException, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as crypto from 'crypto';
@@ -195,7 +195,20 @@ describe('WebhookService', () => {
await service.findAll();
- expect(repository.find).toHaveBeenCalledWith({ order: { createdAt: 'DESC' } });
+ expect(repository.find).toHaveBeenCalledWith({ order: { createdAt: 'DESC' }, take: 1000, skip: 0 });
+ });
+
+ it('applies bounded pagination to cross-session listing', async () => {
+ (repository.find as jest.Mock).mockResolvedValue([]);
+
+ await service.findAll(['sess-1'], { limit: 5000, offset: -5 });
+
+ expect(repository.find).toHaveBeenCalledWith({
+ where: { sessionId: In(['sess-1']) },
+ order: { createdAt: 'DESC' },
+ take: 1000,
+ skip: 0,
+ });
});
});
@@ -666,6 +679,8 @@ describe('WebhookService', () => {
// ── dispatch (queue mode) ─────────────────────────────────────────
describe('dispatch (queue mode)', () => {
+ afterEach(() => (undiciFetch as jest.Mock).mockReset());
+
it('should add job to queue when queue is enabled', async () => {
// Create a new service with queue enabled
const queueModule: TestingModule = await Test.createTestingModule({
@@ -725,5 +740,60 @@ describe('WebhookService', () => {
}),
);
});
+
+ it('falls back to direct delivery when queue add fails', async () => {
+ const queueModule: TestingModule = await Test.createTestingModule({
+ providers: [
+ WebhookService,
+ { provide: getRepositoryToken(Webhook, 'data'), useValue: repository },
+ {
+ provide: ConfigService,
+ useValue: {
+ get: jest.fn().mockImplementation(<T>(key: string, def?: T): T | boolean | number => {
+ if (key === 'queue.enabled') return true;
+ if (key === 'webhook.retryDelay') return 5000;
+ if (key === 'webhook.timeout') return 25000;
+ return def as T;
+ }),
+ },
+ },
+ { provide: HookManager, useValue: hookManager },
+ { provide: getQueueToken(QUEUE_NAMES.WEBHOOK), useValue: webhookQueue },
+ ],
+ }).compile();
+
+ const queueService = queueModule.get<WebhookService>(WebhookService);
+ const webhook = createMockWebhook({ events: ['message.received'], retryCount: 1 });
+ const queuePayload: WebhookPayload = {
+ event: 'message.received',
+ data: {},
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ };
+ const mockFetch = undiciFetch as jest.Mock;
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: { sessionId: 'sess-1', event: 'message.received', payload: queuePayload },
+ });
+ webhookQueue.add.mockRejectedValueOnce(new Error('redis down'));
+ mockFetch.mockResolvedValue({ ok: true, status: 200 });
+
+ await queueService.dispatch('sess-1', 'message.received', {});
+
+ expect(webhookQueue.add).toHaveBeenCalled();
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://example.com/webhook',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ expect(hookManager.execute).toHaveBeenCalledWith(
+ 'webhook:delivered',
+ expect.objectContaining({ webhookId: webhook.id, fallback: 'queue_failed' }),
+ expect.anything(),
+ );
+ });
});
});
diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.ts
index 46c1c5b69..193a208f4 100644
--- a/src/modules/webhook/webhook.service.ts
+++ b/src/modules/webhook/webhook.service.ts
@@ -8,6 +8,7 @@ import * as crypto from 'crypto';
import { Webhook } from './entities/webhook.entity';
import { CreateWebhookDto, UpdateWebhookDto } from './dto';
import { createLogger } from '../../common/services/logger.service';
+import { ListOptions, resolveListWindow } from '../../common/utils/paginate';
import { QUEUE_NAMES } from '../queue/queue-names';
import { generateIdempotencyKey, generateDeliveryId } from './utils/idempotency.util';
import { evaluateFilters } from './filters/filter-evaluator';
@@ -99,10 +100,11 @@ export class WebhookService {
});
}
- async findAll(allowedSessions?: string[] | null): Promise<Webhook[]> {
+ async findAll(allowedSessions?: string[] | null, opts: ListOptions = {}): Promise<Webhook[]> {
// A session-restricted key only sees its own sessions' webhooks; an unrestricted key
// (null/empty allowlist, e.g. ADMIN) sees all — mirroring the ApiKeyGuard allowedSessions model.
- const options: FindManyOptions<Webhook> = { order: { createdAt: 'DESC' } };
+ const { limit, offset } = resolveListWindow(opts.limit, opts.offset);
+ const options: FindManyOptions<Webhook> = { order: { createdAt: 'DESC' }, take: limit, skip: offset };
if (allowedSessions && allowedSessions.length > 0) {
options.where = { sessionId: In(allowedSessions) };
}
@@ -327,6 +329,42 @@ export class WebhookService {
webhookId: webhook.id,
action: 'webhook_queue_failed',
});
+
+ // Fallback: deliver directly when the queue add failed (e.g. Redis unreachable with the
+ // producer's enableOfflineQueue:false). This is at-least-once — if add() actually reached
+ // Redis before rejecting, the queued job AND this fallback may both POST. Both paths carry the
+ // same X-OpenWA-Idempotency-Key / X-OpenWA-Delivery-Id, so a conformant receiver dedupes.
+ try {
+ await this.deliverWebhook(webhook, finalPayload, headers);
+
+ await this.hookManager.execute(
+ 'webhook:delivered',
+ { sessionId, event, webhookId: webhook.id, deliveryId, fallback: 'queue_failed' },
+ { sessionId, source: 'WebhookService' },
+ );
+
+ await this.hookManager.execute(
+ 'webhook:after',
+ { sessionId, event, webhookId: webhook.id, success: true, fallback: 'queue_failed' },
+ { sessionId, source: 'WebhookService' },
+ );
+ } catch (fallbackError) {
+ await this.hookManager.execute(
+ 'webhook:error',
+ {
+ sessionId,
+ event,
+ webhookId: webhook.id,
+ error: `Queue fallback delivery failed: ${String(fallbackError)}`,
+ },
+ { sessionId, source: 'WebhookService' },
+ );
+
+ this.logger.error(`Queue fallback delivery failed for webhook ${webhook.id}`, String(fallbackError), {
+ webhookId: webhook.id,
+ action: 'webhook_queue_fallback_failed',
+ });
+ }
}
} else {
// Direct delivery when queue is disabled
diff --git a/src/modules/webhook/webhooks-list.controller.ts b/src/modules/webhook/webhooks-list.controller.ts
index 709d91256..d6fa320d4 100644
--- a/src/modules/webhook/webhooks-list.controller.ts
+++ b/src/modules/webhook/webhooks-list.controller.ts
@@ -1,5 +1,5 @@
-import { Controller, Get } from '@nestjs/common';
-import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
+import { Controller, Get, Query } from '@nestjs/common';
+import { ApiTags, ApiOperation, ApiResponse, ApiQuery } from '@nestjs/swagger';
import { WebhookService } from './webhook.service';
import { WebhookResponseDto } from './dto';
import { RequireRole, CurrentApiKey } from '../auth/decorators/auth.decorators';
@@ -18,9 +18,20 @@ export class WebhooksListController {
description: 'List of webhooks',
type: [WebhookResponseDto],
})
- async findAll(@CurrentApiKey() apiKey?: ApiKey): Promise<WebhookResponseDto[]> {
+ @ApiQuery({ name: 'limit', required: false, description: 'Max webhooks to return (1-1000, default 1000)' })
+ @ApiQuery({ name: 'offset', required: false, description: 'Number of webhooks to skip (for paging)' })
+ async findAll(
+ @CurrentApiKey() apiKey?: ApiKey,
+ @Query('limit') limit?: string,
+ @Query('offset') offset?: string,
+ ): Promise<WebhookResponseDto[]> {
// Scope to the key's allowedSessions so a session-restricted key cannot enumerate every
// session's webhook URLs. A null/empty allowlist (e.g. ADMIN) still sees all.
- return WebhookResponseDto.fromEntities(await this.webhookService.findAll(apiKey?.allowedSessions));
+ return WebhookResponseDto.fromEntities(
+ await this.webhookService.findAll(apiKey?.allowedSessions, {
+ limit: limit ? parseInt(limit, 10) : undefined,
+ offset: offset ? parseInt(offset, 10) : undefined,
+ }),
+ );
}
}