Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk): adjudicate the client wire-shape backlog — 33 pairs gated, 23→7 exclusions
Yudhi Armyndharisee7f00629fa2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c48a89a42..cbf811bff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,7 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added- Weekly scheduled security scan (`.github/workflows/security-scan.yml`): the merge-time audit gates re-run against the current dependency trees, and the release image scan re-runs against the published `latest` image on both architectures — a newly published advisory surfaces within days instead of at the next push or release. Also dispatchable on demand.-- Client wire-shape contract gate (`check:contract-shapes`, in the CI lint job): the JavaScript SDK's and the dashboard's hand-written wire types are now checked field-by-field against the OpenAPI schemas — presence, required-vs-optional, and type drift for simple fields — closing the gap where every existing gate verified which routes exist but none verified the body shapes they carry. 21 pairs conform today; 23 known-drifting pairs are excluded inline with recorded reasons and shrink as each is adjudicated.+- Client wire-shape contract gate (`check:contract-shapes`, in the CI lint job): the JavaScript SDK's and the dashboard's hand-written wire types are now checked field-by-field against the OpenAPI schemas — presence, required-vs-optional, and type drift for simple fields — closing the gap where every existing gate verified which routes exist but none verified the body shapes they carry. 33 pairs conform today; the 7 remaining exclusions are recorded inline with reasons — one is deliberate (the dashboard's tri-state `engineLoaded` client model), the rest are a field-by-field adjudication backlog.## [0.19.0] - 2026-08-15diff --git a/dashboard/src/pages/MessageTester.tsx b/dashboard/src/pages/MessageTester.tsxindex 6a567b416..af79f26b8 100644--- a/dashboard/src/pages/MessageTester.tsx+++ b/dashboard/src/pages/MessageTester.tsx@@ -315,6 +315,7 @@ export function MessageTester() {batchId: batch.batchId,status: 'pending',progress: { total: batch.totalMessages, sent: 0, failed: 0, pending: batch.totalMessages, cancelled: 0 },+ results: [],});startBatchPolling(session, batch.batchId);return;diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 9d2047058..abe2998e3 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -49,11 +49,14 @@ export interface Session {* Whether the gateway holds a live engine for this session right now. The precondition the* lifecycle routes enforce, and not derivable from `status`: `disconnected` covers both a session* mid automatic-reconnect (engine present, start 400s) and one stopped through stop() (no engine).- * Optional only because a dashboard can be served by a gateway that predates the field.+ * Optional BY DESIGN, not drift: the wire always carries it, but this client's state model+ * clears it to "unknown" after a websocket status event until the row refreshes, so the action+ * helpers fall back to the historical status set instead of trusting a stale value.*/engineLoaded?: boolean;phone?: string | null;pushName?: string | null;+ connectedAt?: string | null;lastActive?: string | null;createdAt: string;updatedAt: string;@@ -130,7 +133,9 @@ export interface Webhook {events: string[];filters?: WebhookFilters | null;active: boolean;- secret?: string;+ retryCount: number;+ /** Null until the first delivery attempt. */+ lastTriggeredAt?: string | null;createdAt: string;updatedAt: string;}@@ -165,22 +170,30 @@ export interface ApiKey {lastUsedAt?: string;usageCount: number;createdAt: string;- apiKey?: string; // Only returned on creation+}++/** The creation response: every list/detail field plus the plaintext key, shown exactly once. */+export interface CreatedApiKey extends ApiKey {+ apiKey: string;}export interface AuditLog {id: string;action: string;severity: 'info' | 'warn' | 'error';- apiKeyId?: string;- apiKeyName?: string;- sessionId?: string;- sessionName?: string;- ipAddress?: string;- method?: string;- path?: string;- statusCode?: number;- errorMessage?: string;+ apiKeyId: string | null;+ apiKeyName: string | null;+ sessionId: string | null;+ sessionName: string | null;+ ipAddress: string | null;+ userAgent: string | null;+ method: string | null;+ path: string | null;+ statusCode: number | null;+ /** Null when the action succeeded. */+ errorMessage: string | null;+ /** Free-form context whose shape varies per action. */+ metadata: Record<string, unknown> | null;createdAt: string;}@@ -285,9 +298,12 @@ export interface EngineHistoryMessage {export interface Channel {id: string;name: string;- subscriberCount?: number;+ description?: string;inviteCode?: string;+ subscriberCount?: number;+ picture?: string;verified?: boolean;+ createdAt?: number;}export interface ChannelMessage {@@ -323,7 +339,12 @@ export interface Contact {id: string;name?: string;pushName?: string;- number?: string;+ /** MSISDN digits without separators — always present in the response. */+ number: string;+ isMyContact: boolean;+ isBlocked: boolean;+ /** Absent when the contact has none or privacy hides it. */+ profilePicUrl?: string;}export interface SendMediaPayload {@@ -429,9 +450,10 @@ export interface BatchStatusResponse {batchId: string;status: BatchStatus;progress: BatchProgress;- results?: BatchMessageResult[];- startedAt?: string;- completedAt?: string;+ /** One entry per recipient already attempted — empty until the first send resolves. */+ results: BatchMessageResult[];+ startedAt?: string | null;+ completedAt?: string | null;}export interface HealthStatus {@@ -576,7 +598,7 @@ export interface SearchHit {/** Epoch-seconds (mirrors the persisted messages.timestamp column). */timestamp: number;type: string;- direction: string;+ direction: 'incoming' | 'outgoing';from: string;score?: number;}@@ -874,7 +896,7 @@ export const apiKeyApi = {allowedSessions?: string[];expiresAt?: string;}) =>- request<ApiKey>('/auth/api-keys', {+ request<CreatedApiKey>('/auth/api-keys', {method: 'POST',body: JSON.stringify(data),}),diff --git a/scripts/check-contract-shapes.mjs b/scripts/check-contract-shapes.mjsindex 67e546307..2a60e7039 100644--- a/scripts/check-contract-shapes.mjs+++ b/scripts/check-contract-shapes.mjs@@ -38,6 +38,7 @@ const MAPPINGS = {BatchStatusResponse: 'BatchStatusResponseDto',BulkMessageContent: 'BulkMessageContentDto',BulkMessageItem: 'BulkMessageItemDto',+ BulkMessageResponse: 'BulkMessageResponseDto',CallLinkResponse: 'CallLinkResponseDto',ChatHistoryMessage: 'ChatHistoryMessageDto',ChatSummary: 'ChatSummaryDto',@@ -58,23 +59,19 @@ const MAPPINGS = {},'dashboard/src/services/api.ts': {AccountRestriction: 'AccountRestrictionDto',- ApiKey: 'ApiKeyResponseDto',- BatchMessageResult: 'BatchMessageResultDto',- Chat: 'ChatSummaryDto',AuditLog: 'AuditLogDto',BatchProgress: 'BatchProgressDto',BatchStatusResponse: 'BatchStatusResponseDto',- BulkMessageItem: 'BulkMessageItemDto',Channel: 'ChannelDto',ChannelMessage: 'ChannelMessageDto',ChatPresence: 'ChatPresenceResponseDto',Contact: 'ContactDto',+ CreatedApiKey: 'ApiKeyCreatedResponseDto',EngineHistoryMessage: 'ChatHistoryMessageDto',MessageResponse: 'MessageResponseDto',ParticipantPresence: 'ParticipantPresenceDto',ProfilePictureResponse: 'ProfilePictureResponseDto',SearchHit: 'SearchHitDto',- Session: 'SessionResponseDto',SessionConfig: 'SessionConfigResponseDto',Webhook: 'WebhookResponseDto',},@@ -83,13 +80,6 @@ const MAPPINGS = {/** Known drift, deliberately not gated yet — each line is a to-adjudicate follow-up. */const EXCLUDED = {'sdk/javascript/src/types.ts': {- AccountRestriction:- 'hand types expiresAt as string|null; contract declares string — adjudicate which side reflects the runtime',- GroupSummary: 'hand types linkedParentJID as string|null; contract declares string — adjudicate',- ProfilePictureResponse: 'hand types url as string|null; contract declares string — adjudicate',- BatchMessageResult: 'hand marks chatId/status optional; contract declares them required with a status enum',- BulkMessageResponse: 'hand requires estimatedCompletionTime; contract declares it optional',- BatchStatusResponse: 'hand marks results optional; contract requires it',ChatHistoryMessage: 'field-level differences across the 20+-field history shape; adjudicate pair-by-pair',ChatSummary:'hand marks every field optional and widens timestamp to string|number; contract requires them, timestamp a number',@@ -99,22 +89,10 @@ const EXCLUDED = {'CONTRACT GAP: response schema declares filters as Record<string, never>; fix the backend DTO decorator, then pin',},'dashboard/src/services/api.ts': {- AccountRestriction:- 'hand types expiresAt as string|null; contract declares string — adjudicate which side reflects the runtime',- ProfilePictureResponse: 'hand types url as string|null; contract declares string — adjudicate',- SearchHit: 'hand widens direction to string; contract narrows to enum(incoming,outgoing) — narrow the hand type',- SessionConfig: 'hand types maxReconnectAttempts as number|null; contract declares number — adjudicate',- ApiKey:- 'hand declares an apiKey field the response never carries (the plaintext is shown once at creation); drop it from the type',- AuditLog:- 'hand marks apiKeyId/apiKeyName/sessionId/sessionName and the action fields optional; contract requires them, and adds metadata/userAgent',- BatchStatusResponse: 'hand marks results optional; contract requires it',- Channel: 'hand lacks createdAt/description/picture the response carries',- Contact: 'hand marks number optional; contract requires it, and hand lacks isBlocked/isMyContact/profilePicUrl',+ Session:+ 'BY DESIGN, not drift: the wire always carries engineLoaded, but this client clears it to "unknown" after a websocket status event so the action helpers fall back to the status set — the type models client state, not the wire',EngineHistoryMessage:'hand models a subset of the history shape (13 contract fields missing, fromMe optional); mirror the full shape',- Session: 'hand marks engineLoaded optional and lacks connectedAt; contract requires both',- Webhook: 'hand declares secret (never returned) and lacks lastTriggeredAt/retryCount',},};@@ -122,8 +100,18 @@ const EXCLUDED = {export function parseHandTypes(source) {const types = {};- const iface = /export interface (\w+)(?: extends \w+)? \{([\s\S]*?)\n\}/g;- for (const [, name, body] of source.matchAll(iface)) types[name] = parseMembers(body);+ const parents = {};+ const iface = /export interface (\w+)(?: extends (\w+))? \{([\s\S]*?)\n\}/g;+ for (const [, name, parent, body] of source.matchAll(iface)) {+ types[name] = parseMembers(body);+ if (parent) parents[name] = parent;+ }+ // An `extends` adds the parent's members underneath the child's own (child wins on collision) —+ // without this, every inherited field reads as "missing" and response types like the dashboard's+ // CreatedApiKey (extends ApiKey) can never conform.+ for (const [name, parent] of Object.entries(parents)) {+ if (types[parent]) types[name] = { ...types[parent], ...types[name] };+ }return types;}@@ -203,6 +191,13 @@ export function handToken(text, types, depth = 0) {}export function schemaToken(node, schemas, depth = 0) {+ const token = baseSchemaToken(node, schemas, depth);+ // OpenAPI 3.0 nullability is a SIBLING flag on the node (`nullable: true`), not a type member —+ // dropping it silently downgraded every honest `string | null` hand type to a false mismatch.+ return node?.nullable === true && !token.endsWith('|null') ? `${token}|null` : token;+}++function baseSchemaToken(node, schemas, depth = 0) {if (!node || typeof node !== 'object') return 'any';if (node.$ref) {const target = schemas[node.$ref.split('/').pop()];diff --git a/scripts/check-contract-shapes.spec.mjs b/scripts/check-contract-shapes.spec.mjsindex ac3f68215..014391d62 100644--- a/scripts/check-contract-shapes.spec.mjs+++ b/scripts/check-contract-shapes.spec.mjs@@ -102,3 +102,26 @@ test('handToken reduces enums, null unions and arrays deterministically', () =>assert.equal(handToken('number | null', types), 'number|null');assert.equal(handToken('string[]', types), 'array<string>');});++test('schemaToken honors the OpenAPI 3.0 sibling nullable flag', () => {+ // Regression: nullable is a sibling flag, not a type member — dropping it turned every honest+ // `string | null` hand type into a false mismatch against a plain `string` schema.+ const nullableSchema = { type: 'string', nullable: true };+ assert.equal(schemaToken(nullableSchema, {}), 'string|null');+ assert.equal(schemaToken({ type: 'string' }, {}), 'string');+ assert.equal(schemaToken({ type: 'integer', nullable: true }, {}), 'number|null');+});++test('parseHandTypes resolves `extends` — inherited fields are not "missing"', () => {+ // Regression: CreatedApiKey extends ApiKey read as a bare { apiKey } shape and could never+ // conform to the schema that actually includes every inherited member.+ const types = parseHandTypes(`+export interface Base {+ id: string;+}+export interface Child extends Base {+ apiKey: string;+}+`);+ assert.deepEqual(Object.keys(types.Child), ['id', 'apiKey']);+});diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 47d2b3c85..1246acdf7 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -595,7 +595,7 @@ export interface BulkMessageResponse {batchId: string;status: string;totalMessages: number;- estimatedCompletionTime: string;+ estimatedCompletionTime?: string;statusUrl: string;}@@ -610,13 +610,16 @@ export interface BatchProgress {/** Per-message outcome within a batch result list. */export interface BatchMessageResult {- chatId?: Jid;- status?: string;+ chatId: Jid;+ status: BatchMessageStatus;messageId?: string;sentAt?: string;error?: { code: string; message: string };}+/** Lifecycle of one recipient's send inside a batch — the `status` of {@link BatchMessageResult}. */+export type BatchMessageStatus = 'pending' | 'sent' | 'failed' | 'cancelled';+/*** Response from `GET /messages/batch/:batchId` (batch status polling) and* `POST /messages/batch/:batchId/cancel`. Distinct from@@ -624,13 +627,16 @@ export interface BatchMessageResult {*/export interface BatchStatusResponse {batchId: string;- status: string;- progress?: BatchProgress;- results?: BatchMessageResult[];- startedAt?: string;- completedAt?: string;+ status: BatchLifecycleStatus;+ progress: BatchProgress;+ results: BatchMessageResult[];+ startedAt?: string | null;+ completedAt?: string | null;}+/** Lifecycle of a whole batch — the `status` of {@link BatchStatusResponse}. */+export type BatchLifecycleStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'cancelled';+// ── Contact ───────────────────────────────────────────────────────export interface ContactRecord {