Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

release: v0.7.0 — plugin contract, reliability, and dashboard polish (#448)

Yudhi Armyndharis90a8d95ec2df
diff --git a/.gitignore b/.gitignore
index 3ea005ef3..2ba34d0e2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -76,3 +76,4 @@ uploads/
docs/plans/
CLAUDE.md
_docs/
+.superpowers/
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b762a4fba..ab483aa63 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [0.7.0] - 2026-06-23
+
> **v0.7 — plugin-contract expansion.** Richer plugin config (declarative + sandboxed-iframe editors),
> per-session activation and config, SSRF-guarded outbound HTTP, and the removal of the bundled
> reference extensions in favour of the marketplace. ⚠️ See the **Removed** note before upgrading.
@@ -18,6 +20,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Plugins: **per-session config overrides**. A session-scoped plugin can carry per-session config on top of its base (`'*'`) config via `PUT /plugins/:id/config/:sessionId`; `ctx.config` (read inside a hook) is the override shallow-merged over the base for the firing session, resolved race-safely via `AsyncLocalStorage` for both in-process and sandboxed plugins. Overrides are secret-redacted per slice on the API and survive a restart. (#441)
- Plugins: per-session activation. A session-scoped plugin can now be activated for all numbers (`*`) or an explicit set of sessions via `PUT /plugins/:id/sessions`, and only receives hook events for the sessions it is active for (enforced at delivery). A plugin declares `sessionScoped` in its manifest (default `true`); a global plugin (`false`, e.g. a metrics logger) always runs. The active set is surfaced on the plugin API and survives a restart. (#438)
- Plugins: a new `ctx.net.fetch` capability lets a sandboxed plugin make outbound HTTP through the host's SSRF guard (resolve-once-pin, redirects refused), gated by a `net:fetch` permission plus a manifest `net.allow` host allowlist (`host:port`, bare `host`, or `*` for any public host; internal IPs are always blocked). Responses are bounded by a timeout and a streamed size cap. (#437)
+- Chats: opening a conversation now shows its recent history. The dashboard backfills messages directly from WhatsApp when the gateway has none stored yet and merges them with locally-persisted messages, so a freshly connected session shows the conversation instead of an empty thread.
+- Engine (whatsapp-web.js): a reconnect that stalls mid-authentication now self-heals — the stale local auth is cleared and a fresh QR pairing is started — and the WhatsApp Web build can be pinned via `WWEBJS_WEB_VERSION` for environments where the auto-selected build drifts.
+- Dashboard: a searchable plugin catalog, audit-log CSV export across all pages (not just the current view), the running version shown in the sidebar, and an engine-aware engine-configuration dialog (Baileys no longer shows Puppeteer-only fields).
+
+### Changed
+
+- Dashboard, small screens: the chat view is now a single-pane list → conversation flow with a back control instead of a cramped two-pane; page headers place the description directly under the title; and keyboard focus is a consistent, cross-browser, keyboard-only ring. Plus assorted copy and empty-state refinements.
+- Plugins (install): install-from-URL / catalog downloads now follow CDN redirects safely — each hop is re-validated through the SSRF guard — so plugins published on GitHub Releases install correctly.
### Removed
@@ -27,6 +37,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Plugins: an operator's per-session activation (and now per-session config) was silently dropped from the on-disk registry on the second restart, because the registry entry was rebuilt on each load without carrying those fields. Both are now preserved across restarts. (#441)
- Docker: the multi-arch image build failed on `linux/arm64` (`Cannot find module lightningcss.linux-arm64-gnu.node`) — the builder stage was QEMU-emulated per target and the emulated arm64 install couldn't fetch lightningcss's (Vite's native CSS minifier) arm64 binary. The builder, which only produces arch-independent artifacts, is now pinned to `$BUILDPLATFORM` so it runs natively; per-arch runtime deps still install in the target-platform stage. Restores `linux/arm64` GHCR publishing.
+- Inbound media is now size-capped before the full attachment is buffered into memory, on both engines, and concurrent inbound media downloads are bounded — lowering peak memory under bursty load.
+- Plugins: composite (object/array) config fields marked `secret` are now fully masked when read back; plugin storage files and directories are created with owner-only permissions; and several runtime robustness fixes (timeout, validation, and error handling) in the sandbox and installer.
+
+### Security
+
+- Session scope is now enforced on the session-statistics overview and on per-session plugin activation, so an API key restricted to specific sessions can no longer read or change state for sessions outside its scope.
## [0.6.2] - 2026-06-23
diff --git a/dashboard/package-lock.json b/dashboard/package-lock.json
index 9bee14aba..6ef355e67 100644
--- a/dashboard/package-lock.json
+++ b/dashboard/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "dashboard",
- "version": "0.6.2",
+ "version": "0.7.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dashboard",
- "version": "0.6.2",
+ "version": "0.7.0",
"dependencies": {
"@tanstack/react-query": "^5.101.0",
"@tanstack/react-table": "^8.21.3",
diff --git a/dashboard/package.json b/dashboard/package.json
index 3d8ab9962..56f3e04c4 100644
--- a/dashboard/package.json
+++ b/dashboard/package.json
@@ -1,7 +1,7 @@
{
"name": "dashboard",
"private": true,
- "version": "0.6.2",
+ "version": "0.7.0",
"type": "module",
"scripts": {
"dev": "vite",
diff --git a/dashboard/src/components/Layout.css b/dashboard/src/components/Layout.css
index 4c2fd6da8..005b42d3c 100644
--- a/dashboard/src/components/Layout.css
+++ b/dashboard/src/components/Layout.css
@@ -70,6 +70,15 @@
color: var(--text-muted);
}
+.brand-version {
+ font-size: 0.625rem;
+ font-weight: 500;
+ letter-spacing: 0.02em;
+ color: var(--text-muted);
+ opacity: 0.7;
+ margin-top: 1px;
+}
+
/* Collapse Toggle Button - Circular design at edge */
.collapse-toggle {
position: absolute;
@@ -193,9 +202,7 @@
height: 24px;
flex-shrink: 0;
border-radius: 999px;
- background:
- radial-gradient(circle at 70% 25%, rgba(255, 255, 255, 0.8), transparent 24%),
- var(--swatch-color);
+ background: radial-gradient(circle at 70% 25%, rgba(255, 255, 255, 0.8), transparent 24%), var(--swatch-color);
color: white;
box-shadow:
0 0 0 2px var(--bg-white),
@@ -322,9 +329,7 @@
height: 34px;
flex-shrink: 0;
border-radius: 999px;
- background:
- linear-gradient(135deg, rgba(255, 255, 255, 0.65), transparent 42%),
- var(--swatch-color);
+ background: linear-gradient(135deg, rgba(255, 255, 255, 0.65), transparent 42%), var(--swatch-color);
box-shadow:
inset 0 0 0 1px rgba(255, 255, 255, 0.35),
0 0 0 4px color-mix(in srgb, var(--swatch-color) 13%, transparent);
@@ -402,9 +407,7 @@
width: 20px;
height: 20px;
border-radius: 999px;
- background:
- linear-gradient(135deg, rgba(255, 255, 255, 0.6), transparent 45%),
- var(--swatch-color);
+ background: linear-gradient(135deg, rgba(255, 255, 255, 0.6), transparent 45%), var(--swatch-color);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.35);
}
@@ -575,35 +578,35 @@
}
/* ==================== RTL support ==================== */
-[dir="rtl"] .sidebar {
+[dir='rtl'] .sidebar {
border-right: none;
border-left: 1px solid var(--border);
}
-[dir="rtl"] .collapse-toggle {
+[dir='rtl'] .collapse-toggle {
right: auto;
left: -14px;
}
-[dir="rtl"] .collapse-toggle svg {
+[dir='rtl'] .collapse-toggle svg {
transform: scaleX(-1);
}
-[dir="rtl"] .language-menu-item {
+[dir='rtl'] .language-menu-item {
text-align: right;
}
-[dir="rtl"] .sidebar.collapsed .language-menu-list {
+[dir='rtl'] .sidebar.collapsed .language-menu-list {
right: calc(100% + 0.5rem);
left: auto;
}
-[dir="rtl"] .sidebar.collapsed .appearance-menu-list {
+[dir='rtl'] .sidebar.collapsed .appearance-menu-list {
right: calc(100% + 0.5rem);
left: auto;
}
-[dir="rtl"] .main-content {
+[dir='rtl'] .main-content {
margin-left: 0;
margin-right: 260px;
transition:
@@ -611,13 +614,13 @@
width 0.3s ease;
}
-[dir="rtl"] .main-content.expanded {
+[dir='rtl'] .main-content.expanded {
margin-right: 72px;
}
@media (max-width: 768px) {
- [dir="rtl"] .main-content,
- [dir="rtl"] .main-content.mobile {
+ [dir='rtl'] .main-content,
+ [dir='rtl'] .main-content.mobile {
margin-right: 0;
}
}
diff --git a/dashboard/src/components/Layout.tsx b/dashboard/src/components/Layout.tsx
index 96afc5ac5..191e5a9a4 100644
--- a/dashboard/src/components/Layout.tsx
+++ b/dashboard/src/components/Layout.tsx
@@ -162,7 +162,7 @@ export function Layout({ onLogout, userRole }: LayoutProps) {
{!isCollapsed && (
<div className="sidebar-brand">
<span className="brand-name">{t('common.appName')}</span>
- <span className="brand-subtitle">{t('common.appSubtitle')}</span>
+ <span className="brand-version">v{__APP_VERSION__}</span>
</div>
)}
</div>
@@ -174,9 +174,17 @@ export function Layout({ onLogout, userRole }: LayoutProps) {
title={isCollapsed ? t('common.expand') : t('common.collapse')}
aria-label={isCollapsed ? t('common.expand') : t('common.collapse')}
>
- {isCollapsed
- ? (isRtl ? <ChevronLeft size={16} /> : <ChevronRight size={16} />)
- : (isRtl ? <ChevronRight size={16} /> : <ChevronLeft size={16} />)}
+ {isCollapsed ? (
+ isRtl ? (
+ <ChevronLeft size={16} />
+ ) : (
+ <ChevronRight size={16} />
+ )
+ ) : isRtl ? (
+ <ChevronRight size={16} />
+ ) : (
+ <ChevronLeft size={16} />
+ )}
</button>
)}
diff --git a/dashboard/src/components/PageHeader.css b/dashboard/src/components/PageHeader.css
index a3f91a2e2..040409420 100644
--- a/dashboard/src/components/PageHeader.css
+++ b/dashboard/src/components/PageHeader.css
@@ -3,22 +3,27 @@
Consistent header styling for all pages
============================================= */
+/* Grid so the three regions can re-order responsively: on desktop the title and actions share
+ the top row with the subtitle beneath; on mobile the subtitle follows the title directly and
+ the actions drop to the bottom (description should follow the title, not the call-to-action). */
.page-header {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ grid-template-areas:
+ 'title actions'
+ 'subtitle subtitle';
+ align-items: center;
+ column-gap: 1rem;
margin-bottom: 1.5rem;
width: 100%;
}
-.page-header__top {
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: 1rem;
-}
-
.page-header__title-group {
+ grid-area: title;
display: flex;
align-items: center;
gap: 0.75rem;
+ min-width: 0;
}
.page-header__title-group h1 {
@@ -31,12 +36,15 @@
}
.page-header__actions {
+ grid-area: actions;
+ justify-self: end;
display: flex;
align-items: center;
gap: 0.75rem;
}
.page-header__subtitle {
+ grid-area: subtitle;
margin: 0;
margin-top: 0.5rem; /* Consistent 8px gap from title row */
font-size: 0.9375rem;
@@ -44,11 +52,15 @@
line-height: 1.5;
}
-/* Mobile Responsive */
+/* Mobile Responsive: stack as title -> subtitle -> actions */
@media (max-width: 768px) {
- .page-header__top {
- flex-wrap: wrap;
- gap: 0.75rem;
+ .page-header {
+ grid-template-columns: 1fr;
+ grid-template-areas:
+ 'title'
+ 'subtitle'
+ 'actions';
+ column-gap: 0;
}
.page-header__title-group h1 {
@@ -56,7 +68,8 @@
}
.page-header__actions {
- flex-shrink: 0;
+ justify-self: stretch;
+ margin-top: 0.25rem;
}
.page-header__subtitle {
@@ -65,15 +78,6 @@
}
@media (max-width: 480px) {
- .page-header__top {
- flex-direction: column;
- align-items: flex-start;
- }
-
- .page-header__actions {
- width: 100%;
- }
-
.page-header__actions > button,
.page-header__actions > .btn-primary,
.page-header__actions > .btn-secondary {
diff --git a/dashboard/src/components/PageHeader.tsx b/dashboard/src/components/PageHeader.tsx
index a4384c5ac..34f7553a0 100644
--- a/dashboard/src/components/PageHeader.tsx
+++ b/dashboard/src/components/PageHeader.tsx
@@ -27,13 +27,11 @@ interface PageHeaderProps {
export function PageHeader({ title, subtitle, badge, actions }: PageHeaderProps) {
return (
<header className="page-header">
- <div className="page-header__top">
- <div className="page-header__title-group">
- <h1>{title}</h1>
- {badge && <span className="page-header__badge">{badge}</span>}
- </div>
- {actions && <div className="page-header__actions">{actions}</div>}
+ <div className="page-header__title-group">
+ <h1>{title}</h1>
+ {badge && <span className="page-header__badge">{badge}</span>}
</div>
+ {actions && <div className="page-header__actions">{actions}</div>}
{subtitle && <p className="page-header__subtitle">{subtitle}</p>}
</header>
);
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index d4c26295b..a88b5ca1b 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -105,7 +105,7 @@
"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.",
+ "placeholderDesc": "Choose a conversation to read and reply.",
"deleteConfirm": "Delete this message for everyone?",
"messageDeleted": "🚫 This message was deleted",
"errors": {
@@ -594,11 +594,11 @@
"disabled": "Disabled"
},
"restart": {
- "idleTitle": "⚙️ Configuration Saved",
- "restartingTitle": "🔄 Restarting Server...",
- "waitingTitle": "⏳ Please Wait...",
- "successTitle": "✅ Server Ready",
- "errorTitle": "❌ Restart Failed",
+ "idleTitle": "Configuration saved",
+ "restartingTitle": "Restarting server…",
+ "waitingTitle": "Please wait…",
+ "successTitle": "Server ready",
+ "errorTitle": "Restart failed",
"idleDesc": "Configuration has been saved to <code>.env.generated</code>.<br/>A server restart is required to apply the changes.",
"later": "Restart Later",
"now": "Restart Now",
@@ -633,10 +633,10 @@
"install": "Install plugin",
"uninstall": "Uninstall",
"uninstallConfirm": "Uninstall \"{{name}}\"? This deletes its files.",
- "engineSwitchHint": "Set as the active engine in Settings, then restart",
+ "engineSwitchHint": "To switch the active engine, set ENGINE_TYPE in the environment and restart the server",
"empty": {
- "title": "No Plugins Found",
- "description": "Install plugins to extend OpenWA functionality"
+ "title": "No plugins installed",
+ "description": "Install a plugin to extend what OpenWA can do."
},
"config": {
"title": "Configure {{name}}",
diff --git a/dashboard/src/index.css b/dashboard/src/index.css
index 694be2aa3..a18a136d3 100644
--- a/dashboard/src/index.css
+++ b/dashboard/src/index.css
@@ -7,17 +7,16 @@
font-weight: 400;
}
-html[lang="he"],
-html[dir="rtl"] {
+html[lang='he'],
+html[dir='rtl'] {
font-family: 'Heebo', 'Rubik', 'Noto Sans Hebrew', 'Segoe UI', Arial, sans-serif;
}
-html[lang="ar"] {
+html[lang='ar'] {
font-family: 'Noto Sans Arabic', 'Cairo', 'Tajawal', 'Segoe UI', Arial, sans-serif;
}
:root {
-
color-scheme: light dark;
color: var(--text-primary);
background-color: var(--bg-light);
@@ -81,9 +80,16 @@ button {
button:hover {
border-color: #646cff;
}
-button:focus,
-button:focus-visible {
- outline: 4px auto -webkit-focus-ring-color;
+/* Visible keyboard focus — cross-browser and keyboard-only, so the ring guides Tab navigation
+ without flashing on every mouse click. */
+button:focus-visible,
+a:focus-visible,
+[tabindex]:focus-visible {
+ outline: 2px solid var(--primary, #25d366);
+ outline-offset: 2px;
+}
+button:focus:not(:focus-visible) {
+ outline: none;
}
@media (prefers-color-scheme: light) {
@@ -271,6 +277,9 @@ select:disabled {
/* Secondary Button */
.btn-secondary {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
padding: 0.75rem 1.25rem;
background: var(--bg-light, #f8fafc);
color: var(--text-secondary, #64748b);
@@ -315,51 +324,51 @@ code {
/* RTL / Hebrew direction support */
/* Keep code, technical identifiers, and numbers LTR even inside RTL containers */
-[dir="rtl"] code,
-[dir="rtl"] .mono,
-[dir="rtl"] pre {
+[dir='rtl'] code,
+[dir='rtl'] .mono,
+[dir='rtl'] pre {
direction: ltr;
text-align: left;
unicode-bidi: embed;
}
/* Modal footer: actions should align to the start of the writing direction */
-[dir="rtl"] .modal-footer {
+[dir='rtl'] .modal-footer {
justify-content: flex-end;
flex-direction: row-reverse;
}
/* Select dropdown caret on the opposite side */
-[dir="rtl"] select {
+[dir='rtl'] select {
padding: 0.75rem 1rem 0.75rem 2.5rem;
background-position: left 0.75rem center;
}
/* Inputs in modals: text aligns naturally */
-[dir="rtl"] .modal-body input,
-[dir="rtl"] .modal-body textarea,
-[dir="rtl"] input[type="text"],
-[dir="rtl"] input[type="url"],
-[dir="rtl"] input[type="password"],
-[dir="rtl"] input[type="number"],
-[dir="rtl"] textarea {
+[dir='rtl'] .modal-body input,
+[dir='rtl'] .modal-body textarea,
+[dir='rtl'] input[type='text'],
+[dir='rtl'] input[type='url'],
+[dir='rtl'] input[type='password'],
+[dir='rtl'] input[type='number'],
+[dir='rtl'] textarea {
text-align: right;
}
/* URLs, emails, phones — force LTR even inside RTL */
-[dir="rtl"] input[type="url"],
-[dir="rtl"] input[type="email"],
-[dir="rtl"] input[type="tel"] {
+[dir='rtl'] input[type='url'],
+[dir='rtl'] input[type='email'],
+[dir='rtl'] input[type='tel'] {
direction: ltr;
text-align: left;
}
-[dir="rtl"] .page-header__top {
+[dir='rtl'] .page-header__top {
flex-direction: row-reverse;
}
/* Toast container — slide in from the opposite side */
-[dir="rtl"] .toast-container {
+[dir='rtl'] .toast-container {
right: auto;
left: 1rem;
}
@@ -416,4 +425,3 @@ code {
overflow-y: auto;
}
}
-
diff --git a/dashboard/src/pages/ApiKeys.css b/dashboard/src/pages/ApiKeys.css
index c2522a5fc..a0a6597db 100644
--- a/dashboard/src/pages/ApiKeys.css
+++ b/dashboard/src/pages/ApiKeys.css
@@ -1,14 +1,14 @@
-.api-keys-page {
+.api-keys-page{
padding: 2rem;
width: 100%;
box-sizing: border-box;
}
-.page-header {
+.api-keys-page .page-header{
margin-bottom: 2rem;
}
-.header-content {
+.api-keys-page .header-content{
display: flex;
justify-content: space-between;
align-items: center;
@@ -16,7 +16,7 @@
/* H1 inherited from global */
-.btn-primary {
+.api-keys-page .btn-primary{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -31,17 +31,17 @@
transition: background 0.2s;
}
-.btn-primary:hover {
+.api-keys-page .btn-primary:hover{
background: var(--primary-hover);
}
-.api-keys-content {
+.api-keys-page .api-keys-content{
display: flex;
flex-direction: column;
gap: 1.5rem;
}
-.keys-table-container {
+.api-keys-page .keys-table-container{
background: var(--bg-white);
border-radius: 12px;
box-shadow: var(--shadow-sm);
@@ -50,14 +50,14 @@
overflow-x: auto;
}
-.keys-table {
+.api-keys-page .keys-table{
width: 100%;
font-size: 0.875rem;
border-collapse: collapse;
}
/* Table header and row styling */
-.keys-table thead tr.table-row.header th {
+.api-keys-page .keys-table thead tr.table-row.header th{
background: var(--bg-light);
font-size: 0.7rem;
font-weight: 700;
@@ -69,41 +69,41 @@
text-align: left;
}
-.keys-table tbody tr.table-row td {
+.api-keys-page .keys-table tbody tr.table-row td{
padding: 1.125rem 1.5rem;
border-bottom: 1px solid var(--border);
vertical-align: middle;
}
-.keys-table tbody tr.table-row:last-child td {
+.api-keys-page .keys-table tbody tr.table-row:last-child td{
border-bottom: none;
}
-.keys-table tbody tr.table-row:hover {
+.api-keys-page .keys-table tbody tr.table-row:hover{
background: rgba(37, 211, 102, 0.05);
}
-.keys-table tbody tr.table-row:nth-child(even) {
+.api-keys-page .keys-table tbody tr.table-row:nth-child(even){
background: rgba(0, 0, 0, 0.02);
}
-.keys-table tbody tr.table-row:nth-child(even):hover {
+.api-keys-page .keys-table tbody tr.table-row:nth-child(even):hover{
background: rgba(37, 211, 102, 0.05);
}
-.name-cell {
+.api-keys-page .name-cell{
font-weight: 500;
color: var(--text-primary);
white-space: nowrap;
}
-.key-cell {
+.api-keys-page .key-cell{
display: flex;
align-items: center;
gap: 0.5rem;
}
-.key-cell code {
+.api-keys-page .key-cell code{
font-size: 0.8125rem;
color: var(--text-secondary);
background: var(--bg-light);
@@ -113,7 +113,7 @@
white-space: nowrap;
}
-.icon-btn-sm {
+.api-keys-page .icon-btn-sm{
padding: 0.25rem;
background: transparent;
border: none;
@@ -123,17 +123,17 @@
flex-shrink: 0;
}
-.icon-btn-sm:hover {
+.api-keys-page .icon-btn-sm:hover{
color: var(--text-primary);
}
-.permissions-cell {
+.api-keys-page .permissions-cell{
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
}
-.permission-badge {
+.api-keys-page .permission-badge{
font-size: 0.6875rem;
padding: 0.25rem 0.5rem;
background: #e0f2fe;
@@ -143,25 +143,25 @@
white-space: nowrap;
}
-.permission-badge:first-child:last-child {
+.api-keys-page .permission-badge:first-child:last-child{
background: rgba(37, 211, 102, 0.1);
color: var(--primary);
}
-.rate-limit {
+.api-keys-page .rate-limit{
font-family: monospace;
font-size: 0.8125rem;
color: var(--text-secondary);
white-space: nowrap;
}
-.actions-cell {
+.api-keys-page .actions-cell{
display: flex;
gap: 0.25rem;
justify-content: flex-end;
}
-.icon-btn {
+.api-keys-page .icon-btn{
padding: 0.5rem;
background: transparent;
border: 1px solid var(--border);
@@ -172,18 +172,18 @@
flex-shrink: 0;
}
-.icon-btn:hover {
+.api-keys-page .icon-btn:hover{
background: var(--bg-light);
color: var(--text-primary);
}
-.icon-btn.danger:hover {
+.api-keys-page .icon-btn.danger:hover{
background: #fee2e2;
border-color: #fecaca;
color: #dc2626;
}
-.permissions-reference {
+.api-keys-page .permissions-reference{
background: var(--bg-white);
border-radius: 12px;
padding: 1.5rem;
@@ -191,18 +191,18 @@
border: 1px solid var(--border);
}
-.permissions-reference h3 {
+.api-keys-page .permissions-reference h3{
/* Inherits from H3 */
margin-bottom: 1rem;
}
-.permissions-list {
+.api-keys-page .permissions-list{
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 0.75rem;
}
-.perm-item {
+.api-keys-page .perm-item{
display: flex;
flex-direction: column;
gap: 0.25rem;
@@ -211,7 +211,7 @@
border-radius: var(--radius);
}
-.perm-item code {
+.api-keys-page .perm-item code{
font-size: 0.8125rem;
color: var(--primary);
background: rgba(37, 211, 102, 0.1);
@@ -220,13 +220,13 @@
width: fit-content;
}
-.perm-item span {
+.api-keys-page .perm-item span{
font-size: 0.75rem;
color: var(--text-secondary);
}
/* Empty Table State */
-.empty-table-state {
+.api-keys-page .empty-table-state{
display: flex;
flex-direction: column;
align-items: center;
@@ -236,41 +236,41 @@
color: var(--text-muted);
}
-.empty-table-state svg {
+.api-keys-page .empty-table-state svg{
margin-bottom: 1rem;
opacity: 0.4;
color: var(--text-muted);
}
-.empty-table-state h3 {
+.api-keys-page .empty-table-state h3{
font-size: 1.125rem;
font-weight: 600;
color: var(--text-secondary);
margin: 0 0 0.5rem;
}
-.empty-table-state p {
+.api-keys-page .empty-table-state p{
margin: 0;
font-size: 0.875rem;
max-width: 300px;
}
/* Confirmation Modal Styles */
-.confirm-modal {
+.api-keys-page .confirm-modal{
max-width: 400px;
}
-.confirm-icon-wrapper {
+.api-keys-page .confirm-icon-wrapper{
display: flex;
justify-content: center;
margin-bottom: 1rem;
}
-.confirm-warning-icon {
+.api-keys-page .confirm-warning-icon{
color: #f59e0b;
}
-.confirm-message {
+.api-keys-page .confirm-message{
text-align: center;
color: var(--text-secondary);
font-size: 0.9375rem;
@@ -278,11 +278,11 @@
margin: 0;
}
-.confirm-message strong {
+.api-keys-page .confirm-message strong{
color: var(--text-primary);
}
-.btn-danger {
+.api-keys-page .btn-danger{
padding: 0.75rem 1.25rem;
background: #dc2626;
color: white;
@@ -294,29 +294,29 @@
transition: background 0.2s;
}
-.btn-danger:hover {
+.api-keys-page .btn-danger:hover{
background: #b91c1c;
}
/* Mobile Responsive */
@media (max-width: 768px) {
- .api-keys-page {
+ .api-keys-page{
padding: 1rem;
}
/* Header adjustments for mobile */
- .api-keys-page .header-content {
+ .api-keys-page .header-content{
flex-direction: column;
align-items: stretch;
gap: 1rem;
}
- .api-keys-page .btn-primary {
+ .api-keys-page .btn-primary{
width: 100%;
justify-content: center;
}
- .keys-table-container {
+ .api-keys-page .keys-table-container{
overflow-x: visible;
border: none;
background: transparent;
@@ -324,21 +324,21 @@
}
/* Switch to card layout on mobile */
- .keys-table {
+ .api-keys-page .keys-table{
display: block;
}
- .keys-table thead {
+ .api-keys-page .keys-table thead{
display: none;
}
- .keys-table tbody {
+ .api-keys-page .keys-table tbody{
display: flex;
flex-direction: column;
gap: 1rem;
}
- .keys-table tbody tr.table-row {
+ .api-keys-page .keys-table tbody tr.table-row{
display: flex;
flex-direction: column;
gap: 0.75rem;
@@ -349,24 +349,22 @@
box-shadow: var(--shadow-sm);
}
- .keys-table tbody tr.table-row:hover,
- .keys-table tbody tr.table-row:nth-child(even),
- .keys-table tbody tr.table-row:nth-child(even):hover {
+ .api-keys-page .keys-table tbody tr.table-row:hover, .api-keys-page .keys-table tbody tr.table-row:nth-child(even), .api-keys-page .keys-table tbody tr.table-row:nth-child(even):hover{
background: var(--bg-white);
}
- .keys-table tbody tr.table-row td {
+ .api-keys-page .keys-table tbody tr.table-row td{
padding: 0;
border-bottom: none;
display: block;
}
/* Name cell - prominent at top */
- .keys-table tbody tr.table-row td:first-child {
+ .api-keys-page .keys-table tbody tr.table-row td:first-child{
order: 1;
}
- .keys-table tbody tr.table-row td:first-child .name-cell {
+ .api-keys-page .keys-table tbody tr.table-row td:first-child .name-cell{
font-size: 1.125rem;
font-weight: 600;
display: block;
@@ -374,81 +372,80 @@
}
/* Key cell */
- .keys-table tbody tr.table-row td:nth-child(2) {
+ .api-keys-page .keys-table tbody tr.table-row td:nth-child(2){
order: 2;
}
- .keys-table tbody tr.table-row td:nth-child(2) .key-cell {
+ .api-keys-page .keys-table tbody tr.table-row td:nth-child(2) .key-cell{
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
- .keys-table tbody tr.table-row td:nth-child(2) .key-cell code {
+ .api-keys-page .keys-table tbody tr.table-row td:nth-child(2) .key-cell code{
font-size: 0.75rem;
word-break: break-all;
white-space: normal;
}
/* Role & Status - wrapper for badges */
- .keys-table tbody tr.table-row td:nth-child(3),
- .keys-table tbody tr.table-row td:nth-child(4) {
+ .api-keys-page .keys-table tbody tr.table-row td:nth-child(3), .api-keys-page .keys-table tbody tr.table-row td:nth-child(4){
display: inline-block;
order: 3;
}
- .keys-table tbody tr.table-row td:nth-child(3) {
+ .api-keys-page .keys-table tbody tr.table-row td:nth-child(3){
margin-right: 0.5rem;
}
/* Status badges styling */
- .status-badge {
+ .api-keys-page .status-badge{
font-size: 0.6875rem;
padding: 0.25rem 0.5rem;
border-radius: 9999px;
font-weight: 600;
}
- .status-badge.active {
+ .api-keys-page .status-badge.active{
background: rgba(37, 211, 102, 0.1);
color: var(--primary);
}
- .status-badge.inactive {
+ .api-keys-page .status-badge.inactive{
background: #fee2e2;
color: #dc2626;
}
/* Actions cell - bottom with separator */
- .keys-table tbody tr.table-row td:last-child {
+ .api-keys-page .keys-table tbody tr.table-row td:last-child{
order: 5;
margin-top: 0.5rem;
padding-top: 0.75rem;
border-top: 1px solid var(--border);
}
- .keys-table tbody tr.table-row td:last-child .actions-cell {
+ .api-keys-page .keys-table tbody tr.table-row td:last-child .actions-cell{
justify-content: flex-start;
gap: 0.5rem;
}
/* Permissions reference mobile */
- .permissions-reference {
+ .api-keys-page .permissions-reference{
padding: 1rem;
}
- .permissions-reference h3 {
+ .api-keys-page .permissions-reference h3{
font-size: 0.9375rem;
}
}
@media (max-width: 480px) {
- .permissions-list {
+ .api-keys-page .permissions-list{
grid-template-columns: 1fr;
}
- .api-keys-page {
+ .api-keys-page{
padding: 0.75rem;
}
}
diff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.css
index 17627c734..0ef3c257e 100644
--- a/dashboard/src/pages/Chats.css
+++ b/dashboard/src/pages/Chats.css
@@ -1,4 +1,4 @@
-.chats-page {
+.chats-page{
padding: 2rem;
width: 100%;
height: calc(100vh - 4rem);
@@ -7,7 +7,7 @@
box-sizing: border-box;
}
-.chats-layout {
+.chats-page .chats-layout{
display: flex;
flex: 1;
background: var(--bg-white);
@@ -22,7 +22,7 @@
/* =============================================================================
SIDEBAR: Left Column
============================================================================= */
-.chats-sidebar {
+.chats-page .chats-sidebar{
width: 320px;
border-right: 1px solid var(--border);
display: flex;
@@ -31,7 +31,7 @@
flex-shrink: 0;
}
-.sidebar-header-box {
+.chats-page .sidebar-header-box{
padding: 1.25rem;
border-bottom: 1px solid var(--border);
display: flex;
@@ -39,13 +39,13 @@
gap: 1rem;
}
-.session-select-group {
+.chats-page .session-select-group{
display: flex;
flex-direction: column;
gap: 0.375rem;
}
-.session-selector {
+.chats-page .session-selector{
width: 100%;
padding: 0.625rem 0.75rem;
border: 1px solid var(--border);
@@ -59,13 +59,13 @@
transition: all 0.2s;
}
-.session-selector:focus {
+.chats-page .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 {
+.chats-page .chat-search-input{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -75,12 +75,12 @@
border-radius: var(--radius, 8px);
}
-.chat-search-input svg {
+.chats-page .chat-search-input svg{
color: var(--text-muted);
flex-shrink: 0;
}
-.chat-search-input input {
+.chats-page .chat-search-input input{
flex: 1;
border: none;
background: none;
@@ -89,7 +89,7 @@
outline: none;
}
-.chats-list {
+.chats-page .chats-list{
flex: 1;
overflow-y: auto;
display: flex;
@@ -97,24 +97,20 @@
}
/* Custom Scrollbar for chats list */
-.chats-list::-webkit-scrollbar,
-.room-messages::-webkit-scrollbar {
+.chats-page .chats-list::-webkit-scrollbar, .chats-page .room-messages::-webkit-scrollbar{
width: 6px;
}
-.chats-list::-webkit-scrollbar-thumb,
-.room-messages::-webkit-scrollbar-thumb {
+.chats-page .chats-list::-webkit-scrollbar-thumb, .chats-page .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 {
+.chats-page .chats-list::-webkit-scrollbar-track, .chats-page .room-messages::-webkit-scrollbar-track{
background: transparent;
}
-.chats-list-loading,
-.chats-list-empty {
+.chats-page .chats-list-loading, .chats-page .chats-list-empty{
display: flex;
flex-direction: column;
align-items: center;
@@ -125,7 +121,7 @@
gap: 0.5rem;
}
-.chat-item-card {
+.chats-page .chat-item-card{
display: flex;
align-items: center;
gap: 0.75rem;
@@ -136,15 +132,15 @@
user-select: none;
}
-.chat-item-card:hover {
+.chats-page .chat-item-card:hover{
background: var(--bg-light);
}
-.chat-item-card.active {
+.chats-page .chat-item-card.active{
background: rgba(34, 197, 94, 0.08);
}
-.chat-avatar {
+.chats-page .chat-avatar{
width: 44px;
height: 44px;
border-radius: 50%;
@@ -157,13 +153,13 @@
flex-shrink: 0;
}
-.chat-item-card.active .chat-avatar {
+.chats-page .chat-item-card.active .chat-avatar{
background: var(--bg-white);
color: var(--primary);
border-color: rgba(34, 197, 94, 0.3);
}
-.chat-item-info {
+.chats-page .chat-item-info{
flex: 1;
display: flex;
flex-direction: column;
@@ -171,13 +167,13 @@
min-width: 0; /* Ensures text truncation works */
}
-.chat-item-top {
+.chats-page .chat-item-top{
display: flex;
justify-content: space-between;
align-items: baseline;
}
-.chat-item-name {
+.chats-page .chat-item-name{
font-size: 0.9375rem;
font-weight: 600;
color: var(--text-primary);
@@ -186,19 +182,19 @@
text-overflow: ellipsis;
}
-.chat-item-time {
+.chats-page .chat-item-time{
font-size: 0.75rem;
color: var(--text-muted);
white-shrink: 0;
}
-.chat-item-bottom {
+.chats-page .chat-item-bottom{
display: flex;
justify-content: space-between;
align-items: center;
}
-.chat-item-snippet {
+.chats-page .chat-item-snippet{
font-size: 0.8125rem;
color: var(--text-muted);
white-space: nowrap;
@@ -207,12 +203,12 @@
max-width: 180px;
}
-.chat-item-snippet .no-message {
+.chats-page .chat-item-snippet .no-message{
font-style: italic;
opacity: 0.6;
}
-.chat-unread-badge {
+.chats-page .chat-unread-badge{
background: var(--primary);
color: white;
font-size: 0.75rem;
@@ -227,14 +223,14 @@
/* =============================================================================
CHAT ROOM: Right Column
============================================================================= */
-.chats-room {
+.chats-page .chats-room{
flex: 1;
display: flex;
flex-direction: column;
background: var(--bg-light);
}
-.chats-room-placeholder {
+.chats-page .chats-room-placeholder{
flex: 1;
display: flex;
flex-direction: column;
@@ -245,33 +241,36 @@
color: var(--text-muted);
}
-.placeholder-icon {
+.chats-page .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-page .chats-room-placeholder h2{
+ font-size: 1.25rem;
+ font-weight: 600;
+ color: var(--text-primary);
+ /* Reset the global h2 eyebrow treatment: this is an empty-state title, not a section label. */
+ text-transform: none;
+ letter-spacing: -0.01em;
+ margin: 0 0 0.375rem;
}
-.chats-room-placeholder p {
+.chats-page .chats-room-placeholder p{
font-size: 0.9375rem;
max-width: 380px;
margin: 0;
}
-.room-container {
+.chats-page .room-container{
flex: 1;
display: flex;
flex-direction: column;
height: 100%;
}
-.room-header {
+.chats-page .room-header{
height: 70px;
background: var(--bg-white);
border-bottom: 1px solid var(--border);
@@ -282,7 +281,28 @@
box-sizing: border-box;
}
-.room-avatar {
+/* Back-to-list control: only needed in the single-pane mobile layout; hidden on the two-pane desktop. */
+.chats-page .room-back{
+ display: none;
+ align-items: center;
+ justify-content: center;
+ width: 36px;
+ height: 36px;
+ margin-left: -0.5rem;
+ background: transparent;
+ border: none;
+ border-radius: 8px;
+ color: var(--text-secondary);
+ cursor: pointer;
+ flex-shrink: 0;
+}
+
+.chats-page .room-back:hover{
+ background: var(--bg-light);
+ color: var(--text-primary);
+}
+
+.chats-page .room-avatar{
width: 40px;
height: 40px;
border-radius: 50%;
@@ -294,20 +314,20 @@
color: var(--text-secondary);
}
-.room-contact-info h3 {
+.chats-page .room-contact-info h3{
font-size: 1rem;
font-weight: 600;
color: var(--text-primary);
margin: 0;
}
-.room-contact-info span {
+.chats-page .room-contact-info span{
font-size: 0.75rem;
color: var(--text-muted);
font-family: monospace;
}
-.room-messages {
+.chats-page .room-messages{
flex: 1;
padding: 1.5rem;
overflow-y: auto;
@@ -318,7 +338,7 @@
background-size: 24px 24px;
}
-.messages-loading {
+.chats-page .messages-loading{
display: flex;
flex-direction: column;
align-items: center;
@@ -329,7 +349,7 @@
gap: 0.75rem;
}
-.messages-empty {
+.chats-page .messages-empty{
display: flex;
flex-direction: column;
align-items: center;
@@ -342,20 +362,20 @@
padding: 2rem;
}
-.message-bubble-wrapper {
+.chats-page .message-bubble-wrapper{
display: flex;
width: 100%;
}
-.message-bubble-wrapper.incoming {
+.chats-page .message-bubble-wrapper.incoming{
justify-content: flex-start;
}
-.message-bubble-wrapper.outgoing {
+.chats-page .message-bubble-wrapper.outgoing{
justify-content: flex-end;
}
-.message-bubble {
+.chats-page .message-bubble{
max-width: 100%;
padding: 0.625rem 0.875rem 0.375rem;
border-radius: 12px;
@@ -365,31 +385,31 @@
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
-.message-bubble.incoming {
+.chats-page .message-bubble.incoming{
background: var(--bg-white);
color: var(--text-primary);
border-bottom-left-radius: 2px;
border: 1px solid var(--border);
}
-.message-bubble.outgoing {
+.chats-page .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 {
+.chats-page [data-theme='dark'] .message-bubble.outgoing{
background: #005c4b; /* Dark WhatsApp Green */
color: #e9edef;
}
-.chats-page .message-text {
+.chats-page .message-text{
word-break: break-word;
white-space: pre-wrap;
}
-.chats-page .message-meta {
+.chats-page .message-meta{
display: flex;
align-items: center;
justify-content: flex-end;
@@ -397,36 +417,36 @@
margin-top: 0.25rem;
}
-.chats-page .message-time {
+.chats-page .message-time{
font-size: 0.6875rem;
color: var(--text-muted);
}
-.chats-page .message-status-icon {
+.chats-page .message-status-icon{
font-size: 0.75rem;
}
-.chats-page .message-status-icon.read {
+.chats-page .message-status-icon.read{
color: #53bdeb; /* WhatsApp blue checks */
}
/* =============================================================================
INPUT BAR: Bottom Footer
============================================================================= */
-.room-input-footer {
+.chats-page .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 {
+.chats-page .input-form{
display: flex;
gap: 0.75rem;
align-items: center;
}
-.message-text-input {
+.chats-page .message-text-input{
flex: 1;
padding: 0.75rem 1rem;
border: 1px solid var(--border);
@@ -439,13 +459,13 @@
box-sizing: border-box;
}
-.message-text-input:focus {
+.chats-page .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 {
+.chats-page .btn-send-message{
display: flex;
align-items: center;
justify-content: center;
@@ -461,12 +481,12 @@
box-shadow: 0 2px 8px rgba(34, 197, 94, 0.3);
}
-.btn-send-message:hover:not(:disabled) {
+.chats-page .btn-send-message:hover:not(:disabled){
background: var(--primary-hover);
transform: scale(1.05);
}
-.btn-send-message:disabled {
+.chats-page .btn-send-message:disabled{
background: var(--border);
color: var(--text-muted);
cursor: not-allowed;
@@ -476,8 +496,7 @@
/* =============================================================================
GENERAL CHATS STYLES & ERROR STATES
============================================================================= */
-.chats-loading-container,
-.chats-error-state {
+.chats-page .chats-loading-container, .chats-page .chats-error-state{
display: flex;
flex-direction: column;
align-items: center;
@@ -493,25 +512,25 @@
flex: 1;
}
-.chats-error-state h3 {
+.chats-page .chats-error-state h3{
font-size: 1.25rem;
margin: 1rem 0 0.5rem;
color: var(--text-primary);
}
-.chats-error-state p {
+.chats-page .chats-error-state p{
font-size: 0.9375rem;
max-width: 450px;
margin: 0;
color: var(--text-muted);
}
-.text-warn {
+.chats-page .text-warn{
color: #ea580c;
}
/* Real-time connection-lost banner */
-.chats-reconnect-banner {
+.chats-page .chats-reconnect-banner{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -523,14 +542,14 @@
font-size: 0.875rem;
}
-.chats-reconnect-banner button {
+.chats-page .chats-reconnect-banner button{
margin-left: auto;
}
/* =============================================================================
ATTACHMENT PREVIEW & EMOJI PICKER
============================================================================= */
-.btn-input-accessory {
+.chats-page .btn-input-accessory{
background: transparent;
border: none;
color: var(--text-secondary);
@@ -544,17 +563,17 @@
flex-shrink: 0;
}
-.btn-input-accessory:hover {
+.chats-page .btn-input-accessory:hover{
background: var(--bg-light);
color: var(--text-primary);
}
-.btn-input-accessory.active {
+.chats-page .btn-input-accessory.active{
background: rgba(34, 197, 94, 0.1);
color: var(--primary);
}
-.attachment-preview-banner {
+.chats-page .attachment-preview-banner{
background: var(--bg-white);
border-top: 1px solid var(--border);
padding: 0.75rem 1.5rem;
@@ -564,7 +583,7 @@
box-sizing: border-box;
}
-.chats-page .preview-thumbnail {
+.chats-page .preview-thumbnail{
width: 48px;
height: 48px;
object-fit: cover;
@@ -572,7 +591,7 @@
border: 1px solid var(--border);
}
-.chats-page .preview-file-icon {
+.chats-page .preview-file-icon{
width: 48px;
height: 48px;
background: var(--bg-light);
@@ -584,14 +603,14 @@
font-size: 1.5rem;
}
-.chats-page .preview-file-info {
+.chats-page .preview-file-info{
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
}
-.chats-page .preview-filename {
+.chats-page .preview-filename{
font-size: 0.875rem;
font-weight: 600;
color: var(--text-primary);
@@ -600,12 +619,12 @@
text-overflow: ellipsis;
}
-.chats-page .preview-filesize {
+.chats-page .preview-filesize{
font-size: 0.75rem;
color: var(--text-muted);
}
-.btn-remove-attachment {
+.chats-page .btn-remove-attachment{
background: transparent;
border: none;
color: var(--text-muted);
@@ -618,12 +637,12 @@
transition: all 0.2s;
}
-.btn-remove-attachment:hover {
+.chats-page .btn-remove-attachment:hover{
background: #fee2e2;
color: #dc2626;
}
-.chats-emoji-picker {
+.chats-page .chats-emoji-picker{
background: var(--bg-white);
border-top: 1px solid var(--border);
padding: 0.75rem 1.5rem;
@@ -632,13 +651,13 @@
overflow-y: auto;
}
-.chats-page .emoji-grid {
+.chats-page .emoji-grid{
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
-.chats-page .emoji-btn {
+.chats-page .emoji-btn{
background: transparent;
border: none;
font-size: 1.25rem;
@@ -651,12 +670,12 @@
justify-content: center;
}
-.chats-page .emoji-btn:hover {
+.chats-page .emoji-btn:hover{
background: var(--bg-light);
transform: scale(1.15);
}
-.message-bubble.media-type {
+.chats-page .message-bubble.media-type{
border-top-left-radius: 12px;
border-top-right-radius: 12px;
}
@@ -665,28 +684,42 @@
RESPONSIVENESS
============================================================================= */
@media (max-width: 768px) {
- .chats-page {
+ .chats-page{
padding: 1rem;
height: auto;
}
- .chats-layout {
+ .chats-page .chats-layout{
flex-direction: column;
- height: 600px;
+ height: calc(100vh - 7rem);
}
- .chats-sidebar {
+ /* Single-pane on mobile: the list and the open conversation each take the full panel
+ instead of being squeezed into one short stacked column. */
+ .chats-page .chats-sidebar{
width: 100%;
- height: 250px;
+ height: 100%;
border-right: none;
- border-bottom: 1px solid var(--border);
}
- .chats-room {
- height: 350px;
+ .chats-page .chats-room{
+ height: 100%;
+ }
+
+ /* Opening a chat replaces the list with the thread; the back button returns to the list. */
+ .chats-page .chats-layout.has-active-chat .chats-sidebar{
+ display: none;
+ }
+
+ .chats-page .chats-layout:not(.has-active-chat) .chats-room{
+ display: none;
+ }
+
+ .chats-page .room-back{
+ display: inline-flex;
}
- .room-header {
+ .chats-page .room-header{
height: 60px;
}
}
@@ -694,7 +727,7 @@
/* =============================================================================
MEDIA RENDERING STYLES
============================================================================= */
-.chat-image-media {
+.chats-page .chat-image-media{
max-width: 100%;
max-height: 250px;
border-radius: 8px;
@@ -704,7 +737,7 @@
object-fit: cover;
}
-.chat-video-media {
+.chats-page .chat-video-media{
max-width: 100%;
max-height: 250px;
border-radius: 8px;
@@ -712,13 +745,13 @@
margin-bottom: 0.5rem;
}
-.chat-audio-media {
+.chats-page .chat-audio-media{
max-width: 100%;
display: block;
margin-bottom: 0.5rem;
}
-.chat-document-media {
+.chats-page .chat-document-media{
display: inline-flex;
align-items: center;
gap: 0.5rem;
@@ -735,23 +768,23 @@
word-break: break-all;
}
-.chat-document-media:hover {
+.chats-page .chat-document-media:hover{
background: var(--border);
}
-[data-theme='dark'] .chat-document-media {
+.chats-page [data-theme='dark'] .chat-document-media{
background: #202c33;
border-color: #2f3b43;
}
-.message-bubble.media-type {
+.chats-page .message-bubble.media-type{
padding: 0.5rem;
}
/* =============================================================================
HOVER MENU, REPLIES, REACTIONS, AND DELETIONS
============================================================================= */
-.message-bubble-container {
+.chats-page .message-bubble-container{
position: relative;
display: flex;
align-items: center;
@@ -759,16 +792,16 @@
max-width: 70%;
}
-.message-bubble-wrapper.outgoing .message-bubble-container {
+.chats-page .message-bubble-wrapper.outgoing .message-bubble-container{
flex-direction: row-reverse;
}
-.message-bubble-wrapper.incoming .message-bubble-container {
+.chats-page .message-bubble-wrapper.incoming .message-bubble-container{
flex-direction: row;
}
/* Hover Menu */
-.message-actions-menu {
+.chats-page .message-actions-menu{
display: none;
align-items: center;
gap: 0.25rem;
@@ -780,11 +813,11 @@
z-index: 5;
}
-.message-bubble-container:hover .message-actions-menu {
+.chats-page .message-bubble-container:hover .message-actions-menu{
display: flex;
}
-.chats-page .action-btn {
+.chats-page .action-btn{
background: transparent;
border: none;
color: var(--text-muted);
@@ -797,22 +830,22 @@
transition: all 0.15s ease;
}
-.chats-page .action-btn:hover {
+.chats-page .action-btn:hover{
background: var(--bg-light);
color: var(--text-primary);
}
-.chats-page .action-btn.delete-btn:hover {
+.chats-page .action-btn.delete-btn:hover{
color: #dc2626;
background: #fee2e2;
}
/* Reaction Quick Popover */
-.reaction-trigger-wrapper {
+.chats-page .reaction-trigger-wrapper{
position: relative;
}
-.reaction-quick-popover {
+.chats-page .reaction-quick-popover{
display: none;
position: absolute;
bottom: 100%;
@@ -828,7 +861,7 @@
white-space: nowrap;
}
-.reaction-quick-popover::after {
+.chats-page .reaction-quick-popover::after{
content: '';
position: absolute;
top: 100%;
@@ -838,11 +871,11 @@
background: transparent;
}
-.reaction-trigger-wrapper:hover .reaction-quick-popover {
+.chats-page .reaction-trigger-wrapper:hover .reaction-quick-popover{
display: flex;
}
-.reaction-quick-popover button {
+.chats-page .reaction-quick-popover button{
background: transparent;
border: none;
font-size: 1.25rem;
@@ -851,12 +884,12 @@
transition: transform 0.1s ease;
}
-.reaction-quick-popover button:hover {
+.chats-page .reaction-quick-popover button:hover{
transform: scale(1.3);
}
/* Reactions Badge */
-.message-reactions-badge {
+.chats-page .message-reactions-badge{
position: absolute;
bottom: -12px;
background: var(--bg-white);
@@ -873,26 +906,26 @@
user-select: none;
}
-.message-bubble-wrapper.outgoing .message-reactions-badge {
+.chats-page .message-bubble-wrapper.outgoing .message-reactions-badge{
right: 12px;
}
-.message-bubble-wrapper.incoming .message-reactions-badge {
+.chats-page .message-bubble-wrapper.incoming .message-reactions-badge{
left: 12px;
}
-.reaction-emoji-span {
+.chats-page .reaction-emoji-span{
font-size: 0.8125rem;
}
-.reactions-count-span {
+.chats-page .reactions-count-span{
font-weight: 600;
color: var(--text-secondary);
margin-left: 2px;
}
/* Quoted Box inside Bubble */
-.message-quote-box {
+.chats-page .message-quote-box{
background: rgba(0, 0, 0, 0.04);
border-left: 4px solid var(--primary);
border-radius: 4px;
@@ -903,16 +936,16 @@
cursor: pointer;
}
-.message-bubble.outgoing .message-quote-box {
+.chats-page .message-bubble.outgoing .message-quote-box{
background: rgba(0, 0, 0, 0.05);
border-left-color: #008069;
}
-[data-theme='dark'] .message-quote-box {
+.chats-page [data-theme='dark'] .message-quote-box{
background: rgba(255, 255, 255, 0.08);
}
-.chats-page .quote-body {
+.chats-page .quote-body{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
@@ -920,7 +953,7 @@
}
/* Replying Preview Banner above Input Footer */
-.replying-preview-banner {
+.chats-page .replying-preview-banner{
background: var(--bg-white);
border-top: 1px solid var(--border);
padding: 0.75rem 1.5rem;
@@ -931,7 +964,7 @@
box-sizing: border-box;
}
-.replying-preview-content {
+.chats-page .replying-preview-content{
flex: 1;
border-left: 4px solid var(--primary);
padding-left: 0.75rem;
@@ -940,13 +973,13 @@
min-width: 0;
}
-.replying-to-title {
+.chats-page .replying-to-title{
font-size: 0.8125rem;
font-weight: 700;
color: var(--primary);
}
-.replying-to-body {
+.chats-page .replying-to-body{
font-size: 0.875rem;
color: var(--text-secondary);
white-space: nowrap;
@@ -954,7 +987,7 @@
text-overflow: ellipsis;
}
-.btn-close-reply {
+.chats-page .btn-close-reply{
background: transparent;
border: none;
color: var(--text-muted);
@@ -967,20 +1000,18 @@
transition: all 0.2s;
}
-.btn-close-reply:hover {
+.chats-page .btn-close-reply:hover{
background: var(--bg-light);
color: var(--text-primary);
}
/* Revoked / Deleted message type */
-.message-bubble.revoked-type {
+.chats-page .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 {
+.chats-page [data-theme='dark'] .message-actions-menu, .chats-page [data-theme='dark'] .reaction-quick-popover, .chats-page [data-theme='dark'] .message-reactions-badge{
background: #202c33;
border-color: #2f3b43;
}
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 32387bb1d..ce8b6092d 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -3,6 +3,7 @@ import { Trans, useTranslation } from 'react-i18next';
import {
Search,
Send,
+ ArrowLeft,
Loader2,
User,
Users,
@@ -23,6 +24,7 @@ import {
type ChatMessage,
type MessageType,
} from '../services/api';
+import { mapEngineHistoryMessage, mergeChatMessages } from '../utils/chatMessages';
import { useWebSocket } from '../hooks/useWebSocket';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useRole } from '../hooks/useRole';
@@ -333,8 +335,18 @@ export function Chats() {
try {
setLoadingMessages(true);
markChatRead(chatId);
- const data = await sessionApi.getChatMessages(selectedSessionId, chatId, 100);
- setMessages([...data.messages].reverse());
+ // The DB holds only messages captured live since the gateway connected; the engine holds the
+ // real WhatsApp history (including messages from before connect). Merge both so a freshly
+ // paired session shows the conversation instead of an empty thread. Tolerate either side
+ // failing — only surface an error if both do.
+ const [dbRes, historyRes] = await Promise.allSettled([
+ sessionApi.getChatMessages(selectedSessionId, chatId, 100),
+ sessionApi.getChatHistory(selectedSessionId, chatId, 100),
+ ]);
+ if (dbRes.status === 'rejected' && historyRes.status === 'rejected') throw dbRes.reason;
+ const dbMessages = dbRes.status === 'fulfilled' ? dbRes.value.messages : [];
+ const history = historyRes.status === 'fulfilled' ? historyRes.value.map(mapEngineHistoryMessage) : [];
+ setMessages(mergeChatMessages(dbMessages, history));
} catch (err) {
showErrorToast(t('chats.errors.loadMessages'), err instanceof Error ? err.message : undefined);
setMessages([]);
@@ -641,7 +653,7 @@ export function Chats() {
</p>
</div>
) : (
- <div className="chats-layout">
+ <div className={`chats-layout ${activeChat ? 'has-active-chat' : ''}`}>
{/* LEFT SIDEBAR: session & chat rooms */}
<aside className="chats-sidebar">
<div className="sidebar-header-box">
@@ -730,6 +742,9 @@ export function Chats() {
<div className="room-container">
{/* Room header */}
<header className="room-header">
+ <button className="room-back" onClick={() => setActiveChat(null)} aria-label={t('common.back')}>
+ <ArrowLeft size={20} />
+ </button>
<div className="room-avatar">
{activeChat.isGroup ? <Users size={20} /> : <User size={20} />}
</div>
diff --git a/dashboard/src/pages/Dashboard.css b/dashboard/src/pages/Dashboard.css
index dec903c53..7f0f54e1f 100644
--- a/dashboard/src/pages/Dashboard.css
+++ b/dashboard/src/pages/Dashboard.css
@@ -1,14 +1,14 @@
-.dashboard {
+.dashboard{
padding: 2rem;
width: 100%;
box-sizing: border-box;
}
-.page-header {
+.dashboard .page-header{
margin-bottom: 2rem;
}
-.header-title {
+.dashboard .header-title{
display: flex;
align-items: center;
gap: 1rem;
@@ -16,7 +16,7 @@
/* H1 inherited from global */
-.status-badge {
+.dashboard .status-badge{
padding: 0.375rem 0.75rem;
border-radius: 9999px;
font-size: 0.6875rem;
@@ -25,12 +25,12 @@
letter-spacing: 0.025em;
}
-.status-badge.connected {
+.dashboard .status-badge.connected{
background: rgba(37, 211, 102, 0.1);
color: var(--primary);
}
-.stats-grid {
+.dashboard .stats-grid{
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 1.5rem;
@@ -38,7 +38,7 @@
width: 100%;
}
-.stat-card {
+.dashboard .stat-card{
position: relative;
background: var(--bg-white);
border-radius: 12px;
@@ -52,25 +52,25 @@
box-shadow 0.2s ease;
}
-.stat-card:hover {
+.dashboard .stat-card:hover{
transform: translateY(-2px);
box-shadow: var(--shadow-md);
}
-.stat-header {
+.dashboard .stat-header{
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.75rem;
}
-.stat-icon {
+.dashboard .stat-icon{
color: var(--text-muted);
position: relative;
z-index: 2;
}
-.stat-watermark {
+.dashboard .stat-watermark{
position: absolute;
right: -10px;
bottom: -15px;
@@ -83,7 +83,7 @@
z-index: 1;
}
-.stat-label {
+.dashboard .stat-label{
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
@@ -93,7 +93,7 @@
z-index: 2;
}
-.stat-value {
+.dashboard .stat-value{
font-size: 2rem;
font-weight: 700;
color: var(--text-primary);
@@ -101,7 +101,7 @@
z-index: 2;
}
-.stat-trend {
+.dashboard .stat-trend{
display: flex;
align-items: center;
gap: 0.25rem;
@@ -112,15 +112,15 @@
z-index: 2;
}
-.stat-trend.up {
+.dashboard .stat-trend.up{
color: var(--primary);
}
-.stat-trend.down {
+.dashboard .stat-trend.down{
color: #ef4444;
}
-.sessions-section {
+.dashboard .sessions-section{
background: var(--bg-white);
border-radius: 12px;
padding: 1.5rem;
@@ -130,7 +130,7 @@
box-sizing: border-box;
}
-.section-header {
+.dashboard .section-header{
display: flex;
justify-content: space-between;
align-items: center;
@@ -139,20 +139,19 @@
/* H2 inherited from global */
-.section-subtitle {
+.dashboard .section-subtitle{
font-size: 0.875rem;
color: var(--text-muted);
}
-.sessions-table {
+.dashboard .sessions-table{
display: flex;
flex-direction: column;
width: 100%;
font-size: 0.875rem;
}
-.sessions-table .table-header,
-.sessions-table .table-row {
+.dashboard .sessions-table .table-header, .dashboard .sessions-table .table-row{
display: grid;
grid-template-columns: 140px 200px 140px 1fr 180px;
gap: 1rem;
@@ -160,7 +159,7 @@
align-items: center;
}
-.sessions-table .table-header {
+.dashboard .sessions-table .table-header{
background: var(--bg-light);
border-radius: var(--radius) var(--radius) 0 0;
font-size: 0.7rem;
@@ -171,29 +170,29 @@
border-bottom: 1px solid var(--border);
}
-.sessions-table .table-row {
+.dashboard .sessions-table .table-row{
border-bottom: 1px solid var(--border);
}
-.sessions-table .table-row:last-child {
+.dashboard .sessions-table .table-row:last-child{
border-bottom: none;
}
-.session-info-cell {
+.dashboard .session-info-cell{
display: flex;
flex-direction: column;
gap: 0.125rem;
min-width: 0;
}
-.session-id {
+.dashboard .session-id{
font-family: 'JetBrains Mono', monospace;
font-size: 0.8125rem;
color: var(--text-primary);
white-space: nowrap;
}
-.session-name {
+.dashboard .session-name{
font-size: 0.75rem;
color: var(--text-muted);
white-space: nowrap;
@@ -202,13 +201,13 @@
max-width: 140px;
}
-.phone {
+.dashboard .phone{
color: var(--text-primary);
font-size: 0.8125rem;
white-space: nowrap;
}
-.status-pill {
+.dashboard .status-pill{
display: inline-block;
padding: 0.25rem 0.75rem;
border-radius: 9999px;
@@ -217,33 +216,33 @@
width: fit-content;
}
-.status-pill.ready {
+.dashboard .status-pill.ready{
background: rgba(37, 211, 102, 0.1);
color: var(--primary);
}
-.status-pill.connecting {
+.dashboard .status-pill.connecting{
background: #fef3c7;
color: #d97706;
}
-.status-pill.disconnected {
+.dashboard .status-pill.disconnected{
background: #f3f4f6;
color: var(--text-muted);
}
-.last-active {
+.dashboard .last-active{
color: var(--text-secondary);
font-size: 0.875rem;
}
-.actions {
+.dashboard .actions{
display: flex;
gap: 0.5rem;
justify-content: flex-end;
}
-.btn-sm {
+.dashboard .btn-sm{
padding: 0.375rem 0.75rem;
font-size: 0.75rem;
font-weight: 500;
@@ -255,46 +254,46 @@
color: var(--text-secondary);
}
-.btn-sm:hover {
+.dashboard .btn-sm:hover{
background: var(--bg-white);
border-color: var(--text-muted);
}
-.btn-sm.danger {
+.dashboard .btn-sm.danger{
color: #dc2626;
border-color: #fecaca;
background: #fef2f2;
}
-.btn-sm.danger:hover {
+.dashboard .btn-sm.danger:hover{
background: #fee2e2;
}
@media (max-width: 1200px) {
- .stats-grid {
+ .dashboard .stats-grid{
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 768px) {
- .dashboard {
+ .dashboard{
padding: 1rem;
}
- .stats-grid {
+ .dashboard .stats-grid{
grid-template-columns: 1fr;
gap: 1rem;
}
- .stat-value {
+ .dashboard .stat-value{
font-size: 1.5rem;
}
- .sessions-section {
+ .dashboard .sessions-section{
padding: 1rem;
}
- .section-header {
+ .dashboard .section-header{
flex-direction: column;
align-items: flex-start;
gap: 0.5rem;
@@ -302,11 +301,11 @@
}
/* Convert table to card layout on mobile */
- .sessions-table .table-header {
+ .dashboard .sessions-table .table-header{
display: none;
}
- .sessions-table .table-row {
+ .dashboard .sessions-table .table-row{
display: flex;
flex-direction: column;
gap: 0.5rem;
@@ -314,34 +313,34 @@
border-bottom: 1px solid var(--border);
}
- .sessions-table .table-row:last-child {
+ .dashboard .sessions-table .table-row:last-child{
border-bottom: none;
}
- .session-info-cell {
+ .dashboard .session-info-cell{
order: 1;
}
- .session-id {
+ .dashboard .session-id{
font-size: 0.9375rem;
font-weight: 600;
}
- .phone {
+ .dashboard .phone{
order: 2;
}
- .status-pill {
+ .dashboard .status-pill{
order: 3;
}
- .last-active {
+ .dashboard .last-active{
order: 4;
font-size: 0.75rem;
color: var(--text-muted);
}
- .actions {
+ .dashboard .actions{
order: 5;
justify-content: flex-start;
padding-top: 0.5rem;
@@ -350,11 +349,11 @@
}
@media (max-width: 480px) {
- .dashboard {
+ .dashboard{
padding: 0.75rem;
}
- .header-title {
+ .dashboard .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.css
index 62f9cbb05..2e4c85260 100644
--- a/dashboard/src/pages/Infrastructure.css
+++ b/dashboard/src/pages/Infrastructure.css
@@ -1,29 +1,29 @@
-.infrastructure-page {
+.infrastructure-page{
padding: 2rem;
width: 100%;
box-sizing: border-box;
}
-.page-header {
+.infrastructure-page .page-header{
margin-bottom: 2rem;
}
/* H1 inherited from global */
-.page-subtitle {
+.infrastructure-page .page-subtitle{
margin: 0;
font-size: 0.9375rem;
color: var(--text-secondary);
}
-.infra-sections {
+.infrastructure-page .infra-sections{
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1.5rem;
width: 100%;
}
-.infra-card {
+.infrastructure-page .infra-card{
background: var(--bg-white);
border-radius: 12px;
padding: 1.5rem;
@@ -33,11 +33,11 @@
box-sizing: border-box;
}
-.infra-card.full-width {
+.infrastructure-page .infra-card.full-width{
grid-column: 1 / -1;
}
-.card-header {
+.infrastructure-page .card-header{
display: flex;
justify-content: space-between;
align-items: center;
@@ -46,21 +46,21 @@
border-bottom: 1px solid var(--border);
}
-.header-left {
+.infrastructure-page .header-left{
display: flex;
align-items: center;
gap: 0.75rem;
}
-.header-left svg {
+.infrastructure-page .header-left svg{
color: var(--primary);
}
-.card-header h2 {
+.infrastructure-page .card-header h2{
margin: 0;
}
-.status-indicator {
+.infrastructure-page .status-indicator{
display: flex;
align-items: center;
gap: 0.375rem;
@@ -70,22 +70,22 @@
border-radius: 9999px;
}
-.status-indicator.connected {
+.infrastructure-page .status-indicator.connected{
background: rgba(37, 211, 102, 0.1);
color: var(--primary);
}
-.status-indicator.disconnected {
+.infrastructure-page .status-indicator.disconnected{
background: #fee2e2;
color: #dc2626;
}
-.status-indicator.sqlite {
+.infrastructure-page .status-indicator.sqlite{
background: #e0f2fe;
color: #0369a1;
}
-.warning-badge {
+.infrastructure-page .warning-badge{
font-size: 0.75rem;
padding: 0.375rem 0.75rem;
background: #fef3c7;
@@ -94,14 +94,14 @@
}
/* Radio Group */
-.radio-group {
+.infrastructure-page .radio-group{
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
margin-bottom: 1.5rem;
}
-.radio-option {
+.infrastructure-page .radio-option{
display: flex;
flex-direction: column;
gap: 0.25rem;
@@ -112,36 +112,36 @@
transition: all 0.2s;
}
-.radio-option:hover {
+.infrastructure-page .radio-option:hover{
border-color: var(--text-muted);
}
-.radio-option.selected {
+.infrastructure-page .radio-option.selected{
border-color: var(--primary);
background: rgba(37, 211, 102, 0.05);
}
-.radio-option input {
+.infrastructure-page .radio-option input{
display: none;
}
-.radio-option span {
+.infrastructure-page .radio-option span{
font-weight: 600;
color: var(--text-primary);
}
-.radio-option small {
+.infrastructure-page .radio-option small{
font-size: 0.75rem;
color: var(--text-secondary);
}
/* Watermark Icon */
-.radio-option {
+.infrastructure-page .radio-option{
position: relative;
overflow: hidden;
}
-.watermark-icon {
+.infrastructure-page .watermark-icon{
position: absolute;
right: -15px;
bottom: -15px;
@@ -153,40 +153,40 @@
transition: all 0.3s ease;
}
-.radio-option:hover .watermark-icon {
+.infrastructure-page .radio-option:hover .watermark-icon{
opacity: 0.25;
transform: rotate(-12deg) scale(1.05);
}
-.radio-option.selected .watermark-icon {
+.infrastructure-page .radio-option.selected .watermark-icon{
opacity: 0.3;
transform: rotate(-12deg) scale(1.1);
}
/* Form Styles */
-.config-form {
+.infrastructure-page .config-form{
display: flex;
flex-direction: column;
gap: 1rem;
}
-.form-row {
+.infrastructure-page .form-row{
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
}
-.form-row .form-group.small {
+.infrastructure-page .form-row .form-group.small{
max-width: 120px;
}
-.form-group {
+.infrastructure-page .form-group{
display: flex;
flex-direction: column;
gap: 0.5rem;
}
-.form-group label {
+.infrastructure-page .form-group label{
font-size: 0.7rem;
font-weight: 700;
text-transform: uppercase;
@@ -194,8 +194,7 @@
color: var(--text-secondary);
}
-.form-group input,
-.form-group select {
+.infrastructure-page .form-group input, .infrastructure-page .form-group select{
padding: 0.75rem 1rem;
font-size: 0.9375rem;
border: 1px solid var(--border);
@@ -204,53 +203,52 @@
transition: border-color 0.2s;
}
-.form-group input:focus,
-.form-group select:focus {
+.infrastructure-page .form-group input:focus, .infrastructure-page .form-group select:focus{
outline: none;
border-color: var(--primary);
}
/* Toggle */
-.toggle-row {
+.infrastructure-page .toggle-row{
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.75rem 0;
}
-.toggle-info {
+.infrastructure-page .toggle-info{
display: flex;
flex-direction: column;
gap: 0.25rem;
}
-.toggle-info span {
+.infrastructure-page .toggle-info span{
font-size: 0.9375rem;
font-weight: 500;
color: var(--text-primary);
}
-.toggle-info small {
+.infrastructure-page .toggle-info small{
font-size: 0.75rem;
font-weight: 400;
color: #64748b; /* Slate 500 */
opacity: 0.85;
}
-.toggle-switch {
+.infrastructure-page .toggle-switch{
position: relative;
width: 48px;
height: 26px;
cursor: pointer;
}
-.toggle-switch input {
+.infrastructure-page .toggle-switch input{
opacity: 0;
width: 0;
height: 0;
}
-.toggle-slider {
+.infrastructure-page .toggle-slider{
position: absolute;
top: 0;
left: 0;
@@ -261,7 +259,7 @@
transition: all 0.2s;
}
-.toggle-slider::before {
+.infrastructure-page .toggle-slider::before{
content: '';
position: absolute;
width: 20px;
@@ -274,36 +272,36 @@
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}
-.toggle-switch input:checked + .toggle-slider {
+.infrastructure-page .toggle-switch input:checked + .toggle-slider{
background: var(--primary);
}
-.toggle-switch input:checked + .toggle-slider::before {
+.infrastructure-page .toggle-switch input:checked + .toggle-slider::before{
transform: translateX(22px);
}
/* Migrations Section */
-.migrations-section {
+.infrastructure-page .migrations-section{
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid var(--border);
}
-.migrations-section h3 {
+.infrastructure-page .migrations-section h3{
margin: 0 0 1rem;
font-size: 0.9375rem;
font-weight: 600;
color: var(--text-primary);
}
-.migrations-list {
+.infrastructure-page .migrations-list{
background: var(--bg-light);
border-radius: var(--radius);
padding: 0.5rem;
margin-bottom: 1rem;
}
-.migration-item {
+.infrastructure-page .migration-item{
display: grid;
grid-template-columns: 24px 1fr auto;
gap: 0.75rem;
@@ -311,115 +309,115 @@
align-items: center;
}
-.migration-status {
+.infrastructure-page .migration-status{
font-size: 0.875rem;
}
-.migration-item.completed .migration-status {
+.infrastructure-page .migration-item.completed .migration-status{
color: var(--primary);
}
-.migration-item.pending .migration-status {
+.infrastructure-page .migration-item.pending .migration-status{
color: var(--text-muted);
}
-.migration-name {
+.infrastructure-page .migration-name{
font-size: 0.875rem;
color: var(--text-primary);
}
-.migration-date {
+.infrastructure-page .migration-date{
font-size: 0.75rem;
color: var(--text-muted);
}
-.migration-actions {
+.infrastructure-page .migration-actions{
display: flex;
gap: 0.75rem;
}
/* Queue Stats */
-.queue-stats {
+.infrastructure-page .queue-stats{
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid var(--border);
}
-.queue-stats h3 {
+.infrastructure-page .queue-stats h3{
margin: 0 0 1rem;
font-size: 0.9375rem;
font-weight: 600;
color: var(--text-primary);
}
-.stats-row {
+.infrastructure-page .stats-row{
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
margin-bottom: 1rem;
}
-.queue-stat-card {
+.infrastructure-page .queue-stat-card{
background: var(--bg-light);
padding: 1rem;
border-radius: var(--radius);
}
-.queue-stat-card h4 {
+.infrastructure-page .queue-stat-card h4{
margin: 0 0 0.75rem;
font-size: 0.8125rem;
font-weight: 600;
color: var(--text-secondary);
}
-.stat-values {
+.infrastructure-page .stat-values{
display: flex;
gap: 1.5rem;
}
-.stat-item {
+.infrastructure-page .stat-item{
display: flex;
flex-direction: column;
gap: 0.125rem;
}
-.stat-item .value {
+.infrastructure-page .stat-item .value{
font-size: 1.25rem;
font-weight: 700;
}
-.stat-item .label {
+.infrastructure-page .stat-item .label{
font-size: 0.6875rem;
text-transform: uppercase;
letter-spacing: 0.05em;
}
-.stat-item.pending .value {
+.infrastructure-page .stat-item.pending .value{
color: #d97706;
}
-.stat-item.pending .label {
+.infrastructure-page .stat-item.pending .label{
color: #d97706;
}
-.stat-item.completed .value {
+.infrastructure-page .stat-item.completed .value{
color: var(--primary);
}
-.stat-item.completed .label {
+.infrastructure-page .stat-item.completed .label{
color: var(--primary);
}
-.stat-item.failed .value {
+.infrastructure-page .stat-item.failed .value{
color: #dc2626;
}
-.stat-item.failed .label {
+.infrastructure-page .stat-item.failed .label{
color: #dc2626;
}
-.queue-actions {
+.infrastructure-page .queue-actions{
display: flex;
gap: 0.75rem;
}
/* Buttons */
-.btn-primary {
+.infrastructure-page .btn-primary{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -434,16 +432,16 @@
transition: background 0.2s;
}
-.btn-primary:hover {
+.infrastructure-page .btn-primary:hover{
background: var(--primary-hover);
}
-.btn-primary.large {
+.infrastructure-page .btn-primary.large{
padding: 0.875rem 1.5rem;
font-size: 1rem;
}
-.btn-outline {
+.infrastructure-page .btn-outline{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -458,11 +456,11 @@
transition: all 0.2s;
}
-.btn-outline:hover {
+.infrastructure-page .btn-outline:hover{
background: var(--bg-light);
}
-.btn-danger-outline {
+.infrastructure-page .btn-danger-outline{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -477,12 +475,12 @@
transition: all 0.2s;
}
-.btn-danger-outline:hover {
+.infrastructure-page .btn-danger-outline:hover{
background: #fee2e2;
}
/* Footer */
-.page-footer {
+.infrastructure-page .page-footer{
margin-top: 2rem;
padding-top: 1.5rem;
border-top: 1px solid var(--border);
@@ -492,44 +490,44 @@
/* Responsive */
@media (max-width: 900px) {
- .infra-sections {
+ .infrastructure-page .infra-sections{
grid-template-columns: 1fr;
}
- .infrastructure-page {
+ .infrastructure-page{
padding: 1rem;
}
- .radio-group {
+ .infrastructure-page .radio-group{
grid-template-columns: 1fr;
}
- .form-row {
+ .infrastructure-page .form-row{
grid-template-columns: 1fr;
}
- .stats-row {
+ .infrastructure-page .stats-row{
grid-template-columns: 1fr;
}
/* Card header mobile layout */
- .card-header {
+ .infrastructure-page .card-header{
flex-wrap: wrap;
gap: 0.75rem;
}
- .header-left {
+ .infrastructure-page .header-left{
flex: 1;
min-width: 0;
}
- .header-left h2 {
+ .infrastructure-page .header-left h2{
font-size: 0.9375rem;
line-height: 1.3;
}
/* Status badge mobile - prevent shrinking */
- .status-indicator {
+ .infrastructure-page .status-indicator{
flex-shrink: 0;
white-space: nowrap;
font-size: 0.75rem;
@@ -537,7 +535,7 @@
}
/* Warning badge mobile */
- .warning-badge {
+ .infrastructure-page .warning-badge{
flex-shrink: 0;
white-space: nowrap;
font-size: 0.6875rem;
@@ -545,78 +543,77 @@
}
/* Toggle row mobile - prevent switch from being cut off */
- .toggle-row {
+ .infrastructure-page .toggle-row{
gap: 1rem;
}
- .toggle-info {
+ .infrastructure-page .toggle-info{
flex: 1;
min-width: 0;
}
- .toggle-switch {
+ .infrastructure-page .toggle-switch{
flex-shrink: 0;
}
/* Queue actions stack on mobile */
- .queue-actions {
+ .infrastructure-page .queue-actions{
flex-direction: column;
}
- .queue-actions button {
+ .infrastructure-page .queue-actions button{
justify-content: center;
}
}
@media (max-width: 768px) {
- .infrastructure-page {
+ .infrastructure-page{
padding: 0.75rem;
}
- .infra-card {
+ .infrastructure-page .infra-card{
padding: 1rem;
}
- .form-row .form-group.small {
+ .infrastructure-page .form-row .form-group.small{
max-width: none;
}
- .form-group input,
- .form-group select {
+ .infrastructure-page .form-group input, .infrastructure-page .form-group select{
font-size: 0.875rem;
padding: 0.625rem 0.875rem;
}
- .migration-item {
+ .infrastructure-page .migration-item{
grid-template-columns: 24px 1fr;
gap: 0.5rem;
}
- .migration-date {
+ .infrastructure-page .migration-date{
grid-column: 2;
}
- .migration-actions {
+ .infrastructure-page .migration-actions{
flex-direction: column;
}
- .migration-actions button {
+ .infrastructure-page .migration-actions button{
justify-content: center;
}
- .stat-values {
+ .infrastructure-page .stat-values{
gap: 1rem;
}
- .stat-item .value {
+ .infrastructure-page .stat-item .value{
font-size: 1rem;
}
- .page-footer {
+ .infrastructure-page .page-footer{
justify-content: stretch;
}
- .page-footer button {
+ .infrastructure-page .page-footer button{
width: 100%;
justify-content: center;
}
diff --git a/dashboard/src/pages/Login.css b/dashboard/src/pages/Login.css
index 08be54eb0..02b41b408 100644
--- a/dashboard/src/pages/Login.css
+++ b/dashboard/src/pages/Login.css
@@ -1,4 +1,4 @@
-.login-container {
+.login-container{
min-height: 100vh;
width: 100%;
display: flex;
@@ -14,7 +14,7 @@
bottom: 0;
}
-.login-card {
+.login-container .login-card{
background: var(--bg-white);
border-radius: 12px;
box-shadow: var(--shadow-lg);
@@ -24,7 +24,7 @@
text-align: center;
}
-.login-logo {
+.login-container .login-logo{
display: flex;
flex-direction: column;
align-items: center;
@@ -33,19 +33,19 @@
margin-bottom: 1.5rem;
}
-.logo-icon {
+.login-container .logo-icon{
width: 127px;
height: 127px;
object-fit: contain;
}
-.version-info {
+.login-container .version-info{
font-size: 0.75rem;
color: var(--text-muted);
font-weight: 500;
}
-.login-language {
+.login-container .login-language{
display: flex;
align-items: center;
gap: 0.6rem;
@@ -58,11 +58,11 @@
background: var(--bg-white);
}
-.login-language svg {
+.login-container .login-language svg{
flex-shrink: 0;
}
-.login-language select {
+.login-container .login-language select{
flex: 1;
min-width: 0;
border: 0;
@@ -73,36 +73,36 @@
cursor: pointer;
}
-.login-language:focus-within {
+.login-container .login-language:focus-within{
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(37, 211, 102, 0.1);
}
-.login-title {
+.login-container .login-title{
font-size: 1.75rem;
font-weight: 600;
color: var(--text-primary);
margin: 0 0 0.5rem;
}
-.login-subtitle {
+.login-container .login-subtitle{
color: var(--text-secondary);
margin: 0 0 2rem;
}
-.login-form {
+.login-container .login-form{
text-align: left;
}
-[dir="rtl"] .login-form {
+.login-container [dir="rtl"] .login-form{
text-align: right;
}
-.input-group {
+.login-container .input-group{
margin-bottom: 1.5rem;
}
-.input-group label {
+.login-container .input-group label{
display: block;
font-size: 0.875rem;
font-weight: 500;
@@ -110,11 +110,11 @@
margin-bottom: 0.5rem;
}
-.input-wrapper {
+.login-container .input-wrapper{
position: relative;
}
-.input-wrapper input {
+.login-container .input-wrapper input{
width: 100%;
padding: 0.75rem 3rem 0.75rem 1rem;
font-size: 1rem;
@@ -126,17 +126,17 @@
box-shadow 0.2s;
}
-.input-wrapper input:focus {
+.login-container .input-wrapper input:focus{
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(37, 211, 102, 0.1);
}
-.input-wrapper input.error {
+.login-container .input-wrapper input.error{
border-color: var(--error);
}
-.toggle-visibility {
+.login-container .toggle-visibility{
position: absolute;
right: 0.75rem;
top: 50%;
@@ -148,18 +148,18 @@
padding: 0.25rem;
}
-.toggle-visibility:hover {
+.login-container .toggle-visibility:hover{
color: var(--text-secondary);
}
-.error-message {
+.login-container .error-message{
display: block;
color: var(--error);
font-size: 0.875rem;
margin-top: 0.5rem;
}
-.connect-btn {
+.login-container .connect-btn{
width: 100%;
padding: 0.875rem 1.5rem;
font-size: 1rem;
@@ -172,32 +172,32 @@
transition: background 0.2s;
}
-.connect-btn:hover:not(:disabled) {
+.login-container .connect-btn:hover:not(:disabled){
background: var(--primary-hover);
}
-.connect-btn:disabled {
+.login-container .connect-btn:disabled{
opacity: 0.7;
cursor: not-allowed;
}
-.login-help {
+.login-container .login-help{
margin-top: 1.5rem;
font-size: 0.875rem;
color: var(--text-secondary);
}
-.login-help a {
+.login-container .login-help a{
color: var(--primary);
text-decoration: none;
font-weight: 500;
}
-.login-help a:hover {
+.login-container .login-help a:hover{
text-decoration: underline;
}
-.login-footer {
+.login-container .login-footer{
margin-top: 2rem;
display: flex;
flex-direction: column;
@@ -208,61 +208,61 @@
text-align: center;
}
-.login-footer .github-link {
+.login-container .login-footer .github-link{
color: var(--text-muted);
transition: color 0.2s;
}
-.login-footer .github-link:hover {
+.login-container .login-footer .github-link:hover{
color: var(--primary);
}
-.login-footer a {
+.login-container .login-footer a{
color: var(--text-muted);
font-size: 0.75rem;
text-decoration: none;
}
-.login-footer a:hover {
+.login-container .login-footer a:hover{
color: var(--text-secondary);
}
/* Mobile Responsive */
@media (max-width: 480px) {
- .login-container {
+ .login-container{
padding: 1rem;
}
- .login-card {
+ .login-container .login-card{
padding: 2rem 1.5rem;
border-radius: 10px;
}
- .logo-icon {
+ .login-container .logo-icon{
width: 80px;
height: 80px;
}
- .login-title {
+ .login-container .login-title{
font-size: 1.375rem;
}
- .login-subtitle {
+ .login-container .login-subtitle{
font-size: 0.875rem;
margin-bottom: 1.5rem;
}
- .input-wrapper input {
+ .login-container .input-wrapper input{
padding: 0.625rem 2.5rem 0.625rem 0.875rem;
font-size: 0.9375rem;
}
- .connect-btn {
+ .login-container .connect-btn{
padding: 0.75rem 1.25rem;
font-size: 0.9375rem;
}
- .login-help {
+ .login-container .login-help{
font-size: 0.8125rem;
}
}
diff --git a/dashboard/src/pages/Logs.css b/dashboard/src/pages/Logs.css
index 7a4ea255a..d97baa773 100644
--- a/dashboard/src/pages/Logs.css
+++ b/dashboard/src/pages/Logs.css
@@ -1,14 +1,14 @@
-.logs-page {
+.logs-page{
padding: 2rem;
width: 100%;
box-sizing: border-box;
}
-.page-header {
+.logs-page .page-header{
margin-bottom: 1.5rem;
}
-.header-content {
+.logs-page .header-content{
display: flex;
justify-content: space-between;
align-items: center;
@@ -16,7 +16,7 @@
/* H1 inherited from global */
-.btn-secondary {
+.logs-page .btn-secondary{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -31,17 +31,17 @@
transition: all 0.2s;
}
-.btn-secondary:hover {
+.logs-page .btn-secondary:hover{
background: var(--bg-light);
}
-.filters-bar {
+.logs-page .filters-bar{
display: flex;
gap: 1rem;
margin-bottom: 1.5rem;
}
-.search-input {
+.logs-page .search-input{
display: flex;
align-items: center;
gap: 0.75rem;
@@ -53,11 +53,11 @@
border-radius: var(--radius);
}
-.search-input svg {
+.logs-page .search-input svg{
color: var(--text-muted);
}
-.search-input input {
+.logs-page .search-input input{
flex: 1;
border: none;
background: none;
@@ -65,11 +65,11 @@
color: var(--text-primary);
}
-.search-input input:focus {
+.logs-page .search-input input:focus{
outline: none;
}
-.filter-group {
+.logs-page .filter-group{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -79,11 +79,11 @@
border-radius: var(--radius);
}
-.filter-group svg {
+.logs-page .filter-group svg{
color: var(--text-muted);
}
-.filter-group select {
+.logs-page .filter-group select{
padding: 0.75rem 0;
border: none;
background: none;
@@ -92,11 +92,11 @@
cursor: pointer;
}
-.filter-group select:focus {
+.logs-page .filter-group select:focus{
outline: none;
}
-.logs-table-container {
+.logs-page .logs-table-container{
background: var(--bg-white);
border-radius: 12px;
box-shadow: var(--shadow-sm);
@@ -104,7 +104,7 @@
overflow-x: auto;
}
-.logs-table {
+.logs-page .logs-table{
display: flex;
flex-direction: column;
width: 100%;
@@ -112,7 +112,7 @@
}
/* Unified row styling - same class for header and data */
-.logs-table .table-row {
+.logs-page .logs-table .table-row{
display: grid;
grid-template-columns: 180px 200px 150px 150px 150px 1fr 120px;
gap: 1rem;
@@ -121,11 +121,11 @@
border-bottom: 1px solid var(--border);
}
-.logs-table .table-row:last-child {
+.logs-page .logs-table .table-row:last-child{
border-bottom: none;
}
-.logs-table .table-row.header {
+.logs-page .logs-table .table-row.header{
background: var(--bg-light);
font-size: 0.7rem;
font-weight: 700;
@@ -135,37 +135,37 @@
border-bottom: 1px solid var(--border);
}
-.logs-table .table-row:not(.header):hover {
+.logs-page .logs-table .table-row:not(.header):hover{
background: rgba(37, 211, 102, 0.05);
}
-.timestamp {
+.logs-page .timestamp{
font-family: monospace;
font-size: 0.8125rem;
color: var(--text-muted);
white-space: nowrap;
}
-.action {
+.logs-page .action{
font-weight: 600;
color: var(--text-primary);
font-size: 0.8125rem;
white-space: nowrap;
}
-.api-key {
+.logs-page .api-key{
font-family: monospace;
font-size: 0.8125rem;
white-space: nowrap;
}
-.ip {
+.logs-page .ip{
font-family: monospace;
font-size: 0.8125rem;
white-space: nowrap;
}
-.details {
+.logs-page .details{
font-size: 0.875rem;
color: var(--text-secondary);
overflow: hidden;
@@ -173,7 +173,7 @@
white-space: nowrap;
}
-.severity-badge {
+.logs-page .severity-badge{
display: inline-block;
padding: 0.25rem 0.625rem;
border-radius: 6px;
@@ -184,26 +184,26 @@
white-space: nowrap;
}
-.logs-table .table-row > span:last-child {
+.logs-page .logs-table .table-row > span:last-child{
justify-self: end;
}
-.severity-badge.info {
+.logs-page .severity-badge.info{
background: #dbeafe;
color: #1d4ed8;
}
-.severity-badge.warn {
+.logs-page .severity-badge.warn{
background: #fef3c7;
color: #d97706;
}
-.severity-badge.error {
+.logs-page .severity-badge.error{
background: #fee2e2;
color: #dc2626;
}
-.pagination {
+.logs-page .pagination{
display: flex;
justify-content: center;
align-items: center;
@@ -211,7 +211,7 @@
margin-top: 1.5rem;
}
-.pagination button {
+.logs-page .pagination button{
padding: 0.5rem 1rem;
font-size: 0.875rem;
background: var(--bg-white);
@@ -222,33 +222,33 @@
transition: all 0.2s;
}
-.pagination button:hover:not(:disabled) {
+.logs-page .pagination button:hover:not(:disabled){
background: var(--bg-light);
}
-.pagination button:disabled {
+.logs-page .pagination button:disabled{
opacity: 0.5;
cursor: not-allowed;
}
-.page-numbers {
+.logs-page .page-numbers{
display: flex;
gap: 0.25rem;
}
-.page-numbers button {
+.logs-page .page-numbers button{
min-width: 36px;
padding: 0.5rem;
}
-.page-numbers button.active {
+.logs-page .page-numbers button.active{
background: var(--primary);
border-color: var(--primary);
color: white;
}
/* Empty Table State */
-.empty-table-state {
+.logs-page .empty-table-state{
display: flex;
flex-direction: column;
align-items: center;
@@ -258,20 +258,20 @@
color: var(--text-muted);
}
-.empty-table-state svg {
+.logs-page .empty-table-state svg{
margin-bottom: 1rem;
opacity: 0.4;
color: var(--text-muted);
}
-.empty-table-state h3 {
+.logs-page .empty-table-state h3{
font-size: 1.125rem;
font-weight: 600;
color: var(--text-secondary);
margin: 0 0 0.5rem;
}
-.empty-table-state p {
+.logs-page .empty-table-state p{
margin: 0;
font-size: 0.875rem;
max-width: 300px;
@@ -279,47 +279,49 @@
/* Mobile Responsive */
@media (max-width: 768px) {
- .logs-page {
+ .logs-page{
padding: 1rem;
}
- .filters-bar {
+ .logs-page .filters-bar{
flex-direction: column;
gap: 0.75rem;
}
- .search-input {
+ .logs-page .search-input{
max-width: none;
}
- .filter-group {
+ .logs-page .filter-group{
width: 100%;
justify-content: space-between;
}
- .filter-group select {
+ .logs-page .filter-group select{
flex: 1;
padding: 0.75rem 0;
}
- .logs-table-container {
+ .logs-page .logs-table-container{
overflow-x: visible;
border: none;
background: transparent;
box-shadow: none;
}
- .logs-table {
+ .logs-page .logs-table{
display: block;
}
- .logs-table .table-row.header {
+ .logs-page .logs-table .table-row.header{
display: none;
}
- .logs-table .table-row:not(.header) {
+ .logs-page .logs-table .table-row:not(.header){
display: flex;
flex-direction: column;
+ align-items: flex-start;
+ text-align: left;
gap: 0.5rem;
padding: 1rem;
background: var(--bg-white);
@@ -329,12 +331,19 @@
margin-bottom: 0.75rem;
}
- .logs-table .table-row:not(.header):hover {
+ /* Cells inherit centering from the desktop grid; force a left-aligned, scannable card. */
+ .logs-page .logs-table .table-row:not(.header) > span{
+ width: 100%;
+ justify-content: flex-start;
+ text-align: left;
+ }
+
+ .logs-page .logs-table .table-row:not(.header):hover{
background: var(--bg-white);
}
/* Action label prominent at top */
- .logs-table .table-row .action {
+ .logs-page .logs-table .table-row .action{
font-size: 0.9375rem;
font-weight: 600;
order: 1;
@@ -342,42 +351,40 @@
}
/* Timestamp secondary */
- .logs-table .table-row .timestamp {
+ .logs-page .logs-table .table-row .timestamp{
order: 2;
font-size: 0.75rem;
}
/* Session, API Key, IP - inline info */
- .logs-table .table-row > span:nth-child(3),
- .logs-table .table-row > span:nth-child(4),
- .logs-table .table-row > span:nth-child(5) {
+ .logs-page .logs-table .table-row > span:nth-child(3), .logs-page .logs-table .table-row > span:nth-child(4), .logs-page .logs-table .table-row > span:nth-child(5){
display: none;
}
/* Severity badge stays visible */
- .logs-table .table-row > span:last-child {
+ .logs-page .logs-table .table-row > span:last-child{
order: 3;
justify-self: flex-start;
}
- .pagination {
+ .logs-page .pagination{
flex-wrap: wrap;
gap: 0.5rem;
}
- .pagination button {
+ .logs-page .pagination button{
padding: 0.5rem 0.75rem;
font-size: 0.8125rem;
}
- .page-numbers button {
+ .logs-page .page-numbers button{
min-width: 32px;
padding: 0.5rem 0.25rem;
}
}
@media (max-width: 480px) {
- .logs-page {
+ .logs-page{
padding: 0.75rem;
}
}
diff --git a/dashboard/src/pages/Logs.tsx b/dashboard/src/pages/Logs.tsx
index 6c172686c..5a6e0cedc 100644
--- a/dashboard/src/pages/Logs.tsx
+++ b/dashboard/src/pages/Logs.tsx
@@ -2,6 +2,7 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Download, Search, Filter, Loader2, FileText, AlertCircle } from 'lucide-react';
import type { AuditLog } from '../services/api';
+import { auditApi } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useLogsQuery } from '../hooks/queries';
import { PageHeader } from '../components/PageHeader';
@@ -13,6 +14,7 @@ export function Logs() {
const [searchQuery, setSearchQuery] = useState('');
const [severityFilter, setSeverityFilter] = useState('all');
const [page, setPage] = useState(1);
+ const [exporting, setExporting] = useState(false);
const limit = 20;
const severityParam = severityFilter !== 'all' ? severityFilter : undefined;
@@ -31,10 +33,7 @@ export function Logs() {
const formatTimestamp = (date: string) => new Date(date).toLocaleString();
- // Export the currently loaded (and filtered) logs to a CSV download. Client-side only —
- // it exports what the page already has, not the whole audit history.
- const handleExportCsv = () => {
- if (filteredLogs.length === 0) return;
+ const buildCsv = (rows: AuditLog[]): string => {
const headers = [
'timestamp',
'action',
@@ -51,7 +50,7 @@ export function Logs() {
const s = value === undefined || value === null ? '' : String(value);
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};
- const rows = filteredLogs.map(log =>
+ const lines = rows.map(log =>
[
log.createdAt,
log.action,
@@ -67,7 +66,10 @@ export function Logs() {
.map(escape)
.join(','),
);
- const csv = [headers.join(','), ...rows].join('\n');
+ return [headers.join(','), ...lines].join('\n');
+ };
+
+ const download = (csv: string) => {
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -77,6 +79,35 @@ export function Logs() {
URL.revokeObjectURL(url);
};
+ // Export the WHOLE audit history (honouring the active severity filter + search), not just the
+ // current page — paginate through the API up to a safety cap so a huge table can't OOM the tab. On
+ // a fetch error, fall back to exporting the rows already on screen.
+ const handleExportCsv = async () => {
+ if (exporting) return;
+ setExporting(true);
+ const PAGE = 500;
+ const CAP = 50000;
+ try {
+ const all: AuditLog[] = [];
+ let offset = 0;
+ for (;;) {
+ const res = await auditApi.list({ severity: severityParam, limit: PAGE, offset });
+ all.push(...res.data);
+ offset += res.data.length;
+ if (res.data.length < PAGE || offset >= res.total || all.length >= CAP) break;
+ }
+ const q = searchQuery.toLowerCase();
+ const rows = q
+ ? all.filter(l => l.action.toLowerCase().includes(q) || (l.errorMessage || '').toLowerCase().includes(q))
+ : all;
+ if (rows.length > 0) download(buildCsv(rows));
+ } catch {
+ if (filteredLogs.length > 0) download(buildCsv(filteredLogs)); // graceful fallback to the page
+ } finally {
+ setExporting(false);
+ }
+ };
+
if (loading && logs.length === 0) {
return (
<div
@@ -94,8 +125,8 @@ export function Logs() {
title={t('logs.title')}
subtitle={t('logs.subtitle')}
actions={
- <button className="btn-secondary" onClick={handleExportCsv} disabled={filteredLogs.length === 0}>
- <Download size={18} />
+ <button className="btn-secondary" onClick={() => void handleExportCsv()} disabled={exporting || total === 0}>
+ {exporting ? <Loader2 size={18} className="animate-spin" /> : <Download size={18} />}
{t('logs.exportCsv')}
</button>
}
diff --git a/dashboard/src/pages/MessageTester.css b/dashboard/src/pages/MessageTester.css
index 0b319476e..fcdcd926b 100644
--- a/dashboard/src/pages/MessageTester.css
+++ b/dashboard/src/pages/MessageTester.css
@@ -1,28 +1,27 @@
-.message-tester {
+.message-tester{
padding: 2rem;
width: 100%;
box-sizing: border-box;
}
-.message-tester .page-header {
+.message-tester .page-header{
margin-bottom: 2rem;
}
/* H1 inherited from global */
-.message-tester .page-header p {
+.message-tester .page-header p{
margin: 0;
font-size: 0.9375rem;
color: var(--text-secondary);
}
-.tester-panels {
+.message-tester .tester-panels{
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1.5rem;
}
-.compose-panel,
-.response-panel {
+.message-tester .compose-panel, .message-tester .response-panel{
background: var(--bg-white);
border-radius: 12px;
padding: 1.5rem;
@@ -30,17 +29,16 @@
border: 1px solid var(--border);
}
-.compose-panel h2,
-.response-panel h2 {
+.message-tester .compose-panel h2, .message-tester .response-panel h2{
/* Inherits from H2 */
margin-bottom: 1.5rem;
}
-.form-group {
+.message-tester .form-group{
margin-bottom: 1.25rem;
}
-.form-group label {
+.message-tester .form-group label{
display: block;
font-size: 0.7rem;
font-weight: 700;
@@ -50,9 +48,7 @@
margin-bottom: 0.5rem;
}
-.form-group input,
-.form-group select,
-.form-group textarea {
+.message-tester .form-group input, .message-tester .form-group select, .message-tester .form-group textarea{
width: 100%;
padding: 0.75rem 1rem;
font-size: 0.9375rem;
@@ -62,33 +58,31 @@
transition: border-color 0.2s;
}
-.form-group input:focus,
-.form-group select:focus,
-.form-group textarea:focus {
+.message-tester .form-group input:focus, .message-tester .form-group select:focus, .message-tester .form-group textarea:focus{
outline: none;
border-color: var(--primary);
}
-.form-group textarea {
+.message-tester .form-group textarea{
resize: vertical;
min-height: 100px;
}
-.form-group .hint {
+.message-tester .form-group .hint{
display: block;
font-size: 0.75rem;
color: var(--text-muted);
margin-top: 0.375rem;
}
-.toggle-group {
+.message-tester .toggle-group{
display: flex;
border: 1px solid var(--border);
border-radius: var(--radius);
overflow: hidden;
}
-.toggle-group button {
+.message-tester .toggle-group button{
flex: 1;
padding: 0.625rem 1rem;
font-size: 0.875rem;
@@ -100,16 +94,16 @@
color: var(--text-secondary);
}
-.toggle-group button:first-child {
+.message-tester .toggle-group button:first-child{
border-right: 1px solid var(--border);
}
-.toggle-group button.active {
+.message-tester .toggle-group button.active{
background: var(--primary);
color: white;
}
-.send-btn {
+.message-tester .send-btn{
display: flex;
align-items: center;
justify-content: center;
@@ -126,16 +120,16 @@
transition: background 0.2s;
}
-.send-btn:hover:not(:disabled) {
+.message-tester .send-btn:hover:not(:disabled){
background: var(--primary-hover);
}
-.send-btn:disabled {
+.message-tester .send-btn:disabled{
opacity: 0.7;
cursor: not-allowed;
}
-.response-status {
+.message-tester .response-status{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -146,54 +140,54 @@
margin-bottom: 1rem;
}
-.response-status.success {
+.message-tester .response-status.success{
background: rgba(37, 211, 102, 0.1);
color: var(--primary);
}
-.response-status.error {
+.message-tester .response-status.error{
background: #FEE2E2;
color: #DC2626;
}
-.response-details {
+.message-tester .response-details{
margin-bottom: 1rem;
}
-.detail-row {
+.message-tester .detail-row{
display: flex;
justify-content: space-between;
padding: 0.625rem 0;
border-bottom: 1px solid var(--border);
}
-.detail-row:last-child {
+.message-tester .detail-row:last-child{
border-bottom: none;
}
-.detail-label {
+.message-tester .detail-label{
font-size: 0.875rem;
color: var(--text-secondary);
}
-.detail-value {
+.message-tester .detail-value{
font-size: 0.875rem;
color: var(--text-primary);
font-weight: 500;
}
-.detail-value.mono {
+.message-tester .detail-value.mono{
font-family: monospace;
}
-.response-json {
+.message-tester .response-json{
background: #1E293B;
border-radius: var(--radius);
padding: 1rem;
overflow-x: auto;
}
-.response-json pre {
+.message-tester .response-json pre{
margin: 0;
color: #E2E8F0;
font-size: 0.8125rem;
@@ -201,7 +195,7 @@
white-space: pre-wrap;
}
-.response-empty {
+.message-tester .response-empty{
display: flex;
align-items: center;
justify-content: center;
@@ -210,35 +204,34 @@
border-radius: var(--radius);
}
-.response-empty p {
+.message-tester .response-empty p{
color: var(--text-muted);
margin: 0;
}
@media (max-width: 1000px) {
- .tester-panels {
+ .message-tester .tester-panels{
grid-template-columns: 1fr;
}
}
@media (max-width: 768px) {
- .message-tester {
+ .message-tester{
padding: 1rem;
}
- .compose-panel,
- .response-panel {
+ .message-tester .compose-panel, .message-tester .response-panel{
padding: 1rem;
}
- .toggle-group {
+ .message-tester .toggle-group{
flex-wrap: wrap;
border: none;
gap: 0.5rem;
overflow: visible;
}
- .toggle-group button {
+ .message-tester .toggle-group button{
min-width: 0;
padding: 0.5rem 0.875rem;
font-size: 0.8125rem;
@@ -246,18 +239,16 @@
border-radius: 6px;
}
- .toggle-group button.active {
+ .message-tester .toggle-group button.active{
border-color: var(--primary) !important;
}
- .send-btn {
+ .message-tester .send-btn{
font-size: 0.9375rem;
padding: 0.75rem 1rem;
}
- .form-group input,
- .form-group select,
- .form-group textarea {
+ .message-tester .form-group input, .message-tester .form-group select, .message-tester .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.css
index b9bc5222e..8723b6ec1 100644
--- a/dashboard/src/pages/Plugins.css
+++ b/dashboard/src/pages/Plugins.css
@@ -1,11 +1,11 @@
-.plugins-page {
+.plugins-page{
padding: 2rem;
width: 100%;
box-sizing: border-box;
}
/* Engine Card */
-.engine-card {
+.plugins-page .engine-card{
background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, rgba(16, 185, 129, 0.1) 100%);
border: 1px solid rgba(34, 197, 94, 0.2);
border-radius: 12px;
@@ -13,19 +13,19 @@
margin-bottom: 2rem;
}
-.engine-header {
+.plugins-page .engine-header{
display: flex;
align-items: center;
justify-content: space-between;
}
-.engine-info {
+.plugins-page .engine-info{
display: flex;
align-items: center;
gap: 1rem;
}
-.engine-icon-wrapper {
+.plugins-page .engine-icon-wrapper{
width: 48px;
height: 48px;
background: rgba(34, 197, 94, 0.15);
@@ -35,11 +35,11 @@
justify-content: center;
}
-.engine-icon-wrapper svg {
+.plugins-page .engine-icon-wrapper svg{
color: #22c55e;
}
-.engine-title {
+.plugins-page .engine-title{
font-size: 1.125rem;
font-weight: 600;
color: var(--text-primary);
@@ -48,18 +48,18 @@
letter-spacing: normal;
}
-.engine-name {
+.plugins-page .engine-name{
font-size: 0.875rem;
color: #22c55e;
}
-.engine-features {
+.plugins-page .engine-features{
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid rgba(34, 197, 94, 0.15);
}
-.features-label {
+.plugins-page .features-label{
font-size: 0.75rem;
color: var(--text-secondary);
margin-bottom: 0.5rem;
@@ -67,13 +67,13 @@
letter-spacing: 0.05em;
}
-.features-list {
+.plugins-page .features-list{
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
-.feature-tag {
+.plugins-page .feature-tag{
padding: 0.25rem 0.5rem;
background: rgba(34, 197, 94, 0.1);
color: #22c55e;
@@ -82,14 +82,14 @@
}
/* Plugins Grid */
-.plugins-grid {
+.plugins-page .plugins-grid{
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: 1.5rem;
}
/* Plugin Card */
-.plugin-card {
+.plugins-page .plugin-card{
background: var(--bg-white);
border: 1px solid var(--border);
border-radius: 12px;
@@ -99,12 +99,12 @@
box-shadow 0.2s;
}
-.plugin-card:hover {
+.plugins-page .plugin-card:hover{
transform: translateY(-2px);
box-shadow: var(--shadow-md);
}
-.plugin-card-header {
+.plugins-page .plugin-card-header{
padding: 1.25rem 1.25rem 1rem;
display: flex;
align-items: center;
@@ -112,14 +112,14 @@
gap: 0.5rem;
}
-.plugin-info {
+.plugins-page .plugin-info{
display: flex;
align-items: center;
gap: 0.75rem;
min-width: 0;
}
-.plugin-icon-wrapper {
+.plugins-page .plugin-icon-wrapper{
width: 42px;
height: 42px;
background: var(--bg-light);
@@ -130,43 +130,43 @@
flex-shrink: 0;
}
-.plugin-icon-wrapper svg {
+.plugins-page .plugin-icon-wrapper svg{
color: var(--text-secondary);
}
/* Calm, low-saturation type tints on the icon only — no loud gradient header, no alarming red. */
-.type-engine .plugin-icon-wrapper {
+.plugins-page .type-engine .plugin-icon-wrapper{
background: rgba(34, 197, 94, 0.12);
}
-.type-engine .plugin-icon-wrapper svg {
+.plugins-page .type-engine .plugin-icon-wrapper svg{
color: #16a34a;
}
-.type-extension .plugin-icon-wrapper {
+.plugins-page .type-extension .plugin-icon-wrapper{
background: rgba(99, 102, 241, 0.12);
}
-.type-extension .plugin-icon-wrapper svg {
+.plugins-page .type-extension .plugin-icon-wrapper svg{
color: #6366f1;
}
-.type-storage .plugin-icon-wrapper {
+.plugins-page .type-storage .plugin-icon-wrapper{
background: rgba(13, 148, 136, 0.12);
}
-.type-storage .plugin-icon-wrapper svg {
+.plugins-page .type-storage .plugin-icon-wrapper svg{
color: #0d9488;
}
-.type-queue .plugin-icon-wrapper {
+.plugins-page .type-queue .plugin-icon-wrapper{
background: rgba(217, 119, 6, 0.12);
}
-.type-queue .plugin-icon-wrapper svg {
+.plugins-page .type-queue .plugin-icon-wrapper svg{
color: #d97706;
}
-.type-auth .plugin-icon-wrapper {
+.plugins-page .type-auth .plugin-icon-wrapper{
background: rgba(147, 51, 234, 0.12);
}
-.type-auth .plugin-icon-wrapper svg {
+.plugins-page .type-auth .plugin-icon-wrapper svg{
color: #9333ea;
}
-.plugin-name {
+.plugins-page .plugin-name{
font-size: 0.9375rem;
font-weight: 600;
color: var(--text-primary);
@@ -178,12 +178,12 @@
text-overflow: ellipsis;
}
-.plugin-version {
+.plugins-page .plugin-version{
font-size: 0.75rem;
color: var(--text-muted);
}
-.plugin-builtin-badge {
+.plugins-page .plugin-builtin-badge{
padding: 0.1875rem 0.5rem;
background: var(--bg-light);
color: var(--text-muted);
@@ -197,73 +197,73 @@
flex-shrink: 0;
}
-.plugin-card-body {
+.plugins-page .plugin-card-body{
padding: 1.25rem;
}
-.plugin-description {
+.plugins-page .plugin-description{
color: var(--text-secondary);
font-size: 0.875rem;
margin-bottom: 1rem;
line-height: 1.5;
}
-.plugin-status-row {
+.plugins-page .plugin-status-row{
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 1rem;
}
-.plugin-status {
+.plugins-page .plugin-status{
display: flex;
align-items: center;
gap: 0.5rem;
}
-.status-dot {
+.plugins-page .status-dot{
width: 8px;
height: 8px;
border-radius: 50%;
}
-.status-dot.enabled {
+.plugins-page .status-dot.enabled{
background: #22c55e;
}
-.status-dot.disabled {
+.plugins-page .status-dot.disabled{
background: #eab308;
}
-.status-dot.error {
+.plugins-page .status-dot.error{
background: #ef4444;
}
-.status-dot.installed {
+.plugins-page .status-dot.installed{
background: #64748b;
}
-.status-text {
+.plugins-page .status-text{
font-size: 0.875rem;
color: var(--text-primary);
text-transform: capitalize;
}
-.plugin-type-label {
+.plugins-page .plugin-type-label{
font-size: 0.625rem;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.05em;
}
-.plugin-provides {
+.plugins-page .plugin-provides{
display: flex;
flex-wrap: wrap;
gap: 0.375rem;
margin-bottom: 1rem;
}
-.provides-tag {
+.plugins-page .provides-tag{
padding: 0.25rem 0.5rem;
background: var(--bg-light);
color: var(--text-secondary);
@@ -271,7 +271,7 @@
border-radius: 4px;
}
-.plugin-error {
+.plugins-page .plugin-error{
background: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.2);
border-radius: 6px;
@@ -279,12 +279,12 @@
margin-bottom: 1rem;
}
-.plugin-error-text {
+.plugins-page .plugin-error-text{
color: #ef4444;
font-size: 0.75rem;
}
-.plugin-actions {
+.plugins-page .plugin-actions{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -292,7 +292,7 @@
border-top: 1px solid var(--border);
}
-.btn-toggle {
+.plugins-page .btn-toggle{
flex: 1;
display: flex;
align-items: center;
@@ -308,35 +308,35 @@
/* Positive action (Enable / Activate): the one solid brand-green CTA, so an action never reads
the same as the passive "Active" state below. */
-.btn-toggle.enable {
+.plugins-page .btn-toggle.enable{
background: var(--primary, #25d366);
border: 1px solid var(--primary, #25d366);
color: #fff;
}
-.btn-toggle.enable:hover {
+.plugins-page .btn-toggle.enable:hover{
background: #16a34a;
border-color: #16a34a;
}
-.btn-toggle.disable {
+.plugins-page .btn-toggle.disable{
background: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.3);
color: #ef4444;
}
-.btn-toggle.disable:hover {
+.plugins-page .btn-toggle.disable:hover{
background: rgba(239, 68, 68, 0.2);
}
-.btn-toggle:disabled {
+.plugins-page .btn-toggle:disabled{
opacity: 0.5;
cursor: not-allowed;
}
/* Passive states (Active / Required) are NOT actions — render them as quiet neutral chips, with
only a small green check as the "it's on" signal, so they're clearly distinct from the green CTA. */
-.btn-required {
+.plugins-page .btn-required{
flex: 1;
display: flex;
align-items: center;
@@ -352,11 +352,11 @@
cursor: default;
}
-.btn-required svg {
+.plugins-page .btn-required svg{
color: var(--text-muted);
}
-.btn-active {
+.plugins-page .btn-active{
flex: 1;
display: flex;
align-items: center;
@@ -372,11 +372,11 @@
cursor: default;
}
-.btn-active svg {
+.plugins-page .btn-active svg{
color: #16a34a;
}
-.btn-action {
+.plugins-page .btn-action{
width: 36px;
height: 36px;
display: flex;
@@ -390,43 +390,43 @@
padding: 0;
}
-.btn-action:hover {
+.plugins-page .btn-action:hover{
background: var(--bg-white);
border-color: var(--text-muted);
}
-.btn-action svg {
+.plugins-page .btn-action svg{
color: var(--text-secondary);
}
/* Empty State */
-.empty-state {
+.plugins-page .empty-state{
text-align: center;
padding: 4rem 2rem;
}
-.empty-state svg {
+.plugins-page .empty-state svg{
color: var(--text-muted);
margin-bottom: 1rem;
}
-.empty-state h3 {
+.plugins-page .empty-state h3{
font-size: 1.25rem;
color: var(--text-secondary);
margin-bottom: 0.5rem;
}
-.empty-state p {
+.plugins-page .empty-state p{
color: var(--text-muted);
}
/* Config Modal */
-.config-modal {
+.plugins-page .config-modal{
max-width: 500px;
width: 90%;
}
-.config-info-banner {
+.plugins-page .config-info-banner{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -439,11 +439,11 @@
font-size: 0.875rem;
}
-.config-form .form-group {
+.plugins-page .config-form .form-group{
margin-bottom: 1.25rem;
}
-.config-form .form-group label {
+.plugins-page .config-form .form-group label{
display: block;
font-size: 0.875rem;
font-weight: 600;
@@ -451,9 +451,7 @@
margin-bottom: 0.5rem;
}
-.config-form .form-group input,
-.config-form .form-group select,
-.config-form .form-group textarea {
+.plugins-page .config-form .form-group input, .plugins-page .config-form .form-group select, .plugins-page .config-form .form-group textarea{
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid var(--border);
@@ -464,15 +462,13 @@
box-sizing: border-box;
}
-.config-form .form-group textarea {
+.plugins-page .config-form .form-group textarea{
font-family: inherit;
resize: vertical;
min-height: 4.5rem;
}
-.config-form .form-group input:focus,
-.config-form .form-group select:focus,
-.config-form .form-group textarea:focus {
+.plugins-page .config-form .form-group input:focus, .plugins-page .config-form .form-group select:focus, .plugins-page .config-form .form-group textarea:focus{
outline: none;
border-color: var(--primary);
background: var(--bg-white);
@@ -480,7 +476,7 @@
}
/* Nested object — a bordered group of sub-fields. */
-.config-form .config-fieldset {
+.plugins-page .config-form .config-fieldset{
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.75rem 1rem 0.25rem;
@@ -488,7 +484,7 @@
min-width: 0;
}
-.config-form .config-fieldset > legend {
+.plugins-page .config-form .config-fieldset > legend{
font-size: 0.8125rem;
font-weight: 600;
color: var(--text-secondary);
@@ -496,11 +492,11 @@
}
/* Array-of-rows — repeating rows with add/remove. */
-.config-form .config-array {
+.plugins-page .config-form .config-array{
margin-bottom: 1.25rem;
}
-.config-form .config-array > label {
+.plugins-page .config-form .config-array > label{
display: block;
font-size: 0.875rem;
font-weight: 600;
@@ -508,21 +504,21 @@
margin-bottom: 0.5rem;
}
-.config-form .config-array-row {
+.plugins-page .config-form .config-array-row{
display: flex;
align-items: flex-start;
gap: 0.5rem;
margin-bottom: 0.5rem;
}
-.config-form .config-array-row-body {
+.plugins-page .config-form .config-array-row-body{
flex: 1;
min-width: 0;
border-left: 2px solid var(--border);
padding-left: 0.75rem;
}
-.config-form .config-array-remove {
+.plugins-page .config-form .config-array-remove{
display: inline-flex;
align-items: center;
justify-content: center;
@@ -535,13 +531,13 @@
transition: all 0.2s;
}
-.config-form .config-array-remove:hover {
+.plugins-page .config-form .config-array-remove:hover{
background: var(--danger, #e5484d);
color: #fff;
border-color: var(--danger, #e5484d);
}
-.config-form .config-array-add {
+.plugins-page .config-form .config-array-add{
display: inline-flex;
align-items: center;
gap: 0.35rem;
@@ -556,13 +552,13 @@
transition: all 0.2s;
}
-.config-form .config-array-add:hover {
+.plugins-page .config-form .config-array-add:hover{
border-color: var(--primary);
color: var(--primary);
}
/* Sandboxed-iframe config editor (B-full). */
-.plugin-config-ui-frame {
+.plugins-page .plugin-config-ui-frame{
display: block;
width: 100%;
border: 1px solid var(--border);
@@ -570,7 +566,7 @@
background: var(--bg-white);
}
-.config-ui-status {
+.plugins-page .config-ui-status{
display: flex;
align-items: center;
justify-content: center;
@@ -578,13 +574,13 @@
color: var(--text-muted);
}
-.config-ui-error {
+.plugins-page .config-ui-error{
padding: 1rem;
text-align: center;
color: var(--danger, #e5484d);
}
-.config-form .form-group small {
+.plugins-page .config-form .form-group small{
display: block;
margin-top: 0.4rem;
font-size: 0.75rem;
@@ -592,11 +588,11 @@
line-height: 1.4;
}
-.config-form .form-group .required-mark {
+.plugins-page .config-form .form-group .required-mark{
color: var(--danger, #e5484d);
}
-.toggle-group {
+.plugins-page .toggle-group{
display: flex;
align-items: center;
justify-content: space-between;
@@ -605,22 +601,22 @@
border-radius: 8px;
}
-.toggle-info {
+.plugins-page .toggle-info{
flex: 1;
}
-.toggle-info label {
+.plugins-page .toggle-info label{
display: block !important;
margin-bottom: 0.25rem !important;
}
-.toggle-info small {
+.plugins-page .toggle-info small{
display: block;
font-size: 0.75rem;
color: var(--text-muted);
}
-.toggle-switch {
+.plugins-page .toggle-switch{
position: relative;
display: inline-block;
width: 48px;
@@ -628,13 +624,13 @@
flex-shrink: 0;
}
-.toggle-switch input {
+.plugins-page .toggle-switch input{
opacity: 0;
width: 0;
height: 0;
}
-.toggle-slider {
+.plugins-page .toggle-slider{
position: absolute;
cursor: pointer;
top: 0;
@@ -646,7 +642,7 @@
border-radius: 26px;
}
-.toggle-slider:before {
+.plugins-page .toggle-slider:before{
position: absolute;
content: '';
height: 20px;
@@ -659,25 +655,25 @@
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
-.toggle-switch input:checked + .toggle-slider {
+.plugins-page .toggle-switch input:checked + .toggle-slider{
background-color: var(--primary, #22c55e);
}
-.toggle-switch input:checked + .toggle-slider:before {
+.plugins-page .toggle-switch input:checked + .toggle-slider:before{
transform: translateX(22px);
}
-.no-config {
+.plugins-page .no-config{
text-align: center;
padding: 2rem;
color: var(--text-muted);
}
-.no-config p {
+.plugins-page .no-config p{
margin-top: 1rem;
}
-.btn-primary {
+.plugins-page .btn-primary{
padding: 0.75rem 1.5rem;
background: var(--primary, #22c55e);
color: white;
@@ -692,26 +688,26 @@
gap: 0.5rem;
}
-.btn-primary:hover {
+.plugins-page .btn-primary:hover{
background: #16a34a;
}
-.btn-primary:disabled {
+.plugins-page .btn-primary:disabled{
opacity: 0.6;
cursor: not-allowed;
}
/* Responsive */
@media (max-width: 768px) {
- .plugins-page {
+ .plugins-page{
padding: 1rem;
}
- .plugins-grid {
+ .plugins-page .plugins-grid{
grid-template-columns: 1fr;
}
- .engine-header {
+ .plugins-page .engine-header{
flex-direction: column;
align-items: flex-start;
gap: 1rem;
@@ -719,13 +715,13 @@
}
/* ── Two-column control layout: status rail + plugin catalog ─────────────── */
-.plugins-layout {
+.plugins-page .plugins-layout{
display: flex;
gap: 1.5rem;
align-items: flex-start;
}
-.plugins-rail {
+.plugins-page .plugins-rail{
flex: 0 0 280px;
position: sticky;
top: 1.5rem;
@@ -738,12 +734,12 @@
padding: 1.25rem;
}
-.plugins-main {
+.plugins-page .plugins-main{
flex: 1 1 auto;
min-width: 0;
}
-.rail-label {
+.plugins-page .rail-label{
font-size: 0.6875rem;
font-weight: 600;
text-transform: uppercase;
@@ -752,13 +748,13 @@
margin-bottom: 0.625rem;
}
-.rail-engine {
+.plugins-page .rail-engine{
display: flex;
align-items: center;
gap: 0.625rem;
}
-.rail-engine-icon {
+.plugins-page .rail-engine-icon{
width: 34px;
height: 34px;
display: flex;
@@ -770,30 +766,30 @@
flex-shrink: 0;
}
-.rail-engine-meta {
+.plugins-page .rail-engine-meta{
display: flex;
flex-direction: column;
min-width: 0;
flex: 1;
}
-.rail-engine-name {
+.plugins-page .rail-engine-name{
font-weight: 600;
font-size: 0.875rem;
color: var(--text-primary);
}
-.rail-engine-lib {
+.plugins-page .rail-engine-lib{
font-size: 0.75rem;
color: var(--text-muted);
}
-.rail-stats {
+.plugins-page .rail-stats{
display: flex;
gap: 0.75rem;
}
-.rail-stat {
+.plugins-page .rail-stat{
flex: 1;
background: var(--bg-light);
border-radius: 8px;
@@ -801,7 +797,7 @@
text-align: center;
}
-.rail-stat-num {
+.plugins-page .rail-stat-num{
display: block;
font-size: 1.25rem;
font-weight: 700;
@@ -809,14 +805,14 @@
line-height: 1.2;
}
-.rail-stat-label {
+.plugins-page .rail-stat-label{
font-size: 0.6875rem;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.04em;
}
-.rail-active-list {
+.plugins-page .rail-active-list{
list-style: none;
margin: 0;
padding: 0;
@@ -825,13 +821,13 @@
gap: 0.5rem;
}
-.rail-active-item {
+.plugins-page .rail-active-item{
display: flex;
align-items: center;
gap: 0.5rem;
}
-.rail-active-name {
+.plugins-page .rail-active-name{
font-size: 0.8125rem;
color: var(--text-primary);
flex: 1;
@@ -840,20 +836,20 @@
white-space: nowrap;
}
-.rail-active-type {
+.plugins-page .rail-active-type{
font-size: 0.625rem;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.04em;
}
-.rail-empty {
+.plugins-page .rail-empty{
font-size: 0.8125rem;
color: var(--text-muted);
}
/* Engine that isn't the active one — non-actionable (switch via Settings + restart) */
-.btn-available {
+.plugins-page .btn-available{
flex: 1;
display: flex;
align-items: center;
@@ -870,24 +866,24 @@
}
/* Uninstall icon button — neutral, red on hover */
-.btn-action-danger:hover {
+.plugins-page .btn-action-danger:hover{
background: rgba(239, 68, 68, 0.1);
border-color: rgba(239, 68, 68, 0.3);
}
-.btn-action-danger:hover svg {
+.plugins-page .btn-action-danger:hover svg{
color: #ef4444;
}
/* Install modal */
-.install-hint {
+.plugins-page .install-hint{
font-size: 0.875rem;
color: var(--text-secondary);
line-height: 1.5;
margin-bottom: 1rem;
}
-.install-drop {
+.plugins-page .install-drop{
display: flex;
flex-direction: column;
align-items: center;
@@ -902,29 +898,29 @@
text-align: center;
}
-.install-drop:hover {
+.plugins-page .install-drop:hover{
border-color: var(--primary, #25d366);
color: var(--text-secondary);
}
-.install-drop.has-file {
+.plugins-page .install-drop.has-file{
border-style: solid;
border-color: var(--primary, #25d366);
color: var(--text-primary);
background: rgba(34, 197, 94, 0.05);
}
-.install-drop-name {
+.plugins-page .install-drop-name{
font-size: 0.875rem;
word-break: break-all;
}
@media (max-width: 860px) {
- .plugins-layout {
+ .plugins-page .plugins-layout{
flex-direction: column;
}
- .plugins-rail {
+ .plugins-page .plugins-rail{
flex-basis: auto;
width: 100%;
position: static;
@@ -932,14 +928,14 @@
}
/* ── Install modal: Upload / Catalog tabs + catalog list ─────────────────── */
-.install-tabs {
+.plugins-page .install-tabs{
display: flex;
gap: 4px;
padding: 0 20px;
border-bottom: 1px solid var(--border, #e5e7eb);
}
-.install-tab {
+.plugins-page .install-tab{
display: inline-flex;
align-items: center;
gap: 6px;
@@ -952,20 +948,20 @@
cursor: pointer;
}
-.install-tab.active {
+.plugins-page .install-tab.active{
color: var(--text, #111827);
border-bottom-color: var(--primary, #25d366);
}
/* Config modal tabs (Configuration / Sessions) */
-.config-modal .modal-tabs {
+.plugins-page .config-modal .modal-tabs{
display: flex;
gap: 4px;
padding: 0 1.5rem;
border-bottom: 1px solid var(--border);
}
-.config-modal .modal-tab {
+.plugins-page .config-modal .modal-tab{
padding: 0.625rem 0.9rem;
background: none;
border: none;
@@ -976,33 +972,33 @@
cursor: pointer;
}
-.config-modal .modal-tab.active {
+.plugins-page .config-modal .modal-tab.active{
color: var(--text-primary);
border-bottom-color: var(--primary);
}
/* Sessions tab */
-.sessions-tab {
+.plugins-page .sessions-tab{
display: flex;
flex-direction: column;
gap: 1.5rem;
}
-.sessions-section > h3 {
+.plugins-page .sessions-section > h3{
font-size: 0.9375rem;
font-weight: 600;
color: var(--text-primary);
margin: 0 0 0.25rem;
}
-.sessions-section > small {
+.plugins-page .sessions-section > small{
display: block;
color: var(--text-muted);
font-size: 0.75rem;
margin-bottom: 0.75rem;
}
-.sessions-radio {
+.plugins-page .sessions-radio{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -1012,7 +1008,7 @@
cursor: pointer;
}
-.sessions-checklist {
+.plugins-page .sessions-checklist{
display: flex;
flex-direction: column;
gap: 0.25rem;
@@ -1021,7 +1017,7 @@
overflow-y: auto;
}
-.sessions-check {
+.plugins-page .sessions-check{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -1030,13 +1026,13 @@
cursor: pointer;
}
-.sessions-empty {
+.plugins-page .sessions-empty{
margin: 0.25rem 0 0.75rem 1.5rem;
font-size: 0.8125rem;
color: var(--text-muted);
}
-.sessions-select {
+.plugins-page .sessions-select{
width: 100%;
padding: 0.6rem 0.85rem;
border: 1px solid var(--border);
@@ -1047,14 +1043,14 @@
box-sizing: border-box;
}
-.sessions-override-actions {
+.plugins-page .sessions-override-actions{
display: flex;
justify-content: flex-end;
gap: 0.5rem;
margin-top: 0.5rem;
}
-.catalog-empty {
+.plugins-page .catalog-empty{
display: flex;
align-items: center;
justify-content: center;
@@ -1064,12 +1060,32 @@
font-size: 0.875rem;
}
-.catalog-error {
+.plugins-page .catalog-error{
flex-wrap: wrap;
color: var(--danger, #dc2626);
}
-.catalog-list {
+.plugins-page .catalog-search{
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.5rem 0.75rem;
+ margin-bottom: 0.75rem;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ color: var(--text-muted);
+}
+
+.plugins-page .catalog-search input{
+ flex: 1;
+ border: none;
+ background: transparent;
+ outline: none;
+ font-size: 0.9375rem;
+ color: var(--text-primary);
+}
+
+.plugins-page .catalog-list{
display: flex;
flex-direction: column;
gap: 8px;
@@ -1077,7 +1093,7 @@
overflow-y: auto;
}
-.catalog-row {
+.plugins-page .catalog-row{
display: flex;
align-items: center;
justify-content: space-between;
@@ -1087,27 +1103,27 @@
border-radius: 8px;
}
-.catalog-row-info {
+.plugins-page .catalog-row-info{
min-width: 0;
}
-.catalog-row-name {
+.plugins-page .catalog-row-name{
font-weight: 600;
}
-.catalog-row-version {
+.plugins-page .catalog-row-version{
color: var(--text-secondary, #6b7280);
font-weight: 400;
font-size: 0.85em;
}
-.catalog-row-desc {
+.plugins-page .catalog-row-desc{
color: var(--text-secondary, #6b7280);
font-size: 0.85rem;
margin-top: 2px;
}
-.catalog-row-meta {
+.plugins-page .catalog-row-meta{
display: flex;
align-items: center;
gap: 8px;
@@ -1116,15 +1132,15 @@
color: var(--text-secondary, #6b7280);
}
-.catalog-badge.update {
+.plugins-page .catalog-badge.update{
color: var(--primary, #25d366);
}
-.catalog-row-action {
+.plugins-page .catalog-row-action{
flex-shrink: 0;
}
-.catalog-installed {
+.plugins-page .catalog-installed{
display: inline-flex;
align-items: center;
gap: 6px;
diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsx
index f5a1128ff..a7c1ea4bf 100644
--- a/dashboard/src/pages/Plugins.tsx
+++ b/dashboard/src/pages/Plugins.tsx
@@ -1,6 +1,7 @@
import { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { localizePlugin } from '../utils/localizePlugin';
+import { coerceFieldInput, emptyForField } from '../utils/pluginConfigForm';
import { useQueryClient } from '@tanstack/react-query';
import {
Puzzle,
@@ -22,6 +23,7 @@ import {
Globe,
Download,
Plus,
+ Search,
} from 'lucide-react';
import { pluginsApi, infraApi } from '../services/api';
import type { Plugin, CatalogPlugin, PluginConfigField } from '../services/api';
@@ -55,27 +57,6 @@ interface EngineConfig {
browserArgs: string;
}
-/** A blank value for a field, used to seed a form and to add a new array row. */
-function emptyForField(field: PluginConfigField): unknown {
- if (field.default !== undefined) return field.default;
- // A <select> always shows its first option, so seed enum state to it — otherwise the form shows a
- // value the user never picked and would save '' instead.
- if (field.enum && field.enum.length > 0) return field.enum[0];
- switch (field.type) {
- case 'boolean':
- return false;
- case 'array':
- return [];
- case 'object': {
- const obj: Record<string, unknown> = {};
- if (field.properties) for (const [k, sub] of Object.entries(field.properties)) obj[k] = emptyForField(sub);
- return obj;
- }
- default: // string | number | textarea — empty string (number coerced on input)
- return '';
- }
-}
-
/**
* Build a sparse per-session config override from a full edited config: include only non-secret keys
* whose value differs from the Global base (so untouched keys keep inheriting Global), plus every
@@ -243,6 +224,7 @@ function ConfigField({
<textarea
value={value === undefined || value === null ? '' : String(value)}
placeholder={field.default !== undefined ? String(field.default) : undefined}
+ required={field.required}
minLength={field.min}
maxLength={field.max}
rows={4}
@@ -262,14 +244,13 @@ function ConfigField({
value={value === undefined || value === null ? '' : String(value)}
placeholder={field.default !== undefined ? String(field.default) : undefined}
autoComplete={field.secret ? 'new-password' : undefined}
+ required={field.required}
min={field.type === 'number' ? field.min : undefined}
max={field.type === 'number' ? field.max : undefined}
minLength={field.type !== 'number' ? field.min : undefined}
maxLength={field.type !== 'number' ? field.max : undefined}
pattern={field.type !== 'number' ? field.pattern : undefined}
- onChange={e =>
- onChange(field.type === 'number' ? (e.target.value === '' ? '' : Number(e.target.value)) : e.target.value)
- }
+ onChange={e => onChange(coerceFieldInput(field, e.target.value))}
/>
{desc}
</div>
@@ -335,7 +316,11 @@ function PluginConfigUi({ plugin, sessionId }: { plugin: Plugin; sessionId?: str
void (async () => {
try {
if (sessionId)
- await pluginsApi.updateSessionConfig(plugin.id, sessionId, sparseSessionOverride(msg.config ?? {}, plugin));
+ await pluginsApi.updateSessionConfig(
+ plugin.id,
+ sessionId,
+ sparseSessionOverride(msg.config ?? {}, plugin),
+ );
else await pluginsApi.updateConfig(plugin.id, msg.config ?? {});
void queryClient.invalidateQueries({ queryKey: queryKeys.plugins });
post({ type: 'config:saved' });
@@ -407,6 +392,7 @@ function SessionsTab({ plugin }: { plugin: Plugin }) {
const [selSession, setSelSession] = useState<string>('');
const [overrideCfg, setOverrideCfg] = useState<Record<string, unknown>>({});
const [savingOverride, setSavingOverride] = useState(false);
+ const overrideFormRef = useRef<HTMLFormElement>(null);
// Seed the override form from the resolved slice (the session's override value where set, else base).
// Keyed on selSession + plugin.id (NOT the plugin object): `configPlugin` is derived from the live
@@ -429,6 +415,8 @@ function SessionsTab({ plugin }: { plugin: Plugin }) {
const saveOverride = async () => {
if (!selSession || !plugin.configSchema?.properties) return;
+ // Enforce the schema's HTML constraint hints (required/min/max/pattern) before saving.
+ if (overrideFormRef.current && !overrideFormRef.current.reportValidity()) return;
setSavingOverride(true);
try {
await pluginsApi.updateSessionConfig(plugin.id, selSession, sparseSessionOverride(overrideCfg, plugin));
@@ -513,7 +501,7 @@ function SessionsTab({ plugin }: { plugin: Plugin }) {
<PluginConfigUi key={selSession} plugin={plugin} sessionId={selSession} />
) : selSession && plugin.configSchema ? (
<>
- <div className="config-form">
+ <form ref={overrideFormRef} className="config-form" onSubmit={e => e.preventDefault()}>
{Object.entries(lzProps ?? plugin.configSchema.properties).map(([key, field]) => (
<ConfigField
key={key}
@@ -523,7 +511,7 @@ function SessionsTab({ plugin }: { plugin: Plugin }) {
onChange={v => setOverrideCfg({ ...overrideCfg, [key]: v })}
/>
))}
- </div>
+ </form>
<div className="sessions-override-actions">
<button className="btn-secondary" onClick={() => void clearOverride()} disabled={savingOverride}>
{t('plugins.sessions.clearOverride')}
@@ -553,6 +541,7 @@ export default function Plugins() {
const loading = loadingPlugins;
const error = queryError instanceof Error ? queryError.message : null;
const [actionLoading, setActionLoading] = useState<string | null>(null);
+ const schemaFormRef = useRef<HTMLFormElement>(null);
const [showConfigModal, setShowConfigModal] = useState(false);
const [configPluginId, setConfigPluginId] = useState<string | null>(null);
@@ -576,6 +565,7 @@ export default function Plugins() {
const [catalog, setCatalog] = useState<CatalogPlugin[]>([]);
const [catalogLoading, setCatalogLoading] = useState(false);
const [catalogError, setCatalogError] = useState<string | null>(null);
+ const [catalogSearch, setCatalogSearch] = useState('');
const [installingId, setInstallingId] = useState<string | null>(null);
const refetchAll = () => {
@@ -594,7 +584,10 @@ export default function Plugins() {
}
refetchAll();
} catch (err) {
- toast.error(t('plugins.toasts.errorTitle'), err instanceof Error ? err.message : t('plugins.toasts.errorDefault'));
+ toast.error(
+ t('plugins.toasts.errorTitle'),
+ err instanceof Error ? err.message : t('plugins.toasts.errorDefault'),
+ );
} finally {
setActionLoading(null);
}
@@ -632,6 +625,8 @@ export default function Plugins() {
const handleSaveSchemaConfig = async () => {
if (!configPlugin) return;
+ // Enforce the schema's HTML constraint hints (required/min/max/pattern) before saving.
+ if (schemaFormRef.current && !schemaFormRef.current.reportValidity()) return;
setSavingConfig(true);
try {
await pluginsApi.updateConfig(configPlugin.id, schemaConfig);
@@ -858,138 +853,145 @@ export default function Plugins() {
<main className="plugins-main">
<div className="plugins-grid">
- {plugins.map(plugin => {
- const TypeIcon = pluginTypeIcons[plugin.type as PluginType] || Puzzle;
- const isLoading = actionLoading === plugin.id;
- const lz = localizePlugin(plugin, i18n.language);
-
- return (
- <div key={plugin.id} className="plugin-card">
- <div className={`plugin-card-header type-${plugin.type}`}>
- <div className="plugin-info">
- <div className="plugin-icon-wrapper">
- <TypeIcon size={20} />
- </div>
- <div>
- <h3 className="plugin-name">{lz.name}</h3>
- <span className="plugin-version">v{plugin.version}</span>
+ {plugins.map(plugin => {
+ const TypeIcon = pluginTypeIcons[plugin.type as PluginType] || Puzzle;
+ const isLoading = actionLoading === plugin.id;
+ const lz = localizePlugin(plugin, i18n.language);
+
+ return (
+ <div key={plugin.id} className="plugin-card">
+ <div className={`plugin-card-header type-${plugin.type}`}>
+ <div className="plugin-info">
+ <div className="plugin-icon-wrapper">
+ <TypeIcon size={20} />
+ </div>
+ <div>
+ <h3 className="plugin-name">{lz.name}</h3>
+ <span className="plugin-version">v{plugin.version}</span>
+ </div>
+ </div>
+ {plugin.builtIn && <span className="plugin-builtin-badge">{t('plugins.builtIn')}</span>}
</div>
- </div>
- {plugin.builtIn && <span className="plugin-builtin-badge">{t('plugins.builtIn')}</span>}
- </div>
- <div className="plugin-card-body">
- <p className="plugin-description">{lz.description || t('plugins.noDescription')}</p>
+ <div className="plugin-card-body">
+ <p className="plugin-description">{lz.description || t('plugins.noDescription')}</p>
- <div className="plugin-status-row">
- <div className="plugin-status">
- <span className={`status-dot ${plugin.status}`} />
- <span className="status-text">{plugin.status}</span>
- </div>
- <span className="plugin-type-label">{plugin.type}</span>
- </div>
-
- {plugin.error && (
- <div className="plugin-error">
- <p className="plugin-error-text">{plugin.error}</p>
- </div>
- )}
+ <div className="plugin-status-row">
+ <div className="plugin-status">
+ <span className={`status-dot ${plugin.status}`} />
+ <span className="status-text">{plugin.status}</span>
+ </div>
+ <span className="plugin-type-label">{plugin.type}</span>
+ </div>
- {plugin.provides && plugin.provides.length > 0 && (
- <div className="plugin-provides">
- {plugin.provides.map(item => (
- <span key={item} className="provides-tag">
- {item}
- </span>
- ))}
- </div>
- )}
+ {plugin.error && (
+ <div className="plugin-error">
+ <p className="plugin-error-text">{plugin.error}</p>
+ </div>
+ )}
- <div className="plugin-actions">
- {plugin.type === 'engine' ? (
- (() => {
- const enginePlugins = plugins.filter(p => p.type === 'engine');
- const isOnlyEngine = enginePlugins.length === 1;
- const isActive = plugin.status === 'enabled';
-
- if (isOnlyEngine && isActive) {
- return (
- <span className="btn-required">
- <CheckCircle size={16} />
- {t('plugins.required')}
- </span>
- );
- } else if (isActive) {
- return (
- <span className="btn-active">
- <CheckCircle size={16} />
- {t('plugins.active')}
- </span>
- );
- } else {
- // Engines are pinned to engine.type and switched via Settings + restart, not at
- // runtime — show "available" instead of a misleading "Activate" that the API rejects.
- return (
- <span
- className="btn-available"
- title={t('plugins.engineSwitchHint', 'Set as the active engine in Settings, then restart')}
- >
- <Cpu size={16} />
- {t('plugins.available', 'Available')}
+ {plugin.provides && plugin.provides.length > 0 && (
+ <div className="plugin-provides">
+ {plugin.provides.map(item => (
+ <span key={item} className="provides-tag">
+ {item}
</span>
- );
- }
- })()
- ) : (
- <button
- onClick={() => handleToggle(plugin)}
- disabled={isLoading}
- className={`btn-toggle ${plugin.status === 'enabled' ? 'disable' : 'enable'}`}
- >
- {isLoading ? (
- <Loader2 size={16} className="animate-spin" />
- ) : plugin.status === 'enabled' ? (
- <>
- <PowerOff size={16} />
- {t('plugins.disable')}
- </>
+ ))}
+ </div>
+ )}
+
+ <div className="plugin-actions">
+ {plugin.type === 'engine' ? (
+ (() => {
+ const enginePlugins = plugins.filter(p => p.type === 'engine');
+ const isOnlyEngine = enginePlugins.length === 1;
+ const isActive = plugin.status === 'enabled';
+
+ if (isOnlyEngine && isActive) {
+ return (
+ <span className="btn-required">
+ <CheckCircle size={16} />
+ {t('plugins.required')}
+ </span>
+ );
+ } else if (isActive) {
+ return (
+ <span className="btn-active">
+ <CheckCircle size={16} />
+ {t('plugins.active')}
+ </span>
+ );
+ } else {
+ // Engines are pinned to engine.type and switched via Settings + restart, not at
+ // runtime — show "available" instead of a misleading "Activate" that the API rejects.
+ return (
+ <span
+ className="btn-available"
+ title={t(
+ 'plugins.engineSwitchHint',
+ 'Set as the active engine in Settings, then restart',
+ )}
+ >
+ <Cpu size={16} />
+ {t('plugins.available', 'Available')}
+ </span>
+ );
+ }
+ })()
) : (
- <>
- <Power size={16} />
- {t('plugins.enable')}
- </>
+ <button
+ onClick={() => handleToggle(plugin)}
+ disabled={isLoading}
+ className={`btn-toggle ${plugin.status === 'enabled' ? 'disable' : 'enable'}`}
+ >
+ {isLoading ? (
+ <Loader2 size={16} className="animate-spin" />
+ ) : plugin.status === 'enabled' ? (
+ <>
+ <PowerOff size={16} />
+ {t('plugins.disable')}
+ </>
+ ) : (
+ <>
+ <Power size={16} />
+ {t('plugins.enable')}
+ </>
+ )}
+ </button>
)}
- </button>
- )}
- <button
- onClick={() => handleHealthCheck(plugin.id)}
- disabled={isLoading}
- className="btn-action"
- title={t('plugins.healthCheck')}
- >
- <CheckCircle size={16} />
- </button>
+ <button
+ onClick={() => handleHealthCheck(plugin.id)}
+ disabled={isLoading}
+ className="btn-action"
+ title={t('plugins.healthCheck')}
+ >
+ <CheckCircle size={16} />
+ </button>
- <button className="btn-action" title={t('plugins.configure')} onClick={() => handleOpenConfig(plugin)}>
- <Settings size={16} />
- </button>
+ <button
+ className="btn-action"
+ title={t('plugins.configure')}
+ onClick={() => handleOpenConfig(plugin)}
+ >
+ <Settings size={16} />
+ </button>
- {!plugin.builtIn && (
- <button
- className="btn-action btn-action-danger"
- title={t('plugins.uninstall', 'Uninstall')}
- onClick={() => void handleUninstall(plugin)}
- disabled={isLoading}
- >
- <Trash2 size={16} />
- </button>
- )}
+ {!plugin.builtIn && (
+ <button
+ className="btn-action btn-action-danger"
+ title={t('plugins.uninstall', 'Uninstall')}
+ onClick={() => void handleUninstall(plugin)}
+ disabled={isLoading}
+ >
+ <Trash2 size={16} />
+ </button>
+ )}
+ </div>
+ </div>
</div>
- </div>
- </div>
- );
- })}
+ );
+ })}
</div>
</main>
</div>
@@ -1030,7 +1032,10 @@ export default function Plugins() {
<>
<div className="modal-body">
<p className="install-hint">
- {t('plugins.installModal.hint', 'Upload a plugin packaged as a .zip (with a manifest.json). It runs sandboxed once enabled.')}
+ {t(
+ 'plugins.installModal.hint',
+ 'Upload a plugin packaged as a .zip (with a manifest.json). It runs sandboxed once enabled.',
+ )}
</p>
<label className={`install-drop${installFile ? ' has-file' : ''}`}>
<input
@@ -1049,7 +1054,11 @@ export default function Plugins() {
<button className="btn-secondary" onClick={() => setShowInstallModal(false)} disabled={installing}>
{t('common.cancel', 'Cancel')}
</button>
- <button className="btn-primary" onClick={() => void handleInstall()} disabled={!installFile || installing}>
+ <button
+ className="btn-primary"
+ onClick={() => void handleInstall()}
+ disabled={!installFile || installing}
+ >
{installing ? <Loader2 size={16} className="animate-spin" /> : <Upload size={16} />}
{t('plugins.install', 'Install plugin')}
</button>
@@ -1059,7 +1068,10 @@ export default function Plugins() {
<>
<div className="modal-body">
<p className="install-hint">
- {t('plugins.installModal.catalogHint', 'Install directly from the OpenWA plugin catalog. The .zip is fetched server-side through the SSRF guard, then validated and sandboxed.')}
+ {t(
+ 'plugins.installModal.catalogHint',
+ 'Install directly from the OpenWA plugin catalog. The .zip is fetched server-side through the SSRF guard, then validated and sandboxed.',
+ )}
</p>
{catalogLoading ? (
<div className="catalog-empty">
@@ -1075,64 +1087,92 @@ export default function Plugins() {
) : catalog.length === 0 ? (
<div className="catalog-empty">{t('plugins.catalog.empty', 'No plugins in the catalog.')}</div>
) : (
- <div className="catalog-list">
- {catalog.map(entry => {
- const lz = localizePlugin(entry, i18n.language);
- return (
- <div className="catalog-row" key={entry.id}>
- <div className="catalog-row-info">
- <div className="catalog-row-name">
- {lz.name} <span className="catalog-row-version">v{entry.version}</span>
+ (() => {
+ const q = catalogSearch.trim().toLowerCase();
+ const filtered = q
+ ? catalog.filter(e =>
+ [e.name, e.description, e.author, e.id].some(f => f?.toLowerCase().includes(q)),
+ )
+ : catalog;
+ return (
+ <>
+ <div className="catalog-search">
+ <Search size={15} />
+ <input
+ type="text"
+ value={catalogSearch}
+ onChange={e => setCatalogSearch(e.target.value)}
+ placeholder={t('plugins.catalog.searchPlaceholder', 'Search plugins…')}
+ />
+ </div>
+ {filtered.length === 0 ? (
+ <div className="catalog-empty">
+ {t('plugins.catalog.noMatch', 'No plugins match your search.')}
</div>
- {lz.description && <div className="catalog-row-desc">{lz.description}</div>}
- <div className="catalog-row-meta">
- {entry.author && <span className="catalog-row-author">{entry.author}</span>}
- {entry.updateAvailable && (
- <span className="catalog-badge update">
- {t('plugins.catalog.updateAvailable', 'Update available')} (v{entry.installedVersion} → v{entry.version})
- </span>
- )}
+ ) : (
+ <div className="catalog-list">
+ {filtered.map(entry => {
+ const lz = localizePlugin(entry, i18n.language);
+ return (
+ <div className="catalog-row" key={entry.id}>
+ <div className="catalog-row-info">
+ <div className="catalog-row-name">
+ {lz.name} <span className="catalog-row-version">v{entry.version}</span>
+ </div>
+ {lz.description && <div className="catalog-row-desc">{lz.description}</div>}
+ <div className="catalog-row-meta">
+ {entry.author && <span className="catalog-row-author">{entry.author}</span>}
+ {entry.updateAvailable && (
+ <span className="catalog-badge update">
+ {t('plugins.catalog.updateAvailable', 'Update available')} (v
+ {entry.installedVersion} → v{entry.version})
+ </span>
+ )}
+ </div>
+ </div>
+ <div className="catalog-row-action">
+ {entry.installed ? (
+ entry.updateAvailable ? (
+ <button
+ className="btn-primary"
+ disabled={installingId !== null || !entry.download}
+ onClick={() => void handleUpdateFromCatalog(entry)}
+ >
+ {installingId === entry.id ? (
+ <Loader2 size={15} className="animate-spin" />
+ ) : (
+ <Download size={15} />
+ )}
+ {t('plugins.catalog.update', 'Update')}
+ </button>
+ ) : (
+ <span className="catalog-installed">
+ <CheckCircle size={15} /> {t('plugins.catalog.installed', 'Installed')}
+ </span>
+ )
+ ) : (
+ <button
+ className="btn-primary"
+ disabled={installingId !== null || !entry.download}
+ onClick={() => void handleInstallFromCatalog(entry)}
+ >
+ {installingId === entry.id ? (
+ <Loader2 size={15} className="animate-spin" />
+ ) : (
+ <Download size={15} />
+ )}
+ {t('plugins.catalog.install', 'Install')}
+ </button>
+ )}
+ </div>
+ </div>
+ );
+ })}
</div>
- </div>
- <div className="catalog-row-action">
- {entry.installed ? (
- entry.updateAvailable ? (
- <button
- className="btn-primary"
- disabled={installingId !== null || !entry.download}
- onClick={() => void handleUpdateFromCatalog(entry)}
- >
- {installingId === entry.id ? (
- <Loader2 size={15} className="animate-spin" />
- ) : (
- <Download size={15} />
- )}
- {t('plugins.catalog.update', 'Update')}
- </button>
- ) : (
- <span className="catalog-installed">
- <CheckCircle size={15} /> {t('plugins.catalog.installed', 'Installed')}
- </span>
- )
- ) : (
- <button
- className="btn-primary"
- disabled={installingId !== null || !entry.download}
- onClick={() => void handleInstallFromCatalog(entry)}
- >
- {installingId === entry.id ? (
- <Loader2 size={15} className="animate-spin" />
- ) : (
- <Download size={15} />
- )}
- {t('plugins.catalog.install', 'Install')}
- </button>
- )}
- </div>
- </div>
- );
- })}
- </div>
+ )}
+ </>
+ );
+ })()
)}
</div>
<div className="modal-footer">
@@ -1146,135 +1186,144 @@ export default function Plugins() {
</div>
)}
- {showConfigModal && configPlugin && (() => {
- const lz = localizePlugin(configPlugin, i18n.language);
- // Session-scoped, non-engine plugins get a Configuration/Sessions tab split; others keep one body.
- const showTabs = configPlugin.type !== 'engine' && configPlugin.sessionScoped !== false;
- return (
- <div className="modal-overlay" onClick={() => setShowConfigModal(false)}>
- <div className="modal config-modal" onClick={e => e.stopPropagation()}>
- <div className="modal-header">
- <h2>{t('plugins.config.title', { name: lz.name })}</h2>
- <button className="btn-icon" onClick={() => setShowConfigModal(false)}>
- <X size={20} />
- </button>
- </div>
-
- {showTabs && (
- <div className="modal-tabs">
- <button
- className={`modal-tab ${configTab === 'config' ? 'active' : ''}`}
- onClick={() => setConfigTab('config')}
- >
- {t('plugins.config.tabConfig')}
- </button>
- <button
- className={`modal-tab ${configTab === 'sessions' ? 'active' : ''}`}
- onClick={() => setConfigTab('sessions')}
- >
- {t('plugins.config.tabSessions')}
- </button>
- </div>
- )}
+ {showConfigModal &&
+ configPlugin &&
+ (() => {
+ const lz = localizePlugin(configPlugin, i18n.language);
+ // Session-scoped, non-engine plugins get a Configuration/Sessions tab split; others keep one body.
+ const showTabs = configPlugin.type !== 'engine' && configPlugin.sessionScoped !== false;
+ return (
+ <div className="modal-overlay" onClick={() => setShowConfigModal(false)}>
+ <div className="modal config-modal" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>{t('plugins.config.title', { name: lz.name })}</h2>
+ <button className="btn-icon" onClick={() => setShowConfigModal(false)}>
+ <X size={20} />
+ </button>
+ </div>
- <div className="modal-body">
- {showTabs && configTab === 'sessions' ? (
- <SessionsTab plugin={configPlugin} />
- ) : configPlugin.type === 'engine' ? (
- <>
- <div className="config-info-banner">
- <AlertCircle size={16} />
- <span>{t('plugins.config.restartNotice')}</span>
+ {showTabs && (
+ <div className="modal-tabs">
+ <button
+ className={`modal-tab ${configTab === 'config' ? 'active' : ''}`}
+ onClick={() => setConfigTab('config')}
+ >
+ {t('plugins.config.tabConfig')}
+ </button>
+ <button
+ className={`modal-tab ${configTab === 'sessions' ? 'active' : ''}`}
+ onClick={() => setConfigTab('sessions')}
+ >
+ {t('plugins.config.tabSessions')}
+ </button>
</div>
+ )}
- <div className="config-form">
- <div className="form-group">
- <label>{t('plugins.config.engineType')}</label>
- <select
- value={engineConfig.type}
- onChange={e => setEngineConfig({ ...engineConfig, type: e.target.value })}
- >
- <option value="whatsapp-web.js">WhatsApp Web.js</option>
- </select>
- </div>
-
- <div className="form-group toggle-group">
- <div className="toggle-info">
- <label>{t('plugins.config.headless')}</label>
- <small>{t('plugins.config.headlessDesc')}</small>
+ <div className="modal-body">
+ {showTabs && configTab === 'sessions' ? (
+ <SessionsTab plugin={configPlugin} />
+ ) : configPlugin.type === 'engine' ? (
+ <>
+ <div className="config-info-banner">
+ <AlertCircle size={16} />
+ <span>{t('plugins.config.restartNotice')}</span>
</div>
- <label className="toggle-switch">
- <input
- type="checkbox"
- checked={engineConfig.headless}
- onChange={e => setEngineConfig({ ...engineConfig, headless: e.target.checked })}
- />
- <span className="toggle-slider"></span>
- </label>
- </div>
- <div className="form-group">
- <label>{t('plugins.config.sessionDataPath')}</label>
- <input
- type="text"
- value={engineConfig.sessionDataPath}
- onChange={e => setEngineConfig({ ...engineConfig, sessionDataPath: e.target.value })}
- />
- </div>
+ {/* Only the browser engine (whatsapp-web.js) has Puppeteer settings. Baileys is a
+ WebSocket client with no browser, so headless/browser-args don't apply. */}
+ {configPlugin.id === 'whatsapp-web.js' ? (
+ <div className="config-form">
+ <div className="form-group toggle-group">
+ <div className="toggle-info">
+ <label>{t('plugins.config.headless')}</label>
+ <small>{t('plugins.config.headlessDesc')}</small>
+ </div>
+ <label className="toggle-switch">
+ <input
+ type="checkbox"
+ checked={engineConfig.headless}
+ onChange={e => setEngineConfig({ ...engineConfig, headless: e.target.checked })}
+ />
+ <span className="toggle-slider"></span>
+ </label>
+ </div>
+
+ <div className="form-group">
+ <label>{t('plugins.config.sessionDataPath')}</label>
+ <input
+ type="text"
+ value={engineConfig.sessionDataPath}
+ onChange={e => setEngineConfig({ ...engineConfig, sessionDataPath: e.target.value })}
+ />
+ </div>
- <div className="form-group">
- <label>{t('plugins.config.browserArgs')}</label>
- <input
- type="text"
- value={engineConfig.browserArgs}
- onChange={e => setEngineConfig({ ...engineConfig, browserArgs: e.target.value })}
- placeholder="--no-sandbox --disable-gpu"
- />
+ <div className="form-group">
+ <label>{t('plugins.config.browserArgs')}</label>
+ <input
+ type="text"
+ value={engineConfig.browserArgs}
+ onChange={e => setEngineConfig({ ...engineConfig, browserArgs: e.target.value })}
+ placeholder="--no-sandbox --disable-gpu"
+ />
+ </div>
+ </div>
+ ) : (
+ <div className="no-config">
+ <Cpu size={48} style={{ opacity: 0.3 }} />
+ <p>
+ {t(
+ 'plugins.config.noBrowserEngine',
+ 'This engine connects over WebSocket — it has no browser, so there are no headless or browser-argument settings here. Its options are set via environment variables, and the active engine is selected with ENGINE_TYPE (a restart applies the change).',
+ )}
+ </p>
+ </div>
+ )}
+ </>
+ ) : configPlugin.configUi ? (
+ <PluginConfigUi plugin={configPlugin} />
+ ) : lz.configSchema && Object.keys(lz.configSchema.properties).length > 0 ? (
+ <form ref={schemaFormRef} className="config-form" onSubmit={e => e.preventDefault()}>
+ {Object.entries(lz.configSchema.properties).map(([key, field]) => (
+ <ConfigField
+ key={key}
+ field={field}
+ label={field.title || key}
+ value={schemaConfig[key]}
+ onChange={v => setSchemaConfig({ ...schemaConfig, [key]: v })}
+ />
+ ))}
+ </form>
+ ) : (
+ <div className="no-config">
+ <Settings size={48} style={{ opacity: 0.3 }} />
+ <p>{t('plugins.config.noOptions')}</p>
</div>
- </div>
- </>
- ) : configPlugin.configUi ? (
- <PluginConfigUi plugin={configPlugin} />
- ) : lz.configSchema && Object.keys(lz.configSchema.properties).length > 0 ? (
- <div className="config-form">
- {Object.entries(lz.configSchema.properties).map(([key, field]) => (
- <ConfigField
- key={key}
- field={field}
- label={field.title || key}
- value={schemaConfig[key]}
- onChange={v => setSchemaConfig({ ...schemaConfig, [key]: v })}
- />
- ))}
- </div>
- ) : (
- <div className="no-config">
- <Settings size={48} style={{ opacity: 0.3 }} />
- <p>{t('plugins.config.noOptions')}</p>
+ )}
</div>
- )}
- </div>
- <div className="modal-footer">
- <button className="btn-secondary" onClick={() => setShowConfigModal(false)}>
- {t('common.close')}
- </button>
- {/* The Sessions tab has its own Save/Clear actions; the footer Save is config-tab only. */}
- {showTabs && configTab === 'sessions' ? null : configPlugin.type === 'engine' ? (
- <button className="btn-primary" onClick={handleSaveConfig} disabled={savingConfig}>
- {savingConfig ? <Loader2 size={16} className="animate-spin" /> : t('plugins.config.save')}
- </button>
- ) : configPlugin.configUi ? null : lz.configSchema &&
- Object.keys(lz.configSchema.properties).length > 0 ? (
- <button className="btn-primary" onClick={handleSaveSchemaConfig} disabled={savingConfig}>
- {savingConfig ? <Loader2 size={16} className="animate-spin" /> : t('plugins.config.save')}
- </button>
- ) : null}
+ <div className="modal-footer">
+ <button className="btn-secondary" onClick={() => setShowConfigModal(false)}>
+ {t('common.close')}
+ </button>
+ {/* The Sessions tab has its own Save/Clear actions; the footer Save is config-tab only.
+ Only the browser engine has savable settings — Baileys shows an info panel, no Save. */}
+ {showTabs && configTab === 'sessions' ? null : configPlugin.type === 'engine' ? (
+ configPlugin.id === 'whatsapp-web.js' ? (
+ <button className="btn-primary" onClick={handleSaveConfig} disabled={savingConfig}>
+ {savingConfig ? <Loader2 size={16} className="animate-spin" /> : t('plugins.config.save')}
+ </button>
+ ) : null
+ ) : configPlugin.configUi ? null : lz.configSchema &&
+ Object.keys(lz.configSchema.properties).length > 0 ? (
+ <button className="btn-primary" onClick={handleSaveSchemaConfig} disabled={savingConfig}>
+ {savingConfig ? <Loader2 size={16} className="animate-spin" /> : t('plugins.config.save')}
+ </button>
+ ) : null}
+ </div>
+ </div>
</div>
- </div>
- </div>
- );
- })()}
+ );
+ })()}
</div>
);
}
diff --git a/dashboard/src/pages/Sessions.css b/dashboard/src/pages/Sessions.css
index 3a9dafdef..1d5160e22 100644
--- a/dashboard/src/pages/Sessions.css
+++ b/dashboard/src/pages/Sessions.css
@@ -1,15 +1,15 @@
-.sessions-page {
+.sessions-page{
padding: 2rem;
width: 100%;
box-sizing: border-box;
}
-.page-header {
+.sessions-page .page-header{
margin-bottom: 2rem;
width: 100%;
}
-.header-content {
+.sessions-page .header-content{
display: flex;
justify-content: space-between;
align-items: center;
@@ -19,7 +19,7 @@
/* H1 inherited from global */
-.btn-primary {
+.sessions-page .btn-primary{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -34,17 +34,17 @@
transition: background 0.2s;
}
-.btn-primary:hover {
+.sessions-page .btn-primary:hover{
background: var(--primary-hover);
}
-.filters-bar {
+.sessions-page .filters-bar{
display: flex;
gap: 1rem;
margin-bottom: 1.5rem;
}
-.search-input {
+.sessions-page .search-input{
display: flex;
align-items: center;
gap: 0.75rem;
@@ -56,12 +56,12 @@
border-radius: var(--radius);
}
-.search-input svg {
+.sessions-page .search-input svg{
color: var(--text-muted);
flex-shrink: 0;
}
-.search-input input {
+.sessions-page .search-input input{
flex: 1;
border: none;
background: none;
@@ -69,11 +69,11 @@
color: var(--text-primary);
}
-.search-input input:focus {
+.sessions-page .search-input input:focus{
outline: none;
}
-.filter-group {
+.sessions-page .filter-group{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -83,11 +83,11 @@
border-radius: var(--radius);
}
-.filter-group svg {
+.sessions-page .filter-group svg{
color: var(--text-muted);
}
-.filter-group select {
+.sessions-page .filter-group select{
padding: 0.75rem 0;
border: none;
background: none;
@@ -97,19 +97,19 @@
cursor: pointer;
}
-.filter-group select:focus {
+.sessions-page .filter-group select:focus{
outline: none;
box-shadow: none;
}
-.sessions-grid {
+.sessions-page .sessions-grid{
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 1.5rem;
width: 100%;
}
-.session-card {
+.sessions-page .session-card{
background: var(--bg-white);
border-radius: 12px;
padding: 1.5rem;
@@ -117,14 +117,14 @@
border: 1px solid var(--border);
}
-.card-header {
+.sessions-page .card-header{
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.25rem;
}
-.card-header h3 {
+.sessions-page .card-header h3{
/* Inherits from H3 */
margin: 0;
white-space: nowrap;
@@ -133,7 +133,7 @@
max-width: 180px;
}
-.qr-placeholder {
+.sessions-page .qr-placeholder{
display: flex;
flex-direction: column;
align-items: center;
@@ -144,33 +144,33 @@
margin-bottom: 1rem;
}
-.qr-icon {
+.sessions-page .qr-icon{
color: var(--text-muted);
margin-bottom: 0.75rem;
}
-.qr-placeholder p {
+.sessions-page .qr-placeholder p{
margin: 0;
color: var(--text-secondary);
font-size: 0.875rem;
}
-.session-info {
+.sessions-page .session-info{
margin-bottom: 1rem;
}
-.info-row {
+.sessions-page .info-row{
display: flex;
justify-content: space-between;
padding: 0.5rem 0;
border-bottom: 1px solid var(--border);
}
-.info-row:last-child {
+.sessions-page .info-row:last-child{
border-bottom: none;
}
-.info-label {
+.sessions-page .info-label{
font-size: 0.7rem;
font-weight: 600;
text-transform: uppercase;
@@ -178,17 +178,17 @@
color: var(--text-secondary);
}
-.info-value {
+.sessions-page .info-value{
font-size: 0.8125rem;
color: var(--text-primary);
font-weight: 500;
}
-.info-value.mono {
+.sessions-page .info-value.mono{
font-family: monospace;
}
-.info-value.error-text {
+.sessions-page .info-value.error-text{
color: var(--color-danger, #dc2626);
font-weight: 500;
max-width: 60%;
@@ -198,13 +198,13 @@
white-space: nowrap;
}
-.card-actions {
+.sessions-page .card-actions{
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
-.btn-action {
+.sessions-page .btn-action{
display: flex;
align-items: center;
gap: 0.375rem;
@@ -219,91 +219,91 @@
color: var(--text-secondary);
}
-.btn-action:hover {
+.sessions-page .btn-action:hover{
background: var(--bg-white);
color: var(--text-primary);
}
-.btn-action.danger {
+.sessions-page .btn-action.danger{
color: #dc2626;
}
-.btn-action.danger:hover {
+.sessions-page .btn-action.danger:hover{
background: #fee2e2;
border-color: #fecaca;
}
@media (max-width: 1400px) {
- .sessions-grid {
+ .sessions-page .sessions-grid{
grid-template-columns: repeat(3, 1fr);
}
}
@media (max-width: 1000px) {
- .sessions-grid {
+ .sessions-page .sessions-grid{
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 600px) {
- .sessions-grid {
+ .sessions-page .sessions-grid{
grid-template-columns: 1fr;
}
- .sessions-page {
+ .sessions-page{
padding: 1rem;
}
- .filters-bar {
+ .sessions-page .filters-bar{
flex-direction: column;
gap: 0.75rem;
}
- .search-input {
+ .sessions-page .search-input{
max-width: none;
}
- .filter-group {
+ .sessions-page .filter-group{
width: 100%;
justify-content: space-between;
}
- .filter-group select {
+ .sessions-page .filter-group select{
flex: 1;
}
- .header-content {
+ .sessions-page .header-content{
flex-direction: column;
align-items: stretch;
gap: 1rem;
}
- .sessions-page .btn-primary {
+ .sessions-page .btn-primary{
width: 100%;
justify-content: center;
}
- .session-card {
+ .sessions-page .session-card{
padding: 1rem;
}
- .card-actions {
+ .sessions-page .card-actions{
flex-direction: column;
}
- .card-actions .btn-action {
+ .sessions-page .card-actions .btn-action{
justify-content: center;
}
}
@media (max-width: 480px) {
- .sessions-page {
+ .sessions-page{
padding: 0.75rem;
}
}
/* Modal Overlay */
-.modal-overlay {
+.sessions-page .modal-overlay{
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
@@ -325,7 +325,7 @@
}
/* Modal Card */
-.modal {
+.sessions-page .modal{
background: var(--bg-white);
border-radius: 16px;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
@@ -346,7 +346,7 @@
}
}
-.modal-header {
+.sessions-page .modal-header{
display: flex;
justify-content: space-between;
align-items: center;
@@ -354,30 +354,30 @@
border-bottom: 1px solid var(--border);
}
-.modal-header h2 {
+.sessions-page .modal-header h2{
font-size: 1.25rem;
font-weight: 700;
color: var(--text-primary);
margin: 0;
}
-.modal-title {
+.sessions-page .modal-title{
display: flex;
flex-direction: column;
gap: 0.25rem;
}
-.session-name {
+.sessions-page .session-name{
font-size: 0.875rem;
font-weight: 500;
color: var(--text-muted);
}
-.modal-body {
+.sessions-page .modal-body{
padding: 1.5rem;
}
-.modal-body > label {
+.sessions-page .modal-body > label{
display: block;
font-size: 0.875rem;
font-weight: 600;
@@ -385,7 +385,7 @@
margin-bottom: 0.5rem;
}
-.modal-body input {
+.sessions-page .modal-body input{
width: 100%;
padding: 0.875rem 1rem;
border: 1px solid var(--border);
@@ -396,24 +396,24 @@
box-sizing: border-box;
}
-.modal-body input:focus {
+.sessions-page .modal-body input:focus{
outline: none;
border-color: var(--primary);
background: var(--bg-white);
box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.1);
}
-.modal-body input::placeholder {
+.sessions-page .modal-body input::placeholder{
color: var(--text-muted);
}
-.input-hint {
+.sessions-page .input-hint{
margin: 0.5rem 0 0;
font-size: 0.75rem;
color: var(--text-muted);
}
-.input-hint code {
+.sessions-page .input-hint code{
background: var(--bg-light);
padding: 0.125rem 0.375rem;
border-radius: 4px;
@@ -421,14 +421,14 @@
font-size: 0.7rem;
}
-.input-error {
+.sessions-page .input-error{
margin: 0.5rem 0 0;
font-size: 0.75rem;
color: #dc2626;
font-weight: 500;
}
-.modal-footer {
+.sessions-page .modal-footer{
display: flex;
justify-content: flex-end;
gap: 0.75rem;
@@ -436,7 +436,7 @@
}
/* Secondary Button */
-.btn-secondary {
+.sessions-page .btn-secondary{
padding: 0.75rem 1.25rem;
background: var(--bg-light);
color: var(--text-secondary);
@@ -448,13 +448,13 @@
transition: all 0.2s;
}
-.btn-secondary:hover {
+.sessions-page .btn-secondary:hover{
background: var(--bg-white);
border-color: var(--text-muted);
color: var(--text-primary);
}
-.btn-danger {
+.sessions-page .btn-danger{
padding: 0.75rem 1.25rem;
background: #dc2626;
color: white;
@@ -465,25 +465,25 @@
transition: all 0.2s;
}
-.btn-danger:hover {
+.sessions-page .btn-danger:hover{
background: #b91c1c;
}
-.confirm-modal {
+.sessions-page .confirm-modal{
max-width: 400px;
}
-.confirm-modal .modal-body p {
+.sessions-page .confirm-modal .modal-body p{
margin: 0 0 0.5rem 0;
}
-.text-muted {
+.sessions-page .text-muted{
color: var(--text-muted);
font-size: 0.875rem;
}
/* Icon Button */
-.btn-icon {
+.sessions-page .btn-icon{
display: flex;
align-items: center;
justify-content: center;
@@ -497,13 +497,13 @@
transition: all 0.2s;
}
-.btn-icon:hover {
+.sessions-page .btn-icon:hover{
background: var(--bg-light);
color: var(--text-primary);
}
/* Empty State */
-.empty-state {
+.sessions-page .empty-state{
grid-column: 1 / -1;
display: flex;
flex-direction: column;
@@ -514,25 +514,25 @@
color: var(--text-muted);
}
-.empty-state svg {
+.sessions-page .empty-state svg{
margin-bottom: 1rem;
opacity: 0.5;
}
-.empty-state h3 {
+.sessions-page .empty-state h3{
font-size: 1.125rem;
font-weight: 600;
color: var(--text-secondary);
margin: 0 0 0.5rem;
}
-.empty-state p {
+.sessions-page .empty-state p{
margin: 0;
font-size: 0.875rem;
}
/* Status Badge */
-.status-badge {
+.sessions-page .status-badge{
display: inline-flex;
align-items: center;
gap: 0.375rem;
@@ -544,22 +544,22 @@
letter-spacing: 0.03em;
}
-.status-badge.connected {
+.sessions-page .status-badge.connected{
background: rgba(34, 197, 94, 0.1);
color: #16a34a;
}
-.status-badge.disconnected {
+.sessions-page .status-badge.disconnected{
background: rgba(107, 114, 128, 0.1);
color: #6b7280;
}
-.status-badge.connecting {
+.sessions-page .status-badge.connecting{
background: rgba(234, 179, 8, 0.1);
color: #ca8a04;
}
-.status-badge::before {
+.sessions-page .status-badge::before{
content: '';
width: 6px;
height: 6px;
@@ -568,18 +568,18 @@
}
/* Detail Grid for Session Modal */
-.detail-grid {
+.sessions-page .detail-grid{
display: grid;
gap: 1rem;
}
-.detail-item {
+.sessions-page .detail-item{
display: flex;
flex-direction: column;
gap: 0.25rem;
}
-.detail-label {
+.sessions-page .detail-label{
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
@@ -587,13 +587,13 @@
color: var(--text-muted);
}
-.detail-value {
+.sessions-page .detail-value{
font-size: 0.9375rem;
color: var(--text-primary);
word-break: break-all;
}
-.detail-value.mono {
+.sessions-page .detail-value.mono{
font-family: 'JetBrains Mono', monospace;
font-size: 0.8125rem;
background: var(--bg-light);
@@ -602,7 +602,7 @@
}
/* Close Button - Always Visible */
-.btn-close {
+.sessions-page .btn-close{
display: flex;
align-items: center;
justify-content: center;
@@ -617,29 +617,29 @@
flex-shrink: 0;
}
-.btn-close svg {
+.sessions-page .btn-close svg{
width: 20px !important;
height: 20px !important;
min-width: 20px;
flex-shrink: 0;
}
-.btn-close:hover {
+.sessions-page .btn-close:hover{
background: #fee2e2;
border-color: #fecaca;
color: #dc2626;
}
-.btn-close:hover svg {
+.sessions-page .btn-close:hover svg{
stroke: #dc2626;
}
/* QR Modal Specific */
-.qr-modal .modal-body {
+.sessions-page .qr-modal .modal-body{
padding: 1.5rem;
}
-.qr-instructions {
+.sessions-page .qr-instructions{
margin-top: 1.5rem;
text-align: left;
background: var(--bg-light);
@@ -647,7 +647,7 @@
padding: 1rem 1.25rem;
}
-.qr-step {
+.sessions-page .qr-step{
margin: 0;
padding: 0.5rem 0;
font-size: 0.875rem;
@@ -655,15 +655,15 @@
border-bottom: 1px solid var(--border);
}
-.qr-step:last-child {
+.sessions-page .qr-step:last-child{
border-bottom: none;
}
-.qr-step strong {
+.sessions-page .qr-step strong{
color: var(--text-primary);
}
-.qr-auto-refresh {
+.sessions-page .qr-auto-refresh{
display: flex;
align-items: center;
justify-content: center;
@@ -673,7 +673,7 @@
color: var(--text-muted);
}
-.spin-slow {
+.sessions-page .spin-slow{
animation: spin 2s linear infinite;
}
@@ -687,7 +687,7 @@
}
/* Status Pill for Card Headers */
-.status-pill {
+.sessions-page .status-pill{
display: inline-flex;
padding: 0.25rem 0.75rem;
border-radius: 20px;
@@ -696,35 +696,33 @@
text-transform: capitalize;
}
-.status-pill.created,
-.status-pill.idle {
+.sessions-page .status-pill.created, .sessions-page .status-pill.idle{
background: rgba(107, 114, 128, 0.1);
color: #6b7280;
}
-.status-pill.initializing,
-.status-pill.connecting {
+.sessions-page .status-pill.initializing, .sessions-page .status-pill.connecting{
background: rgba(234, 179, 8, 0.1);
color: #ca8a04;
}
-.status-pill.qr_ready {
+.sessions-page .status-pill.qr_ready{
background: rgba(59, 130, 246, 0.1);
color: #2563eb;
}
-.status-pill.ready {
+.sessions-page .status-pill.ready{
background: rgba(34, 197, 94, 0.1);
color: #16a34a;
}
-.status-pill.disconnected {
+.sessions-page .status-pill.disconnected{
background: rgba(239, 68, 68, 0.1);
color: #dc2626;
}
/* Small Button for QR Placeholder */
-.btn-sm {
+.sessions-page .btn-sm{
padding: 0.5rem 1rem;
font-size: 0.8125rem;
font-weight: 600;
@@ -737,6 +735,6 @@
transition: background 0.2s;
}
-.btn-sm:hover {
+.sessions-page .btn-sm:hover{
background: var(--primary-hover);
}
diff --git a/dashboard/src/pages/Templates.css b/dashboard/src/pages/Templates.css
index 594e7dbcf..e84a2c7d8 100644
--- a/dashboard/src/pages/Templates.css
+++ b/dashboard/src/pages/Templates.css
@@ -1,27 +1,24 @@
-.templates-page {
+.templates-page{
width: 100%;
padding: 2rem;
overflow-x: hidden;
}
-.templates-loading,
-.templates-loading-inline,
-.templates-empty-page,
-.templates-empty-list {
+.templates-page .templates-loading, .templates-page .templates-loading-inline, .templates-page .templates-empty-page, .templates-page .templates-empty-list{
display: flex;
align-items: center;
justify-content: center;
}
-.templates-loading {
+.templates-page .templates-loading{
min-height: 400px;
}
-.templates-session-select {
+.templates-page .templates-session-select{
min-width: 240px;
}
-.templates-workspace {
+.templates-page .templates-workspace{
display: grid;
grid-template-columns: minmax(260px, 320px) minmax(420px, 1fr) minmax(280px, 360px);
min-height: calc(100vh - 180px);
@@ -32,23 +29,19 @@
overflow: hidden;
}
-.templates-library,
-.template-editor,
-.template-preview {
+.templates-page .templates-library, .templates-page .template-editor, .templates-page .template-preview{
min-width: 0;
min-height: 0;
}
-.templates-library {
+.templates-page .templates-library{
display: flex;
flex-direction: column;
border-right: 1px solid var(--border);
background: var(--bg-light);
}
-.templates-library-header,
-.template-editor-header,
-.template-preview-header {
+.templates-page .templates-library-header, .templates-page .template-editor-header, .templates-page .template-preview-header{
display: flex;
align-items: center;
justify-content: space-between;
@@ -58,9 +51,7 @@
border-bottom: 1px solid var(--border);
}
-.templates-library-header h2,
-.template-editor-header h2,
-.template-preview-header h2 {
+.templates-page .templates-library-header h2, .templates-page .template-editor-header h2, .templates-page .template-preview-header h2{
margin: 0;
color: var(--text-secondary);
font-size: 0.75rem;
@@ -69,27 +60,25 @@
letter-spacing: 0.05em;
}
-.templates-library-header span,
-.template-editor-header p,
-.template-preview-header span {
+.templates-page .templates-library-header span, .templates-page .template-editor-header p, .templates-page .template-preview-header span{
display: block;
margin-top: 0.25rem;
color: var(--text-muted);
font-size: 0.8125rem;
}
-.template-editor-header p {
+.templates-page .template-editor-header p{
margin-bottom: 0;
}
-.templates-new-btn {
+.templates-page .templates-new-btn{
min-height: 36px;
padding: 0.5rem 0.75rem;
font-size: 0.8125rem;
white-space: nowrap;
}
-.templates-search {
+.templates-page .templates-search{
display: grid;
grid-template-columns: 18px minmax(0, 1fr);
align-items: center;
@@ -102,7 +91,7 @@
color: var(--text-muted);
}
-.templates-search input {
+.templates-page .templates-search input{
width: 100%;
padding: 0;
border: 0;
@@ -112,7 +101,7 @@
font-size: 0.875rem;
}
-.template-list {
+.templates-page .template-list{
display: flex;
flex: 1;
flex-direction: column;
@@ -120,7 +109,7 @@
padding: 0 0.5rem 1rem;
}
-.template-list-item {
+.templates-page .template-list-item{
display: flex;
flex-direction: column;
align-items: stretch;
@@ -134,17 +123,17 @@
text-align: left;
}
-.template-list-item:hover {
+.templates-page .template-list-item:hover{
border-color: var(--border);
background: var(--bg-white);
}
-.template-list-item.selected {
+.templates-page .template-list-item.selected{
border-color: var(--primary);
background: var(--primary-soft);
}
-.template-list-title {
+.templates-page .template-list-title{
overflow: hidden;
color: var(--text-primary);
font-size: 0.9375rem;
@@ -153,7 +142,7 @@
white-space: nowrap;
}
-.template-list-body {
+.templates-page .template-list-body{
display: -webkit-box;
overflow: hidden;
color: var(--text-secondary);
@@ -163,7 +152,7 @@
-webkit-line-clamp: 2;
}
-.template-list-meta {
+.templates-page .template-list-meta{
overflow: hidden;
color: var(--text-muted);
font-family: 'JetBrains Mono', ui-monospace, monospace;
@@ -172,20 +161,19 @@
white-space: nowrap;
}
-.template-editor {
+.templates-page .template-editor{
display: flex;
flex-direction: column;
background: var(--bg-white);
}
-.template-header-actions,
-.template-editor-actions {
+.templates-page .template-header-actions, .templates-page .template-editor-actions{
display: flex;
align-items: center;
gap: 0.5rem;
}
-.template-form {
+.templates-page .template-form{
display: flex;
flex: 1;
flex-direction: column;
@@ -194,29 +182,26 @@
overflow-y: auto;
}
-.template-message-fields {
+.templates-page .template-message-fields{
display: grid;
grid-template-rows: auto minmax(240px, 1fr) auto;
gap: 1rem;
flex: 1;
}
-.template-form .form-group {
+.templates-page .template-form .form-group{
display: flex;
flex-direction: column;
gap: 0.5rem;
}
-.template-form label,
-.placeholder-list label > span {
+.templates-page .template-form label, .templates-page .placeholder-list label > span{
color: var(--text-secondary);
font-size: 0.8125rem;
font-weight: 700;
}
-.template-form input,
-.template-form textarea,
-.placeholder-list input {
+.templates-page .template-form input, .templates-page .template-form textarea, .templates-page .placeholder-list input{
width: 100%;
border: 1px solid var(--border);
border-radius: 8px;
@@ -225,12 +210,11 @@
font-size: 0.9375rem;
}
-.template-form input,
-.placeholder-list input {
+.templates-page .template-form input, .templates-page .placeholder-list input{
padding: 0.8125rem 0.875rem;
}
-.template-form textarea {
+.templates-page .template-form textarea{
flex: 1;
min-height: 240px;
padding: 0.875rem;
@@ -238,32 +222,30 @@
resize: vertical;
}
-.template-form input:focus,
-.template-form textarea:focus,
-.placeholder-list input:focus {
+.templates-page .template-form input:focus, .templates-page .template-form textarea:focus, .templates-page .placeholder-list input:focus{
outline: none;
border-color: var(--primary);
background: var(--bg-white);
box-shadow: 0 0 0 3px var(--primary-soft);
}
-.body-field {
+.templates-page .body-field{
min-height: 0;
}
-.template-editor-actions {
+.templates-page .template-editor-actions{
justify-content: flex-end;
padding-top: 0.25rem;
}
-.template-preview {
+.templates-page .template-preview{
display: flex;
flex-direction: column;
border-left: 1px solid var(--border);
background: var(--bg-light);
}
-.template-preview-header span {
+.templates-page .template-preview-header span{
display: inline-flex;
align-items: center;
justify-content: center;
@@ -278,11 +260,11 @@
font-weight: 700;
}
-.template-preview-message {
+.templates-page .template-preview-message{
padding: 1rem;
}
-.template-preview-message pre {
+.templates-page .template-preview-message pre{
min-height: 220px;
max-height: 360px;
margin: 0;
@@ -299,39 +281,37 @@
word-break: break-word;
}
-.template-variable-panel {
+.templates-page .template-variable-panel{
flex: 1;
overflow-y: auto;
padding: 0 1rem 1rem;
}
-.placeholder-list {
+.templates-page .placeholder-list{
display: flex;
flex-direction: column;
gap: 0.875rem;
}
-.placeholder-list label {
+.templates-page .placeholder-list label{
display: flex;
flex-direction: column;
gap: 0.375rem;
}
-.placeholder-list label > span {
+.templates-page .placeholder-list label > span{
color: var(--primary);
font-family: 'JetBrains Mono', ui-monospace, monospace;
}
-.template-muted {
+.templates-page .template-muted{
margin: 0;
color: var(--text-secondary);
font-size: 0.875rem;
line-height: 1.5;
}
-.templates-loading-inline,
-.templates-empty-list,
-.templates-empty-page {
+.templates-page .templates-loading-inline, .templates-page .templates-empty-list, .templates-page .templates-empty-page{
min-height: 220px;
flex-direction: column;
gap: 0.75rem;
@@ -340,32 +320,30 @@
text-align: center;
}
-.templates-empty-list.compact {
+.templates-page .templates-empty-list.compact{
min-height: 140px;
}
-.templates-empty-page {
+.templates-page .templates-empty-page{
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg-white);
box-shadow: var(--shadow-sm);
}
-.templates-empty-list h3,
-.templates-empty-page h3 {
+.templates-page .templates-empty-list h3, .templates-page .templates-empty-page h3{
margin: 0;
color: var(--text-secondary);
}
-.templates-empty-list p,
-.templates-empty-page p {
+.templates-page .templates-empty-list p, .templates-page .templates-empty-page p{
max-width: 340px;
margin: 0;
color: var(--text-secondary);
font-size: 0.875rem;
}
-.icon-btn {
+.templates-page .icon-btn{
display: inline-flex;
align-items: center;
justify-content: center;
@@ -378,18 +356,18 @@
color: var(--text-secondary);
}
-.icon-btn:hover {
+.templates-page .icon-btn:hover{
background: var(--bg-light);
color: var(--text-primary);
}
-.icon-btn.danger:hover {
+.templates-page .icon-btn.danger:hover{
border-color: #fecaca;
background: #fee2e2;
color: #dc2626;
}
-.btn-danger {
+.templates-page .btn-danger{
display: inline-flex;
align-items: center;
gap: 0.5rem;
@@ -402,11 +380,11 @@
font-weight: 600;
}
-.btn-danger:hover {
+.templates-page .btn-danger:hover{
background: #b91c1c;
}
-.toast {
+.templates-page .toast{
position: fixed;
top: 1.5rem;
right: 1.5rem;
@@ -421,19 +399,19 @@
font-weight: 500;
}
-.toast.success {
+.templates-page .toast.success{
border: 1px solid #a7f3d0;
background: #ecfdf5;
color: #047857;
}
-.toast.error {
+.templates-page .toast.error{
border: 1px solid #fecaca;
background: #fef2f2;
color: #dc2626;
}
-.toast-close {
+.templates-page .toast-close{
display: inline-flex;
align-items: center;
justify-content: center;
@@ -446,16 +424,16 @@
opacity: 0.7;
}
-.toast-close:hover {
+.templates-page .toast-close:hover{
opacity: 1;
}
@media (max-width: 1280px) {
- .templates-workspace {
+ .templates-page .templates-workspace{
grid-template-columns: 280px minmax(380px, 1fr);
}
- .template-preview {
+ .templates-page .template-preview{
grid-column: 1 / -1;
display: grid;
grid-template-columns: 1fr 320px;
@@ -463,63 +441,57 @@
border-left: 0;
}
- .template-preview-header {
+ .templates-page .template-preview-header{
grid-column: 1 / -1;
}
- .template-variable-panel {
+ .templates-page .template-variable-panel{
padding-top: 1rem;
}
}
@media (max-width: 900px) {
- .templates-page {
+ .templates-page{
padding: 1rem;
}
- .templates-session-select {
+ .templates-page .templates-session-select{
min-width: 0;
width: 100%;
}
- .templates-workspace {
+ .templates-page .templates-workspace{
display: flex;
flex-direction: column;
min-height: auto;
}
- .templates-library {
+ .templates-page .templates-library{
max-height: 360px;
border-right: 0;
border-bottom: 1px solid var(--border);
}
- .template-editor-header,
- .templates-library-header,
- .template-preview-header {
+ .templates-page .template-editor-header, .templates-page .templates-library-header, .templates-page .template-preview-header{
min-height: auto;
}
- .template-preview {
+ .templates-page .template-preview{
display: flex;
}
}
@media (max-width: 640px) {
- .templates-library-header,
- .template-editor-header,
- .template-editor-actions {
+ .templates-page .templates-library-header, .templates-page .template-editor-header, .templates-page .template-editor-actions{
flex-direction: column;
align-items: stretch;
}
- .template-header-actions {
+ .templates-page .template-header-actions{
justify-content: flex-end;
}
- .template-form,
- .template-preview-message,
- .template-variable-panel {
+ .templates-page .template-form, .templates-page .template-preview-message, .templates-page .template-variable-panel{
padding: 1rem;
}
}
diff --git a/dashboard/src/pages/Webhooks.css b/dashboard/src/pages/Webhooks.css
index ce5132140..fda9b5256 100644
--- a/dashboard/src/pages/Webhooks.css
+++ b/dashboard/src/pages/Webhooks.css
@@ -1,4 +1,4 @@
-.webhooks-page {
+.webhooks-page{
padding: 2rem;
width: 100%;
box-sizing: border-box;
@@ -6,29 +6,27 @@
}
/* Webhook create/edit modal: roomier than the default 480px (filters need width). */
-.webhooks-page .modal:not(.modal-sm) {
+.webhooks-page .modal:not(.modal-sm){
max-width: 640px;
}
/* Consistent vertical rhythm between top-level form blocks in the webhook modals.
Direct-child only, so nested FilterBuilder inputs/selects are untouched. */
-.webhooks-page .modal-body > input,
-.webhooks-page .modal-body > select,
-.webhooks-page .modal-body > .event-tags {
+.webhooks-page .modal-body > input, .webhooks-page .modal-body > select, .webhooks-page .modal-body > .event-tags{
margin-bottom: 0.75rem;
}
-.webhooks-page .modal-body > .event-tags {
+.webhooks-page .modal-body > .event-tags{
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
-.page-header {
+.webhooks-page .page-header{
margin-bottom: 2rem;
}
-.header-content {
+.webhooks-page .header-content{
display: flex;
justify-content: space-between;
align-items: center;
@@ -36,7 +34,7 @@
/* H1 inherited from global */
-.btn-primary {
+.webhooks-page .btn-primary{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -51,28 +49,28 @@
transition: background 0.2s;
}
-.btn-primary:hover {
+.webhooks-page .btn-primary:hover{
background: var(--primary-hover);
}
-.webhooks-content {
+.webhooks-page .webhooks-content{
display: grid;
grid-template-columns: 1fr 280px;
gap: 1.5rem;
}
-.webhooks-list-container {
+.webhooks-page .webhooks-list-container{
width: 100%;
min-width: 0;
}
-.webhooks-card-list {
+.webhooks-page .webhooks-card-list{
display: flex;
flex-direction: column;
gap: 1rem;
}
-.webhook-card {
+.webhooks-page .webhook-card{
background: var(--bg-white);
border-radius: 12px;
box-shadow: var(--shadow-sm);
@@ -81,11 +79,11 @@
transition: box-shadow 0.2s;
}
-.webhook-card:hover {
+.webhooks-page .webhook-card:hover{
box-shadow: var(--shadow-md);
}
-.webhook-card-header {
+.webhooks-page .webhook-card-header{
display: flex;
align-items: center;
justify-content: space-between;
@@ -95,7 +93,7 @@
gap: 1rem;
}
-.webhook-url-row {
+.webhooks-page .webhook-url-row{
display: flex;
align-items: center;
gap: 0.625rem;
@@ -103,12 +101,12 @@
min-width: 0;
}
-.webhook-url-icon {
+.webhooks-page .webhook-url-icon{
color: var(--primary);
flex-shrink: 0;
}
-.webhook-url {
+.webhooks-page .webhook-url{
font-size: 0.8125rem;
font-weight: 500;
color: var(--text-primary);
@@ -120,30 +118,30 @@
font-family: 'JetBrains Mono', monospace;
}
-.webhook-card-actions {
+.webhooks-page .webhook-card-actions{
display: flex;
gap: 0.375rem;
flex-shrink: 0;
}
-.webhook-card-body {
+.webhooks-page .webhook-card-body{
padding: 1rem 1.25rem;
overflow: hidden;
}
-.webhook-meta {
+.webhooks-page .webhook-meta{
display: flex;
gap: 2rem;
margin-bottom: 0.875rem;
}
-.webhook-meta-item {
+.webhooks-page .webhook-meta-item{
display: flex;
flex-direction: column;
gap: 0.25rem;
}
-.webhook-meta-label {
+.webhooks-page .webhook-meta-label{
font-size: 0.6875rem;
font-weight: 700;
text-transform: uppercase;
@@ -151,19 +149,19 @@
color: var(--text-secondary);
}
-.webhook-meta-value {
+.webhooks-page .webhook-meta-value{
font-size: 0.875rem;
font-weight: 500;
color: var(--text-primary);
}
-.webhook-events {
+.webhooks-page .webhook-events{
display: flex;
flex-direction: column;
gap: 0.375rem;
}
-.empty-table-state {
+.webhooks-page .empty-table-state{
display: flex;
flex-direction: column;
align-items: center;
@@ -173,32 +171,32 @@
color: var(--text-muted);
}
-.empty-table-state svg {
+.webhooks-page .empty-table-state svg{
margin-bottom: 1rem;
opacity: 0.4;
color: var(--text-muted);
}
-.empty-table-state h3 {
+.webhooks-page .empty-table-state h3{
font-size: 1.125rem;
font-weight: 600;
color: var(--text-secondary);
margin: 0 0 0.5rem;
}
-.empty-table-state p {
+.webhooks-page .empty-table-state p{
margin: 0;
font-size: 0.875rem;
max-width: 300px;
}
-.events-cell {
+.webhooks-page .events-cell{
display: flex;
flex-wrap: wrap;
gap: 0.375rem;
}
-.event-tag {
+.webhooks-page .event-tag{
font-size: 0.75rem;
padding: 0.25rem 0.625rem;
background: rgba(37, 211, 102, 0.15);
@@ -213,7 +211,7 @@
}
/* Modal event tags - clickable (webhooks only) */
-.webhooks-page .modal-body .event-tag {
+.webhooks-page .modal-body .event-tag{
font-size: 0.8125rem;
padding: 0.5rem 0.75rem;
background: var(--bg-light);
@@ -224,18 +222,18 @@
transition: all 0.2s;
}
-.webhooks-page .modal-body .event-tag:hover {
+.webhooks-page .modal-body .event-tag:hover{
border-color: var(--primary);
color: var(--primary);
}
-.webhooks-page .modal-body .event-tag.selected {
+.webhooks-page .modal-body .event-tag.selected{
background: var(--primary);
color: white;
border-color: var(--primary);
}
-.filter-badge {
+.webhooks-page .filter-badge{
display: inline-flex;
align-items: center;
gap: 0.25rem;
@@ -249,20 +247,19 @@
border: 1px solid var(--border);
}
-.filter-badge-interactive {
+.webhooks-page .filter-badge-interactive{
position: relative;
cursor: default;
outline: none;
}
-.filter-badge-interactive:hover,
-.filter-badge-interactive:focus-visible {
+.webhooks-page .filter-badge-interactive:hover, .webhooks-page .filter-badge-interactive:focus-visible{
border-color: var(--primary);
color: var(--text-primary);
}
/* Fixed-positioned (escapes the card's overflow:hidden); coordinates set inline from the badge rect. */
-.filter-popover {
+.webhooks-page .filter-popover{
position: fixed;
z-index: 100;
min-width: 200px;
@@ -280,7 +277,7 @@
cursor: default;
}
-.filter-popover-title {
+.webhooks-page .filter-popover-title{
font-size: 0.65rem;
font-weight: 700;
text-transform: uppercase;
@@ -289,18 +286,18 @@
margin-bottom: 0.125rem;
}
-.filter-popover-row {
+.webhooks-page .filter-popover-row{
font-size: 0.78rem;
color: var(--text-primary);
word-break: break-word;
}
-.filter-popover-row + .filter-popover-row {
+.webhooks-page .filter-popover-row + .filter-popover-row{
padding-top: 0.25rem;
border-top: 1px solid var(--border);
}
-.status-badge {
+.webhooks-page .status-badge{
display: inline-flex;
align-items: center;
gap: 0.375rem;
@@ -312,7 +309,7 @@
width: fit-content;
}
-.status-badge::before {
+.webhooks-page .status-badge::before{
content: '';
width: 6px;
height: 6px;
@@ -321,17 +318,17 @@
flex-shrink: 0;
}
-.status-badge.active {
+.webhooks-page .status-badge.active{
background: rgba(37, 211, 102, 0.15);
color: var(--primary);
}
-.status-badge.inactive {
+.webhooks-page .status-badge.inactive{
background: var(--bg-light);
color: var(--text-muted);
}
-.icon-btn {
+.webhooks-page .icon-btn{
padding: 0.5rem;
background: transparent;
border: 1px solid var(--border);
@@ -342,18 +339,18 @@
flex-shrink: 0;
}
-.icon-btn:hover {
+.webhooks-page .icon-btn:hover{
background: var(--bg-light);
color: var(--text-primary);
}
-.icon-btn.danger:hover {
+.webhooks-page .icon-btn.danger:hover{
background: #fee2e2;
border-color: #fecaca;
color: #dc2626;
}
-.events-reference {
+.webhooks-page .events-reference{
background: var(--bg-white);
border-radius: 12px;
padding: 1.5rem;
@@ -362,7 +359,7 @@
height: fit-content;
}
-.events-reference h3 {
+.webhooks-page .events-reference h3{
font-size: 1rem;
font-weight: 700;
color: var(--text-primary);
@@ -371,19 +368,19 @@
letter-spacing: normal;
}
-.events-list {
+.webhooks-page .events-list{
display: flex;
flex-direction: column;
gap: 0.75rem;
}
-.event-item {
+.webhooks-page .event-item{
display: flex;
flex-direction: column;
gap: 0.25rem;
}
-.event-item code {
+.webhooks-page .event-item code{
font-size: 0.8125rem;
color: var(--primary);
background: rgba(37, 211, 102, 0.1);
@@ -392,134 +389,134 @@
width: fit-content;
}
-.event-item span {
+.webhooks-page .event-item span{
font-size: 0.8125rem;
color: var(--text-secondary);
line-height: 1.4;
}
/* Dark mode - explicit theme */
-[data-theme='dark'] .event-tag {
+.webhooks-page [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 {
+.webhooks-page [data-theme='dark'] .status-badge.active{
color: #4ade80;
background: rgba(37, 211, 102, 0.2);
}
-[data-theme='dark'] .webhook-url {
+.webhooks-page [data-theme='dark'] .webhook-url{
color: #e2e8f0;
}
-[data-theme='dark'] .webhook-meta-label {
+.webhooks-page [data-theme='dark'] .webhook-meta-label{
color: #94a3b8;
}
-[data-theme='dark'] .webhook-meta-value {
+.webhooks-page [data-theme='dark'] .webhook-meta-value{
color: #e2e8f0;
}
/* Dark mode - system preference */
@media (prefers-color-scheme: dark) {
- :root:not([data-theme='light']) .event-tag {
+ :root:not([data-theme='light']) .webhooks-page .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 {
+ :root:not([data-theme='light']) .webhooks-page .status-badge.active{
color: #4ade80;
background: rgba(37, 211, 102, 0.2);
}
- :root:not([data-theme='light']) .webhook-url {
+ :root:not([data-theme='light']) .webhooks-page .webhook-url{
color: #e2e8f0;
}
- :root:not([data-theme='light']) .webhook-meta-label {
+ :root:not([data-theme='light']) .webhooks-page .webhook-meta-label{
color: #94a3b8;
}
- :root:not([data-theme='light']) .webhook-meta-value {
+ :root:not([data-theme='light']) .webhooks-page .webhook-meta-value{
color: #e2e8f0;
}
}
/* Responsive */
@media (max-width: 1024px) {
- .webhooks-content {
+ .webhooks-page .webhooks-content{
grid-template-columns: 1fr;
}
- .events-reference {
+ .webhooks-page .events-reference{
display: none;
}
}
@media (max-width: 768px) {
- .webhooks-page {
+ .webhooks-page{
padding: 1rem;
}
- .webhooks-content {
+ .webhooks-page .webhooks-content{
grid-template-columns: 1fr;
}
- .webhook-card {
+ .webhooks-page .webhook-card{
overflow: hidden;
}
- .webhook-card-header {
+ .webhooks-page .webhook-card-header{
flex-direction: column;
align-items: flex-start;
gap: 0.75rem;
padding: 0.875rem 1rem;
}
- .webhook-url-row {
+ .webhooks-page .webhook-url-row{
width: 100%;
min-width: 0;
}
- .webhook-url {
+ .webhooks-page .webhook-url{
font-size: 0.75rem;
}
- .webhook-card-actions {
+ .webhooks-page .webhook-card-actions{
width: 100%;
justify-content: flex-end;
}
- .webhook-card-body {
+ .webhooks-page .webhook-card-body{
padding: 0.875rem 1rem;
}
- .webhook-meta {
+ .webhooks-page .webhook-meta{
flex-direction: column;
gap: 0.75rem;
}
- .webhook-meta-value {
+ .webhooks-page .webhook-meta-value{
font-size: 0.8125rem;
word-break: break-all;
}
- .events-cell {
+ .webhooks-page .events-cell{
flex-wrap: wrap;
gap: 0.375rem;
}
- .event-tag {
+ .webhooks-page .event-tag{
font-size: 0.6875rem;
padding: 0.2rem 0.5rem;
}
}
/* Toast Notification */
-.toast {
+.webhooks-page .toast{
position: fixed;
top: 1.5rem;
right: 1.5rem;
@@ -546,19 +543,19 @@
}
}
-.toast.success {
+.webhooks-page .toast.success{
background: #ecfdf5;
border: 1px solid #a7f3d0;
color: #047857;
}
-.toast.error {
+.webhooks-page .toast.error{
background: #fef2f2;
border: 1px solid #fecaca;
color: #dc2626;
}
-.toast-close {
+.webhooks-page .toast-close{
background: transparent;
border: none;
padding: 0.25rem;
@@ -567,12 +564,12 @@
color: inherit;
}
-.toast-close:hover {
+.webhooks-page .toast-close:hover{
opacity: 1;
}
/* Danger Button */
-.btn-danger {
+.webhooks-page .btn-danger{
display: flex;
align-items: center;
gap: 0.5rem;
@@ -587,23 +584,23 @@
transition: background 0.2s;
}
-.btn-danger:hover {
+.webhooks-page .btn-danger:hover{
background: #b91c1c;
}
/* Small Modal Variant */
-.modal.modal-sm {
+.webhooks-page .modal.modal-sm{
max-width: 400px;
}
/* Disabled button */
-.icon-btn:disabled {
+.webhooks-page .icon-btn:disabled{
opacity: 0.5;
cursor: not-allowed;
}
/* Animate spin for loading */
-.animate-spin {
+.webhooks-page .animate-spin{
animation: spin 1s linear infinite;
}
@@ -617,7 +614,7 @@
}
/* Toggle Switch */
-.toggle-group {
+.webhooks-page .toggle-group{
display: flex;
align-items: center;
gap: 1rem;
@@ -627,25 +624,25 @@
border-radius: var(--radius);
}
-.toggle-label {
+.webhooks-page .toggle-label{
font-weight: 500;
color: var(--text-primary);
}
-.toggle-switch {
+.webhooks-page .toggle-switch{
position: relative;
display: inline-block;
width: 48px;
height: 26px;
}
-.toggle-switch input {
+.webhooks-page .toggle-switch input{
opacity: 0;
width: 0;
height: 0;
}
-.toggle-slider {
+.webhooks-page .toggle-slider{
position: absolute;
cursor: pointer;
top: 0;
@@ -657,7 +654,7 @@
border-radius: 26px;
}
-.toggle-slider::before {
+.webhooks-page .toggle-slider::before{
position: absolute;
content: '';
height: 20px;
@@ -670,23 +667,23 @@
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}
-.toggle-switch input:checked + .toggle-slider {
+.webhooks-page .toggle-switch input:checked + .toggle-slider{
background-color: var(--primary);
}
-.toggle-switch input:checked + .toggle-slider::before {
+.webhooks-page .toggle-switch input:checked + .toggle-slider::before{
transform: translateX(22px);
}
-.toggle-status {
+.webhooks-page .toggle-status{
font-size: 0.875rem;
font-weight: 500;
}
-.toggle-status.active {
+.webhooks-page .toggle-status.active{
color: var(--primary);
}
-.toggle-status.inactive {
+.webhooks-page .toggle-status.inactive{
color: var(--text-muted);
}
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 3ec6482b9..61e21f326 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -169,6 +169,20 @@ export interface ChatMessage {
};
}
+// Live WhatsApp message from the engine history endpoint (not a persisted DB row): it carries `fromMe`
+// instead of `direction`/`status`. Used to backfill a chat thread the gateway never captured live.
+export interface EngineHistoryMessage {
+ id: string;
+ chatId: string;
+ from: string;
+ to: string;
+ body: string;
+ type: string;
+ timestamp: number;
+ fromMe?: boolean;
+ media?: { mimetype: string; filename?: string; data?: string };
+}
+
export interface SendMediaPayload {
base64?: string;
url?: string;
@@ -379,6 +393,12 @@ export const sessionApi = {
request<{ messages: ChatMessage[]; total: number }>(
`/sessions/${id}/messages?chatId=${encodeURIComponent(chatId)}&limit=${limit}`,
),
+ // Live history straight from WhatsApp (bypasses the DB) — backfills a thread the gateway never
+ // captured, e.g. a freshly paired session whose persisted store is still empty.
+ getChatHistory: (id: string, chatId: string, limit = 100) =>
+ request<EngineHistoryMessage[]>(
+ `/sessions/${id}/messages/${encodeURIComponent(chatId)}/history?limit=${limit}`,
+ ),
};
// =============================================================================
diff --git a/dashboard/src/styles.scope.test.ts b/dashboard/src/styles.scope.test.ts
new file mode 100644
index 000000000..86cac7818
--- /dev/null
+++ b/dashboard/src/styles.scope.test.ts
@@ -0,0 +1,63 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync, readdirSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+// Guard against the route-CSS cascade-collision class of bug: every page stylesheet must keep all of
+// its rules scoped under that page's root class (e.g. `.sessions-page …`). Two pages defining the same
+// bare class (`.btn-action`) leak across each other depending on lazy-load/navigation order — the last
+// route visited wins the cascade. Scoping every rule under the page root makes leakage impossible.
+// This test fails the build if any page CSS rule is left unscoped, so the fix can never silently regress.
+
+const PAGES_DIR = join(dirname(fileURLToPath(import.meta.url)), 'pages');
+
+function stripComments(css: string): string {
+ return css.replace(/\/\*[\s\S]*?\*\//g, '');
+}
+
+// Top-level (and @media-nested) selectors, excluding @keyframes/@font-face bodies.
+function selectors(css: string): string[] {
+ const out: string[] = [];
+ let i = 0;
+ const n = css.length;
+ while (i < n) {
+ let j = i;
+ while (j < n && css[j] !== '{' && css[j] !== '}') j++;
+ if (j >= n) break;
+ if (css[j] === '}') { i = j + 1; continue; }
+ const header = css.slice(i, j).trim();
+ let depth = 1, k = j + 1;
+ while (k < n && depth) { if (css[k] === '{') depth++; else if (css[k] === '}') depth--; k++; }
+ const body = css.slice(j + 1, k - 1);
+ if (/^@keyframes|^@font-face|^@page/.test(header)) {
+ /* keyframe/font selectors are not class-scoped — skip */
+ } else if (/^@media|^@supports|^@container/.test(header)) {
+ out.push(...selectors(body)); // recurse: inner rules must still be scoped
+ } else if (header) {
+ out.push(...header.split(',').map(s => s.trim()).filter(Boolean));
+ }
+ i = k;
+ }
+ return out;
+}
+
+const files = readdirSync(PAGES_DIR).filter(f => f.endsWith('.css'));
+
+for (const file of files) {
+ test(`${file}: every rule is scoped under its page root`, () => {
+ const css = stripComments(readFileSync(join(PAGES_DIR, file), 'utf8'));
+ const sels = selectors(css);
+ assert.ok(sels.length > 0, `${file} produced no selectors (parse error?)`);
+ // The page root is the first bare single-class selector (each page CSS opens with `.x-page { … }`).
+ const root = sels.find(s => /^\.[a-zA-Z][\w-]*$/.test(s));
+ assert.ok(root, `${file}: could not find a root class rule`);
+ const unscoped = sels.filter(s => !s.includes(root!));
+ assert.deepEqual(
+ unscoped,
+ [],
+ `${file}: ${unscoped.length} selector(s) not scoped under "${root}" — move them under the page root ` +
+ `(or into a global stylesheet) to avoid cross-page CSS collisions:\n ${unscoped.join('\n ')}`,
+ );
+ });
+}
diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.ts
new file mode 100644
index 000000000..fb0ac198e
--- /dev/null
+++ b/dashboard/src/utils/chatMessages.test.ts
@@ -0,0 +1,70 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mapEngineHistoryMessage, mergeChatMessages, type EngineHistoryMessage } from './chatMessages.ts';
+import type { ChatMessage } from '../services/api';
+
+const hist = (over: Partial<EngineHistoryMessage> = {}): EngineHistoryMessage => ({
+ id: '[email protected]_AAA',
+ chatId: '[email protected]',
+ body: 'hello',
+ type: 'text',
+ timestamp: 1782053533,
+ fromMe: false,
+ ...over,
+});
+
+const db = (over: Partial<ChatMessage> = {}): ChatMessage => ({
+ id: 'row-1',
+ waMessageId: '[email protected]_BBB',
+ chatId: '[email protected]',
+ from: 'me',
+ body: 'sent',
+ type: 'text',
+ direction: 'outgoing',
+ status: 'delivered',
+ timestamp: 1782053999,
+ createdAt: '2026-06-23T11:16:34.000Z',
+ ...over,
+});
+
+test('mapEngineHistoryMessage: fromMe=true becomes an outgoing bubble', () => {
+ assert.equal(mapEngineHistoryMessage(hist({ id: 'true_x', fromMe: true })).direction, 'outgoing');
+});
+
+test('mapEngineHistoryMessage: fromMe=false becomes an incoming bubble', () => {
+ assert.equal(mapEngineHistoryMessage(hist({ fromMe: false })).direction, 'incoming');
+});
+
+test('mapEngineHistoryMessage: carries id into waMessageId so it dedups against DB rows', () => {
+ const m = mapEngineHistoryMessage(hist({ id: '[email protected]_ZZZ' }));
+ assert.equal(m.waMessageId, '[email protected]_ZZZ');
+});
+
+test('mapEngineHistoryMessage: derives createdAt from the unix timestamp', () => {
+ const m = mapEngineHistoryMessage(hist({ timestamp: 1782053533 }));
+ assert.equal(Date.parse(m.createdAt), 1782053533 * 1000);
+});
+
+test('mergeChatMessages: an engine-only message (no DB row) is included — the backfill case', () => {
+ const merged = mergeChatMessages([], [mapEngineHistoryMessage(hist())]);
+ assert.equal(merged.length, 1);
+ assert.equal(merged[0].body, 'hello');
+});
+
+test('mergeChatMessages: the DB row wins over the engine copy of the same message (keeps real status)', () => {
+ const sameId = '[email protected]_BBB';
+ const fromEngine = mapEngineHistoryMessage(hist({ id: sameId, fromMe: true, body: 'sent' }));
+ const merged = mergeChatMessages([db({ waMessageId: sameId, status: 'read' })], [fromEngine]);
+ assert.equal(merged.length, 1);
+ assert.equal(merged[0].status, 'read'); // DB status preserved, not the engine default
+});
+
+test('mergeChatMessages: returns ascending by timestamp (oldest first, newest last)', () => {
+ const older = mapEngineHistoryMessage(hist({ id: 'a', timestamp: 1000 }));
+ const newer = mapEngineHistoryMessage(hist({ id: 'b', timestamp: 2000 }));
+ const merged = mergeChatMessages([], [newer, older]);
+ assert.deepEqual(merged.map(m => m.id), ['a', 'b']);
+});
diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.ts
new file mode 100644
index 000000000..9e779b73d
--- /dev/null
+++ b/dashboard/src/utils/chatMessages.ts
@@ -0,0 +1,37 @@
+import type { ChatMessage, EngineHistoryMessage, MessageType } from '../services/api';
+
+export type { EngineHistoryMessage };
+
+// Normalize an engine history message into the DB ChatMessage shape the thread renders. Historical
+// messages have no live delivery state, so default to `read` (they are old/already-seen); real status
+// for current-session messages still comes from the DB copy and live websocket acks.
+export function mapEngineHistoryMessage(h: EngineHistoryMessage): ChatMessage {
+ return {
+ id: h.id,
+ waMessageId: h.id,
+ chatId: h.chatId,
+ from: h.from,
+ to: h.to,
+ body: h.body ?? '',
+ type: h.type as MessageType,
+ direction: h.fromMe ? 'outgoing' : 'incoming',
+ status: 'read',
+ timestamp: h.timestamp,
+ createdAt: new Date((h.timestamp ?? 0) * 1000).toISOString(),
+ metadata: h.media ? { media: h.media } : undefined,
+ };
+}
+
+const msgKey = (m: ChatMessage): string => m.waMessageId ?? m.id;
+const msgTime = (m: ChatMessage): number =>
+ typeof m.timestamp === 'number' ? m.timestamp : Math.floor(Date.parse(m.createdAt) / 1000) || 0;
+
+// Merge persisted DB messages with engine history into one ascending thread. The engine fills the
+// backfill (history from before the gateway captured anything); the DB copy wins on conflict so the
+// real delivery status survives. Deduped by the wweb.js serialized id (engine `id` == DB `waMessageId`).
+export function mergeChatMessages(db: ChatMessage[], history: ChatMessage[]): ChatMessage[] {
+ const byId = new Map<string, ChatMessage>();
+ for (const m of history) byId.set(msgKey(m), m);
+ for (const m of db) byId.set(msgKey(m), m); // DB overwrites the engine copy (authoritative status)
+ return [...byId.values()].sort((a, b) => msgTime(a) - msgTime(b) || a.createdAt.localeCompare(b.createdAt));
+}
diff --git a/dashboard/src/utils/pluginConfigForm.test.ts b/dashboard/src/utils/pluginConfigForm.test.ts
new file mode 100644
index 000000000..403a5e0a3
--- /dev/null
+++ b/dashboard/src/utils/pluginConfigForm.test.ts
@@ -0,0 +1,28 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { coerceFieldInput, emptyForField } from './pluginConfigForm.ts';
+import type { PluginConfigField } from '../services/api';
+
+const num: PluginConfigField = { type: 'number' };
+const str: PluginConfigField = { type: 'string' };
+
+test('coerceFieldInput: a cleared number field becomes undefined (never an empty string)', () => {
+ assert.equal(coerceFieldInput(num, ''), undefined);
+});
+
+test('coerceFieldInput: a non-empty number is coerced to a Number', () => {
+ assert.equal(coerceFieldInput(num, '42'), 42);
+});
+
+test('coerceFieldInput: a string field passes the raw value through unchanged', () => {
+ assert.equal(coerceFieldInput(str, ''), '');
+ assert.equal(coerceFieldInput(str, 'hi'), 'hi');
+});
+
+test('emptyForField: a number field seeds to undefined, not an empty string', () => {
+ assert.equal(emptyForField(num), undefined);
+});
+
+test('emptyForField: a string field seeds to an empty string', () => {
+ assert.equal(emptyForField(str), '');
+});
diff --git a/dashboard/src/utils/pluginConfigForm.ts b/dashboard/src/utils/pluginConfigForm.ts
new file mode 100644
index 000000000..8d423aef5
--- /dev/null
+++ b/dashboard/src/utils/pluginConfigForm.ts
@@ -0,0 +1,33 @@
+import type { PluginConfigField } from '../services/api';
+
+/** A blank value for a field, used to seed a form and to add a new array row. */
+export function emptyForField(field: PluginConfigField): unknown {
+ if (field.default !== undefined) return field.default;
+ // A <select> always shows its first option, so seed enum state to it — otherwise the form shows a
+ // value the user never picked and would save '' instead.
+ if (field.enum && field.enum.length > 0) return field.enum[0];
+ switch (field.type) {
+ case 'boolean':
+ return false;
+ case 'array':
+ return [];
+ case 'object': {
+ const obj: Record<string, unknown> = {};
+ if (field.properties) for (const [k, sub] of Object.entries(field.properties)) obj[k] = emptyForField(sub);
+ return obj;
+ }
+ case 'number':
+ // Seed (and leave) a blank number as undefined, never '' — persisting an empty string for a
+ // type:'number' field hands the plugin a string where it expects a number.
+ return undefined;
+ default: // string | textarea
+ return '';
+ }
+}
+
+/** Coerce a text-input value to the field's type. A cleared number becomes undefined (so the key is
+ * omitted) rather than '' — the inverse of {@link emptyForField} for number fields. */
+export function coerceFieldInput(field: PluginConfigField, raw: string): unknown {
+ if (field.type === 'number') return raw === '' ? undefined : Number(raw);
+ return raw;
+}
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 230440243..16ddd44cf 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -58,6 +58,9 @@ services:
- WWEBJS_AUTH_TIMEOUT_MS=${WWEBJS_AUTH_TIMEOUT_MS:-}
- STORAGE_TYPE=local
- STORAGE_LOCAL_PATH=/app/data/media
+ # Install plugins into the writable, persistent data volume (the root FS is read-only). Matches
+ # docker-compose.yml; without this it falls back to ./plugins on the read-only root and install fails.
+ - PLUGINS_DIR=/app/data/plugins
- WEBHOOK_TIMEOUT=10000
- WEBHOOK_MAX_RETRIES=3
- QUEUE_ENABLED=false
diff --git a/package-lock.json b/package-lock.json
index dbb94797b..7e1d80e0a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "openwa",
- "version": "0.6.2",
+ "version": "0.7.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openwa",
- "version": "0.6.2",
+ "version": "0.7.0",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
diff --git a/package.json b/package.json
index 538e704ad..1b6376936 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "openwa",
- "version": "0.6.2",
+ "version": "0.7.0",
"description": "Open Source WhatsApp API Gateway - Free, Self-Hosted HTTP API for WhatsApp",
"author": "Yudhi Armyndharis & OpenWA Contributors",
"private": true,
diff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.ts
index 40ec4c85a..8354b6565 100644
--- a/src/common/security/ssrf-guard.spec.ts
+++ b/src/common/security/ssrf-guard.spec.ts
@@ -6,6 +6,7 @@ import {
isSsrfProtectionEnabled,
resolveSafeFetchTarget,
pinnedLookup,
+ validatingLookup,
withSafeFetch,
} from './ssrf-guard';
import * as dnsPromises from 'dns/promises';
@@ -266,6 +267,96 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {
expect(init.redirect).toBe('follow');
expect(init.dispatcher).toBeUndefined();
});
+
+ it('follows redirects through a validating dispatcher when followRedirects is set (download path)', async () => {
+ // GitHub Releases 302 to a CDN; the download path must follow (not refuse) redirects — but via a
+ // per-host validating lookup so every hop is still checked. Here the original host validates and a
+ // 302 is delivered to `use` (proving assertNoRedirect is NOT applied on this path).
+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);
+ (undiciFetch as jest.Mock).mockResolvedValue({ status: 302, type: 'basic' });
+ const use = jest.fn(() => 'followed');
+
+ const result = await withSafeFetch('https://github.com/x/releases/download/v1/p.zip', {}, use, {
+ followRedirects: true,
+ });
+
+ expect(result).toBe('followed');
+ expect(use).toHaveBeenCalledTimes(1);
+ const [, init] = (undiciFetch as jest.Mock).mock.calls[0] as [string, { redirect: string; dispatcher: unknown }];
+ expect(init.redirect).toBe('follow'); // not 'manual' — undici follows, our lookup guards each hop
+ expect(init.dispatcher).toBeDefined();
+ });
+
+ it('still rejects an internal ORIGINAL url even with followRedirects (scheme/host validated first)', async () => {
+ const use = jest.fn();
+ await expect(withSafeFetch('http://127.0.0.1/p.zip', {}, use, { followRedirects: true })).rejects.toThrow(
+ SsrfBlockedError,
+ );
+ expect(use).not.toHaveBeenCalled();
+ });
+});
+
+describe('validatingLookup (per-hop redirect guard)', () => {
+ const run = (hostname: string): Promise<{ err: unknown; rest: unknown[] }> =>
+ new Promise(resolve => {
+ const lookup = validatingLookup() as unknown as (
+ h: string,
+ o: { all: boolean },
+ cb: (err: unknown, ...rest: unknown[]) => void,
+ ) => void;
+ lookup(hostname, { all: true }, (err, ...rest) => resolve({ err, rest }));
+ });
+
+ it('passes a public IP literal through', async () => {
+ const { err, rest } = await run('93.184.216.34');
+ expect(err).toBeNull();
+ expect(rest[0]).toEqual([{ address: '93.184.216.34', family: 4 }]);
+ });
+
+ it('refuses an internal IPv4 literal (a redirect target cannot be loopback/private)', async () => {
+ expect((await run('127.0.0.1')).err).toBeInstanceOf(SsrfBlockedError);
+ expect((await run('169.254.169.254')).err).toBeInstanceOf(SsrfBlockedError); // cloud metadata
+ expect((await run('10.0.0.5')).err).toBeInstanceOf(SsrfBlockedError);
+ });
+
+ it('refuses an internal IPv6 literal', async () => {
+ expect((await run('::1')).err).toBeInstanceOf(SsrfBlockedError);
+ });
+
+ it('refuses a hostname that resolves to an internal address', async () => {
+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '10.0.0.9', family: 4 }]);
+ expect((await run('rebind.evil.example')).err).toBeInstanceOf(SsrfBlockedError);
+ });
+
+ it('passes a hostname that resolves to a public address', async () => {
+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);
+ const { err, rest } = await run('cdn.example.com');
+ expect(err).toBeNull();
+ expect(rest[0]).toEqual([{ address: '93.184.216.34', family: 4 }]);
+ });
+
+ it('returns a single (address, family) pair in non-all form', async () => {
+ const single = await new Promise<{ err: unknown; rest: unknown[] }>(resolve => {
+ const lookup = validatingLookup() as unknown as (
+ h: string,
+ o: { all: boolean },
+ cb: (err: unknown, ...rest: unknown[]) => void,
+ ) => void;
+ lookup('93.184.216.34', { all: false }, (err, ...rest) => resolve({ err, rest }));
+ });
+ expect(single.err).toBeNull();
+ expect(single.rest).toEqual(['93.184.216.34', 4]);
+ });
+
+ it('surfaces a DNS resolution failure to the callback (does not hang the connect)', async () => {
+ (dnsPromises.lookup as jest.Mock).mockRejectedValueOnce(new Error('ENOTFOUND'));
+ expect((await run('nope.example')).err).toBeInstanceOf(Error);
+ });
+
+ it('refuses a host that resolves to no addresses', async () => {
+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([]);
+ expect((await run('empty.example')).err).toBeInstanceOf(SsrfBlockedError);
+ });
});
describe('isSsrfProtectionEnabled', () => {
diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.ts
index dd432fce9..1928279a1 100644
--- a/src/common/security/ssrf-guard.ts
+++ b/src/common/security/ssrf-guard.ts
@@ -273,6 +273,52 @@ export function pinnedLookup(addresses: LookupAddress[]): LookupFunction {
return fn as unknown as LookupFunction;
}
+/**
+ * A `connect.lookup` that resolves EVERY host it is asked to connect to and refuses any that resolve
+ * to an internal/reserved address. Used by the redirect-following download path so that each hop —
+ * the original URL AND every redirect target — is validated at connect time, not just the first one.
+ * This closes the redirect-bypass hole a single-host pin can't: a 3xx to an internal host is rejected
+ * at the socket. Allowlisted hosts (SSRF_ALLOWED_HOSTS) are resolved without the block check, matching
+ * {@link resolveSafeFetchTarget}.
+ */
+export function validatingLookup(): LookupFunction {
+ const fn = (hostname: string, options: LookupOptions, callback: (...args: unknown[]) => void): void => {
+ const host = hostname.replace(/^\[|\]$/g, ''); // strip IPv6 brackets
+ const allowlisted = getAllowedHosts().has(host.toLowerCase());
+ const finish = (addrs: LookupAddress[]): void => {
+ if (options.all) callback(null, addrs);
+ else callback(null, addrs[0].address, addrs[0].family);
+ };
+
+ if (isIPv4(host) || isIPv6(host)) {
+ if (!allowlisted && isBlockedAddress(host)) {
+ callback(new SsrfBlockedError(`Blocked internal address: ${host}`));
+ return;
+ }
+ finish([{ address: host, family: isIPv6(host) ? 6 : 4 }]);
+ return;
+ }
+
+ lookupWithDeadline(host)
+ .then(resolved => {
+ if (resolved.length === 0) {
+ callback(new SsrfBlockedError(`Could not resolve host: ${host}`));
+ return;
+ }
+ if (!allowlisted) {
+ const bad = resolved.find(a => isBlockedAddress(a.address));
+ if (bad) {
+ callback(new SsrfBlockedError(`Host ${host} resolves to a blocked internal address: ${bad.address}`));
+ return;
+ }
+ }
+ finish(resolved);
+ })
+ .catch((err: unknown) => callback(err instanceof Error ? err : new Error(String(err))));
+ };
+ return fn as unknown as LookupFunction;
+}
+
/**
* Perform an SSRF-safe fetch and hand the response to `use`, then tear down the per-request
* connection. The host is validated and resolved ONCE; the connection is pinned to the vetted IP(s)
@@ -291,13 +337,28 @@ export async function withSafeFetch<T>(
rawUrl: string,
init: RequestInit,
use: (response: Response) => Promise<T> | T,
- opts: { guard?: boolean } = {},
+ opts: { guard?: boolean; followRedirects?: boolean } = {},
): Promise<T> {
const guard = opts.guard ?? true;
if (!guard) {
return use(await undiciFetch(rawUrl, { ...init, redirect: 'follow' }));
}
+ if (opts.followRedirects) {
+ // Download path (plugin .zip / catalog JSON): public release hosts legitimately 302 to a CDN, so
+ // refusing every redirect breaks them. Follow redirects, but SECURELY — instead of pinning one
+ // host's IPs, route the connection through a lookup that resolves+validates EVERY host on demand,
+ // so each hop (original + every redirect target) is checked at connect time and a 3xx to an
+ // internal host is blocked at the socket. The scheme/host of the original URL is validated first.
+ await resolveSafeFetchTarget(rawUrl);
+ const dispatcher = new Agent({ connect: { lookup: validatingLookup() } });
+ try {
+ return await use(await undiciFetch(rawUrl, { ...init, redirect: 'follow', dispatcher }));
+ } finally {
+ await dispatcher.destroy().catch(() => undefined);
+ }
+ }
+
const target = await resolveSafeFetchTarget(rawUrl);
const dispatcher = target ? new Agent({ connect: { lookup: pinnedLookup(target) } }) : undefined;
try {
diff --git a/src/core/hooks/hook.interfaces.ts b/src/core/hooks/hook.interfaces.ts
index 5150711a7..19456f40c 100644
--- a/src/core/hooks/hook.interfaces.ts
+++ b/src/core/hooks/hook.interfaces.ts
@@ -25,6 +25,37 @@ export type HookEvent =
| 'webhook:after' // After webhook attempt (direct mode only, deprecated for queue)
| 'webhook:error'; // After webhook delivery failed (all retries exhausted)
+// Runtime allowlist of every HookEvent. The Record is exhaustively typed, so adding a HookEvent above
+// without listing it here is a COMPILE error — keeping the runtime set in lockstep with the type.
+// Used to reject fabricated event names at the sandbox IPC boundary (HookEvent is type-only; the wire
+// payload is an arbitrary string), bounding host-registry growth to this finite set.
+const HOOK_EVENT_REGISTRY: Record<HookEvent, true> = {
+ 'session:created': true,
+ 'session:starting': true,
+ 'session:ready': true,
+ 'session:qr': true,
+ 'session:disconnected': true,
+ 'session:error': true,
+ 'session:deleted': true,
+ 'message:received': true,
+ 'message:sending': true,
+ 'message:sent': true,
+ 'message:failed': true,
+ 'message:ack': true,
+ 'webhook:before': true,
+ 'webhook:queued': true,
+ 'webhook:delivered': true,
+ 'webhook:after': true,
+ 'webhook:error': true,
+};
+
+export const KNOWN_HOOK_EVENTS: ReadonlySet<HookEvent> = new Set(Object.keys(HOOK_EVENT_REGISTRY) as HookEvent[]);
+
+/** Type guard: is `event` one of the known HookEvent values? Narrows an untrusted string to HookEvent. */
+export function isKnownHookEvent(event: string): event is HookEvent {
+ return (KNOWN_HOOK_EVENTS as ReadonlySet<string>).has(event);
+}
+
export interface HookContext<T = unknown> {
event: HookEvent;
data: T;
diff --git a/src/core/plugins/plugin-loader-activation.spec.ts b/src/core/plugins/plugin-loader-activation.spec.ts
index 6f6310668..183a02bae 100644
--- a/src/core/plugins/plugin-loader-activation.spec.ts
+++ b/src/core/plugins/plugin-loader-activation.spec.ts
@@ -103,3 +103,38 @@ describe('PluginLoaderService — per-session activation gate (hook delivery)',
});
});
});
+
+// A built-in/bundled plugin must read its persisted per-session activation + config back into the
+// runtime on boot, exactly like a directory plugin (loadPlugin) — otherwise the gate falls back to
+// all-sessions/base-config after every restart, silently widening delivery for a plugin the operator
+// had restricted.
+describe('PluginLoaderService — registerBuiltInPlugin restart read-back', () => {
+ it('seeds activeSessions and sessionConfig from persisted storage', () => {
+ const hookManager = new HookManager();
+ const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
+ const pluginStorage = {
+ getPluginConfig: jest.fn().mockReturnValue({}),
+ getPluginSessions: jest.fn().mockReturnValue(['sess-1']),
+ getPluginSessionConfig: jest.fn().mockReturnValue({ 'sess-1': { lang: 'id' } }),
+ getPluginEntry: jest.fn().mockReturnValue(undefined),
+ setPluginEntry: jest.fn(),
+ } as unknown as PluginStorageService;
+ const loader = new PluginLoaderService(configService, hookManager, pluginStorage, {
+ get: jest.fn(),
+ } as unknown as ModuleRef);
+
+ const manifest: PluginManifest = {
+ id: 'builtin-ext',
+ name: 'Built-in Ext',
+ version: '1.0.0',
+ type: PluginType.EXTENSION,
+ main: 'index.js',
+ sessionScoped: true,
+ };
+ loader.registerBuiltInPlugin(manifest, {});
+
+ const plugin = (loader as unknown as { plugins: Map<string, PluginInstance> }).plugins.get('builtin-ext');
+ expect(plugin?.activeSessions).toEqual(['sess-1']);
+ expect(plugin?.sessionConfig).toEqual({ 'sess-1': { lang: 'id' } });
+ });
+});
diff --git a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
index c4a21e283..c57af09ac 100644
--- a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
+++ b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
@@ -11,7 +11,12 @@ type FakeHost = { load: jest.Mock; runLifecycle: jest.Mock; terminate: jest.Mock
/** Loader that returns fake worker hosts so routing is testable without spawning a real OS thread. */
class TestableLoader extends PluginLoaderService {
readonly hosts: FakeHost[] = [];
- protected createSandboxHost(): PluginWorkerHost {
+ capturedOnHookSubscribe?: (event: string, priority?: number) => void;
+ protected createSandboxHost(
+ _capDispatcher?: (verb: string, args: unknown[]) => Promise<unknown>,
+ onHookSubscribe?: (event: string, priority?: number) => void,
+ ): PluginWorkerHost {
+ this.capturedOnHookSubscribe = onHookSubscribe;
const host: FakeHost = {
load: jest.fn().mockResolvedValue(undefined),
runLifecycle: jest.fn().mockResolvedValue(undefined),
@@ -100,6 +105,46 @@ describe('PluginLoaderService — sandbox tier routing', () => {
expect((loader as unknown as { sandboxHosts: Map<string, unknown> }).sandboxHosts.has('p1')).toBe(false);
});
+ it('dedups duplicate hook-subscribe from the worker so a flood cannot grow the host registry', async () => {
+ const loader = makeLoader();
+ seed(loader, { builtIn: false, instance: null });
+ const hookManager = (loader as unknown as { hookManager: HookManager }).hookManager;
+ const registerSpy = jest.spyOn(hookManager, 'register');
+
+ await loader.enablePlugin('p1');
+ const onHookSubscribe = loader.capturedOnHookSubscribe;
+ expect(onHookSubscribe).toBeDefined();
+
+ // A hostile worker posts the same subscribe many times; the host must register it ONCE.
+ onHookSubscribe!('message:received');
+ onHookSubscribe!('message:received');
+ onHookSubscribe!('message:received');
+ expect(registerSpy.mock.calls.filter(c => c[1] === 'message:received')).toHaveLength(1);
+
+ // A genuinely distinct event still registers.
+ onHookSubscribe!('message:sending');
+ expect(registerSpy.mock.calls.filter(c => c[1] === 'message:sending')).toHaveLength(1);
+ });
+
+ it('drops fabricated (unknown) hook-subscribe events so the host registry cannot grow unbounded', async () => {
+ const loader = makeLoader();
+ seed(loader, { builtIn: false, instance: null });
+ const hookManager = (loader as unknown as { hookManager: HookManager }).hookManager;
+ const registerSpy = jest.spyOn(hookManager, 'register');
+
+ await loader.enablePlugin('p1');
+ const onHookSubscribe = loader.capturedOnHookSubscribe;
+ expect(onHookSubscribe).toBeDefined();
+
+ // A worker floods the boundary with fabricated event names — none may reach hookManager.register.
+ for (let i = 0; i < 1000; i++) onHookSubscribe!(`x:${i}`);
+ expect(registerSpy).not.toHaveBeenCalled();
+
+ // A real, known event still registers.
+ onHookSubscribe!('message:received');
+ expect(registerSpy.mock.calls.filter(c => c[1] === 'message:received')).toHaveLength(1);
+ });
+
it('enables a built-in plugin in-process (no sandbox worker spawned)', async () => {
const loader = makeLoader();
const onEnable = jest.fn().mockResolvedValue(undefined);
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index a1b282d3d..c7ca0256f 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -84,6 +84,8 @@ describe('PluginLoaderService.registerBuiltInPlugin config', () => {
getPluginEntry: jest.fn().mockReturnValue(undefined),
setPluginEntry: jest.fn(),
getPluginConfig: jest.fn().mockReturnValue(null),
+ getPluginSessions: jest.fn().mockReturnValue(undefined),
+ getPluginSessionConfig: jest.fn().mockReturnValue(undefined),
} as unknown as PluginStorageService;
return new PluginLoaderService(configService, new HookManager(), pluginStorage, {} as unknown as ModuleRef);
}
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 4bdef2409..2b69d894a 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -5,7 +5,7 @@ import { AsyncLocalStorage } from 'async_hooks';
import * as fs from 'fs';
import * as path from 'path';
import { createLogger } from '../../common/services/logger.service';
-import { HookManager, HookEvent } from '../hooks';
+import { HookManager, HookEvent, KNOWN_HOOK_EVENTS, isKnownHookEvent } from '../hooks';
import {
PluginCapabilityError,
PluginCapabilityPermission,
@@ -666,10 +666,33 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
// When the worker subscribes to a hook, register a shim with the hook manager that dispatches the
// event into the worker (time-bounded, so a wedged plugin can't stall the chain). The shim looks
// the host up at fire time, so disabling the plugin (which removes it + unregisters hooks) stops it.
+ // Harden the IPC boundary against an untrusted worker flooding the host hook registry. HookEvent is
+ // a type-only union and the wire payload is an arbitrary string, so a hostile/buggy worker can post
+ // 'hook-subscribe' with (a) the same event repeatedly and (b) unbounded fabricated event names
+ // ('x:0','x:1',…). Without guards each call adds a live host-side registration (unbounded host-heap
+ // growth + an O(n log n) re-sort). Three guards, all local to this enableSandboxed call (dropped on
+ // disable): reject unknown events (bounds growth to the finite known set + drops events that can
+ // never fire), dedup per event, and a belt-and-suspenders size cap.
+ const subscribedEvents = new Set<HookEvent>();
+ let unknownEventWarned = false;
const onHookSubscribe = (event: string, priority?: number): void => {
+ if (!isKnownHookEvent(event)) {
+ if (!unknownEventWarned) {
+ unknownEventWarned = true; // warn at most once per plugin so a flood isn't a log-flood vector
+ this.logger.warn(`Sandboxed plugin ${pluginId} subscribed to an unknown hook event; ignoring`, {
+ pluginId,
+ event,
+ action: 'sandbox_unknown_hook_event',
+ });
+ }
+ return;
+ }
+ if (subscribedEvents.has(event)) return;
+ if (subscribedEvents.size >= KNOWN_HOOK_EVENTS.size) return; // can't exceed the known set
+ subscribedEvents.add(event);
this.hookManager.register(
pluginId,
- event as HookEvent,
+ event,
async hookCtx => {
const liveHost = this.sandboxHosts.get(pluginId);
if (!liveHost) return { continue: true };
@@ -859,6 +882,11 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
instance,
loadedAt: new Date(),
builtIn: true,
+ // Read persisted per-session activation + config back into the runtime, like loadPlugin —
+ // otherwise the delivery gate falls back to all-sessions/base-config after every restart for a
+ // session-scoped built-in the operator had restricted.
+ activeSessions: this.pluginStorage.getPluginSessions(manifest.id) ?? undefined,
+ sessionConfig: this.pluginStorage.getPluginSessionConfig(manifest.id) ?? undefined,
};
this.plugins.set(manifest.id, pluginInstance);
diff --git a/src/core/plugins/plugin-net.spec.ts b/src/core/plugins/plugin-net.spec.ts
index c199a336c..89d075c49 100644
--- a/src/core/plugins/plugin-net.spec.ts
+++ b/src/core/plugins/plugin-net.spec.ts
@@ -77,6 +77,17 @@ describe('performPluginFetch', () => {
expect(sink.init?.body).toBe('{}');
});
+ it('coerces a non-numeric timeoutMs to the default instead of throwing a RangeError', async () => {
+ const sink: { init?: RequestInit } = {};
+ const fetcher = fakeSafeFetch(cannedResponse('{}', { 'content-type': 'application/json' }), sink);
+ // A string 'abc' would make AbortSignal.timeout(NaN) throw before the request runs; the coercion
+ // must fall back to the default so the documented timeout clamp holds and the fetch proceeds.
+ await expect(
+ performPluginFetch('https://api.example.com/t', { timeoutMs: 'abc' as unknown as number }, { fetch: fetcher }),
+ ).resolves.toMatchObject({ ok: true });
+ expect(sink.init?.signal).toBeInstanceOf(AbortSignal);
+ });
+
it('rejects a response whose declared content-length exceeds the cap', async () => {
const sink: { init?: RequestInit } = {};
const big = String(11 * 1024 * 1024);
diff --git a/src/core/plugins/plugin-net.ts b/src/core/plugins/plugin-net.ts
index 8dd63f179..3ffadb7a5 100644
--- a/src/core/plugins/plugin-net.ts
+++ b/src/core/plugins/plugin-net.ts
@@ -58,7 +58,12 @@ export async function performPluginFetch(
deps: { fetch?: typeof withSafeFetch } = {},
): Promise<PluginNetResponse> {
const safeFetch = deps.fetch ?? withSafeFetch;
- const timeoutMs = Math.min(Math.max(init.timeoutMs ?? DEFAULT_TIMEOUT_MS, 1), MAX_TIMEOUT_MS);
+ // Coerce a non-finite timeoutMs (a string/object/NaN from the untrusted worker) to the default
+ // instead of letting it flow through as NaN — `Math.max('abc', 1)` is NaN, and AbortSignal.timeout(NaN)
+ // throws a RangeError, silently defeating the documented default + hard-cap clamp.
+ const requested =
+ typeof init.timeoutMs === 'number' && Number.isFinite(init.timeoutMs) ? init.timeoutMs : DEFAULT_TIMEOUT_MS;
+ const timeoutMs = Math.min(Math.max(requested, 1), MAX_TIMEOUT_MS);
return safeFetch<PluginNetResponse>(
url,
diff --git a/src/core/plugins/plugin-storage.service.spec.ts b/src/core/plugins/plugin-storage.service.spec.ts
index 5e22b5a74..3eec8fcb9 100644
--- a/src/core/plugins/plugin-storage.service.spec.ts
+++ b/src/core/plugins/plugin-storage.service.spec.ts
@@ -34,6 +34,13 @@ describe('PluginStorageService sandboxed per-plugin storage containment', () =>
expect(await storage.get('state')).toBeNull();
});
+ it('creates the per-plugin dir 0o700 and data files 0o600 (persisted secrets not world-readable)', async () => {
+ await storage.set('secret', { token: 'shh' });
+ const pluginDataDir = path.join(dataDir, 'plugins', pluginId);
+ expect(fs.statSync(pluginDataDir).mode & 0o777).toBe(0o700);
+ expect(fs.statSync(path.join(pluginDataDir, 'secret.json')).mode & 0o777).toBe(0o600);
+ });
+
it('is atomic: a write that fails mid-way leaves the previous file intact (no partial overwrite)', async () => {
await storage.set('state', { good: true });
// Simulate a crash after the temp file is written but before the rename — the target must keep its
diff --git a/src/core/plugins/plugin-storage.service.ts b/src/core/plugins/plugin-storage.service.ts
index c661a37b5..954e42d4b 100644
--- a/src/core/plugins/plugin-storage.service.ts
+++ b/src/core/plugins/plugin-storage.service.ts
@@ -176,9 +176,11 @@ export class PluginStorageService {
createPluginStorage(pluginId: string): PluginStorage {
const pluginDataDir = path.join(this.dataDir, 'plugins', pluginId);
- // Ensure directory exists
+ // Ensure directory exists. 0o700 (owner-only) because plugin storage holds the same class of
+ // secret as the registry (OAuth/refresh tokens, webhook secrets a plugin persists) — mirror the
+ // hardening saveRegistry already applies rather than inherit a group/other-readable umask default.
if (!fs.existsSync(pluginDataDir)) {
- fs.mkdirSync(pluginDataDir, { recursive: true });
+ fs.mkdirSync(pluginDataDir, { recursive: true, mode: 0o700 });
}
const logger = this.logger;
@@ -213,7 +215,11 @@ export class PluginStorageService {
return Promise.reject(new Error(`Unsafe plugin storage key (escapes sandbox): ${key}`));
}
try {
- atomicWriteFileSync(filePath, JSON.stringify(value, null, 2));
+ // 0o600 (owner-only): a plugin-persisted secret must not land in a group/other-readable file.
+ // The mode on the temp write carries through the rename; chmod is a backstop if the target
+ // pre-existed (writeFileSync mode only applies on create). Mirrors saveRegistry's hardening.
+ atomicWriteFileSync(filePath, JSON.stringify(value, null, 2), { mode: 0o600 });
+ fs.chmodSync(filePath, 0o600);
return Promise.resolve();
} catch (error) {
logger.error(`Failed to write plugin data: ${pluginId}/${key}`, String(error));
diff --git a/src/core/plugins/sandbox/plugin-worker-host.spec.ts b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
index 8d497072f..6d7452919 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.spec.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
@@ -211,6 +211,17 @@ describe('PluginWorkerHost', () => {
expect(onTimeout).toHaveBeenCalled();
jest.useRealTimers();
});
+
+ it('drains an in-flight hook immediately on worker exit (no stall for the full hook timeout)', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ // A long timeout: only the worker-exit drain (not the timer) can settle this promptly.
+ const pending = host.dispatchHook({ event: 'message:received', data: {}, source: 'Engine', timeoutMs: 5000 });
+ ch.crash(1);
+
+ await expect(pending).resolves.toEqual({ continue: true });
+ });
});
describe('logger + static context', () => {
diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.ts
index 64d873a26..def0d5823 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.ts
@@ -253,6 +253,14 @@ export class PluginWorkerHost {
resolve({ healthy: false, message: 'plugin worker exited' });
});
this.healthPending.clear();
+ // Drain in-flight hooks too (symmetry with the maps above): resolve {continue:true} — the same
+ // fail-open value the per-hook timeout already produces — so the host hook chain unblocks
+ // immediately on a worker crash instead of stalling for the full hook timeout per in-flight hook.
+ this.hookPending.forEach(({ resolve, timer }) => {
+ clearTimeout(timer);
+ resolve({ continue: true });
+ });
+ this.hookPending.clear();
}
private drain<T>(waiters: T[], fn: (w: T) => void): void {
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 88d572b95..3b7b1d483 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -56,7 +56,16 @@ jest.mock('@whiskeysockets/baileys', () => ({
useMultiFileAuthState: jest.fn().mockResolvedValue({ state: { creds: {}, keys: {} }, saveCreds }),
fetchLatestBaileysVersion: jest.fn().mockResolvedValue({ version: [2, 3000, 0] }),
getContentType: jest.fn(() => 'conversation'),
- downloadMediaMessage: jest.fn().mockResolvedValue(Buffer.from('IMGDATA')),
+ // The adapter now downloads via 'stream' mode, so resolve to an async-iterable of chunks (factory is
+ // hoisted above imports, so this stays inline; tests override with the `streamOf` helper below).
+ downloadMediaMessage: jest.fn(() =>
+ Promise.resolve({
+ // eslint-disable-next-line @typescript-eslint/require-await
+ async *[Symbol.asyncIterator]() {
+ yield Buffer.from('IMGDATA');
+ },
+ }),
+ ),
// Identity passthrough by default; individual tests may override to simulate unwrapping.
normalizeMessageContent: jest.fn((c: unknown) => c),
DisconnectReason: { loggedOut: 401, restartRequired: 515 },
@@ -80,6 +89,17 @@ const fakeStore = {
getMessage: jest.fn(),
clearSession: jest.fn().mockResolvedValue(undefined),
};
+
+/** A fresh async-iterable stream of the given chunks (the shape `downloadMediaMessage('stream')` returns). */
+function streamOf(...chunks: Buffer[]): AsyncIterable<Buffer> & { destroy: () => void } {
+ return {
+ // eslint-disable-next-line @typescript-eslint/require-await
+ async *[Symbol.asyncIterator]() {
+ for (const c of chunks) yield c;
+ },
+ destroy: jest.fn(),
+ };
+}
const newAdapter = (): BaileysAdapter =>
new BaileysAdapter({ sessionId: 'sess-1', authDir: './data/baileys', messageStore: fakeStore });
@@ -710,7 +730,7 @@ describe('BaileysAdapter inbound fan-out', () => {
};
baileys.getContentType.mockReturnValue('imageMessage');
const imgBuf = Buffer.from('PNGBYTES');
- baileys.downloadMediaMessage.mockResolvedValue(imgBuf);
+ baileys.downloadMediaMessage.mockResolvedValue(streamOf(imgBuf));
const onMessage = jest.fn();
const adapter = newAdapter();
@@ -739,6 +759,81 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(msg.media).toEqual({ mimetype: 'image/png', data: imgBuf.toString('base64') });
});
+ it('inbound media: skips the download entirely when the declared fileLength exceeds the cap', async () => {
+ const prev = process.env.MEDIA_DOWNLOAD_MAX_BYTES;
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '10';
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
+ const baileys = jest.requireMock('@whiskeysockets/baileys') as {
+ getContentType: jest.Mock;
+ downloadMediaMessage: jest.Mock;
+ };
+ baileys.getContentType.mockReturnValue('documentMessage');
+ baileys.downloadMediaMessage.mockClear();
+
+ const onMessage = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessage });
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'BIG1' },
+ message: { documentMessage: { mimetype: 'application/pdf', fileName: 'huge.pdf', fileLength: 1000 } },
+ messageTimestamp: 1700000030,
+ },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ const msg = onMessage.mock.calls[0][0] as { media: { omitted?: boolean; data?: string; sizeBytes?: number } };
+ expect(msg.media.omitted).toBe(true);
+ expect(msg.media.data).toBeUndefined();
+ expect(msg.media.sizeBytes).toBe(1000);
+ expect(baileys.downloadMediaMessage).not.toHaveBeenCalled(); // over-cap media is never downloaded
+ } finally {
+ if (prev === undefined) delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;
+ else process.env.MEDIA_DOWNLOAD_MAX_BYTES = prev;
+ }
+ });
+
+ it('inbound media: aborts mid-download when the stream exceeds the cap (sender understated size)', async () => {
+ const prev = process.env.MEDIA_DOWNLOAD_MAX_BYTES;
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '10';
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
+ const baileys = jest.requireMock('@whiskeysockets/baileys') as {
+ getContentType: jest.Mock;
+ downloadMediaMessage: jest.Mock;
+ };
+ baileys.getContentType.mockReturnValue('imageMessage');
+ // No declared fileLength (passes the pre-gate), but the stream yields 18 bytes > the 10-byte cap.
+ baileys.downloadMediaMessage.mockResolvedValue(streamOf(Buffer.alloc(6), Buffer.alloc(6), Buffer.alloc(6)));
+
+ const onMessage = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessage });
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'LIAR1' },
+ message: { imageMessage: { mimetype: 'image/png' } },
+ messageTimestamp: 1700000031,
+ },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ const msg = onMessage.mock.calls[0][0] as { media: { omitted?: boolean; data?: string } };
+ expect(msg.media.omitted).toBe(true);
+ expect(msg.media.data).toBeUndefined();
+ } finally {
+ if (prev === undefined) delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;
+ else process.env.MEDIA_DOWNLOAD_MAX_BYTES = prev;
+ }
+ });
+
it('inbound documentWithCaption: normalizeMessageContent unwraps wrapper, yields non-empty mimetype', async () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const baileys = jest.requireMock('@whiskeysockets/baileys') as {
@@ -748,7 +843,7 @@ describe('BaileysAdapter inbound fan-out', () => {
};
baileys.getContentType.mockReturnValue('documentWithCaptionMessage');
const docBuf = Buffer.from('PDFBYTES');
- baileys.downloadMediaMessage.mockResolvedValue(docBuf);
+ baileys.downloadMediaMessage.mockResolvedValue(streamOf(docBuf));
// Simulate normalizeMessageContent unwrapping: returns the inner documentMessage.
baileys.normalizeMessageContent.mockReturnValue({
documentMessage: { mimetype: 'application/pdf', fileName: 'report.pdf', caption: 'Q1 report' },
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 9ca25568b..78ba580a9 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -40,7 +40,13 @@ import { MessageNotFoundError } from '../../common/errors/message-not-found.erro
import { createLogger } from '../../common/services/logger.service';
import { BaileysAdapterConfig, BaileysLogger } from '../types/baileys.types';
import { BaileysSessionStore } from './baileys-session-store';
-import { capInboundMedia } from './inbound-media-cap';
+import {
+ capInboundMedia,
+ inboundMediaConcurrency,
+ inboundMediaMaxBytes,
+ coerceDeclaredSize,
+} from './inbound-media-cap';
+import { ConcurrencyLimiter } from './concurrency-limiter';
/** Linked-device identity shown in WhatsApp (Settings → Linked Devices). */
const BAILEYS_BROWSER: [string, string, string] = ['OpenWA', 'Chrome', '120.0.0'];
@@ -103,6 +109,9 @@ export class BaileysAdapter implements IWhatsAppEngine {
private static readonly MAX_RECONNECT_ATTEMPTS = 5;
private readonly logger = createLogger('BaileysAdapter');
+ // Bound concurrent inbound media downloads: each materialises a full decrypted buffer in heap, so an
+ // unbounded fire-and-forget loop lets a sender flood the gateway with N parallel multi-MB allocations.
+ private readonly inboundLimiter = new ConcurrencyLimiter(inboundMediaConcurrency());
private readonly authPath: string;
private readonly sessionStore: BaileysSessionStore;
private sock: WASocket | null = null;
@@ -799,7 +808,10 @@ export class BaileysAdapter implements IWhatsAppEngine {
if (!msg.message || !msg.key?.remoteJid) {
continue; // protocol/empty messages carry no neutral content
}
- void this.processInboundMessage(msg);
+ // Throttle through the limiter so a burst of media messages can't run unbounded parallel
+ // downloads (each a full decrypted buffer in heap). Ordering stays correct — the message store
+ // keeps the newest by timestamp — and none are dropped (the limiter queues the overflow).
+ void this.inboundLimiter.run(() => this.processInboundMessage(msg));
}
}
@@ -903,6 +915,37 @@ export class BaileysAdapter implements IWhatsAppEngine {
}
}
+ /**
+ * Download inbound media via a stream, accumulating chunks but ABORTING (destroy + discard) once the
+ * running total exceeds `maxBytes`. Returns null on abort. Uses `downloadMediaMessage(..., 'stream')`
+ * (not the raw `downloadContentFromMessage`) so the library's expired-media re-upload retry is kept;
+ * for under-cap media the concatenated buffer is byte-identical to the 'buffer' mode it replaces.
+ */
+ private async downloadInboundMediaCapped(msg: WAMessage, maxBytes: number): Promise<Buffer | null> {
+ const b = await this.loadLib();
+ const stream = (await b.downloadMediaMessage(
+ msg,
+ 'stream',
+ {},
+ {
+ logger: createSilentLogger(),
+ reuploadRequest: this.sock!.updateMediaMessage,
+ },
+ )) as AsyncIterable<Buffer> & { destroy?: () => void };
+
+ const chunks: Buffer[] = [];
+ let total = 0;
+ for await (const chunk of stream) {
+ total += chunk.length;
+ if (total > maxBytes) {
+ stream.destroy?.();
+ return null;
+ }
+ chunks.push(chunk);
+ }
+ return Buffer.concat(chunks);
+ }
+
private async mapMessage(msg: WAMessage, contentType: string | undefined): Promise<IncomingMessage> {
const b = await this.loadLib();
const content = msg.message ?? {};
@@ -942,46 +985,54 @@ export class BaileysAdapter implements IWhatsAppEngine {
contentType === 'documentWithCaptionMessage' ||
contentType === 'stickerMessage';
if (isMediaType) {
- try {
- const buf = await b.downloadMediaMessage(
- msg,
- 'buffer',
- {},
- {
- logger: createSilentLogger(),
- reuploadRequest: this.sock!.updateMediaMessage,
- },
- );
- // normalizeMessageContent unwraps documentWithCaptionMessage / viewOnceMessage /
- // ephemeralMessage wrappers so we always reach the inner media sub-message.
- const normalizedContent = b.normalizeMessageContent(content) ?? content;
- const subMessage =
- normalizedContent.imageMessage ??
- normalizedContent.videoMessage ??
- normalizedContent.audioMessage ??
- normalizedContent.documentMessage ??
- normalizedContent.stickerMessage;
- const mimetype = subMessage?.mimetype ?? '';
- const filename = normalizedContent.documentMessage?.fileName ?? undefined;
- // Cap inbound media (lazy base64) so an oversized blob from an untrusted sender is never
- // encoded/persisted/webhooked/broadcast — preventing heap blow-up. Envelope is kept.
- media = capInboundMedia({
- mimetype,
- filename,
- sizeBytes: buf.byteLength,
- toBase64: () => buf.toString('base64'),
+ // normalizeMessageContent unwraps documentWithCaptionMessage / viewOnceMessage / ephemeralMessage
+ // so we reach the inner media sub-message — needed BEFORE download for the declared-size pre-gate.
+ const normalizedContent = b.normalizeMessageContent(content) ?? content;
+ const subMessage =
+ normalizedContent.imageMessage ??
+ normalizedContent.videoMessage ??
+ normalizedContent.audioMessage ??
+ normalizedContent.documentMessage ??
+ normalizedContent.stickerMessage;
+ const mimetype = subMessage?.mimetype ?? '';
+ const filename = normalizedContent.documentMessage?.fileName ?? undefined;
+ const maxBytes = inboundMediaMaxBytes();
+ const declared = coerceDeclaredSize(subMessage?.fileLength);
+
+ if (declared > maxBytes) {
+ // Pre-download gate: an honest over-cap sender's media is never decrypted into heap at all
+ // (Baileys integrity-checks content against the declared size, so this is a robust bound).
+ media = { mimetype, filename, omitted: true, sizeBytes: declared };
+ this.logger.warn('Inbound media declared size exceeds MEDIA_DOWNLOAD_MAX_BYTES; skipped download', {
+ msgId: msg.key.id,
+ sizeBytes: declared,
});
- if (media.omitted) {
- this.logger.warn('Inbound media exceeds MEDIA_DOWNLOAD_MAX_BYTES; dropped payload, kept envelope', {
+ } else {
+ try {
+ // Stream-download with a running-total abort so a sender who understates fileLength still
+ // can't materialise an over-cap blob. For under-cap media this yields the identical buffer.
+ const buf = await this.downloadInboundMediaCapped(msg, maxBytes);
+ if (buf === null) {
+ media = { mimetype, filename, omitted: true, sizeBytes: maxBytes };
+ this.logger.warn('Inbound media exceeded MEDIA_DOWNLOAD_MAX_BYTES mid-download; aborted', {
+ msgId: msg.key.id,
+ });
+ } else {
+ // capInboundMedia is the last line (lazy base64, never persist/webhook/broadcast an over-cap
+ // blob); the real heap bound is the pre-gate + streaming abort + concurrency limiter.
+ media = capInboundMedia({
+ mimetype,
+ filename,
+ sizeBytes: buf.byteLength,
+ toBase64: () => buf.toString('base64'),
+ });
+ }
+ } catch (err) {
+ this.logger.debug('Failed to download inbound media; emitting message without media', {
+ error: err instanceof Error ? err.message : String(err),
msgId: msg.key.id,
- sizeBytes: media.sizeBytes,
});
}
- } catch (err) {
- this.logger.debug('Failed to download inbound media; emitting message without media', {
- error: err instanceof Error ? err.message : String(err),
- msgId: msg.key.id,
- });
}
}
diff --git a/src/engine/adapters/concurrency-limiter.spec.ts b/src/engine/adapters/concurrency-limiter.spec.ts
new file mode 100644
index 000000000..dfc93dc7d
--- /dev/null
+++ b/src/engine/adapters/concurrency-limiter.spec.ts
@@ -0,0 +1,78 @@
+import { ConcurrencyLimiter } from './concurrency-limiter';
+
+describe('ConcurrencyLimiter', () => {
+ it('never runs more than `max` tasks at once and still runs them all', async () => {
+ const limiter = new ConcurrencyLimiter(2);
+ let active = 0;
+ let peak = 0;
+ let done = 0;
+
+ const tasks = Array.from({ length: 8 }, () =>
+ limiter.run(async () => {
+ active++;
+ peak = Math.max(peak, active);
+ await new Promise<void>(resolve => setTimeout(resolve, 5));
+ active--;
+ done++;
+ }),
+ );
+
+ await Promise.all(tasks);
+
+ expect(peak).toBe(2); // concurrency cap held across all 8
+ expect(done).toBe(8); // none dropped — queued tasks still ran
+ });
+
+ it('never exceeds max when a fresh arrival races a just-woken waiter', async () => {
+ // The synchronous-burst test above can't catch the over-admission race: a freeing slot wakes a
+ // waiter, but a NEW run() arriving in the microtask gap (before the woken waiter increments) sees
+ // the slot as free and admits too. This interleaves arrivals/completions across microtasks to hit it.
+ const limiter = new ConcurrencyLimiter(1);
+ let running = 0;
+ let peak = 0;
+ const releases: Array<() => void> = [];
+ const spawn = (): Promise<void> =>
+ limiter.run(
+ () =>
+ new Promise<void>(resolve => {
+ running++;
+ peak = Math.max(peak, running);
+ releases.push(() => {
+ running--;
+ resolve();
+ });
+ }),
+ );
+
+ const a = spawn(); // A admitted, running=1
+ await Promise.resolve();
+ const b = spawn(); // B queued behind A
+ await Promise.resolve();
+
+ releases[0](); // finish A: its finally frees the slot and wakes B
+ await Promise.resolve(); // A's finally runs: slot free, B woken (its increment still pending)
+ const c = spawn(); // C arrives in the gap — must NOT admit alongside the woken B
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(peak).toBeLessThanOrEqual(1);
+
+ // Drain: waking a waiter makes it run and push its own release, so keep flushing until none remain.
+ for (let i = 0; i < 20 && (running > 0 || releases.length); i++) {
+ releases.splice(0).forEach(r => r());
+ await new Promise<void>(r => setTimeout(r, 0));
+ }
+ await Promise.all([a, b, c]);
+ });
+
+ it('clamps a non-positive max to 1 (never deadlocks)', async () => {
+ const limiter = new ConcurrencyLimiter(0);
+ await expect(limiter.run(() => Promise.resolve('ok'))).resolves.toBe('ok');
+ });
+
+ it('frees its slot even when a task throws (no permanent leak)', async () => {
+ const limiter = new ConcurrencyLimiter(1);
+ await expect(limiter.run(() => Promise.reject(new Error('boom')))).rejects.toThrow('boom');
+ await expect(limiter.run(() => Promise.resolve('after'))).resolves.toBe('after'); // slot was released
+ });
+});
diff --git a/src/engine/adapters/concurrency-limiter.ts b/src/engine/adapters/concurrency-limiter.ts
new file mode 100644
index 000000000..aff272735
--- /dev/null
+++ b/src/engine/adapters/concurrency-limiter.ts
@@ -0,0 +1,36 @@
+/**
+ * Minimal async concurrency gate: runs at most `max` tasks concurrently, queueing the rest (FIFO).
+ * Used to bound how many inbound media downloads run at once — each materializes a full decrypted
+ * buffer in heap, so an unbounded fire-and-forget loop lets a sender flood the gateway with N parallel
+ * multi-MB allocations. No external dependency (the codebase ships no p-limit/semaphore).
+ */
+export class ConcurrencyLimiter {
+ private active = 0;
+ private readonly waiters: Array<() => void> = [];
+
+ /** `max` is clamped to at least 1 so a misconfigured 0/negative value never deadlocks the gate. */
+ constructor(private readonly max: number) {
+ this.max = Math.max(1, Math.floor(max));
+ }
+
+ async run<T>(task: () => Promise<T>): Promise<T> {
+ if (this.active < this.max) {
+ this.active++;
+ } else {
+ // Park until a finishing task HANDS us its slot. We must not increment on wake: the count was
+ // never released (it was transferred), so re-incrementing would over-admit when a fresh run()
+ // raced into the microtask gap and already took a (wrongly-freed) slot.
+ await new Promise<void>(resolve => this.waiters.push(resolve));
+ }
+ try {
+ return await task();
+ } finally {
+ const next = this.waiters.shift();
+ if (next) {
+ next(); // transfer this slot to the next waiter — active count stays the same (no free window)
+ } else {
+ this.active--; // no one waiting: actually release the slot
+ }
+ }
+ }
+}
diff --git a/src/engine/adapters/inbound-media-cap.spec.ts b/src/engine/adapters/inbound-media-cap.spec.ts
index 717fc297b..a22aaa4be 100644
--- a/src/engine/adapters/inbound-media-cap.spec.ts
+++ b/src/engine/adapters/inbound-media-cap.spec.ts
@@ -1,11 +1,56 @@
-import { capInboundMedia, inboundMediaMaxBytes } from './inbound-media-cap';
+import {
+ capInboundMedia,
+ inboundMediaMaxBytes,
+ inboundMediaConcurrency,
+ coerceDeclaredSize,
+} from './inbound-media-cap';
describe('inbound media cap', () => {
const ENV = 'MEDIA_DOWNLOAD_MAX_BYTES';
+ const CONC = 'INBOUND_MEDIA_CONCURRENCY';
const orig = process.env[ENV];
+ const origConc = process.env[CONC];
afterEach(() => {
if (orig === undefined) delete process.env[ENV];
else process.env[ENV] = orig;
+ if (origConc === undefined) delete process.env[CONC];
+ else process.env[CONC] = origConc;
+ });
+
+ describe('inboundMediaConcurrency', () => {
+ it('defaults to 4', () => {
+ delete process.env[CONC];
+ expect(inboundMediaConcurrency()).toBe(4);
+ });
+ it('honors a positive override', () => {
+ process.env[CONC] = '2';
+ expect(inboundMediaConcurrency()).toBe(2);
+ });
+ it('falls back to the default for a non-positive/garbage override', () => {
+ process.env[CONC] = '0';
+ expect(inboundMediaConcurrency()).toBe(4);
+ process.env[CONC] = 'abc';
+ expect(inboundMediaConcurrency()).toBe(4);
+ });
+ });
+
+ describe('coerceDeclaredSize', () => {
+ it('passes a finite number through', () => {
+ expect(coerceDeclaredSize(1234)).toBe(1234);
+ });
+ it('reads a Long-like { toNumber() }', () => {
+ expect(coerceDeclaredSize({ toNumber: () => 5000 })).toBe(5000);
+ });
+ it('parses a numeric string', () => {
+ expect(coerceDeclaredSize('4096')).toBe(4096);
+ });
+ it("returns 0 for absent/garbage (never NaN — don't pre-gate on unknown)", () => {
+ expect(coerceDeclaredSize(undefined)).toBe(0);
+ expect(coerceDeclaredSize(null)).toBe(0);
+ expect(coerceDeclaredSize('xyz')).toBe(0);
+ expect(coerceDeclaredSize(NaN)).toBe(0);
+ expect(coerceDeclaredSize({})).toBe(0);
+ });
});
describe('inboundMediaMaxBytes', () => {
diff --git a/src/engine/adapters/inbound-media-cap.ts b/src/engine/adapters/inbound-media-cap.ts
index e6dce6ee3..a11458a9a 100644
--- a/src/engine/adapters/inbound-media-cap.ts
+++ b/src/engine/adapters/inbound-media-cap.ts
@@ -9,16 +9,46 @@ export function inboundMediaMaxBytes(): number {
return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_INBOUND_MEDIA_MAX_BYTES;
}
+/** Default number of inbound media downloads processed at once. */
+const DEFAULT_INBOUND_MEDIA_CONCURRENCY = 4;
+
+/**
+ * Max inbound media downloads processed concurrently. Each download materialises a full decrypted
+ * buffer in heap, so an unbounded fire-and-forget loop lets a sender flood the gateway with N parallel
+ * multi-MB allocations; this bounds N. Override via INBOUND_MEDIA_CONCURRENCY; garbage falls back.
+ */
+export function inboundMediaConcurrency(): number {
+ const parsed = Number.parseInt(process.env.INBOUND_MEDIA_CONCURRENCY ?? '', 10);
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_INBOUND_MEDIA_CONCURRENCY;
+}
+
+/**
+ * Coerce a sender-declared media size (a protobuf `fileLength`, which may be a number, a Long-like
+ * `{ toNumber() }`, a numeric string, or absent) to a finite byte count. Unknown/garbage → 0, i.e.
+ * "don't pre-gate" (the streaming abort is the backstop), never NaN.
+ */
+export function coerceDeclaredSize(value: unknown): number {
+ if (typeof value === 'number') return Number.isFinite(value) ? value : 0;
+ if (value && typeof (value as { toNumber?: () => number }).toNumber === 'function') {
+ const n = (value as { toNumber: () => number }).toNumber();
+ return Number.isFinite(n) ? n : 0;
+ }
+ const n = Number(value);
+ return Number.isFinite(n) ? n : 0;
+}
+
type InboundMedia = NonNullable<IncomingMessage['media']>;
/**
- * Cap inbound media from an untrusted sender. Within the limit, keep it (base64 encoded via
+ * SECONDARY guard on inbound media from an untrusted sender. Within the limit, keep it (base64 via
* `toBase64`). Over the limit, drop the blob and return a marker `{ mimetype, filename?, omitted,
- * sizeBytes }` so the `media` field stays present (n8n/dashboard contract) while the multi-MB
- * base64 is never encoded, persisted, webhooked, or broadcast.
+ * sizeBytes }` so the `media` field stays present (n8n/dashboard contract) while the multi-MB base64
+ * is never encoded, persisted, webhooked, or broadcast — the durable amplification.
*
- * `toBase64` is a lazy callback so an over-cap payload is never base64-encoded — that +33% heap
- * copy is exactly the OOM vector this guards against.
+ * `toBase64` is a lazy callback so an over-cap payload is never base64-encoded (the +33% copy). NOTE:
+ * this runs AFTER the bytes are in heap, so it does NOT bound the decrypted-download allocation — the
+ * caller must do that with the pre-download declared-size gate + the streaming abort + the concurrency
+ * limiter. This is the last line, not the OOM guard for the download itself.
*/
export function capInboundMedia(args: {
mimetype: string;
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index decb2218c..31211e69c 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -10,6 +10,7 @@ import {
resolveWebVersionPin,
wwebjsAckToDeliveryStatus,
} from './whatsapp-web-js.adapter';
+import * as fs from 'fs';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { EngineStatus } from '../interfaces/whatsapp-engine.interface';
import { SsrfBlockedError } from '../../common/security/ssrf-guard';
@@ -545,22 +546,49 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
// A wedged page can make getState() hang (the exact #251/#273 condition). The probe must keep its
// own cadence (a hung probe can't stall the loop) and still honor the 90s give-up deadline.
- it('keeps probing and still times out when getState hangs instead of stalling forever', async () => {
+ it('keeps probing and self-heals (clears auth + disconnects) when getState hangs past the deadline', async () => {
jest.useFakeTimers();
+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
const adapter = newAdapter();
- const { client } = attachFakeClient(adapter, { getState: jest.fn().mockReturnValue(new Promise<never>(() => {})) });
+ const { client } = attachFakeClient(adapter, {
+ getState: jest.fn().mockReturnValue(new Promise<never>(() => {})),
+ destroy: jest.fn().mockResolvedValue(undefined),
+ });
+ const onDisconnected = jest.fn();
+ (adapter as unknown as { callbacks: { onDisconnected?: jest.Mock } }).callbacks.onDisconnected = onDisconnected;
client.emit('authenticated');
await jest.advanceTimersByTimeAsync(50_000);
expect(jest.getTimerCount()).toBe(1); // chain still alive despite the hung probe
await jest.advanceTimersByTimeAsync(45_000); // ~95s total
- expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING); // never falsely promoted
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED); // never falsely promoted; self-healed
expect(jest.getTimerCount()).toBe(0); // gave up at the 90s deadline
- // The at-most-one-in-flight guard must keep the single hung probe from piling up: getState is
- // issued once and not re-issued while it's still pending (a guard-less per-tick probe would be ~45).
- expect(client.getState).toHaveBeenCalledTimes(1);
+ expect(client.getState).toHaveBeenCalledTimes(1); // at-most-one-in-flight guard held
+ // Self-heal: the broken auth is cleared and a disconnect surfaced so the lifecycle re-pairs (QR).
+ expect(rmSpy).toHaveBeenCalledWith(expect.stringContaining('session-sess-1'), { recursive: true, force: true });
+ expect(onDisconnected).toHaveBeenCalled();
+
+ rmSpy.mockRestore();
+ });
+
+ it('fails terminally on a second stuck-auth cycle (no QR -> timeout -> clear loop)', async () => {
+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ const adapter = newAdapter();
+ const onError = jest.fn();
+ (adapter as unknown as { callbacks: { onError?: jest.Mock } }).callbacks = { onError };
+ const recover = (adapter as unknown as { recoverFromStuckAuth: () => Promise<void> }).recoverFromStuckAuth.bind(
+ adapter,
+ );
+
+ await recover(); // first stuck cycle: clears + disconnects
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ await recover(); // second: terminal failure, not another clear
+ expect(adapter.getStatus()).toBe(EngineStatus.FAILED);
+ expect(onError).toHaveBeenCalled();
+ expect(rmSpy).toHaveBeenCalledTimes(1); // auth cleared only once
+ rmSpy.mockRestore();
});
});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 8ef2eb896..9c8b866b4 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -1,7 +1,8 @@
import { EventEmitter } from 'events';
-import { Client, LocalAuth, MessageMedia, MessageTypes, WAState } from 'whatsapp-web.js';
+import { Client, LocalAuth, MessageMedia, MessageTypes, WAState, type Message } from 'whatsapp-web.js';
import * as qrcode from 'qrcode';
import * as path from 'path';
+import * as fs from 'fs';
import {
IWhatsAppEngine,
EngineStatus,
@@ -46,7 +47,13 @@ import {
GroupCreateResult,
} from '../types/whatsapp-web-js.types';
import { buildIncomingMessageBase } from './message-mapper';
-import { capInboundMedia } from './inbound-media-cap';
+import {
+ capInboundMedia,
+ inboundMediaConcurrency,
+ inboundMediaMaxBytes,
+ coerceDeclaredSize,
+} from './inbound-media-cap';
+import { ConcurrencyLimiter } from './concurrency-limiter';
/**
* Map a whatsapp-web.js MessageAck integer to the neutral DeliveryStatus.
@@ -189,6 +196,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
private readyReconcileTimer: ReturnType<typeof setTimeout> | null = null;
private readyReconcileStartedAt = 0;
private readyReconcileProbeInFlight = false;
+ // Guards the stuck-auth self-heal so it runs at most once per engine: a re-paired session that still
+ // can't reach readiness fails terminally instead of looping QR -> timeout -> clear forever.
+ private stuckAuthRecoveryAttempted = false;
// Set once teardown begins so a late 'authenticated' can't resurrect a disconnecting adapter. Not
// reset — an adapter is single-use after teardown (the session creates a fresh one to reconnect).
private tearingDown = false;
@@ -198,6 +208,47 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}
private readonly logger = createLogger('WhatsAppWebJsAdapter');
+ // Bound concurrent inbound media downloads: downloadMedia() materialises the full base64 blob, so an
+ // unbounded burst could stack many multi-MB allocations.
+ private readonly inboundLimiter = new ConcurrencyLimiter(inboundMediaConcurrency());
+
+ /**
+ * Download inbound media safely. downloadMedia() can't be size-bounded at the source, so (1) pre-gate
+ * on the sender-declared size and skip the download entirely when it exceeds the cap, and (2) run the
+ * download through the concurrency limiter for backpressure. Returns undefined when there's no media.
+ */
+ private async capInboundMediaFor(msg: Message): Promise<IncomingMessage['media'] | undefined> {
+ const maxBytes = inboundMediaMaxBytes();
+ const data = (msg as unknown as { _data?: { size?: number; mimetype?: string; filename?: string } })._data;
+ const declared = coerceDeclaredSize(data?.size);
+ if (declared > maxBytes) {
+ this.logger.warn('Inbound media declared size exceeds MEDIA_DOWNLOAD_MAX_BYTES; skipped download', {
+ msgId: msg.id._serialized,
+ sizeBytes: declared,
+ });
+ return {
+ mimetype: data?.mimetype ?? '',
+ filename: data?.filename || undefined,
+ omitted: true,
+ sizeBytes: declared,
+ };
+ }
+ const media = await this.inboundLimiter.run(() => msg.downloadMedia());
+ if (!media) return undefined;
+ const capped = capInboundMedia({
+ mimetype: media.mimetype,
+ filename: media.filename || undefined,
+ sizeBytes: Buffer.byteLength(media.data, 'base64'),
+ toBase64: () => media.data,
+ });
+ if (capped.omitted) {
+ this.logger.warn('Inbound media exceeds MEDIA_DOWNLOAD_MAX_BYTES; dropped payload, kept envelope', {
+ msgId: msg.id._serialized,
+ sizeBytes: capped.sizeBytes,
+ });
+ }
+ return capped;
+ }
async initialize(callbacks: EngineEventCallbacks): Promise<void> {
this.callbacks = callbacks;
@@ -337,22 +388,8 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// Handle media
if (msg.hasMedia) {
try {
- const media = await msg.downloadMedia();
- if (media) {
- // Cap inbound media so an oversized blob isn't persisted/webhooked/broadcast.
- incomingMessage.media = capInboundMedia({
- mimetype: media.mimetype,
- filename: media.filename || undefined,
- sizeBytes: Buffer.byteLength(media.data, 'base64'),
- toBase64: () => media.data,
- });
- if (incomingMessage.media.omitted) {
- this.logger.warn('Inbound media exceeds MEDIA_DOWNLOAD_MAX_BYTES; dropped payload, kept envelope', {
- msgId: msg.id._serialized,
- sizeBytes: incomingMessage.media.sizeBytes,
- });
- }
- }
+ const capped = await this.capInboundMediaFor(msg);
+ if (capped) incomingMessage.media = capped;
} catch (error) {
this.logger.error('Error downloading media', String(error));
}
@@ -478,8 +515,16 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// Deadline checked at the TOP of every tick (not after the probe) so a slow/hung getState() — a
// wedged page can make it never resolve, the very #251/#273 condition — can't defeat the 90s ceiling.
if (Date.now() - this.readyReconcileStartedAt >= READY_RECONCILE_TIMEOUT_MS) {
- this.logger.warn('Timed out waiting for WhatsApp Web runtime readiness after authentication');
+ this.logger.warn(
+ 'Timed out waiting for WhatsApp Web runtime readiness after authentication — the saved session ' +
+ 'is stuck after the QR scan (usually the auto-selected WhatsApp Web build is incompatible). ' +
+ 'Clearing it to re-pair; pin a known-good version via WWEBJS_WEB_VERSION (see ' +
+ 'docs/12-troubleshooting-faq.md) if it keeps recurring.',
+ );
this.clearReadyReconcile();
+ // Self-heal: don't leave the session stuck at "authenticating" forever — clear the broken auth
+ // and disconnect so the lifecycle re-pairs (a fresh QR) instead of hanging.
+ void this.recoverFromStuckAuth();
return;
}
@@ -517,6 +562,42 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.readyReconcileProbeInFlight = false;
}
+ /**
+ * Recover a session that authenticated but never reached runtime readiness (stale/incompatible auth
+ * or a wedged page). Clear the broken LocalAuth and disconnect so the session lifecycle re-pairs (a
+ * fresh QR) instead of hanging at "authenticating". Runs at most once per engine — a re-paired session
+ * that still can't reach readiness fails terminally rather than looping.
+ */
+ private async recoverFromStuckAuth(): Promise<void> {
+ if (this.stuckAuthRecoveryAttempted) {
+ this.setStatus(EngineStatus.FAILED);
+ this.callbacks.onError?.(
+ 'WhatsApp Web could not reach readiness after re-pairing. Pin WWEBJS_WEB_VERSION to a known-good build and try again.',
+ );
+ return;
+ }
+ this.stuckAuthRecoveryAttempted = true;
+
+ const client = this.client;
+ this.client = null;
+ // Clear auth + disconnect FIRST (the recovery path), then tear the wedged client down in the
+ // background so a hung Chromium destroy can't block (or skip) the recovery.
+ await this.clearLocalAuth();
+ this.setStatus(EngineStatus.DISCONNECTED);
+ // onDisconnected drives the lifecycle's reconnect, which re-creates the engine with no saved auth
+ // → a fresh QR. (A no-op once the engine is superseded/torn down.)
+ this.callbacks.onDisconnected?.('Saved session could not be restored; cleared for re-pairing');
+ if (typeof client?.destroy === 'function') void client.destroy().catch(() => undefined);
+ }
+
+ /** Remove this session's LocalAuth directory so the next start re-pairs from a clean slate. */
+ private async clearLocalAuth(): Promise<void> {
+ const dir = path.join(path.resolve(this.config.sessionDataPath), `session-${this.config.sessionId}`);
+ await fs.promises.rm(dir, { recursive: true, force: true }).catch((error: unknown) => {
+ this.logger.warn(`Could not clear stale auth at ${dir}`, String(error));
+ });
+ }
+
private async isClientRuntimeReady(): Promise<boolean> {
if (!this.client) return false;
if ((await this.client.getState()) !== WAState.CONNECTED) return false;
@@ -1231,16 +1312,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
out.isStatusBroadcast = chatId === 'status@broadcast';
if (includeMedia && msg.hasMedia) {
try {
- const media = await msg.downloadMedia();
- if (media) {
- // Cap history media too: a large historical blob shouldn't bloat the response/heap.
- out.media = capInboundMedia({
- mimetype: media.mimetype,
- filename: media.filename || undefined,
- sizeBytes: Buffer.byteLength(media.data, 'base64'),
- toBase64: () => media.data,
- });
- }
+ // Same pre-gate + limiter as live media: a large historical blob shouldn't bloat the response/heap.
+ const capped = await this.capInboundMediaFor(msg);
+ if (capped) out.media = capped;
} catch (error) {
this.logger.warn(`Failed to download media for ${msg.id._serialized}: ${String(error)}`);
}
diff --git a/src/modules/plugins/plugin-download.ts b/src/modules/plugins/plugin-download.ts
index a3abdf65d..152a14d06 100644
--- a/src/modules/plugins/plugin-download.ts
+++ b/src/modules/plugins/plugin-download.ts
@@ -7,12 +7,14 @@ const DEFAULT_TIMEOUT_MS = 30_000;
/**
* Fetch a remote resource (plugin .zip or catalog JSON) as a Buffer, always behind the SSRF guard:
- * the host is validated before any socket opens, the connection is pinned to the vetted IP, and
- * redirects are refused. The byte cap is enforced while streaming (Content-Length may be absent or
- * wrong) so a hostile or oversized response can't exhaust memory.
+ * every host (the original URL and every redirect hop) is validated before its socket opens and a hop
+ * resolving to an internal/reserved address is refused. Redirects ARE followed — public release hosts
+ * (e.g. GitHub Releases) legitimately 302 to a CDN — but each hop is re-validated, so following them
+ * cannot reach an internal target. The byte cap is enforced while streaming (Content-Length may be
+ * absent or wrong) so a hostile or oversized response can't exhaust memory.
*
* Operators must add a non-public catalog/release host to `SSRF_ALLOWED_HOSTS`; public hosts
- * (github.com, raw.githubusercontent.com) resolve and pass the guard normally.
+ * (github.com, objects.githubusercontent.com, raw.githubusercontent.com) resolve and pass normally.
*/
export async function fetchSafeBuffer(
url: string,
@@ -24,34 +26,39 @@ export async function fetchSafeBuffer(
Number.isFinite(opts.maxBytes) && (opts.maxBytes as number) > 0 ? (opts.maxBytes as number) : DEFAULT_MAX_BYTES;
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
- return withSafeFetch(url, { signal: AbortSignal.timeout(timeoutMs) }, async response => {
- if (!response.ok) {
- throw new Error(`download failed with status ${response.status}`);
- }
+ return withSafeFetch(
+ url,
+ { signal: AbortSignal.timeout(timeoutMs) },
+ async response => {
+ if (!response.ok) {
+ throw new Error(`download failed with status ${response.status}`);
+ }
- const declaredLength = Number(response.headers.get('content-length') ?? '');
- if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
- throw new Error(`download exceeds the ${maxBytes}-byte limit`);
- }
+ const declaredLength = Number(response.headers.get('content-length') ?? '');
+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
+ throw new Error(`download exceeds the ${maxBytes}-byte limit`);
+ }
- const reader = response.body?.getReader();
- if (!reader) {
- throw new Error('download response has no body');
- }
+ const reader = response.body?.getReader();
+ if (!reader) {
+ throw new Error('download response has no body');
+ }
- const chunks: Buffer[] = [];
- let total = 0;
- for (;;) {
- const { done, value } = (await reader.read()) as { done: boolean; value: Uint8Array };
- if (done) break;
- total += value.byteLength;
- if (total > maxBytes) {
- await reader.cancel();
- throw new Error(`download exceeds the ${maxBytes}-byte limit`);
+ const chunks: Buffer[] = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = (await reader.read()) as { done: boolean; value: Uint8Array };
+ if (done) break;
+ total += value.byteLength;
+ if (total > maxBytes) {
+ await reader.cancel();
+ throw new Error(`download exceeds the ${maxBytes}-byte limit`);
+ }
+ chunks.push(Buffer.from(value));
}
- chunks.push(Buffer.from(value));
- }
- return Buffer.concat(chunks);
- });
+ return Buffer.concat(chunks);
+ },
+ { followRedirects: true },
+ );
}
diff --git a/src/modules/plugins/plugin-installer.spec.ts b/src/modules/plugins/plugin-installer.spec.ts
index f832e628a..f63bbb02e 100644
--- a/src/modules/plugins/plugin-installer.spec.ts
+++ b/src/modules/plugins/plugin-installer.spec.ts
@@ -43,6 +43,25 @@ describe('parsePluginPackage', () => {
);
});
+ it('rejects a non-string required field (numeric main) with a clean 400, not a TypeError/500', () => {
+ // A non-string `main` is truthy, so a bare falsy check would pass it through and then crash
+ // path.posix.normalize with an uncaught TypeError (HTTP 500). It must be rejected as a 400.
+ const bad = { ...validManifest, main: 123 };
+ expect(() => parsePluginPackage(zipOf({ 'manifest.json': JSON.stringify(bad), 'index.js': 'x' }))).toThrow(
+ /invalid required field/i,
+ );
+ });
+
+ it('rejects a non-object manifest (null / array / scalar) with a 400, not a TypeError/500', () => {
+ // JSON.parse("null") is null (no throw); accessing manifest['id'] on it then throws an uncaught
+ // TypeError (HTTP 500). null, an array, and a bare scalar must all be rejected as a clean 400.
+ for (const body of ['null', '[]', '"x"', '5', 'true']) {
+ expect(() => parsePluginPackage(zipOf({ 'manifest.json': body, 'index.js': 'x' }))).toThrow(
+ /must be a JSON object/i,
+ );
+ }
+ });
+
it('rejects an unsafe plugin id', () => {
const bad = { ...validManifest, id: '../evil' };
expect(() => parsePluginPackage(zipOf({ 'manifest.json': JSON.stringify(bad), 'index.js': 'x' }))).toThrow(
@@ -57,6 +76,15 @@ describe('parsePluginPackage', () => {
);
});
+ it('rejects a case-variant of a reserved id (the id check is case-insensitive)', () => {
+ // SAFE_ID accepts mixed case, so a case-variant must still hit the reservation — else `Auto-Reply`
+ // installs as a distinct plugin that shadows the reserved `auto-reply`.
+ const bad = { ...validManifest, id: 'Auto-Reply' };
+ expect(() => parsePluginPackage(zipOf({ 'manifest.json': JSON.stringify(bad), 'index.js': 'x' }))).toThrow(
+ /reserved/i,
+ );
+ });
+
it('rejects an engine-type package (engines are built-in, not user-installable)', () => {
const bad = { ...validManifest, id: 'my-engine', type: 'engine' };
expect(() => parsePluginPackage(zipOf({ 'manifest.json': JSON.stringify(bad), 'index.js': 'x' }))).toThrow(
diff --git a/src/modules/plugins/plugin-installer.ts b/src/modules/plugins/plugin-installer.ts
index 84b30f388..5c3f1bf19 100644
--- a/src/modules/plugins/plugin-installer.ts
+++ b/src/modules/plugins/plugin-installer.ts
@@ -57,19 +57,30 @@ export function parsePluginPackage(buffer: Buffer, limits: PackageLimits = DEFAU
const dir = path.posix.dirname(manifestEntry.entryName);
const prefix = dir === '.' ? '' : dir + '/';
- let manifest: PluginManifest;
+ let parsed: unknown;
try {
- manifest = JSON.parse(manifestEntry.getData().toString('utf-8')) as PluginManifest;
+ parsed = JSON.parse(manifestEntry.getData().toString('utf-8'));
} catch {
throw new BadRequestException('manifest.json is not valid JSON');
}
+ // JSON.parse("null") / "[]" / "5" don't throw — but indexing a field on a non-object then throws an
+ // uncaught TypeError (HTTP 500) on the attacker-controlled install path. Require a plain object.
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ throw new BadRequestException('manifest.json must be a JSON object');
+ }
+ const manifest = parsed as PluginManifest;
for (const field of REQUIRED_FIELDS) {
- if (!manifest[field]) throw new BadRequestException(`manifest.json is missing required field: ${field}`);
+ // Require a non-empty STRING: a non-string value (e.g. `main: 123`) is truthy and would pass a
+ // bare falsy check, then crash a string-only API like path.posix.normalize with an uncaught
+ // TypeError (HTTP 500). Reject it cleanly as a 400 here.
+ if (typeof manifest[field] !== 'string' || manifest[field].length === 0) {
+ throw new BadRequestException(`manifest.json is missing or has an invalid required field: ${field}`);
+ }
}
if (!SAFE_ID.test(manifest.id) || manifest.id.includes('..')) {
throw new BadRequestException(`Invalid plugin id: "${manifest.id}"`);
}
- if (RESERVED_PLUGIN_IDS.has(manifest.id)) {
+ if (RESERVED_PLUGIN_IDS.has(manifest.id.toLowerCase())) {
throw new BadRequestException(`Plugin id "${manifest.id}" is reserved by a built-in plugin`);
}
if (!INSTALLABLE_TYPES.has(manifest.type)) {
diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.ts
index d0647ba5f..b934acab9 100644
--- a/src/modules/plugins/plugins.controller.ts
+++ b/src/modules/plugins/plugins.controller.ts
@@ -17,8 +17,8 @@ import { ApiTags, ApiOperation, ApiResponse, ApiConsumes } from '@nestjs/swagger
import { PluginsService } from './plugins.service';
import { PluginDto, PluginConfigDto, PluginSessionsDto, InstallFromUrlDto } from './dto/plugin.dto';
import type { CatalogPlugin } from './catalog';
-import { RequireRole } from '../auth/decorators/auth.decorators';
-import { ApiKeyRole } from '../auth/entities/api-key.entity';
+import { RequireRole, CurrentApiKey } from '../auth/decorators/auth.decorators';
+import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';
/** Max accepted upload size for a plugin package (compressed). */
const MAX_PLUGIN_UPLOAD_BYTES = 5 * 1024 * 1024;
@@ -138,8 +138,10 @@ export class PluginsController {
@ApiResponse({ status: 200, description: 'Plugin session activation updated', type: PluginDto })
@ApiResponse({ status: 400, description: 'Plugin is global (not session-scoped)' })
@ApiResponse({ status: 404, description: 'Plugin not found' })
- updateSessions(@Param('id') id: string, @Body() dto: PluginSessionsDto): PluginDto {
- return this.pluginsService.updateSessions(id, dto.sessions);
+ updateSessions(@Param('id') id: string, @Body() dto: PluginSessionsDto, @CurrentApiKey() apiKey?: ApiKey): PluginDto {
+ // The target sessions live in the body, which the ApiKeyGuard (keyed off route params) never
+ // inspects — so a session-restricted key's allowedSessions scope must be enforced here.
+ return this.pluginsService.updateSessions(id, dto.sessions, apiKey?.allowedSessions);
}
@Post(':id/update')
diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.ts
index fcda973c5..b2529fbd0 100644
--- a/src/modules/plugins/plugins.service.spec.ts
+++ b/src/modules/plugins/plugins.service.spec.ts
@@ -262,6 +262,22 @@ describe('PluginsService — per-session config', () => {
expect(plugin?.sessionConfig?.['sess-A']).toEqual({ apiKey: 'A-secret', lang: 'he' });
});
+ // A session-restricted API key must not activate the plugin for sessions outside its allowedSessions
+ // scope (the target sessions are in the request body the guard never inspects).
+ it('rejects activating for a session outside a restricted key scope', () => {
+ expect(() => service.updateSessions('sess-cfg', ['sess-B'], ['sess-A'])).toThrow(/not authorized/i);
+ expect(() => service.updateSessions('sess-cfg', ['*'], ['sess-A'])).toThrow(/not authorized/i);
+ });
+
+ it('allows a restricted key to activate only within its scope', () => {
+ expect(service.updateSessions('sess-cfg', ['sess-A'], ['sess-A']).activeSessions).toEqual(['sess-A']);
+ });
+
+ it('lets an unrestricted key activate for all sessions', () => {
+ expect(service.updateSessions('sess-cfg', ['*'], undefined).activeSessions).toEqual(['*']);
+ expect(service.updateSessions('sess-cfg', ['*'], []).activeSessions).toEqual(['*']);
+ });
+
it('clears the override when an empty slice is written', () => {
service.updateSessionConfig('sess-cfg', 'sess-A', { lang: 'he' });
service.updateSessionConfig('sess-cfg', 'sess-A', {});
diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.ts
index c879c0907..cc3382384 100644
--- a/src/modules/plugins/plugins.service.ts
+++ b/src/modules/plugins/plugins.service.ts
@@ -1,4 +1,11 @@
-import { Injectable, NotFoundException, BadRequestException, ConflictException, HttpException } from '@nestjs/common';
+import {
+ Injectable,
+ NotFoundException,
+ BadRequestException,
+ ConflictException,
+ ForbiddenException,
+ HttpException,
+} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';
@@ -120,11 +127,20 @@ export class PluginsService {
}
}
- updateSessions(id: string, sessions: string[]): PluginDto {
+ updateSessions(id: string, sessions: string[], allowedSessions?: string[] | null): PluginDto {
const plugin = this.pluginLoader.getPlugin(id);
if (!plugin) {
throw new NotFoundException(`Plugin ${id} not found`);
}
+ // A session-restricted key (non-empty allowedSessions) may only activate the plugin for sessions
+ // in its own scope — never '*' (all) or another tenant's session. An unrestricted key (null/empty)
+ // is the normal dashboard/admin path and may activate for any session, including '*'.
+ if (allowedSessions && allowedSessions.length > 0) {
+ const outOfScope = sessions.filter(s => s === '*' || !allowedSessions.includes(s));
+ if (outOfScope.length > 0) {
+ throw new ForbiddenException(`API key not authorized for session(s): ${outOfScope.join(', ')}`);
+ }
+ }
try {
this.pluginLoader.setPluginSessions(id, sessions);
} catch (error) {
diff --git a/src/modules/plugins/redact-config.spec.ts b/src/modules/plugins/redact-config.spec.ts
index ee4d1b81d..c31871cfc 100644
--- a/src/modules/plugins/redact-config.spec.ts
+++ b/src/modules/plugins/redact-config.spec.ts
@@ -206,4 +206,129 @@ describe('restoreSecretConfig (nested)', () => {
endpoints: [{ url: 'NEW' }, { url: 'a', token: 'real1' }],
});
});
+
+ // A row's signature is the row with its secret masked, so editing a NON-secret field changes the
+ // signature and the content-match misses. On an in-place edit (array length unchanged) the row at
+ // the same index is the same logical row, so its stored secret must be preserved — losing it on a
+ // routine rename is silent data loss.
+ it('keeps a row secret when only its non-secret field changed (same length)', () => {
+ expect(
+ restoreSecretConfig(
+ { endpoints: [{ url: 'a-renamed', token: SECRET_SENTINEL }] },
+ { endpoints: [{ url: 'a', token: 'real' }] },
+ nestedSchema,
+ ),
+ ).toEqual({ endpoints: [{ url: 'a-renamed', token: 'real' }] });
+ });
+
+ // Two rows with identical non-secret content collide on signature; on an unchanged round-trip both
+ // secrets must survive (positional fallback), not be dropped to nothing.
+ it('restores both secrets when two rows share non-secret content (no-op round-trip)', () => {
+ expect(
+ restoreSecretConfig(
+ {
+ endpoints: [
+ { url: 'a', token: SECRET_SENTINEL },
+ { url: 'a', token: SECRET_SENTINEL },
+ ],
+ },
+ {
+ endpoints: [
+ { url: 'a', token: 'real1' },
+ { url: 'a', token: 'real2' },
+ ],
+ },
+ nestedSchema,
+ ),
+ ).toEqual({
+ endpoints: [
+ { url: 'a', token: 'real1' },
+ { url: 'a', token: 'real2' },
+ ],
+ });
+ });
+});
+
+// An array whose ITEMS are scalar secrets (e.g. a list of API keys) — every masked element shares the
+// signature "***", so content-matching is impossible and restore must align by position. A no-op
+// round-trip or an in-place edit must never wipe the stored secrets to null.
+const scalarSecretArraySchema: PluginConfigSchema = {
+ type: 'object',
+ properties: {
+ keys: { type: 'array', items: { type: 'string', secret: true } },
+ },
+};
+
+describe('restoreSecretConfig (scalar-secret array)', () => {
+ it('restores every secret on an unchanged round-trip (no null pollution)', () => {
+ expect(
+ restoreSecretConfig(
+ { keys: [SECRET_SENTINEL, SECRET_SENTINEL] },
+ { keys: ['k1', 'k2'] },
+ scalarSecretArraySchema,
+ ),
+ ).toEqual({ keys: ['k1', 'k2'] });
+ });
+
+ it('keeps a genuinely-new secret element while restoring the unchanged ones', () => {
+ expect(
+ restoreSecretConfig({ keys: [SECRET_SENTINEL, 'brand-new'] }, { keys: ['k1', 'k2'] }, scalarSecretArraySchema),
+ ).toEqual({ keys: ['k1', 'brand-new'] });
+ });
+
+ it('drops a sentinel element that has nothing stored to keep (no null in the array)', () => {
+ expect(restoreSecretConfig({ keys: [SECRET_SENTINEL] }, { keys: [] }, scalarSecretArraySchema)).toEqual({
+ keys: [],
+ });
+ });
+});
+
+// A composite field (object/array) that is itself marked secret:true must be masked as ONE unit on
+// read and restored as a unit on write — recursing would leak its non-secret children in plaintext.
+const compositeSecretSchema: PluginConfigSchema = {
+ type: 'object',
+ properties: {
+ creds: { type: 'object', secret: true, properties: { user: { type: 'string' }, pass: { type: 'string' } } },
+ keys: { type: 'array', secret: true, items: { type: 'string' } },
+ },
+};
+
+describe('redactSecretConfig (composite secret field)', () => {
+ it('masks a whole secret object so its children never leak', () => {
+ expect(redactSecretConfig({ creds: { user: 'u', pass: 'p' } }, compositeSecretSchema)).toEqual({
+ creds: SECRET_SENTINEL,
+ });
+ });
+
+ it('masks a whole secret array so its entries never leak', () => {
+ expect(redactSecretConfig({ keys: ['k1', 'k2'] }, compositeSecretSchema)).toEqual({ keys: SECRET_SENTINEL });
+ });
+});
+
+describe('restoreSecretConfig (composite secret field)', () => {
+ it('restores a secret object from the sentinel instead of clobbering it', () => {
+ expect(
+ restoreSecretConfig({ creds: SECRET_SENTINEL }, { creds: { user: 'u', pass: 'p' } }, compositeSecretSchema),
+ ).toEqual({ creds: { user: 'u', pass: 'p' } });
+ });
+
+ it('restores a secret array from the sentinel', () => {
+ expect(restoreSecretConfig({ keys: SECRET_SENTINEL }, { keys: ['k1', 'k2'] }, compositeSecretSchema)).toEqual({
+ keys: ['k1', 'k2'],
+ });
+ });
+
+ it('stores a genuinely-new secret object as a unit', () => {
+ expect(
+ restoreSecretConfig(
+ { creds: { user: 'x', pass: 'y' } },
+ { creds: { user: 'u', pass: 'p' } },
+ compositeSecretSchema,
+ ),
+ ).toEqual({ creds: { user: 'x', pass: 'y' } });
+ });
+
+ it('drops a sentinel secret object when there is nothing stored', () => {
+ expect(restoreSecretConfig({ creds: SECRET_SENTINEL }, {}, compositeSecretSchema)).not.toHaveProperty('creds');
+ });
});
diff --git a/src/modules/plugins/redact-config.ts b/src/modules/plugins/redact-config.ts
index c218062cb..4ffe3da46 100644
--- a/src/modules/plugins/redact-config.ts
+++ b/src/modules/plugins/redact-config.ts
@@ -14,13 +14,16 @@ const isPlainObject = (v: unknown): v is Record<string, unknown> =>
* as-is so the mask never implies a secret that isn't set.
*/
function redactValue(value: unknown, field: PluginConfigField): unknown {
+ // Mask a `secret` field BEFORE descending into its structure: a whole object/array marked secret
+ // (e.g. a credentials object or a list of keys) must be masked as one unit, not recursed into —
+ // otherwise its non-secret children leak verbatim. Scalar secrets are masked here too.
+ if (field.secret && isMeaningful(value)) return SECRET_SENTINEL;
if (field.type === 'object' && field.properties && isPlainObject(value)) {
return redactObject(value, field.properties);
}
if (field.type === 'array' && field.items && Array.isArray(value)) {
return value.map(item => redactValue(item, field.items as PluginConfigField));
}
- if (field.secret && isMeaningful(value)) return SECRET_SENTINEL;
return value;
}
@@ -81,6 +84,16 @@ function restoreValue(
existing: unknown,
field: PluginConfigField,
): { keep: boolean; value?: unknown } {
+ // Mirror redactValue: a `secret` field is handled as ONE unit before any structural recursion. A
+ // sentinel/empty incoming keeps the stored value (or drops it); a genuinely-new value is stored
+ // as-is. Without this, a composite secret (object/array) would recurse and its masked children
+ // would clobber the stored secret instead of restoring it.
+ if (field.secret) {
+ if (incoming === SECRET_SENTINEL || !isMeaningful(incoming)) {
+ return isMeaningful(existing) ? { keep: true, value: existing } : { keep: false };
+ }
+ return { keep: true, value: incoming };
+ }
if (field.type === 'object' && field.properties && isPlainObject(incoming)) {
return {
keep: true,
@@ -89,7 +102,7 @@ function restoreValue(
}
if (field.type === 'array' && field.items && Array.isArray(incoming)) {
const itemField = field.items;
- const existingArr = Array.isArray(existing) ? existing : [];
+ const existingArr: unknown[] = Array.isArray(existing) ? existing : [];
// Match each incoming element to its stored counterpart by NON-SECRET content (a row's signature
// is the row with its secrets masked), not by array index. Adding / removing / reordering rows
// then can't bind a sentinel to a different row's secret. Only an unambiguous match (exactly one
@@ -102,19 +115,27 @@ function restoreValue(
sigCount.set(s, (sigCount.get(s) ?? 0) + 1);
if (!sigFirst.has(s)) sigFirst.set(s, ex);
}
+ const sameLength = incoming.length === existingArr.length;
return {
keep: true,
- value: incoming.map(item => {
- const s = elementSignature(item, itemField);
- const match = sigCount.get(s) === 1 ? sigFirst.get(s) : undefined;
- return restoreValue(item, match, itemField).value;
- }),
+ value: incoming
+ .map((item, i) => {
+ const s = elementSignature(item, itemField);
+ // Prefer an unambiguous content match — a row keeps its secret across reorder / insert /
+ // removal. When the signature can't disambiguate (scalar-secret elements all mask to the
+ // sentinel; duplicate rows; or a row whose NON-secret field was edited), fall back to the
+ // same index, but only when the array length is unchanged: a same-length round-trip is an
+ // in-place edit (position i is the same logical row), whereas a length change is a true
+ // insert/removal where positional binding could graft a stored secret onto a new row.
+ const match = sigCount.get(s) === 1 ? sigFirst.get(s) : sameLength ? existingArr[i] : undefined;
+ return restoreValue(item, match, itemField);
+ })
+ // Honor keep:false like restoreObject does (drop the element) rather than emitting `.value`
+ // (undefined), which would serialize to a null hole in the persisted array.
+ .filter(r => r.keep)
+ .map(r => r.value),
};
}
- if (field.secret && (incoming === SECRET_SENTINEL || !isMeaningful(incoming))) {
- if (isMeaningful(existing)) return { keep: true, value: existing };
- return { keep: false };
- }
return { keep: true, value: incoming };
}
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 04a29fa3b..7372bfa88 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -299,7 +299,7 @@ export class SessionController {
status: 200,
description: 'Session statistics including counts and memory usage',
})
- async getStats(): Promise<{
+ async getStats(@CurrentApiKey() apiKey?: ApiKey): Promise<{
total: number;
active: number;
ready: number;
@@ -307,6 +307,8 @@ export class SessionController {
byStatus: Record<string, number>;
memoryUsage: { heapUsed: number; heapTotal: number; rss: number };
}> {
- return this.sessionService.getStats();
+ // Scope aggregate stats to the key's allowedSessions so a session-restricted key cannot enumerate
+ // global session counts/status (the route carries no :id for the guard to scope against).
+ return this.sessionService.getStats(apiKey?.allowedSessions);
}
}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index a68f743b7..1dad8d20e 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1231,6 +1231,22 @@ describe('SessionService', () => {
expect(stats.byStatus[SessionStatus.READY]).toBe(2);
expect(stats.memoryUsage).toBeDefined();
});
+
+ it('scopes the stats to a restricted key (active counts only in-scope engines)', async () => {
+ const findSpy = (repository.find as jest.Mock).mockResolvedValue([
+ createMockSession({ id: 'sess-A', status: SessionStatus.READY }),
+ ]);
+ const engines = (service as unknown as { engines: Map<string, unknown> }).engines;
+ engines.set('sess-A', {});
+ engines.set('sess-B', {}); // global engine the scoped key must NOT see counted
+
+ const stats = await service.getStats(['sess-A']);
+
+ expect(findSpy).toHaveBeenCalled(); // scope threaded into findAll
+ expect(stats.total).toBe(1);
+ expect(stats.active).toBe(1); // not 2 (global engines.size)
+ engines.clear();
+ });
});
// ── getChats ──────────────────────────────────────────────────────
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 1949277ac..77875c117 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -1181,7 +1181,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
/**
* Get overall session statistics for multi-session monitoring
*/
- async getStats(): Promise<{
+ async getStats(allowedSessions?: string[] | null): Promise<{
total: number;
active: number;
ready: number;
@@ -1189,7 +1189,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
byStatus: Record<string, number>;
memoryUsage: { heapUsed: number; heapTotal: number; rss: number };
}> {
- const sessions = await this.findAll();
+ // Scope to the caller's allowedSessions so a session-restricted key cannot enumerate the count /
+ // status distribution of sessions it has no rights to (matches the scoped GET /sessions route).
+ const scope = allowedSessions && allowedSessions.length > 0 ? allowedSessions : null;
+ const sessions = await this.findAll(scope);
const byStatus: Record<string, number> = {};
for (const session of sessions) {
@@ -1200,7 +1203,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return {
total: sessions.length,
- active: this.engines.size,
+ // engines is keyed by session id; a scoped key sees only its own running engines, not the global count.
+ active: scope ? [...this.engines.keys()].filter(id => scope.includes(id)).length : this.engines.size,
ready: byStatus[SessionStatus.READY] || 0,
disconnected: byStatus[SessionStatus.DISCONNECTED] || 0,
byStatus,
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
index 800f72217..071342be8 100644
--- a/src/modules/webhook/webhook.service.spec.ts
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -379,6 +379,23 @@ describe('WebhookService', () => {
});
});
+ describe('dispatch (queued mode) — serialization safety', () => {
+ it('catches an unserializable webhook:before payload instead of aborting the loop / rejecting', async () => {
+ (service as unknown as { queueEnabled: boolean }).queueEnabled = true;
+ // A plugin's webhook:before returns a payload JSON.stringify cannot serialize (BigInt). With the
+ // secret set, the queued branch signs JSON.stringify(finalPayload) — which throws.
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: { payload: { x: 1n } } });
+ const webhook = createMockWebhook({ secret: 'sek', events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+
+ // Must NOT reject (the loop/dispatch promise stays settled); the throw is caught + logged.
+ await expect(service.dispatch('sess-1', 'message.received', { ok: true })).resolves.toBeUndefined();
+
+ expect(webhookQueue.add).not.toHaveBeenCalled(); // never enqueued the un-signable job
+ expect(hookManager.execute).toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());
+ });
+ });
+
// ── dispatch (smart filters) ──────────────────────────────────────
// The event still has to match `events[]`; filters then refine WHETHER it fires based
// on the payload. A webhook with no filters behaves exactly as before (fires on match).
diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.ts
index 2bd8ca740..46c1c5b69 100644
--- a/src/modules/webhook/webhook.service.ts
+++ b/src/modules/webhook/webhook.service.ts
@@ -271,24 +271,28 @@ export class WebhookService {
// Use queue if available, otherwise fallback to direct delivery
if (this.queueEnabled && this.webhookQueue) {
- const signature = webhook.secret ? this.generateSignature(JSON.stringify(finalPayload), webhook.secret) : '';
+ try {
+ // finalPayload comes from the (untrusted) webhook:before hook result, so JSON.stringify can
+ // throw (BigInt / circular). Keep serialization + signing INSIDE the try so a poisoned payload
+ // is caught here (one webhook dropped + logged) instead of aborting the whole dispatch loop
+ // and rejecting the fire-and-forget dispatch() promise.
+ const signature = webhook.secret ? this.generateSignature(JSON.stringify(finalPayload), webhook.secret) : '';
- if (webhook.secret) {
- headers['X-OpenWA-Signature'] = signature;
- }
+ if (webhook.secret) {
+ headers['X-OpenWA-Signature'] = signature;
+ }
- const jobData: WebhookJobData = {
- webhookId: webhook.id,
- url: webhook.url,
- event,
- payload: finalPayload,
- signature,
- headers,
- attempt: 1,
- maxRetries: webhook.retryCount,
- };
+ const jobData: WebhookJobData = {
+ webhookId: webhook.id,
+ url: webhook.url,
+ event,
+ payload: finalPayload,
+ signature,
+ headers,
+ attempt: 1,
+ maxRetries: webhook.retryCount,
+ };
- try {
await this.webhookQueue.add(`webhook-${webhook.id}`, jobData, {
attempts: webhook.retryCount,
backoff: {