Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat: Integration Fabric — operator provisioning API for plugin instances (#571)

Yudhi Armyndharis39a422826690
diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.ts
index 6a10492e2..047e30135 100644
--- a/src/modules/audit/entities/audit-log.entity.ts
+++ b/src/modules/audit/entities/audit-log.entity.ts
@@ -27,6 +27,11 @@ export enum AuditAction {
WEBHOOK_DELETED = 'webhook_deleted',
WEBHOOK_TRIGGERED = 'webhook_triggered',
WEBHOOK_FAILED = 'webhook_failed',
+
+ // Integration plugin-instance events
+ INTEGRATION_INSTANCE_CREATED = 'integration_instance_created',
+ INTEGRATION_INSTANCE_SECRET_REGENERATED = 'integration_instance_secret_regenerated',
+ INTEGRATION_INSTANCE_DELETED = 'integration_instance_deleted',
}
export enum AuditSeverity {
diff --git a/src/modules/integration/dto/instance.dto.ts b/src/modules/integration/dto/instance.dto.ts
new file mode 100644
index 000000000..016ce965e
--- /dev/null
+++ b/src/modules/integration/dto/instance.dto.ts
@@ -0,0 +1,56 @@
+import { IsBoolean, IsObject, IsOptional, IsString, Matches, MaxLength } from 'class-validator';
+import { IngressUrl } from '../ingress-url';
+
+// Safe charset: also prevents an instanceId containing ':' (which would collide the P1 ordering key).
+const INSTANCE_ID_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
+
+export class CreateInstanceDto {
+ @IsString()
+ @Matches(INSTANCE_ID_PATTERN, { message: 'instanceId must match ^[a-zA-Z0-9_-]{1,64}$' })
+ instanceId: string;
+
+ @IsOptional()
+ @IsString()
+ @MaxLength(256)
+ sessionScope?: string;
+
+ @IsOptional()
+ @IsString()
+ @MaxLength(512)
+ verifyToken?: string;
+
+ @IsOptional()
+ @IsObject()
+ config?: Record<string, unknown>;
+}
+
+export class UpdateInstanceDto {
+ @IsOptional()
+ @IsBoolean()
+ enabled?: boolean;
+
+ @IsOptional()
+ @IsString()
+ @MaxLength(256)
+ sessionScope?: string;
+
+ @IsOptional()
+ @IsObject()
+ config?: Record<string, unknown>;
+}
+
+export interface InstanceView {
+ id: string;
+ pluginId: string;
+ instanceId: string;
+ sessionScope: string | null;
+ secret: string; // masked ('***') on reads
+ verifyToken: string | null; // masked ('***') on reads when set
+ config: Record<string, unknown> | null;
+ enabled: boolean;
+ createdAt: Date;
+ updatedAt: Date;
+ ingressUrls: IngressUrl[];
+}
+
+export type MintedInstance = InstanceView; // identical shape; `secret` carries the plaintext once
diff --git a/src/modules/integration/entities/plugin-instance.entity.ts b/src/modules/integration/entities/plugin-instance.entity.ts
index 4546ccadd..eb999170e 100644
--- a/src/modules/integration/entities/plugin-instance.entity.ts
+++ b/src/modules/integration/entities/plugin-instance.entity.ts
@@ -19,7 +19,9 @@ export class PluginInstance {
sessionScope: string | null; // resolved session id this instance acts on; null = inherit manifest.sessions
@Column()
- secret: string; // host-minted ingress HMAC secret (masked on read via redactSecretConfig)
+ secret: string; // host-minted ingress HMAC secret; stored plaintext, masked to '***' on API reads
+ // (via PluginInstanceService.maskedView + the provisioning controller's reveal flag), exposed
+ // in full only on mint and regenerate-secret. Note: instance `config` is NOT secret-redacted.
@Column({ type: 'varchar', nullable: true })
verifyToken: string | null; // optional provider challenge token
diff --git a/src/modules/integration/ingress-url.spec.ts b/src/modules/integration/ingress-url.spec.ts
new file mode 100644
index 000000000..4cd462feb
--- /dev/null
+++ b/src/modules/integration/ingress-url.spec.ts
@@ -0,0 +1,24 @@
+import { buildIngressUrls } from './ingress-url';
+
+describe('buildIngressUrls', () => {
+ it('builds absolute URLs from BASE_URL for each route', () => {
+ expect(buildIngressUrls('https://api.example.com', 'chatwoot', 'acct1', ['chatwoot', 'status'])).toEqual([
+ { route: 'chatwoot', url: 'https://api.example.com/api/ingress/chatwoot/acct1/chatwoot' },
+ { route: 'status', url: 'https://api.example.com/api/ingress/chatwoot/acct1/status' },
+ ]);
+ });
+
+ it('strips a trailing slash on BASE_URL', () => {
+ expect(buildIngressUrls('https://api.example.com/', 'p', 'i', ['r'])[0].url).toBe(
+ 'https://api.example.com/api/ingress/p/i/r',
+ );
+ });
+
+ it('falls back to a relative path when BASE_URL is unset', () => {
+ expect(buildIngressUrls(undefined, 'p', 'i', ['r'])).toEqual([{ route: 'r', url: '/api/ingress/p/i/r' }]);
+ });
+
+ it('returns an empty array when the plugin declares no routes', () => {
+ expect(buildIngressUrls('https://x', 'p', 'i', [])).toEqual([]);
+ });
+});
diff --git a/src/modules/integration/ingress-url.ts b/src/modules/integration/ingress-url.ts
new file mode 100644
index 000000000..60fa24032
--- /dev/null
+++ b/src/modules/integration/ingress-url.ts
@@ -0,0 +1,19 @@
+export interface IngressUrl {
+ route: string;
+ url: string;
+}
+
+// Absolute URL from BASE_URL when set (trailing slash trimmed), else a relative path the operator
+// prepends with their own host. Never throws.
+export function buildIngressUrls(
+ baseUrl: string | undefined,
+ pluginId: string,
+ instanceId: string,
+ routes: string[],
+): IngressUrl[] {
+ const base = (baseUrl ?? '').replace(/\/+$/, '');
+ return routes.map(route => ({
+ route,
+ url: `${base}/api/ingress/${pluginId}/${instanceId}/${route}`,
+ }));
+}
diff --git a/src/modules/integration/integration-instance.controller.ts b/src/modules/integration/integration-instance.controller.ts
new file mode 100644
index 000000000..59c484f83
--- /dev/null
+++ b/src/modules/integration/integration-instance.controller.ts
@@ -0,0 +1,140 @@
+import {
+ BadRequestException,
+ Body,
+ ConflictException,
+ Controller,
+ Delete,
+ Get,
+ HttpCode,
+ NotFoundException,
+ Param,
+ Patch,
+ Post,
+} from '@nestjs/common';
+import { RequireRole } from '../auth/decorators/auth.decorators';
+import { ApiKeyRole } from '../auth/entities/api-key.entity';
+import { AuditAction } from '../audit/entities/audit-log.entity';
+import { AuditService } from '../audit/audit.service';
+import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
+import { InstanceExistsError, PluginInstanceService } from './plugin-instance.service';
+import { PluginInstance } from './entities/plugin-instance.entity';
+import { buildIngressUrls } from './ingress-url';
+import { CreateInstanceDto, InstanceView, UpdateInstanceDto } from './dto/instance.dto';
+
+// ADMIN-only provisioning surface for per-plugin instances (e.g. one Chatwoot account). Only plugins
+// that declare an ingress route AND the webhook:ingress permission can have instances; everything
+// else is rejected before touching persistence.
+@Controller('integration/plugins/:pluginId/instances')
+@RequireRole(ApiKeyRole.ADMIN)
+export class IntegrationInstanceController {
+ constructor(
+ private readonly instances: PluginInstanceService,
+ private readonly loader: PluginLoaderService,
+ private readonly audit: AuditService,
+ ) {}
+
+ @Post()
+ @HttpCode(201)
+ async create(@Param('pluginId') pluginId: string, @Body() dto: CreateInstanceDto): Promise<InstanceView> {
+ const routes = this.assertIngressCapable(pluginId);
+ try {
+ const inst = await this.instances.create(pluginId, dto.instanceId, {
+ sessionScope: dto.sessionScope,
+ verifyToken: dto.verifyToken,
+ config: dto.config,
+ });
+ void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_CREATED, {
+ metadata: { pluginId, instanceId: dto.instanceId },
+ });
+ return this.view(inst, routes, /* reveal */ true);
+ } catch (err) {
+ if (err instanceof InstanceExistsError) throw new ConflictException(err.message);
+ throw err;
+ }
+ }
+
+ @Get()
+ async list(@Param('pluginId') pluginId: string): Promise<InstanceView[]> {
+ const routes = this.pluginRoutes(pluginId);
+ const rows = await this.instances.list(pluginId);
+ return rows.map(r => this.view(r, routes, false));
+ }
+
+ @Get(':instanceId')
+ async getOne(@Param('pluginId') pluginId: string, @Param('instanceId') instanceId: string): Promise<InstanceView> {
+ const inst = await this.instances.resolve(pluginId, instanceId);
+ if (!inst) throw new NotFoundException('instance not found');
+ return this.view(inst, this.pluginRoutes(pluginId), false);
+ }
+
+ @Post(':instanceId/regenerate-secret')
+ @HttpCode(200)
+ async regenerate(
+ @Param('pluginId') pluginId: string,
+ @Param('instanceId') instanceId: string,
+ ): Promise<InstanceView> {
+ if (!(await this.instances.resolve(pluginId, instanceId))) throw new NotFoundException('instance not found');
+ const inst = await this.instances.regenerateSecret(pluginId, instanceId);
+ void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_SECRET_REGENERATED, {
+ metadata: { pluginId, instanceId },
+ });
+ return this.view(inst, this.pluginRoutes(pluginId), true);
+ }
+
+ @Patch(':instanceId')
+ async patch(
+ @Param('pluginId') pluginId: string,
+ @Param('instanceId') instanceId: string,
+ @Body() dto: UpdateInstanceDto,
+ ): Promise<InstanceView> {
+ let inst: PluginInstance | null = await this.instances.resolve(pluginId, instanceId);
+ if (!inst) throw new NotFoundException('instance not found');
+ if (dto.enabled !== undefined) inst = await this.instances.setEnabled(pluginId, instanceId, dto.enabled);
+ if (dto.sessionScope !== undefined || dto.config !== undefined) {
+ inst = await this.instances.update(pluginId, instanceId, { sessionScope: dto.sessionScope, config: dto.config });
+ }
+ return this.view(inst as PluginInstance, this.pluginRoutes(pluginId), false);
+ }
+
+ @Delete(':instanceId')
+ @HttpCode(204)
+ async remove(@Param('pluginId') pluginId: string, @Param('instanceId') instanceId: string): Promise<void> {
+ const removed = await this.instances.remove(pluginId, instanceId);
+ if (!removed) throw new NotFoundException('instance not found');
+ void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_DELETED, { metadata: { pluginId, instanceId } });
+ }
+
+ // The plugin must exist AND declare ingress + the webhook:ingress permission to have instances.
+ private assertIngressCapable(pluginId: string): string[] {
+ const plugin = this.loader.getPlugin(pluginId);
+ if (!plugin) throw new NotFoundException(`plugin ${pluginId} not found`);
+ const routes = plugin.manifest.ingress?.map(r => r.route) ?? [];
+ const hasPerm = (plugin.manifest.permissions ?? []).includes('webhook:ingress');
+ if (routes.length === 0 || !hasPerm) {
+ throw new BadRequestException(`plugin ${pluginId} is not ingress-capable`);
+ }
+ return routes;
+ }
+
+ // Best-effort routes for read responses; empty when the plugin is gone or non-ingress (no throw).
+ private pluginRoutes(pluginId: string): string[] {
+ return this.loader.getPlugin(pluginId)?.manifest.ingress?.map(r => r.route) ?? [];
+ }
+
+ private view(inst: PluginInstance, routes: string[], reveal: boolean): InstanceView {
+ const masked = reveal ? inst : this.instances.maskedView(inst);
+ return {
+ id: masked.id,
+ pluginId: masked.pluginId,
+ instanceId: masked.instanceId,
+ sessionScope: masked.sessionScope,
+ secret: masked.secret,
+ verifyToken: reveal ? inst.verifyToken : inst.verifyToken ? '***' : null,
+ config: masked.config,
+ enabled: masked.enabled,
+ createdAt: masked.createdAt,
+ updatedAt: masked.updatedAt,
+ ingressUrls: buildIngressUrls(process.env.BASE_URL, inst.pluginId, inst.instanceId, routes),
+ };
+ }
+}
diff --git a/src/modules/integration/integration.module.ts b/src/modules/integration/integration.module.ts
index cac9667ee..de6f9e6ae 100644
--- a/src/modules/integration/integration.module.ts
+++ b/src/modules/integration/integration.module.ts
@@ -10,6 +10,7 @@ import { IngressController } from './ingress.controller';
import { IngressEnqueueService } from './ingress-enqueue.service';
import { RedriveService } from './redrive.service';
import { RedriveController } from './redrive.controller';
+import { IntegrationInstanceController } from './integration-instance.controller';
import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
/**
@@ -21,7 +22,7 @@ import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
*/
@Module({
imports: [TypeOrmModule.forFeature([PluginInstance, IngressEvent, IntegrationDeliveryFailure], 'data')],
- controllers: [IngressController, RedriveController],
+ controllers: [IngressController, RedriveController, IntegrationInstanceController],
providers: [
PluginInstanceService,
IngressEventService,
diff --git a/src/modules/integration/plugin-instance.service.spec.ts b/src/modules/integration/plugin-instance.service.spec.ts
index 2268149dd..286e882ea 100644
--- a/src/modules/integration/plugin-instance.service.spec.ts
+++ b/src/modules/integration/plugin-instance.service.spec.ts
@@ -1,6 +1,6 @@
import { DataSource } from 'typeorm';
import { PluginInstance } from './entities/plugin-instance.entity';
-import { PluginInstanceService } from './plugin-instance.service';
+import { PluginInstanceService, InstanceExistsError } from './plugin-instance.service';
import { AddIntegrationFabric1781900000000 } from '../../database/migrations/1781900000000-AddIntegrationFabric';
describe('PluginInstanceService', () => {
@@ -35,3 +35,52 @@ describe('PluginInstanceService', () => {
expect(await service.resolve('chatwoot', 'nope')).toBeNull();
});
});
+
+describe('PluginInstanceService provisioning', () => {
+ let ds: DataSource;
+ let service: PluginInstanceService;
+ beforeEach(async () => {
+ ds = new DataSource({ type: 'sqlite', database: ':memory:', entities: [PluginInstance], migrations: [] });
+ await ds.initialize();
+ const runner = ds.createQueryRunner();
+ await new AddIntegrationFabric1781900000000().up(runner);
+ await runner.release();
+ service = new PluginInstanceService(ds.getRepository(PluginInstance));
+ });
+ afterEach(async () => {
+ if (ds.isInitialized) await ds.destroy();
+ });
+
+ it('create mints a new instance and rejects a duplicate with InstanceExistsError', async () => {
+ const inst = await service.create('chatwoot', 'acct1', { sessionScope: 'sess-1' });
+ expect(inst.id).toBe('chatwoot:acct1');
+ expect(inst.secret).toMatch(/^[0-9a-f]{64}$/);
+ await expect(service.create('chatwoot', 'acct1', {})).rejects.toBeInstanceOf(InstanceExistsError);
+ });
+
+ it('list returns all instances for a plugin', async () => {
+ await service.create('chatwoot', 'acct1', {});
+ await service.create('chatwoot', 'acct2', {});
+ await service.create('other', 'x', {});
+ const list = await service.list('chatwoot');
+ expect(list.map(i => i.instanceId).sort()).toEqual(['acct1', 'acct2']);
+ });
+
+ it('regenerateSecret replaces the secret with a new value', async () => {
+ const created = await service.create('chatwoot', 'acct1', {});
+ const rotated = await service.regenerateSecret('chatwoot', 'acct1');
+ expect(rotated.secret).toMatch(/^[0-9a-f]{64}$/);
+ expect(rotated.secret).not.toBe(created.secret);
+ });
+
+ it('setEnabled toggles enabled; update patches scope/config; remove deletes', async () => {
+ await service.create('chatwoot', 'acct1', { sessionScope: 'a' });
+ expect((await service.setEnabled('chatwoot', 'acct1', false))?.enabled).toBe(false);
+ const patched = await service.update('chatwoot', 'acct1', { sessionScope: 'b', config: { k: 1 } });
+ expect(patched?.sessionScope).toBe('b');
+ expect(patched?.config).toEqual({ k: 1 });
+ expect(await service.remove('chatwoot', 'acct1')).toBe(true);
+ expect(await service.resolve('chatwoot', 'acct1')).toBeNull();
+ expect(await service.remove('chatwoot', 'acct1')).toBe(false);
+ });
+});
diff --git a/src/modules/integration/plugin-instance.service.ts b/src/modules/integration/plugin-instance.service.ts
index e748ad9f6..923438ee0 100644
--- a/src/modules/integration/plugin-instance.service.ts
+++ b/src/modules/integration/plugin-instance.service.ts
@@ -6,6 +6,13 @@ import { PluginInstance } from './entities/plugin-instance.entity';
const SECRET_MASK = '***';
+export class InstanceExistsError extends Error {
+ constructor(pluginId: string, instanceId: string) {
+ super(`instance ${instanceId} already exists for plugin ${pluginId}`);
+ this.name = 'InstanceExistsError';
+ }
+}
+
@Injectable()
export class PluginInstanceService {
constructor(@InjectRepository(PluginInstance, 'data') private readonly repo: Repository<PluginInstance>) {}
@@ -39,4 +46,59 @@ export class PluginInstanceService {
maskedView(instance: PluginInstance): PluginInstance {
return { ...instance, secret: SECRET_MASK };
}
+
+ async create(
+ pluginId: string,
+ instanceId: string,
+ opts: { sessionScope?: string; verifyToken?: string; config?: Record<string, unknown> },
+ ): Promise<PluginInstance> {
+ const id = `${pluginId}:${instanceId}`;
+ if (await this.repo.findOne({ where: { id } })) throw new InstanceExistsError(pluginId, instanceId);
+ const inst = this.repo.create({
+ id,
+ pluginId,
+ instanceId,
+ sessionScope: opts.sessionScope ?? null,
+ secret: randomBytes(32).toString('hex'),
+ verifyToken: opts.verifyToken ?? null,
+ config: opts.config ?? null,
+ enabled: true,
+ });
+ return this.repo.save(inst);
+ }
+
+ list(pluginId: string): Promise<PluginInstance[]> {
+ return this.repo.find({ where: { pluginId } });
+ }
+
+ async regenerateSecret(pluginId: string, instanceId: string): Promise<PluginInstance> {
+ const inst = await this.resolve(pluginId, instanceId);
+ if (!inst) throw new Error(`instance ${instanceId} not found for plugin ${pluginId}`);
+ inst.secret = randomBytes(32).toString('hex');
+ return this.repo.save(inst);
+ }
+
+ async setEnabled(pluginId: string, instanceId: string, enabled: boolean): Promise<PluginInstance | null> {
+ const inst = await this.resolve(pluginId, instanceId);
+ if (!inst) return null;
+ inst.enabled = enabled;
+ return this.repo.save(inst);
+ }
+
+ async update(
+ pluginId: string,
+ instanceId: string,
+ patch: { sessionScope?: string; config?: Record<string, unknown> },
+ ): Promise<PluginInstance | null> {
+ const inst = await this.resolve(pluginId, instanceId);
+ if (!inst) return null;
+ if (patch.sessionScope !== undefined) inst.sessionScope = patch.sessionScope;
+ if (patch.config !== undefined) inst.config = patch.config;
+ return this.repo.save(inst);
+ }
+
+ async remove(pluginId: string, instanceId: string): Promise<boolean> {
+ const result = await this.repo.delete({ id: `${pluginId}:${instanceId}` });
+ return (result.affected ?? 0) > 0;
+ }
}
diff --git a/test/integration-instance.e2e-spec.ts b/test/integration-instance.e2e-spec.ts
new file mode 100644
index 000000000..bb4e43dd6
--- /dev/null
+++ b/test/integration-instance.e2e-spec.ts
@@ -0,0 +1,166 @@
+// archiver v8 is ESM-only; stub it so ts-jest can load the module graph.
+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));
+
+// Seed the well-known dev-admin-key BEFORE AppModule is imported (mirrors mcp-auth.e2e-spec.ts's
+// pattern of setting the enabling env var ahead of the import).
+process.env.ALLOW_DEV_API_KEY = 'true';
+process.env.BASE_URL = 'https://api.example.com';
+
+import { INestApplication, ValidationPipe } from '@nestjs/common';
+import { Test } from '@nestjs/testing';
+import request from 'supertest';
+import { App } from 'supertest/types';
+import { AppModule } from '../src/app.module';
+import { PluginLoaderService } from '../src/core/plugins/plugin-loader.service';
+
+// A stub ingress-capable plugin so the capability check passes without a real plugin on disk.
+const INGRESS_PLUGIN = {
+ manifest: { id: 'chatwoot', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress', 'conversation:send'] },
+};
+const NON_INGRESS_PLUGIN = { manifest: { id: 'plain', permissions: [] } };
+
+interface InstanceViewBody {
+ secret: string;
+ enabled: boolean;
+ sessionScope: string | null;
+ ingressUrls: Array<{ route: string; url: string }>;
+}
+
+describe('IntegrationInstanceController (e2e)', () => {
+ let app: INestApplication<App>;
+ const key = 'dev-admin-key';
+ const base = '/api/integration/plugins';
+
+ beforeAll(async () => {
+ const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
+ .overrideProvider(PluginLoaderService)
+ .useValue({
+ getPlugin: (id: string) =>
+ id === 'chatwoot' ? INGRESS_PLUGIN : id === 'plain' ? NON_INGRESS_PLUGIN : undefined,
+ dispatchWebhookForInstance: jest.fn(),
+ // EngineFactory.onModuleInit registers the built-in whatsapp-web.js/baileys engine plugins
+ // and auto-enables the configured one through these at boot; no-ops keep app boot working
+ // without a real plugin registry (enablePlugin failing is caught+logged, not fatal, but a
+ // no-op keeps the test log free of that expected-but-noisy error).
+ registerBuiltInPlugin: jest.fn(),
+ enablePlugin: jest.fn().mockResolvedValue(undefined),
+ onModuleInit: jest.fn(),
+ onModuleDestroy: jest.fn(),
+ })
+ .compile();
+ app = moduleRef.createNestApplication();
+ app.setGlobalPrefix('api');
+ app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
+ await app.init();
+ });
+
+ afterAll(async () => {
+ try {
+ await app?.close();
+ } catch {
+ /* ignore teardown-only multi-datasource quirk */
+ }
+ });
+
+ it('requires an API key (401 without one)', async () => {
+ await request(app.getHttpServer()).get(`${base}/chatwoot/instances`).expect(401);
+ });
+
+ it('mints an instance and returns the secret + ingress URLs exactly once, then masks on read', async () => {
+ const mint = await request(app.getHttpServer())
+ .post(`${base}/chatwoot/instances`)
+ .set('X-API-Key', key)
+ .send({ instanceId: 'acct1', sessionScope: 'sess-1' })
+ .expect(201);
+ const minted = mint.body as InstanceViewBody;
+ expect(minted.secret).toMatch(/^[0-9a-f]{64}$/);
+ expect(minted.ingressUrls).toEqual([
+ { route: 'chatwoot', url: 'https://api.example.com/api/ingress/chatwoot/acct1/chatwoot' },
+ ]);
+
+ const list = await request(app.getHttpServer()).get(`${base}/chatwoot/instances`).set('X-API-Key', key).expect(200);
+ expect((list.body as InstanceViewBody[])[0].secret).toBe('***');
+
+ const one = await request(app.getHttpServer())
+ .get(`${base}/chatwoot/instances/acct1`)
+ .set('X-API-Key', key)
+ .expect(200);
+ expect((one.body as InstanceViewBody).secret).toBe('***');
+ });
+
+ it('rejects minting on a non-ingress plugin (400) and a duplicate (409)', async () => {
+ await request(app.getHttpServer())
+ .post(`${base}/plain/instances`)
+ .set('X-API-Key', key)
+ .send({ instanceId: 'x' })
+ .expect(400);
+ await request(app.getHttpServer())
+ .post(`${base}/chatwoot/instances`)
+ .set('X-API-Key', key)
+ .send({ instanceId: 'acct1' })
+ .expect(409);
+ });
+
+ it('rejects minting on an unknown plugin (404)', async () => {
+ await request(app.getHttpServer())
+ .post(`${base}/nonexistent/instances`)
+ .set('X-API-Key', key)
+ .send({ instanceId: 'x' })
+ .expect(404);
+ });
+
+ it('rejects an invalid instanceId charset (400)', async () => {
+ await request(app.getHttpServer())
+ .post(`${base}/chatwoot/instances`)
+ .set('X-API-Key', key)
+ .send({ instanceId: 'bad:id' })
+ .expect(400);
+ });
+
+ it('regenerates the secret and returns it once, then masks again on the next read', async () => {
+ const regen = await request(app.getHttpServer())
+ .post(`${base}/chatwoot/instances/acct1/regenerate-secret`)
+ .set('X-API-Key', key)
+ .expect(200);
+ expect((regen.body as InstanceViewBody).secret).toMatch(/^[0-9a-f]{64}$/);
+
+ const one = await request(app.getHttpServer())
+ .get(`${base}/chatwoot/instances/acct1`)
+ .set('X-API-Key', key)
+ .expect(200);
+ expect((one.body as InstanceViewBody).secret).toBe('***');
+ });
+
+ it('patches enabled + sessionScope and returns a masked view', async () => {
+ const patched = await request(app.getHttpServer())
+ .patch(`${base}/chatwoot/instances/acct1`)
+ .set('X-API-Key', key)
+ .send({ enabled: false, sessionScope: 'sess-2' })
+ .expect(200);
+ const body = patched.body as InstanceViewBody;
+ expect(body.enabled).toBe(false);
+ expect(body.sessionScope).toBe('sess-2');
+ expect(body.secret).toBe('***');
+ });
+
+ it('404s GET/PATCH/DELETE for a missing instanceId on an ingress-capable plugin', async () => {
+ await request(app.getHttpServer())
+ .get(`${base}/chatwoot/instances/does-not-exist`)
+ .set('X-API-Key', key)
+ .expect(404);
+ await request(app.getHttpServer())
+ .patch(`${base}/chatwoot/instances/does-not-exist`)
+ .set('X-API-Key', key)
+ .send({ enabled: false })
+ .expect(404);
+ await request(app.getHttpServer())
+ .delete(`${base}/chatwoot/instances/does-not-exist`)
+ .set('X-API-Key', key)
+ .expect(404);
+ });
+
+ it('deletes the instance (204) and audits it', async () => {
+ await request(app.getHttpServer()).delete(`${base}/chatwoot/instances/acct1`).set('X-API-Key', key).expect(204);
+ await request(app.getHttpServer()).get(`${base}/chatwoot/instances/acct1`).set('X-API-Key', key).expect(404);
+ });
+});