Files
waggle-os/packages/team-server/tests/routes/webhooks.test.ts
shumeiko.it c25efe6c44 refactor(server): move the team runtime into a postponed package (P1.1)
Team mode stays in the repository but is not built or shipped (ADR-0003).

- The team server (index.ts, config, db, daemons, plugins, proactive,
  routes, scheduler, services, ws, drizzle migrations) and its tests move
  from @waggle/server to packages/team-server (@waggle/team-server,
  private). It keeps its own copies of the logger and the agent-group
  executor, so it does not import @waggle/server. @clerk/fastify, bullmq,
  ioredis, postgres, drizzle-orm, drizzle-kit, cron-parser and
  @waggle/waggle-dance leave @waggle/server; the launcher drops the same
  team-only dependencies.
- build:packages no longer builds waggle-dance or the worker: nothing in
  the community edition imports them, and the worker's project reference
  would otherwise build the team server. The worker now imports from
  team-server; the team Dockerfile builds both explicitly.
- The sidecar no longer starts the team server when DATABASE_URL is set,
  and loses the team routes (/api/team/*, /api/teams), the WaggleDance
  routes and bridge (/api/waggle-dance/*), the Team server binding and
  egress guard, the WebSocket team client, the TeamSync cache and pushes,
  team audit forwarding, team workspace registration and the team
  capability-policy lookup in chat. The in-process room signal bus stays:
  agent groups, fleet runs and external tool runs use it.
  middleware/audit.ts was dead and is deleted.
- @waggle/core loses TeamSync and the teamServer part of WaggleConfig. A
  teamServer key in config.json is ignored and kept on save, as P0.1 does
  for the tier keys. Workspaces lose teamServerUrl and teamUserId; teamId
  and teamRole stay because workspaces from a shared data directory still
  carry them and the viewer write guards read them. POST /api/workspaces
  ignores team fields.
- The sidecar bundle no longer marks the team packages as external.

The agent still references the TeamSync type in orchestrator.ts and
pattern-write-back.ts; those files are being rewritten in P1.5 and drop
it there.

Logs UF-030 and UF-031 (team sync and team policy defects found while
removing the code).
2026-10-24 12:17:41 +02:00

174 lines
5.5 KiB
TypeScript

import { createHmac } from 'node:crypto';
import Fastify, { type FastifyInstance } from 'fastify';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { webhookRoutes } from '../../src/routes/webhooks.js';
const SIGNING_KEY = Buffer.from('waggle-clerk-webhook-test-secret');
const SIGNING_SECRET = `whsec_${SIGNING_KEY.toString('base64')}`;
const createEvent = {
type: 'user.created',
data: {
id: 'clerk_webhook_user',
first_name: 'Ada',
last_name: 'Lovelace',
email_addresses: [{ email_address: 'ada@example.com' }],
image_url: 'https://example.com/ada.png',
},
};
function signedHeaders(payload: object, timestamp = Math.floor(Date.now() / 1000)) {
const id = 'msg_waggle_clerk_test';
const body = JSON.stringify(payload);
const signature = createHmac('sha256', SIGNING_KEY)
.update(`${id}.${timestamp}.${body}`)
.digest('base64');
return {
'svix-id': id,
'svix-timestamp': String(timestamp),
'svix-signature': `v1,${signature}`,
};
}
function createDbDouble() {
const onConflictDoNothing = vi.fn().mockResolvedValue(undefined);
const values = vi.fn(() => ({ onConflictDoNothing }));
const insert = vi.fn(() => ({ values }));
const updateWhere = vi.fn().mockResolvedValue(undefined);
const set = vi.fn(() => ({ where: updateWhere }));
const update = vi.fn(() => ({ set }));
const deleteWhere = vi.fn().mockResolvedValue(undefined);
const deleteFrom = vi.fn(() => ({ where: deleteWhere }));
return {
db: { insert, update, delete: deleteFrom },
mutations: { insert, values, update, deleteFrom },
};
}
describe('Clerk webhook authenticity', () => {
let app: FastifyInstance;
let mutations: ReturnType<typeof createDbDouble>['mutations'];
let originalSigningSecret: string | undefined;
beforeEach(async () => {
originalSigningSecret = process.env.CLERK_WEBHOOK_SIGNING_SECRET;
process.env.CLERK_WEBHOOK_SIGNING_SECRET = SIGNING_SECRET;
const dbDouble = createDbDouble();
mutations = dbDouble.mutations;
app = Fastify();
app.decorate('db', dbDouble.db as never);
await app.register(webhookRoutes);
});
afterEach(async () => {
await app.close();
if (originalSigningSecret === undefined) {
delete process.env.CLERK_WEBHOOK_SIGNING_SECRET;
} else {
process.env.CLERK_WEBHOOK_SIGNING_SECRET = originalSigningSecret;
}
});
it.each([
['user.created', createEvent.data],
['user.updated', createEvent.data],
['user.deleted', { id: createEvent.data.id }],
])('rejects an unsigned %s event before any database mutation', async (type, data) => {
const response = await app.inject({
method: 'POST',
url: '/api/webhooks/clerk',
payload: { type, data },
});
expect(response.statusCode).toBe(400);
expect(response.json()).toEqual({ error: 'Invalid webhook signature' });
expect(mutations.insert).not.toHaveBeenCalled();
expect(mutations.update).not.toHaveBeenCalled();
expect(mutations.deleteFrom).not.toHaveBeenCalled();
});
it('rejects an otherwise signed event when its timestamp is stale', async () => {
const staleTimestamp = Math.floor(Date.now() / 1000) - 301;
const response = await app.inject({
method: 'POST',
url: '/api/webhooks/clerk',
headers: signedHeaders(createEvent, staleTimestamp),
payload: createEvent,
});
expect(response.statusCode).toBe(400);
expect(mutations.insert).not.toHaveBeenCalled();
});
it('rejects a signature that was generated for a different body', async () => {
const tamperedEvent = {
...createEvent,
data: { ...createEvent.data, email_addresses: [{ email_address: 'attacker@example.com' }] },
};
const response = await app.inject({
method: 'POST',
url: '/api/webhooks/clerk',
headers: signedHeaders(createEvent),
payload: tamperedEvent,
});
expect(response.statusCode).toBe(400);
expect(mutations.insert).not.toHaveBeenCalled();
});
it('fails closed when the Clerk webhook signing secret is not configured', async () => {
delete process.env.CLERK_WEBHOOK_SIGNING_SECRET;
const response = await app.inject({
method: 'POST',
url: '/api/webhooks/clerk',
headers: signedHeaders(createEvent),
payload: createEvent,
});
expect(response.statusCode).toBe(400);
expect(mutations.insert).not.toHaveBeenCalled();
});
it('preserves a correctly signed user.created event and its field mapping', async () => {
const response = await app.inject({
method: 'POST',
url: '/api/webhooks/clerk',
headers: signedHeaders(createEvent),
payload: createEvent,
});
expect(response.statusCode).toBe(200);
expect(response.json()).toEqual({ received: true });
expect(mutations.values).toHaveBeenCalledWith({
clerkId: 'clerk_webhook_user',
displayName: 'Ada Lovelace',
email: 'ada@example.com',
avatarUrl: 'https://example.com/ada.png',
});
});
it('preserves correctly signed user.updated and user.deleted events', async () => {
const updateEvent = { ...createEvent, type: 'user.updated' };
const deleteEvent = { type: 'user.deleted', data: { id: createEvent.data.id } };
for (const event of [updateEvent, deleteEvent]) {
const response = await app.inject({
method: 'POST',
url: '/api/webhooks/clerk',
headers: signedHeaders(event),
payload: event,
});
expect(response.statusCode).toBe(200);
}
expect(mutations.update).toHaveBeenCalledOnce();
expect(mutations.deleteFrom).toHaveBeenCalledOnce();
});
});