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