import { BadRequestException, Injectable, UnauthorizedException, } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { createHmac } from 'crypto'; import { Repository } from 'typeorm'; import { PipelineUnits } from '../pipeline-tasks/enums/pipeline-units.enum'; import { PipelineTasksService } from '../pipeline-tasks/pipeline-tasks.service'; import { GiteaHookPayloadDto } from './dtos/gitea-hook-payload.dto'; import { CreateWebhookLogModel } from './models/create-webhook-log.model'; import { WebhookLog } from './webhook-log.entity'; @Injectable() export class WebhooksService { constructor( @InjectRepository(WebhookLog) private readonly repository: Repository, private readonly taskService: PipelineTasksService, ) {} async onCall( pipelineId: string, model: CreateWebhookLogModel, ) { if (model.sourceEvent.toLowerCase() === 'push') { const taskDto = { pipelineId, commit: model.payload.after, units: Object.values(PipelineUnits), }; await this.taskService.addTask(taskDto); return await this.repository.save( this.repository.create({ ...model, localEvent: 'create-pipeline-task', localPayload: taskDto, }), ); } else { throw new BadRequestException('无法处理的请求'); } } async verifySignature(payload: any, signature: string, secret: string) { const local = await new Promise((resolve, reject) => { const hmac = createHmac('sha256', secret); hmac.on('readable', () => { const data = hmac.read(); if (data) { resolve(data.toString('hex')); } }); hmac.on('error', (err) => { reject(err); }); hmac.write(payload); hmac.end(); }); if (local !== signature) { throw new UnauthorizedException(); } } }