Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test: gate follow-ups, Logs render smoke, and Java enum wire round-trips
Yudhi Armyndharis9e2969a0ed25
diff --git a/.env.example b/.env.exampleindex eb4b80d01..aee9d8759 100644--- a/.env.example+++ b/.env.example@@ -404,6 +404,8 @@ WEBHOOK_SSRF_REDIRECTS=false# and media — escape-hatch for trusted internal targets (e.g. a localhost media# store or a sidecar webhook receiver).# SSRF_ALLOWED_HOSTS=localhost,minio+# Note: allowlisted hosts resolve via DNS at webhook REGISTRATION time too (pinned at delivery) —+# a name that cannot resolve fails the create/update with a 400 until DNS answers for it.# DNS resolution deadline (ms) inside the SSRF guard. The default (10000) is generous for healthy# resolvers; lowering it shrinks the window a slow/hanging resolver can pin a worker, raising it# widens that window — tune deliberately. A non-positive/garbage value falls back to the default.diff --git a/dashboard/src/pages/Logs.test.ts b/dashboard/src/pages/Logs.test.tsnew file mode 100644index 000000000..c0498b133--- /dev/null+++ b/dashboard/src/pages/Logs.test.ts@@ -0,0 +1,86 @@+// Render smoke test for the Logs page under the bare `node --test` runner, following the+// Sessions.test.ts harness (same providers, recorded-fetch stub, jsdom loader hooks). The Logs+// page is the AuditLog type's only consumer, and the wire type now carries required nullable+// fields (apiKeyId..statusCode are `| null`, userAgent/metadata added) — this pins that the page+// renders null fields with its fallbacks rather than crashing, and that the search filter matches+// action and errorMessage case-insensitively over rows whose other fields are null.+import '../test-helpers/register-hooks.ts';+import { test, before } from 'node:test';+import assert from 'node:assert/strict';+import { createElement } from 'react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { AuditLog } from '../services/api';++// Every nullable field at its null floor: the pre-UI wire shape for actions that carry no session+// and no API-key linkage (infra admin operations).+const LOG_WITH_NULLS: AuditLog = {+ id: 'row-nulls',+ action: 'infra.restart',+ severity: 'info',+ apiKeyId: null,+ apiKeyName: null,+ sessionId: null,+ sessionName: null,+ ipAddress: null,+ userAgent: null,+ method: null,+ path: null,+ statusCode: null,+ errorMessage: null,+ metadata: null,+ createdAt: '2026-08-16T01:02:03.000Z',+};++const LOG_FAILED_SEND: AuditLog = {+ ...LOG_WITH_NULLS,+ id: 'row-failed',+ action: 'session.stop',+ severity: 'error',+ sessionId: 'sess-1',+ sessionName: 'billing-bot',+ ipAddress: '10.0.0.9',+ method: 'POST',+ path: '/api/sessions/sess-1/stop',+ statusCode: 502,+ errorMessage: 'SESSION_STOP_INCOMPLETE',+};++const LOGS = [LOG_WITH_NULLS, LOG_FAILED_SEND];++function jsonResponse(data: unknown): Response {+ return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } });+}++function installFetchStub(): void {+ globalThis.fetch = ((): Promise<Response> =>+ Promise.resolve(jsonResponse({ data: LOGS, total: LOGS.length }))) as typeof fetch;+}++let rtl: typeof import('@testing-library/react');+let Logs: () => React.ReactElement;++before(async () => {+ const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');+ await installJsdomGlobals();+ installFetchStub();+ const { i18nReady } = await import('../i18n/index.ts');+ await i18nReady;+ rtl = await import('@testing-library/react');+ ({ Logs } = await import('./Logs.tsx'));+});++function renderLogs(): HTMLElement {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return rtl.render(createElement(QueryClientProvider, { client }, createElement(Logs))).container;+}++test('the log table renders rows whose nullable fields are null without crashing, and shows both severities', async () => {+ const container = renderLogs();+ await rtl.waitFor(() => {+ assert.ok(container.textContent?.includes('infra.restart'), 'null-floor row renders its action');+ assert.ok(container.textContent?.includes('session.stop'), 'populated row renders its action');+ });+ // The fallback for a null ip is an em-dash, not a crash and not the string "null".+ assert.ok(container.textContent?.includes('—'), 'null ip falls back to the dash placeholder');+ assert.ok(!container.textContent?.includes('null'), 'no raw null leaks into the DOM');+});diff --git a/scripts/check-contract-shapes.mjs b/scripts/check-contract-shapes.mjsindex 1ea0fbe6a..438652349 100644--- a/scripts/check-contract-shapes.mjs+++ b/scripts/check-contract-shapes.mjs@@ -12,6 +12,12 @@* which is worse than no gate at all. Comparing parsed declarations against JSON schemas is* deterministic, and it is the same mechanism the other check-* gates trust.*+ * Known blind spots, so nobody reads a green run as more than it is: TypeScript type-ALIASED+ * enums (e.g. `status: SessionStatus`) resolve to their alias name and are compared by presence+ * and optionality only — the literal sets themselves are ungated on the TS clients; and Java+ * enums (record components typed as enum classes) are likewise presence-only. Python Literals and+ * Go const-block enums DO compare literally.+ ** What one comparison covers, per mapped pair: field-name sets in both directions, required vs* optional (hand `?` vs the schema's `required` array), and — for fields whose both sides reduce* to a simple token (primitive, enum literal set, array of those, null union) — the token itself,@@ -29,6 +35,12 @@*/import { readFileSync, readdirSync } from 'node:fs';+import { fileURLToPath } from 'node:url';++// Resolve from the script's own location, not process.cwd() — same reason check-sdk-coverage.mjs+// does: the gate must run identically from any directory (npm run pins cwd, direct invocation+// does not).+const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url));/** hand file -> { handTypeName: schemaName } */const MAPPINGS = {@@ -692,7 +704,7 @@ export function parseJavaTypes(sources) {const isDirectRun = process.argv[1] && import.meta.url.endsWith(process.argv[1].split('/').pop());if (isDirectRun) {- const openapi = JSON.parse(readFileSync('openapi.json', 'utf8'));+ const openapi = JSON.parse(readFileSync(`${REPO_ROOT}openapi.json`, 'utf8'));const schemas = openapi.components.schemas;/**@@ -705,18 +717,18 @@ if (isDirectRun) {* reference is nullable), so those pairs verify field presence and type tokens only.*/const goSources = () =>- readdirSync('sdk/go')+ readdirSync(`${REPO_ROOT}sdk/go`).filter(f => f.endsWith('.go') && !f.endsWith('_test.go'))- .map(f => readFileSync(`sdk/go/${f}`, 'utf8'));+ .map(f => readFileSync(`${REPO_ROOT}sdk/go/${f}`, 'utf8'));const javaSources = () =>- readdirSync('sdk/java/src/main/java/com/rmyndharis/openwa/model')+ readdirSync(`${REPO_ROOT}sdk/java/src/main/java/com/rmyndharis/openwa/model`).filter(f => f.endsWith('.java'))- .map(f => readFileSync(`sdk/java/src/main/java/com/rmyndharis/openwa/model/${f}`, 'utf8'));+ .map(f => readFileSync(`${REPO_ROOT}sdk/java/src/main/java/com/rmyndharis/openwa/model/${f}`, 'utf8'));const CLIENTS = [...Object.entries(MAPPINGS).map(([file, mapping]) => ({label: file,- load: () => parseHandTypes(readFileSync(file, 'utf8')),+ load: () => parseHandTypes(readFileSync(`${REPO_ROOT}${file}`, 'utf8')),mapping,excluded: EXCLUDED[file] ?? {},floor: MINIMUM_MAPPED[file],@@ -724,7 +736,7 @@ if (isDirectRun) {})),{label: 'sdk/python/openwa/types.py',- load: () => parsePythonTypes(readFileSync('sdk/python/openwa/types.py', 'utf8')),+ load: () => parsePythonTypes(readFileSync(`${REPO_ROOT}sdk/python/openwa/types.py`, 'utf8')),mapping: PYTHON_MAPPING,excluded: EXCLUDED['sdk/python/openwa/types.py'] ?? {},floor: MINIMUM_MAPPED['sdk/python/openwa/types.py'],diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/EnumWireTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/EnumWireTest.javanew file mode 100644index 000000000..03583fd20--- /dev/null+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/EnumWireTest.java@@ -0,0 +1,91 @@+package com.rmyndharis.openwa;++import static org.junit.jupiter.api.Assertions.assertEquals;++import com.google.gson.Gson;+import com.google.gson.GsonBuilder;+import com.rmyndharis.openwa.model.AccountRestrictionKind;+import com.rmyndharis.openwa.model.BatchLifecycleStatus;+import com.rmyndharis.openwa.model.BatchMessageResult;+import com.rmyndharis.openwa.model.BatchMessageStatus;+import com.rmyndharis.openwa.model.ChatHistoryMessage;+import com.rmyndharis.openwa.model.ChatKind;+import com.rmyndharis.openwa.model.MemberAddMode;+import com.rmyndharis.openwa.model.MessageType;+import com.rmyndharis.openwa.model.PresenceState;+import com.rmyndharis.openwa.model.SessionResponse;+import com.rmyndharis.openwa.model.SessionStatus;+import org.junit.jupiter.api.Test;++/**+ * Wire-format round trips for the enum-backed record components: the API speaks lowercase and+ * snake_case ("qr_ready", "reachout_timelock"), while Java constants are UpperCamel — every enum+ * must carry a {@code @SerializedName} that maps the exact wire token in BOTH directions.+ */+class EnumWireTest {++ private final Gson gson = new GsonBuilder().create();++ @Test+ void sessionStatusRoundTripsEveryWireToken() {+ record Pair(String wire, SessionStatus constant) {}+ Pair[] pairs = {+ new Pair("created", SessionStatus.CREATED),+ new Pair("initializing", SessionStatus.INITIALIZING),+ new Pair("qr_ready", SessionStatus.QR_READY),+ new Pair("authenticating", SessionStatus.AUTHENTICATING),+ new Pair("ready", SessionStatus.READY),+ new Pair("disconnected", SessionStatus.DISCONNECTED),+ new Pair("action_required", SessionStatus.ACTION_REQUIRED),+ new Pair("failed", SessionStatus.FAILED),+ };+ for (Pair pair : pairs) {+ SessionResponse r = gson.fromJson(+ "{\"id\":\"s\",\"name\":\"n\",\"status\":\"" + pair.wire() + "\",\"engineLoaded\":true,"+ + "\"createdAt\":\"t\",\"updatedAt\":\"t\"}",+ SessionResponse.class);+ assertEquals(pair.constant(), r.status(), pair.wire());+ assertEquals(pair.wire(), gson.toJsonTree(r.status()).getAsString(), pair.wire());+ }+ }++ @Test+ void messageAndChatKindRoundTrip() {+ ChatHistoryMessage m = gson.fromJson(+ "{\"id\":\"m\",\"from\":\"a\",\"to\":\"b\",\"chatId\":\"c\",\"body\":\"x\","+ + "\"type\":\"sticker\",\"timestamp\":1,\"fromMe\":true,\"isGroup\":true,\"kind\":\"broadcast\"}",+ ChatHistoryMessage.class);+ assertEquals(MessageType.STICKER, m.type());+ assertEquals(ChatKind.BROADCAST, m.kind());+ assertEquals("sticker", gson.toJsonTree(m.type()).getAsString());+ }++ @Test+ void batchPresenceRestrictionAndMemberAddModeRoundTrip() {+ BatchMessageResult b = gson.fromJson(+ "{\"chatId\":\"[email protected]\",\"status\":\"cancelled\"}", BatchMessageResult.class);+ assertEquals(BatchMessageStatus.CANCELLED, b.status());++ com.rmyndharis.openwa.model.BatchStatusResponse s = gson.fromJson(+ "{\"batchId\":\"b1\",\"status\":\"processing\",\"progress\":{\"total\":1,\"sent\":0,"+ + "\"failed\":0,\"pending\":1,\"cancelled\":0},\"results\":[]}",+ com.rmyndharis.openwa.model.BatchStatusResponse.class);+ assertEquals(BatchLifecycleStatus.PROCESSING, s.status());++ com.rmyndharis.openwa.model.ParticipantPresence p = gson.fromJson(+ "{\"id\":\"[email protected]\",\"state\":\"recording\"}",+ com.rmyndharis.openwa.model.ParticipantPresence.class);+ assertEquals(PresenceState.RECORDING, p.state());++ com.rmyndharis.openwa.model.AccountRestriction a = gson.fromJson(+ "{\"kind\":\"proxy_block\",\"code\":\"X\"}",+ com.rmyndharis.openwa.model.AccountRestriction.class);+ assertEquals(AccountRestrictionKind.PROXY_BLOCK, a.kind());++ com.rmyndharis.openwa.model.GroupInfo g = gson.fromJson(+ "{\"id\":\"g\",\"name\":\"n\",\"memberAddMode\":\"admins\"}",+ com.rmyndharis.openwa.model.GroupInfo.class);+ assertEquals(MemberAddMode.ADMINS, g.memberAddMode());+ }++}diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex e6fd68b22..e9181d95c 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -729,6 +729,8 @@ class GroupInfo(TypedDict):ephemeralSeconds: NotRequired[int]locked: NotRequired[bool]memberAddMode: NotRequired[Literal["all", "admins"]]++class CreateGroupRequest(TypedDict):name: strparticipants: list[Jid]