forked from veridatum-labs/earnproof-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhooks.controller.ts
More file actions
460 lines (441 loc) · 14.1 KB
/
Copy pathwebhooks.controller.ts
File metadata and controls
460 lines (441 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import {
Body,
Controller,
Delete,
ForbiddenException,
Get,
HttpStatus,
Param,
Patch,
Post,
UseGuards,
} from "@nestjs/common";
import {
ApiBearerAuth,
ApiForbiddenResponse,
ApiNotFoundResponse,
ApiOperation,
ApiParam,
ApiResponse,
ApiTags,
ApiUnauthorizedResponse,
} from "@nestjs/swagger";
import { AuthenticatedUser } from "../auth/auth.types";
import { CurrentUser } from "../common/decorators/current-user.decorator";
import { AuthGuard } from "../common/guards/auth.guard";
import { PrismaService } from "../database/prisma.service";
import { ApiErrorDto } from "../common/dto/api-error.dto";
import { SESSION_AUTH_SCHEME } from "../common/swagger/security-schemes";
import { CreateWebhookDto } from "./dto/create-webhook.dto";
import { UpdateWebhookEventsDto } from "./dto/update-webhook-events.dto";
import { WebhooksService } from "./webhooks.service";
/**
* Resolves the organisation ID from the current authenticated user.
*
* The JWT carries userId only. We query the first ACTIVE organisation
* the user belongs to. In a multi-org scenario the org could be passed
* as a path or query param — kept simple here per scope constraints.
*/
@ApiTags("webhooks")
@ApiBearerAuth(SESSION_AUTH_SCHEME)
@ApiUnauthorizedResponse({
description: "Missing, invalid, or expired session token.",
type: ApiErrorDto,
})
@ApiForbiddenResponse({
description:
"The session is valid but belongs to no active organisation, or the "
+ "webhook belongs to another organisation.",
type: ApiErrorDto,
})
@UseGuards(AuthGuard)
@Controller("webhooks")
export class WebhooksController {
constructor(
private readonly webhooksService: WebhooksService,
private readonly prisma: PrismaService,
) {}
// ---------------------------------------------------------------------------
// Endpoint management
// ---------------------------------------------------------------------------
@Post()
@ApiOperation({
summary: "Create a webhook endpoint",
description:
"Registers an HTTPS endpoint for the caller's organisation and returns its " +
"signing secret. The secret is shown exactly once: store it before leaving " +
"the response, and rotate the endpoint if it is lost.",
})
@ApiResponse({
status: HttpStatus.CREATED,
description:
"Endpoint registered. `signingSecret` is returned once and never again.",
schema: {
example: {
id: "ckv8v6h2b0002qzrm7t4k9xza",
url: "https://example.com/webhooks/earnproof",
events: ["proof.created", "proof.verified"],
status: "ACTIVE",
createdAt: "2026-08-24T12:00:00.000Z",
signingSecret:
"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
},
},
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
description:
"The URL is not HTTPS, or the event list is empty or names an unknown " +
"event type.",
type: ApiErrorDto,
})
async create(@CurrentUser() user: AuthenticatedUser, @Body() dto: CreateWebhookDto) {
const orgId = await this.requireOrgId(user);
return this.webhooksService.create(orgId, dto);
}
@Get()
@ApiOperation({
summary: "List webhook endpoints for your organisation",
description:
"Returns every endpoint registered by the caller's organisation. Signing " +
"secrets are never included.",
})
@ApiResponse({
status: HttpStatus.OK,
description: "Endpoints owned by the caller's organisation.",
schema: {
example: [
{
id: "ckv8v6h2b0002qzrm7t4k9xza",
url: "https://example.com/webhooks/earnproof",
events: ["proof.created", "proof.verified"],
status: "ACTIVE",
createdAt: "2026-08-24T12:00:00.000Z",
updatedAt: "2026-08-24T12:00:00.000Z",
},
],
},
})
async list(@CurrentUser() user: AuthenticatedUser) {
const orgId = await this.requireOrgId(user);
return this.webhooksService.listForOrg(orgId);
}
@Get(":id")
@ApiOperation({
summary: "Get a webhook endpoint",
description: "Returns one endpoint owned by the caller's organisation.",
})
@ApiParam({
name: "id",
description: "Webhook endpoint identifier.",
example: "ckv8v6h2b0002qzrm7t4k9xza",
})
@ApiResponse({
status: HttpStatus.OK,
description: "The endpoint.",
schema: {
example: {
id: "ckv8v6h2b0002qzrm7t4k9xza",
url: "https://example.com/webhooks/earnproof",
events: ["proof.created", "proof.verified"],
status: "ACTIVE",
createdAt: "2026-08-24T12:00:00.000Z",
updatedAt: "2026-08-24T12:00:00.000Z",
},
},
})
@ApiNotFoundResponse({
description: "No such endpoint in the caller's organisation.",
type: ApiErrorDto,
})
async get(@CurrentUser() user: AuthenticatedUser, @Param("id") id: string) {
const orgId = await this.requireOrgId(user);
return this.webhooksService.getForOrg(orgId, id);
}
@Patch(":id/events")
@ApiOperation({
summary: "Update event subscriptions",
description:
"Replaces the endpoint's subscription set. The list is a replacement, not " +
"a delta: events omitted here stop being delivered.",
})
@ApiParam({
name: "id",
description: "Webhook endpoint identifier.",
example: "ckv8v6h2b0002qzrm7t4k9xza",
})
@ApiResponse({
status: HttpStatus.OK,
description: "Subscriptions replaced.",
schema: {
example: {
id: "ckv8v6h2b0002qzrm7t4k9xza",
url: "https://example.com/webhooks/earnproof",
events: ["proof.revoked"],
status: "ACTIVE",
updatedAt: "2026-08-24T13:05:00.000Z",
},
},
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
description: "The event list is empty or names an unknown event type.",
type: ApiErrorDto,
})
@ApiNotFoundResponse({
description: "No such endpoint in the caller's organisation.",
type: ApiErrorDto,
})
async updateEvents(
@CurrentUser() user: AuthenticatedUser,
@Param("id") id: string,
@Body() dto: UpdateWebhookEventsDto,
) {
const orgId = await this.requireOrgId(user);
return this.webhooksService.updateEvents(orgId, id, dto);
}
@Post(":id/rotate-secret")
@ApiOperation({
summary: "Rotate the signing secret (returns new secret once)",
description:
"Issues a new signing secret and invalidates the old one immediately. " +
"Deliveries already in flight fail their current attempt and are retried " +
"with the new secret, so rotate before the old secret is discarded.",
})
@ApiParam({
name: "id",
description: "Webhook endpoint identifier.",
example: "ckv8v6h2b0002qzrm7t4k9xza",
})
@ApiResponse({
status: HttpStatus.CREATED,
description: "New secret issued. Returned once and never again.",
schema: {
example: {
webhookId: "ckv8v6h2b0002qzrm7t4k9xza",
signingSecret:
"3b1f6c0d9e5a4728b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f60718293a4b5c6d",
rotatedAt: "2026-08-24T13:10:00.000Z",
note:
"Any in-flight deliveries signed with the old secret will fail their current attempt. They will be retried with the new secret.",
},
},
})
@ApiNotFoundResponse({
description: "No such endpoint in the caller's organisation.",
type: ApiErrorDto,
})
async rotateSecret(@CurrentUser() user: AuthenticatedUser, @Param("id") id: string) {
const orgId = await this.requireOrgId(user);
return this.webhooksService.rotateSecret(orgId, id);
}
@Patch(":id/disable")
@ApiOperation({
summary: "Disable a webhook endpoint",
description:
"Stops delivery without deleting the endpoint or its history. Reversible " +
"with the enable route.",
})
@ApiParam({
name: "id",
description: "Webhook endpoint identifier.",
example: "ckv8v6h2b0002qzrm7t4k9xza",
})
@ApiResponse({
status: HttpStatus.OK,
description: "Endpoint disabled.",
schema: {
example: {
id: "ckv8v6h2b0002qzrm7t4k9xza",
status: "DISABLED",
updatedAt: "2026-08-24T13:20:00.000Z",
},
},
})
@ApiNotFoundResponse({
description: "No such endpoint in the caller's organisation.",
type: ApiErrorDto,
})
async disable(@CurrentUser() user: AuthenticatedUser, @Param("id") id: string) {
const orgId = await this.requireOrgId(user);
return this.webhooksService.disable(orgId, id);
}
@Patch(":id/enable")
@ApiOperation({
summary: "Re-enable a webhook endpoint",
description: "Resumes delivery for a previously disabled endpoint.",
})
@ApiParam({
name: "id",
description: "Webhook endpoint identifier.",
example: "ckv8v6h2b0002qzrm7t4k9xza",
})
@ApiResponse({
status: HttpStatus.OK,
description: "Endpoint re-enabled.",
schema: {
example: {
id: "ckv8v6h2b0002qzrm7t4k9xza",
status: "ACTIVE",
updatedAt: "2026-08-24T13:25:00.000Z",
},
},
})
@ApiNotFoundResponse({
description: "No such endpoint in the caller's organisation.",
type: ApiErrorDto,
})
async enable(@CurrentUser() user: AuthenticatedUser, @Param("id") id: string) {
const orgId = await this.requireOrgId(user);
return this.webhooksService.enable(orgId, id);
}
@Delete(":id")
@ApiOperation({
summary: "Delete a webhook endpoint",
description:
"Removes the endpoint. Disable it instead when the delivery history still " +
"matters.",
})
@ApiParam({
name: "id",
description: "Webhook endpoint identifier.",
example: "ckv8v6h2b0002qzrm7t4k9xza",
})
@ApiResponse({
status: HttpStatus.OK,
description: "Endpoint deleted.",
schema: {
example: { deleted: true, webhookId: "ckv8v6h2b0002qzrm7t4k9xza" },
},
})
@ApiNotFoundResponse({
description: "No such endpoint in the caller's organisation.",
type: ApiErrorDto,
})
async delete(@CurrentUser() user: AuthenticatedUser, @Param("id") id: string) {
const orgId = await this.requireOrgId(user);
return this.webhooksService.delete(orgId, id);
}
// ---------------------------------------------------------------------------
// Delivery observability
// ---------------------------------------------------------------------------
@Get(":id/deliveries")
@ApiOperation({
summary: "List delivery records for a webhook endpoint",
description:
"The 100 most recent delivery attempts, newest first. Request bodies and " +
"signing headers are never stored, so nothing here can leak a secret.",
})
@ApiParam({
name: "id",
description: "Webhook endpoint identifier.",
example: "ckv8v6h2b0002qzrm7t4k9xza",
})
@ApiResponse({
status: HttpStatus.OK,
description: "Recent delivery attempts.",
schema: {
example: [
{
id: "ckv8v6h2b0003qzrm4d8n2plq",
eventType: "proof.created",
eventId: "evt_01hxk8s3n7q9v2m4c6d8e0f2g4",
attempt: 1,
status: "DELIVERED",
statusCode: 200,
responseBody: '{"ok":true}',
durationMs: 142,
failureReason: null,
replayOf: null,
replayedBy: null,
deliveredAt: "2026-08-24T12:30:01.000Z",
nextRetryAt: null,
createdAt: "2026-08-24T12:30:00.000Z",
},
],
},
})
@ApiNotFoundResponse({
description: "No such endpoint in the caller's organisation.",
type: ApiErrorDto,
})
async listDeliveries(@CurrentUser() user: AuthenticatedUser, @Param("id") id: string) {
const orgId = await this.requireOrgId(user);
return this.webhooksService.listDeliveries(orgId, id);
}
// ---------------------------------------------------------------------------
// Manual replay
// ---------------------------------------------------------------------------
@Post("deliveries/:deliveryId/replay")
@ApiOperation({
summary: "Manually replay a delivery (DEVELOPER or ADMIN only)",
description:
"Re-sends a stored delivery to its endpoint as a new attempt, keeping the " +
"original event identifier so a receiver that de-duplicates on it can " +
"recognise the replay. The replay is recorded against the acting user.",
})
@ApiParam({
name: "deliveryId",
description: "Delivery record to replay.",
example: "ckv8v6h2b0003qzrm4d8n2plq",
})
@ApiResponse({
status: HttpStatus.CREATED,
description: "Replay queued.",
schema: {
example: {
replayDeliveryId: "ckv8v6h2b0004qzrm1s6y3wkc",
originalDeliveryId: "ckv8v6h2b0003qzrm4d8n2plq",
eventId: "evt_01hxk8s3n7q9v2m4c6d8e0f2g4",
eventType: "proof.created",
replayedBy: "ckv8v6h2b0000qzrmn831i7rn",
replayedAt: "2026-08-24T14:00:00.000Z",
},
},
})
@ApiForbiddenResponse({
description:
"The caller is not a DEVELOPER or ADMIN, or the delivery belongs to " +
"another organisation.",
type: ApiErrorDto,
})
@ApiNotFoundResponse({
description: "No such delivery record.",
type: ApiErrorDto,
})
async replayDelivery(
@CurrentUser() user: AuthenticatedUser,
@Param("deliveryId") deliveryId: string,
) {
this.requirePrivilegedRole(user);
const orgId = await this.requireOrgId(user);
return this.webhooksService.replayDelivery(orgId, deliveryId, user.id);
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
private async requireOrgId(user: AuthenticatedUser): Promise<string> {
// Find an active organization the user belongs to
const userWithOrgs = await this.prisma.user.findUnique({
where: { id: user.id },
select: {
organizations: {
where: { status: "ACTIVE" },
select: { id: true },
take: 1,
},
},
});
if (!userWithOrgs?.organizations?.[0]) {
throw new ForbiddenException("No active organisation found for this user");
}
return userWithOrgs.organizations[0].id;
}
private requirePrivilegedRole(user: AuthenticatedUser): void {
if (user.role !== "DEVELOPER" && user.role !== "ADMIN") {
throw new ForbiddenException(
"Only DEVELOPER or ADMIN users may replay webhook deliveries",
);
}
}
}