| 1 | import { randomUUID } from 'node:crypto'; |
| 2 | |
| 3 | import { type Database, |
| 4 | import { Inject, Injectable |
| 5 | import { ConfigService } |
| 6 | import { and, desc |
| 7 | |
| 8 | import { DATABASE } |
| 9 | import { isoTimestamp } |
| 10 | import { administeredOrganization } |
| 11 | import { |
| 12 | DeliveryNotFoundError, |
| 13 | InvalidWebhookUrlError, |
| 14 | WebhookNotFoundError, |
| 15 | WebhooksNotConfiguredError, |
| 16 | } from '../../lib/webhooks/webhooks.errors.js'; |
| 17 | import { |
| 18 | newWebhookSecret, |
| 19 | sealWebhookSecret, |
| 20 | type WebhookEvent, |
| 21 | type WebhookOwner, |
| 22 | webhookSecretKey, |
| 23 | webhookUrlProblem, |
| 24 | } from '../../lib/webhooks/webhooks.js'; |
| 25 | import { RepositoryAccessService } |
| 26 | import { WebhookFanoutService } |
| 27 | import type { DeliveryAttemptDTO |
| 28 | |
| 29 | const DELIVERY_LOG_LENGTH = 50 |
| 30 | |
| 31 | const webhookColumns = { |
| 32 | id: schema.webhookEndpoint |
| 33 | url: schema.webhookEndpoint |
| 34 | // only this service writes it, from the validated list |
| 35 | events: sql<WebhookEvent |
| 36 | active: schema.webhookEndpoint |
| 37 | disabledReason: schema.webhookEndpoint |
| 38 | createdAt: isoTimestamp(schema |
| 39 | }; |
| 40 | |
| 41 | /** Webhook endpoints of a repository or an organization, and their delivery log. Admins only. */ |
| 42 | @Injectable() |
| 43 | export class WebhooksService |
| 44 | private readonly key |
| 45 | private readonly allowPrivate |
| 46 | |
| 47 | constructor( |
| 48 | @Inject(DATABASE) |
| 49 | private readonly access |
| 50 | private readonly fanout |
| 51 | config: ConfigService |
| 52 | ) { |
| 53 | this.key = |
| 54 | this.allowPrivate = |
| 55 | config.get<string |
| 56 | } |
| 57 | |
| 58 | async ofRepository({ |
| 59 | username, |
| 60 | repo, |
| 61 | requesterId, |
| 62 | }: { |
| 63 | username: string |
| 64 | repo: string |
| 65 | requesterId: string |
| 66 | }): Promise |
| 67 | const repository = |
| 68 | username, |
| 69 | repo, |
| 70 | requesterId, |
| 71 | operation: 'admin', |
| 72 | }); |
| 73 | return { repositoryId: |
| 74 | } |
| 75 | |
| 76 | async ofOrganization({ |
| 77 | slug, |
| 78 | requesterId, |
| 79 | }: { |
| 80 | slug: string |
| 81 | requesterId: string |
| 82 | }): Promise |
| 83 | const { organizationId |
| 84 | this.db, |
| 85 | slug, |
| 86 | requesterId, |
| 87 | ); |
| 88 | return { organizationId, |
| 89 | } |
| 90 | |
| 91 | async list(owner |
| 92 | const webhooks = |
| 93 | .select(webhookColumns) |
| 94 | .from(schema.webhookEndpoint |
| 95 | .where(ownedBy(owner |
| 96 | .orderBy(schema.webhookEndpoint |
| 97 | return { webhooks |
| 98 | } |
| 99 | |
| 100 | /** Sends the new endpoint a `ping`. The response is the only time anyone sees its secret. */ |
| 101 | async create( |
| 102 | owner: WebhookOwner |
| 103 | { url, events |
| 104 | ) { |
| 105 | if (!this.key |
| 106 | const problem = |
| 107 | if (problem) throw |
| 108 | |
| 109 | const secret = |
| 110 | const [webhook] |
| 111 | .insert(schema.webhookEndpoint |
| 112 | .values({ |
| 113 | repositoryId: 'repositoryId' in |
| 114 | organizationId: 'organizationId' in |
| 115 | url, |
| 116 | secret: sealWebhookSecret(this |
| 117 | events: [...new |
| 118 | }) |
| 119 | .returning(webhookColumns); |
| 120 | await this.fanout |
| 121 | return { ...webhook |
| 122 | } |
| 123 | |
| 124 | async update( |
| 125 | owner: WebhookOwner |
| 126 | webhookId: string, |
| 127 | changes: { |
| 128 | ) { |
| 129 | await this.find |
| 130 | if (changes.url |
| 131 | const problem = |
| 132 | if (problem) throw |
| 133 | } |
| 134 | |
| 135 | const [webhook] |
| 136 | .update(schema.webhookEndpoint |
| 137 | .set({ |
| 138 | url: changes.url |
| 139 | events: changes.events |
| 140 | active: changes.active |
| 141 | // turning it back on is the owner saying the problem is fixed |
| 142 | ...(changes.active |
| 143 | disabledReason: null, |
| 144 | disabledNotifiedAt: null, |
| 145 | }), |
| 146 | }) |
| 147 | .where(eq(schema |
| 148 | .returning(webhookColumns); |
| 149 | return webhook; |
| 150 | } |
| 151 | |
| 152 | /** Pending deliveries go with it. */ |
| 153 | async remove(owner |
| 154 | await this.find |
| 155 | await this.db |
| 156 | .delete(schema.webhookEndpoint |
| 157 | .where(eq(schema |
| 158 | } |
| 159 | |
| 160 | /** No overlap: a delivery sent from now on, retries included, is signed with the new secret. */ |
| 161 | async rollSecret(owner |
| 162 | if (!this.key |
| 163 | await this.find |
| 164 | const secret = |
| 165 | await this.db |
| 166 | .update(schema.webhookEndpoint |
| 167 | .set({ secret: |
| 168 | .where(eq(schema |
| 169 | return { secret |
| 170 | } |
| 171 | |
| 172 | async ping(owner |
| 173 | await this.fanout |
| 174 | } |
| 175 | |
| 176 | async deliveries(owner |
| 177 | await this.find |
| 178 | const deliveries = |
| 179 | .select({ |
| 180 | id: schema.deliveryJob |
| 181 | event: sql<string |
| 182 | status: schema.deliveryJob |
| 183 | body: sql<string |
| 184 | createdAt: isoTimestamp(schema |
| 185 | nextAttemptAt: sql< |
| 186 | string | null |
| 187 | >`case when ${schema.deliveryJob |
| 188 | attempts: sql<DeliveryAttemptDTO |
| 189 | select json_agg(json_build_object( |
| 190 | 'startedAt', ${isoTimestamp(sql`a.started_at |
| 191 | 'durationMs', a.duration_ms, |
| 192 | 'statusCode', a.status_code, |
| 193 | 'error', a.error, |
| 194 | 'requestHeaders', a.request_headers, |
| 195 | 'responseBody', a.response_body |
| 196 | ) order by a.started_at desc) |
| 197 | from ${schema.deliveryAttempt} a |
| 198 | where a.job_id = ${schema.deliveryJob}.id |
| 199 | ), '[]'::json)`, |
| 200 | }) |
| 201 | .from(schema.deliveryJob |
| 202 | .where(eq(schema |
| 203 | .orderBy(desc(schema |
| 204 | .limit(DELIVERY_LOG_LENGTH); |
| 205 | return { deliveries |
| 206 | } |
| 207 | |
| 208 | /** The same body again as a new delivery, with its own id and a fresh round of retries. */ |
| 209 | async redeliver(owner |
| 210 | await this.find |
| 211 | const [delivery] |
| 212 | .select({ |
| 213 | event: sql<string |
| 214 | body: sql<string |
| 215 | }) |
| 216 | .from(schema.deliveryJob |
| 217 | .where( |
| 218 | and( |
| 219 | eq(schema.deliveryJob |
| 220 | eq(schema.deliveryJob |
| 221 | ), |
| 222 | ); |
| 223 | if (!delivery) |
| 224 | await this.fanout |
| 225 | { |
| 226 | endpointId: webhookId, |
| 227 | ...delivery, |
| 228 | idempotencyKey: `redeliver:${deliveryId |
| 229 | }, |
| 230 | ]); |
| 231 | } |
| 232 | |
| 233 | private async find |
| 234 | const [webhook] |
| 235 | .select(webhookColumns) |
| 236 | .from(schema.webhookEndpoint |
| 237 | .where(and(eq |
| 238 | if (!webhook) |
| 239 | return webhook; |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | function ownedBy(owner: |
| 244 | return 'repositoryId' in |
| 245 | ? eq(schema. |
| 246 | : eq(schema. |
| 247 | } |