Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
Release v0.2.0 — i18n, real-time chats, webhooks & delivery state, templates, security & container hardening (#229)
Yudhi Armyndharis04a7be6fe6fa
diff --git a/.env.example b/.env.exampleindex fca130155..d90ca224b 100644--- a/.env.example+++ b/.env.example@@ -22,7 +22,9 @@ DASHBOARD_PORT=2886# BASE_URL=https://api.yourdomain.com# DASHBOARD_URL=https://dashboard.yourdomain.com-# CORS Configuration (comma-separated origins, or * for all)+# CORS Configuration: comma-separated allowed origins. The wildcard "*" is allowed+# only in development; in production it is REFUSED (cross-origin browser requests are+# blocked) — set explicit origin(s) there, e.g. https://dashboard.yourdomain.comCORS_ORIGINS=*# SSL/TLS (enable for production with real domain)@@ -106,6 +108,10 @@ S3_SECRET_KEY=minioadminWEBHOOK_TIMEOUT=10000 # Timeout in millisecondsWEBHOOK_MAX_RETRIES=3 # Number of retry attemptsWEBHOOK_RETRY_DELAY=5000 # Delay between retries in ms+# Block outbound webhooks to internal/reserved addresses (SSRF protection).+# Off by default; enable on internet-exposed deployments. When on, webhook URLs+# resolving to loopback/private/link-local/metadata ranges are refused.+WEBHOOK_SSRF_PROTECT=false# =============================================================================# RATE LIMITING@@ -125,7 +131,14 @@ PLUGINS_DIR=./data/plugins # Plugin directory# Master API key (leave empty to disable, or set to secure value)API_MASTER_KEY=+# First-boot default admin key. By default a cryptographically random key is+# generated (printed in the startup banner / written to data/.api-key). Set this+# to true ONLY for local development to seed the well-known, insecure+# `dev-admin-key` instead. Ignored when API_MASTER_KEY is set.+# ALLOW_DEV_API_KEY=true+# =============================================================================# DEVELOPER SETTINGS# =============================================================================-ENABLE_SWAGGER=true # Enable API documentation at /api/docs+ENABLE_SWAGGER=true # Enable API documentation at /api/docs (set false to disable on exposed deployments)+BODY_SIZE_LIMIT=25mb # Max request body size (base64 media sends ride in the JSON body)diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 000000000..86634432a--- /dev/null+++ b/.gitattributes@@ -0,0 +1,3 @@+# Force LF line endings for files that must run inside Linux containers+*.sh text eol=lf+Dockerfile* text eol=lfdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9703f40a8..316a733ff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,7 +5,151 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).-## [Unreleased]+## [0.2.0] - 2026-06-15++A major feature- and security-focused release. Adds six dashboard languages and a+real-time Chats view, completes the outgoing-message and delivery-state webhook+story, introduces message templates and live chat history, hardens the API surface,+session lifecycle, and container runtime, and upgrades the WhatsApp engine. See+**Upgrade notes** for the behavior changes.++### Added++- **Dashboard / Chats:** A new real-time Chats view — browse a session's+ conversations, stream incoming and outgoing messages live over WebSocket, send+ text and media, and mark chats as read. Thanks @akbarxleqi (#152).+- **Dashboard / i18n:** Six new languages on a single canonical language picker —+ Simplified Chinese, Traditional Chinese, Arabic (full RTL), Telugu, French, and+ Italian — alongside the existing English and Hebrew. The picker now also appears+ on the Login screen and resolves `zh-Hant/HK/MO/TW` regional variants. Thanks+ @jr-everstar (#150), @7odaifa-ab (#145), @abhinayguduri (#149), and+ @albanobattistella (#224).+- **Messages:** Server-side **message templates** with `{{variable}}` substitution —+ full CRUD under `/sessions/:id/templates` plus a+ `POST /sessions/:id/messages/send-template` endpoint that renders and sends.+ Text templates only; interactive buttons/list/HSM are not supported on the+ whatsapp-web.js engine. Thanks @esakarya (#69).+- **Messages:** `GET /sessions/:id/messages/:chatId/history` reads chat history live+ from WhatsApp (bypassing the local DB), with optional base64 media; `limit` is+ clamped to 1–100. Thanks @jgalea (#96, closes #162).+- **Groups:** Group payloads now expose `linkedParentJID` — the JID of the parent+ community a sub-group belongs to. Thanks @ferhatte10 (#201).+- **Webhooks:** `message.sent` now fires for **every** outgoing message — including+ messages composed on a linked phone (via the whatsapp-web.js `message_create`+ event), not just messages sent through the API. (closes #93, #168, #195)+- **Webhooks / Sessions:** Stored message status now reflects real delivery state+ from acks — `delivered`, `read`, and `failed` — advancing monotonically (a late+ or out-of-order ack can never downgrade a higher status). A send that never+ receives a delivery ack stays `sent`, so it is visibly "not delivered" instead of+ falsely "sent". A new `message.failed` webhook is emitted on an error ack so+ consumers can detect non-delivery without polling. Independently identified and+ prototyped by @aminebalti55 (#225). (closes #155, #199, #220)+- **Webhooks:** Opt-in outbound SSRF protection — set `WEBHOOK_SSRF_PROTECT=true` to+ refuse webhook URLs that resolve to loopback, private, link-local, CGNAT, or+ cloud-metadata addresses (default off). (#221)+- **API:** `BODY_SIZE_LIMIT` caps request body size (default 25 MB, sized for+ base64 media sends). `ENABLE_SWAGGER` gates the `/api/docs` UI (default on; set+ `false` to disable it on exposed deployments). (#221, #67)+- **Webhooks:** `message.received` payloads now include the group sender's identity+ — `author` (the participant WID) and `contact` `{ name, pushName }`. Additive and+ backward compatible. (#223, closes #146)+- **Sessions:** Opt-in auto-start of previously authenticated sessions on boot via+ `AUTO_START_SESSIONS=true` (default off); sessions start sequentially to bound+ Puppeteer memory and one failure does not block the others. Thanks @mayko7d+ (#135, closes #218).+- **Sessions:** `PUPPETEER_EXECUTABLE_PATH` points the engine at a system+ Chromium/Chrome binary (for Alpine, ARM, or custom base images); unset keeps+ Puppeteer's bundled Chromium. (#219)+- **Docs:** Community integrations page documenting the community-maintained+ ioBroker adapter (with a not-endorsed caveat). (#223, closes #134)++### Changed++- **Engine:** Upgraded `whatsapp-web.js` from 1.26.1-alpha.3 to **1.34.7**+ (improved LID handling and stability). (#222)+- **Dashboard:** Responsive layout for small screens and improved dark-mode+ contrast across pages; the Plugins page no longer truncates the feature list.+ Thanks @ashiwanikumar (#66).+- **Auth:** The first-boot admin key is now a cryptographically random `owa_k1_`+ key in **all** environments by default; the fixed `dev-admin-key` is seeded only+ when `ALLOW_DEV_API_KEY=true` is explicitly set. (#221)+- **Auth:** Requests with a valid key but insufficient role now return **403+ Forbidden** instead of 401. (#221)+- **Docker / Podman:** Base images are fully qualified (`docker.io/node:22-slim`)+ and the container healthcheck uses `curl`, so the image builds and runs under+ Podman as well as Docker; added a Podman compatibility note to the docs. Thanks+ @3bsalam-1 (#68).+- **Docs / API:** Interactive messages (`Buttons` / `List`) are documented as+ unsupported on the whatsapp-web.js engine, and the speculative request-body+ examples were removed from the API collection. (#223, closes #158)++### Fixed++- **Sessions:** An engine operation attempted while a session is disconnected,+ reconnecting, or still initializing (for example, refreshing the dashboard after+ disconnecting the session from the phone) now returns **409 Conflict**+ ("session not connected") instead of a 500 Internal Server Error. Thanks+ @VincenzoKoestler for the related report. (#100)+- **Sessions:** A terminal engine failure (Chromium failed to launch, or WhatsApp+ rejected the stored credentials) now surfaces as a `failed` status with a+ human-readable reason on the session and in the dashboard, instead of silently+ closing the QR modal; `auth_failure` is treated as terminal rather than+ triggering a reconnect loop. A status race that could revert `qr_ready` back to+ `initializing` during startup is also fixed. (#219)+- **Engine:** The built-in engine plugin now honors `SESSION_DATA_PATH` and the+ configured Puppeteer settings instead of silently falling back to relative-path+ defaults. (#219)+- **Infrastructure dashboard:** Saved configuration (`data/.env.generated`) now+ applies reliably. The save handler wrote several env names the backend never read+ (`STORAGE_PATH`, `S3_ACCESS_KEY` / `S3_SECRET_KEY`, `ENGINE_HEADLESS` /+ `ENGINE_SESSION_PATH` / `ENGINE_BROWSER_ARGS`), so those settings silently reverted+ to defaults on restart; they now match what `configuration.ts` reads. Saving also+ merges into the existing file instead of rewriting it from scratch, so a partial+ save no longer blanks other keys or stored secrets, and the form hydrates from a+ new `GET /infra/config` endpoint. Thanks @VincenzoKoestler (#226).++### Security++- **CORS:** A wildcard (`*`) origin is now **refused in production** (cross-origin+ requests are blocked), and CORS credentials are only enabled with an explicit+ origin allowlist. (#221)+- **WebSocket:** A session-scoped API key can no longer subscribe to `*` or to+ sessions outside its `allowedSessions` allowlist, preventing cross-tenant event+ leakage. (#221)+- **Authorization:** Plugin enable/disable/config and the infrastructure read+ endpoints (`/infra/status`, `/infra/config`, `/engines`, `/engines/current`,+ `/storage/files/count`) now require an **ADMIN** key. (#221, #226)+- **Docker:** The container reaches the Docker API through a least-privilege+ `docker-socket-proxy` over TCP (`DOCKER_HOST`) instead of mounting the socket+ directly, and the Node process runs as a non-root `openwa` user via a `gosu`+ privilege-dropping entrypoint (`dumb-init` stays PID 1 for clean signal handling).+ Thanks @A831ARD0 (#227, #228; supersedes #129).+- **Health:** `/api/health` is excluded from rate limiting so liveness probes do+ not exhaust the limiter. (#221)++### Dependencies++- **CI:** Upgraded `softprops/action-gh-release` v2→v3 and+ `docker/build-push-action` v6→v7 (both move the GitHub Actions runtime to+ Node 24). (#169, #170)++### Upgrade notes++- **CORS in production:** if you serve the dashboard on a different origin than the+ API and relied on the default `CORS_ORIGINS=*`, set `CORS_ORIGINS` to the explicit+ dashboard origin(s) — a wildcard is now refused in production.+- **Infrastructure reads are ADMIN-only:** `/api/infra/status`, `/infra/config`,+ `/engines`, `/engines/current`, and `/storage/files/count` now require an ADMIN key.+- **Role-denied requests return 403** (was 401) — update clients that branch on the+ status code.+- **Not-ready engine ops return 409** (was 500) — clients calling group/chat/send+ endpoints while a session is not connected now receive `409 SESSION_NOT_READY`.+- **First-boot key:** non-production no longer seeds `dev-admin-key` by default (a+ random key is generated and printed in the startup banner / written to+ `data/.api-key`). Set `ALLOW_DEV_API_KEY=true` to restore the fixed local key.+- **Docker:** the bundled Compose now runs a `docker-proxy` sibling and the API+ talks to it via `DOCKER_HOST`, and the container runs as non-root; review the new+ Compose if you mounted the Docker socket directly or customized orchestration.## [0.1.8] - 2026-06-13diff --git a/Dockerfile b/Dockerfileindex 2a6793605..29c90deef 100644--- a/Dockerfile+++ b/Dockerfile@@ -2,7 +2,7 @@# Multi-stage build for production-ready image# ===== Stage 1: Builder =====-FROM node:22-slim AS builder+FROM docker.io/node:22-slim AS builderWORKDIR /app@@ -26,7 +26,7 @@ COPY . .RUN npm run build# ===== Stage 2: Production =====-FROM node:22-slim AS production+FROM docker.io/node:22-slim AS production# Install Chrome/Chromium and required dependenciesRUN apt-get update && apt-get install -y \@@ -49,6 +49,8 @@ RUN apt-get update && apt-get install -y \libxrandr2 \xdg-utils \dumb-init \+ gosu \+ curl \&& rm -rf /var/lib/apt/lists/*# Set Chrome executable path for Puppeteer@@ -69,21 +71,23 @@ RUN npm ci --omit=dev && npm cache clean --force# Copy built application from builder stageCOPY --from=builder /app/dist ./dist-# Create data directories with proper permissions+# Create data directories with correct ownershipRUN mkdir -p ./data/sessions ./data/media && \chown -R openwa:openwa /app-# Note: Running as root to allow Docker socket access for orchestration-# For production with stricter security, consider using a Docker socket proxy-# USER openwa+# Copy entrypoint: runs as root to fix named-volume ownership, then drops to openwa via gosu+COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh+RUN chmod +x /usr/local/bin/docker-entrypoint.sh# Expose portEXPOSE 2785# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \- CMD node -e "require('http').get('http://localhost:2785/api/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1))"+ CMD curl -f http://localhost:2785/api/health || exit 1-# Start with dumb-init to handle signals properly-ENTRYPOINT ["dumb-init", "--"]+# dumb-init is PID 1 and handles signal forwarding.+# It execs docker-entrypoint.sh (as root), which fixes volume ownership and+# then drops to the openwa user via gosu before starting the node process.+ENTRYPOINT ["dumb-init", "--", "/usr/local/bin/docker-entrypoint.sh"]CMD ["node", "dist/main"]diff --git a/README.md b/README.mdindex 18a346fba..fe3988fe5 100644--- a/README.md+++ b/README.md@@ -16,7 +16,7 @@</p><p align="center">- <img src="https://img.shields.io/badge/version-0.1.8-blue.svg" alt="Version"/>+ <img src="https://img.shields.io/badge/version-0.2.0-blue.svg" alt="Version"/><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License"/><img src="https://img.shields.io/badge/node-22_LTS-brightgreen.svg" alt="Node"/><img src="https://img.shields.io/badge/NestJS-11.x-red.svg" alt="NestJS"/>@@ -109,6 +109,17 @@ docker compose -f docker-compose.dev.yml up -d# Swagger: http://localhost:2785/api/docs```+> **Using Podman instead of Docker?**+> Podman rootless mode requires the socket to be running and `DOCKER_HOST` to be set:+>+> ```bash+> systemctl --user start podman.socket+> systemctl --user enable podman.socket+> export DOCKER_HOST=unix:///run/user/$(id -u)/podman/podman.sock+> ```+>+> Add the `export` line to your `~/.bashrc` to make it permanent.+### Option B: Local Development```bash@@ -130,6 +141,40 @@ npm run dev---+## 🔒 Security Architecture++### Docker Socket Proxy++The production stack never exposes `/var/run/docker.sock` directly to the application container. Instead, a dedicated `docker-proxy` sidecar (based on [`tecnativa/docker-socket-proxy`](https://github.com/Tecnativa/docker-socket-proxy)) acts as the sole gateway to the Docker daemon:++```+openwa-api ──TCP 2375──▶ docker-proxy ──unix──▶ /var/run/docker.sock+```++Only the operations needed for container orchestration are enabled (`CONTAINERS`, `IMAGES`, `VOLUMES`, `INFO`, `PING`, `POST`, `DELETE`). The application connects via the `DOCKER_HOST=tcp://docker-proxy:2375` environment variable, which `DockerService` detects automatically.++---++## 🔒 Security Architecture++### Non-root Container Execution++The production image never runs the Node.js process as root. On startup, the container follows this chain:++```+dumb-init (PID 1)+ └─ docker-entrypoint.sh (root — fixes named-volume ownership via chown)+ └─ gosu openwa node dist/main (drops to the openwa user)+```++- **dumb-init** is PID 1 and forwards signals (SIGTERM, etc.) for graceful shutdown.+- **docker-entrypoint.sh** runs as root only long enough to `chown` the named-volume mount points so the `openwa` user can write to them.+- **gosu** performs a clean `exec`-based privilege drop — no `su` or `sudo` wrappers, so the node process is the direct child of dumb-init.++Named volumes (e.g. `openwa-data`) get their ownership corrected automatically on every start, so no manual `chown` step is needed after volume creation.++---+## 🏭 Production DeploymentFor production, use the main `docker-compose.yml` with optional services:diff --git a/dashboard/Dockerfile b/dashboard/Dockerfileindex 37486f2e0..4b6e1f4c8 100644--- a/dashboard/Dockerfile+++ b/dashboard/Dockerfile@@ -1,4 +1,4 @@-FROM node:20-alpine AS builder+FROM docker.io/node:20-alpine AS builderWORKDIR /app@@ -15,7 +15,7 @@ COPY . .RUN npm run build# Production stage with nginx-FROM nginx:alpine+FROM docker.io/nginx:alpine# Copy built filesCOPY --from=builder /app/dist /usr/share/nginx/htmldiff --git a/dashboard/package-lock.json b/dashboard/package-lock.jsonindex 94de582d1..3c94f7284 100644--- a/dashboard/package-lock.json+++ b/dashboard/package-lock.json@@ -1,12 +1,12 @@{"name": "dashboard",- "version": "0.1.0",+ "version": "0.2.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "dashboard",- "version": "0.1.0",+ "version": "0.2.0","dependencies": {"@tanstack/react-query": "^5.101.0","@tanstack/react-table": "^8.21.3",diff --git a/dashboard/package.json b/dashboard/package.jsonindex e50af22ac..e92a19b87 100644--- a/dashboard/package.json+++ b/dashboard/package.json@@ -1,7 +1,7 @@{"name": "dashboard","private": true,- "version": "0.1.8",+ "version": "0.2.0","type": "module","scripts": {"dev": "vite",diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsxindex 21c674922..f4cb7fd25 100644--- a/dashboard/src/App.tsx+++ b/dashboard/src/App.tsx@@ -11,6 +11,7 @@ import './App.css';const Login = lazy(() => import('./pages/Login').then(m => ({ default: m.Login })));const Dashboard = lazy(() => import('./pages/Dashboard').then(m => ({ default: m.Dashboard })));const Sessions = lazy(() => import('./pages/Sessions').then(m => ({ default: m.Sessions })));+const Chats = lazy(() => import('./pages/Chats').then(m => ({ default: m.Chats })));const Webhooks = lazy(() => import('./pages/Webhooks').then(m => ({ default: m.Webhooks })));const Logs = lazy(() => import('./pages/Logs').then(m => ({ default: m.Logs })));const ApiKeys = lazy(() => import('./pages/ApiKeys').then(m => ({ default: m.ApiKeys })));@@ -101,6 +102,7 @@ function AppContent() {<Route path="/" element={<Layout onLogout={handleLogout} userRole={role} />}><Route index element={<Dashboard />} /><Route path="sessions" element={<Sessions />} />+ <Route path="chats" element={<Chats />} /><Route path="webhooks" element={<Webhooks />} />{role === 'admin' && <Route path="api-keys" element={<ApiKeys />} />}<Route path="logs" element={<Logs />} />diff --git a/dashboard/src/components/Layout.css b/dashboard/src/components/Layout.cssindex 0db1288f9..b54d046de 100644--- a/dashboard/src/components/Layout.css+++ b/dashboard/src/components/Layout.css@@ -195,6 +195,64 @@color: var(--text-primary);}+.language-menu {+ position: relative;+}++.language-menu .theme-toggle-btn {+ width: 100%;+}++.language-menu-list {+ position: absolute;+ left: 0;+ right: 0;+ bottom: calc(100% + 0.35rem);+ display: flex;+ flex-direction: column;+ gap: 0.15rem;+ min-width: 160px;+ padding: 0.3rem;+ background: var(--bg-white);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ box-shadow: 0 10px 30px rgba(15, 23, 42, 0.16);+ z-index: 120;+}++.language-menu-item {+ display: flex;+ align-items: center;+ width: 100%;+ min-height: 34px;+ padding: 0.45rem 0.6rem;+ color: var(--text-secondary);+ background: transparent;+ border: 0;+ border-radius: calc(var(--radius) - 2px);+ font-size: 0.875rem;+ font-weight: 500;+ text-align: left;+ cursor: pointer;+ transition: all 0.2s;+}++.language-menu-item:hover {+ background: var(--bg-light);+ color: var(--text-primary);+}++.language-menu-item.active {+ background: rgba(37, 211, 102, 0.1);+ color: var(--primary);+}++.sidebar.collapsed .language-menu-list {+ right: auto;+ left: calc(100% + 0.5rem);+ bottom: 0;+}+.logout-btn {display: flex;align-items: center;@@ -352,6 +410,15 @@transform: scaleX(-1);}+[dir="rtl"] .language-menu-item {+ text-align: right;+}++[dir="rtl"] .sidebar.collapsed .language-menu-list {+ right: calc(100% + 0.5rem);+ left: auto;+}+[dir="rtl"] .main-content {margin-left: 0;margin-right: 260px;diff --git a/dashboard/src/components/Layout.tsx b/dashboard/src/components/Layout.tsxindex f2815bb8a..90de18a94 100644--- a/dashboard/src/components/Layout.tsx+++ b/dashboard/src/components/Layout.tsx@@ -1,9 +1,10 @@-import { useState, useEffect } from 'react';+import { useState, useEffect, useRef } from 'react';import { NavLink, Outlet } from 'react-router-dom';import { useTranslation } from 'react-i18next';import {LayoutDashboard,Smartphone,+ MessageSquare,Webhook,Key,FileText,@@ -22,7 +23,7 @@ import {} from 'lucide-react';import { useTheme } from '../hooks/useTheme';import { type UserRole } from '../hooks/useRole';-import { supportedLanguages, type SupportedLanguage } from '../i18n';+import { languageOptions, resolveSupportedLanguage, rtlLanguages, type SupportedLanguage } from '../i18n';import './Layout.css';interface LayoutProps {@@ -33,6 +34,7 @@ interface LayoutProps {const allNavItems = [{ to: '/', icon: LayoutDashboard, key: 'dashboard' as const, adminOnly: false },{ to: '/sessions', icon: Smartphone, key: 'sessions' as const, adminOnly: false },+ { to: '/chats', icon: MessageSquare, key: 'chats' as const, adminOnly: false },{ to: '/webhooks', icon: Webhook, key: 'webhooks' as const, adminOnly: false },{ to: '/api-keys', icon: Key, key: 'apiKeys' as const, adminOnly: true },{ to: '/message-tester', icon: Send, key: 'messageTester' as const, adminOnly: false },@@ -54,6 +56,8 @@ export function Layout({ onLogout, userRole }: LayoutProps) {const [isCollapsed, setIsCollapsed] = useState(false);const [isMobileOpen, setIsMobileOpen] = useState(false);const [isMobile, setIsMobile] = useState(window.innerWidth < 768);+ const [isLanguageMenuOpen, setIsLanguageMenuOpen] = useState(false);+ const languageMenuRef = useRef<HTMLDivElement>(null);useEffect(() => {const handleResize = () => {@@ -76,17 +80,36 @@ export function Layout({ onLogout, userRole }: LayoutProps) {};}, [isMobileOpen]);+ useEffect(() => {+ if (!isLanguageMenuOpen) return;++ const closeOnOutsideClick = (event: MouseEvent) => {+ if (!languageMenuRef.current?.contains(event.target as Node)) {+ setIsLanguageMenuOpen(false);+ }+ };+ const closeOnEscape = (event: KeyboardEvent) => {+ if (event.key === 'Escape') setIsLanguageMenuOpen(false);+ };++ document.addEventListener('mousedown', closeOnOutsideClick);+ document.addEventListener('keydown', closeOnEscape);+ return () => {+ document.removeEventListener('mousedown', closeOnOutsideClick);+ document.removeEventListener('keydown', closeOnEscape);+ };+ }, [isLanguageMenuOpen]);+const toggleCollapse = () => setIsCollapsed(!isCollapsed);const toggleMobile = () => setIsMobileOpen(!isMobileOpen);- const currentLang = (i18n.resolvedLanguage || i18n.language || 'en').split('-')[0] as SupportedLanguage;- const cycleLanguage = () => {- const idx = supportedLanguages.indexOf(currentLang);- const next = supportedLanguages[(idx + 1) % supportedLanguages.length];- void i18n.changeLanguage(next);+ const currentLang = resolveSupportedLanguage(i18n.resolvedLanguage || i18n.language);+ const languageLabel = languageOptions.find(option => option.value === currentLang)?.compactLabel ?? 'EN';+ const changeLanguage = (language: SupportedLanguage) => {+ setIsLanguageMenuOpen(false);+ void i18n.changeLanguage(language);};- const languageLabel = currentLang === 'he' ? 'עברית' : 'EN';- const isRtl = currentLang === 'he';+ const isRtl = rtlLanguages.includes(currentLang);return (<div className="layout">@@ -151,15 +174,34 @@ export function Layout({ onLogout, userRole }: LayoutProps) {</nav><div className="sidebar-footer">- <button- className="theme-toggle-btn"- onClick={cycleLanguage}- title={t('common.language')}- aria-label={t('common.language')}- >- <Languages size={18} />- {!isCollapsed && <span>{languageLabel}</span>}- </button>+ <div className="language-menu" ref={languageMenuRef}>+ <button+ className="theme-toggle-btn"+ onClick={() => setIsLanguageMenuOpen(open => !open)}+ title={t('common.language')}+ aria-label={t('common.language')}+ aria-haspopup="menu"+ aria-expanded={isLanguageMenuOpen}+ >+ <Languages size={18} />+ {!isCollapsed && <span>{languageLabel}</span>}+ </button>+ {isLanguageMenuOpen && (+ <div className="language-menu-list" role="menu" aria-label={t('common.language')}>+ {languageOptions.map(option => (+ <button+ key={option.value}+ className={`language-menu-item ${option.value === currentLang ? 'active' : ''}`}+ onClick={() => changeLanguage(option.value)}+ role="menuitemradio"+ aria-checked={option.value === currentLang}+ >+ <span>{option.label}</span>+ </button>+ ))}+ </div>+ )}+ </div><buttonclassName="theme-toggle-btn"onClick={toggleTheme}diff --git a/dashboard/src/hooks/queries.ts b/dashboard/src/hooks/queries.tsindex 21e641b66..e7c912df3 100644--- a/dashboard/src/hooks/queries.ts+++ b/dashboard/src/hooks/queries.ts@@ -15,6 +15,7 @@ export const queryKeys = {sessions: ['sessions'] as const,sessionStats: ['sessions', 'stats'] as const,sessionGroups: (sessionId: string) => ['sessions', sessionId, 'groups'] as const,+ sessionChats: (sessionId: string) => ['sessions', sessionId, 'chats'] as const,webhooks: ['webhooks'] as const,apiKeys: ['apiKeys'] as const,logs: (params: { severity?: string; page: number; limit: number }) =>@@ -52,6 +53,15 @@ export function useSessionGroupsQuery(sessionId: string, enabled: boolean) {});}+export function useSessionChatsQuery(sessionId: string, enabled: boolean) {+ return useQuery({+ queryKey: queryKeys.sessionChats(sessionId),+ queryFn: () => sessionApi.getChats(sessionId),+ enabled: enabled && !!sessionId,+ staleTime: 10_000,+ });+}+export function useCreateSessionMutation() {const queryClient = useQueryClient();return useMutation({@@ -203,6 +213,14 @@ export function useInfraStatusQuery() {});}+export function useInfraConfigQuery() {+ return useQuery({+ queryKey: ['infra', 'config'],+ queryFn: infraApi.getConfig,+ staleTime: 30_000,+ });+}+// ── Plugin Queries ────────────────────────────────────────────────────export function usePluginsQuery() {diff --git a/dashboard/src/hooks/useWebSocket.ts b/dashboard/src/hooks/useWebSocket.tsindex 592f7c8a6..387d16ebf 100644--- a/dashboard/src/hooks/useWebSocket.ts+++ b/dashboard/src/hooks/useWebSocket.ts@@ -19,10 +19,54 @@ interface MessageEvent {timestamp: string;}+interface MessageAckEvent {+ sessionId: string;+ messageId: string;+ ack: number;+ ackName: string;+ chatId?: string;+ timestamp: string;+}++interface MessageReactionEvent {+ sessionId: string;+ messageId: string;+ chatId: string;+ reaction: string;+ senderId: string;+ reactions: Record<string, string>;+ timestamp: string;+}++interface MessageRevokedEvent {+ sessionId: string;+ id: string;+ chatId: string;+ from: string;+ to: string;+ body: string;+ type: string;+ timestamp: number;+}+interface WebSocketEvents {onSessionStatus?: (event: SessionStatusEvent) => void;onQRCode?: (event: QRCodeEvent) => void;onMessage?: (event: MessageEvent) => void;+ onMessageAck?: (event: MessageAckEvent) => void;+ onMessageReaction?: (event: MessageReactionEvent) => void;+ onMessageRevoked?: (event: MessageRevokedEvent) => void;+}++// Shape of the server -> client event envelope produced by the NestJS gateway.+interface ServerEventEnvelope {+ type: string;+ timestamp: string;+ payload?: {+ event: string;+ sessionId: string;+ data: Record<string, unknown>;+ };}// Use current origin for WebSocket (goes through nginx proxy in Docker)@@ -61,12 +105,10 @@ export function useWebSocket(events: WebSocketEvents = {}) {});socketRef.current.on('connect', () => {- console.log('[WebSocket] Connected');setIsConnected(true);});socketRef.current.on('disconnect', () => {- console.log('[WebSocket] Disconnected');setIsConnected(false);});@@ -75,6 +117,25 @@ export function useWebSocket(events: WebSocketEvents = {}) {});}, []);+ const subscribe = useCallback((sessionId: string, eventsList: string[]) => {+ if (socketRef.current?.connected) {+ socketRef.current.emit('message', {+ type: 'subscribe',+ sessionId,+ events: eventsList,+ });+ }+ }, []);++ const unsubscribe = useCallback((sessionId: string) => {+ if (socketRef.current?.connected) {+ socketRef.current.emit('message', {+ type: 'unsubscribe',+ sessionId,+ });+ }+ }, []);+useEffect(() => {connect();@@ -86,30 +147,72 @@ export function useWebSocket(events: WebSocketEvents = {}) {};}, [connect]);- // Register event handlers+ // Register the single envelope handler and fan out to the typed callbacks.useEffect(() => {if (!socketRef.current) return;const socket = socketRef.current;- if (events.onSessionStatus) {- socket.on('session:status', events.onSessionStatus);- }-- if (events.onQRCode) {- socket.on('session:qr', events.onQRCode);- }+ const handleIncomingMessage = (msg: ServerEventEnvelope) => {+ if (!msg || msg.type !== 'event' || !msg.payload) return;++ const { event, sessionId, data } = msg.payload;++ switch (event) {+ case 'session.status':+ events.onSessionStatus?.({ sessionId, status: String(data.status), timestamp: msg.timestamp });+ break;+ case 'session.qr':+ events.onQRCode?.({ sessionId, qrCode: String(data.qrCode), timestamp: msg.timestamp });+ break;+ case 'message.received':+ case 'message.sent':+ events.onMessage?.({ sessionId, message: data, timestamp: msg.timestamp });+ break;+ case 'message.ack':+ events.onMessageAck?.({+ sessionId,+ messageId: String(data.messageId),+ ack: Number(data.ack),+ ackName: String(data.ackName),+ chatId: data.chatId as string | undefined,+ timestamp: msg.timestamp,+ });+ break;+ case 'message.reaction':+ events.onMessageReaction?.({+ sessionId,+ messageId: String(data.messageId),+ chatId: String(data.chatId),+ reaction: String(data.reaction),+ senderId: String(data.senderId),+ reactions: (data.reactions as Record<string, string>) || {},+ timestamp: msg.timestamp,+ });+ break;+ case 'message.revoked':+ events.onMessageRevoked?.({+ sessionId,+ id: String(data.id),+ chatId: String(data.chatId),+ from: String(data.from),+ to: String(data.to),+ body: String(data.body ?? ''),+ type: String(data.type),+ timestamp: Number(data.timestamp),+ });+ break;+ default:+ break;+ }+ };- if (events.onMessage) {- socket.on('session:message', events.onMessage);- }+ socket.on('message', handleIncomingMessage);return () => {- socket.off('session:status');- socket.off('session:qr');- socket.off('session:message');+ socket.off('message', handleIncomingMessage);};- }, [events.onSessionStatus, events.onQRCode, events.onMessage]);+ }, [events]);- return { isConnected };+ return { isConnected, subscribe, unsubscribe };}diff --git a/dashboard/src/i18n/index.ts b/dashboard/src/i18n/index.tsindex cfa5b8c12..dafb0703e 100644--- a/dashboard/src/i18n/index.ts+++ b/dashboard/src/i18n/index.ts@@ -3,11 +3,44 @@ import { initReactI18next } from 'react-i18next';import LanguageDetector from 'i18next-browser-languagedetector';import en from './locales/en.json';import he from './locales/he.json';+import zhCN from './locales/zh-CN.json';+import zhHK from './locales/zh-HK.json';+import ar from './locales/ar.json';+import te from './locales/te.json';+import fr from './locales/fr.json';+import it from './locales/it.json';-export const supportedLanguages = ['en', 'he'] as const;+export const supportedLanguages = ['en', 'he', 'zh-CN', 'zh-HK', 'ar', 'te', 'fr', 'it'] as const;export type SupportedLanguage = (typeof supportedLanguages)[number];-export const rtlLanguages: SupportedLanguage[] = ['he'];+export const rtlLanguages: SupportedLanguage[] = ['he', 'ar'];++export const languageOptions: Array<{ value: SupportedLanguage; label: string; compactLabel: string }> = [+ { value: 'en', label: 'English', compactLabel: 'EN' },+ { value: 'he', label: 'עברית', compactLabel: 'עברית' },+ { value: 'zh-CN', label: '简体中文', compactLabel: '简中' },+ { value: 'zh-HK', label: '繁體中文', compactLabel: '繁中' },+ { value: 'ar', label: 'العربية', compactLabel: 'AR' },+ { value: 'te', label: 'తెలుగు', compactLabel: 'TE' },+ { value: 'fr', label: 'Français', compactLabel: 'FR' },+ { value: 'it', label: 'Italiano', compactLabel: 'IT' },+];++export function resolveSupportedLanguage(lang?: string): SupportedLanguage {+ const value = lang || 'en';+ const exact = supportedLanguages.find(supported => supported.toLowerCase() === value.toLowerCase());+ if (exact) return exact;++ const parts = value.toLowerCase().split('-');+ const base = parts[0];+ if (base === 'zh') {+ const subtags = new Set(parts.slice(1));+ if (subtags.has('hant') || subtags.has('hk') || subtags.has('mo') || subtags.has('tw')) return 'zh-HK';+ return 'zh-CN';+ }++ return supportedLanguages.find(supported => supported === base) ?? 'en';+}void i18n.use(LanguageDetector)@@ -16,24 +49,31 @@ void i18nresources: {en: { translation: en },he: { translation: he },+ 'zh-CN': { translation: zhCN },+ 'zh-HK': { translation: zhHK },+ ar: { translation: ar },+ te: { translation: te },+ fr: { translation: fr },+ it: { translation: it },},fallbackLng: 'en',supportedLngs: supportedLanguages as unknown as string[],- nonExplicitSupportedLngs: true,+ nonExplicitSupportedLngs: false,interpolation: { escapeValue: false },detection: {order: ['localStorage', 'navigator'],lookupLocalStorage: 'openwa_language',caches: ['localStorage'],+ convertDetectedLanguage: (lang: string) => resolveSupportedLanguage(lang),},react: { useSuspense: false },});function applyDirection(lang: string) {- const base = (lang || 'en').split('-')[0] as SupportedLanguage;- const dir = rtlLanguages.includes(base) ? 'rtl' : 'ltr';+ const resolved = resolveSupportedLanguage(lang);+ const dir = rtlLanguages.includes(resolved) ? 'rtl' : 'ltr';if (typeof document !== 'undefined') {- document.documentElement.lang = base;+ document.documentElement.lang = resolved;document.documentElement.dir = dir;}}diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonnew file mode 100644index 000000000..81b5b72a2--- /dev/null+++ b/dashboard/src/i18n/locales/ar.json@@ -0,0 +1,515 @@+{+ "common": {+ "appName": "OpenWA",+ "appSubtitle": "واجهة برمجة واتساب",+ "loading": "جارٍ التحميل...",+ "save": "حفظ",+ "cancel": "إلغاء",+ "delete": "حذف",+ "edit": "تعديل",+ "create": "إنشاء",+ "close": "إغلاق",+ "submit": "إرسال",+ "confirm": "تأكيد",+ "search": "بحث",+ "filter": "تصفية",+ "actions": "إجراءات",+ "status": "الحالة",+ "name": "الاسم",+ "role": "الدور",+ "type": "النوع",+ "url": "الرابط",+ "port": "المنفذ",+ "host": "المضيف",+ "username": "اسم المستخدم",+ "password": "كلمة المرور",+ "active": "نشط",+ "inactive": "غير نشط",+ "enabled": "مفعّل",+ "disabled": "معطّل",+ "connected": "متصل",+ "disconnected": "غير متصل",+ "never": "أبداً",+ "justNow": "الآن",+ "minAgo": "منذ {{count}} دقيقة",+ "hoursAgo": "منذ {{count}} ساعة",+ "optional": "اختياري",+ "language": "اللغة",+ "english": "English",+ "hebrew": "עברית",+ "arabic": "العربية",+ "back": "رجوع",+ "next": "التالي",+ "previous": "السابق",+ "expand": "توسيع",+ "collapse": "طي",+ "logout": "تسجيل الخروج",+ "refresh": "تحديث",+ "errorGeneric": "حدث خطأ",+ "unknownError": "خطأ غير معروف"+ },+ "theme": {+ "light": "فاتح",+ "dark": "داكن",+ "system": "النظام",+ "label": "المظهر: {{value}}"+ },+ "nav": {+ "dashboard": "لوحة التحكم",+ "sessions": "الجلسات",+ "webhooks": "الويب هوك",+ "apiKeys": "مفاتيح API",+ "messageTester": "اختبار الرسائل",+ "infrastructure": "البنية التحتية",+ "plugins": "الإضافات",+ "logs": "السجلات"+ },+ "errorBoundary": {+ "title": "حدث خطأ ما",+ "description": "واجهت لوحة التحكم خطأً غير متوقع.",+ "reload": "إعادة تحميل لوحة التحكم"+ },+ "login": {+ "apiKey": "مفتاح API",+ "apiKeyPlaceholder": "أدخل مفتاح API الخاص بك",+ "apiKeyRequired": "مفتاح API مطلوب",+ "connect": "اتصال",+ "connecting": "جارٍ الاتصال...",+ "invalidKey": "مفتاح API غير صالح",+ "connectionError": "تعذّر الاتصال بالخادم. يرجى المحاولة مرة أخرى.",+ "help": "هل تحتاج مساعدة؟",+ "viewDocs": "عرض التوثيق",+ "footer": "صُنع بـ ❤️ بواسطة Yudhi Armyndharis ومجتمع OpenWA",+ "version": "v{{version}} · {{date}}"+ },+ "dashboard": {+ "title": "لوحة التحكم",+ "subtitle": "نظرة عامة على جلسات واتساب ونشاطك",+ "stats": {+ "activeSessions": "الجلسات النشطة",+ "messagesToday": "رسائل اليوم",+ "webhooksConfigured": "الويب هوك المُهيّأة",+ "apiCalls": "استدعاءات API (24 ساعة)"+ },+ "sessionsOverview": "نظرة عامة على الجلسات",+ "showingSessions": "عرض {{shown}} من {{total}} جلسة",+ "columns": {+ "sessionId": "معرّف الجلسة",+ "phone": "رقم الهاتف",+ "status": "الحالة",+ "lastActive": "آخر نشاط",+ "actions": "إجراءات"+ },+ "noSessions": "لم يتم العثور على جلسات. أنشئ جلسة للبدء.",+ "view": "عرض",+ "disconnect": "قطع الاتصال",+ "errorPrefix": "خطأ: {{message}}",+ "loadError": "فشل تحميل البيانات"+ },+ "sessionStatus": {+ "created": "جديد",+ "idle": "خامل",+ "initializing": "جارٍ البدء...",+ "connecting": "جارٍ الاتصال...",+ "qr_ready": "امسح رمز QR",+ "ready": "متصل",+ "disconnected": "غير متصل"+ },+ "sessions": {+ "title": "الجلسات",+ "subtitle": "إدارة جلسات واتساب واتصالات رمز QR",+ "newSession": "جلسة جديدة",+ "searchPlaceholder": "بحث في الجلسات...",+ "filter": {+ "all": "كل الحالات",+ "active": "نشطة (متصلة)",+ "inactive": "غير نشطة",+ "connecting": "جارٍ الاتصال"+ },+ "empty": {+ "title": "لم يتم العثور على جلسات",+ "description": "أنشئ جلسة جديدة للبدء"+ },+ "create": {+ "title": "إنشاء جلسة جديدة",+ "label": "اسم الجلسة",+ "placeholder": "مثال: marketing-bot",+ "hint": "استخدم الأحرف الصغيرة والأرقام والشرطات فقط. مثال: <code>customer-support</code>، <code>bot-1</code>",+ "invalidChars": "أحرف غير صالحة. يُسمح فقط بالأحرف الصغيرة والأرقام والشرطات.",+ "tooLong": "يجب ألا يتجاوز الاسم 50 حرفاً ({{length}}/50).",+ "duplicate": "جلسة بهذا الاسم موجودة بالفعل.",+ "successTitle": "تم إنشاء الجلسة",+ "successDesc": "تم إنشاء الجلسة \"{{name}}\" بنجاح",+ "errorTitle": "فشل الإنشاء",+ "errorDefault": "فشل إنشاء الجلسة"+ },+ "delete": {+ "title": "تأكيد الحذف",+ "message": "هل أنت متأكد من حذف الجلسة <strong>\"{{name}}\"</strong>؟",+ "warning": "لا يمكن التراجع عن هذا الإجراء.",+ "successTitle": "تم حذف الجلسة",+ "successDescNamed": "تم حذف الجلسة \"{{name}}\"",+ "successDescGeneric": "تم حذف الجلسة",+ "errorTitle": "فشل الحذف",+ "errorDefault": "فشل حذف الجلسة"+ },+ "qr": {+ "title": "مسح رمز QR",+ "step1": "<strong>1.</strong> افتح واتساب على هاتفك",+ "step2": "<strong>2.</strong> اضغط على <strong>القائمة</strong> ← <strong>الأجهزة المرتبطة</strong>",+ "step3": "<strong>3.</strong> اضغط على <strong>ربط جهاز</strong> وامسح رمز QR هذا",+ "autoRefresh": "يتجدد رمز QR تلقائياً كل 5 ثوانٍ",+ "generating": "جارٍ إنشاء رمز QR...",+ "unavailable": "رمز QR غير متاح بعد. حاول مرة أخرى بعد لحظة.",+ "preparing": "جارٍ تحضير رمز QR...",+ "showQr": "عرض رمز QR",+ "loading": "جارٍ التحميل...",+ "scanToConnect": "امسح رمز QR للاتصال"+ },+ "details": {+ "title": "تفاصيل الجلسة",+ "name": "الاسم",+ "status": "الحالة",+ "sessionId": "معرّف الجلسة",+ "phone": "رقم الهاتف",+ "phoneNone": "غير متصل",+ "created": "تاريخ الإنشاء",+ "lastActive": "آخر نشاط"+ },+ "actions": {+ "view": "عرض",+ "start": "بدء",+ "stop": "إيقاف",+ "reconnect": "إعادة الاتصال",+ "delete": "حذف"+ },+ "toasts": {+ "readyTitle": "الجلسة جاهزة",+ "readyDesc": "جلسة واتساب متصلة الآن",+ "disconnectedTitle": "انقطع اتصال الجلسة",+ "disconnectedDesc": "انقطع اتصال جلسة واتساب"+ },+ "card": {+ "phone": "الهاتف",+ "sessionId": "معرّف الجلسة",+ "lastActive": "آخر نشاط"+ }+ },+ "webhooks": {+ "title": "الويب هوك",+ "subtitle": "تهيئة استدعاءات HTTP للإشعارات الفورية بالأحداث",+ "addWebhook": "إضافة ويب هوك",+ "createTitle": "إنشاء ويب هوك",+ "editTitle": "تعديل ويب هوك",+ "deleteTitle": "حذف ويب هوك",+ "deleteConfirm": "هل أنت متأكد من حذف هذا الويب هوك؟",+ "selectSession": "اختر جلسة...",+ "session": "الجلسة",+ "events": "الأحداث",+ "available": "الأحداث المتاحة",+ "saveChanges": "حفظ التغييرات",+ "columns": {+ "url": "الرابط",+ "events": "الأحداث",+ "session": "الجلسة",+ "status": "الحالة",+ "actions": "إجراءات"+ },+ "empty": {+ "title": "لا توجد ويب هوك مُهيّأة",+ "description": "أضف ويب هوك لتلقي إشعارات فورية بالأحداث"+ },+ "toasts": {+ "created": "تم إنشاء الويب هوك بنجاح",+ "createFailed": "فشل إنشاء الويب هوك: {{message}}",+ "deleted": "تم حذف الويب هوك بنجاح",+ "deleteFailed": "فشل حذف الويب هوك: {{message}}",+ "updated": "تم تحديث الويب هوك بنجاح",+ "updateFailed": "فشل تحديث الويب هوك: {{message}}",+ "testOk": "نجح اختبار الويب هوك! الحالة: {{status}}",+ "testFailed": "فشل اختبار الويب هوك: {{message}}",+ "testError": "فشل اختبار الويب هوك: {{message}}"+ },+ "actions": {+ "test": "اختبار",+ "edit": "تعديل",+ "delete": "حذف"+ },+ "eventDescriptions": {+ "message.received": "عند استقبال رسالة",+ "message.sent": "عند إرسال رسالة",+ "session.connected": "عند اتصال جلسة",+ "session.disconnected": "عند انقطاع جلسة",+ "session.qr": "عند إنشاء رمز QR",+ "all": "كل الأحداث"+ }+ },+ "apiKeys": {+ "title": "مفاتيح API",+ "subtitle": "إدارة مفاتيح API للمصادقة والتحكم في الوصول",+ "createBtn": "إنشاء مفتاح API",+ "modalTitle": "إنشاء مفتاح API",+ "createdTitle": "تم إنشاء مفتاح API",+ "createdHint": "انسخ هذا المفتاح الآن. لن تتمكن من رؤيته مرة أخرى.",+ "namePlaceholder": "مثال: مفتاح الإنتاج",+ "rolesTitle": "مرجع الأدوار",+ "roles": {+ "admin": "مدير",+ "operator": "مشغّل",+ "viewer": "مشاهد"+ },+ "roleDescriptions": {+ "admin": "وصول كامل لجميع الموارد",+ "operator": "إدارة الجلسات والرسائل",+ "viewer": "وصول للقراءة فقط"+ },+ "columns": {+ "name": "الاسم",+ "key": "المفتاح",+ "role": "الدور",+ "status": "الحالة",+ "lastUsed": "آخر استخدام",+ "actions": "إجراءات"+ },+ "statuses": {+ "active": "نشط",+ "revoked": "مُلغى"+ },+ "empty": {+ "title": "لا توجد مفاتيح API",+ "description": "أنشئ مفتاح API للمصادقة على طلباتك"+ },+ "confirm": {+ "deleteTitle": "حذف مفتاح API",+ "revokeTitle": "إلغاء مفتاح API",+ "deleteMessage": "هل أنت متأكد من الحذف النهائي لـ <strong>{{name}}</strong>؟ لا يمكن التراجع عن هذا الإجراء.",+ "revokeMessage": "هل أنت متأكد من إلغاء <strong>{{name}}</strong>؟ لن يعمل بعد الآن.",+ "delete": "حذف",+ "revoke": "إلغاء"+ },+ "actions": {+ "copy": "نسخ",+ "revoke": "إلغاء",+ "delete": "حذف"+ }+ },+ "logs": {+ "title": "سجلات التدقيق",+ "subtitle": "تتبع ومراجعة جميع إجراءات API وأحداث النظام",+ "exportCsv": "تصدير CSV",+ "searchPlaceholder": "البحث في السجلات...",+ "severity": {+ "all": "كل الأنواع",+ "info": "معلومات",+ "warn": "تحذير",+ "error": "خطأ"+ },+ "columns": {+ "timestamp": "الوقت",+ "action": "الإجراء",+ "session": "الجلسة",+ "apiKey": "مفتاح API",+ "ip": "عنوان IP",+ "severity": "النوع"+ },+ "empty": {+ "title": "لا توجد سجلات",+ "description": "ستظهر سجلات التدقيق هنا عند تنفيذ الإجراءات"+ }+ },+ "messageTester": {+ "title": "اختبار الرسائل",+ "subtitle": "إرسال رسائل تجريبية عبر API",+ "compose": "إرسال رسالة تجريبية",+ "responseTitle": "استجابة API",+ "session": "الجلسة",+ "noReadySessions": "لا توجد جلسات جاهزة",+ "sessionOptionPhoneNone": "لا يوجد هاتف",+ "recipientType": "نوع المستلم",+ "personal": "شخصي",+ "group": "مجموعة",+ "selectGroup": "اختر مجموعة",+ "recipientPhone": "رقم هاتف المستلم",+ "loadingGroups": "جارٍ تحميل المجموعات...",+ "noGroupsFound": "لم يتم العثور على مجموعات",+ "selectGroupHint": "اختر مجموعة من واتساب الخاص بك",+ "phoneHint": "استخدم الصيغة الدولية بدون مسافات",+ "messageType": "نوع الرسالة",+ "types": {+ "text": "نص",+ "image": "صورة",+ "video": "فيديو",+ "audio": "صوت",+ "document": "مستند"+ },+ "messageContent": "محتوى الرسالة",+ "messagePlaceholder": "أدخل رسالتك هنا...",+ "mediaUrl": "رابط الوسائط",+ "caption": "التعليق",+ "filename": "اسم الملف",+ "captionPlaceholder": "أدخل التعليق...",+ "filenamePlaceholder": "document.pdf",+ "send": "إرسال الرسالة",+ "sending": "جارٍ الإرسال...",+ "viewOnly": "للعرض فقط",+ "responseEmpty": "أرسل رسالة لرؤية استجابة API",+ "successLabel": "200 OK - نجاح",+ "failedLabel": "400 - فشل",+ "response": {+ "timestamp": "الوقت",+ "messageId": "معرّف الرسالة",+ "error": "خطأ"+ },+ "sendFailed": "فشل إرسال الرسالة"+ },+ "infrastructure": {+ "title": "البنية التحتية",+ "subtitle": "تهيئة إعدادات الخادم وقاعدة البيانات والذاكرة المؤقتة والتخزين والمحرك",+ "saveConfig": "حفظ الإعدادات",+ "saving": "جارٍ الحفظ...",+ "server": {+ "title": "إعدادات الخادم",+ "production": "إنتاج",+ "development": "تطوير",+ "environment": "البيئة",+ "domain": "النطاق",+ "apiPort": "منفذ API",+ "dashboardPort": "منفذ لوحة التحكم",+ "corsOrigins": "مصادر CORS",+ "corsPlaceholder": "* أو مصادر مفصولة بفاصلة",+ "publicApiUrl": "رابط API العام (اختياري)",+ "publicDashboardUrl": "رابط لوحة التحكم العامة (اختياري)"+ },+ "webhook": {+ "title": "الويب هوك وحد التحميل",+ "settings": "إعدادات الويب هوك",+ "timeout": "المهلة (مللي ثانية)",+ "maxRetries": "أقصى عدد للمحاولات",+ "retryDelay": "تأخير إعادة المحاولة (مللي ثانية)",+ "rateLimit": "حد التحميل",+ "window": "نافذة الوقت (ثوانٍ)",+ "maxReq": "أقصى عدد طلبات لكل نافذة"+ },+ "database": {+ "title": "إعدادات قاعدة البيانات",+ "sqlite": "SQLite",+ "sqliteDesc": "قاعدة بيانات محلية على الملفات",+ "postgres": "PostgreSQL",+ "postgresDesc": "قاعدة بيانات جاهزة للإنتاج",+ "useBuiltIn": "استخدام حاوية PostgreSQL المدمجة",+ "builtInDesc": "سيدير OpenWA حاوية PostgreSQL نيابةً عنك",+ "dbName": "اسم قاعدة البيانات",+ "poolSize": "حجم المجموعة",+ "ssl": "اتصال SSL",+ "sslDesc": "تفعيل TLS/SSL لاتصالات آمنة بقاعدة البيانات",+ "sslRejectUnauthorized": "التحقق من شهادة SSL",+ "sslRejectUnauthorizedDesc": "رفض الشهادات الموقّعة ذاتيًا أو غير الصالحة. أوقفه لقواعد بيانات Postgres المُدارة ذات الشهادات الموقّعة ذاتيًا (Supabase وHeroku وRender وRailway).",+ "migrationsTitle": "ترحيل قاعدة البيانات",+ "migrationsStatus": "يتم مزامنة المخطط تلقائياً مع TypeORM",+ "migrationsHint": "تُدار عمليات الترحيل تلقائياً. استخدم CLI للترحيل اليدوي."+ },+ "redis": {+ "title": "Redis",+ "enable": "تفعيل Redis",+ "enableDesc": "مطلوب للتخزين المؤقت وتخزين الجلسات وقوائم BullMQ",+ "useBuiltIn": "استخدام حاوية Redis المدمجة",+ "builtInDesc": "سيدير OpenWA حاوية Redis نيابةً عنك",+ "queueTitle": "تفعيل نظام قوائم BullMQ",+ "queueDesc": "استخدام قوائم الرسائل لتوصيل موثوق للرسائل والويب هوك",+ "statsTitle": "إحصائيات القوائم",+ "messageQueue": "قائمة الرسائل",+ "webhookQueue": "قائمة الويب هوك",+ "pending": "في الانتظار",+ "completed": "مكتمل",+ "failed": "فشل",+ "clearFailed": "مسح المهام الفاشلة",+ "viewBullMq": "عرض لوحة Bull MQ",+ "disabledTitle": "Redis معطّل",+ "disabledDesc": "فعّل Redis للتخزين المؤقت وتخزين الجلسات وقوائم رسائل BullMQ.",+ "passwordOptional": "(اختياري)"+ },+ "storage": {+ "title": "إعدادات التخزين",+ "local": "نظام الملفات المحلي",+ "localDesc": "تخزين ملفات الوسائط محلياً",+ "s3": "Amazon S3",+ "s3Desc": "تخزين سحابي (متوافق مع S3)",+ "useBuiltIn": "استخدام حاوية MinIO المدمجة",+ "builtInDesc": "سيدير OpenWA حاوية MinIO (متوافقة مع S3) نيابةً عنك",+ "storagePath": "مسار التخزين",+ "bucket": "اسم الحاوية",+ "region": "المنطقة",+ "accessKey": "مفتاح الوصول",+ "secretKey": "المفتاح السري",+ "endpoint": "نقطة نهاية مخصصة (اختياري)",+ "endpointHint": "لـ MinIO أو خدمات متوافقة مع S3 أخرى"+ },+ "statusLabels": {+ "connected": "متصل",+ "disconnected": "غير متصل",+ "disabled": "معطّل"+ },+ "restart": {+ "idleTitle": "⚙️ تم حفظ الإعدادات",+ "restartingTitle": "🔄 جارٍ إعادة تشغيل الخادم...",+ "waitingTitle": "⏳ يرجى الانتظار...",+ "successTitle": "✅ الخادم جاهز",+ "errorTitle": "❌ فشلت إعادة التشغيل",+ "idleDesc": "تم حفظ الإعدادات في <code>.env.generated</code>.<br/>يلزم إعادة تشغيل الخادم لتطبيق التغييرات.",+ "later": "إعادة التشغيل لاحقاً",+ "now": "إعادة التشغيل الآن",+ "restartingMsg": "جارٍ إعادة تشغيل الخادم... {{count}} ثانية",+ "checking": "جارٍ التحقق من حالة الخادم...",+ "dontClose": "يرجى عدم إغلاق هذه النافذة",+ "successMsg": "الخادم يعمل مرة أخرى! ستُحدَّث الصفحة تلقائياً.",+ "errorMsg": "لم يستجب الخادم بعد 30 ثانية. يرجى مراجعة سجلات Docker وإعادة التشغيل يدوياً.",+ "reload": "إعادة تحميل الصفحة"+ },+ "toasts": {+ "saveFailed": "فشل الحفظ"+ }+ },+ "plugins": {+ "title": "الإضافات",+ "subtitle": "إدارة المحركات وواجهات التخزين والامتدادات",+ "refresh": "تحديث",+ "engineCard": "محرك واتساب النشط",+ "running": "يعمل",+ "supportedFeatures": "الميزات المدعومة:",+ "more": "+{{count}} أخرى",+ "builtIn": "مدمج",+ "noDescription": "لا يوجد وصف متاح",+ "required": "مطلوب",+ "active": "نشط",+ "activate": "تفعيل",+ "enable": "تمكين",+ "disable": "تعطيل",+ "healthCheck": "فحص الصحة",+ "configure": "إعداد",+ "empty": {+ "title": "لم يتم العثور على إضافات",+ "description": "ثبّت إضافات لتوسيع وظائف OpenWA"+ },+ "config": {+ "title": "إعداد {{name}}",+ "restartNotice": "تتطلب التغييرات إعادة تشغيل الخادم لتصبح فعّالة",+ "engineType": "نوع المحرك",+ "headless": "الوضع غير المرئي",+ "headlessDesc": "تشغيل المتصفح بدون واجهة مرئية (موصى به للإنتاج)",+ "sessionDataPath": "مسار بيانات الجلسة",+ "browserArgs": "مُعطيات المتصفح",+ "noOptions": "لا توجد خيارات إعداد لهذه الإضافة",+ "save": "حفظ الإعدادات"+ },+ "toasts": {+ "errorTitle": "خطأ في الإضافة",+ "errorDefault": "فشل تبديل حالة الإضافة",+ "healthOk": "نجح فحص الصحة",+ "healthFail": "فشل فحص الصحة",+ "healthError": "خطأ في فحص الصحة",+ "savedTitle": "تم حفظ الإعدادات",+ "savedDesc": "يلزم إعادة تشغيل الخادم لتطبيق التغييرات.",+ "saveFailed": "فشل الحفظ"+ }+ }+}diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 76c472908..5603d7609 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -56,6 +56,7 @@"nav": {"dashboard": "Dashboard","sessions": "Sessions",+ "chats": "Chats","webhooks": "Webhooks","apiKeys": "API Keys","messageTester": "Message Tester",@@ -63,6 +64,48 @@"plugins": "Plugins","logs": "Logs"},+ "chats": {+ "subtitle": "Send and reply to WhatsApp messages in real time",+ "noSessionsTitle": "No connected sessions",+ "noSessionsDesc": "Please connect a WhatsApp session from the <1>Sessions</1> menu first to use the chat feature.",+ "sessionLabel": "WhatsApp session",+ "noPhone": "No phone",+ "searchPlaceholder": "Search chats...",+ "loadingChats": "Loading chats...",+ "empty": "No chats",+ "noMessageYet": "No messages yet",+ "loadingMessages": "Loading messages...",+ "noMessagesInChat": "No messages yet. Send the first message to get started!",+ "downloadDocument": "Download document",+ "actions": {+ "reply": "Reply",+ "react": "React",+ "delete": "Delete message"+ },+ "replyingTo": "Replying to {{name}}",+ "you": "You",+ "youPrefix": "You: ",+ "yesterday": "Yesterday",+ "attachTitle": "Send file / image",+ "emojiTitle": "Pick emoji",+ "captionPlaceholder": "Add a caption...",+ "messagePlaceholder": "Type a message...",+ "noPermission": "You do not have permission to send messages",+ "send": "Send",+ "placeholderTitle": "Start messaging",+ "placeholderDesc": "Select an active chat from the left sidebar to start reading and sending WhatsApp messages.",+ "deleteConfirm": "Delete this message for everyone?",+ "messageDeleted": "🚫 This message was deleted",+ "errors": {+ "loadSessions": "Failed to load sessions",+ "loadChats": "Failed to load chats",+ "loadMessages": "Failed to load messages",+ "markRead": "Failed to mark chat as read",+ "send": "Failed to send message",+ "react": "Failed to react to message",+ "delete": "Failed to delete message"+ }+ },"errorBoundary": {"title": "Something went wrong","description": "The dashboard encountered an unexpected error.",@@ -186,12 +229,15 @@"readyTitle": "Session Ready","readyDesc": "WhatsApp session is now connected","disconnectedTitle": "Session Disconnected",- "disconnectedDesc": "WhatsApp session was disconnected"+ "disconnectedDesc": "WhatsApp session was disconnected",+ "failedTitle": "Session Failed",+ "failedDesc": "The WhatsApp session failed to start. Open the session to see the reason."},"card": {"phone": "Phone","sessionId": "Session ID",- "lastActive": "Last Active"+ "lastActive": "Last Active",+ "error": "Error"}},"webhooks": {@@ -475,7 +521,6 @@"engineCard": "Active WhatsApp Engine","running": "Running","supportedFeatures": "Supported Features:",- "more": "+{{count}} more","builtIn": "Built-in","noDescription": "No description available","required": "Required",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonnew file mode 100644index 000000000..7ad3a63c6--- /dev/null+++ b/dashboard/src/i18n/locales/fr.json@@ -0,0 +1,514 @@+{+ "common": {+ "appName": "OpenWA",+ "appSubtitle": "WhatsApp API",+ "loading": "Chargement...",+ "save": "Enregistrer",+ "cancel": "Annuler",+ "delete": "Supprimer",+ "edit": "Modifier",+ "create": "Créer",+ "close": "Fermer",+ "submit": "Soumettre",+ "confirm": "Confirmer",+ "search": "Rechercher",+ "filter": "Filtrer",+ "actions": "Actions",+ "status": "Statut",+ "name": "Nom",+ "role": "Rôle",+ "type": "Type",+ "url": "URL",+ "port": "Port",+ "host": "Hôte",+ "username": "Nom d'utilisateur",+ "password": "Mot de passe",+ "active": "Actif",+ "inactive": "Inactif",+ "enabled": "Activé",+ "disabled": "Désactivé",+ "connected": "Connecté",+ "disconnected": "Déconnecté",+ "never": "Jamais",+ "justNow": "À l'instant",+ "minAgo": "Il y a {{count}} min",+ "hoursAgo": "Il y a {{count}} heures",+ "optional": "optionnel",+ "language": "Langue",+ "english": "English",+ "hebrew": "עברית",+ "telugu": "తెలుగు",+ "french": "Français",+ "back": "Retour",+ "next": "Suivant",+ "previous": "Précédent",+ "expand": "Développer",+ "collapse": "Réduire",+ "logout": "Déconnexion",+ "refresh": "Actualiser",+ "errorGeneric": "Une erreur est survenue",+ "unknownError": "Erreur inconnue"+ },+ "theme": {+ "light": "Clair",+ "dark": "Sombre",+ "system": "Système",+ "label": "Thème : {{value}}"+ },+ "nav": {+ "dashboard": "Tableau de bord",+ "sessions": "Sessions",+ "webhooks": "Webhooks",+ "apiKeys": "Clés API",+ "messageTester": "Testeur de messages",+ "infrastructure": "Infrastructure",+ "plugins": "Plugins",+ "logs": "Journaux"+ },+ "errorBoundary": {+ "title": "Une erreur est survenue",+ "description": "Le tableau de bord a rencontré une erreur inattendue.",+ "reload": "Recharger le tableau de bord"+ },+ "login": {+ "apiKey": "Clé API",+ "apiKeyPlaceholder": "Entrez votre clé API",+ "apiKeyRequired": "La clé API est requise",+ "connect": "Connecter",+ "connecting": "Connexion...",+ "invalidKey": "Clé API invalide",+ "connectionError": "Impossible de se connecter au serveur. Veuillez réessayer.",+ "help": "Besoin d'aide ?",+ "viewDocs": "Voir la documentation",+ "footer": "Fait avec ❤️ par Yudhi Armyndharis et la communauté OpenWA",+ "version": "v{{version}} · {{date}}"+ },+ "dashboard": {+ "title": "Tableau de bord",+ "subtitle": "Aperçu de vos sessions WhatsApp et de votre activité",+ "stats": {+ "activeSessions": "Sessions actives",+ "messagesToday": "Messages aujourd'hui",+ "webhooksConfigured": "Webhooks configurés",+ "apiCalls": "Appels API (24h)"+ },+ "sessionsOverview": "Aperçu des sessions",+ "showingSessions": "Affichage de {{shown}} sur {{total}} sessions",+ "columns": {+ "sessionId": "ID de session",+ "phone": "Numéro de téléphone",+ "status": "Statut",+ "lastActive": "Dernière activité",+ "actions": "Actions"+ },+ "noSessions": "Aucune session trouvée. Créez-en une pour commencer.",+ "view": "Voir",+ "disconnect": "Déconnecter",+ "errorPrefix": "Erreur : {{message}}",+ "loadError": "Échec du chargement des données"+ },+ "sessionStatus": {+ "created": "Nouveau",+ "idle": "Inactif",+ "initializing": "Démarrage...",+ "connecting": "Connexion...",+ "qr_ready": "Scanner le QR",+ "ready": "Connecté",+ "disconnected": "Déconnecté"+ },+ "sessions": {+ "title": "Sessions",+ "subtitle": "Gérez vos sessions WhatsApp et vos connexions par code QR",+ "newSession": "Nouvelle session",+ "searchPlaceholder": "Rechercher des sessions...",+ "filter": {+ "all": "Tous les statuts",+ "active": "Actif (Connecté)",+ "inactive": "Inactif",+ "connecting": "Connexion en cours"+ },+ "empty": {+ "title": "Aucune session trouvée",+ "description": "Créez une nouvelle session pour commencer"+ },+ "create": {+ "title": "Créer une nouvelle session",+ "label": "Nom de la session",+ "placeholder": "ex : marketing-bot",+ "hint": "Utilisez uniquement des lettres minuscules, des chiffres et des tirets. Exemple : <code>customer-support</code>, <code>bot-1</code>",+ "invalidChars": "Caractères invalides. Seuls les lettres minuscules, les chiffres et les tirets sont autorisés.",+ "tooLong": "Le nom doit contenir 50 caractères ou moins ({{length}}/50).",+ "duplicate": "Une session avec ce nom existe déjà.",+ "successTitle": "Session créée",+ "successDesc": "La session \"{{name}}\" a été créée avec succès",+ "errorTitle": "Échec de la création",+ "errorDefault": "Impossible de créer la session"+ },+ "delete": {+ "title": "Confirmer la suppression",+ "message": "Êtes-vous sûr de vouloir supprimer la session <strong>\"{{name}}\"</strong> ?",+ "warning": "Cette action ne peut pas être annulée.",+ "successTitle": "Session supprimée",+ "successDescNamed": "Session \"{{name}}\" supprimée",+ "successDescGeneric": "Session supprimée",+ "errorTitle": "Échec de la suppression",+ "errorDefault": "Impossible de supprimer la session"+ },+ "qr": {+ "title": "Scanner le code QR",+ "step1": "<strong>1.</strong> Ouvrez WhatsApp sur votre téléphone",+ "step2": "<strong>2.</strong> Appuyez sur <strong>Menu</strong> → <strong>Appareils connectés</strong>",+ "step3": "<strong>3.</strong> Appuyez sur <strong>Connecter un appareil</strong> et scannez ce QR",+ "autoRefresh": "Le QR code s'actualise automatiquement toutes les 5 secondes",+ "generating": "Génération du code QR...",+ "unavailable": "Code QR non disponible pour le moment. Réessayez dans un instant.",+ "preparing": "Préparation du code QR...",+ "showQr": "Afficher le QR",+ "loading": "Chargement...",+ "scanToConnect": "Scannez le code QR pour vous connecter"+ },+ "details": {+ "title": "Détails de la session",+ "name": "Nom",+ "status": "Statut",+ "sessionId": "ID de session",+ "phone": "Numéro de téléphone",+ "phoneNone": "Non connecté",+ "created": "Créé le",+ "lastActive": "Dernière activité"+ },+ "actions": {+ "view": "Voir",+ "start": "Démarrer",+ "stop": "Arrêter",+ "reconnect": "Reconnecter",+ "delete": "Supprimer"+ },+ "toasts": {+ "readyTitle": "Session prête",+ "readyDesc": "La session WhatsApp est maintenant connectée",+ "disconnectedTitle": "Session déconnectée",+ "disconnectedDesc": "La session WhatsApp a été déconnectée"+ },+ "card": {+ "phone": "Téléphone",+ "sessionId": "ID de session",+ "lastActive": "Dernière activité"+ }+ },+ "webhooks": {+ "title": "Webhooks",+ "subtitle": "Configurez des rappels HTTP pour les notifications d'événements en temps réel",+ "addWebhook": "Ajouter un webhook",+ "createTitle": "Créer un webhook",+ "editTitle": "Modifier le webhook",+ "deleteTitle": "Supprimer le webhook",+ "deleteConfirm": "Êtes-vous sûr de vouloir supprimer ce webhook ?",+ "selectSession": "Sélectionner une session...",+ "session": "Session",+ "events": "Événements",+ "available": "Événements disponibles",+ "saveChanges": "Enregistrer les modifications",+ "columns": {+ "url": "URL",+ "events": "Événements",+ "session": "Session",+ "status": "Statut",+ "actions": "Actions"+ },+ "empty": {+ "title": "Aucun webhook configuré",+ "description": "Ajoutez un webhook pour recevoir des notifications d'événements en temps réel"+ },+ "toasts": {+ "created": "Webhook créé avec succès",+ "createFailed": "Échec de la création du webhook : {{message}}",+ "deleted": "Webhook supprimé avec succès",+ "deleteFailed": "Échec de la suppression du webhook : {{message}}",+ "updated": "Webhook mis à jour avec succès",+ "updateFailed": "Échec de la mise à jour du webhook : {{message}}",+ "testOk": "Test du webhook réussi ! Statut : {{status}}",+ "testFailed": "Test du webhook échoué : {{message}}",+ "testError": "Impossible de tester le webhook : {{message}}"+ },+ "actions": {+ "test": "Tester",+ "edit": "Modifier",+ "delete": "Supprimer"+ },+ "eventDescriptions": {+ "message.received": "Lorsqu'un message est reçu",+ "message.sent": "Lorsqu'un message est envoyé",+ "session.connected": "Lorsqu'une session se connecte",+ "session.disconnected": "Lorsqu'une session se déconnecte",+ "session.qr": "Lorsqu'un code QR est généré",+ "all": "Tous les événements"+ }+ },+ "apiKeys": {+ "title": "Clés API",+ "subtitle": "Gérez les clés API pour l'authentification et le contrôle d'accès",+ "createBtn": "Créer une clé API",+ "modalTitle": "Créer une clé API",+ "createdTitle": "Clé API créée",+ "createdHint": "Copiez cette clé maintenant. Vous ne pourrez plus la revoir.",+ "namePlaceholder": "ex : Clé de Production",+ "rolesTitle": "Référence des rôles",+ "roles": {+ "admin": "Administrateur",+ "operator": "Opérateur",+ "viewer": "Spectateur"+ },+ "roleDescriptions": {+ "admin": "Accès complet à toutes les ressources",+ "operator": "Gestion des sessions et des messages",+ "viewer": "Accès en lecture seule"+ },+ "columns": {+ "name": "Nom",+ "key": "Clé",+ "role": "Rôle",+ "status": "Statut",+ "lastUsed": "Dernière utilisation",+ "actions": "Actions"+ },+ "statuses": {+ "active": "Active",+ "revoked": "Révoquée"+ },+ "empty": {+ "title": "Aucune clé API créée",+ "description": "Créez une clé API pour authentifier vos requêtes"+ },+ "confirm": {+ "deleteTitle": "Supprimer la clé API",+ "revokeTitle": "Révoquer la clé API",+ "deleteMessage": "Êtes-vous sûr de vouloir supprimer définitivement <strong>{{name}}</strong> ? Cette action est irréversible.",+ "revokeMessage": "Êtes-vous sûr de vouloir révoquer <strong>{{name}}</strong> ? Elle ne fonctionnera plus.",+ "delete": "Supprimer",+ "revoke": "Révoquer"+ },+ "actions": {+ "copy": "Copier",+ "revoke": "Révoquer",+ "delete": "Supprimer"+ }+ },+ "logs": {+ "title": "Journaux d'audit",+ "subtitle": "Suivez et examinez toutes les actions de l'API et les événements système",+ "exportCsv": "Exporter en CSV",+ "searchPlaceholder": "Rechercher dans les journaux...",+ "severity": {+ "all": "Toutes les gravités",+ "info": "Info",+ "warn": "Avertissement",+ "error": "Erreur"+ },+ "columns": {+ "timestamp": "Horodatage",+ "action": "Action",+ "session": "Session",+ "apiKey": "Clé API",+ "ip": "Adresse IP",+ "severity": "Gravité"+ },+ "empty": {+ "title": "Aucun journal trouvé",+ "description": "Les journaux d'audit apparaîtront ici au fur et à mesure des actions"+ }+ },+ "messageTester": {+ "title": "Testeur de messages",+ "subtitle": "Envoyez des messages de test via l'API",+ "compose": "Envoyer un message de test",+ "responseTitle": "Réponse de l'API",+ "session": "Session",+ "noReadySessions": "Aucune session prête",+ "sessionOptionPhoneNone": "Aucun téléphone",+ "recipientType": "Type de destinataire",+ "personal": "Personnel",+ "group": "Groupe",+ "selectGroup": "Sélectionner un groupe",+ "recipientPhone": "Numéro de téléphone du destinataire",+ "loadingGroups": "Chargement des groupes...",+ "noGroupsFound": "Aucun groupe trouvé",+ "selectGroupHint": "Sélectionnez un groupe depuis votre WhatsApp",+ "phoneHint": "Utilisez le format international sans espaces",+ "messageType": "Type de message",+ "types": {+ "text": "Texte",+ "image": "Image",+ "video": "Vidéo",+ "audio": "Audio",+ "document": "Document"+ },+ "messageContent": "Contenu du message",+ "messagePlaceholder": "Entrez votre message ici...",+ "mediaUrl": "URL du média",+ "caption": "Légende",+ "filename": "Nom du fichier",+ "captionPlaceholder": "Entrez une légende...",+ "filenamePlaceholder": "document.pdf",+ "send": "Envoyer le message",+ "sending": "Envoi...",+ "viewOnly": "Lecture seule",+ "responseEmpty": "Envoyez un message pour voir la réponse de l'API",+ "successLabel": "200 OK - Succès",+ "failedLabel": "400 - Échec",+ "response": {+ "timestamp": "Horodatage",+ "messageId": "ID du message",+ "error": "Erreur"+ },+ "sendFailed": "Échec de l'envoi du message"+ },+ "infrastructure": {+ "title": "Infrastructure",+ "subtitle": "Configurez les paramètres du serveur, de la base de données, du cache, du stockage et du moteur",+ "saveConfig": "Enregistrer la configuration",+ "saving": "Enregistrement...",+ "server": {+ "title": "Configuration du serveur",+ "production": "Production",+ "development": "Développement",+ "environment": "Environnement",+ "domain": "Domaine",+ "apiPort": "Port API",+ "dashboardPort": "Port du tableau de bord",+ "corsOrigins": "Origines CORS",+ "corsPlaceholder": "* ou origines séparées par des virgules",+ "publicApiUrl": "URL publique de l'API (optionnel)",+ "publicDashboardUrl": "URL publique du tableau de bord (optionnel)"+ },+ "webhook": {+ "title": "Webhook & Limitation de débit",+ "settings": "Paramètres du webhook",+ "timeout": "Délai d'attente (ms)",+ "maxRetries": "Tentatives max",+ "retryDelay": "Délai entre les tentatives (ms)",+ "rateLimit": "Limitation de débit",+ "window": "Fenêtre de temps (secondes)",+ "maxReq": "Requêtes max par fenêtre"+ },+ "database": {+ "title": "Configuration de la base de données",+ "sqlite": "SQLite",+ "sqliteDesc": "Base de données locale basée sur un fichier",+ "postgres": "PostgreSQL",+ "postgresDesc": "Base de données prête pour la production",+ "useBuiltIn": "Utiliser le conteneur PostgreSQL intégré",+ "builtInDesc": "OpenWA gérera un conteneur PostgreSQL pour vous",+ "dbName": "Nom de la base de données",+ "poolSize": "Taille du pool",+ "ssl": "Connexion SSL",+ "sslDesc": "Activer TLS/SSL pour des connexions sécurisées à la base de données",+ "migrationsTitle": "Migrations de base de données",+ "migrationsStatus": "Le schéma est auto-synchronisé avec TypeORM",+ "migrationsHint": "Les migrations sont gérées automatiquement. Utilisez la CLI pour les migrations manuelles."+ },+ "redis": {+ "title": "Redis",+ "enable": "Activer Redis",+ "enableDesc": "Requis pour le cache, le stockage des sessions et les files d'attente BullMQ",+ "useBuiltIn": "Utiliser le conteneur Redis intégré",+ "builtInDesc": "OpenWA gérera un conteneur Redis pour vous",+ "queueTitle": "Activer le système de file d'attente BullMQ",+ "queueDesc": "Utiliser des files d'attente pour une livraison fiable des messages et des webhooks",+ "statsTitle": "Statistiques de la file d'attente",+ "messageQueue": "File d'attente des messages",+ "webhookQueue": "File d'attente des webhooks",+ "pending": "En attente",+ "completed": "Terminé",+ "failed": "Échoué",+ "clearFailed": "Effacer les tâches échouées",+ "viewBullMq": "Voir le tableau de bord Bull MQ",+ "disabledTitle": "Redis est désactivé",+ "disabledDesc": "Activez Redis pour le cache, le stockage des sessions et les files d'attente de messages BullMQ.",+ "passwordOptional": "(optionnel)"+ },+ "storage": {+ "title": "Configuration du stockage",+ "local": "Système de fichiers local",+ "localDesc": "Stocker les fichiers médias localement",+ "s3": "Amazon S3",+ "s3Desc": "Stockage cloud (compatible S3)",+ "useBuiltIn": "Utiliser le conteneur MinIO intégré",+ "builtInDesc": "OpenWA gérera un conteneur MinIO (compatible S3) pour vous",+ "storagePath": "Chemin de stockage",+ "bucket": "Nom du bucket",+ "region": "Région",+ "accessKey": "Clé d'accès",+ "secretKey": "Clé secrète",+ "endpoint": "Point de terminaison personnalisé (optionnel)",+ "endpointHint": "Pour MinIO ou d'autres services compatibles S3"+ },+ "statusLabels": {+ "connected": "Connecté",+ "disconnected": "Déconnecté",+ "disabled": "Désactivé"+ },+ "restart": {+ "idleTitle": "⚙️ Configuration enregistrée",+ "restartingTitle": "🔄 Redémarrage du serveur...",+ "waitingTitle": "⏳ Veuillez patienter...",+ "successTitle": "✅ Serveur prêt",+ "errorTitle": "❌ Échec du redémarrage",+ "idleDesc": "La configuration a été enregistrée dans <code>.env.generated</code>.<br/>Un redémarrage du serveur est nécessaire pour appliquer les modifications.",+ "later": "Redémarrer plus tard",+ "now": "Redémarrer maintenant",+ "restartingMsg": "Redémarrage du serveur... {{count}}s",+ "checking": "Vérification du statut du serveur...",+ "dontClose": "Veuillez ne pas fermer cette fenêtre",+ "successMsg": "Le serveur est de nouveau en ligne ! La page va se recharger automatiquement.",+ "errorMsg": "Le serveur n'a pas répondu après 30 secondes. Veuillez vérifier les journaux Docker et redémarrer manuellement.",+ "reload": "Recharger la page"+ },+ "toasts": {+ "saveFailed": "Échec de l'enregistrement"+ }+ },+ "plugins": {+ "title": "Plugins",+ "subtitle": "Gérez les moteurs, les backends de stockage et les extensions",+ "refresh": "Actualiser",+ "engineCard": "Moteur WhatsApp actif",+ "running": "En cours d'exécution",+ "supportedFeatures": "Fonctionnalités supportées :",+ "more": "+{{count}} de plus",+ "builtIn": "Intégré",+ "noDescription": "Aucune description disponible",+ "required": "Requis",+ "active": "Actif",+ "activate": "Activer",+ "enable": "Activer",+ "disable": "Désactiver",+ "healthCheck": "Bilan de santé",+ "configure": "Configurer",+ "empty": {+ "title": "Aucun plugin trouvé",+ "description": "Installez des plugins pour étendre les fonctionnalités d'OpenWA"+ },+ "config": {+ "title": "Configurer {{name}}",+ "restartNotice": "Les modifications nécessitent un redémarrage du serveur pour prendre effet",+ "engineType": "Type de moteur",+ "headless": "Mode sans tête (Headless)",+ "headlessDesc": "Exécuter le navigateur sans interface visible (recommandé pour la production)",+ "sessionDataPath": "Chemin des données de session",+ "browserArgs": "Arguments du navigateur",+ "noOptions": "Aucune option de configuration disponible pour ce plugin",+ "save": "Enregistrer la configuration"+ },+ "toasts": {+ "errorTitle": "Erreur de plugin",+ "errorDefault": "Échec du basculement du plugin",+ "healthOk": "Bilan de santé réussi",+ "healthFail": "Bilan de santé échoué",+ "healthError": "Erreur lors du bilan de santé",+ "savedTitle": "Configuration enregistrée",+ "savedDesc": "Redémarrage du serveur requis pour appliquer les modifications.",+ "saveFailed": "Échec de l'enregistrement"+ }+ }+}\ No newline at end of filediff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex a84ac60a6..115dfd7a3 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -56,6 +56,7 @@"nav": {"dashboard": "דאשבורד","sessions": "Sessions",+ "chats": "שיחות","webhooks": "Webhooks","apiKeys": "מפתחות API","messageTester": "בדיקת הודעות",@@ -63,6 +64,48 @@"plugins": "תוספים","logs": "לוגים"},+ "chats": {+ "subtitle": "שליחה ומענה להודעות WhatsApp בזמן אמת",+ "noSessionsTitle": "אין סשנים מחוברים",+ "noSessionsDesc": "יש לחבר סשן WhatsApp מתפריט <1>Sessions</1> תחילה כדי להשתמש בתכונת הצ'אט.",+ "sessionLabel": "סשן WhatsApp",+ "noPhone": "אין מספר טלפון",+ "searchPlaceholder": "חיפוש שיחות...",+ "loadingChats": "טוען שיחות...",+ "empty": "אין שיחות",+ "noMessageYet": "אין הודעות עדיין",+ "loadingMessages": "טוען הודעות...",+ "noMessagesInChat": "אין הודעות עדיין. שלח את ההודעה הראשונה כדי להתחיל!",+ "downloadDocument": "הורדת מסמך",+ "actions": {+ "reply": "השב",+ "react": "תגובה",+ "delete": "מחק הודעה"+ },+ "replyingTo": "משיב ל-{{name}}",+ "you": "אתה",+ "youPrefix": "אתה: ",+ "yesterday": "אתמול",+ "attachTitle": "שליחת קובץ / תמונה",+ "emojiTitle": "בחירת אימוג'י",+ "captionPlaceholder": "הוספת כיתוב...",+ "messagePlaceholder": "הקלד הודעה...",+ "noPermission": "אין לך הרשאה לשלוח הודעות",+ "send": "שלח",+ "placeholderTitle": "התחל לשלוח הודעות",+ "placeholderDesc": "בחר שיחה פעילה מהסרגל הצדדי כדי להתחיל לקרוא ולשלוח הודעות WhatsApp.",+ "deleteConfirm": "למחוק הודעה זו עבור כולם?",+ "messageDeleted": "🚫 הודעה זו נמחקה",+ "errors": {+ "loadSessions": "טעינת הסשנים נכשלה",+ "loadChats": "טעינת השיחות נכשלה",+ "loadMessages": "טעינת ההודעות נכשלה",+ "markRead": "סימון השיחה כנקראה נכשל",+ "send": "שליחת ההודעה נכשלה",+ "react": "התגובה להודעה נכשלה",+ "delete": "מחיקת ההודעה נכשלה"+ }+ },"errorBoundary": {"title": "משהו השתבש","description": "הדאשבורד נתקל בשגיאה לא צפויה.",@@ -186,12 +229,15 @@"readyTitle": "ה-Session מוכן","readyDesc": "ה-Session של WhatsApp מחובר","disconnectedTitle": "ה-Session נותק",- "disconnectedDesc": "ה-Session של WhatsApp נותק"+ "disconnectedDesc": "ה-Session של WhatsApp נותק",+ "failedTitle": "ה-Session נכשל",+ "failedDesc": "ה-Session של WhatsApp נכשל באתחול. פתחו את ה-Session כדי לראות את הסיבה."},"card": {"phone": "טלפון","sessionId": "מזהה Session",- "lastActive": "פעילות אחרונה"+ "lastActive": "פעילות אחרונה",+ "error": "שגיאה"}},"webhooks": {@@ -475,7 +521,6 @@"engineCard": "מנוע WhatsApp פעיל","running": "פועל","supportedFeatures": "תכונות נתמכות:",- "more": "+{{count}} נוספים","builtIn": "מובנה","noDescription": "אין תיאור זמין","required": "נדרש",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonnew file mode 100644index 000000000..b17b2a3a2--- /dev/null+++ b/dashboard/src/i18n/locales/it.json@@ -0,0 +1,515 @@+{+ "common": {+ "appName": "OpenWA",+ "appSubtitle": "WhatsApp API",+ "loading": "Caricamento...",+ "save": "Salva",+ "cancel": "Annulla",+ "delete": "Elimina",+ "edit": "Modifica",+ "create": "Crea",+ "close": "Chiudi",+ "submit": "Invia",+ "confirm": "Conferma",+ "search": "Cerca",+ "filter": "Filtra",+ "actions": "Azioni",+ "status": "Stato",+ "name": "Nome",+ "role": "Ruolo",+ "type": "Tipo",+ "url": "URL",+ "port": "Porta",+ "host": "Host",+ "username": "Nome utente",+ "password": "Password",+ "active": "Attivo",+ "inactive": "Inattivo",+ "enabled": "Abilitato",+ "disabled": "Disabilitato",+ "connected": "Connesso",+ "disconnected": "Disconnesso",+ "never": "Mai",+ "justNow": "Ora",+ "minAgo": "{{count}} min fa",+ "hoursAgo": "{{count}} ore fa",+ "optional": "opzionale",+ "language": "Lingua",+ "english": "Inglese",+ "hebrew": "עברית",+ "italian": "Italiano",+ "back": "Indietro",+ "next": "Avanti",+ "previous": "Precedente",+ "expand": "Espandi",+ "collapse": "Riduci",+ "logout": "Disconnetti",+ "refresh": "Aggiorna",+ "errorGeneric": "Si è verificato un errore",+ "unknownError": "Errore sconosciuto"+ },+ "theme": {+ "light": "Chiaro",+ "dark": "Scuro",+ "system": "Sistema",+ "label": "Tema: {{value}}"+ },+ "nav": {+ "dashboard": "Dashboard",+ "sessions": "Sessioni",+ "webhooks": "Webhook",+ "apiKeys": "Chiavi API",+ "messageTester": "Tester Messaggi",+ "infrastructure": "Infrastruttura",+ "plugins": "Plugin",+ "logs": "Log"+ },+ "errorBoundary": {+ "title": "Qualcosa è andato storto",+ "description": "La dashboard ha riscontrato un errore imprevisto.",+ "reload": "Ricarica Dashboard"+ },+ "login": {+ "apiKey": "Chiave API",+ "apiKeyPlaceholder": "Inserisci la tua chiave API",+ "apiKeyRequired": "La chiave API è richiesta",+ "connect": "Connetti",+ "connecting": "Connessione in corso...",+ "invalidKey": "Chiave API non valida",+ "connectionError": "Impossibile connettersi al server. Riprova.",+ "help": "Serve aiuto?",+ "viewDocs": "Visualizza la documentazione",+ "footer": "Fatto con ❤️ da Yudhi Armyndharis e dalla Community di OpenWA",+ "version": "v{{version}} · {{date}}"+ },+ "dashboard": {+ "title": "Dashboard",+ "subtitle": "Panoramica delle sessioni WhatsApp e delle attività",+ "stats": {+ "activeSessions": "Sessioni Attive",+ "messagesToday": "Messaggi di Oggi",+ "webhooksConfigured": "Webhook Configurati",+ "apiCalls": "Chiamate API (24h)"+ },+ "sessionsOverview": "Panoramica Sessioni",+ "showingSessions": "Visualizzazione di {{shown}} di {{total}} sessioni",+ "columns": {+ "sessionId": "ID Sessione",+ "phone": "Numero di Telefono",+ "status": "Stato",+ "lastActive": "Ultima Attività",+ "actions": "Azioni"+ },+ "noSessions": "Nessuna sessione trovata. Creane una per iniziare.",+ "view": "Visualizza",+ "disconnect": "Disconnetti",+ "errorPrefix": "Errore: {{message}}",+ "loadError": "Impossibile caricare i dati"+ },+ "sessionStatus": {+ "created": "Nuova",+ "idle": "Inattiva",+ "initializing": "Avvio in corso...",+ "connecting": "Connessione in corso...",+ "qr_ready": "Scansiona QR",+ "ready": "Connesso",+ "disconnected": "Disconnesso"+ },+ "sessions": {+ "title": "Sessioni",+ "subtitle": "Gestisci le tue sessioni WhatsApp e le connessioni tramite codice QR",+ "newSession": "Nuova Sessione",+ "searchPlaceholder": "Cerca sessioni...",+ "filter": {+ "all": "Tutti gli stati",+ "active": "Attive (Connesse)",+ "inactive": "Inattive",+ "connecting": "In connessione"+ },+ "empty": {+ "title": "Nessuna sessione trovata",+ "description": "Crea una nuova sessione per iniziare"+ },+ "create": {+ "title": "Crea Nuova Sessione",+ "label": "Nome Sessione",+ "placeholder": "es., marketing-bot",+ "hint": "Usa solo lettere minuscole, numeri e trattini. Esempio: <code>supporto-clienti</code>, <code>bot-1</code>",+ "invalidChars": "Caratteri non validi. Sono ammessi solo lettere minuscole, numeri e trattini.",+ "tooLong": "Il nome deve contenere al massimo 50 caratteri ({{length}}/50).",+ "duplicate": "Esiste già una sessione con questo nome.",+ "successTitle": "Sessione Creata",+ "successDesc": "Sessione \"{{name}}\" creata con successo",+ "errorTitle": "Creazione Fallita",+ "errorDefault": "Impossibile creare la sessione"+ },+ "delete": {+ "title": "Conferma Eliminazione",+ "message": "Sei sicuro di voler eliminare la sessione <strong>\"{{name}}\"</strong>?",+ "warning": "Questa azione non può essere annullata.",+ "successTitle": "Sessione Eliminata",+ "successDescNamed": "Sessione \"{{name}}\" eliminata",+ "successDescGeneric": "Sessione eliminata",+ "errorTitle": "Eliminazione Fallita",+ "errorDefault": "Impossibile eliminare la sessione"+ },+ "qr": {+ "title": "Scansiona il Codice QR",+ "step1": "<strong>1.</strong> Apri WhatsApp sul tuo telefono",+ "step2": "<strong>2.</strong> Tocca <strong>Menu</strong> → <strong>Dispositivi collegati</strong>",+ "step3": "<strong>3.</strong> Tocca <strong>Collega un dispositivo</strong> e scansiona questo QR",+ "autoRefresh": "Il codice QR si aggiorna automaticamente ogni 5 secondi",+ "generating": "Generazione del codice QR in corso...",+ "unavailable": "Codice QR non ancora disponibile. Riprova tra un momento.",+ "preparing": "Preparazione del codice QR...",+ "showQr": "Mostra QR",+ "loading": "Caricamento...",+ "scanToConnect": "Scansiona il codice QR per connetterti"+ },+ "details": {+ "title": "Dettagli Sessione",+ "name": "Nome",+ "status": "Stato",+ "sessionId": "ID Sessione",+ "phone": "Numero di Telefono",+ "phoneNone": "Non connesso",+ "created": "Creata",+ "lastActive": "Ultima Attività"+ },+ "actions": {+ "view": "Visualizza",+ "start": "Avvia",+ "stop": "Ferma",+ "reconnect": "Riconnetti",+ "delete": "Elimina"+ },+ "toasts": {+ "readyTitle": "Sessione Pronta",+ "readyDesc": "La sessione WhatsApp è ora connessa",+ "disconnectedTitle": "Sessione Disconnessa",+ "disconnectedDesc": "La sessione WhatsApp è stata disconnessa"+ },+ "card": {+ "phone": "Telefono",+ "sessionId": "ID Sessione",+ "lastActive": "Ultima Attività"+ }+ },+ "webhooks": {+ "title": "Webhook",+ "subtitle": "Configura i callback HTTP per le notifiche degli eventi in tempo reale",+ "addWebhook": "Aggiungi Webhook",+ "createTitle": "Crea Webhook",+ "editTitle": "Modifica Webhook",+ "deleteTitle": "Elimina Webhook",+ "deleteConfirm": "Sei sicuro di voler eliminare questo webhook?",+ "selectSession": "Seleziona sessione...",+ "session": "Sessione",+ "events": "Eventi",+ "available": "Eventi Disponibili",+ "saveChanges": "Salva Modifiche",+ "columns": {+ "url": "URL",+ "events": "Eventi",+ "session": "Sessione",+ "status": "Stato",+ "actions": "Azioni"+ },+ "empty": {+ "title": "Nessun webhook configurato",+ "description": "Aggiungi un webhook per ricevere le notifiche degli eventi in tempo reale"+ },+ "toasts": {+ "created": "Webhook creato con successo",+ "createFailed": "Impossibile creare il webhook: {{message}}",+ "deleted": "Webhook eliminato con successo",+ "deleteFailed": "Impossibile eliminare il webhook: {{message}}",+ "updated": "Webhook aggiornato con successo",+ "updateFailed": "Impossibile aggiornare il webhook: {{message}}",+ "testOk": "Test del webhook riuscito! Stato: {{status}}",+ "testFailed": "Test del webhook fallito: {{message}}",+ "testError": "Impossibile testare il webhook: {{message}}"+ },+ "actions": {+ "test": "Test",+ "edit": "Modifica",+ "delete": "Elimina"+ },+ "eventDescriptions": {+ "message.received": "Quando viene ricevuto un messaggio",+ "message.sent": "Quando viene inviato un messaggio",+ "session.connected": "Quando una sessione si connette",+ "session.disconnected": "Quando una sessione si disconnette",+ "session.qr": "Quando viene generato un codice QR",+ "all": "Tutti gli eventi"+ }+ },+ "apiKeys": {+ "title": "Chiavi API",+ "subtitle": "Gestisci le chiavi API per l'autenticazione e il controllo degli accessi",+ "createBtn": "Crea Chiave API",+ "modalTitle": "Crea Chiave API",+ "createdTitle": "Chiave API Creata",+ "createdHint": "Copia questa chiave ora. Non potrai più visualizzarla.",+ "namePlaceholder": "es., Chiave di Produzione",+ "rolesTitle": "Riferimento Ruoli",+ "roles": {+ "admin": "Amministratore",+ "operator": "Operatore",+ "viewer": "Visualizzatore"+ },+ "roleDescriptions": {+ "admin": "Accesso completo a tutte le risorse",+ "operator": "Gestione delle sessioni e dei messaggi",+ "viewer": "Accesso in sola lettura"+ },+ "columns": {+ "name": "Nome",+ "key": "Chiave",+ "role": "Ruolo",+ "status": "Stato",+ "lastUsed": "Ultimo Utilizzo",+ "actions": "Azioni"+ },+ "statuses": {+ "active": "Attiva",+ "revoked": "Revocata"+ },+ "empty": {+ "title": "Nessuna chiave API creata",+ "description": "Crea una chiave API per autenticare le tue richieste"+ },+ "confirm": {+ "deleteTitle": "Elimina Chiave API",+ "revokeTitle": "Revoca Chiave API",+ "deleteMessage": "Sei sicuro di voler eliminare permanentemente <strong>{{name}}</strong>? Questa azione non può essere annullata.",+ "revokeMessage": "Sei sicuro di voler revocare <strong>{{name}}</strong>? Smetterà di funzionare.",+ "delete": "Elimina",+ "revoke": "Revoca"+ },+ "actions": {+ "copy": "Copia",+ "revoke": "Revoca",+ "delete": "Elimina"+ }+ },+ "logs": {+ "title": "Registri di Controllo",+ "subtitle": "Traccia ed esamina tutte le azioni API e gli eventi di sistema",+ "exportCsv": "Esporta CSV",+ "searchPlaceholder": "Cerca nei log...",+ "severity": {+ "all": "Tutte le gravità",+ "info": "Info",+ "warn": "Avviso",+ "error": "Errore"+ },+ "columns": {+ "timestamp": "Timestamp",+ "action": "Azione",+ "session": "Sessione",+ "apiKey": "Chiave API",+ "ip": "Indirizzo IP",+ "severity": "Gravità"+ },+ "empty": {+ "title": "Nessun registro trovato",+ "description": "I registri di controllo appariranno qui man mano che verranno eseguite le azioni"+ }+ },+ "messageTester": {+ "title": "Tester Messaggi",+ "subtitle": "Invia messaggi di prova tramite le API",+ "compose": "Invia Messaggio di Prova",+ "responseTitle": "Risposta API",+ "session": "Sessione",+ "noReadySessions": "Nessuna sessione pronta",+ "sessionOptionPhoneNone": "Nessun telefono",+ "recipientType": "Tipo di Destinatario",+ "personal": "Personale",+ "group": "Gruppo",+ "selectGroup": "Seleziona Gruppo",+ "recipientPhone": "Numero di Telefono Destinatario",+ "loadingGroups": "Caricamento gruppi...",+ "noGroupsFound": "Nessun gruppo trovato",+ "selectGroupHint": "Seleziona un gruppo dal tuo WhatsApp",+ "phoneHint": "Usa il formato internazionale senza spazi",+ "messageType": "Tipo di Messaggio",+ "types": {+ "text": "Testo",+ "image": "Immagine",+ "video": "Video",+ "audio": "Audio",+ "document": "Documento"+ },+ "messageContent": "Contenuto del Messaggio",+ "messagePlaceholder": "Inserisci qui il tuo messaggio...",+ "mediaUrl": "URL File Multimediale",+ "caption": "Didascalia",+ "filename": "Nome File",+ "captionPlaceholder": "Inserisci una didascalia...",+ "filenamePlaceholder": "documento.pdf",+ "send": "Invia Messaggio",+ "sending": "Invio in corso...",+ "viewOnly": "Sola Visualizzazione",+ "responseEmpty": "Invia un messaggio per vedere la risposta delle API",+ "successLabel": "200 OK - Successo",+ "failedLabel": "400 - Fallito",+ "response": {+ "timestamp": "Timestamp",+ "messageId": "ID Messaggio",+ "error": "Errore"+ },+ "sendFailed": "Impossibile inviare il messaggio"+ },+ "infrastructure": {+ "title": "Infrastruttura",+ "subtitle": "Configura le impostazioni del server, del database, della cache, dello storage e del motore",+ "saveConfig": "Salva Configurazione",+ "saving": "Salvataggio...",+ "server": {+ "title": "Configurazione Server",+ "production": "Produzione",+ "development": "Sviluppo",+ "environment": "Ambiente",+ "domain": "Dominio",+ "apiPort": "Porta API",+ "dashboardPort": "Porta Dashboard",+ "corsOrigins": "Origini CORS",+ "corsPlaceholder": "* o origini separate da virgola",+ "publicApiUrl": "URL API Pubblico (opzionale)",+ "publicDashboardUrl": "URL Dashboard Pubblico (opzionale)"+ },+ "webhook": {+ "title": "Webhook e Limitazione Frequenza",+ "settings": "Impostazioni Webhook",+ "timeout": "Timeout (ms)",+ "maxRetries": "Tentativi Massimi",+ "retryDelay": "Ritardo Tentativi (ms)",+ "rateLimit": "Limitazione Frequenza (Rate Limiting)",+ "window": "Finestra Temporale (secondi)",+ "maxReq": "Richieste Massime per Finestra"+ },+ "database": {+ "title": "Configurazione Database",+ "sqlite": "SQLite",+ "sqliteDesc": "Database locale basato su file",+ "postgres": "PostgreSQL",+ "postgresDesc": "Database pronto per la produzione",+ "useBuiltIn": "Usa Container PostgreSQL Integrato",+ "builtInDesc": "OpenWA gestirà un container PostgreSQL per te",+ "dbName": "Nome Database",+ "poolSize": "Dimensione del Pool",+ "ssl": "Connessione SSL",+ "sslDesc": "Abilita TLS/SSL per connessioni sicure al database",+ "sslRejectUnauthorized": "Verifica Certificato SSL",+ "sslRejectUnauthorizedDesc": "Rifiuta i certificati auto-firmati o non validi. Disabilita per Postgres gestiti con certificati auto-firmati (Supabase, Heroku, Render, Railway).",+ "migrationsTitle": "Migrazioni Database",+ "migrationsStatus": "Lo schema è sincronizzato automaticamente con TypeORM",+ "migrationsHint": "Le migrazioni sono gestite automaticamente. Usa la CLI per le migrazioni manuali."+ },+ "redis": {+ "title": "Redis",+ "enable": "Abilita Redis",+ "enableDesc": "Richiesto per la memorizzazione della cache, dello storage di sessione e delle code BullMQ",+ "useBuiltIn": "Usa Container Redis Integrato",+ "builtInDesc": "OpenWA gestirà un container Redis per te",+ "queueTitle": "Abilita Sistema di Code BullMQ",+ "queueDesc": "Usa le code di messaggi per una consegna affidabile di messaggi e webhook",+ "statsTitle": "Statistiche delle Code",+ "messageQueue": "Coda Messaggi",+ "webhookQueue": "Coda Webhook",+ "pending": "In attesa",+ "completed": "Completati",+ "failed": "Falliti",+ "clearFailed": "Cancella Processi Falliti",+ "viewBullMq": "Visualizza Dashboard BullMQ",+ "disabledTitle": "Redis è Disabilitato",+ "disabledDesc": "Abilita Redis per la cache, lo storage delle sessioni e le code di messaggi BullMQ.",+ "passwordOptional": "(opzionale)"+ },+ "storage": {+ "title": "Configurazione Storage",+ "local": "Filesystem Locale",+ "localDesc": "Memorizza i file multimediali localmente",+ "s3": "Amazon S3",+ "s3Desc": "Archiviazione Cloud (compatibile con S3)",+ "useBuiltIn": "Usa Container MinIO Integrato",+ "builtInDesc": "OpenWA gestirà un container MinIO (compatibile con S3) per te",+ "storagePath": "Percorso Archiviazione",+ "bucket": "Nome Bucket",+ "region": "Regione",+ "accessKey": "Access Key",+ "secretKey": "Secret Key",+ "endpoint": "Endpoint Personalizzato (opzionale)",+ "endpointHint": "Per MinIO o altri servizi compatibili con S3"+ },+ "statusLabels": {+ "connected": "Connesso",+ "disconnected": "Disconnesso",+ "disabled": "Disabilitato"+ },+ "restart": {+ "idleTitle": "⚙️ Configurazione Salvata",+ "restartingTitle": "🔄 Riavvio del Server...",+ "waitingTitle": "⏳ Attendere Prego...",+ "successTitle": "✅ Server Pronto",+ "errorTitle": "❌ Riavvio Fallito",+ "idleDesc": "La configurazione è stata salvata in <code>.env.generated</code>.<br/>È richiesto un riavvio del server per applicare le modifiche.",+ "later": "Riavvia Più Tardi",+ "now": "Riavvia Ora",+ "restartingMsg": "Riavvio del server... {{count}}s",+ "checking": "Verifica dello stato del server...",+ "dontClose": "Si prega di non chiudere questa finestra",+ "successMsg": "Il server è di nuovo online! La pagina si ricaricherà automaticamente.",+ "errorMsg": "Il server non ha risposto dopo 30 secondi. Controlla i log di Docker e riavvia manualmente.",+ "reload": "Ricarica Pagina"+ },+ "toasts": {+ "saveFailed": "Salvataggio Fallito"+ }+ },+ "plugins": {+ "title": "Plugin",+ "subtitle": "Gestisci i motori, i backend di storage e le estensioni",+ "refresh": "Aggiorna",+ "engineCard": "Motore WhatsApp Attivo",+ "running": "In esecuzione",+ "supportedFeatures": "Funzionalità Supportate:",+ "more": "+altri {{count}}",+ "builtIn": "Integrato",+ "noDescription": "Nessuna descrizione disponibile",+ "required": "Richiesto",+ "active": "Attivo",+ "activate": "Attiva",+ "enable": "Abilita",+ "disable": "Disabilita",+ "healthCheck": "Controllo dello Stato (Health Check)",+ "configure": "Configura",+ "empty": {+ "title": "Nessun Plugin Trovato",+ "description": "Installa i plugin per estendere le funzionalità di OpenWA"+ },+ "config": {+ "title": "Configura {{name}}",+ "restartNotice": "Le modifiche richiedono il riavvio del server per avere effetto",+ "engineType": "Tipo di Motore",+ "headless": "Modalità Headless",+ "headlessDesc": "Esegui il browser senza interfaccia grafica visibile (consigliato in produzione)",+ "sessionDataPath": "Percorso Dati Sessione",+ "browserArgs": "Argomenti del Browser",+ "noOptions": "Nessuna opzione di configurazione disponibile per questo plugin",+ "save": "Salva Configurazione"+ },+ "toasts": {+ "errorTitle": "Errore Plugin",+ "errorDefault": "Impossibile attivare/disattivare il plugin",+ "healthOk": "Controllo dello Stato Riuscito",+ "healthFail": "Controllo dello Stato Fallito",+ "healthError": "Errore nel Controllo dello Stato",+ "savedTitle": "Configurazione Salvata",+ "savedDesc": "È richiesto il riavvio del server per applicare le modifiche.",+ "saveFailed": "Salvataggio non riuscito"+ }+ }+}diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonnew file mode 100644index 000000000..47835e91d--- /dev/null+++ b/dashboard/src/i18n/locales/te.json@@ -0,0 +1,514 @@+{+ "common": {+ "appName": "OpenWA",+ "appSubtitle": "WhatsApp API",+ "loading": "లోడ్ అవుతోంది...",+ "save": "సేవ్ చేయి",+ "cancel": "రద్దు చేయి",+ "delete": "తొలగించు",+ "edit": "ఎడిట్ చేయి",+ "create": "సృష్టించు",+ "close": "మూసివేయి",+ "submit": "సమర్పించు",+ "confirm": "ధృవీకరించు",+ "search": "వెతుకు",+ "filter": "ఫిల్టర్",+ "actions": "చర్యలు",+ "status": "స్థితి",+ "name": "పేరు",+ "role": "పాత్ర",+ "type": "రకం",+ "url": "URL",+ "port": "పోర్ట్",+ "host": "హోస్ట్",+ "username": "యూజర్ నేమ్",+ "password": "పాస్వర్డ్",+ "active": "యాక్టివ్",+ "inactive": "ఇన్యాక్టివ్",+ "enabled": "ప్రారంభించబడింది",+ "disabled": "నిలిపివేయబడింది",+ "connected": "కనెక్ట్ అయింది",+ "disconnected": "డిస్కనెక్ట్ అయింది",+ "never": "ఎప్పుడూ కాదు",+ "justNow": "ఇప్పుడే",+ "minAgo": "{{count}} నిమిషం క్రితం",+ "hoursAgo": "{{count}} గంటల క్రితం",+ "optional": "ఐచ్ఛికం",+ "language": "భాష",+ "english": "English",+ "hebrew": "עברית",+ "telugu": "తెలుగు",+ "french": "Français",+ "back": "వెనుకకు",+ "next": "తరువాత",+ "previous": "మునుపటి",+ "expand": "విస్తరించు",+ "collapse": "కుదించు",+ "logout": "లాగౌట్",+ "refresh": "రిఫ్రెష్",+ "errorGeneric": "ఒక లోపం సంభవించింది",+ "unknownError": "తెలియని లోపం"+ },+ "theme": {+ "light": "లైట్",+ "dark": "డార్క్",+ "system": "సిస్టమ్",+ "label": "థీమ్: {{value}}"+ },+ "nav": {+ "dashboard": "డ్యాష్బోర్డ్",+ "sessions": "సెషన్స్",+ "webhooks": "వెబ్హుక్స్",+ "apiKeys": "API కీలు",+ "messageTester": "మెసేజ్ టెస్టర్",+ "infrastructure": "ఇన్ఫ్రాస్ట్రక్చర్",+ "plugins": "ప్లగిన్స్",+ "logs": "లాగ్స్"+ },+ "errorBoundary": {+ "title": "ఏదో తప్పు జరిగింది",+ "description": "డ్యాష్బోర్డ్లో ఊహించని లోపం ఎదురైంది.",+ "reload": "డ్యాష్బోర్డ్ను రీలోడ్ చేయి"+ },+ "login": {+ "apiKey": "API కీ",+ "apiKeyPlaceholder": "మీ API కీని ఎంటర్ చేయండి",+ "apiKeyRequired": "API కీ అవసరం",+ "connect": "కనెక్ట్ చేయి",+ "connecting": "కనెక్ట్ అవుతోంది...",+ "invalidKey": "చెల్లని API కీ",+ "connectionError": "సర్వర్కు కనెక్ట్ కాలేకపోయాము. దయచేసి మళ్లీ ప్రయత్నించండి.",+ "help": "సహాయం కావాలా?",+ "viewDocs": "డాక్యుమెంటేషన్ చూడండి",+ "footer": "Yudhi Armyndharis మరియు OpenWA కమ్యూనిటీ ద్వారా ❤️ తో తయారు చేయబడింది",+ "version": "v{{version}} · {{date}}"+ },+ "dashboard": {+ "title": "డ్యాష్బోర్డ్",+ "subtitle": "మీ వాట్సాప్ సెషన్లు మరియు యాక్టివిటీ యొక్క అవలోకనం",+ "stats": {+ "activeSessions": "యాక్టివ్ సెషన్స్",+ "messagesToday": "ఈరోజు సందేశాలు",+ "webhooksConfigured": "కాన్ఫిగర్ చేసిన వెబ్హుక్స్",+ "apiCalls": "API కాల్స్ (24 గంటలు)"+ },+ "sessionsOverview": "సెషన్ల అవలోకనం",+ "showingSessions": "{{total}} సెషన్లలో {{shown}} చూపిస్తోంది",+ "columns": {+ "sessionId": "సెషన్ ID",+ "phone": "ఫోన్ నంబర్",+ "status": "స్థితి",+ "lastActive": "చివరిసారి యాక్టివ్",+ "actions": "చర్యలు"+ },+ "noSessions": "ఎలాంటి సెషన్లు కనుగొనబడలేదు. ప్రారంభించడానికి ఒకదాన్ని సృష్టించండి.",+ "view": "చూడు",+ "disconnect": "డిస్కనెక్ట్ చేయి",+ "errorPrefix": "లోపం: {{message}}",+ "loadError": "డేటాను లోడ్ చేయడం విఫలమైంది"+ },+ "sessionStatus": {+ "created": "కొత్తది",+ "idle": "ఐడిల్",+ "initializing": "ప్రారంభమవుతోంది...",+ "connecting": "కనెక్ట్ అవుతోంది...",+ "qr_ready": "QR స్కాన్ చేయండి",+ "ready": "కనెక్ట్ అయింది",+ "disconnected": "డిస్కనెక్ట్ అయింది"+ },+ "sessions": {+ "title": "సెషన్స్",+ "subtitle": "మీ వాట్సాప్ సెషన్లు మరియు QR కోడ్ కనెక్షన్లను నిర్వహించండి",+ "newSession": "కొత్త సెషన్",+ "searchPlaceholder": "సెషన్ల కోసం వెతకండి...",+ "filter": {+ "all": "అన్ని స్థితులు",+ "active": "యాక్టివ్ (కనెక్ట్ అయింది)",+ "inactive": "ఇన్యాక్టివ్",+ "connecting": "కనెక్ట్ అవుతోంది"+ },+ "empty": {+ "title": "ఎలాంటి సెషన్లు కనుగొనబడలేదు",+ "description": "ప్రారంభించడానికి ఒక కొత్త సెషన్ను సృష్టించండి"+ },+ "create": {+ "title": "కొత్త సెషన్ను సృష్టించండి",+ "label": "సెషన్ పేరు",+ "placeholder": "ఉదాహరణకు, marketing-bot",+ "hint": "చిన్న అక్షరాలు (lowercase), సంఖ్యలు, మరియు హైఫన్లు మాత్రమే ఉపయోగించండి. ఉదాహరణ: <code>customer-support</code>, <code>bot-1</code>",+ "invalidChars": "చెల్లని అక్షరాలు. చిన్న అక్షరాలు, సంఖ్యలు, మరియు హైఫన్లు మాత్రమే అనుమతించబడతాయి.",+ "tooLong": "పేరు 50 అక్షరాలు లేదా అంతకంటే తక్కువ ఉండాలి ({{length}}/50).",+ "duplicate": "ఈ పేరుతో సెషన్ ఇప్పటికే ఉంది.",+ "successTitle": "సెషన్ సృష్టించబడింది",+ "successDesc": "సెషన్ \"{{name}}\" విజయవంతంగా సృష్టించబడింది",+ "errorTitle": "సృష్టి విఫలమైంది",+ "errorDefault": "సెషన్ను సృష్టించడం విఫలమైంది"+ },+ "delete": {+ "title": "తొలగింపును ధృవీకరించండి",+ "message": "మీరు ఖచ్చితంగా <strong>\"{{name}}\"</strong> సెషన్ను తొలగించాలనుకుంటున్నారా?",+ "warning": "ఈ చర్యను వెనక్కి తీసుకోలేము.",+ "successTitle": "సెషన్ తొలగించబడింది",+ "successDescNamed": "సెషన్ \"{{name}}\" తొలగించబడింది",+ "successDescGeneric": "సెషన్ తొలగించబడింది",+ "errorTitle": "తొలగింపు విఫలమైంది",+ "errorDefault": "సెషన్ను తొలగించడం విఫలమైంది"+ },+ "qr": {+ "title": "QR కోడ్ను స్కాన్ చేయండి",+ "step1": "<strong>1.</strong> మీ ఫోన్లో వాట్సాప్ తెరవండి",+ "step2": "<strong>2.</strong> <strong>మెనూ</strong> → <strong>Linked Devices</strong> పై నొక్కండి",+ "step3": "<strong>3.</strong> <strong>Link a Device</strong> పై నొక్కి, ఈ QR కోడ్ను స్కాన్ చేయండి",+ "autoRefresh": "QR ప్రతి 5 సెకన్లకు స్వయంచాలకంగా అప్డేట్ అవుతుంది",+ "generating": "QR కోడ్ను రూపొందిస్తోంది...",+ "unavailable": "QR కోడ్ ఇంకా అందుబాటులో లేదు. కాసేపటి తర్వాత మళ్లీ ప్రయత్నించండి.",+ "preparing": "QR కోడ్ను సిద్ధం చేస్తోంది...",+ "showQr": "QR చూపించు",+ "loading": "లోడ్ అవుతోంది...",+ "scanToConnect": "కనెక్ట్ కావడానికి QR కోడ్ను స్కాన్ చేయండి"+ },+ "details": {+ "title": "సెషన్ వివరాలు",+ "name": "పేరు",+ "status": "స్థితి",+ "sessionId": "సెషన్ ID",+ "phone": "ఫోన్ నంబర్",+ "phoneNone": "కనెక్ట్ కాలేదు",+ "created": "సృష్టించబడింది",+ "lastActive": "చివరిసారి యాక్టివ్"+ },+ "actions": {+ "view": "చూడు",+ "start": "ప్రారంభించు",+ "stop": "ఆపివేయి",+ "reconnect": "మళ్లీ కనెక్ట్ చేయి",+ "delete": "తొలగించు"+ },+ "toasts": {+ "readyTitle": "సెషన్ సిద్ధంగా ఉంది",+ "readyDesc": "వాట్సాప్ సెషన్ ఇప్పుడు కనెక్ట్ అయింది",+ "disconnectedTitle": "సెషన్ డిస్కనెక్ట్ అయింది",+ "disconnectedDesc": "వాట్సాప్ సెషన్ డిస్కనెక్ట్ చేయబడింది"+ },+ "card": {+ "phone": "ఫోన్",+ "sessionId": "సెషన్ ID",+ "lastActive": "చివరిసారి యాక్టివ్"+ }+ },+ "webhooks": {+ "title": "వెబ్హుక్స్",+ "subtitle": "నిజ-సమయ (real-time) ఈవెంట్ నోటిఫికేషన్ల కోసం HTTP కాల్బ్యాక్లను కాన్ఫిగర్ చేయండి",+ "addWebhook": "వెబ్హుక్ జోడించు",+ "createTitle": "వెబ్హుక్ను సృష్టించండి",+ "editTitle": "వెబ్హుక్ను ఎడిట్ చేయండి",+ "deleteTitle": "వెబ్హుక్ను తొలగించండి",+ "deleteConfirm": "మీరు ఖచ్చితంగా ఈ వెబ్హుక్ను తొలగించాలనుకుంటున్నారా?",+ "selectSession": "సెషన్ను ఎంచుకోండి...",+ "session": "సెషన్",+ "events": "ఈవెంట్స్",+ "available": "అందుబాటులో ఉన్న ఈవెంట్స్",+ "saveChanges": "మార్పులను సేవ్ చేయి",+ "columns": {+ "url": "URL",+ "events": "ఈవెంట్స్",+ "session": "సెషన్",+ "status": "స్థితి",+ "actions": "చర్యలు"+ },+ "empty": {+ "title": "ఎలాంటి వెబ్హుక్స్ కాన్ఫిగర్ చేయబడలేదు",+ "description": "నిజ-సమయ ఈవెంట్ నోటిఫికేషన్లను పొందడానికి ఒక వెబ్హుక్ను జోడించండి"+ },+ "toasts": {+ "created": "వెబ్హుక్ విజయవంతంగా సృష్టించబడింది",+ "createFailed": "వెబ్హుక్ సృష్టించడం విఫలమైంది: {{message}}",+ "deleted": "వెబ్హుక్ విజయవంతంగా తొలగించబడింది",+ "deleteFailed": "వెబ్హుక్ తొలగించడం విఫలమైంది: {{message}}",+ "updated": "వెబ్హుక్ విజయవంతంగా అప్డేట్ చేయబడింది",+ "updateFailed": "వెబ్హుక్ అప్డేట్ చేయడం విఫలమైంది: {{message}}",+ "testOk": "వెబ్హుక్ పరీక్ష విజయవంతమైంది! స్థితి: {{status}}",+ "testFailed": "వెబ్హుక్ పరీక్ష విఫలమైంది: {{message}}",+ "testError": "వెబ్హుక్ను పరీక్షించడంలో లోపం: {{message}}"+ },+ "actions": {+ "test": "పరీక్షించు (Test)",+ "edit": "ఎడిట్ చేయి",+ "delete": "తొలగించు"+ },+ "eventDescriptions": {+ "message.received": "సందేశం వచ్చినప్పుడు",+ "message.sent": "సందేశం పంపబడినప్పుడు",+ "session.connected": "సెషన్ కనెక్ట్ అయినప్పుడు",+ "session.disconnected": "సెషన్ డిస్కనెక్ట్ అయినప్పుడు",+ "session.qr": "QR కోడ్ రూపొందించబడినప్పుడు",+ "all": "అన్ని ఈవెంట్స్"+ }+ },+ "apiKeys": {+ "title": "API కీలు",+ "subtitle": "అథెంటికేషన్ మరియు యాక్సెస్ కంట్రోల్ కోసం API కీలను నిర్వహించండి",+ "createBtn": "API కీని సృష్టించండి",+ "modalTitle": "API కీని సృష్టించండి",+ "createdTitle": "API కీ సృష్టించబడింది",+ "createdHint": "ఈ కీని ఇప్పుడే కాపీ చేసుకోండి. మీరు దీన్ని మళ్లీ చూడలేరు.",+ "namePlaceholder": "ఉదాహరణకు, Production Key",+ "rolesTitle": "పాత్రల సూచిక (Roles Reference)",+ "roles": {+ "admin": "అడ్మిన్",+ "operator": "ఆపరేటర్",+ "viewer": "వీక్షకుడు (Viewer)"+ },+ "roleDescriptions": {+ "admin": "అన్ని వనరులకు పూర్తి యాక్సెస్",+ "operator": "సెషన్ & సందేశాల నిర్వహణ",+ "viewer": "చదవడానికి మాత్రమే యాక్సెస్ (Read-only)"+ },+ "columns": {+ "name": "పేరు",+ "key": "కీ",+ "role": "పాత్ర",+ "status": "స్థితి",+ "lastUsed": "చివరిగా ఉపయోగించినది",+ "actions": "చర్యలు"+ },+ "statuses": {+ "active": "యాక్టివ్",+ "revoked": "రద్దు చేయబడింది"+ },+ "empty": {+ "title": "ఎలాంటి API కీలు సృష్టించబడలేదు",+ "description": "మీ రిక్వెస్ట్లను అథెంటికేట్ చేయడానికి ఒక API కీని సృష్టించండి"+ },+ "confirm": {+ "deleteTitle": "API కీని తొలగించండి",+ "revokeTitle": "API కీని రద్దు చేయండి",+ "deleteMessage": "మీరు ఖచ్చితంగా <strong>{{name}}</strong> ని శాశ్వతంగా తొలగించాలనుకుంటున్నారా? ఈ చర్యను వెనక్కి తీసుకోలేము.",+ "revokeMessage": "మీరు ఖచ్చితంగా <strong>{{name}}</strong> ని రద్దు చేయాలనుకుంటున్నారా? ఇది ఇకపై పనిచేయదు.",+ "delete": "తొలగించు",+ "revoke": "రద్దు చేయి"+ },+ "actions": {+ "copy": "కాపీ",+ "revoke": "రద్దు చేయి",+ "delete": "తొలగించు"+ }+ },+ "logs": {+ "title": "ఆడిట్ లాగ్స్",+ "subtitle": "అన్ని API చర్యలు మరియు సిస్టమ్ ఈవెంట్లను ట్రాక్ చేయండి మరియు సమీక్షించండి",+ "exportCsv": "CSV ఎగుమతి చేయి",+ "searchPlaceholder": "లాగ్స్ కోసం వెతకండి...",+ "severity": {+ "all": "అన్ని తీవ్రతలు",+ "info": "సమాచారం (Info)",+ "warn": "హెచ్చరిక (Warning)",+ "error": "లోపం (Error)"+ },+ "columns": {+ "timestamp": "సమయము (Timestamp)",+ "action": "చర్య",+ "session": "సెషన్",+ "apiKey": "API కీ",+ "ip": "IP చిరునామా",+ "severity": "తీవ్రత"+ },+ "empty": {+ "title": "ఎలాంటి లాగ్లు కనుగొనబడలేదు",+ "description": "చర్యలు జరిగినప్పుడు ఆడిట్ లాగ్లు ఇక్కడ కనిపిస్తాయి"+ }+ },+ "messageTester": {+ "title": "మెసేజ్ టెస్టర్",+ "subtitle": "API ద్వారా పరీక్ష సందేశాలను పంపండి",+ "compose": "పరీక్ష సందేశాన్ని పంపండి",+ "responseTitle": "API రెస్పాన్స్",+ "session": "సెషన్",+ "noReadySessions": "సిద్ధంగా ఉన్న సెషన్లు లేవు",+ "sessionOptionPhoneNone": "ఫోన్ లేదు",+ "recipientType": "స్వీకర్త రకం",+ "personal": "వ్యక్తిగత",+ "group": "గ్రూప్",+ "selectGroup": "గ్రూప్ను ఎంచుకోండి",+ "recipientPhone": "స్వీకర్త ఫోన్ నంబర్",+ "loadingGroups": "గ్రూప్లను లోడ్ చేస్తోంది...",+ "noGroupsFound": "ఎలాంటి గ్రూప్లు కనుగొనబడలేదు",+ "selectGroupHint": "మీ వాట్సాప్ నుండి ఒక గ్రూప్ను ఎంచుకోండి",+ "phoneHint": "ఖాళీలు (spaces) లేకుండా అంతర్జాతీయ ఆకృతిని ఉపయోగించండి",+ "messageType": "సందేశం రకం",+ "types": {+ "text": "టెక్స్ట్",+ "image": "చిత్రం (Image)",+ "video": "వీడియో",+ "audio": "ఆడియో",+ "document": "డాక్యుమెంట్"+ },+ "messageContent": "సందేశం కంటెంట్",+ "messagePlaceholder": "మీ సందేశాన్ని ఇక్కడ ఎంటర్ చేయండి...",+ "mediaUrl": "మీడియా URL",+ "caption": "క్యాప్షన్",+ "filename": "ఫైల్ పేరు",+ "captionPlaceholder": "క్యాప్షన్ ఎంటర్ చేయండి...",+ "filenamePlaceholder": "document.pdf",+ "send": "సందేశం పంపు",+ "sending": "పంపుతోంది...",+ "viewOnly": "చూడటానికి మాత్రమే",+ "responseEmpty": "API రెస్పాన్స్ చూడటానికి ఒక సందేశాన్ని పంపండి",+ "successLabel": "200 OK - విజయం",+ "failedLabel": "400 - విఫలమైంది",+ "response": {+ "timestamp": "సమయము",+ "messageId": "సందేశం ID",+ "error": "లోపం"+ },+ "sendFailed": "సందేశాన్ని పంపడం విఫలమైంది"+ },+ "infrastructure": {+ "title": "ఇన్ఫ్రాస్ట్రక్చర్",+ "subtitle": "సర్వర్, డేటాబేస్, క్యాషే, స్టోరేజ్ మరియు ఇంజిన్ సెట్టింగ్లను కాన్ఫిగర్ చేయండి",+ "saveConfig": "కాన్ఫిగరేషన్ను సేవ్ చేయి",+ "saving": "సేవ్ చేస్తోంది...",+ "server": {+ "title": "సర్వర్ కాన్ఫిగరేషన్",+ "production": "ప్రొడక్షన్",+ "development": "డెవలప్మెంట్",+ "environment": "ఎన్విరాన్మెంట్",+ "domain": "డొమైన్",+ "apiPort": "API పోర్ట్",+ "dashboardPort": "డ్యాష్బోర్డ్ పోర్ట్",+ "corsOrigins": "CORS ఆరిజిన్స్",+ "corsPlaceholder": "* లేదా కామాతో వేరు చేయబడిన ఆరిజిన్స్",+ "publicApiUrl": "పబ్లిక్ API URL (ఐచ్ఛికం)",+ "publicDashboardUrl": "పబ్లిక్ డ్యాష్బోర్డ్ URL (ఐచ్ఛికం)"+ },+ "webhook": {+ "title": "వెబ్హుక్ & రేట్ లిమిటింగ్",+ "settings": "వెబ్హుక్ సెట్టింగ్స్",+ "timeout": "టైమౌట్ (ms)",+ "maxRetries": "గరిష్ట రీట్రైలు",+ "retryDelay": "రీట్రై ఆలస్యం (ms)",+ "rateLimit": "రేట్ లిమిటింగ్",+ "window": "సమయ విండో (సెకన్లు)",+ "maxReq": "ఒక విండోకు గరిష్ట రిక్వెస్ట్లు"+ },+ "database": {+ "title": "డేటాబేస్ కాన్ఫిగరేషన్",+ "sqlite": "SQLite",+ "sqliteDesc": "లోకల్ ఫైల్ ఆధారిత డేటాబేస్",+ "postgres": "PostgreSQL",+ "postgresDesc": "ప్రొడక్షన్-రెడీ డేటాబేస్",+ "useBuiltIn": "ఇన్-బిల్ట్ PostgreSQL కంటైనర్ను ఉపయోగించండి",+ "builtInDesc": "OpenWA మీ కోసం ఒక PostgreSQL కంటైనర్ను నిర్వహిస్తుంది",+ "dbName": "డేటాబేస్ పేరు",+ "poolSize": "పూల్ సైజు",+ "ssl": "SSL కనెక్షన్",+ "sslDesc": "సురక్షిత డేటాబేస్ కనెక్షన్ల కోసం TLS/SSLని ప్రారంభించండి",+ "migrationsTitle": "డేటాబేస్ మైగ్రేషన్స్",+ "migrationsStatus": "స్కీమా TypeORM తో స్వయంచాలకంగా సమకాలీకరించబడింది",+ "migrationsHint": "మైగ్రేషన్స్ స్వయంచాలకంగా నిర్వహించబడతాయి. మాన్యువల్ మైగ్రేషన్స్ కోసం CLIని ఉపయోగించండి."+ },+ "redis": {+ "title": "Redis",+ "enable": "Redis ప్రారంభించండి",+ "enableDesc": "క్యాషింగ్, సెషన్ స్టోరేజ్ మరియు BullMQ క్యూల కోసం అవసరం",+ "useBuiltIn": "ఇన్-బిల్ట్ Redis కంటైనర్ను ఉపయోగించండి",+ "builtInDesc": "OpenWA మీ కోసం ఒక Redis కంటైనర్ను నిర్వహిస్తుంది",+ "queueTitle": "BullMQ క్యూ సిస్టమ్ను ప్రారంభించండి",+ "queueDesc": "నమ్మకమైన సందేశం మరియు వెబ్హుక్ డెలివరీ కోసం సందేశ క్యూలను ఉపయోగించండి",+ "statsTitle": "క్యూ గణాంకాలు",+ "messageQueue": "సందేశ క్యూ",+ "webhookQueue": "వెబ్హుక్ క్యూ",+ "pending": "పెండింగ్",+ "completed": "పూర్తయింది",+ "failed": "విఫలమైంది",+ "clearFailed": "విఫలమైన జాబ్స్ను క్లియర్ చేయి",+ "viewBullMq": "Bull MQ డ్యాష్బోర్డ్ను చూడండి",+ "disabledTitle": "Redis నిలిపివేయబడింది",+ "disabledDesc": "క్యాషింగ్, సెషన్ స్టోరేజ్ మరియు BullMQ సందేశ క్యూల కోసం Redisని ప్రారంభించండి.",+ "passwordOptional": "(ఐచ్ఛికం)"+ },+ "storage": {+ "title": "స్టోరేజ్ కాన్ఫిగరేషన్",+ "local": "లోకల్ ఫైల్సిస్టమ్",+ "localDesc": "మీడియా ఫైల్లను లోకల్గా స్టోర్ చేయి",+ "s3": "Amazon S3",+ "s3Desc": "క్లౌడ్ స్టోరేజ్ (S3 అనుకూలమైనది)",+ "useBuiltIn": "ఇన్-బిల్ట్ MinIO కంటైనర్ను ఉపయోగించండి",+ "builtInDesc": "OpenWA మీ కోసం ఒక MinIO (S3-అనుకూల) కంటైనర్ను నిర్వహిస్తుంది",+ "storagePath": "స్టోరేజ్ పాత్",+ "bucket": "బకెట్ పేరు",+ "region": "ప్రాంతం (Region)",+ "accessKey": "యాక్సెస్ కీ",+ "secretKey": "సీక్రెట్ కీ",+ "endpoint": "కస్టమ్ ఎండ్పాయింట్ (ఐచ్ఛికం)",+ "endpointHint": "MinIO లేదా ఇతర S3-అనుకూల సేవల కోసం"+ },+ "statusLabels": {+ "connected": "కనెక్ట్ అయింది",+ "disconnected": "డిస్కనెక్ట్ అయింది",+ "disabled": "నిలిపివేయబడింది"+ },+ "restart": {+ "idleTitle": "⚙️ కాన్ఫిగరేషన్ సేవ్ చేయబడింది",+ "restartingTitle": "🔄 సర్వర్ రీస్టార్ట్ అవుతోంది...",+ "waitingTitle": "⏳ దయచేసి వేచి ఉండండి...",+ "successTitle": "✅ సర్వర్ సిద్ధంగా ఉంది",+ "errorTitle": "❌ రీస్టార్ట్ విఫలమైంది",+ "idleDesc": "కాన్ఫిగరేషన్ <code>.env.generated</code> కు సేవ్ చేయబడింది.<br/>మార్పులను వర్తింపజేయడానికి సర్వర్ రీస్టార్ట్ అవసరం.",+ "later": "తర్వాత రీస్టార్ట్ చేయి",+ "now": "ఇప్పుడే రీస్టార్ట్ చేయి",+ "restartingMsg": "సర్వర్ రీస్టార్ట్ అవుతోంది... {{count}}సెకన్లు",+ "checking": "సర్వర్ స్థితిని తనిఖీ చేస్తోంది...",+ "dontClose": "దయచేసి ఈ విండోను మూసివేయవద్దు",+ "successMsg": "సర్వర్ తిరిగి ఆన్లైన్లోకి వచ్చింది! పేజీ స్వయంచాలకంగా రీలోడ్ అవుతుంది.",+ "errorMsg": "30 సెకన్ల తర్వాత కూడా సర్వర్ స్పందించలేదు. దయచేసి డోకర్ (Docker) లాగ్లను తనిఖీ చేసి, మాన్యువల్గా రీస్టార్ట్ చేయండి.",+ "reload": "పేజీని రీలోడ్ చేయి"+ },+ "toasts": {+ "saveFailed": "సేవ్ చేయడం విఫలమైంది"+ }+ },+ "plugins": {+ "title": "ప్లగిన్స్",+ "subtitle": "ఇంజిన్లు, స్టోరేజ్ బ్యాకెండ్లు మరియు ఎక్స్టెన్షన్లను నిర్వహించండి",+ "refresh": "రిఫ్రెష్",+ "engineCard": "యాక్టివ్ వాట్సాప్ ఇంజిన్",+ "running": "నడుస్తోంది",+ "supportedFeatures": "మద్దతు ఉన్న ఫీచర్లు:",+ "more": "+ఇంకా {{count}}",+ "builtIn": "ఇన్-బిల్ట్",+ "noDescription": "ఎలాంటి వివరణ అందుబాటులో లేదు",+ "required": "అవసరం",+ "active": "యాక్టివ్",+ "activate": "యాక్టివేట్ చేయి",+ "enable": "ప్రారంభించు",+ "disable": "నిలిపివేయి",+ "healthCheck": "హెల్త్ చెక్",+ "configure": "కాన్ఫిగర్ చేయి",+ "empty": {+ "title": "ఎలాంటి ప్లగిన్స్ కనుగొనబడలేదు",+ "description": "OpenWA కార్యాచరణను విస్తరించడానికి ప్లగిన్లను ఇన్స్టాల్ చేయండి"+ },+ "config": {+ "title": "{{name}} కాన్ఫిగర్ చేయి",+ "restartNotice": "మార్పులు అమలులోకి రావడానికి సర్వర్ రీస్టార్ట్ అవసరం",+ "engineType": "ఇంజిన్ రకం",+ "headless": "హెడ్లెస్ మోడ్",+ "headlessDesc": "కనిపించే UI లేకుండా బ్రౌజర్ను రన్ చేయి (ప్రొడక్షన్ కోసం సిఫార్సు చేయబడింది)",+ "sessionDataPath": "సెషన్ డేటా పాత్",+ "browserArgs": "బ్రౌజర్ ఆర్గుమెంట్స్",+ "noOptions": "ఈ ప్లగిన్ కోసం ఎలాంటి కాన్ఫిగరేషన్ ఆప్షన్లు అందుబాటులో లేవు",+ "save": "కాన్ఫిగరేషన్ను సేవ్ చేయి"+ },+ "toasts": {+ "errorTitle": "ప్లగిన్ లోపం",+ "errorDefault": "ప్లగిన్ టోగుల్ చేయడం విఫలమైంది",+ "healthOk": "హెల్త్ చెక్ పాస్ అయింది",+ "healthFail": "హెల్త్ చెక్ విఫలమైంది",+ "healthError": "హెల్త్ చెక్ లోపం",+ "savedTitle": "కాన్ఫిగరేషన్ సేవ్ చేయబడింది",+ "savedDesc": "మార్పులను వర్తింపజేయడానికి సర్వర్ రీస్టార్ట్ అవసరం.",+ "saveFailed": "సేవ్ చేయడం విఫలమైంది"+ }+ }+}\ No newline at end of filediff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonnew file mode 100644index 000000000..867f511be--- /dev/null+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -0,0 +1,514 @@+{+ "common": {+ "appName": "OpenWA",+ "appSubtitle": "WhatsApp API",+ "loading": "正在加载...",+ "save": "保存",+ "cancel": "取消",+ "delete": "删除",+ "edit": "编辑",+ "create": "创建",+ "close": "关闭",+ "submit": "提交",+ "confirm": "确认",+ "search": "搜索",+ "filter": "筛选",+ "actions": "操作",+ "status": "状态",+ "name": "名称",+ "role": "角色",+ "type": "类型",+ "url": "URL",+ "port": "端口",+ "host": "主机",+ "username": "用户名",+ "password": "密码",+ "active": "活跃",+ "inactive": "非活跃",+ "enabled": "已启用",+ "disabled": "已禁用",+ "connected": "已连接",+ "disconnected": "已断开",+ "never": "从未",+ "justNow": "刚刚",+ "minAgo": "{{count}} 分钟前",+ "hoursAgo": "{{count}} 小时前",+ "optional": "可选",+ "language": "语言",+ "english": "English",+ "hebrew": "עברית",+ "back": "返回",+ "next": "下一步",+ "previous": "上一步",+ "expand": "展开",+ "collapse": "收起",+ "logout": "退出登录",+ "refresh": "刷新",+ "errorGeneric": "发生错误",+ "unknownError": "未知错误"+ },+ "theme": {+ "light": "浅色",+ "dark": "深色",+ "system": "跟随系统",+ "label": "主题:{{value}}"+ },+ "nav": {+ "dashboard": "仪表盘",+ "sessions": "会话",+ "webhooks": "Webhooks",+ "apiKeys": "API 密钥",+ "messageTester": "消息测试器",+ "infrastructure": "基础设施",+ "plugins": "插件",+ "logs": "日志"+ },+ "errorBoundary": {+ "title": "出了点问题",+ "description": "仪表盘遇到意外错误。",+ "reload": "重新加载仪表盘"+ },+ "login": {+ "apiKey": "API 密钥",+ "apiKeyPlaceholder": "输入你的 API 密钥",+ "apiKeyRequired": "必须输入 API 密钥",+ "connect": "连接",+ "connecting": "正在连接...",+ "invalidKey": "API 密钥无效",+ "connectionError": "无法连接到服务器。请重试。",+ "help": "需要帮助?",+ "viewDocs": "查看文档",+ "footer": "由 Yudhi Armyndharis 和 OpenWA 社区用 ❤️ 打造",+ "version": "v{{version}} · {{date}}"+ },+ "dashboard": {+ "title": "仪表盘",+ "subtitle": "查看你的 WhatsApp 会话和活动概览",+ "stats": {+ "activeSessions": "活跃会话",+ "messagesToday": "今日消息",+ "webhooksConfigured": "已配置 Webhook",+ "apiCalls": "API 调用(24 小时)"+ },+ "sessionsOverview": "会话概览",+ "showingSessions": "显示 {{shown}} / {{total}} 个会话",+ "columns": {+ "sessionId": "会话 ID",+ "phone": "电话号码",+ "status": "状态",+ "lastActive": "上次活跃",+ "actions": "操作"+ },+ "noSessions": "未找到会话。创建一个即可开始。",+ "view": "查看",+ "disconnect": "断开连接",+ "errorPrefix": "错误:{{message}}",+ "loadError": "加载数据失败"+ },+ "sessionStatus": {+ "created": "新建",+ "idle": "空闲",+ "initializing": "正在启动...",+ "connecting": "正在连接...",+ "qr_ready": "扫描 QR",+ "ready": "已连接",+ "disconnected": "已断开"+ },+ "sessions": {+ "title": "会话",+ "subtitle": "管理你的 WhatsApp 会话和 QR 码连接",+ "newSession": "新建会话",+ "searchPlaceholder": "搜索会话...",+ "filter": {+ "all": "所有状态",+ "active": "活跃(已连接)",+ "inactive": "非活跃",+ "connecting": "正在连接"+ },+ "empty": {+ "title": "未找到会话",+ "description": "创建新会话即可开始"+ },+ "create": {+ "title": "创建新会话",+ "label": "会话名称",+ "placeholder": "例如:marketing-bot",+ "hint": "只能使用小写字母、数字和连字符。例如:<code>customer-support</code>、<code>bot-1</code>",+ "invalidChars": "字符无效。只能使用小写字母、数字和连字符。",+ "tooLong": "名称长度不能超过 50 个字符({{length}}/50)。",+ "duplicate": "已存在同名会话。",+ "successTitle": "会话已创建",+ "successDesc": "会话 \"{{name}}\" 已成功创建",+ "errorTitle": "创建失败",+ "errorDefault": "创建会话失败"+ },+ "delete": {+ "title": "确认删除",+ "message": "确定要删除会话 <strong>\"{{name}}\"</strong> 吗?",+ "warning": "此操作无法撤销。",+ "successTitle": "会话已删除",+ "successDescNamed": "会话 \"{{name}}\" 已删除",+ "successDescGeneric": "会话已删除",+ "errorTitle": "删除失败",+ "errorDefault": "删除会话失败"+ },+ "qr": {+ "title": "扫描 QR 码",+ "step1": "<strong>1.</strong> 在手机上打开 WhatsApp",+ "step2": "<strong>2.</strong> 点击<strong>菜单</strong> → <strong>已关联设备</strong>",+ "step3": "<strong>3.</strong> 点击<strong>关联设备</strong>并扫描此 QR",+ "autoRefresh": "QR 每 5 秒自动更新一次",+ "generating": "正在生成 QR 码...",+ "unavailable": "QR 码暂不可用。请稍后重试。",+ "preparing": "正在准备 QR 码...",+ "showQr": "显示 QR",+ "loading": "正在加载...",+ "scanToConnect": "扫描 QR 码以连接"+ },+ "details": {+ "title": "会话详情",+ "name": "名称",+ "status": "状态",+ "sessionId": "会话 ID",+ "phone": "电话号码",+ "phoneNone": "未连接",+ "created": "创建时间",+ "lastActive": "上次活跃"+ },+ "actions": {+ "view": "查看",+ "start": "启动",+ "stop": "停止",+ "reconnect": "重新连接",+ "delete": "删除"+ },+ "toasts": {+ "readyTitle": "会话就绪",+ "readyDesc": "WhatsApp 会话现已连接",+ "disconnectedTitle": "会话已断开",+ "disconnectedDesc": "WhatsApp 会话已断开连接"+ },+ "card": {+ "phone": "电话",+ "sessionId": "会话 ID",+ "lastActive": "上次活跃"+ }+ },+ "webhooks": {+ "title": "Webhooks",+ "subtitle": "配置用于实时事件通知的 HTTP 回调",+ "addWebhook": "添加 Webhook",+ "createTitle": "创建 Webhook",+ "editTitle": "编辑 Webhook",+ "deleteTitle": "删除 Webhook",+ "deleteConfirm": "确定要删除此 webhook 吗?",+ "selectSession": "选择会话...",+ "session": "会话",+ "events": "事件",+ "available": "可用事件",+ "saveChanges": "保存更改",+ "columns": {+ "url": "URL",+ "events": "事件",+ "session": "会话",+ "status": "状态",+ "actions": "操作"+ },+ "empty": {+ "title": "尚未配置 Webhook",+ "description": "添加 Webhook 以接收实时事件通知"+ },+ "toasts": {+ "created": "Webhook 创建成功",+ "createFailed": "创建 Webhook 失败:{{message}}",+ "deleted": "Webhook 删除成功",+ "deleteFailed": "删除 Webhook 失败:{{message}}",+ "updated": "Webhook 更新成功",+ "updateFailed": "更新 Webhook 失败:{{message}}",+ "testOk": "Webhook 测试成功!状态:{{status}}",+ "testFailed": "Webhook 测试失败:{{message}}",+ "testError": "测试 Webhook 失败:{{message}}"+ },+ "actions": {+ "test": "测试",+ "edit": "编辑",+ "delete": "删除"+ },+ "eventDescriptions": {+ "message.received": "收到消息时",+ "message.sent": "发送消息时",+ "session.connected": "会话连接时",+ "session.disconnected": "会话断开时",+ "session.qr": "生成 QR 码时",+ "all": "所有事件"+ }+ },+ "apiKeys": {+ "title": "API 密钥",+ "subtitle": "管理用于认证和访问控制的 API 密钥",+ "createBtn": "创建 API 密钥",+ "modalTitle": "创建 API 密钥",+ "createdTitle": "API 密钥已创建",+ "createdHint": "请立即复制此密钥。之后将无法再次查看。",+ "namePlaceholder": "例如:Production Key",+ "rolesTitle": "角色参考",+ "roles": {+ "admin": "管理员",+ "operator": "操作员",+ "viewer": "查看者"+ },+ "roleDescriptions": {+ "admin": "可完全访问所有资源",+ "operator": "会话和消息管理",+ "viewer": "只读访问"+ },+ "columns": {+ "name": "名称",+ "key": "密钥",+ "role": "角色",+ "status": "状态",+ "lastUsed": "上次使用",+ "actions": "操作"+ },+ "statuses": {+ "active": "活跃",+ "revoked": "已撤销"+ },+ "empty": {+ "title": "尚未创建 API 密钥",+ "description": "创建 API 密钥以认证你的请求"+ },+ "confirm": {+ "deleteTitle": "删除 API 密钥",+ "revokeTitle": "撤销 API 密钥",+ "deleteMessage": "确定要永久删除 <strong>{{name}}</strong> 吗?此操作无法撤销。",+ "revokeMessage": "确定要撤销 <strong>{{name}}</strong> 吗?它将不再可用。",+ "delete": "删除",+ "revoke": "撤销"+ },+ "actions": {+ "copy": "复制",+ "revoke": "撤销",+ "delete": "删除"+ }+ },+ "logs": {+ "title": "审计日志",+ "subtitle": "跟踪并查看所有 API 操作和系统事件",+ "exportCsv": "导出 CSV",+ "searchPlaceholder": "搜索日志...",+ "severity": {+ "all": "所有严重级别",+ "info": "信息",+ "warn": "警告",+ "error": "错误"+ },+ "columns": {+ "timestamp": "时间戳",+ "action": "操作",+ "session": "会话",+ "apiKey": "API 密钥",+ "ip": "IP 地址",+ "severity": "严重级别"+ },+ "empty": {+ "title": "未找到日志",+ "description": "执行操作后,审计日志将显示在这里"+ }+ },+ "messageTester": {+ "title": "消息测试器",+ "subtitle": "通过 API 发送测试消息",+ "compose": "发送测试消息",+ "responseTitle": "API 响应",+ "session": "会话",+ "noReadySessions": "没有就绪的会话",+ "sessionOptionPhoneNone": "无电话",+ "recipientType": "接收方类型",+ "personal": "个人",+ "group": "群组",+ "selectGroup": "选择群组",+ "recipientPhone": "接收方电话号码",+ "loadingGroups": "正在加载群组...",+ "noGroupsFound": "未找到群组",+ "selectGroupHint": "从你的 WhatsApp 中选择一个群组",+ "phoneHint": "使用无空格的国际格式",+ "messageType": "消息类型",+ "types": {+ "text": "文本",+ "image": "图片",+ "video": "视频",+ "audio": "音频",+ "document": "文档"+ },+ "messageContent": "消息内容",+ "messagePlaceholder": "在此输入你的消息...",+ "mediaUrl": "媒体 URL",+ "caption": "说明文字",+ "filename": "文件名",+ "captionPlaceholder": "输入说明文字...",+ "filenamePlaceholder": "document.pdf",+ "send": "发送消息",+ "sending": "正在发送...",+ "viewOnly": "仅查看",+ "responseEmpty": "发送消息后即可查看 API 响应",+ "successLabel": "200 OK - 成功",+ "failedLabel": "400 - 失败",+ "response": {+ "timestamp": "时间戳",+ "messageId": "消息 ID",+ "error": "错误"+ },+ "sendFailed": "发送消息失败"+ },+ "infrastructure": {+ "title": "基础设施",+ "subtitle": "配置服务器、数据库、缓存、存储和引擎设置",+ "saveConfig": "保存配置",+ "saving": "正在保存...",+ "server": {+ "title": "服务器配置",+ "production": "生产",+ "development": "开发",+ "environment": "环境",+ "domain": "域名",+ "apiPort": "API 端口",+ "dashboardPort": "仪表盘端口",+ "corsOrigins": "CORS 来源",+ "corsPlaceholder": "* 或用逗号分隔的来源",+ "publicApiUrl": "公共 API URL(可选)",+ "publicDashboardUrl": "公共仪表盘 URL(可选)"+ },+ "webhook": {+ "title": "Webhook 和速率限制",+ "settings": "Webhook 设置",+ "timeout": "超时(毫秒)",+ "maxRetries": "最大重试次数",+ "retryDelay": "重试延迟(毫秒)",+ "rateLimit": "速率限制",+ "window": "时间窗口(秒)",+ "maxReq": "每个窗口最大请求数"+ },+ "database": {+ "title": "数据库配置",+ "sqlite": "SQLite",+ "sqliteDesc": "本地文件型数据库",+ "postgres": "PostgreSQL",+ "postgresDesc": "适用于生产的数据库",+ "useBuiltIn": "使用内置 PostgreSQL 容器",+ "builtInDesc": "OpenWA 将为你管理 PostgreSQL 容器",+ "dbName": "数据库名称",+ "poolSize": "连接池大小",+ "ssl": "SSL 连接",+ "sslDesc": "启用 TLS/SSL 以保障数据库连接安全",+ "sslRejectUnauthorized": "验证 SSL 证书",+ "sslRejectUnauthorizedDesc": "拒绝自签名或无效的证书。对于使用自签名证书的托管 Postgres(Supabase、Heroku、Render、Railway),请关闭此项。",+ "migrationsTitle": "数据库迁移",+ "migrationsStatus": "架构会通过 TypeORM 自动同步",+ "migrationsHint": "迁移会自动管理。手动迁移请使用 CLI。"+ },+ "redis": {+ "title": "Redis",+ "enable": "启用 Redis",+ "enableDesc": "缓存、会话存储和 BullMQ 队列需要 Redis",+ "useBuiltIn": "使用内置 Redis 容器",+ "builtInDesc": "OpenWA 将为你管理 Redis 容器",+ "queueTitle": "启用 BullMQ 队列系统",+ "queueDesc": "使用消息队列可靠地投递消息和 Webhook",+ "statsTitle": "队列统计",+ "messageQueue": "消息队列",+ "webhookQueue": "Webhook 队列",+ "pending": "待处理",+ "completed": "已完成",+ "failed": "失败",+ "clearFailed": "清除失败任务",+ "viewBullMq": "查看 Bull MQ 仪表盘",+ "disabledTitle": "Redis 已禁用",+ "disabledDesc": "启用 Redis 以使用缓存、会话存储和 BullMQ 消息队列。",+ "passwordOptional": "(可选)"+ },+ "storage": {+ "title": "存储配置",+ "local": "本地文件系统",+ "localDesc": "在本地存储媒体文件",+ "s3": "Amazon S3",+ "s3Desc": "云存储(兼容 S3)",+ "useBuiltIn": "使用内置 MinIO 容器",+ "builtInDesc": "OpenWA 将为你管理 MinIO(兼容 S3)容器",+ "storagePath": "存储路径",+ "bucket": "存储桶名称",+ "region": "区域",+ "accessKey": "访问密钥",+ "secretKey": "秘密密钥",+ "endpoint": "自定义端点(可选)",+ "endpointHint": "适用于 MinIO 或其他兼容 S3 的服务"+ },+ "statusLabels": {+ "connected": "已连接",+ "disconnected": "已断开",+ "disabled": "已禁用"+ },+ "restart": {+ "idleTitle": "⚙️ 配置已保存",+ "restartingTitle": "🔄 正在重启服务器...",+ "waitingTitle": "⏳ 请稍候...",+ "successTitle": "✅ 服务器就绪",+ "errorTitle": "❌ 重启失败",+ "idleDesc": "配置已保存到 <code>.env.generated</code>。<br/>需要重启服务器才能应用更改。",+ "later": "稍后重启",+ "now": "立即重启",+ "restartingMsg": "服务器正在重启... {{count}} 秒",+ "checking": "正在检查服务器状态...",+ "dontClose": "请不要关闭此窗口",+ "successMsg": "服务器已恢复在线!页面将自动重新加载。",+ "errorMsg": "服务器在 30 秒后仍无响应。请检查 Docker 日志并手动重启。",+ "reload": "重新加载页面"+ },+ "toasts": {+ "saveFailed": "保存失败"+ }+ },+ "plugins": {+ "title": "插件",+ "subtitle": "管理引擎、存储后端和扩展",+ "refresh": "刷新",+ "engineCard": "当前 WhatsApp 引擎",+ "running": "运行中",+ "supportedFeatures": "支持的功能:",+ "more": "+{{count}} 更多",+ "builtIn": "内置",+ "noDescription": "没有可用描述",+ "required": "必需",+ "active": "活跃",+ "activate": "激活",+ "enable": "启用",+ "disable": "禁用",+ "healthCheck": "健康检查",+ "configure": "配置",+ "empty": {+ "title": "未找到插件",+ "description": "安装插件以扩展 OpenWA 功能"+ },+ "config": {+ "title": "配置 {{name}}",+ "restartNotice": "更改需要重启服务器后才会生效",+ "engineType": "引擎类型",+ "headless": "无头模式",+ "headlessDesc": "运行不显示界面的浏览器(推荐用于生产环境)",+ "sessionDataPath": "会话数据路径",+ "browserArgs": "浏览器参数",+ "noOptions": "此插件没有可用配置项",+ "save": "保存配置"+ },+ "toasts": {+ "errorTitle": "插件错误",+ "errorDefault": "切换插件失败",+ "healthOk": "健康检查通过",+ "healthFail": "健康检查失败",+ "healthError": "健康检查出错",+ "savedTitle": "配置已保存",+ "savedDesc": "需要重启服务器以应用更改。",+ "saveFailed": "保存失败"+ }+ }+}diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonnew file mode 100644index 000000000..f513d60d2--- /dev/null+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -0,0 +1,514 @@+{+ "common": {+ "appName": "OpenWA",+ "appSubtitle": "WhatsApp API",+ "loading": "正在載入...",+ "save": "儲存",+ "cancel": "取消",+ "delete": "刪除",+ "edit": "編輯",+ "create": "建立",+ "close": "關閉",+ "submit": "提交",+ "confirm": "確認",+ "search": "搜尋",+ "filter": "篩選",+ "actions": "操作",+ "status": "狀態",+ "name": "名稱",+ "role": "角色",+ "type": "類型",+ "url": "URL",+ "port": "連接埠",+ "host": "主機",+ "username": "用戶名稱",+ "password": "密碼",+ "active": "活躍",+ "inactive": "非活躍",+ "enabled": "已啟用",+ "disabled": "已停用",+ "connected": "已連線",+ "disconnected": "已中斷連線",+ "never": "從未",+ "justNow": "剛剛",+ "minAgo": "{{count}} 分鐘前",+ "hoursAgo": "{{count}} 小時前",+ "optional": "選填",+ "language": "語言",+ "english": "English",+ "hebrew": "עברית",+ "back": "返回",+ "next": "下一步",+ "previous": "上一步",+ "expand": "展開",+ "collapse": "收合",+ "logout": "登出",+ "refresh": "重新整理",+ "errorGeneric": "發生錯誤",+ "unknownError": "未知錯誤"+ },+ "theme": {+ "light": "淺色",+ "dark": "深色",+ "system": "跟隨系統",+ "label": "主題:{{value}}"+ },+ "nav": {+ "dashboard": "控制面板",+ "sessions": "工作階段",+ "webhooks": "Webhooks",+ "apiKeys": "API 金鑰",+ "messageTester": "訊息測試器",+ "infrastructure": "基礎架構",+ "plugins": "外掛",+ "logs": "記錄"+ },+ "errorBoundary": {+ "title": "發生問題",+ "description": "控制面板遇到未預期的錯誤。",+ "reload": "重新載入控制面板"+ },+ "login": {+ "apiKey": "API 金鑰",+ "apiKeyPlaceholder": "輸入你的 API 金鑰",+ "apiKeyRequired": "必須輸入 API 金鑰",+ "connect": "連線",+ "connecting": "正在連線...",+ "invalidKey": "API 金鑰無效",+ "connectionError": "無法連線到伺服器。請再試一次。",+ "help": "需要協助?",+ "viewDocs": "查看文件",+ "footer": "由 Yudhi Armyndharis 及 OpenWA 社群用 ❤️ 打造",+ "version": "v{{version}} · {{date}}"+ },+ "dashboard": {+ "title": "控制面板",+ "subtitle": "查看你的 WhatsApp 工作階段及活動概覽",+ "stats": {+ "activeSessions": "活躍工作階段",+ "messagesToday": "今日訊息",+ "webhooksConfigured": "已設定 Webhook",+ "apiCalls": "API 呼叫(24 小時)"+ },+ "sessionsOverview": "工作階段概覽",+ "showingSessions": "顯示 {{shown}} / {{total}} 個工作階段",+ "columns": {+ "sessionId": "工作階段 ID",+ "phone": "電話號碼",+ "status": "狀態",+ "lastActive": "上次活躍",+ "actions": "操作"+ },+ "noSessions": "找不到工作階段。建立一個即可開始。",+ "view": "查看",+ "disconnect": "中斷連線",+ "errorPrefix": "錯誤:{{message}}",+ "loadError": "載入資料失敗"+ },+ "sessionStatus": {+ "created": "新增",+ "idle": "閒置",+ "initializing": "正在啟動...",+ "connecting": "正在連線...",+ "qr_ready": "掃描 QR",+ "ready": "已連線",+ "disconnected": "已中斷連線"+ },+ "sessions": {+ "title": "工作階段",+ "subtitle": "管理你的 WhatsApp 工作階段及 QR 碼連線",+ "newSession": "新增工作階段",+ "searchPlaceholder": "搜尋工作階段...",+ "filter": {+ "all": "所有狀態",+ "active": "活躍(已連線)",+ "inactive": "非活躍",+ "connecting": "正在連線"+ },+ "empty": {+ "title": "找不到工作階段",+ "description": "建立新工作階段即可開始"+ },+ "create": {+ "title": "建立新工作階段",+ "label": "工作階段名稱",+ "placeholder": "例如:marketing-bot",+ "hint": "只可使用小寫字母、數字及連字號。例如:<code>customer-support</code>、<code>bot-1</code>",+ "invalidChars": "字元無效。只可使用小寫字母、數字及連字號。",+ "tooLong": "名稱不可超過 50 個字元({{length}}/50)。",+ "duplicate": "已存在同名工作階段。",+ "successTitle": "工作階段已建立",+ "successDesc": "工作階段 \"{{name}}\" 已成功建立",+ "errorTitle": "建立失敗",+ "errorDefault": "建立工作階段失敗"+ },+ "delete": {+ "title": "確認刪除",+ "message": "確定要刪除工作階段 <strong>\"{{name}}\"</strong> 嗎?",+ "warning": "此操作無法復原。",+ "successTitle": "工作階段已刪除",+ "successDescNamed": "工作階段 \"{{name}}\" 已刪除",+ "successDescGeneric": "工作階段已刪除",+ "errorTitle": "刪除失敗",+ "errorDefault": "刪除工作階段失敗"+ },+ "qr": {+ "title": "掃描 QR 碼",+ "step1": "<strong>1.</strong> 在手機上開啟 WhatsApp",+ "step2": "<strong>2.</strong> 點按<strong>選單</strong> → <strong>已連結裝置</strong>",+ "step3": "<strong>3.</strong> 點按<strong>連結裝置</strong>並掃描此 QR",+ "autoRefresh": "QR 每 5 秒自動更新一次",+ "generating": "正在產生 QR 碼...",+ "unavailable": "QR 碼暫時未能使用。請稍後再試。",+ "preparing": "正在準備 QR 碼...",+ "showQr": "顯示 QR",+ "loading": "正在載入...",+ "scanToConnect": "掃描 QR 碼以連線"+ },+ "details": {+ "title": "工作階段詳情",+ "name": "名稱",+ "status": "狀態",+ "sessionId": "工作階段 ID",+ "phone": "電話號碼",+ "phoneNone": "未連線",+ "created": "建立時間",+ "lastActive": "上次活躍"+ },+ "actions": {+ "view": "查看",+ "start": "啟動",+ "stop": "停止",+ "reconnect": "重新連線",+ "delete": "刪除"+ },+ "toasts": {+ "readyTitle": "工作階段就緒",+ "readyDesc": "WhatsApp 工作階段現已連線",+ "disconnectedTitle": "工作階段已中斷連線",+ "disconnectedDesc": "WhatsApp 工作階段已中斷連線"+ },+ "card": {+ "phone": "電話",+ "sessionId": "工作階段 ID",+ "lastActive": "上次活躍"+ }+ },+ "webhooks": {+ "title": "Webhooks",+ "subtitle": "設定用於即時事件通知的 HTTP 回呼",+ "addWebhook": "新增 Webhook",+ "createTitle": "建立 Webhook",+ "editTitle": "編輯 Webhook",+ "deleteTitle": "刪除 Webhook",+ "deleteConfirm": "確定要刪除此 webhook 嗎?",+ "selectSession": "選擇工作階段...",+ "session": "工作階段",+ "events": "事件",+ "available": "可用事件",+ "saveChanges": "儲存變更",+ "columns": {+ "url": "URL",+ "events": "事件",+ "session": "工作階段",+ "status": "狀態",+ "actions": "操作"+ },+ "empty": {+ "title": "尚未設定 Webhook",+ "description": "新增 Webhook 以接收即時事件通知"+ },+ "toasts": {+ "created": "Webhook 建立成功",+ "createFailed": "建立 Webhook 失敗:{{message}}",+ "deleted": "Webhook 刪除成功",+ "deleteFailed": "刪除 Webhook 失敗:{{message}}",+ "updated": "Webhook 更新成功",+ "updateFailed": "更新 Webhook 失敗:{{message}}",+ "testOk": "Webhook 測試成功!狀態:{{status}}",+ "testFailed": "Webhook 測試失敗:{{message}}",+ "testError": "測試 Webhook 失敗:{{message}}"+ },+ "actions": {+ "test": "測試",+ "edit": "編輯",+ "delete": "刪除"+ },+ "eventDescriptions": {+ "message.received": "收到訊息時",+ "message.sent": "傳送訊息時",+ "session.connected": "工作階段連線時",+ "session.disconnected": "工作階段中斷連線時",+ "session.qr": "產生 QR 碼時",+ "all": "所有事件"+ }+ },+ "apiKeys": {+ "title": "API 金鑰",+ "subtitle": "管理用於認證及存取控制的 API 金鑰",+ "createBtn": "建立 API 金鑰",+ "modalTitle": "建立 API 金鑰",+ "createdTitle": "API 金鑰已建立",+ "createdHint": "請立即複製此金鑰。之後將無法再次查看。",+ "namePlaceholder": "例如:Production Key",+ "rolesTitle": "角色參考",+ "roles": {+ "admin": "管理員",+ "operator": "操作員",+ "viewer": "檢視者"+ },+ "roleDescriptions": {+ "admin": "可完整存取所有資源",+ "operator": "工作階段及訊息管理",+ "viewer": "唯讀存取"+ },+ "columns": {+ "name": "名稱",+ "key": "金鑰",+ "role": "角色",+ "status": "狀態",+ "lastUsed": "上次使用",+ "actions": "操作"+ },+ "statuses": {+ "active": "活躍",+ "revoked": "已撤銷"+ },+ "empty": {+ "title": "尚未建立 API 金鑰",+ "description": "建立 API 金鑰以認證你的請求"+ },+ "confirm": {+ "deleteTitle": "刪除 API 金鑰",+ "revokeTitle": "撤銷 API 金鑰",+ "deleteMessage": "確定要永久刪除 <strong>{{name}}</strong> 嗎?此操作無法復原。",+ "revokeMessage": "確定要撤銷 <strong>{{name}}</strong> 嗎?它將無法再使用。",+ "delete": "刪除",+ "revoke": "撤銷"+ },+ "actions": {+ "copy": "複製",+ "revoke": "撤銷",+ "delete": "刪除"+ }+ },+ "logs": {+ "title": "審計記錄",+ "subtitle": "追蹤及查看所有 API 操作和系統事件",+ "exportCsv": "匯出 CSV",+ "searchPlaceholder": "搜尋記錄...",+ "severity": {+ "all": "所有嚴重程度",+ "info": "資訊",+ "warn": "警告",+ "error": "錯誤"+ },+ "columns": {+ "timestamp": "時間戳記",+ "action": "操作",+ "session": "工作階段",+ "apiKey": "API 金鑰",+ "ip": "IP 位址",+ "severity": "嚴重程度"+ },+ "empty": {+ "title": "找不到記錄",+ "description": "執行操作後,審計記錄會顯示在這裡"+ }+ },+ "messageTester": {+ "title": "訊息測試器",+ "subtitle": "透過 API 傳送測試訊息",+ "compose": "傳送測試訊息",+ "responseTitle": "API 回應",+ "session": "工作階段",+ "noReadySessions": "沒有就緒的工作階段",+ "sessionOptionPhoneNone": "沒有電話",+ "recipientType": "接收者類型",+ "personal": "個人",+ "group": "群組",+ "selectGroup": "選擇群組",+ "recipientPhone": "接收者電話號碼",+ "loadingGroups": "正在載入群組...",+ "noGroupsFound": "找不到群組",+ "selectGroupHint": "從你的 WhatsApp 選擇一個群組",+ "phoneHint": "使用不含空格的國際格式",+ "messageType": "訊息類型",+ "types": {+ "text": "文字",+ "image": "圖片",+ "video": "影片",+ "audio": "音訊",+ "document": "文件"+ },+ "messageContent": "訊息內容",+ "messagePlaceholder": "在此輸入你的訊息...",+ "mediaUrl": "媒體 URL",+ "caption": "說明文字",+ "filename": "檔案名稱",+ "captionPlaceholder": "輸入說明文字...",+ "filenamePlaceholder": "document.pdf",+ "send": "傳送訊息",+ "sending": "正在傳送...",+ "viewOnly": "僅檢視",+ "responseEmpty": "傳送訊息後即可查看 API 回應",+ "successLabel": "200 OK - 成功",+ "failedLabel": "400 - 失敗",+ "response": {+ "timestamp": "時間戳記",+ "messageId": "訊息 ID",+ "error": "錯誤"+ },+ "sendFailed": "傳送訊息失敗"+ },+ "infrastructure": {+ "title": "基礎架構",+ "subtitle": "設定伺服器、資料庫、快取、儲存空間和引擎設定",+ "saveConfig": "儲存設定",+ "saving": "正在儲存...",+ "server": {+ "title": "伺服器設定",+ "production": "生產",+ "development": "開發",+ "environment": "環境",+ "domain": "網域",+ "apiPort": "API 連接埠",+ "dashboardPort": "控制面板連接埠",+ "corsOrigins": "CORS 來源",+ "corsPlaceholder": "* 或以逗號分隔的來源",+ "publicApiUrl": "公開 API URL(選填)",+ "publicDashboardUrl": "公開控制面板 URL(選填)"+ },+ "webhook": {+ "title": "Webhook 及速率限制",+ "settings": "Webhook 設定",+ "timeout": "逾時(毫秒)",+ "maxRetries": "最大重試次數",+ "retryDelay": "重試延遲(毫秒)",+ "rateLimit": "速率限制",+ "window": "時間視窗(秒)",+ "maxReq": "每個視窗最大請求數"+ },+ "database": {+ "title": "資料庫設定",+ "sqlite": "SQLite",+ "sqliteDesc": "本機檔案型資料庫",+ "postgres": "PostgreSQL",+ "postgresDesc": "適用於生產環境的資料庫",+ "useBuiltIn": "使用內置 PostgreSQL 容器",+ "builtInDesc": "OpenWA 會為你管理 PostgreSQL 容器",+ "dbName": "資料庫名稱",+ "poolSize": "連線池大小",+ "ssl": "SSL 連線",+ "sslDesc": "啟用 TLS/SSL 以保障資料庫連線安全",+ "sslRejectUnauthorized": "驗證 SSL 憑證",+ "sslRejectUnauthorizedDesc": "拒絕自簽署或無效的憑證。對於使用自簽署憑證的託管 Postgres(Supabase、Heroku、Render、Railway),請關閉此項。",+ "migrationsTitle": "資料庫遷移",+ "migrationsStatus": "結構會透過 TypeORM 自動同步",+ "migrationsHint": "遷移會自動管理。手動遷移請使用 CLI。"+ },+ "redis": {+ "title": "Redis",+ "enable": "啟用 Redis",+ "enableDesc": "快取、工作階段儲存及 BullMQ 佇列需要 Redis",+ "useBuiltIn": "使用內置 Redis 容器",+ "builtInDesc": "OpenWA 會為你管理 Redis 容器",+ "queueTitle": "啟用 BullMQ 佇列系統",+ "queueDesc": "使用訊息佇列可靠地傳遞訊息和 Webhook",+ "statsTitle": "佇列統計",+ "messageQueue": "訊息佇列",+ "webhookQueue": "Webhook 佇列",+ "pending": "待處理",+ "completed": "已完成",+ "failed": "失敗",+ "clearFailed": "清除失敗任務",+ "viewBullMq": "查看 Bull MQ 控制面板",+ "disabledTitle": "Redis 已停用",+ "disabledDesc": "啟用 Redis 以使用快取、工作階段儲存及 BullMQ 訊息佇列。",+ "passwordOptional": "(選填)"+ },+ "storage": {+ "title": "儲存空間設定",+ "local": "本機檔案系統",+ "localDesc": "在本機儲存媒體檔案",+ "s3": "Amazon S3",+ "s3Desc": "雲端儲存空間(兼容 S3)",+ "useBuiltIn": "使用內置 MinIO 容器",+ "builtInDesc": "OpenWA 會為你管理 MinIO(兼容 S3)容器",+ "storagePath": "儲存路徑",+ "bucket": "儲存桶名稱",+ "region": "區域",+ "accessKey": "存取金鑰",+ "secretKey": "秘密金鑰",+ "endpoint": "自訂端點(選填)",+ "endpointHint": "適用於 MinIO 或其他兼容 S3 的服務"+ },+ "statusLabels": {+ "connected": "已連線",+ "disconnected": "已中斷連線",+ "disabled": "已停用"+ },+ "restart": {+ "idleTitle": "⚙️ 設定已儲存",+ "restartingTitle": "🔄 正在重新啟動伺服器...",+ "waitingTitle": "⏳ 請稍候...",+ "successTitle": "✅ 伺服器就緒",+ "errorTitle": "❌ 重新啟動失敗",+ "idleDesc": "設定已儲存到 <code>.env.generated</code>。<br/>需要重新啟動伺服器才能套用變更。",+ "later": "稍後重新啟動",+ "now": "立即重新啟動",+ "restartingMsg": "伺服器正在重新啟動... {{count}} 秒",+ "checking": "正在檢查伺服器狀態...",+ "dontClose": "請不要關閉此視窗",+ "successMsg": "伺服器已重新上線!頁面將自動重新載入。",+ "errorMsg": "伺服器在 30 秒後仍未回應。請檢查 Docker 記錄並手動重新啟動。",+ "reload": "重新載入頁面"+ },+ "toasts": {+ "saveFailed": "儲存失敗"+ }+ },+ "plugins": {+ "title": "外掛",+ "subtitle": "管理引擎、儲存後端和擴充功能",+ "refresh": "重新整理",+ "engineCard": "目前 WhatsApp 引擎",+ "running": "執行中",+ "supportedFeatures": "支援功能:",+ "more": "+{{count}} 更多",+ "builtIn": "內置",+ "noDescription": "沒有可用描述",+ "required": "必需",+ "active": "活躍",+ "activate": "啟用",+ "enable": "啟用",+ "disable": "停用",+ "healthCheck": "健康檢查",+ "configure": "設定",+ "empty": {+ "title": "找不到外掛",+ "description": "安裝外掛以擴展 OpenWA 功能"+ },+ "config": {+ "title": "設定 {{name}}",+ "restartNotice": "變更需要重新啟動伺服器後才會生效",+ "engineType": "引擎類型",+ "headless": "無頭模式",+ "headlessDesc": "執行不顯示介面的瀏覽器(建議用於生產環境)",+ "sessionDataPath": "工作階段資料路徑",+ "browserArgs": "瀏覽器參數",+ "noOptions": "此外掛沒有可用設定選項",+ "save": "儲存設定"+ },+ "toasts": {+ "errorTitle": "外掛錯誤",+ "errorDefault": "切換外掛失敗",+ "healthOk": "健康檢查通過",+ "healthFail": "健康檢查失敗",+ "healthError": "健康檢查錯誤",+ "savedTitle": "設定已儲存",+ "savedDesc": "需要重新啟動伺服器以套用變更。",+ "saveFailed": "儲存失敗"+ }+ }+}diff --git a/dashboard/src/index.css b/dashboard/src/index.cssindex 82bee6d25..5e913aad0 100644--- a/dashboard/src/index.css+++ b/dashboard/src/index.css@@ -1,4 +1,5 @@@import url('https://fonts.googleapis.com/css2?family=Heebo:wght@400;500;600;700&display=swap');+@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@400;500;600;700&display=swap');:root {font-family: 'Plus Jakarta Sans', system-ui, Avenir, Helvetica, Arial, sans-serif;@@ -11,6 +12,10 @@ html[dir="rtl"] {font-family: 'Heebo', 'Rubik', 'Noto Sans Hebrew', 'Segoe UI', Arial, sans-serif;}+html[lang="ar"] {+ font-family: 'Noto Sans Arabic', 'Cairo', 'Tajawal', 'Segoe UI', Arial, sans-serif;+}+:root {color-scheme: light dark;@@ -359,3 +364,56 @@ code {left: 1rem;}+/* Mobile Responsive - Global */+@media (max-width: 768px) {+ h1 {+ font-size: 1.5rem;+ }++ .modal {+ width: 95%;+ max-width: none;+ margin: 1rem;+ border-radius: 12px;+ }++ .modal-header {+ padding: 1.25rem 1.25rem 0.875rem;+ }++ .modal-header h2 {+ font-size: 1.125rem;+ }++ .modal-body {+ padding: 1.25rem;+ }++ .modal-footer {+ padding: 0.875rem 1.25rem 1.25rem;+ }++ select {+ padding: 0.625rem 2.25rem 0.625rem 0.875rem;+ font-size: 0.875rem;+ }+}++@media (max-width: 480px) {+ h1 {+ font-size: 1.25rem;+ }++ .modal-overlay {+ align-items: flex-end;+ }++ .modal {+ width: 100%;+ margin: 0;+ border-radius: 16px 16px 0 0;+ max-height: 90vh;+ overflow-y: auto;+ }+}+diff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.cssnew file mode 100644index 000000000..eca635685--- /dev/null+++ b/dashboard/src/pages/Chats.css@@ -0,0 +1,969 @@+.chats-page {+ padding: 2rem;+ width: 100%;+ height: calc(100vh - 4rem);+ display: flex;+ flex-direction: column;+ box-sizing: border-box;+}++.chats-layout {+ display: flex;+ flex: 1;+ background: var(--bg-white);+ border: 1px solid var(--border);+ border-radius: 16px;+ overflow: hidden;+ box-shadow: var(--shadow-md, 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06));+ height: calc(100vh - 12rem);+ margin-top: 1rem;+}++/* =============================================================================+ SIDEBAR: Left Column+ ============================================================================= */+.chats-sidebar {+ width: 320px;+ border-right: 1px solid var(--border);+ display: flex;+ flex-direction: column;+ background: var(--bg-white);+ flex-shrink: 0;+}++.sidebar-header-box {+ padding: 1.25rem;+ border-bottom: 1px solid var(--border);+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.session-select-group {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+}++.session-selector {+ width: 100%;+ padding: 0.625rem 0.75rem;+ border: 1px solid var(--border);+ border-radius: var(--radius, 8px);+ background: var(--bg-light);+ color: var(--text-primary);+ font-size: 0.875rem;+ font-weight: 500;+ outline: none;+ cursor: pointer;+ transition: all 0.2s;+}++.session-selector:focus {+ border-color: var(--primary);+ background: var(--bg-white);+ box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.1);+}++.chat-search-input {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ padding: 0.625rem 0.75rem;+ background: var(--bg-light);+ border: 1px solid var(--border);+ border-radius: var(--radius, 8px);+}++.chat-search-input svg {+ color: var(--text-muted);+ flex-shrink: 0;+}++.chat-search-input input {+ flex: 1;+ border: none;+ background: none;+ font-size: 0.875rem;+ color: var(--text-primary);+ outline: none;+}++.chats-list {+ flex: 1;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+}++/* Custom Scrollbar for chats list */+.chats-list::-webkit-scrollbar,+.room-messages::-webkit-scrollbar {+ width: 6px;+}++.chats-list::-webkit-scrollbar-thumb,+.room-messages::-webkit-scrollbar-thumb {+ background: rgba(0, 0, 0, 0.1);+ border-radius: 3px;+}++.chats-list::-webkit-scrollbar-track,+.room-messages::-webkit-scrollbar-track {+ background: transparent;+}++.chats-list-loading,+.chats-list-empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: 3rem 1.5rem;+ color: var(--text-muted);+ font-size: 0.875rem;+ gap: 0.5rem;+}++.chat-item-card {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ padding: 1rem 1.25rem;+ border-bottom: 1px solid var(--border);+ cursor: pointer;+ transition: background 0.15s ease;+ user-select: none;+}++.chat-item-card:hover {+ background: var(--bg-light);+}++.chat-item-card.active {+ background: rgba(34, 197, 94, 0.08);+}++.chat-avatar {+ width: 44px;+ height: 44px;+ border-radius: 50%;+ background: var(--bg-light);+ border: 1px solid var(--border);+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--text-secondary);+ flex-shrink: 0;+}++.chat-item-card.active .chat-avatar {+ background: var(--bg-white);+ color: var(--primary);+ border-color: rgba(34, 197, 94, 0.3);+}++.chat-item-info {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0; /* Ensures text truncation works */+}++.chat-item-top {+ display: flex;+ justify-content: space-between;+ align-items: baseline;+}++.chat-item-name {+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--text-primary);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.chat-item-time {+ font-size: 0.75rem;+ color: var(--text-muted);+ white-shrink: 0;+}++.chat-item-bottom {+ display: flex;+ justify-content: space-between;+ align-items: center;+}++.chat-item-snippet {+ font-size: 0.8125rem;+ color: var(--text-muted);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ max-width: 180px;+}++.chat-item-snippet .no-message {+ font-style: italic;+ opacity: 0.6;+}++.chat-unread-badge {+ background: var(--primary);+ color: white;+ font-size: 0.75rem;+ font-weight: 700;+ padding: 0.125rem 0.375rem;+ border-radius: 10px;+ min-width: 14px;+ text-align: center;+ box-shadow: 0 2px 4px rgba(34, 197, 94, 0.3);+}++/* =============================================================================+ CHAT ROOM: Right Column+ ============================================================================= */+.chats-room {+ flex: 1;+ display: flex;+ flex-direction: column;+ background: var(--bg-light);+}++.chats-room-placeholder {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: 3rem;+ text-align: center;+ color: var(--text-muted);+}++.placeholder-icon {+ margin-bottom: 1.5rem;+ opacity: 0.3;+ color: var(--text-secondary);+}++.chats-room-placeholder h2 {+ font-size: 1.5rem;+ font-weight: 700;+ color: var(--text-secondary);+ margin: 0 0 0.5rem;+}++.chats-room-placeholder p {+ font-size: 0.9375rem;+ max-width: 380px;+ margin: 0;+}++.room-container {+ flex: 1;+ display: flex;+ flex-direction: column;+ height: 100%;+}++.room-header {+ height: 70px;+ background: var(--bg-white);+ border-bottom: 1px solid var(--border);+ padding: 0 1.5rem;+ display: flex;+ align-items: center;+ gap: 0.75rem;+ box-sizing: border-box;+}++.room-avatar {+ width: 40px;+ height: 40px;+ border-radius: 50%;+ background: var(--bg-light);+ border: 1px solid var(--border);+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--text-secondary);+}++.room-contact-info h3 {+ font-size: 1rem;+ font-weight: 600;+ color: var(--text-primary);+ margin: 0;+}++.room-contact-info span {+ font-size: 0.75rem;+ color: var(--text-muted);+ font-family: monospace;+}++.room-messages {+ flex: 1;+ padding: 1.5rem;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+ background-image: radial-gradient(var(--border) 1px, transparent 0);+ background-size: 24px 24px;+}++.messages-loading {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ flex: 1;+ color: var(--text-muted);+ font-size: 0.9375rem;+ gap: 0.75rem;+}++.messages-empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ flex: 1;+ color: var(--text-muted);+ font-size: 0.9375rem;+ gap: 0.75rem;+ text-align: center;+ padding: 2rem;+}++.message-bubble-wrapper {+ display: flex;+ width: 100%;+}++.message-bubble-wrapper.incoming {+ justify-content: flex-start;+}++.message-bubble-wrapper.outgoing {+ justify-content: flex-end;+}++.message-bubble {+ max-width: 100%;+ padding: 0.625rem 0.875rem 0.375rem;+ border-radius: 12px;+ font-size: 0.9375rem;+ line-height: 1.4;+ position: relative;+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);+}++.message-bubble.incoming {+ background: var(--bg-white);+ color: var(--text-primary);+ border-bottom-left-radius: 2px;+ border: 1px solid var(--border);+}++.message-bubble.outgoing {+ background: #d9fdd3; /* Soft WhatsApp Green */+ color: #111b21;+ border-bottom-right-radius: 2px;+}++/* Dark theme outgoing chat bubble override */+[data-theme='dark'] .message-bubble.outgoing {+ background: #005c4b; /* Dark WhatsApp Green */+ color: #e9edef;+}++.chats-page .message-text {+ word-break: break-word;+ white-space: pre-wrap;+}++.chats-page .message-meta {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 0.25rem;+ margin-top: 0.25rem;+}++.chats-page .message-time {+ font-size: 0.6875rem;+ color: var(--text-muted);+}++.chats-page .message-status-icon {+ font-size: 0.75rem;+}++.chats-page .message-status-icon.read {+ color: #53bdeb; /* WhatsApp blue checks */+}++/* =============================================================================+ INPUT BAR: Bottom Footer+ ============================================================================= */+.room-input-footer {+ background: var(--bg-white);+ border-top: 1px solid var(--border);+ padding: 1rem 1.5rem;+ box-sizing: border-box;+}++.chats-page .input-form {+ display: flex;+ gap: 0.75rem;+ align-items: center;+}++.message-text-input {+ flex: 1;+ padding: 0.75rem 1rem;+ border: 1px solid var(--border);+ border-radius: 24px;+ font-size: 0.9375rem;+ background: var(--bg-light);+ color: var(--text-primary);+ outline: none;+ transition: all 0.2s;+ box-sizing: border-box;+}++.message-text-input:focus {+ border-color: var(--primary);+ background: var(--bg-white);+ box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.1);+}++.btn-send-message {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 44px;+ height: 44px;+ background: var(--primary);+ border: none;+ border-radius: 50%;+ color: white;+ cursor: pointer;+ transition: background 0.2s, transform 0.1s;+ flex-shrink: 0;+ box-shadow: 0 2px 8px rgba(34, 197, 94, 0.3);+}++.btn-send-message:hover:not(:disabled) {+ background: var(--primary-hover);+ transform: scale(1.05);+}++.btn-send-message:disabled {+ background: var(--border);+ color: var(--text-muted);+ cursor: not-allowed;+ box-shadow: none;+}++/* =============================================================================+ GENERAL CHATS STYLES & ERROR STATES+ ============================================================================= */+.chats-loading-container,+.chats-error-state {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ background: var(--bg-white);+ border: 1px solid var(--border);+ border-radius: 16px;+ padding: 4rem 2rem;+ margin-top: 1rem;+ text-align: center;+ color: var(--text-secondary);+ box-shadow: var(--shadow-sm);+ flex: 1;+}++.chats-error-state h3 {+ font-size: 1.25rem;+ margin: 1rem 0 0.5rem;+ color: var(--text-primary);+}++.chats-error-state p {+ font-size: 0.9375rem;+ max-width: 450px;+ margin: 0;+ color: var(--text-muted);+}++.text-warn {+ color: #ea580c;+}++/* =============================================================================+ ATTACHMENT PREVIEW & EMOJI PICKER+ ============================================================================= */+.btn-input-accessory {+ background: transparent;+ border: none;+ color: var(--text-secondary);+ cursor: pointer;+ padding: 0.5rem;+ border-radius: 50%;+ display: flex;+ align-items: center;+ justify-content: center;+ transition: all 0.2s ease;+ flex-shrink: 0;+}++.btn-input-accessory:hover {+ background: var(--bg-light);+ color: var(--text-primary);+}++.btn-input-accessory.active {+ background: rgba(34, 197, 94, 0.1);+ color: var(--primary);+}++.attachment-preview-banner {+ background: var(--bg-white);+ border-top: 1px solid var(--border);+ padding: 0.75rem 1.5rem;+ display: flex;+ align-items: center;+ gap: 1rem;+ box-sizing: border-box;+}++.chats-page .preview-thumbnail {+ width: 48px;+ height: 48px;+ object-fit: cover;+ border-radius: 6px;+ border: 1px solid var(--border);+}++.chats-page .preview-file-icon {+ width: 48px;+ height: 48px;+ background: var(--bg-light);+ border: 1px solid var(--border);+ border-radius: 6px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 1.5rem;+}++.chats-page .preview-file-info {+ flex: 1;+ display: flex;+ flex-direction: column;+ min-width: 0;+}++.chats-page .preview-filename {+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--text-primary);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.chats-page .preview-filesize {+ font-size: 0.75rem;+ color: var(--text-muted);+}++.btn-remove-attachment {+ background: transparent;+ border: none;+ color: var(--text-muted);+ cursor: pointer;+ padding: 0.375rem;+ border-radius: 50%;+ display: flex;+ align-items: center;+ justify-content: center;+ transition: all 0.2s;+}++.btn-remove-attachment:hover {+ background: #fee2e2;+ color: #dc2626;+}++.chats-emoji-picker {+ background: var(--bg-white);+ border-top: 1px solid var(--border);+ padding: 0.75rem 1.5rem;+ box-sizing: border-box;+ max-height: 120px;+ overflow-y: auto;+}++.chats-page .emoji-grid {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+}++.chats-page .emoji-btn {+ background: transparent;+ border: none;+ font-size: 1.25rem;+ padding: 0.375rem;+ border-radius: 6px;+ cursor: pointer;+ transition: all 0.15s;+ display: flex;+ align-items: center;+ justify-content: center;+}++.chats-page .emoji-btn:hover {+ background: var(--bg-light);+ transform: scale(1.15);+}++.message-bubble.media-type {+ border-top-left-radius: 12px;+ border-top-right-radius: 12px;+}++/* =============================================================================+ RESPONSIVENESS+ ============================================================================= */+@media (max-width: 768px) {+ .chats-page {+ padding: 1rem;+ height: auto;+ }++ .chats-layout {+ flex-direction: column;+ height: 600px;+ }++ .chats-sidebar {+ width: 100%;+ height: 250px;+ border-right: none;+ border-bottom: 1px solid var(--border);+ }++ .chats-room {+ height: 350px;+ }++ .room-header {+ height: 60px;+ }+}++/* =============================================================================+ MEDIA RENDERING STYLES+ ============================================================================= */+.chat-image-media {+ max-width: 100%;+ max-height: 250px;+ border-radius: 8px;+ display: block;+ margin-bottom: 0.5rem;+ cursor: pointer;+ object-fit: cover;+}++.chat-video-media {+ max-width: 100%;+ max-height: 250px;+ border-radius: 8px;+ display: block;+ margin-bottom: 0.5rem;+}++.chat-audio-media {+ max-width: 100%;+ display: block;+ margin-bottom: 0.5rem;+}++.chat-document-media {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ padding: 0.5rem 0.75rem;+ background: var(--bg-light);+ border: 1px solid var(--border);+ border-radius: 6px;+ color: var(--text-primary);+ text-decoration: none;+ font-size: 0.875rem;+ font-weight: 500;+ margin-bottom: 0.5rem;+ transition: all 0.2s;+ word-break: break-all;+}++.chat-document-media:hover {+ background: var(--border);+}++[data-theme='dark'] .chat-document-media {+ background: #202c33;+ border-color: #2f3b43;+}++.message-bubble.media-type {+ padding: 0.5rem;+}++/* =============================================================================+ HOVER MENU, REPLIES, REACTIONS, AND DELETIONS+ ============================================================================= */+.message-bubble-container {+ position: relative;+ display: flex;+ align-items: center;+ gap: 0.5rem;+ max-width: 70%;+}++.message-bubble-wrapper.outgoing .message-bubble-container {+ flex-direction: row-reverse;+}++.message-bubble-wrapper.incoming .message-bubble-container {+ flex-direction: row;+}++/* Hover Menu */+.message-actions-menu {+ display: none;+ align-items: center;+ gap: 0.25rem;+ background: var(--bg-white);+ border: 1px solid var(--border);+ box-shadow: var(--shadow-sm);+ border-radius: 20px;+ padding: 2px 6px;+ z-index: 5;+}++.message-bubble-container:hover .message-actions-menu {+ display: flex;+}++.chats-page .action-btn {+ background: transparent;+ border: none;+ color: var(--text-muted);+ cursor: pointer;+ padding: 4px;+ border-radius: 50%;+ display: flex;+ align-items: center;+ justify-content: center;+ transition: all 0.15s ease;+}++.chats-page .action-btn:hover {+ background: var(--bg-light);+ color: var(--text-primary);+}++.chats-page .action-btn.delete-btn:hover {+ color: #dc2626;+ background: #fee2e2;+}++/* Reaction Quick Popover */+.reaction-trigger-wrapper {+ position: relative;+}++.reaction-quick-popover {+ display: none;+ position: absolute;+ bottom: 100%;+ left: 50%;+ transform: translateX(-50%) translateY(-6px);+ background: var(--bg-white);+ border: 1px solid var(--border);+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);+ border-radius: 24px;+ padding: 0.375rem 0.625rem;+ gap: 0.375rem;+ z-index: 50;+ white-space: nowrap;+}++.reaction-quick-popover::after {+ content: '';+ position: absolute;+ top: 100%;+ left: 0;+ right: 0;+ height: 12px;+ background: transparent;+}++.reaction-trigger-wrapper:hover .reaction-quick-popover {+ display: flex;+}++.reaction-quick-popover button {+ background: transparent;+ border: none;+ font-size: 1.25rem;+ padding: 2px;+ cursor: pointer;+ transition: transform 0.1s ease;+}++.reaction-quick-popover button:hover {+ transform: scale(1.3);+}++/* Reactions Badge */+.message-reactions-badge {+ position: absolute;+ bottom: -12px;+ background: var(--bg-white);+ border: 1px solid var(--border);+ box-shadow: var(--shadow-sm);+ border-radius: 12px;+ padding: 2px 6px;+ display: flex;+ align-items: center;+ gap: 2px;+ font-size: 0.75rem;+ z-index: 2;+ cursor: pointer;+ user-select: none;+}++.message-bubble-wrapper.outgoing .message-reactions-badge {+ right: 12px;+}++.message-bubble-wrapper.incoming .message-reactions-badge {+ left: 12px;+}++.reaction-emoji-span {+ font-size: 0.8125rem;+}++.reactions-count-span {+ font-weight: 600;+ color: var(--text-secondary);+ margin-left: 2px;+}++/* Quoted Box inside Bubble */+.message-quote-box {+ background: rgba(0, 0, 0, 0.04);+ border-left: 4px solid var(--primary);+ border-radius: 4px;+ padding: 0.375rem 0.625rem;+ margin-bottom: 0.5rem;+ font-size: 0.8125rem;+ color: var(--text-secondary);+ cursor: pointer;+}++.message-bubble.outgoing .message-quote-box {+ background: rgba(0, 0, 0, 0.05);+ border-left-color: #008069;+}++[data-theme='dark'] .message-quote-box {+ background: rgba(255, 255, 255, 0.08);+}++.chats-page .quote-body {+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ max-width: 250px;+}++/* Replying Preview Banner above Input Footer */+.replying-preview-banner {+ background: var(--bg-white);+ border-top: 1px solid var(--border);+ padding: 0.75rem 1.5rem;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ box-sizing: border-box;+}++.replying-preview-content {+ flex: 1;+ border-left: 4px solid var(--primary);+ padding-left: 0.75rem;+ display: flex;+ flex-direction: column;+ min-width: 0;+}++.replying-to-title {+ font-size: 0.8125rem;+ font-weight: 700;+ color: var(--primary);+}++.replying-to-body {+ font-size: 0.875rem;+ color: var(--text-secondary);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.btn-close-reply {+ background: transparent;+ border: none;+ color: var(--text-muted);+ cursor: pointer;+ padding: 0.375rem;+ border-radius: 50%;+ display: flex;+ align-items: center;+ justify-content: center;+ transition: all 0.2s;+}++.btn-close-reply:hover {+ background: var(--bg-light);+ color: var(--text-primary);+}++/* Revoked / Deleted message type */+.message-bubble.revoked-type {+ font-style: italic;+ opacity: 0.6;+}++[data-theme='dark'] .message-actions-menu,+[data-theme='dark'] .reaction-quick-popover,+[data-theme='dark'] .message-reactions-badge {+ background: #202c33;+ border-color: #2f3b43;+}diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxnew file mode 100644index 000000000..7a53875f9--- /dev/null+++ b/dashboard/src/pages/Chats.tsx@@ -0,0 +1,999 @@+import { useState, useEffect, useCallback, useRef } from 'react';+import { Trans, useTranslation } from 'react-i18next';+import {+ Search,+ Send,+ Loader2,+ User,+ Users,+ AlertCircle,+ MessageSquare,+ Paperclip,+ Smile,+ X,+ CornerUpLeft,+ Trash2,+} from 'lucide-react';+import { sessionApi, messageApi, type Session, type Chat, type ChatMessage } from '../services/api';+import { useWebSocket } from '../hooks/useWebSocket';+import { useDocumentTitle } from '../hooks/useDocumentTitle';+import { useRole } from '../hooks/useRole';+import { useToast } from '../components/Toast';+import { PageHeader } from '../components/PageHeader';+import './Chats.css';++type MessageMedia = { mimetype: string; filename?: string; data?: string };++interface ChatMessageView extends ChatMessage {+ metadata?: {+ media?: MessageMedia;+ quotedMessage?: { id: string; body: string };+ reactions?: Record<string, string>;+ };+}++interface IncomingWsMessage {+ id: string;+ chatId: string;+ from: string;+ to: string;+ body: string;+ type: string;+ timestamp: number;+ fromMe?: boolean;+ media?: MessageMedia;+ quotedMessage?: { id: string; body: string };+ metadata?: ChatMessageView['metadata'];+}++const getMediaSrc = (media?: MessageMedia): string => {+ if (!media || !media.data) return '';+ if (media.data.startsWith('data:') || media.data.startsWith('http://') || media.data.startsWith('https://')) {+ return media.data;+ }+ return `data:${media.mimetype};base64,${media.data}`;+};++export function Chats() {+ const { t } = useTranslation();+ useDocumentTitle(t('nav.chats'));+ const { canWrite } = useRole();+ const toast = useToast();++ // Sessions list & active session+ const [sessions, setSessions] = useState<Session[]>([]);+ const [selectedSessionId, setSelectedSessionId] = useState<string>('');+ const [loadingSessions, setLoadingSessions] = useState<boolean>(true);++ // Chats list+ const [chats, setChats] = useState<Chat[]>([]);+ const [loadingChats, setLoadingChats] = useState<boolean>(false);+ const [searchQuery, setSearchQuery] = useState<string>('');++ // Selected chat & message history+ const [activeChat, setActiveChat] = useState<Chat | null>(null);+ const [messages, setMessages] = useState<ChatMessageView[]>([]);+ const [loadingMessages, setLoadingMessages] = useState<boolean>(false);+ const [messageInput, setMessageInput] = useState<string>('');+ const [sending, setSending] = useState<boolean>(false);++ // File attachments+ const [attachment, setAttachment] = useState<{+ file: File;+ base64: string;+ mimetype: string;+ filename: string;+ } | null>(null);+ const [previewUrl, setPreviewUrl] = useState<string | null>(null);+ const [showEmojiPicker, setShowEmojiPicker] = useState<boolean>(false);++ // References+ const chatBottomRef = useRef<HTMLDivElement | null>(null);+ const fileInputRef = useRef<HTMLInputElement | null>(null);+ const [replyingTo, setReplyingTo] = useState<ChatMessageView | null>(null);++ // Popular emojis+ const popularEmojis = ['😀', '😂', '👍', '❤️', '🔥', '👏', '🙏', '🎉', '💡', '🤔', '😅', '😍', '😊', '😭', '😎', '😜', '🚀', '✨'];++ // 1. Fetch available connected sessions on mount+ useEffect(() => {+ const loadSessions = async () => {+ try {+ setLoadingSessions(true);+ const list = await sessionApi.list();+ const readySessions = list.filter(s => s.status === 'ready');+ setSessions(readySessions);+ if (readySessions.length > 0) {+ setSelectedSessionId(readySessions[0].id);+ }+ } catch (err) {+ toast.error(t('chats.errors.loadSessions'), err instanceof Error ? err.message : undefined);+ } finally {+ setLoadingSessions(false);+ }+ };+ void loadSessions();+ }, [t, toast]);++ // 2. Fetch chats when active session changes+ const loadChats = useCallback(+ async (sessionId: string) => {+ if (!sessionId) return;+ try {+ setLoadingChats(true);+ const data = await sessionApi.getChats(sessionId);+ const sorted = [...data].sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));+ setChats(sorted);+ } catch (err) {+ toast.error(t('chats.errors.loadChats'), err instanceof Error ? err.message : undefined);+ setChats([]);+ } finally {+ setLoadingChats(false);+ }+ },+ [t, toast],+ );++ useEffect(() => {+ if (selectedSessionId) {+ void loadChats(selectedSessionId);+ setActiveChat(null);+ setMessages([]);+ setAttachment(null);+ setPreviewUrl(null);+ }+ }, [selectedSessionId, loadChats]);++ const markChatRead = useCallback(+ (chatId: string) => {+ void sessionApi.markChatRead(selectedSessionId, chatId).catch(err => {+ toast.warning(t('chats.errors.markRead'), err instanceof Error ? err.message : undefined);+ });+ },+ [selectedSessionId, t, toast],+ );++ // 3. WebSocket integration for real-time messages+ const handleIncomingMessage = useCallback(+ (event: { sessionId: string; message: Record<string, unknown> }) => {+ if (event.sessionId !== selectedSessionId) return;++ const newMsg = event.message as unknown as IncomingWsMessage;++ // Update message list if the message belongs to the currently active chat+ if (activeChat && newMsg.chatId === activeChat.id) {+ markChatRead(activeChat.id);++ const mappedMessage: ChatMessageView = {+ id: newMsg.id,+ waMessageId: newMsg.id,+ chatId: newMsg.chatId,+ from: newMsg.from,+ to: newMsg.to,+ body: newMsg.body,+ type: newMsg.type,+ direction: newMsg.fromMe ? 'outgoing' : 'incoming',+ status: 'sent',+ timestamp: newMsg.timestamp,+ createdAt: new Date(newMsg.timestamp * 1000).toISOString(),+ metadata: newMsg.metadata || {+ media: newMsg.media,+ quotedMessage: newMsg.quotedMessage,+ },+ };++ setMessages(prev => {+ if (prev.some(m => m.id === mappedMessage.id || m.waMessageId === mappedMessage.id)) {+ return prev;+ }+ return [...prev, mappedMessage];+ });+ }++ // Update sidebar chat list+ setChats(prevChats => {+ const chatIndex = prevChats.findIndex(c => c.id === newMsg.chatId);+ if (chatIndex === -1) {+ void loadChats(selectedSessionId);+ return prevChats;+ }++ const updatedChats = [...prevChats];+ const targetChat = { ...updatedChats[chatIndex] };+ targetChat.lastMessage = newMsg.body;+ targetChat.timestamp = newMsg.timestamp;++ if (!newMsg.fromMe && (!activeChat || activeChat.id !== targetChat.id)) {+ targetChat.unreadCount = (targetChat.unreadCount || 0) + 1;+ }++ updatedChats.splice(chatIndex, 1);+ updatedChats.unshift(targetChat);+ return updatedChats;+ });+ },+ [selectedSessionId, activeChat, loadChats, markChatRead],+ );++ const handleIncomingMessageAck = useCallback(+ (event: { sessionId: string; messageId: string; ack: number }) => {+ if (event.sessionId !== selectedSessionId) return;++ setMessages(prev =>+ prev.map(msg => {+ if (msg.id === event.messageId || msg.waMessageId === event.messageId) {+ const statusMap: Record<number, ChatMessageView['status']> = {+ [-1]: 'failed',+ [0]: 'pending',+ [1]: 'sent',+ [2]: 'delivered',+ [3]: 'read',+ [4]: 'read',+ };+ return { ...msg, status: statusMap[event.ack] || msg.status };+ }+ return msg;+ }),+ );+ },+ [selectedSessionId],+ );++ const handleIncomingMessageReaction = useCallback(+ (event: { sessionId: string; messageId: string; reactions: Record<string, string> }) => {+ if (event.sessionId !== selectedSessionId) return;++ setMessages(prev =>+ prev.map(msg => {+ if (msg.id === event.messageId || msg.waMessageId === event.messageId) {+ const metadata = msg.metadata || {};+ return { ...msg, metadata: { ...metadata, reactions: event.reactions } };+ }+ return msg;+ }),+ );+ },+ [selectedSessionId],+ );++ const handleIncomingMessageRevoked = useCallback(+ (event: { sessionId: string; id: string; type: string }) => {+ if (event.sessionId !== selectedSessionId) return;++ setMessages(prev =>+ prev.map(msg => {+ if (msg.id === event.id || msg.waMessageId === event.id) {+ // The backend emits an empty body; the localized "deleted" label is rendered below.+ return { ...msg, body: '', type: event.type };+ }+ return msg;+ }),+ );+ },+ [selectedSessionId],+ );++ const { isConnected, subscribe, unsubscribe } = useWebSocket({+ onMessage: handleIncomingMessage,+ onMessageAck: handleIncomingMessageAck,+ onMessageReaction: handleIncomingMessageReaction,+ onMessageRevoked: handleIncomingMessageRevoked,+ });++ useEffect(() => {+ if (selectedSessionId && isConnected) {+ subscribe(selectedSessionId, [+ 'message.received',+ 'message.sent',+ 'message.ack',+ 'message.reaction',+ 'message.revoked',+ ]);+ return () => {+ unsubscribe(selectedSessionId);+ };+ }+ }, [selectedSessionId, isConnected, subscribe, unsubscribe]);++ // 4. Fetch message history for the selected chat+ const loadMessages = useCallback(+ async (chatId: string) => {+ if (!selectedSessionId || !chatId) return;+ try {+ setLoadingMessages(true);+ markChatRead(chatId);+ const data = await sessionApi.getChatMessages(selectedSessionId, chatId, 100);+ setMessages([...data.messages].reverse());+ } catch (err) {+ toast.error(t('chats.errors.loadMessages'), err instanceof Error ? err.message : undefined);+ setMessages([]);+ } finally {+ setLoadingMessages(false);+ }+ },+ [selectedSessionId, markChatRead, t, toast],+ );++ const handleReactMessage = async (msg: ChatMessageView, emoji: string) => {+ if (!selectedSessionId || !activeChat) return;++ const msgId = msg.waMessageId || msg.id;+ const currentReactions = msg.metadata?.reactions || {};+ const sessionPhone = sessions.find(s => s.id === selectedSessionId)?.phone || 'me';++ let alreadyReacted = false;+ for (const [sender, emo] of Object.entries(currentReactions)) {+ if ((sender === 'me' || sender.includes(sessionPhone)) && emo === emoji) {+ alreadyReacted = true;+ break;+ }+ }++ const emojiToSend = alreadyReacted ? '' : emoji;++ try {+ await messageApi.react(selectedSessionId, {+ chatId: activeChat.id,+ messageId: msgId,+ emoji: emojiToSend,+ });++ setMessages(prev =>+ prev.map(m => {+ if (m.id === msg.id || m.waMessageId === msg.id) {+ const metadata = m.metadata || {};+ const reactions = { ...(metadata.reactions || {}) };+ if (emojiToSend === '') {+ delete reactions['me'];+ } else {+ reactions['me'] = emojiToSend;+ }+ return { ...m, metadata: { ...metadata, reactions } };+ }+ return m;+ }),+ );+ } catch (err) {+ toast.error(t('chats.errors.react'), err instanceof Error ? err.message : undefined);+ }+ };++ const handleDeleteMessage = async (msg: ChatMessageView) => {+ if (!selectedSessionId || !activeChat) return;+ const msgId = msg.waMessageId || msg.id;++ if (!window.confirm(t('chats.deleteConfirm'))) return;++ try {+ await messageApi.delete(selectedSessionId, {+ chatId: activeChat.id,+ messageId: msgId,+ forEveryone: true,+ });++ setMessages(prev =>+ prev.map(m => {+ if (m.id === msg.id || m.waMessageId === msg.id) {+ return { ...m, body: '', type: 'revoked' };+ }+ return m;+ }),+ );+ } catch (err) {+ toast.error(t('chats.errors.delete'), err instanceof Error ? err.message : undefined);+ }+ };++ useEffect(() => {+ if (activeChat) {+ void loadMessages(activeChat.id);+ setChats(prev => prev.map(c => (c.id === activeChat.id ? { ...c, unreadCount: 0 } : c)));+ } else {+ setMessages([]);+ }+ }, [activeChat, loadMessages]);++ // 5. Scroll chat to bottom+ useEffect(() => {+ chatBottomRef.current?.scrollIntoView({ behavior: 'smooth' });+ }, [messages]);++ // 6. Handle file selection & base64 conversion+ const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ if (!file) return;++ if (file.type.startsWith('image/')) {+ setPreviewUrl(URL.createObjectURL(file));+ } else {+ setPreviewUrl(null);+ }++ const reader = new FileReader();+ reader.onload = event => {+ const dataUrl = event.target?.result as string;+ const base64Data = dataUrl.split(',')[1];+ setAttachment({ file, base64: base64Data, mimetype: file.type, filename: file.name });+ };+ reader.readAsDataURL(file);+ };++ const handleRemoveAttachment = () => {+ setAttachment(null);+ setPreviewUrl(null);+ if (fileInputRef.current) fileInputRef.current.value = '';+ };++ const triggerFileSelect = () => {+ fileInputRef.current?.click();+ };++ const handleEmojiClick = (emoji: string) => {+ setMessageInput(prev => prev + emoji);+ setShowEmojiPicker(false);+ };++ // 7. Handle sending a message / media+ const handleSend = async (e?: React.FormEvent) => {+ if (e) e.preventDefault();+ if (!selectedSessionId || !activeChat || sending) return;++ const textToSend = messageInput.trim();+ if (!textToSend && !attachment) return;++ setMessageInput('');+ setSending(true);++ const tempId = `temp_${Date.now()}`;+ const tempMessage: ChatMessageView = {+ id: tempId,+ chatId: activeChat.id,+ from: 'me',+ to: activeChat.id,+ body: attachment+ ? attachment.mimetype.startsWith('image/') ||+ attachment.mimetype.startsWith('video/') ||+ attachment.mimetype.startsWith('audio/')+ ? textToSend+ : attachment.filename+ : textToSend,+ type: attachment ? attachment.mimetype.split('/')[0] : 'text',+ direction: 'outgoing',+ status: 'pending',+ createdAt: new Date().toISOString(),+ metadata: attachment+ ? {+ media: {+ mimetype: attachment.mimetype,+ filename: attachment.filename,+ data: attachment.base64,+ },+ }+ : replyingTo+ ? {+ quotedMessage: {+ id: replyingTo.waMessageId || replyingTo.id,+ body: replyingTo.type !== 'text' ? `[${replyingTo.type}]` : replyingTo.body,+ },+ }+ : undefined,+ };++ setMessages(prev => [...prev, tempMessage]);++ const currentAttachment = attachment;+ const currentReplyingTo = replyingTo;+ handleRemoveAttachment();+ setReplyingTo(null);++ try {+ let result;++ if (currentAttachment) {+ let mediaType: 'image' | 'video' | 'audio' | 'document' = 'document';+ const mime = currentAttachment.mimetype;+ if (mime.startsWith('image/')) mediaType = 'image';+ else if (mime.startsWith('video/')) mediaType = 'video';+ else if (mime.startsWith('audio/')) mediaType = 'audio';++ result = await messageApi.sendMedia(selectedSessionId, activeChat.id, mediaType, {+ base64: currentAttachment.base64,+ mimetype: currentAttachment.mimetype,+ filename: currentAttachment.filename,+ caption: mediaType !== 'audio' ? textToSend : undefined,+ });+ } else if (currentReplyingTo) {+ result = await messageApi.reply(selectedSessionId, {+ chatId: activeChat.id,+ quotedMessageId: currentReplyingTo.waMessageId || currentReplyingTo.id,+ text: textToSend,+ });+ } else {+ result = await messageApi.sendText(selectedSessionId, activeChat.id, textToSend);+ }++ setMessages(prev =>+ prev.map(m =>+ m.id === tempId ? { ...m, id: result.messageId, waMessageId: result.messageId, status: 'sent' } : m,+ ),+ );++ // Update sidebar chat list (move active chat to the top with the new snippet)+ setChats(prevChats => {+ const chatIndex = prevChats.findIndex(c => c.id === activeChat.id);+ if (chatIndex === -1) return prevChats;+ const updatedChats = [...prevChats];+ const target = { ...updatedChats[chatIndex] };+ target.lastMessage = currentAttachment+ ? `[${currentAttachment.mimetype.split('/')[0]}]`+ : textToSend;+ target.timestamp = Math.floor(Date.now() / 1000);+ updatedChats.splice(chatIndex, 1);+ updatedChats.unshift(target);+ return updatedChats;+ });+ } catch (err) {+ toast.error(t('chats.errors.send'), err instanceof Error ? err.message : undefined);+ setMessages(prev => prev.map(m => (m.id === tempId ? { ...m, status: 'failed' } : m)));+ } finally {+ setSending(false);+ }+ };++ // Helper formats+ const formatTime = (timestamp?: number) => {+ if (!timestamp) return '';+ return new Date(timestamp * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });+ };++ const formatLastMessageSnippet = (chat: Chat) => chat.lastMessage || '';++ const formatChatTime = (timestamp?: number) => {+ if (!timestamp) return '';+ const date = new Date(timestamp * 1000);+ const today = new Date();+ if (date.toDateString() === today.toDateString()) {+ return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });+ }+ const yesterday = new Date(today);+ yesterday.setDate(yesterday.getDate() - 1);+ if (date.toDateString() === yesterday.toDateString()) {+ return t('chats.yesterday');+ }+ return date.toLocaleDateString([], { month: 'short', day: 'numeric' });+ };++ const filteredChats = chats.filter(+ c =>+ c.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||+ c.id.toLowerCase().includes(searchQuery.toLowerCase()),+ );++ return (+ <div className="chats-page">+ <PageHeader title={t('nav.chats')} subtitle={t('chats.subtitle')} />++ {loadingSessions ? (+ <div className="chats-loading-container">+ <Loader2 className="animate-spin" size={32} />+ <p>{t('common.loading')}</p>+ </div>+ ) : sessions.length === 0 ? (+ <div className="chats-error-state">+ <AlertCircle size={48} className="text-warn" />+ <h3>{t('chats.noSessionsTitle')}</h3>+ <p>+ <Trans i18nKey="chats.noSessionsDesc">+ Please connect a WhatsApp session from the <strong>Sessions</strong> menu first to use the chat+ feature.+ </Trans>+ </p>+ </div>+ ) : (+ <div className="chats-layout">+ {/* LEFT SIDEBAR: session & chat rooms */}+ <aside className="chats-sidebar">+ <div className="sidebar-header-box">+ {/* Session selector */}+ <div className="session-select-group">+ <label className="form-label">{t('chats.sessionLabel')}</label>+ <select+ value={selectedSessionId}+ onChange={e => setSelectedSessionId(e.target.value)}+ className="session-selector"+ >+ {sessions.map(s => (+ <option key={s.id} value={s.id}>+ {s.name} ({s.phone || t('chats.noPhone')})+ </option>+ ))}+ </select>+ </div>++ {/* Search bar */}+ <div className="chat-search-input">+ <Search size={18} />+ <input+ type="text"+ placeholder={t('chats.searchPlaceholder')}+ value={searchQuery}+ onChange={e => setSearchQuery(e.target.value)}+ />+ </div>+ </div>++ {/* Chat list */}+ <div className="chats-list">+ {loadingChats ? (+ <div className="chats-list-loading">+ <Loader2 className="animate-spin" size={24} />+ <span>{t('chats.loadingChats')}</span>+ </div>+ ) : filteredChats.length === 0 ? (+ <div className="chats-list-empty">+ <span>{t('chats.empty')}</span>+ </div>+ ) : (+ filteredChats.map(chat => {+ const isActive = activeChat?.id === chat.id;+ return (+ <div+ key={chat.id}+ className={`chat-item-card ${isActive ? 'active' : ''}`}+ onClick={() => setActiveChat(chat)}+ >+ <div className="chat-avatar">+ {chat.isGroup ? <Users size={20} /> : <User size={20} />}+ </div>++ <div className="chat-item-info">+ <div className="chat-item-top">+ <span className="chat-item-name" title={chat.name || chat.id}>+ {chat.name || chat.id.split('@')[0]}+ </span>+ {chat.timestamp && (+ <span className="chat-item-time">{formatChatTime(chat.timestamp)}</span>+ )}+ </div>+ <div className="chat-item-bottom">+ <span className="chat-item-snippet" title={formatLastMessageSnippet(chat)}>+ {formatLastMessageSnippet(chat) || (+ <span className="no-message">{t('chats.noMessageYet')}</span>+ )}+ </span>+ {chat.unreadCount > 0 && (+ <span className="chat-unread-badge">{chat.unreadCount}</span>+ )}+ </div>+ </div>+ </div>+ );+ })+ )}+ </div>+ </aside>++ {/* RIGHT VIEW: active chat room */}+ <main className="chats-room">+ {activeChat ? (+ <div className="room-container">+ {/* Room header */}+ <header className="room-header">+ <div className="room-avatar">+ {activeChat.isGroup ? <Users size={20} /> : <User size={20} />}+ </div>+ <div className="room-contact-info">+ <h3>{activeChat.name || activeChat.id.split('@')[0]}</h3>+ <span>{activeChat.id}</span>+ </div>+ </header>++ {/* Messages body */}+ <div className="room-messages">+ {loadingMessages ? (+ <div className="messages-loading">+ <Loader2 className="animate-spin" size={32} />+ <span>{t('chats.loadingMessages')}</span>+ </div>+ ) : messages.length === 0 ? (+ <div className="messages-empty">+ <MessageSquare size={32} />+ <span>{t('chats.noMessagesInChat')}</span>+ </div>+ ) : (+ messages.map(msg => {+ const isMe = msg.direction === 'outgoing';+ const formattedTime = formatTime(+ msg.timestamp || Math.floor(new Date(msg.createdAt).getTime() / 1000),+ );++ const isMediaMessage = msg.type !== 'text';+ const mediaInfo = msg.metadata?.media;++ const renderMedia = () => {+ if (msg.type === 'revoked') return null;+ if (!mediaInfo) return null;+ const mediaSrc = getMediaSrc(mediaInfo);+ if (!mediaSrc) return null;++ switch (msg.type) {+ case 'image':+ case 'sticker':+ return (+ <div className="message-media-image">+ <img+ src={mediaSrc}+ alt={mediaInfo.filename || 'WhatsApp Image'}+ className="chat-image-media"+ />+ </div>+ );+ case 'video':+ return (+ <div className="message-media-video">+ <video src={mediaSrc} controls className="chat-video-media" />+ </div>+ );+ case 'audio':+ case 'voice':+ case 'ptt':+ return (+ <div className="message-media-audio">+ <audio src={mediaSrc} controls className="chat-audio-media" />+ </div>+ );+ case 'document':+ default:+ return (+ <div className="message-media-document">+ <a+ href={mediaSrc}+ download={mediaInfo.filename || 'document'}+ className="chat-document-media"+ >+ 📎 {mediaInfo.filename || t('chats.downloadDocument')}+ </a>+ </div>+ );+ }+ };++ const reactions = msg.metadata?.reactions || {};+ const hasReactions = Object.keys(reactions).length > 0;+ const isRevoked = msg.type === 'revoked';++ return (+ <div+ key={msg.id}+ className={`message-bubble-wrapper ${isMe ? 'outgoing' : 'incoming'}`}+ >+ <div className="message-bubble-container">+ <div+ className={`message-bubble ${isMe ? 'outgoing' : 'incoming'} ${msg.status} ${+ isMediaMessage ? 'media-type' : ''+ } ${isRevoked ? 'revoked-type' : ''}`}+ >+ {/* Quoted message display */}+ {msg.metadata?.quotedMessage && (+ <div className="message-quote-box">+ <div className="quote-body">{msg.metadata.quotedMessage.body}</div>+ </div>+ )}++ {renderMedia()}++ {isRevoked ? (+ <div className="message-text">{t('chats.messageDeleted')}</div>+ ) : (+ msg.body &&+ (!mediaInfo || msg.body !== mediaInfo.filename) && (+ <div className="message-text">{msg.body}</div>+ )+ )}++ <div className="message-meta">+ <span className="message-time">{formattedTime}</span>+ {isMe && (+ <span className={`message-status-icon ${msg.status}`}>+ {msg.status === 'pending' && '🕒'}+ {msg.status === 'sent' && '✓'}+ {msg.status === 'delivered' && '✓✓'}+ {msg.status === 'read' && '✓✓'}+ {msg.status === 'failed' && '⚠️'}+ </span>+ )}+ </div>++ {/* Reactions display */}+ {hasReactions && (+ <div className="message-reactions-badge">+ {Object.values(reactions)+ .slice(0, 3)+ .map((emoji, idx) => (+ <span key={idx} className="reaction-emoji-span">+ {emoji}+ </span>+ ))}+ {Object.keys(reactions).length > 1 && (+ <span className="reactions-count-span">+ {Object.keys(reactions).length}+ </span>+ )}+ </div>+ )}+ </div>++ {/* Message actions menu (hover) */}+ {!isRevoked && (+ <div className="message-actions-menu">+ <button+ type="button"+ className="action-btn"+ onClick={() => setReplyingTo(msg)}+ title={t('chats.actions.reply')}+ >+ <CornerUpLeft size={14} />+ </button>++ <div className="reaction-trigger-wrapper">+ <button+ type="button"+ className="action-btn reaction-btn"+ title={t('chats.actions.react')}+ >+ <Smile size={14} />+ </button>+ <div className="reaction-quick-popover">+ {['👍', '❤️', '😂', '😮', '😢', '🙏'].map(emoji => (+ <button+ key={emoji}+ type="button"+ onClick={() => handleReactMessage(msg, emoji)}+ >+ {emoji}+ </button>+ ))}+ </div>+ </div>++ {isMe && msg.status !== 'pending' && (+ <button+ type="button"+ className="action-btn delete-btn"+ onClick={() => handleDeleteMessage(msg)}+ title={t('chats.actions.delete')}+ >+ <Trash2 size={14} />+ </button>+ )}+ </div>+ )}+ </div>+ </div>+ );+ })+ )}+ <div ref={chatBottomRef} />+ </div>++ {/* Attachment preview banner */}+ {attachment && (+ <div className="attachment-preview-banner">+ {previewUrl ? (+ <img src={previewUrl} alt={attachment.filename} className="preview-thumbnail" />+ ) : (+ <div className="preview-file-icon">📎</div>+ )}+ <div className="preview-file-info">+ <span className="preview-filename">{attachment.filename}</span>+ <span className="preview-filesize">({(attachment.file.size / 1024).toFixed(1)} KB)</span>+ </div>+ <button className="btn-remove-attachment" onClick={handleRemoveAttachment}>+ <X size={18} />+ </button>+ </div>+ )}++ {/* Popular emojis panel */}+ {showEmojiPicker && (+ <div className="chats-emoji-picker">+ <div className="emoji-grid">+ {popularEmojis.map(emoji => (+ <button+ key={emoji}+ type="button"+ className="emoji-btn"+ onClick={() => handleEmojiClick(emoji)}+ >+ {emoji}+ </button>+ ))}+ </div>+ </div>+ )}++ {/* Replying preview banner */}+ {replyingTo && (+ <div className="replying-preview-banner">+ <div className="replying-preview-content">+ <div className="replying-to-title">+ {t('chats.replyingTo', {+ name:+ replyingTo.direction === 'outgoing'+ ? t('chats.you')+ : activeChat.name || activeChat.id.split('@')[0],+ })}+ </div>+ <div className="replying-to-body">+ {replyingTo.type !== 'text' ? `[${replyingTo.type}]` : replyingTo.body}+ </div>+ </div>+ <button className="btn-close-reply" onClick={() => setReplyingTo(null)}>+ <X size={18} />+ </button>+ </div>+ )}++ {/* Message input bar */}+ <footer className="room-input-footer">+ <form onSubmit={handleSend} className="input-form">+ <input type="file" ref={fileInputRef} onChange={handleFileChange} style={{ display: 'none' }} />++ <button+ type="button"+ onClick={triggerFileSelect}+ disabled={!canWrite || sending}+ className="btn-input-accessory"+ title={t('chats.attachTitle')}+ >+ <Paperclip size={20} />+ </button>++ <button+ type="button"+ onClick={() => setShowEmojiPicker(!showEmojiPicker)}+ disabled={!canWrite || sending}+ className={`btn-input-accessory ${showEmojiPicker ? 'active' : ''}`}+ title={t('chats.emojiTitle')}+ >+ <Smile size={20} />+ </button>++ <input+ type="text"+ placeholder={+ canWrite+ ? attachment+ ? t('chats.captionPlaceholder')+ : t('chats.messagePlaceholder')+ : t('chats.noPermission')+ }+ value={messageInput}+ onChange={e => setMessageInput(e.target.value)}+ disabled={!canWrite || sending}+ className="message-text-input"+ />+ <button+ type="submit"+ disabled={!canWrite || (!messageInput.trim() && !attachment) || sending}+ className="btn-send-message"+ aria-label={t('chats.send')}+ >+ {sending ? <Loader2 className="animate-spin" size={18} /> : <Send size={18} />}+ </button>+ </form>+ </footer>+ </div>+ ) : (+ <div className="chats-room-placeholder">+ <MessageSquare size={80} className="placeholder-icon" />+ <h2>{t('chats.placeholderTitle')}</h2>+ <p>{t('chats.placeholderDesc')}</p>+ </div>+ )}+ </main>+ </div>+ )}+ </div>+ );+}diff --git a/dashboard/src/pages/Dashboard.css b/dashboard/src/pages/Dashboard.cssindex 5e2e07a0a..dec903c53 100644--- a/dashboard/src/pages/Dashboard.css+++ b/dashboard/src/pages/Dashboard.css@@ -286,16 +286,77 @@gap: 1rem;}- .table-header,- .table-row {- grid-template-columns: 1fr 1fr 1fr;- font-size: 0.8125rem;+ .stat-value {+ font-size: 1.5rem;}- .table-header span:nth-child(4),- .table-header span:nth-child(5),- .table-row > *:nth-child(4),- .table-row > *:nth-child(5) {+ .sessions-section {+ padding: 1rem;+ }++ .section-header {+ flex-direction: column;+ align-items: flex-start;+ gap: 0.5rem;+ margin-bottom: 1rem;+ }++ /* Convert table to card layout on mobile */+ .sessions-table .table-header {display: none;}++ .sessions-table .table-row {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ padding: 1rem;+ border-bottom: 1px solid var(--border);+ }++ .sessions-table .table-row:last-child {+ border-bottom: none;+ }++ .session-info-cell {+ order: 1;+ }++ .session-id {+ font-size: 0.9375rem;+ font-weight: 600;+ }++ .phone {+ order: 2;+ }++ .status-pill {+ order: 3;+ }++ .last-active {+ order: 4;+ font-size: 0.75rem;+ color: var(--text-muted);+ }++ .actions {+ order: 5;+ justify-content: flex-start;+ padding-top: 0.5rem;+ border-top: 1px solid var(--border);+ }+}++@media (max-width: 480px) {+ .dashboard {+ padding: 0.75rem;+ }++ .header-title {+ flex-direction: column;+ align-items: flex-start;+ gap: 0.5rem;+ }}diff --git a/dashboard/src/pages/Infrastructure.css b/dashboard/src/pages/Infrastructure.cssindex ea079ecf4..62f9cbb05 100644--- a/dashboard/src/pages/Infrastructure.css+++ b/dashboard/src/pages/Infrastructure.css@@ -567,3 +567,57 @@justify-content: center;}}++@media (max-width: 768px) {+ .infrastructure-page {+ padding: 0.75rem;+ }++ .infra-card {+ padding: 1rem;+ }++ .form-row .form-group.small {+ max-width: none;+ }++ .form-group input,+ .form-group select {+ font-size: 0.875rem;+ padding: 0.625rem 0.875rem;+ }++ .migration-item {+ grid-template-columns: 24px 1fr;+ gap: 0.5rem;+ }++ .migration-date {+ grid-column: 2;+ }++ .migration-actions {+ flex-direction: column;+ }++ .migration-actions button {+ justify-content: center;+ }++ .stat-values {+ gap: 1rem;+ }++ .stat-item .value {+ font-size: 1rem;+ }++ .page-footer {+ justify-content: stretch;+ }++ .page-footer button {+ width: 100%;+ justify-content: center;+ }+}diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsxindex 1a36b003d..f41bad44c 100644--- a/dashboard/src/pages/Infrastructure.tsx+++ b/dashboard/src/pages/Infrastructure.tsx@@ -15,7 +15,7 @@ import {} from 'lucide-react';import { infraApi } from '../services/api';import { useDocumentTitle } from '../hooks/useDocumentTitle';-import { useInfraStatusQuery } from '../hooks/queries';+import { useInfraStatusQuery, useInfraConfigQuery } from '../hooks/queries';import { PageHeader } from '../components/PageHeader';import { useToast } from '../components/Toast';import './Infrastructure.css';@@ -89,6 +89,7 @@ export function Infrastructure() {useDocumentTitle(t('infrastructure.title'));const toast = useToast();const { data: infraStatus, isLoading: loading } = useInfraStatusQuery();+ const { data: savedConfig } = useInfraConfigQuery();const [saving, setSaving] = useState(false);const [showRestartModal, setShowRestartModal] = useState(false);const [restartCountdown, setRestartCountdown] = useState(0);@@ -186,6 +187,43 @@ export function Infrastructure() {});}, [infraStatus]);+ // Hydrate the editable form from the saved config (data/.env.generated) so the form+ // reflects what was actually persisted — including fields /status does not expose+ // (username, pool size, SSL flags, S3 details). Secrets are never returned, so their+ // inputs stay empty; an empty submit preserves the stored secret on the backend (#226).+ useEffect(() => {+ if (!savedConfig) return;+ setDbConfig(prev => ({+ ...prev,+ type: savedConfig.database.type,+ builtIn: savedConfig.database.builtIn,+ host: savedConfig.database.host || prev.host,+ port: savedConfig.database.port || prev.port,+ username: savedConfig.database.username || prev.username,+ database: savedConfig.database.database || prev.database,+ poolSize: savedConfig.database.poolSize,+ sslEnabled: savedConfig.database.sslEnabled,+ sslRejectUnauthorized: savedConfig.database.sslRejectUnauthorized,+ }));+ setRedisEnabled(savedConfig.redis.enabled);+ setRedisConfig(prev => ({+ ...prev,+ builtIn: savedConfig.redis.builtIn,+ host: savedConfig.redis.host || prev.host,+ port: savedConfig.redis.port || prev.port,+ }));+ setQueueEnabled(savedConfig.queue.enabled);+ setStorageConfig(prev => ({+ ...prev,+ type: savedConfig.storage.type,+ builtIn: savedConfig.storage.builtIn,+ localPath: savedConfig.storage.localPath || prev.localPath,+ s3Bucket: savedConfig.storage.s3Bucket || prev.s3Bucket,+ s3Region: savedConfig.storage.s3Region || prev.s3Region,+ s3Endpoint: savedConfig.storage.s3Endpoint || prev.s3Endpoint,+ }));+ }, [savedConfig]);+if (loading) {return (<divdiff --git a/dashboard/src/pages/Login.css b/dashboard/src/pages/Login.cssindex 92f31e968..08be54eb0 100644--- a/dashboard/src/pages/Login.css+++ b/dashboard/src/pages/Login.css@@ -45,6 +45,39 @@font-weight: 500;}+.login-language {+ display: flex;+ align-items: center;+ gap: 0.6rem;+ width: 100%;+ margin-bottom: 1.5rem;+ padding: 0.65rem 0.8rem;+ border: 1px solid var(--border);+ border-radius: var(--radius);+ color: var(--text-secondary);+ background: var(--bg-white);+}++.login-language svg {+ flex-shrink: 0;+}++.login-language select {+ flex: 1;+ min-width: 0;+ border: 0;+ outline: 0;+ color: var(--text-primary);+ background: transparent;+ font: inherit;+ cursor: pointer;+}++.login-language:focus-within {+ border-color: var(--primary);+ box-shadow: 0 0 0 3px rgba(37, 211, 102, 0.1);+}+.login-title {font-size: 1.75rem;font-weight: 600;@@ -61,6 +94,10 @@text-align: left;}+[dir="rtl"] .login-form {+ text-align: right;+}+.input-group {margin-bottom: 1.5rem;}@@ -189,3 +226,43 @@.login-footer a:hover {color: var(--text-secondary);}++/* Mobile Responsive */+@media (max-width: 480px) {+ .login-container {+ padding: 1rem;+ }++ .login-card {+ padding: 2rem 1.5rem;+ border-radius: 10px;+ }++ .logo-icon {+ width: 80px;+ height: 80px;+ }++ .login-title {+ font-size: 1.375rem;+ }++ .login-subtitle {+ font-size: 0.875rem;+ margin-bottom: 1.5rem;+ }++ .input-wrapper input {+ padding: 0.625rem 2.5rem 0.625rem 0.875rem;+ font-size: 0.9375rem;+ }++ .connect-btn {+ padding: 0.75rem 1.25rem;+ font-size: 0.9375rem;+ }++ .login-help {+ font-size: 0.8125rem;+ }+}diff --git a/dashboard/src/pages/Login.tsx b/dashboard/src/pages/Login.tsxindex d4ee03c58..516f48e55 100644--- a/dashboard/src/pages/Login.tsx+++ b/dashboard/src/pages/Login.tsx@@ -1,7 +1,8 @@import { useState } from 'react';import { useTranslation } from 'react-i18next';-import { Eye, EyeOff } from 'lucide-react';+import { Eye, EyeOff, Languages } from 'lucide-react';import { GithubIcon } from '../components/GithubIcon';+import { languageOptions, resolveSupportedLanguage, type SupportedLanguage } from '../i18n';import './Login.css';interface LoginProps {@@ -9,11 +10,16 @@ interface LoginProps {}export function Login({ onLogin }: LoginProps) {- const { t } = useTranslation();+ const { t, i18n } = useTranslation();const [apiKey, setApiKey] = useState('');const [showKey, setShowKey] = useState(false);const [isLoading, setIsLoading] = useState(false);const [error, setError] = useState('');+ const currentLang = resolveSupportedLanguage(i18n.resolvedLanguage || i18n.language);++ const changeLanguage = (language: SupportedLanguage) => {+ void i18n.changeLanguage(language);+ };const handleSubmit = async (e: React.FormEvent) => {e.preventDefault();@@ -58,6 +64,22 @@ export function Login({ onLogin }: LoginProps) {})}</span></div>++ <div className="login-language">+ <Languages size={18} />+ <select+ value={currentLang}+ onChange={event => changeLanguage(event.target.value as SupportedLanguage)}+ aria-label={t('common.language')}+ >+ {languageOptions.map(option => (+ <option key={option.value} value={option.value}>+ {option.label}+ </option>+ ))}+ </select>+ </div>+<form onSubmit={handleSubmit} className="login-form"><div className="input-group"><label htmlFor="apiKey">{t('login.apiKey')}</label>diff --git a/dashboard/src/pages/MessageTester.css b/dashboard/src/pages/MessageTester.cssindex 59ba00135..0b319476e 100644--- a/dashboard/src/pages/MessageTester.css+++ b/dashboard/src/pages/MessageTester.css@@ -220,3 +220,45 @@grid-template-columns: 1fr;}}++@media (max-width: 768px) {+ .message-tester {+ padding: 1rem;+ }++ .compose-panel,+ .response-panel {+ padding: 1rem;+ }++ .toggle-group {+ flex-wrap: wrap;+ border: none;+ gap: 0.5rem;+ overflow: visible;+ }++ .toggle-group button {+ min-width: 0;+ padding: 0.5rem 0.875rem;+ font-size: 0.8125rem;+ border: 1px solid var(--border) !important;+ border-radius: 6px;+ }++ .toggle-group button.active {+ border-color: var(--primary) !important;+ }++ .send-btn {+ font-size: 0.9375rem;+ padding: 0.75rem 1rem;+ }++ .form-group input,+ .form-group select,+ .form-group textarea {+ font-size: 0.875rem;+ padding: 0.625rem 0.75rem;+ }+}diff --git a/dashboard/src/pages/Plugins.css b/dashboard/src/pages/Plugins.cssindex aba31ef48..9eccc7bb4 100644--- a/dashboard/src/pages/Plugins.css+++ b/dashboard/src/pages/Plugins.css@@ -81,12 +81,6 @@font-size: 0.75rem;}-.feature-more {- padding: 0.25rem 0.5rem;- color: var(--text-muted);- font-size: 0.75rem;-}-/* Plugins Grid */.plugins-grid {display: grid;diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsxindex 7febb63f6..a595e79d3 100644--- a/dashboard/src/pages/Plugins.tsx+++ b/dashboard/src/pages/Plugins.tsx@@ -178,14 +178,11 @@ export default function Plugins() {<div className="engine-features"><p className="features-label">{t('plugins.supportedFeatures')}</p><div className="features-list">- {activeEngine.features.slice(0, 8).map(feature => (+ {activeEngine.features.map(feature => (<span key={feature} className="feature-tag">- {feature}+ {feature.replace(/-/g, ' ')}</span>))}- {activeEngine.features.length > 8 && (- <span className="feature-more">{t('plugins.more', { count: activeEngine.features.length - 8 })}</span>- )}</div></div>)}diff --git a/dashboard/src/pages/Sessions.css b/dashboard/src/pages/Sessions.cssindex cb6a57a79..0840af5d6 100644--- a/dashboard/src/pages/Sessions.css+++ b/dashboard/src/pages/Sessions.css@@ -188,6 +188,16 @@font-family: monospace;}+.info-value.error-text {+ color: var(--color-danger, #dc2626);+ font-weight: 500;+ max-width: 60%;+ text-align: right;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.card-actions {display: flex;gap: 0.5rem;@@ -239,6 +249,57 @@.sessions-grid {grid-template-columns: 1fr;}++ .sessions-page {+ padding: 1rem;+ }++ .filters-bar {+ flex-direction: column;+ gap: 0.75rem;+ }++ .search-input {+ max-width: none;+ }++ .filter-group {+ width: 100%;+ justify-content: space-between;+ }++ .filter-group select {+ flex: 1;+ }++ .header-content {+ flex-direction: column;+ align-items: stretch;+ gap: 1rem;+ }++ .sessions-page .btn-primary {+ width: 100%;+ justify-content: center;+ }++ .session-card {+ padding: 1rem;+ }++ .card-actions {+ flex-direction: column;+ }++ .card-actions .btn-action {+ justify-content: center;+ }+}++@media (max-width: 480px) {+ .sessions-page {+ padding: 0.75rem;+ }}/* Modal Overlay */diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex db2a00197..18cf4198c 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -26,7 +26,19 @@ export function Sessions() {const [selectedSession, setSelectedSession] = useState<Session | null>(null);const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);- useWebSocket({+ const fetchSessions = useCallback(async () => {+ try {+ setLoading(true);+ const data = await sessionApi.list();+ setSessions(data);+ } catch (err) {+ setError(err instanceof Error ? err.message : t('sessions.create.errorDefault'));+ } finally {+ setLoading(false);+ }+ }, [t]);++ const { isConnected, subscribe } = useWebSocket({onSessionStatus: useCallback((event: { sessionId: string; status: string }) => {setSessions(prev =>@@ -36,23 +48,23 @@ export function Sessions() {toast.success(t('sessions.toasts.readyTitle'), t('sessions.toasts.readyDesc'));} else if (event.status === 'disconnected') {toast.warning(t('sessions.toasts.disconnectedTitle'), t('sessions.toasts.disconnectedDesc'));+ } else if (event.status === 'failed') {+ // Refresh so the card picks up the lastError reason from the API.+ void fetchSessions();+ toast.error(t('sessions.toasts.failedTitle'), t('sessions.toasts.failedDesc'));}},- [toast, t],+ [toast, t, fetchSessions],),});- const fetchSessions = async () => {- try {- setLoading(true);- const data = await sessionApi.list();- setSessions(data);- } catch (err) {- setError(err instanceof Error ? err.message : t('sessions.create.errorDefault'));- } finally {- setLoading(false);+ // The gateway delivers events only to subscribed rooms; join the wildcard+ // session.status room so status changes for every session are received live.+ useEffect(() => {+ if (isConnected) {+ subscribe('*', ['session.status', 'session.qr']);}- };+ }, [isConnected, subscribe]);useEffect(() => {fetchSessions();@@ -481,6 +493,14 @@ export function Sessions() {<span className="info-label">{t('sessions.card.lastActive')}</span><span className="info-value">{formatLastActive(session.lastActive)}</span></div>+ {session.status === 'failed' && session.lastError ? (+ <div className="info-row session-error">+ <span className="info-label">{t('sessions.card.error')}</span>+ <span className="info-value error-text" title={session.lastError}>+ {session.lastError}+ </span>+ </div>+ ) : null}</div>)}diff --git a/dashboard/src/pages/Webhooks.css b/dashboard/src/pages/Webhooks.cssindex ebd341bac..f4d180af2 100644--- a/dashboard/src/pages/Webhooks.css+++ b/dashboard/src/pages/Webhooks.css@@ -2,6 +2,7 @@padding: 2rem;width: 100%;box-sizing: border-box;+ overflow-x: hidden;}.page-header {@@ -41,53 +42,106 @@gap: 1.5rem;}-.webhooks-table-container {+.webhooks-list-container {+ width: 100%;+ min-width: 0;+}++.webhooks-card-list {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.webhook-card {background: var(--bg-white);border-radius: 12px;box-shadow: var(--shadow-sm);border: 1px solid var(--border);- width: 100%;- overflow-x: auto;+ overflow: hidden;+ transition: box-shadow 0.2s;}-.webhooks-table {- display: flex;- flex-direction: column;- width: 100%;- min-width: 650px;- font-size: 0.875rem;+.webhook-card:hover {+ box-shadow: var(--shadow-md);}-/* Unified row styling - same class for header and data */-.webhooks-table .table-row {- display: grid;- grid-template-columns: 1fr 150px 140px 80px 100px;- gap: 0.75rem;- padding: 0.875rem 1.25rem;+.webhook-card-header {+ display: flex;align-items: center;+ justify-content: space-between;+ padding: 1rem 1.25rem;border-bottom: 1px solid var(--border);+ background: var(--bg-light);+ gap: 1rem;}-.webhooks-table .table-row:last-child {- border-bottom: none;+.webhook-url-row {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ flex: 1;+ min-width: 0;}-.webhooks-table .table-row.header {- background: var(--bg-light);- font-size: 0.7rem;+.webhook-url-icon {+ color: var(--primary);+ flex-shrink: 0;+}++.webhook-url {+ font-size: 0.8125rem;+ font-weight: 500;+ color: var(--text-primary);+ background: none;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ min-width: 0;+ font-family: 'JetBrains Mono', monospace;+}++.webhook-card-actions {+ display: flex;+ gap: 0.375rem;+ flex-shrink: 0;+}++.webhook-card-body {+ padding: 1rem 1.25rem;+ overflow: hidden;+}++.webhook-meta {+ display: flex;+ gap: 2rem;+ margin-bottom: 0.875rem;+}++.webhook-meta-item {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+}++.webhook-meta-label {+ font-size: 0.6875rem;font-weight: 700;- color: var(--text-secondary);text-transform: uppercase;letter-spacing: 0.05em;- border-bottom: 1px solid var(--border);+ color: var(--text-secondary);}-.webhooks-table .table-row:not(.header):hover {- background: rgba(37, 211, 102, 0.05);+.webhook-meta-value {+ font-size: 0.875rem;+ font-weight: 500;+ color: var(--text-primary);}-.webhooks-table .table-row:not(.header):nth-child(even) {- background: rgba(0, 0, 0, 0.02);+.webhook-events {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;}.empty-table-state {@@ -119,52 +173,24 @@max-width: 300px;}-.name-cell {- font-weight: 500;- color: var(--text-primary);- white-space: nowrap;-}--.url-cell {- display: flex;- align-items: center;- gap: 0.5rem;-}--.url-cell code {- font-size: 0.8125rem;- color: var(--text-secondary);- background: var(--bg-light);- padding: 0.25rem 0.5rem;- border-radius: 4px;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- flex: 1;- min-width: 0;-}--.url-cell svg {- color: var(--text-muted);- flex-shrink: 0;-}-.events-cell {display: flex;flex-wrap: wrap;- gap: 0.25rem;+ gap: 0.375rem;}.event-tag {- font-size: 0.6875rem;- padding: 0.25rem 0.5rem;- background: rgba(37, 211, 102, 0.1);+ font-size: 0.75rem;+ padding: 0.25rem 0.625rem;+ background: rgba(37, 211, 102, 0.15);color: var(--primary);- border-radius: 4px;- font-weight: 500;+ border-radius: 6px;+ font-weight: 600;white-space: nowrap;- border: none;+ border: 1px solid rgba(37, 211, 102, 0.25);cursor: default;+ font-family: 'JetBrains Mono', monospace;+ letter-spacing: -0.01em;}/* Modal event tags - clickable (webhooks only) */@@ -191,36 +217,36 @@}.status-badge {- display: inline-block;+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;padding: 0.25rem 0.75rem;border-radius: 9999px;font-size: 0.75rem;- font-weight: 500;+ font-weight: 600;white-space: nowrap;+ width: fit-content;+}++.status-badge::before {+ content: '';+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: currentColor;+ flex-shrink: 0;}.status-badge.active {- background: rgba(37, 211, 102, 0.1);+ background: rgba(37, 211, 102, 0.15);color: var(--primary);}.status-badge.inactive {- background: #f3f4f6;+ background: var(--bg-light);color: var(--text-muted);}-.last-triggered {- color: var(--text-secondary);- font-size: 0.875rem;- white-space: nowrap;-}--.actions-cell {- display: flex;- gap: 0.25rem;- justify-content: flex-end;-}-.icon-btn {padding: 0.5rem;background: transparent;@@ -253,8 +279,12 @@}.events-reference h3 {- /* Inherits from H3 */- margin-bottom: 1rem;+ font-size: 1rem;+ font-weight: 700;+ color: var(--text-primary);+ margin: 0 0 1rem 0;+ text-transform: none;+ letter-spacing: normal;}.events-list {@@ -279,8 +309,59 @@}.event-item span {- font-size: 0.75rem;+ font-size: 0.8125rem;color: var(--text-secondary);+ line-height: 1.4;+}++/* Dark mode - explicit theme */+[data-theme='dark'] .event-tag {+ color: #4ade80;+ background: rgba(37, 211, 102, 0.2);+ border-color: rgba(37, 211, 102, 0.35);+}++[data-theme='dark'] .status-badge.active {+ color: #4ade80;+ background: rgba(37, 211, 102, 0.2);+}++[data-theme='dark'] .webhook-url {+ color: #e2e8f0;+}++[data-theme='dark'] .webhook-meta-label {+ color: #94a3b8;+}++[data-theme='dark'] .webhook-meta-value {+ color: #e2e8f0;+}++/* Dark mode - system preference */+@media (prefers-color-scheme: dark) {+ :root:not([data-theme='light']) .event-tag {+ color: #4ade80;+ background: rgba(37, 211, 102, 0.2);+ border-color: rgba(37, 211, 102, 0.35);+ }++ :root:not([data-theme='light']) .status-badge.active {+ color: #4ade80;+ background: rgba(37, 211, 102, 0.2);+ }++ :root:not([data-theme='light']) .webhook-url {+ color: #e2e8f0;+ }++ :root:not([data-theme='light']) .webhook-meta-label {+ color: #94a3b8;+ }++ :root:not([data-theme='light']) .webhook-meta-value {+ color: #e2e8f0;+ }}/* Responsive */@@ -294,6 +375,65 @@}}+@media (max-width: 768px) {+ .webhooks-page {+ padding: 1rem;+ }++ .webhooks-content {+ grid-template-columns: 1fr;+ }++ .webhook-card {+ overflow: hidden;+ }++ .webhook-card-header {+ flex-direction: column;+ align-items: flex-start;+ gap: 0.75rem;+ padding: 0.875rem 1rem;+ }++ .webhook-url-row {+ width: 100%;+ min-width: 0;+ }++ .webhook-url {+ font-size: 0.75rem;+ }++ .webhook-card-actions {+ width: 100%;+ justify-content: flex-end;+ }++ .webhook-card-body {+ padding: 0.875rem 1rem;+ }++ .webhook-meta {+ flex-direction: column;+ gap: 0.75rem;+ }++ .webhook-meta-value {+ font-size: 0.8125rem;+ word-break: break-all;+ }++ .events-cell {+ flex-wrap: wrap;+ gap: 0.375rem;+ }++ .event-tag {+ font-size: 0.6875rem;+ padding: 0.2rem 0.5rem;+ }+}+/* Toast Notification */.toast {position: fixed;diff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsxindex ce0c64773..877c76dd8 100644--- a/dashboard/src/pages/Webhooks.tsx+++ b/dashboard/src/pages/Webhooks.tsx@@ -360,71 +360,78 @@ export function Webhooks() {)}<div className="webhooks-content">- <div className="webhooks-table-container">- <div className="webhooks-table">- <div className="table-row header">- <span>{t('webhooks.columns.url')}</span>- <span>{t('webhooks.columns.events')}</span>- <span>{t('webhooks.columns.session')}</span>- <span>{t('webhooks.columns.status')}</span>- <span>{t('webhooks.columns.actions')}</span>+ <div className="webhooks-list-container">+ {webhooks.length === 0 ? (+ <div className="empty-table-state">+ <WebhookIcon size={48} strokeWidth={1} />+ <h3>{t('webhooks.empty.title')}</h3>+ <p>{t('webhooks.empty.description')}</p></div>- {webhooks.length === 0 ? (- <div className="empty-table-state">- <WebhookIcon size={48} strokeWidth={1} />- <h3>{t('webhooks.empty.title')}</h3>- <p>{t('webhooks.empty.description')}</p>- </div>- ) : (- webhooks.map(webhook => (- <div key={webhook.id} className="table-row">- <span className="url-cell">- <code>{webhook.url}</code>- <ExternalLink size={14} />- </span>- <span className="events-cell">- {webhook.events.map((event: string) => (- <span key={event} className="event-tag">- {event}- </span>- ))}- </span>- <span>- {sessions.find(s => s.id === webhook.sessionId)?.name || webhook.sessionId.substring(0, 8)}- </span>- <span>- <span className={`status-badge ${webhook.active ? 'active' : 'inactive'}`}>- {webhook.active ? t('common.active') : t('common.inactive')}- </span>- </span>- <span className="actions-cell">- <button- className="icon-btn"- title={t('webhooks.actions.test')}- onClick={() => handleTest(webhook.sessionId, webhook.id)}- disabled={testingId === webhook.id}- >- {testingId === webhook.id ? <Loader2 size={16} className="animate-spin" /> : <Play size={16} />}- </button>- {canWrite && (- <>- <button className="icon-btn" title={t('webhooks.actions.edit')} onClick={() => openEdit(webhook)}>- <Edit size={16} />- </button>+ ) : (+ <div className="webhooks-card-list">+ {webhooks.map(webhook => {+ const sessionName = sessions.find(s => s.id === webhook.sessionId)?.name || webhook.sessionId.substring(0, 12);+ return (+ <div key={webhook.id} className="webhook-card">+ <div className="webhook-card-header">+ <div className="webhook-url-row">+ <ExternalLink size={16} className="webhook-url-icon" />+ <code className="webhook-url">{webhook.url}</code>+ </div>+ <div className="webhook-card-actions"><button- className="icon-btn danger"- title={t('webhooks.actions.delete')}- onClick={() => confirmDelete(webhook.sessionId, webhook.id, webhook.url)}+ className="icon-btn"+ title={t('webhooks.actions.test')}+ onClick={() => handleTest(webhook.sessionId, webhook.id)}+ disabled={testingId === webhook.id}>- <Trash2 size={16} />+ {testingId === webhook.id ? <Loader2 size={16} className="animate-spin" /> : <Play size={16} />}</button>- </>- )}- </span>- </div>- ))- )}- </div>+ {canWrite && (+ <>+ <button className="icon-btn" title={t('webhooks.actions.edit')} onClick={() => openEdit(webhook)}>+ <Edit size={16} />+ </button>+ <button+ className="icon-btn danger"+ title={t('webhooks.actions.delete')}+ onClick={() => confirmDelete(webhook.sessionId, webhook.id, webhook.url)}+ >+ <Trash2 size={16} />+ </button>+ </>+ )}+ </div>+ </div>+ <div className="webhook-card-body">+ <div className="webhook-meta">+ <div className="webhook-meta-item">+ <span className="webhook-meta-label">{t('webhooks.columns.session')}</span>+ <span className="webhook-meta-value">{sessionName}</span>+ </div>+ <div className="webhook-meta-item">+ <span className="webhook-meta-label">{t('webhooks.columns.status')}</span>+ <span className={`status-badge ${webhook.active ? 'active' : 'inactive'}`}>+ {webhook.active ? t('common.active') : t('common.inactive')}+ </span>+ </div>+ </div>+ <div className="webhook-events">+ <span className="webhook-meta-label">{t('webhooks.columns.events')}</span>+ <div className="events-cell">+ {webhook.events.map((event: string) => (+ <span key={event} className="event-tag">+ {event}+ </span>+ ))}+ </div>+ </div>+ </div>+ </div>+ );+ })}+ </div>+ )}</div><div className="events-reference">diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 87b37d7b8..19179f26e 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -16,6 +16,8 @@ export interface Session {lastActive?: string;createdAt: string;updatedAt: string;+ /** Human-readable reason for the most recent terminal engine failure (set only when status is 'failed'). */+ lastError?: string | null;}export interface SessionStats {@@ -42,7 +44,7 @@ export interface ApiKey {id: string;name: string;keyPrefix: string;- role: 'admin' | 'user' | 'readonly';+ role: 'admin' | 'operator' | 'viewer';allowedIps?: string[];allowedSessions?: string[];isActive: boolean;@@ -74,6 +76,43 @@ export interface MessageResponse {timestamp: number;}+// Chat summary returned by GET /sessions/:id/chats (mirrors the backend ChatSummary).+export interface Chat {+ id: string;+ name: string;+ isGroup: boolean;+ unreadCount: number;+ timestamp: number;+ lastMessage?: string;+}++export interface ChatMessage {+ id: string;+ waMessageId?: string;+ chatId: string;+ from: string;+ to: string;+ body: string;+ type: string;+ direction: 'incoming' | 'outgoing';+ status: 'pending' | 'sent' | 'delivered' | 'read' | 'failed';+ timestamp?: number;+ createdAt: string;+ metadata?: {+ media?: { mimetype: string; filename?: string; data?: string };+ quotedMessage?: { id: string; body: string };+ reactions?: Record<string, string>;+ };+}++export interface SendMediaPayload {+ base64?: string;+ url?: string;+ mimetype?: string;+ filename?: string;+ caption?: string;+}+export interface HealthStatus {status: 'ok' | 'error';timestamp?: string;@@ -96,6 +135,35 @@ export interface InfraStatus {engine: { type: string; headless: boolean };}+// Saved infrastructure config (from data/.env.generated) used to hydrate the form.+// Secrets are never returned — `*Set` flags indicate whether a value is stored.+export interface SavedConfig {+ database: {+ type: 'sqlite' | 'postgres';+ builtIn: boolean;+ host: string;+ port: string;+ username: string;+ database: string;+ poolSize: number;+ sslEnabled: boolean;+ sslRejectUnauthorized: boolean;+ passwordSet: boolean;+ };+ redis: { enabled: boolean; builtIn: boolean; host: string; port: string; passwordSet: boolean };+ queue: { enabled: boolean };+ storage: {+ type: 'local' | 's3';+ builtIn: boolean;+ localPath: string;+ s3Bucket: string;+ s3Region: string;+ s3Endpoint: string;+ s3CredentialsSet: boolean;+ };+ engine: { headless: boolean; sessionDataPath: string; browserArgs: string };+}+export interface SaveConfigPayload {database?: {type: 'sqlite' | 'postgres';@@ -189,7 +257,18 @@ export const sessionApi = {stop: (id: string) => request<Session>(`/sessions/${id}/stop`, { method: 'POST' }),getQR: (id: string) => request<{ qrCode: string; status: string }>(`/sessions/${id}/qr`),getStats: () => request<SessionStats>('/sessions/stats/overview'),- getGroups: (id: string) => request<{ id: string; name: string }[]>(`/sessions/${id}/groups`),+ getGroups: (id: string) =>+ request<{ id: string; name: string; linkedParentJID?: string | null }[]>(`/sessions/${id}/groups`),+ getChats: (id: string) => request<Chat[]>(`/sessions/${id}/chats`),+ markChatRead: (id: string, chatId: string) =>+ request<{ success: boolean }>(`/sessions/${id}/chats/read`, {+ method: 'POST',+ body: JSON.stringify({ chatId }),+ }),+ getChatMessages: (id: string, chatId: string, limit = 100) =>+ request<{ messages: ChatMessage[]; total: number }>(+ `/sessions/${id}/messages?chatId=${encodeURIComponent(chatId)}&limit=${limit}`,+ ),};// =============================================================================@@ -291,6 +370,31 @@ export const messageApi = {method: 'POST',body: JSON.stringify({ chatId, url, filename }),}),+ sendMedia: (+ sessionId: string,+ chatId: string,+ mediaType: 'image' | 'video' | 'audio' | 'document',+ payload: SendMediaPayload,+ ) =>+ request<MessageResponse>(`/sessions/${sessionId}/messages/send-${mediaType}`, {+ method: 'POST',+ body: JSON.stringify({ chatId, ...payload }),+ }),+ reply: (sessionId: string, data: { chatId: string; quotedMessageId: string; text: string }) =>+ request<MessageResponse>(`/sessions/${sessionId}/messages/reply`, {+ method: 'POST',+ body: JSON.stringify(data),+ }),+ react: (sessionId: string, data: { chatId: string; messageId: string; emoji: string }) =>+ request<void>(`/sessions/${sessionId}/messages/react`, {+ method: 'POST',+ body: JSON.stringify(data),+ }),+ delete: (sessionId: string, data: { chatId: string; messageId: string; forEveryone?: boolean }) =>+ request<void>(`/sessions/${sessionId}/messages/delete`, {+ method: 'POST',+ body: JSON.stringify(data),+ }),};// =============================================================================@@ -304,6 +408,7 @@ export const healthApi = {export const infraApi = {getStatus: () => request<InfraStatus>('/infra/status'),+ getConfig: () => request<SavedConfig>('/infra/config'),updateConfig: (config: Partial<InfraStatus>) =>request<InfraStatus>('/infra/config', {method: 'PUT',diff --git a/dashboard/vite.config.ts b/dashboard/vite.config.tsindex c09245ede..e230d1e66 100644--- a/dashboard/vite.config.ts+++ b/dashboard/vite.config.ts@@ -27,6 +27,13 @@ export default defineConfig({changeOrigin: true,secure: false,},+ // Proxy the WebSocket (socket.io) transport so the dashboard's real-time+ // chats/sessions streams work against the dev backend.+ '/socket.io': {+ target: 'http://localhost:2785',+ ws: true,+ changeOrigin: true,+ },},},});diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex c258bad8c..a59cb4827 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -29,13 +29,7 @@ services:- ./data:/app/datarestart: unless-stoppedhealthcheck:- test:- [- 'CMD',- 'node',- '-e',- "require('http').get('http://localhost:2785/api/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1))",- ]+ test: ['CMD', 'curl', '-f', 'http://localhost:2785/api/health']interval: 30stimeout: 10sretries: 3diff --git a/docker-compose.yml b/docker-compose.ymlindex 229ea4f43..ca401305f 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -2,6 +2,26 @@# Smart Orchestration with Profilesservices:+ # ===== CORE: Docker Socket Proxy (sole container with /var/run/docker.sock access) =====+ docker-proxy:+ image: tecnativa/docker-socket-proxy+ container_name: openwa-docker-proxy+ restart: unless-stopped+ volumes:+ - /var/run/docker.sock:/var/run/docker.sock:ro+ environment:+ CONTAINERS: 1+ IMAGES: 1+ VOLUMES: 1+ INFO: 1+ PING: 1+ POST: 1+ DELETE: 1+ # Everything else is denied by default (AUTH, SECRETS, NETWORKS, PLUGINS, SWARM, TASKS, SERVICES, CONFIGS, NODES, DISTRIBUTIONS)+ labels:+ - 'com.openwa.service=docker-proxy'+ - 'com.openwa.core=true'+# ===== CORE: Traefik Reverse Proxy =====traefik:image: traefik:v3.0@@ -70,11 +90,14 @@ services:- PLUGINS_DIR=/app/data/plugins# Security- API_MASTER_KEY=${API_MASTER_KEY:-}+ # Docker socket proxy (openwa-api never touches /var/run/docker.sock directly)+ - DOCKER_HOST=tcp://docker-proxy:2375volumes:- openwa-data:/app/data- - /var/run/docker.sock:/var/run/docker.sock:ro- ./docker-compose.yml:/app/docker-compose.yml:rodepends_on:+ docker-proxy:+ condition: service_startedpostgres:condition: service_healthyrequired: falsediff --git a/docker-entrypoint.sh b/docker-entrypoint.shnew file mode 100644index 000000000..a318d12ce--- /dev/null+++ b/docker-entrypoint.sh@@ -0,0 +1,12 @@+#!/bin/sh+# Runs as root (via dumb-init). Fixes named-volume ownership then drops to the+# openwa user via gosu so the Node process never holds root privileges.+set -e++mkdir -p /app/data/sessions /app/data/media /app/data/plugins+chown -R openwa:openwa /app/data++# "$@" = CMD from Dockerfile (default: node dist/main).+# gosu performs exec, so the node process replaces this shell and becomes the+# direct child of dumb-init (PID 1), which can therefore forward SIGTERM cleanly.+exec gosu openwa "$@"diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex ae153fd94..a654b756d 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -33,8 +33,9 @@ startup logs and written to:- `data/.api-key` for local development- `/app/data/.api-key` inside the API container for Docker deployments-Local development uses `dev-admin-key` when no keys exist; production creates a-random `owa_k1_...` admin key. Use that admin key to create scoped keys for+By default a random `owa_k1_...` admin key is generated on first run in all+environments; set `ALLOW_DEV_API_KEY=true` to seed the well-known `dev-admin-key`+for local development only. Use that admin key to create scoped keys forintegrations. The full generated key is returned only once in the `apiKey`field of the create response.@@ -937,7 +938,157 @@ GET /api/sessions/:sessionId/chats/:chatId/messages----### 6.4.3 Contacts+#### Send Template Message++Render a stored text template and send it as a regular text message. The+template body (and optional header/footer) is rendered server-side by+substituting `{{placeholder}}` tokens with the supplied `vars`. Rendering+reuses the standard `send-text` path, so plugin hooks, message persistence, and+delivery-status tracking behave identically to a direct text send.++> **Scope (issue #69):** Only **Option B** — server-side text templates with+> variable substitution — is supported. Interactive templates (buttons, list+> messages, WhatsApp Business HSM / approved message templates) are **Option A**+> and are **not supported** on the whatsapp-web.js engine.++```http+POST /api/sessions/:sessionId/messages/send-template+```++**Request Body:**+```json+{+ "chatId": "[email protected]",+ "templateName": "order-confirmation",+ "vars": {+ "customer": "Alice",+ "orderId": "1234"+ }+}+```++**Request Fields:**++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `chatId` | string | Yes | Recipient chat ID |+| `templateId` | string | Conditional | Template UUID. Provide either `templateId` or `templateName`. |+| `templateName` | string | Conditional | Template name within the session. Provide either `templateId` or `templateName`. |+| `vars` | object | No | Map of `{{placeholder}}` keys to substitution values. Unknown placeholders are left literal. |++**Response (201 Created):**+```json+{+ "success": true,+ "data": {+ "messageId": "[email protected]_3EB0ABC123",+ "timestamp": "2025-02-02T10:00:00.000Z"+ }+}+```++Returns `404 Not Found` when the session or the referenced template does not+exist, and `400 Bad Request` when the session is not active.++---++### 6.4.3 Templates++Server-side text message templates (issue #69, Option B). Templates are scoped+to a session and rendered with `{{placeholder}}` substitution by the+[Send Template Message](#send-template-message) endpoint. All endpoints require+an API key with at least the `operator` role.++> Interactive button / list / HSM templates (**Option A**) are out of scope on+> the whatsapp-web.js engine and are not provided.++#### Create Template++```http+POST /api/sessions/:sessionId/templates+```++**Request Body:**+```json+{+ "name": "order-confirmation",+ "body": "Hi {{customer}}, your order {{orderId}} has shipped.",+ "header": "OpenWA Store",+ "footer": "Reply STOP to unsubscribe."+}+```++**Request Fields:**++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `name` | string | Yes | Template name (max 100 chars), unique per session by convention |+| `body` | string | Yes | Template body with `{{placeholder}}` tokens (max 4096 chars) |+| `header` | string | No | Optional header, prepended to the rendered body |+| `footer` | string | No | Optional footer, appended to the rendered body |++When rendered, the header, body, and footer are joined with blank lines.++**Response (201 Created):**+```json+{+ "success": true,+ "data": {+ "id": "b1c2d3e4-f5a6-7890-bcde-f01234567890",+ "sessionId": "sess_abc123",+ "name": "order-confirmation",+ "body": "Hi {{customer}}, your order {{orderId}} has shipped.",+ "header": "OpenWA Store",+ "footer": "Reply STOP to unsubscribe.",+ "createdAt": "2025-02-02T10:00:00.000Z",+ "updatedAt": "2025-02-02T10:00:00.000Z"+ }+}+```++---++#### List Templates++```http+GET /api/sessions/:sessionId/templates+```++Returns all templates for the session, newest first.++---++#### Get Template++```http+GET /api/sessions/:sessionId/templates/:id+```++Returns `404 Not Found` when the template does not exist in the session.++---++#### Update Template++```http+PUT /api/sessions/:sessionId/templates/:id+```++**Request Body:** any subset of `name`, `body`, `header`, `footer`.++---++#### Delete Template++```http+DELETE /api/sessions/:sessionId/templates/:id+```++**Response:** `204 No Content`.++---++### 6.4.4 Contacts#### Get All Contacts@@ -1000,7 +1151,7 @@ GET /api/sessions/:sessionId/contacts/:contactId/profile-picture----### 6.4.4 Groups+### 6.4.5 Groups#### Get All Groups@@ -1074,7 +1225,7 @@ POST /api/sessions/:sessionId/groups----### 6.4.5 Webhooks+### 6.4.6 Webhooks#### Register Webhook@@ -1131,7 +1282,7 @@ DELETE /api/sessions/:sessionId/webhooks/:webhookId----### 6.4.6 Health+### 6.4.7 Health#### Basic Health Checkdiff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 400e8f722..8394375ef 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -1010,8 +1010,9 @@ curl -X POST \All API key management endpoints require an admin API key in `X-API-Key`.OpenWA creates the initial admin key on first run, prints it in the startuplogs, and writes it to `data/.api-key` (or `/app/data/.api-key` inside the API-container). Local development uses `dev-admin-key` when no keys exist;-production creates a random `owa_k1_...` admin key.+container). By default a random `owa_k1_...` admin key is generated on first run+in all environments; set `ALLOW_DEV_API_KEY=true` to seed the well-known+`dev-admin-key` for local development only.### GET /api/auth/api-keysdiff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 16d5caaa5..e98801087 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -49,7 +49,85 @@ flowchart TDA3 -->|No| A3a[Check message format]```-## 12.2 Connection Issues+## 12.2 Podman Compatibility++### Issue: `FileNotFoundError` / Docker socket missing++**Symptoms:**++```text+docker.errors.DockerException: Error while fetching server API version:+ ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))+```++**Cause:** The system uses Podman (not Docker Engine). Podman's rootless socket is inactive by default.++**Fix:**++```bash+systemctl --user start podman.socket+systemctl --user enable podman.socket+export DOCKER_HOST=unix:///run/user/$(id -u)/podman/podman.sock+```++Add the `export` to `~/.bashrc` to make it permanent.++---++### Issue: `short-name did not resolve to an alias`++**Symptoms:**++```text+Error: creating build container: short-name "nginx:alpine" did not resolve to an alias+and no unqualified-search registries are defined+```++**Cause:** Podman rootless mode does not fall back to Docker Hub for unqualified image names.++**Fix:** All `FROM` directives in `Dockerfile` and `dashboard/Dockerfile` must use fully-qualified names:++```dockerfile+FROM docker.io/node:22-slim+FROM docker.io/nginx:alpine+```++---++### Issue: Healthcheck always `unhealthy` on Node 22 + Podman++**Symptoms:** Container starts successfully but stays `unhealthy`; logs show:++```text+SyntaxError: Unexpected end of input+at evalTypeScript (node:internal/process/execution:256:22)+```++**Cause:** Node 22 routes `node -e` through its TypeScript evaluator which rejects arrow-function+syntax. Podman also splits quoted shell commands on whitespace, truncating the `-e` argument.++**Fix:** Use `curl` for the healthcheck instead of `node -e`:++```dockerfile+HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \+ CMD curl -f http://localhost:2785/api/health || exit 1+```++```yaml+# docker-compose.dev.yml+healthcheck:+ test: ['CMD', 'curl', '-f', 'http://localhost:2785/api/health']+```++Ensure `curl` is installed in the production stage:++```dockerfile+RUN apt-get install -y ... curl ...+```++---++## 12.3 Connection Issues### Issue: Container Won't Startdiff --git a/docs/README.md b/docs/README.mdindex 6c43a450e..885246361 100644--- a/docs/README.md+++ b/docs/README.md@@ -16,7 +16,7 @@</p><p align="center">- <img src="https://img.shields.io/badge/version-0.1.8-blue.svg" alt="Version"/>+ <img src="https://img.shields.io/badge/version-0.2.0-blue.svg" alt="Version"/><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License"/><img src="https://img.shields.io/badge/node-22_LTS-brightgreen.svg" alt="Node"/><img src="https://img.shields.io/badge/NestJS-11.x-red.svg" alt="NestJS"/>@@ -108,9 +108,10 @@ OpenWA seeds a default API key on first run and writes it to:- `data/.api-key` (development)- `/app/data/.api-key` inside the API container when using Docker-The startup logs also print the initial key. Local development uses-`dev-admin-key` when no keys exist; production creates a random `owa_k1_...`-admin key. Use an admin key to create additional keys with+The startup logs also print the initial key. By default a cryptographically+random `owa_k1_...` admin key is generated on first run in all environments; set+`ALLOW_DEV_API_KEY=true` to seed the well-known `dev-admin-key` for local+development only. Use an admin key to create additional keys with`POST /api/auth/api-keys` (see[API Specification](./06-api-specification.md#api-key-management)).diff --git a/package-lock.json b/package-lock.jsonindex 9b1d70d16..603f69ab4 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "openwa",- "version": "0.1.6",+ "version": "0.2.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "openwa",- "version": "0.1.6",+ "version": "0.2.0","hasInstallScript": true,"license": "MIT","dependencies": {@@ -40,7 +40,7 @@"tar-stream": "^3.2.0","typeorm": "^0.3.29","uuid": "^14.0.0",- "whatsapp-web.js": "^1.26.1-alpha.3"+ "whatsapp-web.js": "^1.34.7"},"devDependencies": {"@eslint/eslintrc": "^3.2.0",diff --git a/package.json b/package.jsonindex 14c8d2c67..7fcf4aec5 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "openwa",- "version": "0.1.8",+ "version": "0.2.0","description": "Open Source WhatsApp API Gateway - Free, Self-Hosted HTTP API for WhatsApp","author": "Yudhi Armyndharis & OpenWA Contributors","private": true,@@ -66,7 +66,7 @@"tar-stream": "^3.2.0","typeorm": "^0.3.29","uuid": "^14.0.0",- "whatsapp-web.js": "^1.26.1-alpha.3"+ "whatsapp-web.js": "^1.34.7"},"devDependencies": {"@eslint/eslintrc": "^3.2.0",diff --git a/scripts/smoke-test-docker-proxy.sh b/scripts/smoke-test-docker-proxy.shnew file mode 100644index 000000000..341eb50eb--- /dev/null+++ b/scripts/smoke-test-docker-proxy.sh@@ -0,0 +1,53 @@+#!/bin/sh+# Smoke test: verify openwa-api can list containers via docker-socket-proxy.+# Run this after `docker compose up -d` with the stack fully started.+# Usage: ./scripts/smoke-test-docker-proxy.sh [API_KEY]+set -e++API_KEY="${1:-}"+BASE_URL="${BASE_URL:-http://localhost:2785}"++if [ -z "$API_KEY" ]; then+ echo "Usage: $0 <admin-api-key>" >&2+ exit 1+fi++echo "==> Checking openwa-api health..."+STATUS=$(curl -sf -o /dev/null -w "%{http_code}" "$BASE_URL/api/health")+if [ "$STATUS" != "200" ]; then+ echo "FAIL: /api/health returned HTTP $STATUS (expected 200)" >&2+ exit 1+fi+echo "PASS: API health OK"++echo ""+echo "==> Verifying Docker proxy connectivity via infrastructure status..."+RESPONSE=$(curl -sf \+ -H "X-API-Key: $API_KEY" \+ "$BASE_URL/api/infra/status")++echo "Response: $RESPONSE"++# The key check: docker availability flag from DockerService.isDockerAvailable()+# If the proxy is unreachable, the service logs a warning and sets isAvailable=false.+# We indirectly validate this by confirming the API responds without error.+echo ""+echo "==> Verifying docker-proxy container is running..."+PROXY_STATE=$(docker inspect --format='{{.State.Status}}' openwa-docker-proxy 2>/dev/null || echo "not_found")+if [ "$PROXY_STATE" != "running" ]; then+ echo "FAIL: openwa-docker-proxy is not running (state: $PROXY_STATE)" >&2+ exit 1+fi+echo "PASS: openwa-docker-proxy is running"++echo ""+echo "==> Verifying openwa-api socket mount is gone..."+SOCKET_MOUNT=$(docker inspect openwa-api --format='{{range .Mounts}}{{.Source}}{{"\n"}}{{end}}' 2>/dev/null | grep "docker.sock" || true)+if [ -n "$SOCKET_MOUNT" ]; then+ echo "FAIL: openwa-api still has a docker.sock mount: $SOCKET_MOUNT" >&2+ exit 1+fi+echo "PASS: openwa-api has no direct docker.sock mount"++echo ""+echo "All smoke tests passed!"diff --git a/scripts/smoke-test-non-root.sh b/scripts/smoke-test-non-root.shnew file mode 100644index 000000000..48ef7d142--- /dev/null+++ b/scripts/smoke-test-non-root.sh@@ -0,0 +1,44 @@+#!/bin/sh+# Smoke test: verify the built image runs its process as the openwa user (not root).+# Usage: ./scripts/smoke-test-non-root.sh+# Requires Docker to be running locally.+set -e++IMAGE_TAG="openwa-test-non-root:smoke"++echo "==> Building test image..."+docker build -t "$IMAGE_TAG" .++echo ""+echo "==> Checking process user inside container..."+# Override CMD with 'id' so docker-entrypoint.sh runs: exec gosu openwa id+USER_OUTPUT=$(docker run --rm "$IMAGE_TAG" id)+echo " $USER_OUTPUT"++if echo "$USER_OUTPUT" | grep -q "uid=0(root)"; then+ echo "FAIL: process is running as root!" >&2+ docker rmi "$IMAGE_TAG" > /dev/null 2>&1 || true+ exit 1+fi++if echo "$USER_OUTPUT" | grep -q "openwa"; then+ echo "PASS: process runs as openwa (non-root)"+else+ echo "FAIL: process is not running as the openwa user" >&2+ docker rmi "$IMAGE_TAG" > /dev/null 2>&1 || true+ exit 1+fi++echo ""+echo "==> Verifying dumb-init is PID 1..."+PID1=$(docker run --rm "$IMAGE_TAG" sh -c 'cat /proc/1/comm 2>/dev/null || ps -p 1 -o comm= 2>/dev/null || echo unknown')+echo " PID 1: $PID1"+if echo "$PID1" | grep -q "dumb-init"; then+ echo "PASS: dumb-init is PID 1"+else+ echo "WARN: PID 1 is '$PID1' (expected dumb-init) — check entrypoint chain"+fi++docker rmi "$IMAGE_TAG" > /dev/null 2>&1 || true+echo ""+echo "All smoke tests passed!"diff --git a/src/app.module.ts b/src/app.module.tsindex 81810e3f3..1a625dd51 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -5,6 +5,7 @@ import { ThrottlerModule } from '@nestjs/throttler';import configuration from './config/configuration';import { SessionModule } from './modules/session/session.module';import { MessageModule } from './modules/message/message.module';+import { TemplateModule } from './modules/template/template.module';import { WebhookModule } from './modules/webhook/webhook.module';import { HealthModule } from './modules/health/health.module';import { AuthModule } from './modules/auth/auth.module';@@ -71,6 +72,7 @@ if (process.env.QUEUE_ENABLED === 'true') {__dirname + '/modules/session/**/*.entity{.ts,.js}',__dirname + '/modules/webhook/**/*.entity{.ts,.js}',__dirname + '/modules/message/**/*.entity{.ts,.js}',+ __dirname + '/modules/template/**/*.entity{.ts,.js}',],migrations: [__dirname + '/database/migrations/*{.ts,.js}'],logging: configService.get<boolean>('dataDatabase.logging', false),@@ -154,6 +156,7 @@ if (process.env.QUEUE_ENABLED === 'true') {EngineModule,SessionModule,MessageModule,+ TemplateModule,WebhookModule,HealthModule,SettingsModule,diff --git a/src/common/errors/engine-not-ready.error.ts b/src/common/errors/engine-not-ready.error.tsnew file mode 100644index 000000000..edf259dea--- /dev/null+++ b/src/common/errors/engine-not-ready.error.ts@@ -0,0 +1,17 @@+import { ConflictException } from '@nestjs/common';++/**+ * Thrown by the engine layer when an operation requires a connected, READY+ * WhatsApp client but the session is not in that state — e.g. it was just+ * disconnected from the phone, is still initializing, or is reconnecting.+ *+ * Extends NestJS `ConflictException` so it maps to **HTTP 409** through NestJS's+ * built-in exception handler — i.e. it does NOT depend on a custom global filter+ * being registered. API callers (and the dashboard) get a clear, retryable+ * "session not connected" error instead of a generic 500 Internal Server Error.+ */+export class EngineNotReadyError extends ConflictException {+ constructor(message = 'Session is not connected. The WhatsApp client is not ready.') {+ super(message);+ }+}diff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.tsnew file mode 100644index 000000000..2c2c2bb5d--- /dev/null+++ b/src/common/security/ssrf-guard.spec.ts@@ -0,0 +1,73 @@+import { isBlockedAddress, assertSafeWebhookUrl, SsrfBlockedError, isSsrfProtectionEnabled } from './ssrf-guard';++describe('isBlockedAddress', () => {+ it.each([+ ['127.0.0.1', 'IPv4 loopback'],+ ['10.1.2.3', 'RFC1918 10/8'],+ ['172.16.5.5', 'RFC1918 172.16/12'],+ ['192.168.1.1', 'RFC1918 192.168/16'],+ ['169.254.169.254', 'link-local / cloud metadata'],+ ['100.64.0.1', 'CGNAT 100.64/10'],+ ['0.0.0.0', 'unspecified'],+ ['::1', 'IPv6 loopback'],+ ['fc00::1', 'IPv6 ULA fc00::/7'],+ ['fd12:3456::1', 'IPv6 ULA fd'],+ ['fe80::1', 'IPv6 link-local'],+ ['::ffff:127.0.0.1', 'IPv4-mapped loopback (dotted)'],+ ['::ffff:7f00:1', 'IPv4-mapped loopback (hex)'],+ ['::ffff:0a00:0001', 'IPv4-mapped RFC1918 (hex, zero-padded)'],+ ['::ffff:a9fe:a9fe', 'IPv4-mapped cloud metadata 169.254.169.254 (hex)'],+ ])('blocks %s (%s)', ip => {+ expect(isBlockedAddress(ip)).toBe(true);+ });++ it.each([+ ['8.8.8.8', 'public IPv4'],+ ['1.1.1.1', 'public IPv4'],+ ['172.32.0.1', 'just outside 172.16/12'],+ ['2001:4860:4860::8888', 'public IPv6'],+ ['::ffff:0808:0808', 'IPv4-mapped public 8.8.8.8 (hex)'],+ ])('allows %s (%s)', ip => {+ expect(isBlockedAddress(ip)).toBe(false);+ });+});++describe('assertSafeWebhookUrl', () => {+ it('rejects a non-http(s) scheme', async () => {+ await expect(assertSafeWebhookUrl('ftp://example.com/hook')).rejects.toThrow(SsrfBlockedError);+ });++ it('rejects a literal loopback IPv4 host', async () => {+ await expect(assertSafeWebhookUrl('http://127.0.0.1/hook')).rejects.toThrow(SsrfBlockedError);+ });++ it('rejects the cloud metadata IP', async () => {+ await expect(assertSafeWebhookUrl('http://169.254.169.254/latest/meta-data')).rejects.toThrow(SsrfBlockedError);+ });++ it('rejects a literal IPv6 loopback host', async () => {+ await expect(assertSafeWebhookUrl('http://[::1]:8080/hook')).rejects.toThrow(SsrfBlockedError);+ });++ it('rejects a hostname that resolves to loopback (localhost)', async () => {+ await expect(assertSafeWebhookUrl('http://localhost:9999/hook')).rejects.toThrow(SsrfBlockedError);+ });++ it('allows a public literal IP', async () => {+ await expect(assertSafeWebhookUrl('https://8.8.8.8/hook')).resolves.toBeUndefined();+ });+});++describe('isSsrfProtectionEnabled', () => {+ const orig = process.env.WEBHOOK_SSRF_PROTECT;+ afterEach(() => {+ process.env.WEBHOOK_SSRF_PROTECT = orig;+ });++ it('is off by default and on only when explicitly "true"', () => {+ delete process.env.WEBHOOK_SSRF_PROTECT;+ expect(isSsrfProtectionEnabled()).toBe(false);+ process.env.WEBHOOK_SSRF_PROTECT = 'true';+ expect(isSsrfProtectionEnabled()).toBe(true);+ });+});diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.tsnew file mode 100644index 000000000..15f878c43--- /dev/null+++ b/src/common/security/ssrf-guard.ts@@ -0,0 +1,117 @@+import { isIPv4, isIPv6 } from 'net';+import { lookup } from 'dns/promises';++/** Thrown when an outbound webhook URL is blocked by the SSRF guard. */+export class SsrfBlockedError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'SsrfBlockedError';+ }+}++/** Opt-in: outbound webhook SSRF protection is only active when WEBHOOK_SSRF_PROTECT=true. */+export function isSsrfProtectionEnabled(): boolean {+ return process.env.WEBHOOK_SSRF_PROTECT === 'true';+}++function ipv4ToInt(ip: string): number {+ return ip.split('.').reduce((acc, octet) => acc * 256 + Number(octet), 0);+}++function inCidr4(ipInt: number, base: string, bits: number): boolean {+ const baseInt = ipv4ToInt(base);+ const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;+ return (ipInt & mask) >>> 0 === (baseInt & mask) >>> 0;+}++// IPv4 ranges that must never be reachable by an outbound webhook (SSRF targets).+const BLOCKED_V4: ReadonlyArray<readonly [string, number]> = [+ ['0.0.0.0', 8], // "this" network / unspecified+ ['10.0.0.0', 8], // RFC1918 private+ ['100.64.0.0', 10], // CGNAT+ ['127.0.0.0', 8], // loopback+ ['169.254.0.0', 16], // link-local (incl. 169.254.169.254 cloud metadata)+ ['172.16.0.0', 12], // RFC1918 private+ ['192.0.0.0', 24], // IETF protocol assignments+ ['192.168.0.0', 16], // RFC1918 private+ ['198.18.0.0', 15], // benchmarking+ ['224.0.0.0', 4], // multicast+ ['240.0.0.0', 4], // reserved+];++/**+ * Whether an IP literal points at an internal/reserved range that an outbound+ * webhook must not be allowed to reach (loopback, RFC1918, link-local/metadata,+ * CGNAT, multicast, IPv6 loopback/ULA/link-local, IPv4-mapped variants).+ * Anything that isn't a recognizable public IP is treated as blocked (fail-closed).+ */+export function isBlockedAddress(ip: string): boolean {+ if (isIPv4(ip)) {+ const n = ipv4ToInt(ip);+ return BLOCKED_V4.some(([base, bits]) => inCidr4(n, base, bits));+ }++ if (isIPv6(ip)) {+ const lower = ip.toLowerCase();+ if (lower === '::1' || lower === '::') return true;++ // IPv4-mapped (::ffff:a.b.c.d or ::ffff:hhhh:hhhh) — classify by the embedded IPv4, handling+ // BOTH the dotted-decimal and the hex-hextet form (the hex form bypassed a dotted-only regex).+ if (lower.startsWith('::ffff:')) {+ const tail = lower.slice('::ffff:'.length);+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(tail)) {+ return isBlockedAddress(tail);+ }+ const hextets = tail.split(':');+ if (hextets.length === 2 && hextets.every(h => /^[0-9a-f]{1,4}$/.test(h))) {+ const hi = parseInt(hextets[0], 16);+ const lo = parseInt(hextets[1], 16);+ return isBlockedAddress(`${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`);+ }+ }++ const firstHextet = lower.split(':')[0];+ if (firstHextet.startsWith('fc') || firstHextet.startsWith('fd')) return true; // ULA fc00::/7+ if (/^fe[89ab]/.test(firstHextet)) return true; // link-local fe80::/10+ return false;+ }++ // Not a valid IP literal — cannot verify, so block.+ return true;+}++/**+ * Resolves an outbound webhook URL and throws SsrfBlockedError if its scheme is not+ * http(s) or if the host (literal or any DNS-resolved address) is internal/reserved.+ */+export async function assertSafeWebhookUrl(rawUrl: string): Promise<void> {+ let url: URL;+ try {+ url = new URL(rawUrl);+ } catch {+ throw new SsrfBlockedError(`Invalid webhook URL: ${rawUrl}`);+ }++ if (url.protocol !== 'http:' && url.protocol !== 'https:') {+ throw new SsrfBlockedError(`Blocked webhook URL scheme: ${url.protocol}`);+ }++ const host = url.hostname.replace(/^\[|\]$/g, ''); // strip IPv6 brackets++ if (isIPv4(host) || isIPv6(host)) {+ if (isBlockedAddress(host)) {+ throw new SsrfBlockedError(`Blocked internal webhook address: ${host}`);+ }+ return;+ }++ const resolved = await lookup(host, { all: true });+ if (resolved.length === 0) {+ throw new SsrfBlockedError(`Could not resolve webhook host: ${host}`);+ }+ for (const { address } of resolved) {+ if (isBlockedAddress(address)) {+ throw new SsrfBlockedError(`Webhook host ${host} resolves to a blocked internal address: ${address}`);+ }+ }+}diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.tsindex fdb95d4f6..876708cca 100644--- a/src/common/storage/storage.service.ts+++ b/src/common/storage/storage.service.ts@@ -42,8 +42,11 @@ export class StorageService {if (this.storageType === 's3') {const s3Config = this.configService.get<S3Config>('storage.s3') || {};const endpoint = process.env.S3_ENDPOINT || s3Config.endpoint;- const accessKeyId = process.env.S3_ACCESS_KEY || s3Config.accessKeyId;- const secretAccessKey = process.env.S3_SECRET_KEY || s3Config.secretAccessKey;+ // Canonical names are S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY (what configuration.ts+ // and the dashboard write). The legacy S3_ACCESS_KEY / S3_SECRET_KEY are still read as+ // a fallback so existing .env files keep working.+ const accessKeyId = process.env.S3_ACCESS_KEY_ID || process.env.S3_ACCESS_KEY || s3Config.accessKeyId;+ const secretAccessKey = process.env.S3_SECRET_ACCESS_KEY || process.env.S3_SECRET_KEY || s3Config.secretAccessKey;const region = process.env.S3_REGION || s3Config.region || 'us-east-1';if (endpoint && accessKeyId && secretAccessKey) {diff --git a/src/common/utils/template-render.ts b/src/common/utils/template-render.tsnew file mode 100644index 000000000..fee7a46bc--- /dev/null+++ b/src/common/utils/template-render.ts@@ -0,0 +1,38 @@+/**+ * Shared server-side text template renderer.+ *+ * Substitutes Handlebars-style `{{name}}` placeholders with values from the+ * provided `vars` map. Placeholders whose key is absent from `vars` are left+ * untouched (the literal `{{key}}` is preserved) so that missing variables are+ * visible rather than silently blanked.+ *+ * NOTE: bulk-message.service.ts ships an independent single-brace `{name}`+ * renderer (see `applyVariables`). The two placeholder conventions+ * (`{{name}}` here vs `{name}` there) should be reconciled into this shared+ * helper in a follow-up so the gateway exposes one consistent templating+ * syntax. See issue #69.+ */++const PLACEHOLDER_PATTERN = /\{\{\s*([\w.-]+)\s*\}\}/g;++/**+ * Render a template body by replacing `{{key}}` placeholders with `vars[key]`.+ *+ * @param body Template text containing `{{key}}` placeholders.+ * @param vars Map of placeholder keys to substitution values.+ * @returns The rendered text with known placeholders substituted and unknown+ * placeholders left as literal `{{key}}`.+ */+export function renderTemplate(body: string, vars: Record<string, string> = {}): string {+ if (!body) {+ return body;+ }++ return body.replace(PLACEHOLDER_PATTERN, (match, key: string) => {+ if (Object.prototype.hasOwnProperty.call(vars, key) && vars[key] != null) {+ return String(vars[key]);+ }+ // Leave unmatched placeholders literal so missing variables stay visible.+ return match;+ });+}diff --git a/src/config/bootstrap-security.spec.ts b/src/config/bootstrap-security.spec.tsnew file mode 100644index 000000000..5890d2d98--- /dev/null+++ b/src/config/bootstrap-security.spec.ts@@ -0,0 +1,60 @@+import { resolveCorsPolicy, isSwaggerEnabled, resolveBodyLimit } from './bootstrap-security';++describe('resolveCorsPolicy', () => {+ it('defaults to wildcard in development, without credentials', () => {+ expect(resolveCorsPolicy(undefined, 'development')).toEqual({+ origins: ['*'],+ allowAnyOrigin: true,+ credentials: false,+ });+ });++ it('honors an explicit allowlist and enables credentials (no wildcard)', () => {+ expect(resolveCorsPolicy('https://a.com, https://b.com', 'production')).toEqual({+ origins: ['https://a.com', 'https://b.com'],+ allowAnyOrigin: false,+ credentials: true,+ });+ });++ it('REFUSES a wildcard origin in production (collapses to same-origin, no credentials)', () => {+ expect(resolveCorsPolicy('*', 'production')).toEqual({+ origins: [],+ allowAnyOrigin: false,+ credentials: false,+ });+ });++ it('treats the default (unset) as wildcard-blocked in production', () => {+ expect(resolveCorsPolicy(undefined, 'production')).toEqual({+ origins: [],+ allowAnyOrigin: false,+ credentials: false,+ });+ });++ it('still allows wildcard in development', () => {+ expect(resolveCorsPolicy('*', 'development').allowAnyOrigin).toBe(true);+ });+});++describe('isSwaggerEnabled', () => {+ it('is on by default (unset)', () => {+ expect(isSwaggerEnabled(undefined)).toBe(true);+ });+ it('is off only for the literal "false"', () => {+ expect(isSwaggerEnabled('false')).toBe(false);+ expect(isSwaggerEnabled('true')).toBe(true);+ expect(isSwaggerEnabled('')).toBe(true);+ });+});++describe('resolveBodyLimit', () => {+ it('defaults to a media-aware 25mb', () => {+ expect(resolveBodyLimit(undefined)).toBe('25mb');+ expect(resolveBodyLimit('')).toBe('25mb');+ });+ it('honors an explicit limit', () => {+ expect(resolveBodyLimit('5mb')).toBe('5mb');+ });+});diff --git a/src/config/bootstrap-security.ts b/src/config/bootstrap-security.tsnew file mode 100644index 000000000..d5dcbb11e--- /dev/null+++ b/src/config/bootstrap-security.ts@@ -0,0 +1,45 @@+export interface CorsPolicy {+ /** Explicit origin allowlist (empty when none / wildcard blocked). */+ origins: string[];+ /** Whether any origin is allowed (wildcard) — never true in production. */+ allowAnyOrigin: boolean;+ /** CORS credentials are only allowed with an explicit allowlist (never with a wildcard). */+ credentials: boolean;+}++/**+ * Resolves the effective CORS policy from CORS_ORIGINS + NODE_ENV.+ * - Dev: wildcard allowed (no credentials with wildcard — spec-compliant).+ * - Prod: a wildcard origin is REFUSED (collapses to same-origin only) so a+ * misconfigured deployment cannot reflect arbitrary origins with credentials.+ */+export function resolveCorsPolicy(corsOriginsEnv?: string, nodeEnv?: string): CorsPolicy {+ const origins = corsOriginsEnv+ ?.split(',')+ .map(o => o.trim())+ .filter(Boolean) ?? ['*'];+ const hasWildcard = origins.includes('*');++ // In production a wildcard origin is refused: collapse to same-origin only.+ if (hasWildcard && nodeEnv === 'production') {+ return { origins: [], allowAnyOrigin: false, credentials: false };+ }++ return {+ origins,+ allowAnyOrigin: hasWildcard,+ // Credentials are only safe with an explicit allowlist, never with a wildcard.+ credentials: !hasWildcard,+ };+}++/** Swagger UI is served unless ENABLE_SWAGGER=false (default on, backward compatible). */+export function isSwaggerEnabled(enableSwaggerEnv?: string): boolean {+ return enableSwaggerEnv !== 'false';+}++/** Request body-size cap (DoS hardening). Default is media-aware (base64 sends ride in the JSON body). */+export function resolveBodyLimit(bodySizeEnv?: string): string {+ const trimmed = bodySizeEnv?.trim();+ return trimmed ? trimmed : '25mb';+}diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex bca9ce844..09abd9525 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -51,6 +51,10 @@ export default () => ({puppeteer: {headless: process.env.PUPPETEER_HEADLESS !== 'false',args: (process.env.PUPPETEER_ARGS || '--no-sandbox,--disable-setuid-sandbox').split(','),+ // Optional path to a system Chromium/Chrome binary. When unset, whatsapp-web.js+ // uses Puppeteer's bundled Chromium. Required on hosts where the bundled binary+ // is missing or incompatible (Alpine, ARM, custom base images).+ executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || undefined,},sessionDataPath: process.env.SESSION_DATA_PATH || './data/sessions',},diff --git a/src/config/swagger.config.ts b/src/config/swagger.config.tsindex ef02c626c..0ec96bebb 100644--- a/src/config/swagger.config.ts+++ b/src/config/swagger.config.ts@@ -14,7 +14,7 @@ export function createSwaggerConfig(): Omit<OpenAPIObject, 'paths'> {new DocumentBuilder().setTitle('OpenWA API').setDescription('Open Source WhatsApp API Gateway - Free, Self-Hosted HTTP API')- .setVersion('0.1.8')+ .setVersion('0.2.0').addApiKey({ type: 'apiKey', name: 'X-API-Key', in: 'header' }, API_KEY_SECURITY_SCHEME)// Apply the scheme globally so Swagger UI sends the key with every request// (mirrors the global ApiKeyGuard). Without this, "Authorize" is cosmetic.diff --git a/src/core/hooks/hook.interfaces.ts b/src/core/hooks/hook.interfaces.tsindex 194bb7ce0..5150711a7 100644--- a/src/core/hooks/hook.interfaces.ts+++ b/src/core/hooks/hook.interfaces.ts@@ -10,6 +10,7 @@ export type HookEvent =| 'session:ready'| 'session:qr'| 'session:disconnected'+ | 'session:error'| 'session:deleted'// Message lifecycle| 'message:received'diff --git a/src/database/migrations/1779840000000-AddTemplates.ts b/src/database/migrations/1779840000000-AddTemplates.tsnew file mode 100644index 000000000..b464da3ce--- /dev/null+++ b/src/database/migrations/1779840000000-AddTemplates.ts@@ -0,0 +1,37 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Creates the `templates` table backing server-side text message templates+ * (issue #69, Option B). Each template belongs to a session via a CASCADE+ * foreign key so templates are removed when their session is deleted.+ *+ * Hand-authored because `synchronize` is disabled for the `data` connection on+ * PostgreSQL (and may be disabled on SQLite via DATABASE_SYNCHRONIZE=false).+ */+export class AddTemplates1779840000000 implements MigrationInterface {+ name = 'AddTemplates1779840000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ const isPostgres = queryRunner.connection.options.type === 'postgres';++ const exists = await queryRunner.hasTable('templates');+ if (exists) return;++ if (isPostgres) {+ await queryRunner.query(+ `CREATE TABLE "templates" ("id" varchar PRIMARY KEY NOT NULL DEFAULT gen_random_uuid()::varchar, "sessionId" varchar NOT NULL, "name" varchar(100) NOT NULL, "body" text NOT NULL, "header" text, "footer" text, "createdAt" timestamp NOT NULL DEFAULT NOW(), "updatedAt" timestamp NOT NULL DEFAULT NOW(), CONSTRAINT "FK_templates_sessionId" FOREIGN KEY ("sessionId") REFERENCES "sessions" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,+ );+ } else {+ await queryRunner.query(+ `CREATE TABLE "templates" ("id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, "name" varchar(100) NOT NULL, "body" text NOT NULL, "header" text, "footer" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_templates_sessionId" FOREIGN KEY ("sessionId") REFERENCES "sessions" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,+ );+ }++ await queryRunner.query(`CREATE INDEX "IDX_templates_sessionId" ON "templates" ("sessionId")`);+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`DROP INDEX "IDX_templates_sessionId"`);+ await queryRunner.query(`DROP TABLE "templates"`);+ }+}diff --git a/src/engine/adapters/message-mapper.spec.ts b/src/engine/adapters/message-mapper.spec.tsindex b237a76f3..4d145cd98 100644--- a/src/engine/adapters/message-mapper.spec.ts+++ b/src/engine/adapters/message-mapper.spec.ts@@ -37,4 +37,16 @@ describe('buildIncomingMessageBase', () => {expect(r.author).toBe('[email protected]');expect(r.contact).toBeUndefined();});++ it('uses `to` as the chat for an outgoing (fromMe) message, not the account JID in `from`', () => {+ const r = buildIncomingMessageBase({ ...base, fromMe: true, from: '[email protected]', to: '[email protected]' });+ expect(r.chatId).toBe('[email protected]');+ expect(r.isGroup).toBe(false);+ });++ it('flags an outgoing group send (fromMe) as a group via `to`', () => {+ const r = buildIncomingMessageBase({ ...base, fromMe: true, from: '[email protected]', to: '[email protected]' });+ expect(r.chatId).toBe('[email protected]');+ expect(r.isGroup).toBe(true);+ });});diff --git a/src/engine/adapters/message-mapper.ts b/src/engine/adapters/message-mapper.tsindex 7de7a8017..dd4fb7c21 100644--- a/src/engine/adapters/message-mapper.ts+++ b/src/engine/adapters/message-mapper.ts@@ -25,16 +25,19 @@ export interface RawMessageFields {* the adapter; this covers the fields available without an await.*/export function buildIncomingMessageBase(msg: RawMessageFields): IncomingMessage {+ // For an outgoing (fromMe) message `from` is the account's own JID and `to` is the conversation;+ // for an incoming message it's the reverse. So the chat is `to` when fromMe, else `from`.+ const chatId = msg.fromMe ? msg.to : msg.from;const incoming: IncomingMessage = {id: msg.id._serialized,from: msg.from,to: msg.to,- chatId: msg.from,+ chatId,body: msg.body,type: msg.type,timestamp: msg.timestamp,fromMe: msg.fromMe,- isGroup: msg.from.endsWith('@g.us'),+ isGroup: chatId.endsWith('@g.us'),};// In a group, `from` is the group JID, so `author` is the only way to know the real sender.diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsnew file mode 100644index 000000000..1004ea80c--- /dev/null+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -0,0 +1,54 @@+import { WhatsAppWebJsAdapter, extractLinkedParentJID } from './whatsapp-web-js.adapter';+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';++describe('extractLinkedParentJID (#201)', () => {+ it('returns null when no metadata is provided', () => {+ expect(extractLinkedParentJID()).toBeNull();+ expect(extractLinkedParentJID({})).toBeNull();+ });++ it('reads a string candidate directly', () => {+ expect(extractLinkedParentJID({ parentGroup: '[email protected]' })).toBe('[email protected]');+ });++ it('reads the _serialized field of a Wid candidate', () => {+ expect(extractLinkedParentJID({ parentGroup: { _serialized: '[email protected]' } })).toBe('[email protected]');+ });++ it('returns null when a Wid candidate has no _serialized', () => {+ expect(extractLinkedParentJID({ parentGroup: {} })).toBeNull();+ });++ it('prefers parentGroup, then linkedParentGroup, then linkedParent', () => {+ expect(+ extractLinkedParentJID({+ parentGroup: '[email protected]',+ linkedParentGroup: '[email protected]',+ linkedParent: '[email protected]',+ }),+ ).toBe('[email protected]');++ expect(extractLinkedParentJID({ linkedParentGroup: '[email protected]', linkedParent: '[email protected]' })).toBe('[email protected]');+ expect(extractLinkedParentJID({ linkedParent: '[email protected]' })).toBe('[email protected]');+ });++ it('ignores null/undefined candidates and falls through to the next', () => {+ expect(extractLinkedParentJID({ parentGroup: null, linkedParentGroup: '[email protected]' })).toBe('[email protected]');+ });+});++describe('WhatsAppWebJsAdapter readiness guard (#100)', () => {+ const newAdapter = (): WhatsAppWebJsAdapter =>+ new WhatsAppWebJsAdapter({ sessionId: 'sess-1', sessionDataPath: './data/sessions', puppeteer: {} });++ it('rejects engine read ops with EngineNotReadyError when not connected', async () => {+ const adapter = newAdapter(); // status defaults to DISCONNECTED, no client++ await expect(adapter.getGroups()).rejects.toBeInstanceOf(EngineNotReadyError);+ await expect(adapter.checkNumberExists('628123')).rejects.toBeInstanceOf(EngineNotReadyError);+ });++ it('carries HTTP 409 so NestJS returns "session not connected" (not 500) without a custom filter', () => {+ expect(new EngineNotReadyError().getStatus()).toBe(409);+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 4fa038fcf..88fd52c8a 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -26,10 +26,15 @@ import {Product,ProductQueryOptions,PaginatedProducts,+ ChatSummary,+ RevokedMessage,+ ReactionEvent,} from '../interfaces/whatsapp-engine.interface';import { createLogger } from '../../common/services/logger.service';+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import {GroupChat,+ GroupMetadataRaw,MessageWithReactions,BusinessClient,WwjsChannelData,@@ -43,6 +48,7 @@ export interface WhatsAppWebJsConfig {puppeteer?: {headless?: boolean;args?: string[];+ executablePath?: string;};// Phase 3: Proxy per sessionproxy?: {@@ -51,6 +57,26 @@ export interface WhatsAppWebJsConfig {};}+/**+ * Extracts the JID of the parent community a group is linked to, if any.+ * The field name has varied across whatsapp-web.js/WA Web versions, so+ * known candidates are checked in order.+ */+export function extractLinkedParentJID(groupMetadata?: GroupMetadataRaw): string | null {+ const candidate =+ groupMetadata?.parentGroup ?? groupMetadata?.linkedParentGroup ?? groupMetadata?.linkedParent ?? null;++ if (!candidate) {+ return null;+ }++ if (typeof candidate === 'string') {+ return candidate;+ }++ return candidate._serialized ?? null;+}+export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngine {private client: Client | null = null;private status: EngineStatus = EngineStatus.DISCONNECTED;@@ -97,6 +123,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginpuppeteer: {headless: this.config.puppeteer?.headless ?? true,args: puppeteerArgs,+ // Only override the executable when explicitly configured; otherwise let+ // whatsapp-web.js fall back to Puppeteer's bundled Chromium.+ ...(this.config.puppeteer?.executablePath ? { executablePath: this.config.puppeteer.executablePath } : {}),},});@@ -104,6 +133,8 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginawait this.client.initialize();} catch (error) {this.setStatus(EngineStatus.FAILED);+ const reason = error instanceof Error ? error.message : String(error);+ this.callbacks.onError?.(reason);throw error;}}@@ -206,18 +237,71 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}});+ this.client.on('message_create', msg => {+ // `message_create` fires for every message the account creates — including ones composed on a+ // linked phone, which the `message` event above never delivers. Incoming messages are already+ // handled there, so forward only the account's own outgoing (`fromMe`) messages; this is the+ // single source for `message.sent` (covers API sends and phone-composed self-messages alike).+ if (!msg.fromMe) {+ return;+ }++ try {+ this.callbacks.onMessageCreate?.(buildIncomingMessageBase(msg));+ } catch (error) {+ this.logger.error('Error processing outgoing message', String(error));+ }+ });+this.client.on('message_ack', (msg, ack) => {this.callbacks.onMessageAck?.(msg.id._serialized, ack);});+ this.client.on('message_revoke_everyone', after => {+ try {+ const selfWid = this.client?.info?.wid?._serialized;+ // Emit structured data only; the engine layer never produces a localized+ // display string. The dashboard renders the localized "message deleted" text.+ const payload: RevokedMessage = {+ id: after.id._serialized,+ chatId: after.from === selfWid ? after.to : after.from,+ from: after.from,+ to: after.to,+ type: 'revoked',+ body: '',+ timestamp: after.timestamp,+ };+ this.callbacks.onMessageRevoked?.(payload);+ } catch (error) {+ this.logger.error('Error processing message_revoke_everyone', String(error));+ }+ });++ this.client.on('message_reaction', reaction => {+ try {+ const event: ReactionEvent = {+ messageId: reaction.msgId._serialized,+ chatId: reaction.id.remote,+ reaction: reaction.reaction,+ senderId: reaction.senderId,+ };+ this.callbacks.onMessageReaction?.(event);+ } catch (error) {+ this.logger.error('Error processing message_reaction', String(error));+ }+ });+this.client.on('disconnected', reason => {this.setStatus(EngineStatus.DISCONNECTED);this.callbacks.onDisconnected?.(reason);});- this.client.on('auth_failure', () => {+ this.client.on('auth_failure', (message?: string) => {this.setStatus(EngineStatus.FAILED);- this.callbacks.onDisconnected?.('Authentication failed');+ // Authentication failure is terminal: the stored credentials are invalid and+ // reconnecting will not help — the operator must re-scan the QR code. Route it+ // through onError (FAILED, no reconnect) rather than onDisconnected (reconnect).+ this.callbacks.onError?.(message ? `Authentication failed: ${message}` : 'Authentication failed');});}@@ -383,6 +467,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// Filter only group chatsconst groups = chats.filter(chat => chat.isGroup);+ // List path: read linkedParentJID synchronously from whatever metadata getChats()+ // already loaded. We deliberately do NOT fall back to getChatById per group here —+ // that would be an N+1 round-trip across every group on every list call. Groups+ // whose metadata isn't loaded report null; the single-group endpoint (getGroupInfo,+ // which loads full metadata via getChatById) is the authoritative source.return groups.map(g => {const groupChat = g as unknown as GroupChat;return {@@ -392,6 +481,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginisAdmin: groupChat.participants?.some(p => p.isAdmin && p.id._serialized === this.client?.info?.wid?._serialized,),+ linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),};});}@@ -521,6 +611,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginparticipants,isReadOnly: Boolean(groupChat.isReadOnly),isAnnounce: Boolean(groupChat.isAnnounce),+ linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),};} catch (error) {this.logger.warn(`Failed to get group: ${groupId}`, String(error));@@ -792,6 +883,38 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// ========== Gap Quick Wins Implementation ==========+ async getChatHistory(chatId: string, limit: number = 50, includeMedia: boolean = false): Promise<IncomingMessage[]> {+ this.ensureReady();+ const chat = await this.client!.getChatById(chatId);+ const messages = await chat.fetchMessages({ limit });+ const results: IncomingMessage[] = [];+ for (const msg of messages) {+ // Reuse the shared mapper so history messages carry the same author/contact+ // enrichment as live incoming messages (#223). The mapper defaults chatId to+ // msg.from, which is wrong here (history includes fromMe messages whose `from`+ // is our own number), so override it to the requested chat and recompute isGroup.+ const out = buildIncomingMessageBase(msg);+ out.chatId = chatId;+ out.isGroup = chatId.endsWith('@g.us');+ if (includeMedia && msg.hasMedia) {+ try {+ const media = await msg.downloadMedia();+ if (media) {+ out.media = {+ mimetype: media.mimetype,+ filename: media.filename || undefined,+ data: media.data,+ };+ }+ } catch (error) {+ this.logger.warn(`Failed to download media for ${msg.id._serialized}: ${String(error)}`);+ }+ }+ results.push(out);+ }+ return results;+ }+// Delete Messageasync deleteMessage(chatId: string, messageId: string, forEveryone: boolean = true): Promise<void> {this.ensureReady();@@ -933,9 +1056,38 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin/* eslint-enable @typescript-eslint/require-await, @typescript-eslint/no-unused-vars */+ async getChats(): Promise<ChatSummary[]> {+ this.ensureReady();+ const chats = await this.client!.getChats();+ // Map the raw whatsapp-web.js chat objects to the library-agnostic ChatSummary+ // shape so that no library types leak past the engine boundary.+ return chats.map(chat => ({+ id: chat.id._serialized,+ name: chat.name,+ isGroup: chat.isGroup,+ unreadCount: chat.unreadCount,+ timestamp: chat.timestamp,+ lastMessage: chat.lastMessage?.body || undefined,+ }));+ }++ async sendSeen(chatId: string): Promise<boolean> {+ this.ensureReady();+ try {+ const chat = await this.client!.getChatById(chatId);+ return await chat.sendSeen();+ } catch (error) {+ this.logger.error(`Error marking chat ${chatId} as read`, String(error));+ return false;+ }+ }+private ensureReady(): void {if (this.status !== EngineStatus.READY || !this.client) {- throw new Error('WhatsApp client is not ready');+ // Typed so the global filter returns 409 Conflict ("session not connected")+ // instead of a 500 when an engine op is attempted while the session is+ // disconnected / reconnecting / still initializing (#100).+ throw new EngineNotReadyError();}}}diff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.tsnew file mode 100644index 000000000..589c6a4fd--- /dev/null+++ b/src/engine/engine.factory.spec.ts@@ -0,0 +1,53 @@+import { EngineFactory } from './engine.factory';+import { ConfigService } from '@nestjs/config';+import { PluginLoaderService, PluginType } from '../core/plugins';++describe('EngineFactory', () => {+ const buildConfigService = (overrides: Record<string, unknown> = {}): ConfigService => {+ const values: Record<string, unknown> = {+ 'engine.type': 'whatsapp-web.js',+ 'engine.sessionDataPath': '/var/data/sessions',+ 'engine.puppeteer.headless': true,+ 'engine.puppeteer.args': ['--no-sandbox'],+ 'engine.puppeteer.executablePath': '/usr/bin/chromium-browser',+ ...overrides,+ };+ return { get: jest.fn((key: string) => values[key]) } as unknown as ConfigService;+ };++ it('threads the resolved puppeteer config (executablePath/sessionDataPath) to the plugin — #219', () => {+ const createEngine = jest.fn().mockReturnValue({});+ const pluginInstance = { type: PluginType.ENGINE, createEngine };+ const pluginLoader = {+ getPlugin: jest.fn().mockReturnValue({ instance: pluginInstance }),+ } as unknown as PluginLoaderService;++ const factory = new EngineFactory(buildConfigService(), pluginLoader);+ factory.create({ sessionId: 'sess-1' });++ // Finding 2: the built-in plugin registers with an empty context config, so the+ // factory must resolve and pass these through — otherwise sessionDataPath and the+ // executable path silently fall back to relative-path defaults.+ expect(createEngine).toHaveBeenCalledWith(+ expect.objectContaining({+ sessionId: 'sess-1',+ sessionDataPath: '/var/data/sessions',+ headless: true,+ puppeteerArgs: ['--no-sandbox'],+ executablePath: '/usr/bin/chromium-browser',+ }),+ );+ });++ it('falls back to the direct adapter (with executablePath) when no engine plugin is available', () => {+ const pluginLoader = {+ getPlugin: jest.fn().mockReturnValue(undefined),+ } as unknown as PluginLoaderService;++ const factory = new EngineFactory(buildConfigService(), pluginLoader);++ // The fallback path must not throw and must produce an engine instance even when+ // the plugin registry is empty (legacy support).+ expect(() => factory.create({ sessionId: 'sess-2' })).not.toThrow();+ });+});diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.tsindex 05ce58ced..76d37769d 100644--- a/src/engine/engine.factory.ts+++ b/src/engine/engine.factory.ts@@ -69,6 +69,16 @@ export class EngineFactory implements OnModuleInit {sessionId: options.sessionId,proxyUrl: options.proxyUrl,proxyType: options.proxyType,+ // Resolve engine runtime config here (the built-in plugin registers with an+ // empty context config) so sessionDataPath / puppeteer settings honour the+ // environment instead of falling back to relative-path defaults.+ sessionDataPath: this.configService.get<string>('engine.sessionDataPath') ?? './data/sessions',+ headless: this.configService.get<boolean>('engine.puppeteer.headless') ?? true,+ puppeteerArgs: this.configService.get<string[]>('engine.puppeteer.args') ?? [+ '--no-sandbox',+ '--disable-setuid-sandbox',+ ],+ executablePath: this.configService.get<string>('engine.puppeteer.executablePath'),}) as IWhatsAppEngine;}@@ -99,6 +109,7 @@ export class EngineFactory implements OnModuleInit {puppeteer: {headless: this.configService.get<boolean>('engine.puppeteer.headless') ?? true,args: this.configService.get<string[]>('engine.puppeteer.args') ?? ['--no-sandbox', '--disable-setuid-sandbox'],+ executablePath: this.configService.get<string>('engine.puppeteer.executablePath'),},proxy: options.proxyUrl? {diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex d9c1ea8d8..7b45e47f4 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -72,6 +72,8 @@ export interface Group {name: string;participantsCount?: number;isAdmin?: boolean;+ /** JID of the parent community this group is linked to, or null if standalone. */+ linkedParentJID?: string | null;}export interface GroupParticipant {@@ -91,6 +93,8 @@ export interface GroupInfo {participants: GroupParticipant[];isReadOnly?: boolean;isAnnounce?: boolean;+ /** JID of the parent community this group is linked to, or null if standalone. */+ linkedParentJID?: string | null;}export interface ContactCard {@@ -208,13 +212,64 @@ export interface PaginatedProducts {};}+/**+ * Lightweight summary of a chat, exposed to the dashboard's real-time chats view.+ * Only library-agnostic primitives are leaked here; raw whatsapp-web.js objects are+ * mapped to this shape inside the adapter.+ */+export interface ChatSummary {+ id: string;+ name: string;+ isGroup: boolean;+ unreadCount: number;+ timestamp: number;+ lastMessage?: string;+}++/**+ * Structured payload for a remotely-revoked ("deleted for everyone") message.+ * The engine layer never emits a localized display string; `body` is intentionally+ * empty and the dashboard renders the localized "message deleted" text.+ */+export interface RevokedMessage {+ id: string;+ chatId: string;+ from: string;+ to: string;+ type: 'revoked';+ body: '';+ timestamp: number;+}++export interface ReactionEvent {+ messageId: string;+ chatId: string;+ reaction: string;+ senderId: string;+}+export interface EngineEventCallbacks {onQRCode?: (qr: string) => void;onReady?: (phone: string, pushName: string) => void;onMessage?: (message: IncomingMessage) => void;+ /**+ * Fired for messages the account itself created (outgoing) — including sends composed on a+ * linked phone, which the `message`/`onMessage` event never delivers. Used to emit `message.sent`.+ */+ onMessageCreate?: (message: IncomingMessage) => void;onMessageAck?: (messageId: string, ack: number) => void;+ onMessageRevoked?: (message: RevokedMessage) => void;+ onMessageReaction?: (event: ReactionEvent) => void;onDisconnected?: (reason: string) => void;onStateChanged?: (state: EngineStatus) => void;+ /**+ * Fired on a terminal initialization/authentication failure (e.g. Chromium+ * could not launch, or WhatsApp rejected the stored credentials). The engine+ * has already moved to FAILED; `reason` carries a human-readable cause that+ * callers may surface to operators. Distinct from `onDisconnected`, which is+ * recoverable and triggers reconnection.+ */+ onError?: (reason: string) => void;}export interface IWhatsAppEngine {@@ -273,6 +328,7 @@ export interface IWhatsAppEngine {// Message OperationsdeleteMessage(chatId: string, messageId: string, forEveryone?: boolean): Promise<void>;+ getChatHistory(chatId: string, limit?: number, includeMedia?: boolean): Promise<IncomingMessage[]>;// Contact Extended OperationsgetProfilePicture(contactId: string): Promise<string | null>;@@ -307,4 +363,8 @@ export interface IWhatsAppEngine {getProduct(productId: string): Promise<Product | null>;sendProduct(chatId: string, productId: string, body?: string): Promise<MessageResult>;sendCatalog(chatId: string, body?: string): Promise<MessageResult>;++ // Chats+ getChats(): Promise<ChatSummary[]>;+ sendSeen(chatId: string): Promise<boolean>;}diff --git a/src/engine/types/whatsapp-web-js.types.ts b/src/engine/types/whatsapp-web-js.types.tsindex 347f7dd01..0b171fa7a 100644--- a/src/engine/types/whatsapp-web-js.types.ts+++ b/src/engine/types/whatsapp-web-js.types.ts@@ -4,6 +4,25 @@*/import { Chat, Client, Message } from 'whatsapp-web.js';+/**+ * A WhatsApp ID (Wid) as serialized by whatsapp-web.js, e.g. `{ _serialized: '[email protected]' }`.+ */+export interface SerializedWid {+ _serialized?: string;+}++/**+ * Raw group metadata as returned by `chat.groupMetadata.serialize()`.+ * The field that links a community sub-group to its parent community has+ * varied across whatsapp-web.js/WA Web versions, so multiple known+ * candidates are declared here defensively.+ */+export interface GroupMetadataRaw {+ parentGroup?: SerializedWid | string | null;+ linkedParentGroup?: SerializedWid | string | null;+ linkedParent?: SerializedWid | string | null;+}+/*** WhatsApp Group Chat with group-specific properties and methods.*/@@ -19,6 +38,7 @@ export interface GroupChat extends Omit<Chat, 'isReadOnly' | 'getLabels'> {createdAt?: number;isReadOnly?: boolean;isAnnounce?: boolean;+ groupMetadata?: GroupMetadataRaw;addParticipants(ids: string[]): Promise<void>;removeParticipants(ids: string[]): Promise<void>;promoteParticipants(ids: string[]): Promise<void>;diff --git a/src/main.ts b/src/main.tsindex 2690732d8..5ef450d09 100644--- a/src/main.ts+++ b/src/main.ts@@ -5,9 +5,10 @@ import helmet from 'helmet';import { AppModule } from './app.module';import { ShutdownService } from './common/services/shutdown.service';import { createSwaggerConfig } from './config/swagger.config';+import { resolveCorsPolicy, isSwaggerEnabled, resolveBodyLimit } from './config/bootstrap-security';import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware';import { AuthService } from './modules/auth/auth.service';-import { Request, Response, NextFunction } from 'express';+import { Request, Response, NextFunction, json, urlencoded } from 'express';import * as dotenv from 'dotenv';import * as fs from 'fs';import * as path from 'path';@@ -69,7 +70,14 @@ STORAGE_PATH=./data/media}async function bootstrap() {- const app = await NestFactory.create(AppModule);+ // Disable Nest's default body parser so we can set an explicit size cap below.+ const app = await NestFactory.create(AppModule, { bodyParser: false });++ // Cap request body size (DoS hardening). Media sends carry base64 in the JSON body,+ // so the default is generous; tune with BODY_SIZE_LIMIT.+ const bodyLimit = resolveBodyLimit(process.env.BODY_SIZE_LIMIT);+ app.use(json({ limit: bodyLimit }));+ app.use(urlencoded({ extended: true, limit: bodyLimit }));// Enable shutdown hooks for graceful shutdownapp.enableShutdownHooks();@@ -107,21 +115,26 @@ async function bootstrap() {}),);- // CORS Configuration (Phase 3 Security Audit)- const allowedOrigins = process.env.CORS_ORIGINS?.split(',').map(o => o.trim()) || ['*'];+ // CORS Configuration (Phase 3 Security Audit; #221 hardening)+ const corsPolicy = resolveCorsPolicy(process.env.CORS_ORIGINS, process.env.NODE_ENV);+ if (process.env.NODE_ENV === 'production' && corsPolicy.origins.length === 0 && !corsPolicy.allowAnyOrigin) {+ console.warn(+ '[Bootstrap] No explicit CORS_ORIGINS in production (wildcard "*" is refused): cross-origin browser ' ++ 'requests will be blocked. Set CORS_ORIGINS to your dashboard origin(s).',+ );+ }app.enableCors({origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {// Allow requests with no origin (mobile apps, Postman, server-to-server)if (!origin) return callback(null, true);- // Check if wildcard or origin matches- if (allowedOrigins.includes('*') || allowedOrigins.includes(origin)) {+ if (corsPolicy.allowAnyOrigin || corsPolicy.origins.includes(origin)) {callback(null, true);} else {callback(new Error('Not allowed by CORS'));}},- credentials: true,+ credentials: corsPolicy.credentials,methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],allowedHeaders: ['Content-Type', 'X-API-Key', 'Authorization', 'X-Request-ID'],exposedHeaders: ['X-RateLimit-Limit', 'X-RateLimit-Remaining', 'X-RateLimit-Reset'],@@ -144,11 +157,12 @@ async function bootstrap() {}),);- // Swagger documentation- const config = createSwaggerConfig();-- const document = SwaggerModule.createDocument(app, config);- SwaggerModule.setup('api/docs', app, document);+ // Swagger documentation (gated by ENABLE_SWAGGER; default on)+ if (isSwaggerEnabled(process.env.ENABLE_SWAGGER)) {+ const config = createSwaggerConfig();+ const document = SwaggerModule.createDocument(app, config);+ SwaggerModule.setup('api/docs', app, document);+ }// Protect the Bull Board queue UI (/api/admin/queues). It is mounted by// @bull-board/nestjs as raw Express middleware that the global ApiKeyGuarddiff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex ca0eb82fc..be26566c6 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -3,7 +3,7 @@ import { getRepositoryToken } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { UnauthorizedException, NotFoundException } from '@nestjs/common';import { createHash } from 'crypto';-import { AuthService } from './auth.service';+import { AuthService, resolveSeedApiKey } from './auth.service';import { ApiKey, ApiKeyRole } from './entities/api-key.entity';// Helpers@@ -28,6 +28,40 @@ function createMockApiKey(overrides: Partial<ApiKey> = {}): ApiKey {};}+describe('resolveSeedApiKey (first-boot default admin key)', () => {+ const ORIGINAL_ENV = process.env;++ beforeEach(() => {+ process.env = { ...ORIGINAL_ENV };+ delete process.env.API_MASTER_KEY;+ delete process.env.ALLOW_DEV_API_KEY;+ });++ afterEach(() => {+ process.env = ORIGINAL_ENV;+ });++ it('uses API_MASTER_KEY verbatim when set', () => {+ process.env.API_MASTER_KEY = 'my-explicit-master-key';+ expect(resolveSeedApiKey()).toBe('my-explicit-master-key');+ });++ it('generates a random owa_k1_ key by default (no opt-in)', () => {+ expect(resolveSeedApiKey()).toMatch(/^owa_k1_[a-f0-9]{64}$/);+ });++ it('returns the fixed dev-admin-key only when ALLOW_DEV_API_KEY=true', () => {+ process.env.ALLOW_DEV_API_KEY = 'true';+ expect(resolveSeedApiKey()).toBe('dev-admin-key');+ });++ it('prefers API_MASTER_KEY over the dev opt-in', () => {+ process.env.API_MASTER_KEY = 'master-wins';+ process.env.ALLOW_DEV_API_KEY = 'true';+ expect(resolveSeedApiKey()).toBe('master-wins');+ });+});+describe('AuthService', () => {let service: AuthService;let repository: jest.Mocked<Partial<Repository<ApiKey>>>;diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex b138f99a9..409008621 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -10,6 +10,23 @@ import { createLogger } from '../../common/services/logger.service';const API_KEY_FILE = join(process.cwd(), 'data', '.api-key');+/**+ * Resolves the API key to seed on first boot (when no keys exist yet).+ * Precedence: an explicit `API_MASTER_KEY` always wins; otherwise a+ * cryptographically random `owa_k1_` key is generated — the secure default,+ * including in non-production. The legacy fixed `dev-admin-key` is used only when+ * a developer explicitly opts in with `ALLOW_DEV_API_KEY=true`, never by default.+ */+export function resolveSeedApiKey(): string {+ if (process.env.API_MASTER_KEY) {+ return process.env.API_MASTER_KEY;+ }+ if (process.env.ALLOW_DEV_API_KEY === 'true') {+ return 'dev-admin-key';+ }+ return `owa_k1_${randomBytes(32).toString('hex')}`;+}+@Injectable()export class AuthService implements OnModuleInit {private readonly logger = createLogger('AuthService');@@ -26,10 +43,7 @@ export class AuthService implements OnModuleInit {let isNewKey = false;if (count === 0) {- // Use env var if set, otherwise auto-generate predictable key in development, random key in production- displayKey =- process.env.API_MASTER_KEY ||- (process.env.NODE_ENV === 'production' ? `owa_k1_${randomBytes(32).toString('hex')}` : 'dev-admin-key');+ displayKey = resolveSeedApiKey();await this.seedApiKey(displayKey, 'Default Admin Key', ApiKeyRole.ADMIN);isNewKey = true;diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.tsindex 87dd1fd45..ca3103287 100644--- a/src/modules/auth/guards/api-key.guard.spec.ts+++ b/src/modules/auth/guards/api-key.guard.spec.ts@@ -1,4 +1,4 @@-import { ExecutionContext, UnauthorizedException } from '@nestjs/common';+import { ExecutionContext, UnauthorizedException, ForbiddenException } from '@nestjs/common';import { Reflector } from '@nestjs/core';import { ConfigService } from '@nestjs/config';import { ApiKeyGuard } from './api-key.guard';@@ -139,7 +139,7 @@ describe('ApiKeyGuard', () => {const context = createMockContext({ 'x-api-key': 'viewer-key' });- await expect(guard.canActivate(context)).rejects.toThrow('Insufficient permissions');+ await expect(guard.canActivate(context)).rejects.toThrow(ForbiddenException);});it('should pass session ID from route params to validateApiKey', async () => {diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.tsindex 61b6fb6f7..a53a8fcd9 100644--- a/src/modules/auth/guards/api-key.guard.ts+++ b/src/modules/auth/guards/api-key.guard.ts@@ -1,4 +1,4 @@-import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';+import { Injectable, CanActivate, ExecutionContext, UnauthorizedException, ForbiddenException } from '@nestjs/common';import { Reflector } from '@nestjs/core';import { ConfigService } from '@nestjs/config';import { Request } from 'express';@@ -44,7 +44,7 @@ export class ApiKeyGuard implements CanActivate {]);if (requiredRole && !this.authService.hasPermission(apiKey, requiredRole)) {- throw new UnauthorizedException(`Insufficient permissions. Required: ${requiredRole}`);+ throw new ForbiddenException(`Insufficient permissions. Required: ${requiredRole}`);}// Attach API key to request for use in controllersdiff --git a/src/modules/docker/docker.service.spec.ts b/src/modules/docker/docker.service.spec.tsnew file mode 100644index 000000000..126bb4ee3--- /dev/null+++ b/src/modules/docker/docker.service.spec.ts@@ -0,0 +1,44 @@+import { DockerService } from './docker.service';++// Prevent actual Docker connections on module init during tests+jest.mock('dockerode');++describe('DockerService.buildDockerOptions', () => {+ let service: DockerService;+ const originalDockerHost = process.env.DOCKER_HOST;++ beforeEach(() => {+ service = new DockerService();+ });++ afterEach(() => {+ if (originalDockerHost === undefined) {+ delete process.env.DOCKER_HOST;+ } else {+ process.env.DOCKER_HOST = originalDockerHost;+ }+ });++ it('returns TCP options when DOCKER_HOST is set to tcp://host:port', () => {+ process.env.DOCKER_HOST = 'tcp://docker-proxy:2375';+ expect(service.buildDockerOptions()).toEqual({+ host: 'docker-proxy',+ port: 2375,+ protocol: 'http',+ });+ });++ it('falls back to unix socket when DOCKER_HOST is not set', () => {+ delete process.env.DOCKER_HOST;+ expect(service.buildDockerOptions()).toEqual({+ socketPath: '/var/run/docker.sock',+ });+ });++ it('falls back to unix socket for unsupported DOCKER_HOST schemes', () => {+ process.env.DOCKER_HOST = 'unix:///run/docker.sock';+ expect(service.buildDockerOptions()).toEqual({+ socketPath: '/var/run/docker.sock',+ });+ });+});diff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.tsindex c50a32909..93cd591f1 100644--- a/src/modules/docker/docker.service.ts+++ b/src/modules/docker/docker.service.ts@@ -24,6 +24,7 @@ export class DockerService implements OnModuleInit {private readonly logger = new Logger(DockerService.name);private docker: Docker | null = null;private isAvailable = false;+ private reinitInFlight = false;async onModuleInit() {await this.initializeDocker();@@ -71,23 +72,48 @@ export class DockerService implements OnModuleInit {private async initializeDocker(): Promise<void> {try {- this.docker = new Docker({ socketPath: '/var/run/docker.sock' });+ this.docker = new Docker(this.buildDockerOptions());await this.docker.ping();this.isAvailable = true;this.logger.log('Docker API connected successfully');} catch (error) {this.logger.warn(- 'Docker socket not available. Container orchestration disabled.',+ 'Docker not available. Container orchestration disabled.',error instanceof Error ? error.message : error,);this.isAvailable = false;}}+ // Visible for testing+ buildDockerOptions(): Docker.DockerOptions {+ const dockerHost = process.env.DOCKER_HOST;+ if (dockerHost) {+ const match = /^tcp:\/\/([^:]+):(\d+)$/.exec(dockerHost);+ if (match) {+ return { host: match[1], port: parseInt(match[2], 10), protocol: 'http' };+ }+ }+ return { socketPath: '/var/run/docker.sock' };+ }+/**- * Check if Docker is available+ * Check if Docker is available.+ *+ * Startup-race recovery: when the API talks to the Docker socket-proxy over TCP+ * (DOCKER_HOST=tcp://...), the proxy container may not be accepting connections at+ * the moment onModuleInit runs (compose `service_started` doesn't wait for readiness).+ * If the first connect failed, retry it once in the background here so orchestration+ * recovers without a process restart. Only for the DOCKER_HOST (proxy/tcp) case — a+ * socket-based or docker-less deployment has no such race.*/isDockerAvailable(): boolean {+ if (!this.isAvailable && !this.reinitInFlight && process.env.DOCKER_HOST) {+ this.reinitInFlight = true;+ void this.initializeDocker().finally(() => {+ this.reinitInFlight = false;+ });+ }return this.isAvailable;}diff --git a/src/modules/events/dto/ws-messages.dto.ts b/src/modules/events/dto/ws-messages.dto.tsindex eadd94459..846757e96 100644--- a/src/modules/events/dto/ws-messages.dto.ts+++ b/src/modules/events/dto/ws-messages.dto.ts@@ -16,6 +16,7 @@ export const SUBSCRIBABLE_EVENTS = ['message.sent','message.ack','message.revoked',+ 'message.reaction','session.status','session.qr','session.authenticated',diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsnew file mode 100644index 000000000..1f355bb92--- /dev/null+++ b/src/modules/events/events.gateway.spec.ts@@ -0,0 +1,24 @@+import { isSessionSubscriptionAllowed } from './events.gateway';++describe('isSessionSubscriptionAllowed (WS session-scope enforcement)', () => {+ it('allows an unrestricted key (null allowedSessions) to subscribe to anything, including *', () => {+ expect(isSessionSubscriptionAllowed(null, '*')).toBe(true);+ expect(isSessionSubscriptionAllowed(null, 'sess-1')).toBe(true);+ });++ it('allows an unrestricted key (empty allowedSessions) to subscribe to *', () => {+ expect(isSessionSubscriptionAllowed([], '*')).toBe(true);+ });++ it('forbids a session-scoped key from subscribing to the * wildcard', () => {+ expect(isSessionSubscriptionAllowed(['sess-1'], '*')).toBe(false);+ });++ it('allows a session-scoped key to subscribe to a session in its allowlist', () => {+ expect(isSessionSubscriptionAllowed(['sess-1', 'sess-2'], 'sess-2')).toBe(true);+ });++ it('forbids a session-scoped key from subscribing to a session outside its allowlist', () => {+ expect(isSessionSubscriptionAllowed(['sess-1'], 'sess-2')).toBe(false);+ });+});diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 55425e608..555104a6d 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -23,6 +23,23 @@ import type {} from './dto/ws-messages.dto';import { SUBSCRIBABLE_EVENTS, buildRoomName } from './dto/ws-messages.dto';+/**+ * Whether an API key may subscribe to a session's WebSocket event rooms.+ * An unrestricted key (no `allowedSessions`) may subscribe to anything, including+ * the `*` wildcard. A key scoped to specific sessions may NOT subscribe to `*`+ * (which would receive every session's events) nor to a session outside its+ * allowlist — preventing cross-tenant event leakage (#221).+ */+export function isSessionSubscriptionAllowed(allowedSessions: string[] | null | undefined, sessionId: string): boolean {+ if (!allowedSessions || allowedSessions.length === 0) {+ return true;+ }+ if (sessionId === '*') {+ return false;+ }+ return allowedSessions.includes(sessionId);+}+@WebSocketGateway({cors: {origin: '*', // In production, restrict this@@ -103,6 +120,14 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatereturn this.createError('INVALID_SESSION', 'sessionId is required', requestId);}+ // Enforce per-key session scope: a key restricted to specific sessions must not+ // subscribe to '*' or to a session outside its allowlist (prevents cross-tenant+ // event leakage — #221).+ const subscriberKey = (client.data as { apiKey?: { allowedSessions?: string[] | null } }).apiKey;+ if (!isSessionSubscriptionAllowed(subscriberKey?.allowedSessions, sessionId)) {+ return this.createError('FORBIDDEN_SESSION', 'API key is not authorized for this session', requestId);+ }+// Validate eventsif (!events || !Array.isArray(events) || events.length === 0) {return this.createError('INVALID_EVENTS', 'events array is required', requestId);@@ -236,6 +261,20 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatethis.emitToRooms(sessionId, 'message.ack', data);}+ /**+ * Emit message revoked ("deleted for everyone") notification+ */+ emitMessageRevoked(sessionId: string, message: Record<string, unknown>) {+ this.emitToRooms(sessionId, 'message.revoked', message);+ }++ /**+ * Emit message reaction notification+ */+ emitMessageReaction(sessionId: string, data: Record<string, unknown>) {+ this.emitToRooms(sessionId, 'message.reaction', data);+ }+/*** Emit webhook delivery status (broadcast to all - no session context)*/diff --git a/src/modules/health/health.controller.ts b/src/modules/health/health.controller.tsindex 0fa889440..79e299475 100644--- a/src/modules/health/health.controller.ts+++ b/src/modules/health/health.controller.ts@@ -1,6 +1,7 @@import { Controller, Get } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';import { Public } from '../auth/decorators/auth.decorators';+import { SkipThrottle } from '@nestjs/throttler';interface HealthCheckResult {status: 'ok' | 'error';@@ -12,6 +13,7 @@ interface HealthCheckResult {@ApiTags('health')@Controller('health')@Public()+@SkipThrottle()export class HealthController {@Get()@ApiOperation({ summary: 'Basic health check' })diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex b9611f7e0..4dcadb330 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -7,11 +7,17 @@ import { BadRequestException } from '@nestjs/common';// under test never touches archiver, so a lightweight stub is sufficient.jest.mock('archiver', () => ({ default: jest.fn() }));-// saveConfig writes the generated env via fs.writeFileSync; mock only that call so-// the tests can assert the produced content without touching the filesystem.+// saveConfig writes the generated env via fs.writeFileSync and reads the existing file+// via fs.existsSync/readFileSync; mock those so tests assert produced content without+// touching the filesystem. existsSync defaults to false (no prior config).jest.mock('fs', () => {const actual = jest.requireActual<typeof import('fs')>('fs');- return { ...actual, writeFileSync: jest.fn() };+ return {+ ...actual,+ writeFileSync: jest.fn(),+ existsSync: jest.fn().mockReturnValue(false),+ readFileSync: jest.fn().mockReturnValue(''),+ };});import { InfraController } from './infra.controller';@@ -21,16 +27,22 @@ import { ApiKeyRole } from '../auth/entities/api-key.entity';describe('InfraController access control (Vuln 2)', () => {const reflector = new Reflector();- // Every mutating or data-exfiltration endpoint must require the ADMIN role so- // that a low-privilege (VIEWER/OPERATOR) API key cannot wipe data, read- // secrets, change config, restart, or trigger storage import.+ // Every mutating, data-exfiltration, and operational-read endpoint must require+ // the ADMIN role so that a low-privilege (VIEWER/OPERATOR) API key cannot wipe+ // data, read secrets, change config, restart, trigger storage import, or read+ // infrastructure status / engine / storage details (#221 tightened the reads).const adminOnly = [+ 'getConfig', // GET /infra/config (returns saved config; secrets omitted but still ADMIN-only)'saveConfig', // PUT /infra/config'requestRestart', // POST /infra/restart'exportData', // GET /infra/export-data (exposes webhook secrets)'importData', // POST /infra/import-data (DELETEs all rows)'exportStorage', // GET /infra/storage/export'importStorage', // POST /infra/storage/import+ 'getStatus', // GET /infra/status+ 'getEngines', // GET /infra/engines+ 'getCurrentEngine', // GET /infra/engines/current+ 'getStorageFileCount', // GET /infra/storage/files/count] as const;it.each(adminOnly)('%s requires the ADMIN role', method => {@@ -38,13 +50,6 @@ describe('InfraController access control (Vuln 2)', () => {const role = reflector.get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, handler);expect(role).toBe(ApiKeyRole.ADMIN);});-- it('leaves read-only status open to any authenticated key', () => {- // eslint-disable-next-line @typescript-eslint/unbound-method -- reading route metadata off the handler, not invoking it- const handler = InfraController.prototype.getStatus as object;- const role = reflector.get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, handler);- expect(role).toBeUndefined();- });});describe('InfraController.importStorage filePath validation (Vuln 3)', () => {@@ -107,3 +112,120 @@ describe('InfraController.saveConfig SSL reject-unauthorized', () => {expect(env).not.toContain('DATABASE_SSL_REJECT_UNAUTHORIZED');});});++describe('InfraController.saveConfig env-name correctness and merge (#226)', () => {+ const newController = () =>+ new InfraController(+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ );++ function written(config: unknown, existing?: string): string {+ (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);+ (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');+ (fs.writeFileSync as jest.Mock).mockClear();+ newController().saveConfig(config as never);+ const calls = (fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>;+ const content = calls[0][1];+ // Reset to defaults so later tests start from "no prior config".+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ return content;+ }++ it('writes the env names the backend actually reads (not the old ignored names)', () => {+ const env = written({+ engine: { headless: false, sessionDataPath: './sess', browserArgs: '--flag' },+ storage: { type: 's3', s3Bucket: 'b', s3AccessKey: 'ak', s3SecretKey: 'sk' },+ });+ // Correct names (configuration.ts reads these)+ expect(env).toContain('PUPPETEER_HEADLESS=false');+ expect(env).toContain('SESSION_DATA_PATH=./sess');+ expect(env).toContain('PUPPETEER_ARGS=--flag');+ expect(env).toContain('S3_ACCESS_KEY_ID=ak');+ expect(env).toContain('S3_SECRET_ACCESS_KEY=sk');+ // Old, silently-ignored names must be gone+ expect(env).not.toContain('ENGINE_HEADLESS=');+ expect(env).not.toContain('ENGINE_SESSION_PATH=');+ expect(env).not.toContain('ENGINE_BROWSER_ARGS=');+ expect(env).not.toContain('S3_ACCESS_KEY=');+ expect(env).not.toContain('S3_SECRET_KEY=');+ });++ it('writes STORAGE_LOCAL_PATH (the name the backend reads) for local storage', () => {+ const env = written({ storage: { type: 'local', localPath: './data/media' } });+ expect(env).toContain('STORAGE_LOCAL_PATH=./data/media');+ expect(env).not.toContain('STORAGE_PATH=');+ });++ it('preserves existing keys that are not in the current payload', () => {+ const env = written({ engine: { headless: true } }, 'WEBHOOK_TIMEOUT=5000\nSESSION_DATA_PATH=./old\n');+ expect(env).toContain('WEBHOOK_TIMEOUT=5000'); // untouched key survives+ expect(env).toContain('PUPPETEER_HEADLESS=true'); // payload applied+ });++ it('does not blank a stored secret when the form submits an empty value', () => {+ const env = written({ database: { type: 'postgres', host: 'db', password: '' } }, 'DATABASE_PASSWORD=keepme\n');+ expect(env).toContain('DATABASE_PASSWORD=keepme');+ expect(env).toContain('DATABASE_HOST=db');+ });++ it('drops stale postgres keys when switching to sqlite', () => {+ const existing = 'DATABASE_TYPE=postgres\nDATABASE_HOST=oldhost\nDATABASE_PASSWORD=secret\nDATABASE_PORT=5432\n';+ const env = written({ database: { type: 'sqlite' } }, existing);+ expect(env).toContain('DATABASE_TYPE=sqlite');+ expect(env).not.toContain('DATABASE_HOST=');+ expect(env).not.toContain('DATABASE_PASSWORD=');+ expect(env).not.toContain('DATABASE_PORT=');+ });++ it('drops stale S3 keys when switching storage to local', () => {+ const existing =+ 'STORAGE_TYPE=s3\nS3_BUCKET=old\nS3_ACCESS_KEY_ID=ak\nS3_SECRET_ACCESS_KEY=sk\nS3_ENDPOINT=http://x\n';+ const env = written({ storage: { type: 'local', localPath: './data/media' } }, existing);+ expect(env).toContain('STORAGE_TYPE=local');+ expect(env).toContain('STORAGE_LOCAL_PATH=./data/media');+ expect(env).not.toContain('S3_BUCKET=');+ expect(env).not.toContain('S3_ACCESS_KEY_ID=');+ expect(env).not.toContain('S3_SECRET_ACCESS_KEY=');+ });+});++describe('InfraController.getConfig (#226)', () => {+ it('returns the saved config shape without echoing secrets', () => {+ (fs.existsSync as jest.Mock).mockReturnValue(true);+ (fs.readFileSync as jest.Mock).mockReturnValue(+ 'DATABASE_TYPE=postgres\nDATABASE_HOST=db\nDATABASE_PASSWORD=secret\nSESSION_DATA_PATH=./sess\nSTORAGE_TYPE=s3\nS3_ACCESS_KEY_ID=ak\nS3_SECRET_ACCESS_KEY=sk\n',+ );+ const controller = new InfraController(+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ );++ const cfg = controller.getConfig();+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');++ expect(cfg.database.type).toBe('postgres');+ expect(cfg.database.host).toBe('db');+ expect(cfg.database.passwordSet).toBe(true);+ expect(cfg.engine.sessionDataPath).toBe('./sess');+ expect(cfg.storage.type).toBe('s3');+ expect(cfg.storage.s3CredentialsSet).toBe(true);+ // Secrets are never present on the returned object.+ expect(JSON.stringify(cfg)).not.toContain('secret');+ expect(JSON.stringify(cfg)).not.toContain('"ak"');+ });+});diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex b001b74b0..7838a965c 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -14,6 +14,7 @@ import { ShutdownService } from '../../common/services/shutdown.service';import { createLogger } from '../../common/services/logger.service';import * as fs from 'fs';import * as path from 'path';+import * as dotenv from 'dotenv';interface InfraStatus {database: { connected: boolean; type: string; host: string };@@ -134,6 +135,35 @@ interface MigrationTables {messageBatches: MessageBatchRow[];}+// Saved infrastructure config returned to the dashboard form for hydration. Secret+// values are never echoed back — a `*Set` boolean indicates whether one is stored.+interface SavedConfigResponse {+ database: {+ type: 'sqlite' | 'postgres';+ builtIn: boolean;+ host: string;+ port: string;+ username: string;+ database: string;+ poolSize: number;+ sslEnabled: boolean;+ sslRejectUnauthorized: boolean;+ passwordSet: boolean;+ };+ redis: { enabled: boolean; builtIn: boolean; host: string; port: string; passwordSet: boolean };+ queue: { enabled: boolean };+ storage: {+ type: 'local' | 's3';+ builtIn: boolean;+ localPath: string;+ s3Bucket: string;+ s3Region: string;+ s3Endpoint: string;+ s3CredentialsSet: boolean;+ };+ engine: { headless: boolean; sessionDataPath: string; browserArgs: string };+}+@ApiTags('infrastructure')@Controller('infra')export class InfraController {@@ -153,6 +183,7 @@ export class InfraController {) {}@Get('status')+ @RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Get infrastructure status' })@ApiResponse({ status: 200, description: 'Infrastructure status' })async getStatus(): Promise<InfraStatus> {@@ -193,6 +224,7 @@ export class InfraController {}@Get('engines')+ @RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Get available WhatsApp engines' })@ApiResponse({ status: 200, description: 'List of available engines' })getEngines(): Array<{ id: string; name: string; enabled: boolean; features: string[] }> {@@ -200,12 +232,62 @@ export class InfraController {}@Get('engines/current')+ @RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Get current active engine' })@ApiResponse({ status: 200, description: 'Current engine info' })getCurrentEngine(): { engineType: string } {return { engineType: this.engineFactory.getCurrentEngine() };}+ @Get('config')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Read the saved infrastructure configuration for the dashboard form' })+ @ApiResponse({ status: 200, description: 'Saved configuration (secrets omitted)' })+ getConfig(): SavedConfigResponse {+ const envPath = path.resolve(process.cwd(), 'data', '.env.generated');+ const saved: Record<string, string> = fs.existsSync(envPath) ? dotenv.parse(fs.readFileSync(envPath, 'utf8')) : {};++ // Secrets (passwords, S3 keys) are never returned; the form shows a "set" indicator+ // and an empty submission preserves the stored value (see saveConfig). This lets the+ // dashboard hydrate the form so a save no longer overwrites unseen fields (#226).+ return {+ database: {+ type: saved.DATABASE_TYPE === 'postgres' ? 'postgres' : 'sqlite',+ builtIn: saved.POSTGRES_BUILTIN === 'true',+ host: saved.DATABASE_HOST || '',+ port: saved.DATABASE_PORT || '',+ username: saved.DATABASE_USERNAME || '',+ database: saved.DATABASE_NAME || '',+ poolSize: Number(saved.DATABASE_POOL_SIZE) || 10,+ sslEnabled: saved.DATABASE_SSL === 'true',+ sslRejectUnauthorized: saved.DATABASE_SSL_REJECT_UNAUTHORIZED !== 'false',+ passwordSet: Boolean(saved.DATABASE_PASSWORD),+ },+ redis: {+ enabled: saved.REDIS_ENABLED === 'true',+ builtIn: saved.REDIS_BUILTIN === 'true',+ host: saved.REDIS_HOST || '',+ port: saved.REDIS_PORT || '',+ passwordSet: Boolean(saved.REDIS_PASSWORD),+ },+ queue: { enabled: saved.QUEUE_ENABLED === 'true' },+ storage: {+ type: saved.STORAGE_TYPE === 's3' ? 's3' : 'local',+ builtIn: saved.MINIO_BUILTIN === 'true',+ localPath: saved.STORAGE_LOCAL_PATH || '',+ s3Bucket: saved.S3_BUCKET || '',+ s3Region: saved.S3_REGION || '',+ s3Endpoint: saved.S3_ENDPOINT || '',+ s3CredentialsSet: Boolean(saved.S3_ACCESS_KEY_ID && saved.S3_SECRET_ACCESS_KEY),+ },+ engine: {+ headless: saved.PUPPETEER_HEADLESS !== 'false',+ sessionDataPath: saved.SESSION_DATA_PATH || '',+ browserArgs: saved.PUPPETEER_ARGS || '',+ },+ };+ }+@Put('config')@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Save infrastructure configuration to .env file' })@@ -213,119 +295,156 @@ export class InfraController {@ApiBody({ description: 'Configuration to save' })saveConfig(@Body() config: SaveConfigDto): { message: string; saved: boolean; envPath: string; profiles: string[] } {try {- // Build .env content from config- const envLines: string[] = [];const profiles: string[] = [];- // Header- envLines.push('# OpenWA Configuration');- envLines.push(`# Generated at ${new Date().toISOString()}`);- envLines.push('');+ // Merge into the existing saved config rather than rebuilding from scratch, so a+ // partial payload (the dashboard only sends the sections it renders) cannot wipe+ // keys it didn't include (#226).+ const envPath = path.resolve(process.cwd(), 'data', '.env.generated');+ const existing: Record<string, string> = fs.existsSync(envPath)+ ? dotenv.parse(fs.readFileSync(envPath, 'utf8'))+ : {};+ const updates: Record<string, string> = {};+ // Keys to remove from the merged result — used to drop stale settings when the+ // user switches mode (postgres->sqlite, s3->local) so a reload never sees the new+ // mode alongside leftover keys from the old one.+ const staleKeys = new Set<string>();++ // Secret values are never echoed back to the form, so an empty submission means+ // "unchanged" — keep whatever is already stored instead of blanking it.+ const setSecret = (key: string, value: string | undefined): void => {+ if (value) updates[key] = value;+ };- // Database+ // Database. NOTE: these keys must match what src/config/configuration.ts reads.if (config.database) {- envLines.push('# Database');- envLines.push(`DATABASE_TYPE=${config.database.type || 'sqlite'}`);- envLines.push(`POSTGRES_BUILTIN=${config.database.builtIn ? 'true' : 'false'}`);+ updates.DATABASE_TYPE = config.database.type || 'sqlite';+ updates.POSTGRES_BUILTIN = config.database.builtIn ? 'true' : 'false';if (config.database.type === 'postgres') {if (config.database.builtIn) {// Built-in PostgreSQL - use container name as host- envLines.push('DATABASE_HOST=postgres');- envLines.push('DATABASE_PORT=5432');- envLines.push('DATABASE_USERNAME=openwa');- envLines.push('DATABASE_PASSWORD=openwa');- envLines.push('DATABASE_NAME=openwa');+ updates.DATABASE_HOST = 'postgres';+ updates.DATABASE_PORT = '5432';+ updates.DATABASE_USERNAME = 'openwa';+ updates.DATABASE_PASSWORD = 'openwa';+ updates.DATABASE_NAME = 'openwa';profiles.push('postgres');} else {// External PostgreSQL- envLines.push(`DATABASE_HOST=${config.database.host || 'localhost'}`);- envLines.push(`DATABASE_PORT=${config.database.port || '5432'}`);- envLines.push(`DATABASE_USERNAME=${config.database.username || 'postgres'}`);- envLines.push(`DATABASE_PASSWORD=${config.database.password || ''}`);- envLines.push(`DATABASE_NAME=${config.database.database || 'openwa'}`);+ updates.DATABASE_HOST = config.database.host || 'localhost';+ updates.DATABASE_PORT = config.database.port || '5432';+ updates.DATABASE_USERNAME = config.database.username || 'postgres';+ setSecret('DATABASE_PASSWORD', config.database.password);+ updates.DATABASE_NAME = config.database.database || 'openwa';}- envLines.push(`DATABASE_POOL_SIZE=${config.database.poolSize || 10}`);- envLines.push(`DATABASE_SSL=${config.database.sslEnabled ? 'true' : 'false'}`);+ updates.DATABASE_POOL_SIZE = String(config.database.poolSize || 10);+ updates.DATABASE_SSL = config.database.sslEnabled ? 'true' : 'false';if (config.database.sslEnabled) {// Default to certificate verification; only relax it when the operator opts out// (managed Postgres with self-signed certs: Supabase, Heroku, Render, Railway).- envLines.push(- `DATABASE_SSL_REJECT_UNAUTHORIZED=${config.database.sslRejectUnauthorized === false ? 'false' : 'true'}`,- );+ updates.DATABASE_SSL_REJECT_UNAUTHORIZED =+ config.database.sslRejectUnauthorized === false ? 'false' : 'true';+ }+ } else {+ // Switching to sqlite: drop stale postgres connection keys.+ for (const k of [+ 'DATABASE_HOST',+ 'DATABASE_PORT',+ 'DATABASE_USERNAME',+ 'DATABASE_PASSWORD',+ 'DATABASE_NAME',+ 'DATABASE_POOL_SIZE',+ 'DATABASE_SSL',+ 'DATABASE_SSL_REJECT_UNAUTHORIZED',+ ]) {+ staleKeys.add(k);}}- envLines.push('');}// Redis / Queue- envLines.push('# Redis / Queue System');- envLines.push(`REDIS_ENABLED=${config.redis?.enabled ? 'true' : 'false'}`);- envLines.push(`REDIS_BUILTIN=${config.redis?.builtIn ? 'true' : 'false'}`);- envLines.push(`QUEUE_ENABLED=${config.queue?.enabled ? 'true' : 'false'}`);- if (config.redis?.enabled) {- if (config.redis.builtIn) {- // Built-in Redis - use container name as host- envLines.push('REDIS_HOST=redis');- envLines.push('REDIS_PORT=6379');- profiles.push('redis');- } else {- // External Redis- envLines.push(`REDIS_HOST=${config.redis.host || 'localhost'}`);- envLines.push(`REDIS_PORT=${config.redis.port || '6379'}`);- if (config.redis.password) {- envLines.push(`REDIS_PASSWORD=${config.redis.password}`);+ if (config.redis || config.queue) {+ updates.REDIS_ENABLED = config.redis?.enabled ? 'true' : 'false';+ updates.REDIS_BUILTIN = config.redis?.builtIn ? 'true' : 'false';+ updates.QUEUE_ENABLED = config.queue?.enabled ? 'true' : 'false';+ if (config.redis?.enabled) {+ if (config.redis.builtIn) {+ // Built-in Redis - use container name as host+ updates.REDIS_HOST = 'redis';+ updates.REDIS_PORT = '6379';+ profiles.push('redis');+ } else {+ // External Redis+ updates.REDIS_HOST = config.redis.host || 'localhost';+ updates.REDIS_PORT = config.redis.port || '6379';+ setSecret('REDIS_PASSWORD', config.redis.password);}}}- envLines.push('');- // Storage+ // Storage. NOTE: STORAGE_LOCAL_PATH / S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY are+ // the names configuration.ts reads (previously saved as STORAGE_PATH / S3_*_KEY and+ // silently ignored — #226).if (config.storage) {- envLines.push('# Storage');- envLines.push(`STORAGE_TYPE=${config.storage.type || 'local'}`);- envLines.push(`MINIO_BUILTIN=${config.storage.builtIn ? 'true' : 'false'}`);+ updates.STORAGE_TYPE = config.storage.type || 'local';+ updates.MINIO_BUILTIN = config.storage.builtIn ? 'true' : 'false';if (config.storage.type === 'local') {- envLines.push(`STORAGE_PATH=${config.storage.localPath || './uploads'}`);+ updates.STORAGE_LOCAL_PATH = config.storage.localPath || './data/media';+ // Switching to local: drop stale S3 keys.+ for (const k of ['S3_ENDPOINT', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY', 'S3_BUCKET', 'S3_REGION']) {+ staleKeys.add(k);+ }} else if (config.storage.type === 's3') {+ staleKeys.add('STORAGE_LOCAL_PATH');if (config.storage.builtIn) {// Built-in MinIO - use container name as endpoint- envLines.push('S3_ENDPOINT=http://minio:9000');- envLines.push('S3_ACCESS_KEY=minioadmin');- envLines.push('S3_SECRET_KEY=minioadmin');- envLines.push('S3_BUCKET=openwa');- envLines.push('S3_REGION=us-east-1');+ updates.S3_ENDPOINT = 'http://minio:9000';+ updates.S3_ACCESS_KEY_ID = 'minioadmin';+ updates.S3_SECRET_ACCESS_KEY = 'minioadmin';+ updates.S3_BUCKET = 'openwa';+ updates.S3_REGION = 'us-east-1';profiles.push('minio');} else {// External S3/MinIO- envLines.push(`S3_BUCKET=${config.storage.s3Bucket || ''}`);- envLines.push(`S3_REGION=${config.storage.s3Region || 'ap-southeast-1'}`);- envLines.push(`S3_ACCESS_KEY=${config.storage.s3AccessKey || ''}`);- envLines.push(`S3_SECRET_KEY=${config.storage.s3SecretKey || ''}`);+ updates.S3_BUCKET = config.storage.s3Bucket || '';+ updates.S3_REGION = config.storage.s3Region || 'ap-southeast-1';+ setSecret('S3_ACCESS_KEY_ID', config.storage.s3AccessKey);+ setSecret('S3_SECRET_ACCESS_KEY', config.storage.s3SecretKey);if (config.storage.s3Endpoint) {- envLines.push(`S3_ENDPOINT=${config.storage.s3Endpoint}`);+ updates.S3_ENDPOINT = config.storage.s3Endpoint;}}}- envLines.push('');}- // Engine+ // Engine. NOTE: PUPPETEER_HEADLESS / SESSION_DATA_PATH / PUPPETEER_ARGS are the names+ // configuration.ts reads (previously saved as ENGINE_* and silently ignored — #226).if (config.engine) {- envLines.push('# WhatsApp Engine');- envLines.push(`ENGINE_HEADLESS=${config.engine.headless !== false ? 'true' : 'false'}`);- envLines.push(`ENGINE_SESSION_PATH=${config.engine.sessionDataPath || './data/sessions'}`);- envLines.push(`ENGINE_BROWSER_ARGS=${config.engine.browserArgs || '--no-sandbox --disable-gpu'}`);- envLines.push('');+ updates.PUPPETEER_HEADLESS = config.engine.headless !== false ? 'true' : 'false';+ updates.SESSION_DATA_PATH = config.engine.sessionDataPath || './data/sessions';+ updates.PUPPETEER_ARGS = config.engine.browserArgs || '--no-sandbox --disable-gpu';}- // Docker Profiles (for reference)- envLines.push('# Docker Profiles (auto-generated)');- envLines.push(`# Required profiles: ${profiles.length > 0 ? profiles.join(', ') : 'none'}`);- envLines.push('');-- // Write to .env file in data/ directory so it persists across container restarts- const envPath = path.resolve(process.cwd(), 'data', '.env.generated');- fs.writeFileSync(envPath, envLines.join('\n'), 'utf8');+ // Existing values are the base; this payload's values win (secrets handled above).+ const merged: Record<string, string> = { ...existing, ...updates };+ // Drop keys made obsolete by a mode switch (postgres->sqlite, s3->local).+ for (const k of staleKeys) {+ delete merged[k];+ }+ const body = Object.keys(merged)+ .sort()+ .map(key => `${key}=${merged[key]}`);+ const contents = [+ '# OpenWA Configuration',+ `# Generated at ${new Date().toISOString()}`,+ '# Managed via Dashboard > Infrastructure. Values in process env or project .env take precedence.',+ '',+ ...body,+ '',+ ].join('\n');++ // Write to data/ so it persists across container restarts.+ fs.writeFileSync(envPath, contents, 'utf8');this.logger.log('Configuration saved', { envPath });const profileMsg = profiles.length > 0 ? ` Docker profiles required: ${profiles.join(', ')}.` : '';@@ -682,6 +801,7 @@ export class InfraController {// ============================================================================@Get('storage/files/count')+ @RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Get file count in current storage' })@ApiResponse({ status: 200, description: 'File count and size' })async getStorageFileCount(): Promise<{diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex b487889b4..d088c2da1 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -223,6 +223,12 @@ export class BulkMessageService {private applyVariables(content: BulkMessageContent, variables?: Record<string, string>): BulkMessageContent {if (!variables) return content;+ // NOTE: This single-brace `{name}` convention differs from the shared+ // server-side template renderer (`renderTemplate` in+ // common/utils/template-render.ts) which uses double-brace `{{name}}`+ // placeholders. The two conventions should be reconciled onto the shared+ // helper in a follow-up so the gateway exposes one consistent templating+ // syntax. See issue #69.const replaceVars = (str: string): string => {return str.replace(/\{(\w+)\}/g, (_, key: string) => variables[key] || `{${key}}`);};diff --git a/src/modules/message/dto/send-template.dto.ts b/src/modules/message/dto/send-template.dto.tsnew file mode 100644index 000000000..14b6c56c3--- /dev/null+++ b/src/modules/message/dto/send-template.dto.ts@@ -0,0 +1,40 @@+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import { IsString, IsNotEmpty, IsOptional, IsObject, ValidateIf } from 'class-validator';++export class SendTemplateMessageDto {+ @ApiProperty({+ description: 'WhatsApp chat ID ([email protected] for individual, [email protected] for groups)',+ example: '[email protected]',+ })+ @IsString()+ @IsNotEmpty()+ chatId: string;++ @ApiPropertyOptional({+ description: 'Template ID to render. Provide either templateId or templateName.',+ example: 'b1c2d3e4-f5a6-7890-bcde-f01234567890',+ })+ @IsOptional()+ @IsString()+ @IsNotEmpty()+ @ValidateIf((o: SendTemplateMessageDto) => !o.templateName)+ templateId?: string;++ @ApiPropertyOptional({+ description: 'Template name to render. Provide either templateId or templateName.',+ example: 'order-confirmation',+ })+ @IsOptional()+ @IsString()+ @IsNotEmpty()+ @ValidateIf((o: SendTemplateMessageDto) => !o.templateId)+ templateName?: string;++ @ApiPropertyOptional({+ description: 'Variables substituted into {{placeholder}} tokens in the template',+ example: { customer: 'Alice', orderId: '1234' },+ })+ @IsOptional()+ @IsObject()+ vars?: Record<string, string>;+}diff --git a/src/modules/message/message-status.util.spec.ts b/src/modules/message/message-status.util.spec.tsnew file mode 100644index 000000000..415adca89--- /dev/null+++ b/src/modules/message/message-status.util.spec.ts@@ -0,0 +1,44 @@+import { ackToMessageStatus, ackStatusTransitionFrom } from './message-status.util';+import { MessageStatus } from './entities/message.entity';++describe('ackToMessageStatus', () => {+ it('maps an error ack (<0) to FAILED', () => {+ expect(ackToMessageStatus(-1)).toBe(MessageStatus.FAILED);+ });++ it('maps device ack (2) to DELIVERED', () => {+ expect(ackToMessageStatus(2)).toBe(MessageStatus.DELIVERED);+ });++ it('maps read/played ack (>=3) to READ', () => {+ expect(ackToMessageStatus(3)).toBe(MessageStatus.READ);+ expect(ackToMessageStatus(4)).toBe(MessageStatus.READ);+ });++ it('returns null for pending (0) and server-sent (1) — no upgrade beyond SENT', () => {+ expect(ackToMessageStatus(0)).toBeNull();+ expect(ackToMessageStatus(1)).toBeNull();+ });+});++describe('ackStatusTransitionFrom (monotonic delivery-state guard)', () => {+ it('DELIVERED may advance only from PENDING/SENT (never downgrades a READ row)', () => {+ expect(ackStatusTransitionFrom(MessageStatus.DELIVERED)).toEqual([MessageStatus.PENDING, MessageStatus.SENT]);+ expect(ackStatusTransitionFrom(MessageStatus.DELIVERED)).not.toContain(MessageStatus.READ);+ });++ it('READ may advance from PENDING/SENT/DELIVERED', () => {+ expect(ackStatusTransitionFrom(MessageStatus.READ)).toEqual([+ MessageStatus.PENDING,+ MessageStatus.SENT,+ MessageStatus.DELIVERED,+ ]);+ });++ it('FAILED does not clobber an already delivered/read message', () => {+ const from = ackStatusTransitionFrom(MessageStatus.FAILED);+ expect(from).toEqual([MessageStatus.PENDING, MessageStatus.SENT]);+ expect(from).not.toContain(MessageStatus.DELIVERED);+ expect(from).not.toContain(MessageStatus.READ);+ });+});diff --git a/src/modules/message/message-status.util.ts b/src/modules/message/message-status.util.tsnew file mode 100644index 000000000..b81b97279--- /dev/null+++ b/src/modules/message/message-status.util.ts@@ -0,0 +1,36 @@+import { MessageStatus } from './entities/message.entity';++/**+ * Maps a whatsapp-web.js ack level to the delivery status it implies, or null+ * when the ack carries no upgrade beyond the stored `SENT` state.+ *+ * wwebjs MessageAck: -1 ERROR, 0 PENDING, 1 SERVER (sent), 2 DEVICE (delivered),+ * 3 READ, 4 PLAYED. This is how the stored message reflects *real* delivery+ * state (#220): a send that never receives ack≥2 stays `SENT`, visibly+ * "not delivered".+ */+export function ackToMessageStatus(ack: number): MessageStatus | null {+ if (ack < 0) return MessageStatus.FAILED;+ if (ack >= 3) return MessageStatus.READ;+ if (ack === 2) return MessageStatus.DELIVERED;+ return null; // 0 (pending) / 1 (server-received) — message is already SENT, no upgrade+}++/**+ * The stored statuses a delivery transition may advance FROM. Used as a conditional UPDATE guard so+ * delivery state only moves forward — preventing an out-of-order/late ack from downgrading a higher+ * status (e.g. a DELIVERED ack arriving after READ), even though the writes are fire-and-forget.+ * A late FAILED must not clobber a message already confirmed delivered/read, and vice versa.+ */+export function ackStatusTransitionFrom(target: MessageStatus): MessageStatus[] {+ switch (target) {+ case MessageStatus.DELIVERED:+ return [MessageStatus.PENDING, MessageStatus.SENT];+ case MessageStatus.READ:+ return [MessageStatus.PENDING, MessageStatus.SENT, MessageStatus.DELIVERED];+ case MessageStatus.FAILED:+ return [MessageStatus.PENDING, MessageStatus.SENT];+ default:+ return [];+ }+}diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex 8c84eed6a..04bb9ee7c 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -3,6 +3,7 @@ import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/import { MessageService } from './message.service';import { BulkMessageService } from './bulk-message.service';import { SendTextMessageDto, SendMediaMessageDto, MessageResponseDto } from './dto';+import { SendTemplateMessageDto } from './dto/send-template.dto';import { SendBulkMessageDto, BulkMessageResponseDto } from './dto/bulk-message.dto';import { RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';@@ -56,6 +57,27 @@ export class MessageController {return this.messageService.sendText(sessionId, dto);}+ @Post('send-template')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Render a stored text template and send it as a text message' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({+ status: 201,+ description: 'Template rendered and sent',+ type: MessageResponseDto,+ })+ @ApiResponse({+ status: 400,+ description: 'Session not active or invalid request',+ })+ @ApiResponse({ status: 404, description: 'Session or template not found' })+ async sendTemplate(+ @Param('sessionId') sessionId: string,+ @Body() dto: SendTemplateMessageDto,+ ): Promise<MessageResponseDto> {+ return this.messageService.sendTemplate(sessionId, dto);+ }+@Post('send-image')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send an image message' })@@ -240,6 +262,40 @@ export class MessageController {return { success: true };}+ @Get(':chatId/history')+ @ApiOperation({+ summary: 'Fetch chat history live from WhatsApp',+ description:+ 'Reads messages directly from the WhatsApp client for the given chat, bypassing the local DB. ' ++ 'Useful for retrieving messages that arrived before the gateway was started.',+ })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'chatId', description: 'Chat ID (e.g. [email protected] or [email protected])' })+ @ApiQuery({ name: 'limit', required: false, type: Number, description: 'Max messages to return (default 50)' })+ @ApiQuery({+ name: 'includeMedia',+ required: false,+ type: Boolean,+ description: 'When true, downloads media (base64) for messages that have it. Slower; default false.',+ })+ @ApiResponse({ status: 200, description: 'Chat history (most recent messages)' })+ async getChatHistory(+ @Param('sessionId') sessionId: string,+ @Param('chatId') chatId: string,+ @Query('limit') limit?: string,+ @Query('includeMedia') includeMedia?: string,+ ) {+ // Parse the limit defensively: a non-numeric query value (?limit=abc) yields NaN,+ // so fall back to undefined and let the service apply its default + [1,100] clamp.+ const parsedLimit = limit ? parseInt(limit, 10) : undefined;+ return this.messageService.getChatHistory(+ sessionId,+ chatId,+ parsedLimit !== undefined && !Number.isNaN(parsedLimit) ? parsedLimit : undefined,+ includeMedia === 'true' || includeMedia === '1',+ );+ }+@Get(':chatId/:messageId/reactions')@ApiOperation({ summary: 'Get reactions for a specific message' })@ApiParam({ name: 'sessionId', description: 'Session ID' })diff --git a/src/modules/message/message.module.ts b/src/modules/message/message.module.tsindex 8051f3a39..522001e7b 100644--- a/src/modules/message/message.module.ts+++ b/src/modules/message/message.module.ts@@ -4,11 +4,12 @@ import { MessageService } from './message.service';import { BulkMessageService } from './bulk-message.service';import { MessageController } from './message.controller';import { SessionModule } from '../session/session.module';+import { TemplateModule } from '../template/template.module';import { Message } from './entities/message.entity';import { MessageBatch } from './entities/message-batch.entity';@Module({- imports: [TypeOrmModule.forFeature([Message, MessageBatch], 'data'), SessionModule],+ imports: [TypeOrmModule.forFeature([Message, MessageBatch], 'data'), SessionModule, TemplateModule],controllers: [MessageController],providers: [MessageService, BulkMessageService],exports: [MessageService, BulkMessageService],diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex ad8d57adb..ec8271e5a 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -1,11 +1,13 @@import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken } from '@nestjs/typeorm';import { Repository } from 'typeorm';-import { BadRequestException } from '@nestjs/common';+import { BadRequestException, NotFoundException } from '@nestjs/common';import { MessageService } from './message.service';import { Message, MessageDirection, MessageStatus } from './entities/message.entity';import { SessionService } from '../session/session.service';import { HookManager } from '../../core/hooks';+import { TemplateService } from '../template/template.service';+import { Template } from '../template/entities/template.entity';const mockEngineResult = { id: 'wa-msg-1', timestamp: 1706868000 };@@ -24,6 +26,7 @@ function createMockEngine() {reactToMessage: jest.fn().mockResolvedValue(undefined),getMessageReactions: jest.fn().mockResolvedValue([]),deleteMessage: jest.fn().mockResolvedValue(undefined),+ getChatHistory: jest.fn().mockResolvedValue([]),};}@@ -32,12 +35,15 @@ describe('MessageService', () => {let repository: jest.Mocked<Partial<Repository<Message>>>;let sessionService: jest.Mocked<Partial<SessionService>>;let hookManager: jest.Mocked<Partial<HookManager>>;+ let templateService: jest.Mocked<Partial<TemplateService>>;let mockEngine: ReturnType<typeof createMockEngine>;beforeEach(async () => {repository = {create: jest.fn().mockImplementation((data: Partial<Message>) => ({ id: 'msg-uuid-1', ...data }) as Message),save: jest.fn().mockImplementation(msg => Promise.resolve(msg)),+ findOne: jest.fn().mockResolvedValue(null),+ update: jest.fn().mockResolvedValue({ affected: 1 }),createQueryBuilder: jest.fn(),};@@ -55,12 +61,17 @@ describe('MessageService', () => {}),};+ templateService = {+ resolve: jest.fn(),+ };+const module: TestingModule = await Test.createTestingModule({providers: [MessageService,{ provide: getRepositoryToken(Message, 'data'), useValue: repository },{ provide: SessionService, useValue: sessionService },{ provide: HookManager, useValue: hookManager },+ { provide: TemplateService, useValue: templateService },],}).compile();@@ -101,7 +112,7 @@ describe('MessageService', () => {expect(repository.save).toHaveBeenCalledTimes(2);});- it('should execute message:sending and message:sent hooks', async () => {+ it('executes the message:sending hook (message:sent now fires once from the engine message_create path)', async () => {await service.sendText('sess-1', {chatId: '[email protected]',text: 'Hello',@@ -112,11 +123,9 @@ describe('MessageService', () => {expect.objectContaining({ type: 'text' }),expect.any(Object),);- expect(hookManager.execute).toHaveBeenCalledWith(- 'message:sent',- expect.objectContaining({ result: mockEngineResult }),- expect.any(Object),- );+ // message:sent is no longer fired here — it is emitted solely by SessionService.onMessageCreate+ // with a consistent IncomingMessage payload for ALL sends (avoids the prior double dispatch).+ expect(hookManager.execute).not.toHaveBeenCalledWith('message:sent', expect.anything(), expect.anything());});it('should throw BadRequestException when plugin blocks sending', async () => {@@ -136,6 +145,91 @@ describe('MessageService', () => {});});+ // ── sendTemplate ──────────────────────────────────────────────────++ describe('sendTemplate', () => {+ function mockTemplate(overrides: Partial<Template> = {}): Template {+ return {+ id: 'tpl-1',+ sessionId: 'sess-1',+ name: 'order-confirmation',+ body: 'Hi {{customer}}, your order {{orderId}} shipped.',+ header: null,+ footer: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ session: undefined as unknown as Template['session'],+ ...overrides,+ };+ }++ beforeEach(() => {+ // Echo the supplied input back through the hook so the rendered text+ // reaches the engine via the delegated sendText path.+ (hookManager.execute as jest.Mock).mockImplementation((event: string, data: unknown) =>+ Promise.resolve({ continue: true, data }),+ );+ });++ it('should resolve the template, render variables, and delegate to sendText', async () => {+ (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate());++ const result = await service.sendTemplate('sess-1', {+ chatId: '[email protected]',+ templateName: 'order-confirmation',+ vars: { customer: 'Alice', orderId: '1234' },+ });++ expect(templateService.resolve).toHaveBeenCalledWith('sess-1', {+ templateId: undefined,+ templateName: 'order-confirmation',+ });+ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(+ '[email protected]',+ 'Hi Alice, your order 1234 shipped.',+ );+ expect(result.messageId).toBe('wa-msg-1');+ });++ it('should flatten header and footer around the body with blank lines', async () => {+ (templateService.resolve as jest.Mock).mockResolvedValue(+ mockTemplate({ header: 'OpenWA Store', body: 'Hello {{customer}}', footer: 'Reply STOP to opt out' }),+ );++ await service.sendTemplate('sess-1', {+ chatId: '[email protected]',+ templateId: 'tpl-1',+ vars: { customer: 'Bob' },+ });++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(+ '[email protected]',+ 'OpenWA Store\n\nHello Bob\n\nReply STOP to opt out',+ );+ });++ it('should leave unmatched placeholders literal', async () => {+ (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hi {{customer}} {{unknown}}' }));++ await service.sendTemplate('sess-1', {+ chatId: '[email protected]',+ templateId: 'tpl-1',+ vars: { customer: 'Alice' },+ });++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi Alice {{unknown}}');+ });++ it('should propagate NotFoundException when the template cannot be resolved', async () => {+ (templateService.resolve as jest.Mock).mockRejectedValue(new NotFoundException('Template not found'));++ await expect(service.sendTemplate('sess-1', { chatId: '[email protected]', templateName: 'missing' })).rejects.toThrow(+ NotFoundException,+ );+ expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();+ });+ });+// ── sendImage ─────────────────────────────────────────────────────describe('sendImage', () => {@@ -345,6 +439,41 @@ describe('MessageService', () => {});});+ describe('getChatHistory', () => {+ it('should call engine.getChatHistory with default limit and includeMedia=false', async () => {+ await service.getChatHistory('sess-1', '[email protected]');+ expect(mockEngine.getChatHistory).toHaveBeenCalledWith('[email protected]', 50, false);+ });++ it('should pass through custom limit', async () => {+ await service.getChatHistory('sess-1', '[email protected]', 10);+ expect(mockEngine.getChatHistory).toHaveBeenCalledWith('[email protected]', 10, false);+ });++ it('should pass through includeMedia flag', async () => {+ await service.getChatHistory('sess-1', '[email protected]', 5, true);+ expect(mockEngine.getChatHistory).toHaveBeenCalledWith('[email protected]', 5, true);+ });++ it('should clamp the limit to [1, 100] and default non-finite values to 50', async () => {+ await service.getChatHistory('sess-1', '[email protected]', 500);+ expect(mockEngine.getChatHistory).toHaveBeenLastCalledWith('[email protected]', 100, false);++ await service.getChatHistory('sess-1', '[email protected]', 0);+ expect(mockEngine.getChatHistory).toHaveBeenLastCalledWith('[email protected]', 1, false);++ await service.getChatHistory('sess-1', '[email protected]', Number.NaN);+ expect(mockEngine.getChatHistory).toHaveBeenLastCalledWith('[email protected]', 50, false);+ });++ it('should return engine result', async () => {+ const fake = [{ id: 'm1', body: 'hi', from: 'a', to: 'b', chatId: '[email protected]' }];+ mockEngine.getChatHistory.mockResolvedValueOnce(fake);+ const result = await service.getChatHistory('sess-1', '[email protected]');+ expect(result).toBe(fake);+ });+ });+describe('deleteMessage', () => {it('should call engine.deleteMessage with forEveryone default true', async () => {await service.deleteMessage('sess-1', {diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex cd245bd56..ebfc89322 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -3,9 +3,13 @@ import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { SessionService } from '../session/session.service';import { SendTextMessageDto, SendMediaMessageDto, MessageResponseDto } from './dto';+import { SendTemplateMessageDto } from './dto/send-template.dto';import { MediaInput } from '../../engine/interfaces/whatsapp-engine.interface';import { Message, MessageDirection, MessageStatus } from './entities/message.entity';import { HookManager } from '../../core/hooks';+import { TemplateService } from '../template/template.service';+import { renderTemplate } from '../../common/utils/template-render';+import { createLogger } from '../../common/services/logger.service';export interface GetMessagesOptions {chatId?: string;@@ -15,11 +19,14 @@ export interface GetMessagesOptions {@Injectable()export class MessageService {+ private readonly logger = createLogger('MessageService');+constructor(@InjectRepository(Message, 'data')private readonly messageRepository: Repository<Message>,private readonly sessionService: SessionService,private readonly hookManager: HookManager,+ private readonly templateService: TemplateService,) {}async sendText(sessionId: string, dto: SendTextMessageDto): Promise<MessageResponseDto> {@@ -55,13 +62,9 @@ export class MessageService {message.timestamp = result.timestamp;await this.messageRepository.save(message);- // Execute hook after successful send- await this.hookManager.execute(- 'message:sent',- { sessionId, result, input: finalDto },- { sessionId, source: 'MessageService' },- );-+ // Note: the `message:sent` hook is emitted solely by SessionService.onMessageCreate (engine+ // `message_create`) with a consistent IncomingMessage payload for ALL sends (text, media,+ // and phone-composed), so it is intentionally not fired here to avoid a double dispatch.return {messageId: result.id,timestamp: result.timestamp,@@ -82,6 +85,28 @@ export class MessageService {}}+ /**+ * Resolve a stored template, render its body (with optional header/footer+ * flattened using newlines) using the supplied variables, and delegate to the+ * existing {@link sendText} path so plugin hooks, persistence, and status+ * tracking are reused. Throws NotFoundException when the template cannot be+ * resolved by id or name.+ */+ async sendTemplate(sessionId: string, dto: SendTemplateMessageDto): Promise<MessageResponseDto> {+ const template = await this.templateService.resolve(sessionId, {+ templateId: dto.templateId,+ templateName: dto.templateName,+ });++ const vars = dto.vars ?? {};+ const segments = [template.header, template.body, template.footer]+ .filter((segment): segment is string => segment != null && segment.length > 0)+ .map(segment => renderTemplate(segment, vars));+ const text = segments.join('\n\n');++ return this.sendText(sessionId, { chatId: dto.chatId, text });+ }+async sendImage(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {const engine = this.getEngine(sessionId);const media = this.buildMediaInput(dto);@@ -91,6 +116,9 @@ export class MessageService {chatId: dto.chatId,body: dto.caption || '',type: 'image',+ metadata: {+ media: { mimetype: dto.mimetype, filename: dto.filename, data: dto.base64 || dto.url },+ },});try {@@ -122,6 +150,9 @@ export class MessageService {chatId: dto.chatId,body: dto.caption || '',type: 'video',+ metadata: {+ media: { mimetype: dto.mimetype, filename: dto.filename, data: dto.base64 || dto.url },+ },});try {@@ -152,6 +183,9 @@ export class MessageService {const message = await this.saveOutgoingMessage(sessionId, {chatId: dto.chatId,type: 'audio',+ metadata: {+ media: { mimetype: dto.mimetype, filename: dto.filename, data: dto.base64 || dto.url },+ },});try {@@ -183,6 +217,9 @@ export class MessageService {chatId: dto.chatId,body: dto.filename || '',type: 'document',+ metadata: {+ media: { mimetype: dto.mimetype, filename: dto.filename, data: dto.base64 || dto.url },+ },});try {@@ -313,6 +350,9 @@ export class MessageService {const message = await this.saveOutgoingMessage(sessionId, {chatId: dto.chatId,type: 'sticker',+ metadata: {+ media: { mimetype: dto.mimetype, filename: dto.filename, data: dto.base64 || dto.url },+ },});try {@@ -341,11 +381,25 @@ export class MessageService {): Promise<MessageResponseDto> {const engine = this.getEngine(sessionId);+ // Resolve the quoted message body (best-effort) so the dashboard can render the reply preview.+ let quotedBody = '';+ try {+ const quoted = await this.messageRepository.findOne({+ where: { sessionId, waMessageId: dto.quotedMessageId },+ });+ quotedBody = quoted?.body || '';+ } catch (err) {+ this.logger.warn(`Failed to resolve quoted message ${dto.quotedMessageId}`, { error: String(err) });+ }+// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {chatId: dto.chatId,body: dto.text,type: 'text',+ metadata: {+ quotedMessage: { id: dto.quotedMessageId, body: quotedBody },+ },});try {@@ -426,6 +480,7 @@ export class MessageService {type: string;timestamp?: number;status?: MessageStatus;+ metadata?: Record<string, unknown>;},): Promise<Message> {const session = await this.sessionService.findOne(sessionId);@@ -440,6 +495,7 @@ export class MessageService {direction: MessageDirection.OUTGOING,timestamp: data.timestamp,status: data.status ?? MessageStatus.PENDING,+ metadata: data.metadata,});return this.messageRepository.save(message);}@@ -456,6 +512,25 @@ export class MessageService {return engine.getMessageReactions(chatId, messageId);}+ /** Maximum messages a single getChatHistory call may request from the engine. */+ private static readonly MAX_CHAT_HISTORY_LIMIT = 100;++ /**+ * Fetch chat history live from WhatsApp (bypasses local DB).+ * Returns the most recent `limit` messages for the given chat.+ * When `includeMedia` is true, downloads media (base64) for messages that have it.+ *+ * `limit` is clamped to [1, 100] (and falls back to 50 for non-finite input) so a+ * caller cannot ask the engine to fetch an unbounded number of messages.+ */+ async getChatHistory(sessionId: string, chatId: string, limit = 50, includeMedia = false) {+ const engine = this.getEngine(sessionId);+ const safeLimit = Number.isFinite(limit)+ ? Math.min(Math.max(Math.trunc(limit), 1), MessageService.MAX_CHAT_HISTORY_LIMIT)+ : 50;+ return engine.getChatHistory(chatId, safeLimit, includeMedia);+ }+// ========== Delete Message ==========async deleteMessage(@@ -464,6 +539,14 @@ export class MessageService {): Promise<void> {const engine = this.getEngine(sessionId);await engine.deleteMessage(dto.chatId, dto.messageId, dto.forEveryone ?? true);++ // Flag the stored message as revoked. No localized display string is persisted here;+ // the dashboard renders the localized "message deleted" text.+ try {+ await this.messageRepository.update({ sessionId, waMessageId: dto.messageId }, { body: '', type: 'revoked' });+ } catch (err) {+ this.logger.warn(`Failed to flag deleted message ${dto.messageId} as revoked`, { error: String(err) });+ }}private getEngine(sessionId: string) {diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.tsindex 4792fec59..70f617a17 100644--- a/src/modules/plugins/plugins.controller.ts+++ b/src/modules/plugins/plugins.controller.ts@@ -2,6 +2,8 @@ import { Controller, Get, Post, Put, Param, Body, HttpCode, HttpStatus } from '@import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';import { PluginsService } from './plugins.service';import { PluginDto, PluginConfigDto } from './dto/plugin.dto';+import { RequireRole } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';@ApiTags('plugins')@Controller('plugins')@@ -24,6 +26,7 @@ export class PluginsController {}@Post(':id/enable')+ @RequireRole(ApiKeyRole.ADMIN)@HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Enable a plugin' })@ApiResponse({ status: 200, description: 'Plugin enabled successfully' })@@ -32,6 +35,7 @@ export class PluginsController {}@Post(':id/disable')+ @RequireRole(ApiKeyRole.ADMIN)@HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Disable a plugin' })@ApiResponse({ status: 200, description: 'Plugin disabled successfully' })@@ -40,6 +44,7 @@ export class PluginsController {}@Put(':id/config')+ @RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Update plugin configuration' })@ApiResponse({ status: 200, description: 'Plugin configuration updated' })updateConfig(@Param('id') id: string, @Body() configDto: PluginConfigDto): { success: boolean; message: string } {diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.tsindex 669fbc4ec..05edcea64 100644--- a/src/modules/queue/processors/webhook.processor.ts+++ b/src/modules/queue/processors/webhook.processor.ts@@ -7,6 +7,7 @@ import { QUEUE_NAMES } from '../queue-names';import { WebhookJobData } from '../../webhook/webhook.service';import { Webhook } from '../../webhook/entities/webhook.entity';import { HookManager } from '../../../core/hooks';+import { assertSafeWebhookUrl, isSsrfProtectionEnabled } from '../../../common/security/ssrf-guard';export interface WebhookJobResult {statusCode: number;@@ -48,6 +49,9 @@ export class WebhookProcessor extends WorkerHost {};try {+ if (isSsrfProtectionEnabled()) {+ await assertSafeWebhookUrl(url);+ }const response = await fetch(url, {method: 'POST',headers: requestHeaders,diff --git a/src/modules/session/dto/index.ts b/src/modules/session/dto/index.tsindex c9099abe2..c14026563 100644--- a/src/modules/session/dto/index.ts+++ b/src/modules/session/dto/index.ts@@ -1,2 +1,3 @@export * from './create-session.dto';export * from './session-response.dto';+export * from './mark-chat-read.dto';diff --git a/src/modules/session/dto/mark-chat-read.dto.ts b/src/modules/session/dto/mark-chat-read.dto.tsnew file mode 100644index 000000000..e9826a947--- /dev/null+++ b/src/modules/session/dto/mark-chat-read.dto.ts@@ -0,0 +1,16 @@+import { ApiProperty } from '@nestjs/swagger';+import { IsNotEmpty, IsString, Matches } from 'class-validator';++export class MarkChatReadDto {+ @ApiProperty({+ description: 'WhatsApp chat ID to mark as read (e.g., [email protected] or [email protected])',+ example: '[email protected]',+ })+ @IsString()+ @IsNotEmpty()+ // Reject malformed IDs early with a clear 400 instead of a silent no-op at the engine layer.+ @Matches(/^[0-9-]+@[cg]\.us$/, {+ message: 'chatId must be a valid WhatsApp JID (e.g. [email protected] or [email protected])',+ })+ chatId: string;+}diff --git a/src/modules/session/dto/session-response.dto.ts b/src/modules/session/dto/session-response.dto.tsindex 0ca1bac3e..ce5e0b9c5 100644--- a/src/modules/session/dto/session-response.dto.ts+++ b/src/modules/session/dto/session-response.dto.ts@@ -28,6 +28,12 @@ export class SessionResponseDto {@ApiProperty({ example: '2025-02-02T10:00:00Z' })updatedAt: Date;++ @ApiPropertyOptional({+ description: 'Human-readable reason for the most recent terminal engine failure (only set when status is FAILED).',+ example: 'Failed to launch the browser process: spawn /usr/bin/chromium ENOENT',+ })+ lastError?: string | null;}export class QRCodeResponseDto {diff --git a/src/modules/session/entities/session.entity.ts b/src/modules/session/entities/session.entity.tsindex 4abf0fb7b..fe4dc3b7a 100644--- a/src/modules/session/entities/session.entity.ts+++ b/src/modules/session/entities/session.entity.ts@@ -54,4 +54,12 @@ export class Session {@UpdateDateColumn()updatedAt: Date;++ /**+ * Transient (non-persisted) human-readable reason for the most recent terminal+ * engine failure. Populated at read time from the in-memory error map so the+ * dashboard can explain a FAILED status; intentionally not a column because it+ * is runtime state that resets when the engine re-initializes.+ */+ lastError?: string;}diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 0b0fe8628..7998fd9aa 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -1,8 +1,9 @@import { Controller, Get, Post, Delete, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiParam } from '@nestjs/swagger';import { SessionService } from './session.service';-import { CreateSessionDto, SessionResponseDto, QRCodeResponseDto } from './dto';+import { CreateSessionDto, SessionResponseDto, QRCodeResponseDto, MarkChatReadDto } from './dto';import { Session } from './entities/session.entity';+import { ChatSummary } from '../../engine/interfaces/whatsapp-engine.interface';import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { RequireRole } from '../auth/decorators/auth.decorators';@@ -28,6 +29,7 @@ export class SessionController {lastActive: session.lastActiveAt,createdAt: session.createdAt,updatedAt: session.updatedAt,+ lastError: session.lastError ?? null,};}@@ -163,10 +165,32 @@ export class SessionController {})@ApiResponse({ status: 400, description: 'Session not ready' })@ApiResponse({ status: 404, description: 'Session not found' })- async getGroups(@Param('id') id: string): Promise<{ id: string; name: string }[]> {+ async getGroups(@Param('id') id: string): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {return this.sessionService.getGroups(id);}+ @Get(':id/chats')+ @ApiOperation({ summary: 'Get active chats for a session' })+ @ApiParam({ name: 'id', description: 'Session ID' })+ @ApiResponse({ status: 200, description: 'List of active chats' })+ @ApiResponse({ status: 400, description: 'Session not ready' })+ @ApiResponse({ status: 404, description: 'Session not found' })+ async getChats(@Param('id') id: string): Promise<ChatSummary[]> {+ return this.sessionService.getChats(id);+ }++ @Post(':id/chats/read')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Mark a chat as read/seen' })+ @ApiParam({ name: 'id', description: 'Session ID' })+ @ApiResponse({ status: 200, description: 'Chat marked as read successfully' })+ @ApiResponse({ status: 400, description: 'Session not ready' })+ @ApiResponse({ status: 404, description: 'Session not found' })+ async markChatRead(@Param('id') id: string, @Body() dto: MarkChatReadDto): Promise<{ success: boolean }> {+ const success = await this.sessionService.sendSeen(id, dto.chatId);+ return { success };+ }+@Get('stats/overview')@ApiOperation({summary: 'Get session statistics for multi-session monitoring',diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.tsindex d358ad681..7f589a663 100644--- a/src/modules/session/session.module.ts+++ b/src/modules/session/session.module.ts@@ -1,12 +1,13 @@import { Module, forwardRef } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';import { Session } from './entities/session.entity';+import { Message } from '../message/entities/message.entity';import { SessionService } from './session.service';import { SessionController } from './session.controller';import { WebhookModule } from '../webhook/webhook.module';@Module({- imports: [TypeOrmModule.forFeature([Session], 'data'), forwardRef(() => WebhookModule)],+ imports: [TypeOrmModule.forFeature([Session, Message], 'data'), forwardRef(() => WebhookModule)],controllers: [SessionController],providers: [SessionService],exports: [SessionService],diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 2c10e1fe6..52f6207fb 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -4,10 +4,12 @@ import { Repository, DataSource } from 'typeorm';import { NotFoundException, ConflictException, BadRequestException } from '@nestjs/common';import { SessionService } from './session.service';import { Session, SessionStatus } from './entities/session.entity';+import { Message, MessageStatus } from '../message/entities/message.entity';import { EngineFactory } from '../../engine/engine.factory';import { EventsGateway } from '../events/events.gateway';import { WebhookService } from '../webhook/webhook.service';import { HookManager } from '../../core/hooks';+import { IncomingMessage, EngineEventCallbacks } from '../../engine/interfaces/whatsapp-engine.interface';function createMockSession(overrides: Partial<Session> = {}): Session {return {@@ -30,6 +32,7 @@ function createMockSession(overrides: Partial<Session> = {}): Session {describe('SessionService', () => {let service: SessionService;let repository: jest.Mocked<Partial<Repository<Session>>>;+ let messageRepository: jest.Mocked<Partial<Repository<Message>>>;let dataSource: jest.Mocked<Partial<DataSource>>;let engineFactory: jest.Mocked<Partial<EngineFactory>>;let eventsGateway: jest.Mocked<Partial<EventsGateway>>;@@ -48,6 +51,14 @@ describe('SessionService', () => {update: jest.fn(),};+ messageRepository = {+ find: jest.fn().mockResolvedValue([]),+ findOne: jest.fn().mockResolvedValue(null),+ create: jest.fn(),+ save: jest.fn().mockResolvedValue(undefined),+ update: jest.fn().mockResolvedValue({ affected: 1 }),+ };+dataSource = {transaction: jest.fn().mockImplementation(async (cb: (manager: unknown) => Promise<unknown>) => {const manager = {@@ -64,6 +75,8 @@ describe('SessionService', () => {disconnect: jest.fn().mockResolvedValue(undefined),getQRCode: jest.fn().mockReturnValue(null),getGroups: jest.fn().mockResolvedValue([]),+ getChats: jest.fn().mockResolvedValue([]),+ sendSeen: jest.fn().mockResolvedValue(true),};engineFactory = {@@ -73,6 +86,9 @@ describe('SessionService', () => {eventsGateway = {emitSessionStatus: jest.fn(),emitMessage: jest.fn(),+ emitMessageSent: jest.fn(),+ emitMessageRevoked: jest.fn(),+ emitMessageReaction: jest.fn(),};webhookService = {@@ -90,6 +106,10 @@ describe('SessionService', () => {provide: getRepositoryToken(Session, 'data'),useValue: repository,},+ {+ provide: getRepositoryToken(Message, 'data'),+ useValue: messageRepository,+ },{provide: getDataSourceToken('data'),useValue: dataSource,@@ -251,6 +271,233 @@ describe('SessionService', () => {expect.any(Object),);});++ it('persists INITIALIZING before engine.initialize() runs (no post-init clobber) — #219', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ let initializingPersistedBeforeInit = false;+ mockEngine.initialize.mockImplementation(() => {+ initializingPersistedBeforeInit = (repository.update as jest.Mock).mock.calls.some(+ (call: unknown[]) => (call[1] as { status?: SessionStatus })?.status === SessionStatus.INITIALIZING,+ );+ return Promise.resolve();+ });++ await service.start('sess-uuid-1');++ // The engine drives status forward via callbacks during initialize(); writing+ // INITIALIZING afterwards would clobber that progress, so it must be set before.+ expect(initializingPersistedBeforeInit).toBe(true);+ const initializingWrites = (repository.update as jest.Mock).mock.calls.filter(+ (call: unknown[]) => (call[1] as { status?: SessionStatus })?.status === SessionStatus.INITIALIZING,+ );+ expect(initializingWrites).toHaveLength(1);+ });+ });++ // ── engine onError / lastError surfacing (#219) ───────────────────++ describe('engine onError', () => {+ type EngineCallbacks = { onError?: (reason: string) => void; onReady?: (phone: string, name: string) => void };++ const startAndCapture = async (): Promise<EngineCallbacks> => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ let captured: EngineCallbacks = {};+ mockEngine.initialize.mockImplementation((cb: EngineCallbacks) => {+ captured = cb;+ return Promise.resolve();+ });+ await service.start('sess-uuid-1');+ return captured;+ };++ it('marks the session FAILED and runs the session:error hook on a terminal engine error', async () => {+ const callbacks = await startAndCapture();++ callbacks.onError?.('Failed to launch the browser process: spawn ENOENT');++ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { status: SessionStatus.FAILED });+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'session:error',+ expect.objectContaining({ reason: 'Failed to launch the browser process: spawn ENOENT' }),+ expect.objectContaining({ sessionId: 'sess-uuid-1' }),+ );+ });++ it('surfaces the failure reason via lastError when the session is FAILED', async () => {+ const callbacks = await startAndCapture();+ callbacks.onError?.('chromium missing');++ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ status: SessionStatus.FAILED }));+ const result = await service.findOne('sess-uuid-1');++ expect(result.lastError).toBe('chromium missing');+ });++ it('does not surface lastError once the session has recovered', async () => {+ const callbacks = await startAndCapture();+ callbacks.onError?.('transient failure');+ // Engine later becomes ready, which clears the stored reason.+ callbacks.onReady?.('628123', 'Tester');++ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ status: SessionStatus.READY }));+ const result = await service.findOne('sess-uuid-1');++ expect(result.lastError).toBeUndefined();+ });+ });++ // ── engine message-event webhook dispatch ─────────────────────────++ describe('engine message-event webhook dispatch', () => {+ const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));++ async function startAndCaptureCallbacks(): Promise<EngineEventCallbacks> {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');+ const calls = mockEngine.initialize.mock.calls as [EngineEventCallbacks][];+ return calls[0][0];+ }++ function dispatchedEvents(event: string): unknown[][] {+ const calls = (webhookService.dispatch as jest.Mock).mock.calls as unknown[][];+ return calls.filter(call => call[1] === event);+ }++ const makeMessage = (overrides: Partial<IncomingMessage> = {}): IncomingMessage => ({+ id: 'wa-msg-1',+ from: '[email protected]',+ to: '[email protected]',+ chatId: '[email protected]',+ body: 'hello',+ type: 'chat',+ timestamp: 1706868000,+ fromMe: false,+ isGroup: false,+ ...overrides,+ });++ it('dispatches message.sent exactly once for an outgoing (message_create) event', async () => {+ const callbacks = await startAndCaptureCallbacks();+ expect(typeof callbacks.onMessageCreate).toBe('function');++ callbacks.onMessageCreate!(makeMessage({ id: 'wa-out-1', from: '[email protected]', to: '[email protected]', fromMe: true }));+ await flush();++ const sent = dispatchedEvents('message.sent');+ expect(sent).toHaveLength(1);+ expect(sent[0][0]).toBe('sess-uuid-1');+ });++ it('does not dispatch message.sent for an incoming message_create event (fromMe=false)', async () => {+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessageCreate!(makeMessage({ fromMe: false }));+ await flush();++ expect(dispatchedEvents('message.sent')).toHaveLength(0);+ });++ it('does not dispatch message.sent for a status@broadcast (Story) post', async () => {+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessageCreate!(+ makeMessage({ id: 'wa-status', from: '[email protected]', to: 'status@broadcast', fromMe: true }),+ );+ await flush();++ expect(dispatchedEvents('message.sent')).toHaveLength(0);+ });++ it('emits the realtime WS event for an outgoing message as message.sent, not message.received', async () => {+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessageCreate!(makeMessage({ id: 'wa-out-2', from: '[email protected]', to: '[email protected]', fromMe: true }));+ await flush();++ expect(eventsGateway.emitMessageSent as jest.Mock).toHaveBeenCalledWith('sess-uuid-1', expect.anything());+ expect(eventsGateway.emitMessage as jest.Mock).not.toHaveBeenCalled();+ });++ it('dispatches message.ack but never message.sent on a message_ack event', async () => {+ const callbacks = await startAndCaptureCallbacks();+ expect(typeof callbacks.onMessageAck).toBe('function');++ callbacks.onMessageAck!('wa-out-1', 3);+ await flush();++ expect(dispatchedEvents('message.ack')).toHaveLength(1);+ expect(dispatchedEvents('message.sent')).toHaveLength(0);+ });++ it('reflects delivery on the stored message: ack=2 updates status to DELIVERED (#220)', async () => {+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessageAck!('wa-out-1', 2);+ await flush();++ expect(messageRepository.update as jest.Mock).toHaveBeenCalledWith(+ expect.objectContaining({ waMessageId: 'wa-out-1' }),+ { status: MessageStatus.DELIVERED },+ );+ });++ it('marks the stored message FAILED and dispatches message.failed on an error ack (<0) (#220)', async () => {+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessageAck!('wa-out-1', -1);+ await flush();++ expect(messageRepository.update as jest.Mock).toHaveBeenCalledWith(+ expect.objectContaining({ waMessageId: 'wa-out-1' }),+ { status: MessageStatus.FAILED },+ );+ expect(dispatchedEvents('message.failed')).toHaveLength(1);+ });++ it('does not upgrade the stored status (or emit message.failed) for a server-only ack (1)', async () => {+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessageAck!('wa-out-1', 1);+ await flush();++ expect(messageRepository.update as jest.Mock).not.toHaveBeenCalled();+ expect(dispatchedEvents('message.failed')).toHaveLength(0);+ });++ it('dispatches message.received (not message.sent) on an incoming message event', async () => {+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessage!(makeMessage({ fromMe: false }));+ await flush();++ expect(dispatchedEvents('message.received')).toHaveLength(1);+ expect(dispatchedEvents('message.sent')).toHaveLength(0);+ });++ it('dispatches the message.revoked webhook and WS event on a revoke (#152)', async () => {+ const callbacks = await startAndCaptureCallbacks();+ expect(typeof callbacks.onMessageRevoked).toBe('function');++ callbacks.onMessageRevoked!({+ id: 'wa-rev-1',+ chatId: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ type: 'revoked',+ body: '',+ timestamp: 1706868000,+ });+ await flush();++ expect(dispatchedEvents('message.revoked')).toHaveLength(1);+ expect(eventsGateway.emitMessageRevoked as jest.Mock).toHaveBeenCalledWith('sess-uuid-1', expect.anything());+ });});// ── stop ──────────────────────────────────────────────────────────@@ -330,6 +577,111 @@ describe('SessionService', () => {});});+ // ── getChats ──────────────────────────────────────────────────────++ describe('getChats', () => {+ it('should delegate to engine.getChats for a started session', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.start('sess-uuid-1');++ const chats = [{ id: '[email protected]', name: 'Alice', isGroup: false, unreadCount: 2, timestamp: 1700000000 }];+ mockEngine.getChats.mockResolvedValue(chats);++ const result = await service.getChats('sess-uuid-1');++ expect(mockEngine.getChats).toHaveBeenCalled();+ expect(result).toEqual(chats);+ });++ it('should throw BadRequestException when session is not started', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);++ await expect(service.getChats('sess-uuid-1')).rejects.toThrow(BadRequestException);+ });+ });++ // ── sendSeen (markChatRead) ───────────────────────────────────────++ describe('sendSeen', () => {+ it('should delegate to engine.sendSeen with the chatId', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.start('sess-uuid-1');+ mockEngine.sendSeen.mockResolvedValue(true);++ const result = await service.sendSeen('sess-uuid-1', '[email protected]');++ expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]');+ expect(result).toBe(true);+ });++ it('should throw BadRequestException when session is not started', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);++ await expect(service.sendSeen('sess-uuid-1', '[email protected]')).rejects.toThrow(BadRequestException);+ });+ });++ // ── onMessageRevoked (no localized string) ────────────────────────++ describe('onMessageRevoked callback', () => {+ it('persists an empty body with type "revoked" and emits no localized string', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (messageRepository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.start('sess-uuid-1');++ // Grab the callbacks object passed to engine.initialize.+ const initializeCall = mockEngine.initialize.mock.calls[0] as unknown[];+ const callbacks = initializeCall[0] as {+ onMessageRevoked: (m: { id: string; type: string; body: string }) => void;+ };++ const revoked = {+ id: 'WA_MSG_1',+ chatId: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ type: 'revoked' as const,+ body: '' as const,+ timestamp: 1700000000,+ };++ callbacks.onMessageRevoked(revoked);+ // Allow the queued microtask (repository.update().then()) to resolve.+ await Promise.resolve();+ await Promise.resolve();++ // The stored update must carry an EMPTY body and the 'revoked' type — no display string.+ expect(messageRepository.update).toHaveBeenCalledWith(+ { sessionId: 'sess-uuid-1', waMessageId: 'WA_MSG_1' },+ { body: '', type: 'revoked' },+ );++ // The structured payload emitted to clients must not contain any localized text.+ expect(eventsGateway.emitMessageRevoked).toHaveBeenCalledWith(+ 'sess-uuid-1',+ expect.objectContaining({+ id: 'WA_MSG_1',+ type: 'revoked',+ body: '',+ }),+ );+ const revokedCall = (eventsGateway.emitMessageRevoked as jest.Mock).mock.calls[0] as unknown[];+ const emittedPayload = revokedCall[1] as { body: string };+ expect(emittedPayload.body).toBe('');+ });+ });+// ── getActiveCount / isActive ─────────────────────────────────────describe('getActiveCount', () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex f888de62f..0feafb41e 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -10,13 +10,20 @@ import {import { InjectRepository, InjectDataSource } from '@nestjs/typeorm';import { Repository, In, Not, IsNull, DataSource } from 'typeorm';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 { IWhatsAppEngine, EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';+import {+ IWhatsAppEngine,+ EngineStatus,+ ChatSummary,+ IncomingMessage,+} from '../../engine/interfaces/whatsapp-engine.interface';import { createLogger } from '../../common/services/logger.service';import { EventsGateway } from '../events/events.gateway';import { WebhookService } from '../webhook/webhook.service';import { HookManager } from '../../core/hooks';+import { ackToMessageStatus, ackStatusTransitionFrom } from '../message/message-status.util';interface ReconnectState {attempts: number;@@ -31,6 +38,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// In-memory map of active engine instancesprivate engines: Map<string, IWhatsAppEngine> = new Map();+ // Transient, human-readable reason for the most recent terminal engine failure,+ // keyed by session id. Surfaced on read so the dashboard can explain a FAILED+ // status; cleared when the session re-initializes or becomes ready.+ private sessionErrors: Map<string, string> = new Map();// Reconnection state per sessionprivate reconnectStates: Map<string, ReconnectState> = new Map();@@ -38,6 +49,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconstructor(@InjectRepository(Session, 'data')private readonly sessionRepository: Repository<Session>,+ @InjectRepository(Message, 'data')+ private readonly messageRepository: Repository<Message>,@InjectDataSource('data')private readonly dataSource: DataSource,private readonly engineFactory: EngineFactory,@@ -163,9 +176,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}async findAll(): Promise<Session[]> {- return this.sessionRepository.find({+ const sessions = await this.sessionRepository.find({order: { createdAt: 'DESC' },});+ return sessions.map(session => this.attachLastError(session));}async findOne(id: string): Promise<Session> {@@ -173,6 +187,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatif (!session) {throw new NotFoundException(`Session with id '${id}' not found`);}+ return this.attachLastError(session);+ }++ /**+ * Populate the transient `lastError` field from the in-memory error map. Only a+ * FAILED session carries an error; any other status clears it so a recovered+ * session never shows a stale failure reason.+ */+ private attachLastError(session: Session): Session {+ session.lastError = session.status === SessionStatus.FAILED ? this.sessionErrors.get(session.id) : undefined;return session;}@@ -267,6 +291,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatproxyType: session.proxyType || undefined,});this.engines.set(id, engine);+ // Clear any prior failure reason before a fresh start.+ this.sessionErrors.delete(id);++ // Mark INITIALIZING before engine.initialize(): the engine drives status forward+ // (QR_READY -> AUTHENTICATING -> READY) through the callbacks below while it+ // initializes, so writing INITIALIZING afterwards would clobber that progress.+ await this.updateStatus(id, SessionStatus.INITIALIZING);await engine.initialize({onQRCode: (): void => {@@ -305,11 +336,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat},);- // Reset reconnect attempts on successful connection+ // Reset reconnect attempts and clear any stale failure reason on successconst reconnectState = this.reconnectStates.get(id);if (reconnectState) {reconnectState.attempts = 0;}+ this.sessionErrors.delete(id);void this.sessionRepository.update(id, {status: SessionStatus.READY,@@ -343,12 +375,175 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn;}+ // Persist the incoming message so the dashboard chats view can render history.+ const incoming: IncomingMessage = finalMessage;+ const metadata: Record<string, unknown> = {};+ if (incoming.media) {+ metadata.media = incoming.media;+ }+ if (incoming.quotedMessage) {+ metadata.quotedMessage = incoming.quotedMessage;+ }++ const dbMessage = this.messageRepository.create({+ sessionId: id,+ waMessageId: incoming.id,+ chatId: incoming.chatId,+ from: incoming.from,+ to: incoming.to,+ body: incoming.body,+ type: incoming.type,+ direction: incoming.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING,+ timestamp: incoming.timestamp,+ status: MessageStatus.SENT,+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,+ });++ void this.messageRepository.save(dbMessage).catch(err => {+ this.logger.error(`Failed to save incoming message ${incoming.id} to database`, String(err));+ });+// Dispatch to webhooks with potentially modified messagevoid this.webhookService.dispatch(id, 'message.received', finalMessage);// Emit real-time event to WebSocket clientsthis.eventsGateway.emitMessage(id, finalMessage);});},+ onMessageCreate: (message): void => {+ // `message_create` fires for every message the account creates, including sends composed on a+ // linked phone — which the `message`/`onMessage` event never delivers. Incoming messages are+ // already handled by `onMessage`, so only outgoing (`fromMe`) ones produce `message.sent` here.+ if (!message.fromMe) {+ return;+ }++ // Status/Story posts (`status@broadcast`) are account-created but not real conversations;+ // don't emit `message.sent` for them.+ if (message.to === 'status@broadcast' || message.chatId === 'status@broadcast') {+ return;+ }++ this.logger.debug(`Message sent to ${message.to}`, {+ sessionId: id,+ messageId: message.id,+ to: message.to,+ action: 'message_sent',+ });+ // Update last active timestamp+ void this.sessionRepository.update(id, { lastActiveAt: new Date() });+ const messageData = { ...message };++ // Execute hook for message sent - plugins can modify or stop processing+ void this.hookManager+ .execute('message:sent', messageData, {+ sessionId: id,+ source: 'Engine',+ })+ .then(({ continue: shouldContinue, data: finalMessage }) => {+ if (!shouldContinue) {+ return;+ }++ // Dispatch to webhooks with potentially modified message+ void this.webhookService.dispatch(id, 'message.sent', finalMessage);+ // Emit real-time event to WebSocket clients (as message.sent, not message.received)+ this.eventsGateway.emitMessageSent(id, finalMessage);+ });+ },+ onMessageAck: (messageId, ack): void => {+ this.logger.debug(`Message ack: ${messageId} -> ${ack}`, {+ sessionId: id,+ messageId,+ ack,+ action: 'message_ack',+ });++ // Reflect real delivery state on the stored message (#220): ack=2 -> delivered, >=3 -> read,+ // <0 -> failed. A send that never reaches ack>=2 stays SENT — visibly "not delivered".+ // The UPDATE is guarded to the allowed prior statuses so delivery state only ADVANCES: an+ // out-of-order/late ack cannot downgrade a higher status, which also makes these+ // fire-and-forget writes race-safe at the DB level.+ const status = ackToMessageStatus(ack);+ if (status) {+ void this.messageRepository+ .update({ waMessageId: messageId, status: In(ackStatusTransitionFrom(status)) }, { status })+ .then(result => {+ // affected:0 — the row was not advanced: either the send's 2nd save (which sets+ // waMessageId) hasn't committed yet, or the status is already at/above the target.+ if (result.affected === 0) {+ this.logger.debug(`Message ack ${messageId}: no status row advanced to ${status} (ack=${ack})`, {+ sessionId: id,+ messageId,+ ack,+ action: 'message_ack_noop',+ });+ }+ });+ }++ // Dispatch the delivery/read receipt to webhooks (#155). Outgoing `message.sent` is handled+ // solely by `onMessageCreate`, so the ack path deliberately does NOT emit `message.sent`.+ // `id` mirrors the field every other message.* webhook carries (and the idempotency key+ // resolver reads); `messageId` is kept for backward compatibility.+ void this.webhookService.dispatch(id, 'message.ack', { id: messageId, messageId, ack });++ // Surface delivery failures actively so consumers don't have to poll for them (#220).+ if (ack < 0) {+ void this.webhookService.dispatch(id, 'message.failed', { id: messageId, messageId, ack });+ }+ },+ onMessageRevoked: (message): void => {+ this.logger.debug(`Message revoked: ${message.id}`, {+ sessionId: id,+ messageId: message.id,+ action: 'message_revoked',+ });++ // Flag the stored message as revoked (best-effort; the message may not be in the+ // DB). The dashboard renders the localized "message deleted" text, so no display+ // string is persisted here.+ void this.messageRepository+ .update({ sessionId: id, waMessageId: message.id }, { body: '', type: 'revoked' })+ .catch(err => {+ this.logger.error(`Failed to update revoked message: ${message.id}`, String(err));+ });++ // Notify consumers regardless of whether the row existed: webhook (message.revoked+ // is a declared event) + the real-time dashboard stream.+ const revokedPayload = message as unknown as Record<string, unknown>;+ void this.webhookService.dispatch(id, 'message.revoked', revokedPayload);+ this.eventsGateway.emitMessageRevoked(id, revokedPayload);+ },+ onMessageReaction: (event): void => {+ this.logger.debug(`Message reaction received: ${event.messageId} -> ${event.reaction}`, {+ sessionId: id,+ messageId: event.messageId,+ action: 'message_reaction_received',+ });++ void this.messageRepository+ .findOne({ where: { sessionId: id, waMessageId: event.messageId } })+ .then(async msg => {+ if (!msg) return;+ const metadata = msg.metadata || {};+ const reactions = (metadata.reactions as Record<string, string>) || {};++ if (!event.reaction) {+ delete reactions[event.senderId];+ } else {+ reactions[event.senderId] = event.reaction;+ }++ metadata.reactions = reactions;+ msg.metadata = metadata;+ await this.messageRepository.save(msg);++ this.eventsGateway.emitMessageReaction(id, { ...event, reactions });+ })+ .catch(err => {+ this.logger.error(`Failed to update message reaction: ${event.messageId}`, String(err));+ });+ },onDisconnected: (reason: string): void => {this.logger.warn(`Session disconnected: ${reason}`, {sessionId: id,@@ -385,9 +580,30 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatvoid this.updateStatus(id, newStatus);}},- });+ onError: (reason: string): void => {+ this.logger.error(`Session engine failed: ${reason}`, undefined, {+ sessionId: id,+ reason,+ action: 'engine_error',+ });- await this.updateStatus(id, SessionStatus.INITIALIZING);+ // Remember the reason so findOne/findAll can surface it to the dashboard,+ // then persist the FAILED status. This is terminal — no reconnect is+ // scheduled (unlike onDisconnected), since re-scanning is required.+ this.sessionErrors.set(id, reason);++ void this.hookManager.execute(+ 'session:error',+ { reason },+ {+ sessionId: id,+ source: 'Engine',+ },+ );++ void this.updateStatus(id, SessionStatus.FAILED);+ },+ });}private scheduleReconnect(id: string, session: Session): void {@@ -501,7 +717,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn this.engines.get(id);}- async getGroups(id: string): Promise<{ id: string; name: string }[]> {+ async getGroups(id: string): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {await this.findOne(id); // Verify session existsconst engine = this.engines.get(id);@@ -513,9 +729,32 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn groups.map(g => ({id: g.id,name: g.name,+ linkedParentJID: g.linkedParentJID,}));}+ async getChats(id: string): Promise<ChatSummary[]> {+ await this.findOne(id); // Verify session exists+ const engine = this.engines.get(id);++ if (!engine) {+ throw new BadRequestException('Session is not started');+ }++ return engine.getChats();+ }++ async 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');+ }++ return engine.sendSeen(chatId);+ }+private async updateStatus(id: string, status: SessionStatus): Promise<void> {await this.sessionRepository.update(id, { status });this.logger.debug(`Session status updated to ${status}`, {diff --git a/src/modules/template/dto/index.ts b/src/modules/template/dto/index.tsnew file mode 100644index 000000000..4f6a8a930--- /dev/null+++ b/src/modules/template/dto/index.ts@@ -0,0 +1 @@+export * from './template.dto';diff --git a/src/modules/template/dto/template.dto.ts b/src/modules/template/dto/template.dto.tsnew file mode 100644index 000000000..794fb13eb--- /dev/null+++ b/src/modules/template/dto/template.dto.ts@@ -0,0 +1,102 @@+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import { IsString, IsNotEmpty, IsOptional, MaxLength } from 'class-validator';++const NAME_MAX_LENGTH = 100;+const BODY_MAX_LENGTH = 4096;+const HEADER_FOOTER_MAX_LENGTH = 1024;++export class CreateTemplateDto {+ @ApiProperty({+ description: 'Unique template name within the session',+ example: 'order-confirmation',+ maxLength: NAME_MAX_LENGTH,+ })+ @IsString()+ @IsNotEmpty()+ @MaxLength(NAME_MAX_LENGTH)+ name: string;++ @ApiProperty({+ description: 'Template body with {{variable}} placeholders',+ example: 'Hi {{customer}}, your order {{orderId}} has shipped.',+ maxLength: BODY_MAX_LENGTH,+ })+ @IsString()+ @IsNotEmpty()+ @MaxLength(BODY_MAX_LENGTH)+ body: string;++ @ApiPropertyOptional({+ description: 'Optional header text, prepended to the rendered body',+ example: 'OpenWA Store',+ maxLength: HEADER_FOOTER_MAX_LENGTH,+ })+ @IsOptional()+ @IsString()+ @MaxLength(HEADER_FOOTER_MAX_LENGTH)+ header?: string;++ @ApiPropertyOptional({+ description: 'Optional footer text, appended to the rendered body',+ example: 'Reply STOP to unsubscribe.',+ maxLength: HEADER_FOOTER_MAX_LENGTH,+ })+ @IsOptional()+ @IsString()+ @MaxLength(HEADER_FOOTER_MAX_LENGTH)+ footer?: string;+}++export class UpdateTemplateDto {+ @ApiPropertyOptional({ description: 'Template name', maxLength: NAME_MAX_LENGTH })+ @IsOptional()+ @IsString()+ @IsNotEmpty()+ @MaxLength(NAME_MAX_LENGTH)+ name?: string;++ @ApiPropertyOptional({ description: 'Template body with {{variable}} placeholders', maxLength: BODY_MAX_LENGTH })+ @IsOptional()+ @IsString()+ @IsNotEmpty()+ @MaxLength(BODY_MAX_LENGTH)+ body?: string;++ @ApiPropertyOptional({ description: 'Optional header text', maxLength: HEADER_FOOTER_MAX_LENGTH })+ @IsOptional()+ @IsString()+ @MaxLength(HEADER_FOOTER_MAX_LENGTH)+ header?: string;++ @ApiPropertyOptional({ description: 'Optional footer text', maxLength: HEADER_FOOTER_MAX_LENGTH })+ @IsOptional()+ @IsString()+ @MaxLength(HEADER_FOOTER_MAX_LENGTH)+ footer?: string;+}++export class TemplateResponseDto {+ @ApiProperty()+ id: string;++ @ApiProperty()+ sessionId: string;++ @ApiProperty()+ name: string;++ @ApiProperty()+ body: string;++ @ApiPropertyOptional({ nullable: true })+ header?: string | null;++ @ApiPropertyOptional({ nullable: true })+ footer?: string | null;++ @ApiProperty()+ createdAt: Date;++ @ApiProperty()+ updatedAt: Date;+}diff --git a/src/modules/template/entities/template.entity.ts b/src/modules/template/entities/template.entity.tsnew file mode 100644index 000000000..12ed27ff9--- /dev/null+++ b/src/modules/template/entities/template.entity.ts@@ -0,0 +1,41 @@+import {+ Entity,+ Column,+ PrimaryGeneratedColumn,+ CreateDateColumn,+ UpdateDateColumn,+ ManyToOne,+ JoinColumn,+} from 'typeorm';+import { Session } from '../../session/entities/session.entity';++@Entity('templates')+export class Template {+ @PrimaryGeneratedColumn('uuid')+ id: string;++ @Column({ type: 'uuid' })+ sessionId: string;++ @ManyToOne(() => Session, { onDelete: 'CASCADE' })+ @JoinColumn({ name: 'sessionId' })+ session: Session;++ @Column({ type: 'varchar', length: 100 })+ name: string;++ @Column({ type: 'text' })+ body: string;++ @Column({ type: 'text', nullable: true })+ header: string | null;++ @Column({ type: 'text', nullable: true })+ footer: string | null;++ @CreateDateColumn()+ createdAt: Date;++ @UpdateDateColumn()+ updatedAt: Date;+}diff --git a/src/modules/template/template.controller.ts b/src/modules/template/template.controller.tsnew file mode 100644index 000000000..17e2a4789--- /dev/null+++ b/src/modules/template/template.controller.ts@@ -0,0 +1,69 @@+import { Controller, Get, Post, Put, Delete, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiParam } from '@nestjs/swagger';+import { TemplateService } from './template.service';+import { CreateTemplateDto, UpdateTemplateDto, TemplateResponseDto } from './dto';+import { Template } from './entities/template.entity';+import { RequireRole } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';++@ApiTags('templates')+@Controller('sessions/:sessionId/templates')+export class TemplateController {+ constructor(private readonly templateService: TemplateService) {}++ @Post()+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Create a message template for the session' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({ status: 201, description: 'Template created', type: TemplateResponseDto })+ async create(@Param('sessionId') sessionId: string, @Body() dto: CreateTemplateDto): Promise<Template> {+ return this.templateService.create(sessionId, dto);+ }++ @Get()+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'List all templates for a session' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({ status: 200, description: 'List of templates', type: [TemplateResponseDto] })+ async findBySession(@Param('sessionId') sessionId: string): Promise<Template[]> {+ return this.templateService.findBySession(sessionId);+ }++ @Get(':id')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Get a template by ID' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'id', description: 'Template ID' })+ @ApiResponse({ status: 200, description: 'Template details', type: TemplateResponseDto })+ @ApiResponse({ status: 404, description: 'Template not found' })+ async findOne(@Param('sessionId') sessionId: string, @Param('id') id: string): Promise<Template> {+ return this.templateService.findOne(sessionId, id);+ }++ @Put(':id')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Update a template' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'id', description: 'Template ID' })+ @ApiResponse({ status: 200, description: 'Template updated', type: TemplateResponseDto })+ @ApiResponse({ status: 404, description: 'Template not found' })+ async update(+ @Param('sessionId') sessionId: string,+ @Param('id') id: string,+ @Body() dto: UpdateTemplateDto,+ ): Promise<Template> {+ return this.templateService.update(sessionId, id, dto);+ }++ @Delete(':id')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.NO_CONTENT)+ @ApiOperation({ summary: 'Delete a template' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'id', description: 'Template ID' })+ @ApiResponse({ status: 204, description: 'Template deleted' })+ @ApiResponse({ status: 404, description: 'Template not found' })+ async delete(@Param('sessionId') sessionId: string, @Param('id') id: string): Promise<void> {+ return this.templateService.delete(sessionId, id);+ }+}diff --git a/src/modules/template/template.module.ts b/src/modules/template/template.module.tsnew file mode 100644index 000000000..9460ccb1a--- /dev/null+++ b/src/modules/template/template.module.ts@@ -0,0 +1,13 @@+import { Module } from '@nestjs/common';+import { TypeOrmModule } from '@nestjs/typeorm';+import { Template } from './entities/template.entity';+import { TemplateService } from './template.service';+import { TemplateController } from './template.controller';++@Module({+ imports: [TypeOrmModule.forFeature([Template], 'data')],+ controllers: [TemplateController],+ providers: [TemplateService],+ exports: [TemplateService],+})+export class TemplateModule {}diff --git a/src/modules/template/template.service.spec.ts b/src/modules/template/template.service.spec.tsnew file mode 100644index 000000000..f20015f68--- /dev/null+++ b/src/modules/template/template.service.spec.ts@@ -0,0 +1,223 @@+import { Test, TestingModule } from '@nestjs/testing';+import { getRepositoryToken } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import { NotFoundException } from '@nestjs/common';+import { TemplateService } from './template.service';+import { Template } from './entities/template.entity';+import { Session } from '../session/entities/session.entity';+import { renderTemplate } from '../../common/utils/template-render';++function createMockTemplate(overrides: Partial<Template> = {}): Template {+ return {+ id: 'tpl-uuid-1',+ sessionId: 'sess-1',+ name: 'order-confirmation',+ body: 'Hi {{customer}}, order {{orderId}} shipped.',+ header: null,+ footer: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ session: undefined as unknown as Session,+ ...overrides,+ };+}++describe('TemplateService', () => {+ let service: TemplateService;+ let repository: jest.Mocked<Partial<Repository<Template>>>;++ beforeEach(async () => {+ repository = {+ find: jest.fn(),+ findOne: jest.fn(),+ create: jest.fn().mockImplementation((data: Partial<Template>) => ({ id: 'tpl-uuid-1', ...data }) as Template),+ save: jest.fn().mockImplementation((tpl: Template) => Promise.resolve(tpl)),+ remove: jest.fn().mockResolvedValue(undefined),+ };++ const module: TestingModule = await Test.createTestingModule({+ providers: [TemplateService, { provide: getRepositoryToken(Template, 'data'), useValue: repository }],+ }).compile();++ service = module.get<TemplateService>(TemplateService);+ });++ // ── create ────────────────────────────────────────────────────────++ describe('create', () => {+ it('should create a template with normalized null header/footer', async () => {+ await service.create('sess-1', { name: 'welcome', body: 'Hi {{name}}' });++ expect(repository.create).toHaveBeenCalledWith(+ expect.objectContaining({+ sessionId: 'sess-1',+ name: 'welcome',+ body: 'Hi {{name}}',+ header: null,+ footer: null,+ }),+ );+ expect(repository.save).toHaveBeenCalled();+ });++ it('should persist optional header and footer when provided', async () => {+ await service.create('sess-1', {+ name: 'promo',+ body: 'Buy now',+ header: 'OpenWA Store',+ footer: 'Reply STOP to opt out',+ });++ expect(repository.create).toHaveBeenCalledWith(+ expect.objectContaining({ header: 'OpenWA Store', footer: 'Reply STOP to opt out' }),+ );+ });+ });++ // ── findBySession ─────────────────────────────────────────────────++ describe('findBySession', () => {+ it('should list templates for a session ordered by createdAt DESC', async () => {+ (repository.find as jest.Mock).mockResolvedValue([createMockTemplate()]);++ const result = await service.findBySession('sess-1');++ expect(repository.find).toHaveBeenCalledWith({ where: { sessionId: 'sess-1' }, order: { createdAt: 'DESC' } });+ expect(result).toHaveLength(1);+ });+ });++ // ── findOne ───────────────────────────────────────────────────────++ describe('findOne', () => {+ it('should return a template scoped to the session', async () => {+ const template = createMockTemplate();+ (repository.findOne as jest.Mock).mockResolvedValue(template);++ const result = await service.findOne('sess-1', 'tpl-uuid-1');++ expect(repository.findOne).toHaveBeenCalledWith({ where: { id: 'tpl-uuid-1', sessionId: 'sess-1' } });+ expect(result).toBe(template);+ });++ it('should throw NotFoundException when the template does not exist', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(null);++ await expect(service.findOne('sess-1', 'missing')).rejects.toThrow(NotFoundException);+ });+ });++ // ── resolve ───────────────────────────────────────────────────────++ describe('resolve', () => {+ it('should resolve by templateId', async () => {+ const template = createMockTemplate();+ (repository.findOne as jest.Mock).mockResolvedValue(template);++ const result = await service.resolve('sess-1', { templateId: 'tpl-uuid-1' });++ expect(repository.findOne).toHaveBeenCalledWith({ where: { id: 'tpl-uuid-1', sessionId: 'sess-1' } });+ expect(result).toBe(template);+ });++ it('should resolve by templateName', async () => {+ const template = createMockTemplate();+ (repository.findOne as jest.Mock).mockResolvedValue(template);++ const result = await service.resolve('sess-1', { templateName: 'order-confirmation' });++ expect(repository.findOne).toHaveBeenCalledWith({ where: { name: 'order-confirmation', sessionId: 'sess-1' } });+ expect(result).toBe(template);+ });++ it('should throw NotFoundException when name does not resolve', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(null);++ await expect(service.resolve('sess-1', { templateName: 'nope' })).rejects.toThrow(NotFoundException);+ });++ it('should throw NotFoundException when neither id nor name is provided', async () => {+ await expect(service.resolve('sess-1', {})).rejects.toThrow(NotFoundException);+ });+ });++ // ── update ────────────────────────────────────────────────────────++ describe('update', () => {+ it('should update only the provided fields', async () => {+ const template = createMockTemplate();+ (repository.findOne as jest.Mock).mockResolvedValue(template);++ await service.update('sess-1', 'tpl-uuid-1', { body: 'Updated body' });++ expect(repository.save).toHaveBeenCalledWith(+ expect.objectContaining({ body: 'Updated body', name: template.name }),+ );+ });++ it('should throw NotFoundException for an unknown template', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(null);++ await expect(service.update('sess-1', 'missing', { body: 'x' })).rejects.toThrow(NotFoundException);+ });+ });++ // ── delete ────────────────────────────────────────────────────────++ describe('delete', () => {+ it('should remove an existing template', async () => {+ const template = createMockTemplate();+ (repository.findOne as jest.Mock).mockResolvedValue(template);++ await service.delete('sess-1', 'tpl-uuid-1');++ expect(repository.remove).toHaveBeenCalledWith(template);+ });++ it('should throw NotFoundException when deleting a missing template', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(null);++ await expect(service.delete('sess-1', 'missing')).rejects.toThrow(NotFoundException);+ });+ });+});++// ── renderTemplate (shared utility) ───────────────────────────────────++describe('renderTemplate', () => {+ it('should substitute known {{key}} placeholders', () => {+ const result = renderTemplate('Hi {{name}}, your code is {{code}}.', { name: 'Alice', code: '1234' });+ expect(result).toBe('Hi Alice, your code is 1234.');+ });++ it('should leave unmatched placeholders literal', () => {+ const result = renderTemplate('Hi {{name}}, ref {{missing}}.', { name: 'Bob' });+ expect(result).toBe('Hi Bob, ref {{missing}}.');+ });++ it('should tolerate surrounding whitespace inside the braces', () => {+ const result = renderTemplate('Hello {{ name }}', { name: 'Carol' });+ expect(result).toBe('Hello Carol');+ });++ it('should default to an empty vars map and leave all placeholders literal', () => {+ expect(renderTemplate('Order {{id}}')).toBe('Order {{id}}');+ });++ it('should treat a null variable value as missing (left literal)', () => {+ const result = renderTemplate('Hi {{name}}', { name: null as unknown as string });+ expect(result).toBe('Hi {{name}}');+ });++ it('should coerce non-string values to string', () => {+ const result = renderTemplate('Count: {{n}}', { n: 7 as unknown as string });+ expect(result).toBe('Count: 7');+ });++ it('should render a body at the maximum supported length without truncation', () => {+ // The DTO caps body length at 4096; the renderer itself imposes no cap and+ // must return content of the same magnitude when no placeholders are present.+ const body = 'x'.repeat(4096);+ expect(renderTemplate(body, {})).toHaveLength(4096);+ });+});diff --git a/src/modules/template/template.service.ts b/src/modules/template/template.service.tsnew file mode 100644index 000000000..705fe8ed3--- /dev/null+++ b/src/modules/template/template.service.ts@@ -0,0 +1,84 @@+import { Injectable, NotFoundException } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import { Template } from './entities/template.entity';+import { CreateTemplateDto, UpdateTemplateDto } from './dto';+import { createLogger } from '../../common/services/logger.service';++@Injectable()+export class TemplateService {+ private readonly logger = createLogger('TemplateService');++ constructor(+ @InjectRepository(Template, 'data')+ private readonly templateRepository: Repository<Template>,+ ) {}++ async create(sessionId: string, dto: CreateTemplateDto): Promise<Template> {+ const template = this.templateRepository.create({+ sessionId,+ name: dto.name,+ body: dto.body,+ header: dto.header ?? null,+ footer: dto.footer ?? null,+ });++ const saved = await this.templateRepository.save(template);+ this.logger.log('Template created', { sessionId, templateId: saved.id, name: saved.name });+ return saved;+ }++ async findBySession(sessionId: string): Promise<Template[]> {+ return this.templateRepository.find({+ where: { sessionId },+ order: { createdAt: 'DESC' },+ });+ }++ async findOne(sessionId: string, id: string): Promise<Template> {+ const template = await this.templateRepository.findOne({ where: { id, sessionId } });+ if (!template) {+ throw new NotFoundException(`Template with id '${id}' not found`);+ }+ return template;+ }++ /**+ * Resolve a template for a session by id or by name. Throws NotFoundException+ * when neither identifier matches. Used by the send-template message flow.+ */+ async resolve(sessionId: string, identifier: { templateId?: string; templateName?: string }): Promise<Template> {+ const { templateId, templateName } = identifier;++ if (templateId) {+ return this.findOne(sessionId, templateId);+ }++ if (templateName) {+ const template = await this.templateRepository.findOne({ where: { name: templateName, sessionId } });+ if (!template) {+ throw new NotFoundException(`Template with name '${templateName}' not found`);+ }+ return template;+ }++ throw new NotFoundException('Either templateId or templateName must be provided');+ }++ async update(sessionId: string, id: string, dto: UpdateTemplateDto): Promise<Template> {+ const template = await this.findOne(sessionId, id);++ if (dto.name !== undefined) template.name = dto.name;+ if (dto.body !== undefined) template.body = dto.body;+ if (dto.header !== undefined) template.header = dto.header;+ if (dto.footer !== undefined) template.footer = dto.footer;++ return this.templateRepository.save(template);+ }++ async delete(sessionId: string, id: string): Promise<void> {+ const template = await this.findOne(sessionId, id);+ await this.templateRepository.remove(template);+ this.logger.log('Template deleted', { sessionId, templateId: id });+ }+}diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex e25b0760d..2523a4071 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -5,6 +5,7 @@ export const WEBHOOK_EVENTS = ['message.received','message.sent','message.ack',+ 'message.failed','message.revoked','session.status','session.qr',diff --git a/src/modules/webhook/utils/idempotency.util.ts b/src/modules/webhook/utils/idempotency.util.tsindex ff6c862d7..8df9b36fd 100644--- a/src/modules/webhook/utils/idempotency.util.ts+++ b/src/modules/webhook/utils/idempotency.util.ts@@ -41,6 +41,9 @@ export function generateIdempotencyKey(event: string, data: Record<string, unkno// Message ID + ack status together are uniquereturn `ack_${toStr(data.id ?? data.messageId)}_${toStr(data.ack, '0')}`;+ case 'message.failed':+ return `failed_${toStr(data.id ?? data.messageId)}_${toStr(data.ack, '0')}`;+case 'message.revoked':return `rev_${toStr(data.id ?? data.messageId)}`;diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex d7787443f..34d5c4a6e 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -10,6 +10,7 @@ import { CreateWebhookDto, UpdateWebhookDto } from './dto';import { createLogger } from '../../common/services/logger.service';import { QUEUE_NAMES } from '../queue/queue-names';import { generateIdempotencyKey, generateDeliveryId } from './utils/idempotency.util';+import { assertSafeWebhookUrl, isSsrfProtectionEnabled } from '../../common/security/ssrf-guard';import { HookManager } from '../../core/hooks';export interface WebhookPayload {@@ -133,6 +134,9 @@ export class WebhookService {}try {+ if (isSsrfProtectionEnabled()) {+ await assertSafeWebhookUrl(webhook.url);+ }const response = await fetch(webhook.url, {method: 'POST',headers,@@ -315,6 +319,9 @@ export class WebhookService {}try {+ if (isSsrfProtectionEnabled()) {+ await assertSafeWebhookUrl(webhook.url);+ }const response = await fetch(webhook.url, {method: 'POST',headers,diff --git a/src/plugins/engines/whatsapp-web-js/index.spec.ts b/src/plugins/engines/whatsapp-web-js/index.spec.tsnew file mode 100644index 000000000..d49f3a147--- /dev/null+++ b/src/plugins/engines/whatsapp-web-js/index.spec.ts@@ -0,0 +1,46 @@+jest.mock('../../../engine/adapters/whatsapp-web-js.adapter', () => ({+ WhatsAppWebJsAdapter: jest.fn().mockImplementation((config: unknown) => ({ config })),+}));++import { WhatsAppWebJsPlugin } from './index';+import { WhatsAppWebJsAdapter } from '../../../engine/adapters/whatsapp-web-js.adapter';++describe('WhatsAppWebJsPlugin.createEngine (#219)', () => {+ beforeEach(() => {+ (WhatsAppWebJsAdapter as unknown as jest.Mock).mockClear();+ });++ it('prefers per-call config over context/defaults and threads executablePath', () => {+ const plugin = new WhatsAppWebJsPlugin();++ plugin.createEngine({+ sessionId: 'sess-1',+ sessionDataPath: '/data/sessions',+ headless: false,+ puppeteerArgs: ['--single-process'],+ executablePath: '/usr/bin/chromium',+ });++ expect(WhatsAppWebJsAdapter).toHaveBeenCalledWith(+ expect.objectContaining({+ sessionId: 'sess-1',+ sessionDataPath: '/data/sessions',+ puppeteer: { headless: false, args: ['--single-process'], executablePath: '/usr/bin/chromium' },+ }),+ );+ });++ it('falls back to safe defaults when no config is supplied', () => {+ const plugin = new WhatsAppWebJsPlugin();++ plugin.createEngine({ sessionId: 'sess-2' });++ expect(WhatsAppWebJsAdapter).toHaveBeenCalledWith(+ expect.objectContaining({+ sessionId: 'sess-2',+ sessionDataPath: './data/sessions',+ puppeteer: { headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: undefined },+ }),+ );+ });+});diff --git a/src/plugins/engines/whatsapp-web-js/index.ts b/src/plugins/engines/whatsapp-web-js/index.tsindex a2420c51e..1da371397 100644--- a/src/plugins/engines/whatsapp-web-js/index.ts+++ b/src/plugins/engines/whatsapp-web-js/index.ts@@ -11,6 +11,7 @@ export interface WhatsAppWebJsConfig {sessionDataPath?: string;headless?: boolean;puppeteerArgs?: string[];+ executablePath?: string;}export class WhatsAppWebJsPlugin implements IEnginePlugin {@@ -35,12 +36,21 @@ export class WhatsAppWebJsPlugin implements IEnginePlugin {createEngine(config: Record<string, unknown>): IWhatsAppEngine {const sessionId = config.sessionId as string;- const sessionDataPath = (this.context?.config.sessionDataPath as string) ?? './data/sessions';- const headless = (this.context?.config.headless as boolean) ?? true;- const puppeteerArgs = (this.context?.config.puppeteerArgs as string[]) ?? [- '--no-sandbox',- '--disable-setuid-sandbox',- ];+ // Prefer the per-call config resolved by EngineFactory (from ConfigService);+ // fall back to any plugin-level context config, then to safe defaults. The+ // built-in plugin registers with an empty context config, so without the+ // per-call values sessionDataPath/headless/executablePath would silently+ // fall back to relative-path defaults and ignore the environment.+ const sessionDataPath =+ (config.sessionDataPath as string | undefined) ??+ (this.context?.config.sessionDataPath as string | undefined) ??+ './data/sessions';+ const headless =+ (config.headless as boolean | undefined) ?? (this.context?.config.headless as boolean | undefined) ?? true;+ const puppeteerArgs = (config.puppeteerArgs as string[] | undefined) ??+ (this.context?.config.puppeteerArgs as string[] | undefined) ?? ['--no-sandbox', '--disable-setuid-sandbox'];+ const executablePath =+ (config.executablePath as string | undefined) ?? (this.context?.config.executablePath as string | undefined);const proxyUrl = config.proxyUrl as string | undefined;const proxyType = config.proxyType as 'http' | 'https' | 'socks4' | 'socks5' | undefined;@@ -51,6 +61,7 @@ export class WhatsAppWebJsPlugin implements IEnginePlugin {puppeteer: {headless,args: puppeteerArgs,+ executablePath,},proxy: proxyUrl? {