Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(integration): operator-supplied ingress secret, config redaction, SDK type completeness (#585)

Yudhi Armyndharisc463eb8c62a4
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 69b2b1b11..861011c7d 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -915,6 +915,14 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
priority,
);
},
+ // In-process built-ins are not reached by the ingress pipeline (it dispatches to sandbox hosts),
+ // so fail loud rather than silently never firing. Sandboxed plugins get a real registerWebhook
+ // from the worker bootstrap.
+ registerWebhook: () => {
+ throw new PluginCapabilityError(
+ `Plugin ${plugin.manifest.id}: registerWebhook (ingress) is only available to sandboxed plugins`,
+ );
+ },
messages: {
sendText: async (sessionId, chatId, text) => {
// Validate permission + scope + that the session has a live engine BEFORE MessageService
diff --git a/src/core/plugins/plugin-net.ts b/src/core/plugins/plugin-net.ts
index 3ffadb7a5..6f714c875 100644
--- a/src/core/plugins/plugin-net.ts
+++ b/src/core/plugins/plugin-net.ts
@@ -6,11 +6,12 @@ const MAX_TIMEOUT_MS = 30000;
/** Cap the buffered response body so a hostile endpoint can't exhaust host memory through a plugin. */
const MAX_BODY_BYTES = 10 * 1024 * 1024;
-/** Request a sandboxed plugin may make through ctx.net.fetch. Body is a string (text/JSON APIs). */
+/** Request a sandboxed plugin may make through ctx.net.fetch. Body may be a string (text/JSON) or raw
+ * bytes (binary uploads, e.g. multipart) — a Uint8Array survives the worker structuredClone bridge. */
export interface PluginNetRequestInit {
method?: string;
headers?: Record<string, string>;
- body?: string;
+ body?: string | Uint8Array;
timeoutMs?: number;
}
diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.ts
index 7ce22b9fd..c296544ba 100644
--- a/src/core/plugins/plugin.interfaces.ts
+++ b/src/core/plugins/plugin.interfaces.ts
@@ -8,6 +8,11 @@ import type { MessageResponseDto } from '../../modules/message/dto';
import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import type { PluginNetRequestInit, PluginNetResponse } from './plugin-net';
import type { HandoverState } from '../../modules/integration/entities/conversation-mapping.entity';
+import type { WebhookRequest, WebhookResponse, WebhookHandler } from './sandbox/worker-webhooks';
+
+// Re-export the ingress webhook types on the public SDK surface so plugin authors can type their
+// handler without importing from sandbox internals.
+export type { WebhookRequest, WebhookResponse, WebhookHandler };
// ============================================================================
// Plugin Types
@@ -317,6 +322,10 @@ export interface PluginContext {
// Register a hook handler
registerHook: (event: HookEvent, handler: HookHandler, priority?: number) => void;
+ // Claim an inbound ingress webhook route (requires the `webhook:ingress` permission). Delivered only
+ // to sandboxed plugins via the ingress pipeline; in-process built-ins cannot receive ingress.
+ registerWebhook: (route: string, handler: WebhookHandler) => void;
+
// Curated write surface — routes through MessageService (persistence preserved).
messages: PluginMessagingCapability;
diff --git a/src/modules/integration/dto/instance.dto.ts b/src/modules/integration/dto/instance.dto.ts
index 854cfedbd..50d2a2390 100644
--- a/src/modules/integration/dto/instance.dto.ts
+++ b/src/modules/integration/dto/instance.dto.ts
@@ -1,4 +1,4 @@
-import { IsBoolean, IsNotEmpty, IsObject, IsOptional, IsString, Matches, MaxLength } from 'class-validator';
+import { IsBoolean, IsNotEmpty, IsObject, IsOptional, IsString, Matches, MaxLength, MinLength } from 'class-validator';
import { IngressUrl } from '../ingress-url';
// Safe charset: also prevents an instanceId containing ':' (which would collide the P1 ordering key).
@@ -20,6 +20,15 @@ export class CreateInstanceDto {
@MaxLength(512)
verifyToken?: string;
+ // Operator-supplied ingress HMAC secret (e.g. the provider's webhook secret). When present it must be
+ // a real value (>= 16 chars) — an empty/short secret would make the public ingress signature forgeable.
+ // Omit to auto-generate a random 64-hex secret.
+ @IsOptional()
+ @IsString()
+ @MinLength(16, { message: 'secret must be at least 16 characters' })
+ @MaxLength(512)
+ secret?: string;
+
@IsOptional()
@IsObject()
config?: Record<string, unknown>;
diff --git a/src/modules/integration/ingress-golden.spec.ts b/src/modules/integration/ingress-golden.spec.ts
index fae2abae3..e629788b8 100644
--- a/src/modules/integration/ingress-golden.spec.ts
+++ b/src/modules/integration/ingress-golden.spec.ts
@@ -5,13 +5,18 @@ import { IngressService, IngressDeps } from './ingress.service';
// This wires the real IngressService + verifier + a fake dedup/enqueue + a fake loader to prove the
// whole SDK v1 contract: a signed Chatwoot delivery flows to a conversation.send. It is the frozen
-// executable spec — a break here means the wire ABI changed.
+// executable spec — a break here means the wire ABI changed. Chatwoot account-level webhooks sign
+// `sha256=HMAC(secret, "{timestamp}.{rawBody}")` and send an X-Chatwoot-Timestamp header, so the golden
+// exercises exactly that scheme (not a bare-body HMAC) and asserts the replay window is enforced.
describe('Integration SDK v1 golden contract — Chatwoot message_created', () => {
const secret = randomBytes(32).toString('hex');
// Read the RAW bytes from disk — the HMAC must be computed over exactly what a provider would sign,
// not a re-serialized object (JSON.stringify(JSON.parse(raw)) is not guaranteed byte-identical).
const raw = readFileSync(join(__dirname, '__fixtures__/chatwoot-message_created.json'), 'utf8');
- const sig = 'sha256=' + createHmac('sha256', secret).update(raw).digest('hex');
+ // Fixed epoch (seconds) so the replay-window check is deterministic; `now` is injected to match.
+ const ts = 1700000000;
+ const sign = (t: number) => 'sha256=' + createHmac('sha256', secret).update(`${t}.${raw}`).digest('hex');
+ const sig = sign(ts);
const manifestRoute = () => ({
route: 'chatwoot',
@@ -21,9 +26,11 @@ describe('Integration SDK v1 golden contract — Chatwoot message_created', () =
signature: {
scheme: 'hmac-sha256' as const,
header: 'X-Chatwoot-Signature',
- contentTemplate: '{rawBody}',
+ contentTemplate: '{timestamp}.{rawBody}',
encoding: 'hex' as const,
prefix: 'sha256=',
+ timestampHeader: 'X-Chatwoot-Timestamp',
+ toleranceSec: 300,
},
dedupHeader: 'x-chatwoot-delivery',
});
@@ -72,7 +79,7 @@ describe('Integration SDK v1 golden contract — Chatwoot message_created', () =
dispatched.push(jobId);
return Promise.resolve();
},
- now: () => 0,
+ now: () => ts * 1000,
};
const svc = new IngressService(deps);
@@ -81,7 +88,11 @@ describe('Integration SDK v1 golden contract — Chatwoot message_created', () =
instanceId: 'acct1',
route: 'chatwoot',
method: 'POST',
- headers: { 'x-chatwoot-signature': sig, 'x-chatwoot-delivery': 'delivery-1' },
+ headers: {
+ 'x-chatwoot-signature': sig,
+ 'x-chatwoot-timestamp': String(ts),
+ 'x-chatwoot-delivery': 'delivery-1',
+ },
query: {},
rawBody: raw,
});
@@ -101,7 +112,40 @@ describe('Integration SDK v1 golden contract — Chatwoot message_created', () =
dispatched.push(jobId);
return Promise.resolve();
},
- now: () => 0,
+ now: () => ts * 1000,
+ };
+ const svc = new IngressService(deps);
+
+ const res = await svc.handle({
+ pluginId: 'chatwoot',
+ instanceId: 'acct1',
+ route: 'chatwoot',
+ method: 'POST',
+ headers: {
+ 'x-chatwoot-signature': 'sha256=deadbeef',
+ 'x-chatwoot-timestamp': String(ts),
+ 'x-chatwoot-delivery': 'delivery-2',
+ },
+ query: {},
+ rawBody: raw,
+ });
+
+ expect(res.status).toBe(401);
+ expect(dispatched).toEqual([]);
+ });
+
+ it('rejects a stale (replayed) timestamp beyond tolerance (401) and never dispatches', async () => {
+ const staleTs = ts - 3600; // signed correctly but an hour old — well beyond the 300s window
+ const dispatched: unknown[] = [];
+ const deps: IngressDeps = {
+ instances: { resolve: resolveInstance },
+ manifestRoute,
+ events: { recordOrSkip: () => Promise.resolve(true) },
+ enqueue: (_data, jobId) => {
+ dispatched.push(jobId);
+ return Promise.resolve();
+ },
+ now: () => ts * 1000,
};
const svc = new IngressService(deps);
@@ -110,7 +154,11 @@ describe('Integration SDK v1 golden contract — Chatwoot message_created', () =
instanceId: 'acct1',
route: 'chatwoot',
method: 'POST',
- headers: { 'x-chatwoot-signature': 'sha256=deadbeef', 'x-chatwoot-delivery': 'delivery-2' },
+ headers: {
+ 'x-chatwoot-signature': sign(staleTs),
+ 'x-chatwoot-timestamp': String(staleTs),
+ 'x-chatwoot-delivery': 'delivery-3',
+ },
query: {},
rawBody: raw,
});
diff --git a/src/modules/integration/ingress-signature.spec.ts b/src/modules/integration/ingress-signature.spec.ts
index b5e2c4e12..02636a026 100644
--- a/src/modules/integration/ingress-signature.spec.ts
+++ b/src/modules/integration/ingress-signature.spec.ts
@@ -74,4 +74,16 @@ describe('verifyIngressSignature', () => {
it('accepts scheme "none" without a signature', () => {
expect(verifyIngressSignature({ scheme: 'none' }, { rawBody, headers: {}, secret, now: 0 }).ok).toBe(true);
});
+
+ it('fails closed on an empty secret even for a structurally valid HMAC', () => {
+ const emptySecretSpec = { scheme: 'hmac-sha256' as const, header: 'x-sig' };
+ const digest = createHmac('sha256', '').update('body').digest('hex');
+ const out = verifyIngressSignature(emptySecretSpec, {
+ rawBody: 'body',
+ headers: { 'x-sig': digest },
+ secret: '',
+ now: 0,
+ });
+ expect(out.ok).toBe(false);
+ });
});
diff --git a/src/modules/integration/ingress-signature.ts b/src/modules/integration/ingress-signature.ts
index 133e6437e..14fc2b555 100644
--- a/src/modules/integration/ingress-signature.ts
+++ b/src/modules/integration/ingress-signature.ts
@@ -23,6 +23,7 @@ export function verifyIngressSignature(
input: VerifyInput,
): { ok: boolean; reason?: string } {
if (spec.scheme === 'none') return { ok: true };
+ if (!input.secret) return { ok: false, reason: 'empty ingress secret' };
if (spec.timestampHeader) {
const tsRaw = header(input.headers, spec.timestampHeader);
diff --git a/src/modules/integration/integration-instance.controller.ts b/src/modules/integration/integration-instance.controller.ts
index 59c484f83..3d5aede00 100644
--- a/src/modules/integration/integration-instance.controller.ts
+++ b/src/modules/integration/integration-instance.controller.ts
@@ -41,6 +41,7 @@ export class IntegrationInstanceController {
const inst = await this.instances.create(pluginId, dto.instanceId, {
sessionScope: dto.sessionScope,
verifyToken: dto.verifyToken,
+ secret: dto.secret,
config: dto.config,
});
void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_CREATED, {
@@ -122,7 +123,8 @@ export class IntegrationInstanceController {
}
private view(inst: PluginInstance, routes: string[], reveal: boolean): InstanceView {
- const masked = reveal ? inst : this.instances.maskedView(inst);
+ const schema = this.loader.getPlugin(inst.pluginId)?.manifest.configSchema;
+ const masked = reveal ? inst : this.instances.maskedView(inst, schema);
return {
id: masked.id,
pluginId: masked.pluginId,
diff --git a/src/modules/integration/plugin-instance.service.spec.ts b/src/modules/integration/plugin-instance.service.spec.ts
index 53c36b39b..bc8f52820 100644
--- a/src/modules/integration/plugin-instance.service.spec.ts
+++ b/src/modules/integration/plugin-instance.service.spec.ts
@@ -2,6 +2,7 @@ import { DataSource } from 'typeorm';
import { PluginInstance } from './entities/plugin-instance.entity';
import { PluginInstanceService, InstanceExistsError } from './plugin-instance.service';
import { AddIntegrationFabric1781900000000 } from '../../database/migrations/1781900000000-AddIntegrationFabric';
+import type { PluginConfigSchema } from '../../core/plugins/plugin.interfaces';
describe('PluginInstanceService', () => {
let ds: DataSource;
@@ -29,11 +30,48 @@ describe('PluginInstanceService', () => {
expect(service.maskedView(inst).secret).toBe('***');
});
+ it('masks secret:true config fields (apiToken) on masked reads', () => {
+ const schema = {
+ type: 'object',
+ properties: { apiToken: { type: 'string', secret: true }, accountId: { type: 'number' } },
+ } as PluginConfigSchema;
+ const inst = {
+ id: 'p:i',
+ secret: 'x',
+ config: { apiToken: 'live-token', accountId: 3 },
+ } as unknown as PluginInstance;
+ const masked = service.maskedView(inst, schema);
+ const config = masked.config as Record<string, unknown>;
+ expect(masked.secret).toBe('***');
+ expect(config.apiToken).toBe('***');
+ expect(config.accountId).toBe(3);
+ });
+
+ it('masks the ENTIRE config when the schema is unavailable, e.g. the plugin is unloaded (fail-closed)', () => {
+ const inst = {
+ id: 'p:i',
+ secret: 'x',
+ config: { apiToken: 'live-token', accountId: 3 },
+ } as unknown as PluginInstance;
+ const config = service.maskedView(inst, undefined).config as Record<string, unknown>;
+ expect(config.apiToken).toBe('***');
+ expect(config.accountId).toBe('***');
+ });
+
it('resolves an existing instance and returns null for an unknown one', async () => {
await service.mint('chatwoot', 'acct1', {});
expect((await service.resolve('chatwoot', 'acct1'))?.id).toBe('chatwoot:acct1');
expect(await service.resolve('chatwoot', 'nope')).toBeNull();
});
+
+ it('accepts a valid operator secret, rejects short/empty, else auto-generates', async () => {
+ const ok = await service.create('chatwoot-adapter', 'a1', { secret: 'cw-secret-16chars!' });
+ expect(ok.secret).toBe('cw-secret-16chars!');
+ await expect(service.create('chatwoot-adapter', 'a2', { secret: ' ' })).rejects.toThrow(/secret/i);
+ await expect(service.create('chatwoot-adapter', 'a3', { secret: 'short' })).rejects.toThrow(/16/);
+ const gen = await service.create('chatwoot-adapter', 'a4', {});
+ expect(gen.secret).toMatch(/^[0-9a-f]{64}$/);
+ });
});
describe('PluginInstanceService provisioning', () => {
diff --git a/src/modules/integration/plugin-instance.service.ts b/src/modules/integration/plugin-instance.service.ts
index 1bd8c6640..a70dba5e3 100644
--- a/src/modules/integration/plugin-instance.service.ts
+++ b/src/modules/integration/plugin-instance.service.ts
@@ -1,11 +1,41 @@
import { randomBytes } from 'node:crypto';
-import { Injectable } from '@nestjs/common';
+import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PluginInstance } from './entities/plugin-instance.entity';
+import type { PluginConfigSchema } from '../../core/plugins/plugin.interfaces';
const SECRET_MASK = '***';
+// A supplied ingress secret must be a real, guessing-resistant value; an empty/short one would make the
+// public HMAC forgeable. Absent => auto-generate. Trimmed so pasted whitespace can't slip a weak secret in.
+function normalizeSecret(supplied?: string): string {
+ if (supplied === undefined) return randomBytes(32).toString('hex');
+ const s = supplied.trim();
+ if (s.length < 16) {
+ throw new BadRequestException('instance secret must be a non-empty string of at least 16 characters');
+ }
+ return s;
+}
+
+// Mask every config value the plugin's schema marks `secret:true` (e.g. a Chatwoot apiToken) on operator
+// reads — core does not otherwise redact instance `config`. Top-level fields only (the declarative
+// configSchema is flat for secret credentials).
+function redactSecrets(
+ config: Record<string, unknown> | null,
+ schema?: PluginConfigSchema,
+): Record<string, unknown> | null {
+ if (!config) return config;
+ // Schema unavailable (plugin unloaded / failed to load) — we can't tell which fields are secret, so
+ // fail closed by masking every value rather than risk leaking a credential such as an API token.
+ if (!schema?.properties) return Object.fromEntries(Object.keys(config).map(key => [key, SECRET_MASK]));
+ const out: Record<string, unknown> = { ...config };
+ for (const [key, field] of Object.entries(schema.properties)) {
+ if (key in out && field.secret) out[key] = SECRET_MASK;
+ }
+ return out;
+}
+
export class InstanceExistsError extends Error {
constructor(pluginId: string, instanceId: string) {
super(`instance ${instanceId} already exists for plugin ${pluginId}`);
@@ -20,7 +50,7 @@ export class PluginInstanceService {
async mint(
pluginId: string,
instanceId: string,
- opts: { sessionScope?: string; verifyToken?: string; config?: Record<string, unknown> },
+ opts: { sessionScope?: string; verifyToken?: string; secret?: string; config?: Record<string, unknown> },
): Promise<PluginInstance> {
const id = `${pluginId}:${instanceId}`;
const existing = await this.repo.findOne({ where: { id } });
@@ -30,7 +60,7 @@ export class PluginInstanceService {
pluginId,
instanceId,
sessionScope: opts.sessionScope || null,
- secret: randomBytes(32).toString('hex'),
+ secret: normalizeSecret(opts.secret),
verifyToken: opts.verifyToken ?? null,
config: opts.config ?? null,
enabled: true,
@@ -42,15 +72,16 @@ export class PluginInstanceService {
return this.repo.findOne({ where: { id: `${pluginId}:${instanceId}` } });
}
- // Operator-facing view: never leak the raw secret. Reuses the redact-config sentinel convention.
- maskedView(instance: PluginInstance): PluginInstance {
- return { ...instance, secret: SECRET_MASK };
+ // Operator-facing view: never leak the raw secret, and mask any `secret:true` config field (e.g. a
+ // provider apiToken) per the plugin's configSchema. Reuses the redact-config sentinel convention.
+ maskedView(instance: PluginInstance, schema?: PluginConfigSchema): PluginInstance {
+ return { ...instance, secret: SECRET_MASK, config: redactSecrets(instance.config, schema) };
}
async create(
pluginId: string,
instanceId: string,
- opts: { sessionScope?: string; verifyToken?: string; config?: Record<string, unknown> },
+ opts: { sessionScope?: string; verifyToken?: string; secret?: string; config?: Record<string, unknown> },
): Promise<PluginInstance> {
const id = `${pluginId}:${instanceId}`;
if (await this.repo.findOne({ where: { id } })) throw new InstanceExistsError(pluginId, instanceId);
@@ -59,7 +90,7 @@ export class PluginInstanceService {
pluginId,
instanceId,
sessionScope: opts.sessionScope || null,
- secret: randomBytes(32).toString('hex'),
+ secret: normalizeSecret(opts.secret),
verifyToken: opts.verifyToken ?? null,
config: opts.config ?? null,
enabled: true,