diff --git a/README.md b/README.md index 5e0dcc2..bbc0314 100644 --- a/README.md +++ b/README.md @@ -159,4 +159,19 @@ Jenkins 自动同步器每分钟顺序检查各纳管 job 的最新 1 次构建 - 回滚复用现有构建部署流程并锁定历史 SHA,不能仅重建 `master/develop`。无法核实旧构建的实际 SHA/标签时拒绝;不会撤销数据库迁移或外部数据。 - Jenkins 任务必须支持 `DEPLOY_COMMIT`。`deploy/enable-pinned-checkout.py --jobs-json '["folder/job"]'` 默认仅预检;加 `--apply` 后备份原 XML,保留既有参数选择器,加入精确 checkout 阶段和同 job 串行构建。该脚本使用服务端已有 Jenkins 环境凭据,不能在参数中传密钥。 -没有新增表、数据库迁移、依赖、向量库或常驻服务。 +上述精确发布与回滚能力没有新增表、数据库迁移、依赖、向量库或常驻服务。 + +## 通知偏好与模板 + +通知配置由超级管理员维护,沿用当前服务端 provider / webhook,不向前端返回任何凭据: + +| 接口 | 用途 | +| --- | --- | +| `GET /notifications/config` | 读取偏好、版本号、字段/事件/样式目录和通道状态 | +| `PUT /notifications/config` | 提交 `{preferences, version}`;并发修改返回 409 | +| `POST /notifications/config/preview` | 提交 `{preferences, event}`,使用明确标注的示例生成预览,不发送消息 | +| `POST /notifications/config/test` | 同预览并要求 `confirmed=true`,发送一条带测试标记的消息,10 秒限流 | + +支持通知开关、六种发布时机、十一种显示字段及顺序、三种 Markdown 样式、emoji、标题/正文变量、信尾和链接开关。预览、真实事件和 outbox 重试共用 `NotificationTemplateService`。模板可使用 `{{emoji}}`、`{{eventTitle}}`、`{{greeting}}`、`{{fields}}`、`{{links}}` 和已勾选字段名;空正文使用预设排版。未勾选或缺失字段为空,HTTP(S) 之外的链接不会输出。内容按企微 Markdown 字节上限提前校验;企微响应必须同时满足 HTTP 成功和 `errcode=0`。 + +通知偏好经 Prisma 存入 `notification_configs`,上线需执行 `20261028030000_notification_config` 迁移并生成 Prisma Client;未启用数据库的本地模式仅在当前进程保留偏好。保存与测试均记录脱敏审计。关闭的通知时机不创建新的 outbox;已有相应失败消息停止自动重试,不会重新开启历史补发。 diff --git a/prisma/migrations/20261028030000_notification_config/migration.sql b/prisma/migrations/20261028030000_notification_config/migration.sql new file mode 100644 index 0000000..fb2eb6f --- /dev/null +++ b/prisma/migrations/20261028030000_notification_config/migration.sql @@ -0,0 +1,8 @@ +CREATE TABLE `notification_configs` ( + `id` VARCHAR(191) NOT NULL DEFAULT 'system', + `preferences` JSON NOT NULL, + `version` INTEGER NOT NULL DEFAULT 1, + `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updatedAt` DATETIME(3) NOT NULL, + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index f6a008d..938a802 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -322,6 +322,16 @@ model AgentInvocation { @@map("agent_invocations") } +model NotificationConfig { + id String @id @default("system") + preferences Json + version Int @default(1) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@map("notification_configs") +} + model OutboxMessage { id String @id @default(cuid()) deployRunId String? diff --git a/src/notifications/config/notification-config.controller.ts b/src/notifications/config/notification-config.controller.ts new file mode 100644 index 0000000..2ae43bc --- /dev/null +++ b/src/notifications/config/notification-config.controller.ts @@ -0,0 +1,101 @@ +import { + Body, + Controller, + Get, + Post, + Put, + Req, + UseGuards, +} from '@nestjs/common'; +import { ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger'; +import type { SchemaObject } from '@nestjs/swagger/dist/interfaces/open-api-spec.interface'; +import { z } from 'zod'; +import { AdminOnlyMessage } from '../../auth/admin-only-message.decorator'; +import { AuthGuard } from '../../auth/auth.guard'; +import { + AuthenticatedUser, + AuthRequestContext, + RequestWithUser, +} from '../../auth/auth.types'; +import { CurrentUser } from '../../auth/current-user.decorator'; +import { PasswordChangeGuard } from '../../auth/password-change.guard'; +import { SuperAdminGuard } from '../../auth/super-admin.guard'; +import { resolveRequestId } from '../../common/http/request-id'; +import { ZodValidationPipe } from '../../common/pipes/zod-validation.pipe'; +import { + PreviewNotificationInput, + previewNotificationSchema, + SaveNotificationConfigInput, + saveNotificationConfigSchema, + TestNotificationInput, + testNotificationSchema, +} from './notification-config.dto'; +import { NotificationConfigService } from './notification-config.service'; + +@ApiTags('通知配置') +@Controller('notifications/config') +@UseGuards(AuthGuard, PasswordChangeGuard, SuperAdminGuard) +@AdminOnlyMessage('仅超级管理员可维护通知配置') +export class NotificationConfigController { + constructor(private readonly service: NotificationConfigService) {} + @Get() + @ApiOperation({ summary: '读取通知偏好、字段目录和通道状态,不返回 webhook' }) + getConfig() { + return this.service.getConfig(); + } + @Put() + @ApiBody({ + schema: z.toJSONSchema(saveNotificationConfigSchema, { + target: 'openapi-3.0', + }) as SchemaObject, + }) + @ApiOperation({ + summary: '保存通知时机、显示字段和模板(version 用于并发校验)', + }) + save( + @Body(new ZodValidationPipe(saveNotificationConfigSchema)) + input: SaveNotificationConfigInput, + @CurrentUser() user: AuthenticatedUser, + @Req() request: RequestWithUser, + ) { + return this.service.save(input, user, this.context(request)); + } + @Post('preview') + @ApiBody({ + schema: z.toJSONSchema(previewNotificationSchema, { + target: 'openapi-3.0', + }) as SchemaObject, + }) + @ApiOperation({ summary: '使用草稿与示例数据生成预览,不发送消息' }) + preview( + @Body(new ZodValidationPipe(previewNotificationSchema)) + input: PreviewNotificationInput, + ) { + return this.service.preview(input); + } + @Post('test') + @ApiBody({ + schema: z.toJSONSchema(testNotificationSchema, { + target: 'openapi-3.0', + }) as SchemaObject, + }) + @ApiOperation({ + summary: '显式确认后发送一条带测试标记的草稿消息,10 秒限流', + }) + test( + @Body(new ZodValidationPipe(testNotificationSchema)) + input: TestNotificationInput, + @CurrentUser() user: AuthenticatedUser, + @Req() request: RequestWithUser, + ) { + return this.service.test(input, user, this.context(request)); + } + private context(request: RequestWithUser): AuthRequestContext { + const userAgent = request.headers['user-agent']; + return { + requestId: resolveRequestId(request.headers), + sourceIp: request.ip ?? request.socket?.remoteAddress, + userAgent: Array.isArray(userAgent) ? userAgent[0] : userAgent, + }; + } +} diff --git a/src/notifications/config/notification-config.dto.ts b/src/notifications/config/notification-config.dto.ts new file mode 100644 index 0000000..38b6885 --- /dev/null +++ b/src/notifications/config/notification-config.dto.ts @@ -0,0 +1,71 @@ +import { z } from 'zod'; +import { + notificationEvents, + notificationFields, + templateVariables, +} from './notification-config.types'; + +const template = (max: number) => + z + .string() + .max(max) + .refine( + (value) => + [...value.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].every((match) => + (templateVariables as readonly string[]).includes(match[1]), + ), + '模板包含不支持的变量', + ); + +export const notificationPreferencesSchema = z + .object({ + enabled: z.boolean(), + events: z + .array(z.enum(notificationEvents)) + .max(notificationEvents.length) + .refine((v) => new Set(v).size === v.length), + fields: z + .array(z.enum(notificationFields)) + .max(notificationFields.length) + .refine((v) => new Set(v).size === v.length), + style: z.enum(['cozy', 'simple', 'compact']), + emojiEnabled: z.boolean(), + titleTemplate: template(120).refine( + (v) => v.trim().length > 0 && !/[\r\n]/.test(v), + '请填写单行标题', + ), + bodyTemplate: template(1600), + footer: z.string().max(200), + includeDetailLink: z.boolean(), + includeBuildLink: z.boolean(), + }) + .strict() + .refine((v) => !v.enabled || v.events.length > 0, { + message: '开启通知时至少选择一个通知时机', + path: ['events'], + }); + +export const saveNotificationConfigSchema = z + .object({ + preferences: notificationPreferencesSchema, + version: z.number().int().nonnegative(), + }) + .strict(); +export const previewNotificationSchema = z + .object({ + preferences: notificationPreferencesSchema, + event: z.enum(notificationEvents), + }) + .strict(); +export const testNotificationSchema = previewNotificationSchema + .extend({ + confirmed: z.literal(true), + }) + .strict(); +export type SaveNotificationConfigInput = z.infer< + typeof saveNotificationConfigSchema +>; +export type PreviewNotificationInput = z.infer< + typeof previewNotificationSchema +>; +export type TestNotificationInput = z.infer; diff --git a/src/notifications/config/notification-config.repository.spec.ts b/src/notifications/config/notification-config.repository.spec.ts new file mode 100644 index 0000000..ea02bfa --- /dev/null +++ b/src/notifications/config/notification-config.repository.spec.ts @@ -0,0 +1,61 @@ +import { ConfigService } from '@nestjs/config'; +import { EnvConfig } from '../../config/env.schema'; +import { PrismaService } from '../../prisma/prisma.service'; +import { NotificationConfigRepository } from './notification-config.repository'; +import { defaultNotificationPreferences } from './notification-config.types'; + +describe('NotificationConfigRepository', () => { + it('saves local preferences and rejects stale versions without losing newer settings', async () => { + const config = { get: () => false } as unknown as ConfigService< + EnvConfig, + true + >; + const repository = new NotificationConfigRepository( + config, + {} as PrismaService, + ); + const initial = await repository.getConfig(); + expect(initial.version).toBe(0); + const saved = await repository.save( + { ...defaultNotificationPreferences, style: 'compact' }, + 0, + ); + expect(saved.version).toBe(1); + await expect( + repository.save(defaultNotificationPreferences, 0), + ).rejects.toMatchObject({ code: 'CONFLICT' }); + expect((await repository.getConfig()).preferences.style).toBe('compact'); + }); + it('reads persistent preferences through Prisma and uses version matching for writes', async () => { + const updateMany = jest.fn(() => Promise.resolve({ count: 0 })); + const prisma = { + notificationConfig: { + findUnique: jest.fn(() => + Promise.resolve({ + preferences: defaultNotificationPreferences, + version: 3, + updatedAt: new Date(), + }), + ), + }, + $transaction: jest.fn((callback: (tx: unknown) => Promise) => + callback({ notificationConfig: { updateMany } }), + ), + }; + const config = { get: () => true } as unknown as ConfigService< + EnvConfig, + true + >; + const repository = new NotificationConfigRepository( + config, + prisma as unknown as PrismaService, + ); + expect((await repository.getConfig()).version).toBe(3); + await expect( + repository.save(defaultNotificationPreferences, 2), + ).rejects.toMatchObject({ code: 'CONFLICT' }); + expect(updateMany).toHaveBeenCalledWith( + expect.objectContaining({ where: { id: 'system', version: 2 } }), + ); + }); +}); diff --git a/src/notifications/config/notification-config.repository.ts b/src/notifications/config/notification-config.repository.ts new file mode 100644 index 0000000..38543e1 --- /dev/null +++ b/src/notifications/config/notification-config.repository.ts @@ -0,0 +1,93 @@ +import { Injectable } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { Prisma } from '@prisma/client'; +import { AppError } from '../../common/errors/app-error'; +import { EnvConfig } from '../../config/env.schema'; +import { PrismaService } from '../../prisma/prisma.service'; +import { notificationPreferencesSchema } from './notification-config.dto'; +import { + defaultNotificationPreferences, + NotificationPreferences, + StoredNotificationConfig, +} from './notification-config.types'; + +@Injectable() +export class NotificationConfigRepository { + private memory?: StoredNotificationConfig; + + constructor( + private readonly config: ConfigService, + private readonly prisma: PrismaService, + ) {} + + async getConfig(): Promise { + if (!this.useDatabase()) return this.memory ?? this.defaults(); + const row = await this.prisma.notificationConfig.findUnique({ + where: { id: 'system' }, + }); + return row + ? { + preferences: notificationPreferencesSchema.parse(row.preferences), + version: row.version, + updatedAt: row.updatedAt.toISOString(), + } + : this.defaults(); + } + + async save( + preferences: NotificationPreferences, + version: number, + ): Promise { + if (!this.useDatabase()) { + if ((this.memory?.version ?? 0) !== version) this.conflict(); + this.memory = { + preferences: structuredClone(preferences), + version: version + 1, + updatedAt: new Date().toISOString(), + }; + return this.memory; + } + try { + await this.prisma.$transaction(async (tx) => { + const data = JSON.parse( + JSON.stringify(preferences), + ) as Prisma.InputJsonValue; + if (version === 0) { + await tx.notificationConfig.create({ + data: { id: 'system', preferences: data }, + }); + } else { + const result = await tx.notificationConfig.updateMany({ + where: { id: 'system', version }, + data: { preferences: data, version: { increment: 1 } }, + }); + if (result.count !== 1) this.conflict(); + } + }); + } catch (error) { + if ( + error instanceof Prisma.PrismaClientKnownRequestError && + error.code === 'P2002' + ) + this.conflict(); + throw error; + } + return this.getConfig(); + } + + private defaults(): StoredNotificationConfig { + return { + preferences: structuredClone(defaultNotificationPreferences), + version: 0, + }; + } + private conflict(): never { + throw new AppError('CONFLICT', '通知配置已被更新,请重新加载后再保存', 409); + } + private useDatabase(): boolean { + return ( + this.config.get('USE_DATABASE_READS', { infer: true }) && + Boolean(this.config.get('DATABASE_URL', { infer: true })) + ); + } +} diff --git a/src/notifications/config/notification-config.service.spec.ts b/src/notifications/config/notification-config.service.spec.ts new file mode 100644 index 0000000..83676ba --- /dev/null +++ b/src/notifications/config/notification-config.service.spec.ts @@ -0,0 +1,96 @@ +import { ConfigService } from '@nestjs/config'; +import { AuditService } from '../../audit/audit.service'; +import { AuthenticatedUser } from '../../auth/auth.types'; +import { EnvConfig } from '../../config/env.schema'; +import { DeployNotificationService } from '../wecom/deploy-notification.service'; +import { NotificationConfigController } from './notification-config.controller'; +import { NotificationConfigRepository } from './notification-config.repository'; +import { NotificationConfigService } from './notification-config.service'; +import { defaultNotificationPreferences } from './notification-config.types'; +import { NotificationTemplateService } from './notification-template.service'; + +describe('NotificationConfigService', () => { + const user = { id: 'admin', account: 'admin' } as AuthenticatedUser; + const input = () => ({ + preferences: structuredClone(defaultNotificationPreferences), + event: 'succeeded' as const, + confirmed: true as const, + }); + function create() { + const delivery = { + healthSummary: jest.fn(() => ({ status: 'ok', provider: 'wecom' })), + sendTestMessage: jest.fn(() => Promise.resolve()), + }; + const audit = { record: jest.fn(() => Promise.resolve()) }; + const config = { get: () => undefined } as unknown as ConfigService< + EnvConfig, + true + >; + const repository = { + getConfig: jest.fn(() => + Promise.resolve({ + preferences: defaultNotificationPreferences, + version: 1, + }), + ), + }; + const service = new NotificationConfigService( + repository as unknown as NotificationConfigRepository, + new NotificationTemplateService(), + delivery as unknown as DeployNotificationService, + audit as unknown as AuditService, + config, + ); + return { service, delivery, audit }; + } + it('previews drafts without saving or sending', () => { + const { service, delivery, audit } = create(); + expect(service.preview(input()).sample).toBe(true); + expect(delivery.sendTestMessage).not.toHaveBeenCalled(); + expect(audit.record).not.toHaveBeenCalled(); + }); + it('sends one confirmed draft test and limits repeat clicks', async () => { + const { service, delivery, audit } = create(); + await expect(service.test(input(), user, {})).resolves.toMatchObject({ + success: true, + }); + expect(delivery.sendTestMessage).toHaveBeenCalledTimes(1); + await expect(service.test(input(), user, {})).rejects.toMatchObject({ + code: 'RATE_LIMITED', + }); + expect(audit.record).toHaveBeenCalledWith( + expect.objectContaining({ + action: 'NOTIFICATION_TEST_SENT', + actorId: 'admin', + }), + ); + }); + it('requires explicit confirmation and records failed deliveries without reporting success', async () => { + const { service, delivery, audit } = create(); + await expect( + service.test( + { ...input(), confirmed: false } as unknown as ReturnType, + user, + {}, + ), + ).rejects.toMatchObject({ code: 'VALIDATION_FAILED' }); + delivery.sendTestMessage.mockRejectedValueOnce(new Error('unavailable')); + await expect(service.test(input(), user, {})).rejects.toThrow( + 'unavailable', + ); + expect(audit.record).toHaveBeenCalledWith( + expect.objectContaining({ action: 'NOTIFICATION_TEST_FAILED' }), + ); + }); + it('protects all configuration and test actions with the super-admin guard', () => { + const guards = Reflect.getMetadata( + '__guards__', + NotificationConfigController, + ) as { name: string }[]; + expect(guards.map((guard) => guard.name)).toEqual([ + 'AuthGuard', + 'PasswordChangeGuard', + 'SuperAdminGuard', + ]); + }); +}); diff --git a/src/notifications/config/notification-config.service.ts b/src/notifications/config/notification-config.service.ts new file mode 100644 index 0000000..7a357e0 --- /dev/null +++ b/src/notifications/config/notification-config.service.ts @@ -0,0 +1,164 @@ +import { Injectable } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { AuditService } from '../../audit/audit.service'; +import { AuthenticatedUser, AuthRequestContext } from '../../auth/auth.types'; +import { AppError } from '../../common/errors/app-error'; +import { EnvConfig } from '../../config/env.schema'; +import { DeployNotificationService } from '../wecom/deploy-notification.service'; +import { + PreviewNotificationInput, + SaveNotificationConfigInput, + TestNotificationInput, +} from './notification-config.dto'; +import { NotificationConfigRepository } from './notification-config.repository'; +import { + eventCatalog, + fieldCatalog, + NotificationPreferences, + styleCatalog, + templateVariables, +} from './notification-config.types'; +import { NotificationTemplateService } from './notification-template.service'; + +@Injectable() +export class NotificationConfigService { + private testing = false; + private lastTestAt = 0; + constructor( + private readonly repository: NotificationConfigRepository, + private readonly templates: NotificationTemplateService, + private readonly delivery: DeployNotificationService, + private readonly audit: AuditService, + private readonly config: ConfigService, + ) {} + + async getConfig() { + return { + ...(await this.repository.getConfig()), + channel: this.delivery.healthSummary(), + catalog: { + events: eventCatalog, + fields: fieldCatalog, + styles: styleCatalog, + variables: templateVariables, + }, + }; + } + + async save( + input: SaveNotificationConfigInput, + user: AuthenticatedUser, + context: AuthRequestContext, + ) { + this.validateTemplates(input.preferences); + const before = await this.repository.getConfig(); + const saved = await this.repository.save(input.preferences, input.version); + await this.audit.record({ + action: 'NOTIFICATION_CONFIG_UPDATED', + resourceType: 'notification_config', + resourceId: 'system', + actorId: user.id, + actorName: user.account, + ...context, + before: { + version: before.version, + enabled: before.preferences.enabled, + events: before.preferences.events, + }, + after: { + version: saved.version, + enabled: saved.preferences.enabled, + events: saved.preferences.events, + fields: saved.preferences.fields, + style: saved.preferences.style, + }, + parameterDigest: { + titleCustomized: Boolean(input.preferences.titleTemplate), + bodyCustomized: Boolean(input.preferences.bodyTemplate), + }, + }); + return { + ...saved, + channel: this.delivery.healthSummary(), + catalog: { + events: eventCatalog, + fields: fieldCatalog, + styles: styleCatalog, + variables: templateVariables, + }, + }; + } + + preview(input: PreviewNotificationInput) { + return this.templates.render( + input.preferences, + this.templates.sample( + input.event, + this.config.get('DEVOPS_PUBLIC_URL', { infer: true }), + ), + true, + ); + } + + async test( + input: TestNotificationInput, + user: AuthenticatedUser, + context: AuthRequestContext, + ) { + if (input.confirmed !== true) + throw new AppError( + 'VALIDATION_FAILED', + '请确认向当前通知群发送测试消息', + 400, + ); + if (this.testing || Date.now() - this.lastTestAt < 10_000) + throw new AppError( + 'RATE_LIMITED', + '测试消息已发送,请稍等 10 秒再试', + 429, + ); + const preview = this.preview(input); + this.testing = true; + this.lastTestAt = Date.now(); + try { + await this.delivery.sendTestMessage(preview); + await this.audit.record({ + action: 'NOTIFICATION_TEST_SENT', + resourceType: 'notification_config', + resourceId: 'system', + actorId: user.id, + actorName: user.account, + ...context, + after: { + event: input.event, + style: input.preferences.style, + draft: true, + }, + parameterDigest: { confirmed: true }, + }); + return { + success: true, + message: '测试消息已发送,请到通知群查看 🐾', + checkedAt: new Date().toISOString(), + }; + } catch (error) { + await this.audit.record({ + action: 'NOTIFICATION_TEST_FAILED', + resourceType: 'notification_config', + resourceId: 'system', + actorId: user.id, + actorName: user.account, + ...context, + after: { event: input.event, style: input.preferences.style }, + }); + throw error; + } finally { + this.testing = false; + } + } + + private validateTemplates(preferences: NotificationPreferences) { + for (const event of eventCatalog) + this.preview({ preferences, event: event.key }); + } +} diff --git a/src/notifications/config/notification-config.types.ts b/src/notifications/config/notification-config.types.ts new file mode 100644 index 0000000..f230092 --- /dev/null +++ b/src/notifications/config/notification-config.types.ts @@ -0,0 +1,162 @@ +export const notificationEvents = [ + 'created', + 'queued', + 'succeeded', + 'failed', + 'canceled', + 'retried', +] as const; +export type NotificationEvent = (typeof notificationEvents)[number]; +export const notificationFields = [ + 'projectKey', + 'environment', + 'ref', + 'status', + 'operator', + 'buildNumber', + 'duration', + 'commit', + 'createdAt', + 'runId', + 'failureSummary', +] as const; +export type NotificationField = (typeof notificationFields)[number]; +export type NotificationStyle = 'cozy' | 'simple' | 'compact'; + +export type NotificationPreferences = { + enabled: boolean; + events: NotificationEvent[]; + fields: NotificationField[]; + style: NotificationStyle; + emojiEnabled: boolean; + titleTemplate: string; + bodyTemplate: string; + footer: string; + includeDetailLink: boolean; + includeBuildLink: boolean; +}; +export type StoredNotificationConfig = { + preferences: NotificationPreferences; + version: number; + updatedAt?: string; +}; +export type NotificationContext = { + event: NotificationEvent; + projectKey?: string; + environment?: string; + ref?: string; + status?: string; + operator?: string; + buildNumber?: number; + queueId?: string | number; + duration?: string; + commit?: string; + createdAt?: string; + runId?: string; + failureSummary?: string; + buildUrl?: string; + detailUrl?: string; +}; +export type NotificationPreview = { + title: string; + body: string; + markdown: string; + plainText: string; + byteLength: number; + sample: boolean; +}; + +export const eventCatalog = [ + { + key: 'created', + label: '创建发布', + emoji: '🌱', + title: 'DevOps 发布已创建', + }, + { + key: 'queued', + label: '进入队列', + emoji: '⏳', + title: 'DevOps 发布已进入 Jenkins 队列', + }, + { + key: 'succeeded', + label: '发布成功', + emoji: '🎉', + title: 'DevOps 发布成功', + }, + { key: 'failed', label: '发布失败', emoji: '🧯', title: 'DevOps 发布失败' }, + { + key: 'canceled', + label: '发布取消', + emoji: '🍃', + title: 'DevOps 发布已取消', + }, + { + key: 'retried', + label: '重新发布', + emoji: '🔄', + title: 'DevOps 发布已重试', + }, +] as const; +export const fieldCatalog = [ + { key: 'projectKey', label: '项目', emoji: '📦' }, + { key: 'environment', label: '环境', emoji: '🌍' }, + { key: 'ref', label: '分支 / 标签', emoji: '🌿' }, + { key: 'status', label: '状态', emoji: '📍' }, + { key: 'operator', label: '操作者', emoji: '👤' }, + { key: 'buildNumber', label: '构建编号', emoji: '🔨' }, + { key: 'duration', label: '耗时', emoji: '⏱️' }, + { key: 'commit', label: '提交 SHA', emoji: '🧩' }, + { key: 'createdAt', label: '创建时间', emoji: '🗓️' }, + { key: 'runId', label: '发布单 ID', emoji: '🏷️' }, + { key: 'failureSummary', label: '失败摘要', emoji: '🔎' }, +] as const; +export const styleCatalog = [ + { + key: 'cozy', + label: '软萌信笺', + emoji: '💌', + description: '轻轻问候,重点信息分行呈现', + }, + { + key: 'simple', + label: '清爽简报', + emoji: '🫧', + description: '清晰的字段与留白,专注发布结果', + }, + { + key: 'compact', + label: '极简速报', + emoji: '⚡', + description: '把关键数据收进一则短消息', + }, +] as const; +export const defaultNotificationPreferences: NotificationPreferences = { + enabled: true, + events: [...notificationEvents], + fields: [ + 'projectKey', + 'environment', + 'ref', + 'operator', + 'buildNumber', + 'duration', + 'failureSummary', + ], + style: 'cozy', + emojiEnabled: true, + titleTemplate: '{{emoji}} {{eventTitle}}', + bodyTemplate: '', + footer: '', + includeDetailLink: true, + includeBuildLink: true, +}; +export const templateVariables = [ + 'emoji', + 'eventTitle', + 'greeting', + 'fields', + 'links', + ...notificationFields, +] as const; diff --git a/src/notifications/config/notification-template.service.spec.ts b/src/notifications/config/notification-template.service.spec.ts new file mode 100644 index 0000000..eb261e6 --- /dev/null +++ b/src/notifications/config/notification-template.service.spec.ts @@ -0,0 +1,119 @@ +import { NotificationTemplateService } from './notification-template.service'; +import { + defaultNotificationPreferences, + NotificationPreferences, +} from './notification-config.types'; +import { + notificationPreferencesSchema, + testNotificationSchema, +} from './notification-config.dto'; + +describe('NotificationTemplateService', () => { + const templates = new NotificationTemplateService(); + const preferences = ( + patch: Partial = {}, + ): NotificationPreferences => ({ + ...structuredClone(defaultNotificationPreferences), + ...patch, + }); + + it('uses selected field order, hides unselected and missing values, and uses friendly environment names', () => { + const result = templates.render( + preferences({ fields: ['operator', 'environment', 'failureSummary'] }), + templates.sample('succeeded'), + ); + expect(result.body.indexOf('操作者')).toBeLessThan( + result.body.indexOf('环境'), + ); + expect(result.body).toContain('生产'); + expect(result.body).not.toContain('role-user'); + expect(result.body).not.toContain('失败摘要'); + }); + it('applies the same variables to custom titles and bodies while honoring hidden fields', () => { + const result = templates.render( + preferences({ + fields: ['projectKey'], + titleTemplate: '{{eventTitle}} · {{projectKey}}', + bodyTemplate: '**{{projectKey}}**\n\n{{fields}}\n{{operator}}', + footer: '辛苦啦 🌷', + }), + templates.sample('failed'), + ); + expect(result.title).toContain('role-user'); + expect(result.body).toContain('**role-user**'); + expect(result.body).not.toContain('发布小助手'); + expect(result.body.endsWith('辛苦啦 🌷')).toBe(true); + }); + it('renders compact style without quote rows or greetings and can turn off decorative emoji', () => { + const result = templates.render( + preferences({ style: 'compact', emojiEnabled: false }), + templates.sample('failed'), + ); + expect(result.body).toContain(' · '); + expect(result.body).not.toContain('> '); + expect(result.title).toBe('DevOps 发布失败'); + expect(result.body).not.toContain('🐾'); + }); + it('does not create actionable links for unsafe protocols or URL credentials', () => { + const result = templates.render(preferences(), { + ...templates.sample('succeeded'), + detailUrl: 'javascript:alert(1)', + buildUrl: 'https://user:secret@example.com/logs', + }); + expect(result.body).not.toContain('javascript'); + expect(result.body).not.toContain('secret'); + }); + it('redacts failure secrets and prevents runtime data from mentioning group members', () => { + const result = templates.render(preferences(), { + ...templates.sample('failed'), + operator: '<@all>', + failureSummary: + 'failed https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=secret-test-value', + }); + expect(result.body).not.toContain('<@all>'); + expect(result.body).not.toContain('secret-test-value'); + }); + it('rejects overlong rendered output before any message is sent', () => { + expect(() => + templates.render( + preferences({ bodyTemplate: '花'.repeat(1500) }), + templates.sample('succeeded'), + ), + ).toThrow('通知内容过长'); + }); + it('validates events, fields, duplicates, template variables, and explicit test confirmation', () => { + expect( + notificationPreferencesSchema.safeParse(preferences({ events: [] })) + .success, + ).toBe(false); + expect( + notificationPreferencesSchema.safeParse( + preferences({ enabled: false, events: [] }), + ).success, + ).toBe(true); + expect( + notificationPreferencesSchema.safeParse( + preferences({ fields: ['projectKey', 'projectKey'] }), + ).success, + ).toBe(false); + expect( + notificationPreferencesSchema.safeParse( + preferences({ bodyTemplate: '{{unsupported}}' }), + ).success, + ).toBe(false); + expect( + testNotificationSchema.safeParse({ + preferences: preferences(), + event: 'succeeded', + }).success, + ).toBe(false); + expect( + testNotificationSchema.safeParse({ + preferences: preferences(), + event: 'succeeded', + confirmed: true, + webhook: 'https://bad.example', + }).success, + ).toBe(false); + }); +}); diff --git a/src/notifications/config/notification-template.service.ts b/src/notifications/config/notification-template.service.ts new file mode 100644 index 0000000..a3bd9a8 --- /dev/null +++ b/src/notifications/config/notification-template.service.ts @@ -0,0 +1,187 @@ +import { Injectable } from '@nestjs/common'; +import { AppError } from '../../common/errors/app-error'; +import { redactSensitive } from '../../common/security/redact-sensitive'; +import { + eventCatalog, + fieldCatalog, + NotificationContext, + NotificationEvent, + NotificationPreferences, + NotificationPreview, +} from './notification-config.types'; + +@Injectable() +export class NotificationTemplateService { + render( + preferences: NotificationPreferences, + context: NotificationContext, + sample = false, + ): NotificationPreview { + const event = eventCatalog.find((item) => item.key === context.event)!; + const values: Record = {}; + for (const field of fieldCatalog) { + if (!preferences.fields.includes(field.key)) continue; + let value = context[field.key]; + if (field.key === 'environment') + value = + value === 'production' ? '生产' : value === 'test' ? '测试' : value; + if (field.key === 'status') + value = + ( + { + pending: '待执行', + queued: '排队中', + running: '运行中', + success: '成功', + failed: '失败', + canceled: '已取消', + } as Record + )[String(value)] ?? value; + if (field.key === 'buildNumber' && value !== undefined) + value = `#${value}`; + if (field.key === 'commit' && typeof value === 'string') + value = value.slice(0, 12); + if (value === undefined || value === '') continue; + const safe = redactSensitive({ text: String(value) }) + .text.replace(/[\r\n]+/g, ' ') + .slice(0, field.key === 'failureSummary' ? 350 : 160); + values[field.key] = safe + .replace(/[<>]/g, '') + .replace(/([\\`*[\]])/g, '\\$1'); + } + const rows = preferences.fields.flatMap((key) => { + const field = fieldCatalog.find((item) => item.key === key)!; + return values[key] + ? [ + `${preferences.emojiEnabled && preferences.style === 'cozy' ? `${field.emoji} ` : ''}${field.label}:${values[key]}`, + ] + : []; + }); + const fields = + preferences.style === 'compact' + ? rows.join(' · ') + : rows + .map((row) => (preferences.style === 'cozy' ? `> ${row}` : row)) + .join('\n'); + const links = [ + preferences.includeDetailLink + ? this.link('查看发布详情', context.detailUrl) + : '', + preferences.includeBuildLink + ? this.link('查看构建日志', context.buildUrl) + : '', + ] + .filter(Boolean) + .join(' · '); + const greeting = + preferences.style === 'cozy' + ? this.greeting(context.event, preferences.emojiEnabled) + : ''; + const variables: Record = { + ...values, + emoji: preferences.emojiEnabled ? event.emoji : '', + eventTitle: event.title, + greeting, + fields, + links, + }; + const substitute = (value: string) => + value.replace( + /\{\{\s*([^{}]+?)\s*\}\}/g, + (_, key: string) => variables[key] ?? '', + ); + const title = substitute(preferences.titleTemplate) + .replace(/[\r\n]+/g, ' ') + .trim(); + if (!title) + throw new AppError( + 'VALIDATION_FAILED', + '标题模板生成的内容不能为空', + 400, + ); + const content = preferences.bodyTemplate.trim() + ? substitute(preferences.bodyTemplate) + : [greeting, fields, links].filter(Boolean).join('\n\n'); + const body = [content.trim(), preferences.footer.trim()] + .filter(Boolean) + .join('\n\n'); + const markdown = `# ${title}\n\n${body}`; + const byteLength = Buffer.byteLength(markdown, 'utf8'); + if (byteLength > 3900) + throw new AppError( + 'VALIDATION_FAILED', + '通知内容过长,请精简正文或减少显示字段(最多 3900 字节)', + 400, + ); + return { + title, + body, + markdown, + plainText: `${title}\n\n${body.replace(/^> /gm, '').replace(/\*\*/g, '')}`, + byteLength, + sample, + }; + } + + sample(event: NotificationEvent, publicUrl?: string): NotificationContext { + return { + event, + projectKey: 'role-user', + environment: 'production', + ref: 'v1.2.3', + status: { + created: 'pending', + queued: 'queued', + succeeded: 'success', + failed: 'failed', + canceled: 'canceled', + retried: 'queued', + }[event], + operator: '发布小助手', + buildNumber: 65, + duration: ['succeeded', 'failed', 'canceled'].includes(event) + ? '46 秒' + : undefined, + commit: 'a1b2c3d4e5f6', + buildUrl: 'https://jenkins.example.com/job/example/65/console', + createdAt: '2026-10-28 10:00', + runId: 'preview-example', + failureSummary: + event === 'failed' + ? '健康检查未通过:应用未在规定时间内就绪' + : undefined, + detailUrl: this.safeUrl(publicUrl) + ? new URL('/runs', publicUrl).toString() + : undefined, + }; + } + + private greeting(event: NotificationEvent, emoji: boolean): string { + const text = { + created: '新的发布任务已收到,准备出发。', + queued: '正在排队,马上就轮到这次发布啦。', + succeeded: '代码已平安抵达,辛苦啦!', + failed: '部署遇到一点状况,请查看下方原因。', + canceled: '本次发布已停下,等准备好再出发。', + retried: '已重新出发,一起等待好消息。', + }[event]; + return `${text}${emoji ? (event === 'succeeded' ? ' 🌷' : ' 🐾') : ''}`; + } + private safeUrl(value?: string): boolean { + if (!value) return false; + try { + const url = new URL(value); + return ( + ['https:', 'http:'].includes(url.protocol) && + !url.username && + !url.password && + !/[\s()]/.test(value) + ); + } catch { + return false; + } + } + private link(label: string, url?: string): string { + return this.safeUrl(url) ? `[${label}](${url})` : ''; + } +} diff --git a/src/notifications/wecom/deploy-notification.service.spec.ts b/src/notifications/wecom/deploy-notification.service.spec.ts index 4443a1c..135d32f 100644 --- a/src/notifications/wecom/deploy-notification.service.spec.ts +++ b/src/notifications/wecom/deploy-notification.service.spec.ts @@ -7,6 +7,9 @@ import { WeComClient } from './wecom.client'; import { DeployNotificationService } from './deploy-notification.service'; import { DeployRunSummary } from '../../deploy-runs/deploy-run.types'; import { NotificationOutboxService } from '../outbox/notification-outbox.service'; +import { NotificationConfigRepository } from '../config/notification-config.repository'; +import { NotificationTemplateService } from '../config/notification-template.service'; +import { defaultNotificationPreferences } from '../config/notification-config.types'; describe('DeployNotificationService', () => { const run: DeployRunSummary = { @@ -38,6 +41,8 @@ describe('DeployNotificationService', () => { createConfig({}), weCom as unknown as WeComClient, createOutbox() as unknown as NotificationOutboxService, + createPreferences() as unknown as NotificationConfigRepository, + new NotificationTemplateService(), ); const result = await service.sendDeployRunEvent(run, 'created'); @@ -56,6 +61,8 @@ describe('DeployNotificationService', () => { createConfig({ NOTIFICATION_PROVIDER: 'wecom' }), weCom as unknown as WeComClient, createOutbox() as unknown as NotificationOutboxService, + createPreferences() as unknown as NotificationConfigRepository, + new NotificationTemplateService(), ); const result = await service.sendDeployRunEvent(run, 'created'); @@ -73,6 +80,7 @@ describe('DeployNotificationService', () => { it('sends text payload when Feishu provider is configured', async () => { const fetchMock = jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, + json: () => Promise.resolve({ code: 0 }), } as Response); const weCom = { healthSummary: jest.fn(() => ({ status: 'not_configured' as const })), @@ -85,6 +93,8 @@ describe('DeployNotificationService', () => { }), weCom as unknown as WeComClient, createOutbox() as unknown as NotificationOutboxService, + createPreferences() as unknown as NotificationConfigRepository, + new NotificationTemplateService(), ); const result = await service.sendDeployRunEvent(run, 'failed'); @@ -102,6 +112,7 @@ describe('DeployNotificationService', () => { it('sends structured payload when generic provider is configured', async () => { const fetchMock = jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, + json: () => Promise.resolve({ code: 0 }), } as Response); const weCom = { healthSummary: jest.fn(() => ({ status: 'not_configured' as const })), @@ -115,6 +126,8 @@ describe('DeployNotificationService', () => { }), weCom as unknown as WeComClient, createOutbox() as unknown as NotificationOutboxService, + createPreferences() as unknown as NotificationConfigRepository, + new NotificationTemplateService(), ); const result = await service.sendDeployRunEvent(run, 'succeeded'); @@ -128,10 +141,112 @@ describe('DeployNotificationService', () => { }), ); }); + + it('does not enqueue or send events disabled by notification preferences', async () => { + const weCom = { + healthSummary: () => ({ status: 'ok' as const }), + sendMarkdown: jest.fn(), + }; + const outbox = createOutbox(); + const preferences = createPreferences(); + preferences.getConfig.mockResolvedValue({ + version: 1, + preferences: { + ...defaultNotificationPreferences, + emojiEnabled: false, + style: 'simple', + events: ['succeeded'], + }, + }); + const service = new DeployNotificationService( + createConfig({ NOTIFICATION_PROVIDER: 'wecom' }), + weCom as unknown as WeComClient, + outbox as unknown as NotificationOutboxService, + preferences as unknown as NotificationConfigRepository, + new NotificationTemplateService(), + ); + await expect( + service.sendDeployRunEvent(run, 'created'), + ).resolves.toMatchObject({ status: 'skipped' }); + expect(outbox.createMessage).not.toHaveBeenCalled(); + expect(weCom.sendMarkdown).not.toHaveBeenCalled(); + }); + + it('uses saved templates and fields for actual delivery', async () => { + const weCom = { + healthSummary: () => ({ status: 'ok' as const }), + sendMarkdown: jest.fn(() => Promise.resolve({ accepted: true })), + }; + const preferences = createPreferences(); + preferences.getConfig.mockResolvedValue({ + version: 1, + preferences: { + ...defaultNotificationPreferences, + emojiEnabled: false, + style: 'simple', + fields: ['operator'], + titleTemplate: '部署回执', + bodyTemplate: '{{fields}}', + }, + }); + const service = new DeployNotificationService( + createConfig({ NOTIFICATION_PROVIDER: 'wecom' }), + weCom as unknown as WeComClient, + createOutbox() as unknown as NotificationOutboxService, + preferences as unknown as NotificationConfigRepository, + new NotificationTemplateService(), + ); + await service.sendDeployRunEvent(run, 'succeeded'); + expect(weCom.sendMarkdown).toHaveBeenCalledWith({ + title: '部署回执', + markdown: '操作者:ops-admin', + }); + }); + + it('stops automatic retry of messages whose event was disabled', async () => { + const weCom = { + healthSummary: () => ({ status: 'ok' as const }), + sendMarkdown: jest.fn(), + }; + const outbox = createOutbox(); + const preferences = createPreferences(); + preferences.getConfig.mockResolvedValue({ + version: 1, + preferences: { + ...defaultNotificationPreferences, + emojiEnabled: false, + style: 'simple', + events: ['succeeded'], + }, + }); + const service = new DeployNotificationService( + createConfig({ NOTIFICATION_PROVIDER: 'wecom' }), + weCom as unknown as WeComClient, + outbox as unknown as NotificationOutboxService, + preferences as unknown as NotificationConfigRepository, + new NotificationTemplateService(), + ); + const message = await outbox.createMessage({ + channel: 'wecom', + template: 'deploy.created', + payload: {}, + idempotencyKey: 'retry-filter', + }); + await expect(service.retryOutboxMessage(message)).resolves.toMatchObject({ + status: 'skipped', + }); + expect(outbox.completeMessage).toHaveBeenCalledWith( + message.id, + expect.objectContaining({ status: 'dead' }), + ); + expect(weCom.sendMarkdown).not.toHaveBeenCalled(); + }); }); function createConfig( - values: Partial>, + values: Partial< + Record + >, ): ConfigService { return { get: jest.fn((key: keyof EnvConfig) => values[key]), @@ -160,3 +275,18 @@ function createOutbox(): Pick< completeMessage: jest.fn(), }; } + +function createPreferences() { + return { + getConfig: jest.fn(() => + Promise.resolve({ + version: 0, + preferences: { + ...defaultNotificationPreferences, + emojiEnabled: false, + style: 'simple' as const, + }, + }), + ), + }; +} diff --git a/src/notifications/wecom/deploy-notification.service.ts b/src/notifications/wecom/deploy-notification.service.ts index 6c9a01e..c3875ab 100644 --- a/src/notifications/wecom/deploy-notification.service.ts +++ b/src/notifications/wecom/deploy-notification.service.ts @@ -9,6 +9,13 @@ import { DeployRunSummary } from '../../deploy-runs/deploy-run.types'; import { NotificationOutboxService } from '../outbox/notification-outbox.service'; import { NotificationOutboxMessage } from '../outbox/notification-outbox.types'; import { WeComClient } from './wecom.client'; +import { AppError } from '../../common/errors/app-error'; +import { NotificationConfigRepository } from '../config/notification-config.repository'; +import { NotificationTemplateService } from '../config/notification-template.service'; +import { + NotificationContext, + NotificationPreview, +} from '../config/notification-config.types'; export type DeployNotificationEvent = | 'created' @@ -33,21 +40,6 @@ type DeployNotificationHealth = { message?: string; }; -type DeployNotificationPayloadSummary = { - event?: string; - title?: string; - deployRunId?: string; - projectKey?: string; - environment?: string; - ref?: string; - status?: string; - operator?: string; - jenkinsQueueId?: string | number; - jenkinsBuildNumber?: number; - failureSummary?: string; - publicUrl?: string; -}; - /** * 统一封装发布单通知,保证 webhook 只存在于后端配置边界内。 */ @@ -57,6 +49,8 @@ export class DeployNotificationService { private readonly config: ConfigService, private readonly weComClient: WeComClient, private readonly notificationOutboxService: NotificationOutboxService, + private readonly notificationConfig: NotificationConfigRepository, + private readonly templates: NotificationTemplateService, ) {} healthSummary(): DeployNotificationHealth { @@ -95,6 +89,18 @@ export class DeployNotificationService { ): Promise { const health = this.healthSummary(); const channel = health.provider ?? 'none'; + try { + const { preferences } = await this.notificationConfig.getConfig(); + if (!preferences.enabled || !preferences.events.includes(event)) { + return { status: 'skipped', channel, reason: '当前通知时机已关闭' }; + } + } catch { + return { + status: 'failed', + channel, + reason: '通知配置读取失败,请检查服务端配置', + }; + } const outboxMessage = await this.createOutboxMessage(run, event, channel); if (health.status === 'not_configured') { @@ -158,6 +164,31 @@ export class DeployNotificationService { ): Promise { const health = this.healthSummary(); const channel = health.provider ?? 'none'; + try { + const { preferences } = await this.notificationConfig.getConfig(); + if ( + !preferences.enabled || + !preferences.events.includes(this.eventFromTemplate(message)) + ) { + await this.notificationOutboxService.completeMessage(message.id, { + status: 'dead', + lastError: '当前通知时机已关闭,停止自动重试', + }); + return { + status: 'skipped', + channel, + reason: '当前通知时机已关闭', + outboxMessageId: message.id, + }; + } + } catch { + return { + status: 'failed', + channel, + reason: '通知配置读取失败', + outboxMessageId: message.id, + }; + } if (health.status === 'not_configured') { await this.completeOutboxFailure( @@ -279,56 +310,38 @@ export class DeployNotificationService { : 'NOTIFICATION_WEBHOOK_URL'; } + async sendTestMessage(preview: NotificationPreview): Promise { + const health = this.healthSummary(); + if (health.status !== 'ok' || !health.provider) { + throw new AppError( + 'CONFIG_MISSING', + '通知通道尚未配置,请先完成服务端接入', + 400, + ); + } + await this.dispatchMessage( + health.provider, + { event: 'succeeded' }, + { + ...preview, + title: `【通知测试】${preview.title}`, + plainText: `【通知测试】${preview.plainText}`, + }, + true, + ); + } + private async sendByProvider( provider: DeployNotificationProvider, run: DeployRunSummary, event: DeployNotificationEvent, ): Promise { - const title = this.titleFor(event); - const markdown = this.markdownFor(run, event); - - if (provider === 'wecom') { - await this.weComClient.sendMarkdown({ - title, - markdown, - }); - return; - } - - if (provider === 'feishu') { - await this.postWebhook( - this.config.get('FEISHU_WEBHOOK_URL', { infer: true }) ?? '', - { - msg_type: 'text', - content: { - text: `${title}\n${this.plainTextFor(run, event)}`, - }, - }, - provider, - ); - return; - } - - await this.postWebhook( - this.config.get('NOTIFICATION_WEBHOOK_URL', { infer: true }) ?? '', - { - event: `deploy.${event}`, - title, - markdown, - run: { - id: run.id, - projectKey: run.projectKey, - environment: run.environment, - ref: run.ref, - status: run.status, - operator: run.operator, - jenkinsQueueId: run.jenkinsQueueId, - jenkinsBuildNumber: run.jenkinsBuildNumber, - failureSummary: run.failureSummary, - }, - publicUrl: this.config.get('DEVOPS_PUBLIC_URL', { infer: true }), - }, + const { preferences } = await this.notificationConfig.getConfig(); + const context = this.contextForRun(run, event); + await this.dispatchMessage( provider, + context, + this.templates.render(preferences, context), ); } @@ -336,73 +349,81 @@ export class DeployNotificationService { provider: DeployNotificationProvider, message: NotificationOutboxMessage, ): Promise { - const payload = this.toNotificationPayloadSummary(message.payloadSummary); - const title = payload.title || this.titleFor(this.eventFromTemplate(message)); - const markdown = this.markdownForPayload(payload, title); - const plainText = this.plainTextForPayload(payload, title); - - if (provider === 'wecom') { - await this.weComClient.sendMarkdown({ - title, - markdown, - }); - return; - } - - if (provider === 'feishu') { - await this.postWebhook( - this.config.get('FEISHU_WEBHOOK_URL', { infer: true }) ?? '', - { - msg_type: 'text', - content: { - text: `${title}\n${plainText}`, - }, - }, - provider, - ); - return; - } - - await this.postWebhook( - this.config.get('NOTIFICATION_WEBHOOK_URL', { infer: true }) ?? '', - { - event: payload.event ?? message.template, - title, - markdown, - run: { - id: payload.deployRunId ?? message.deployRunId, - projectKey: payload.projectKey, - environment: payload.environment, - ref: payload.ref, - status: payload.status, - operator: payload.operator, - jenkinsQueueId: payload.jenkinsQueueId, - jenkinsBuildNumber: payload.jenkinsBuildNumber, - failureSummary: payload.failureSummary, - }, - publicUrl: - payload.publicUrl ?? - this.config.get('DEVOPS_PUBLIC_URL', { infer: true }), - }, + const { preferences } = await this.notificationConfig.getConfig(); + const context = this.contextForPayload( + message.payloadSummary ?? {}, + this.eventFromTemplate(message), + ); + await this.dispatchMessage( provider, + context, + this.templates.render(preferences, context), ); } - private async postWebhook( - webhookUrl: string, - body: unknown, + private async dispatchMessage( provider: DeployNotificationProvider, + context: NotificationContext, + rendered: NotificationPreview, + test = false, ): Promise { - const response = await fetch(webhookUrl, { + if (provider === 'wecom') { + await this.weComClient.sendMarkdown({ + title: rendered.title, + markdown: rendered.body, + }); + return; + } + const url = + this.config.get( + provider === 'feishu' + ? 'FEISHU_WEBHOOK_URL' + : 'NOTIFICATION_WEBHOOK_URL', + { infer: true }, + ) ?? ''; + const body = + provider === 'feishu' + ? { msg_type: 'text', content: { text: rendered.plainText } } + : { + event: test ? 'notification.test' : `deploy.${context.event}`, + title: rendered.title, + markdown: rendered.body, + run: { + id: context.runId, + projectKey: context.projectKey, + environment: context.environment, + ref: context.ref, + status: context.status, + operator: context.operator, + jenkinsQueueId: context.queueId, + jenkinsBuildNumber: context.buildNumber, + failureSummary: context.failureSummary, + }, + publicUrl: this.config.get('DEVOPS_PUBLIC_URL', { infer: true }), + }; + const response = await fetch(url, { method: 'POST', - headers: { - 'content-type': 'application/json', - }, + headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), + signal: AbortSignal.timeout(10000), }); - - if (!response.ok) { - throw new Error(`${provider} webhook 请求失败:${response.status}`); + if (!response.ok) + throw new AppError( + 'INTEGRATION_REQUEST_FAILED', + `${provider} 通知请求失败:HTTP ${response.status}`, + 502, + ); + if (provider === 'feishu') { + const result = (await response.json()) as { + code?: number; + StatusCode?: number; + }; + if (result.code !== 0 && result.StatusCode !== 0) + throw new AppError( + 'INTEGRATION_REQUEST_FAILED', + '飞书未接受通知,请检查机器人配置', + 502, + ); } } @@ -445,6 +466,11 @@ export class DeployNotificationService { operator: run.operator, jenkinsQueueId: run.jenkinsQueueId, jenkinsBuildNumber: run.jenkinsBuildNumber, + jenkinsBuildUrl: run.jenkinsBuildUrl, + startedAt: run.startedAt, + finishedAt: run.finishedAt, + createdAt: run.createdAt, + resolvedCommit: run.resolvedCommit?.slice(0, 12), failureSummary: run.failureSummary, publicUrl: this.config.get('DEVOPS_PUBLIC_URL', { infer: true }), }; @@ -470,132 +496,83 @@ export class DeployNotificationService { return ref.length > 48 ? `${ref.slice(0, 45)}...` : ref; } - private markdownFor( + private contextForRun( run: DeployRunSummary, event: DeployNotificationEvent, - ): string { - return [ - `> 事件:${this.titleFor(event)}`, - `> 项目:${run.projectKey}`, - `> 环境:${run.environment}`, - `> Ref:${run.ref}`, - `> 状态:${run.status}`, - `> 操作者:${run.operator}`, - `> Run ID:${run.id}`, - run.jenkinsQueueId ? `> Jenkins Queue:${run.jenkinsQueueId}` : undefined, - run.jenkinsBuildNumber ? `> Jenkins Build:#${run.jenkinsBuildNumber}` : undefined, - run.failureSummary ? `> 失败摘要:${run.failureSummary}` : undefined, - ] - .filter(Boolean) - .join('\n'); + ): NotificationContext { + return this.contextForPayload(this.outboxPayloadFor(run, event), event); } - private plainTextFor( - run: DeployRunSummary, + private contextForPayload( + payload: Record, event: DeployNotificationEvent, - ): string { - return [ - `事件:${this.titleFor(event)}`, - `项目:${run.projectKey}`, - `环境:${run.environment}`, - `Ref:${run.ref}`, - `状态:${run.status}`, - `操作者:${run.operator}`, - `Run ID:${run.id}`, - run.failureSummary ? `失败摘要:${run.failureSummary}` : undefined, - ] - .filter(Boolean) - .join('\n'); + ): NotificationContext { + const text = (key: string) => + typeof payload[key] === 'string' ? payload[key] : undefined; + const startedAt = text('startedAt'); + const finishedAt = text('finishedAt'); + const elapsed = + startedAt && finishedAt + ? Date.parse(finishedAt) - Date.parse(startedAt) + : NaN; + const publicUrl = this.config.get('DEVOPS_PUBLIC_URL', { infer: true }); + const runId = text('deployRunId'); + let detailUrl: string | undefined; + if (publicUrl && runId) { + const url = new URL('/runs', publicUrl); + url.searchParams.set('runId', runId); + detailUrl = url.toString(); + } + const created = text('createdAt'); + return { + event, + projectKey: text('projectKey'), + environment: text('environment'), + ref: text('ref'), + status: text('status'), + operator: text('operator'), + runId, + buildNumber: + typeof payload.jenkinsBuildNumber === 'number' + ? payload.jenkinsBuildNumber + : undefined, + queueId: + typeof payload.jenkinsQueueId === 'string' || + typeof payload.jenkinsQueueId === 'number' + ? payload.jenkinsQueueId + : undefined, + buildUrl: text('jenkinsBuildUrl'), + commit: text('resolvedCommit'), + duration: + Number.isFinite(elapsed) && elapsed >= 0 + ? `${Math.round(elapsed / 1000)} 秒` + : undefined, + createdAt: + created && Number.isFinite(Date.parse(created)) + ? new Intl.DateTimeFormat('zh-CN', { + timeZone: 'Asia/Shanghai', + dateStyle: 'short', + timeStyle: 'short', + }).format(new Date(created)) + : undefined, + failureSummary: text('failureSummary'), + detailUrl, + }; } private eventFromTemplate( message: NotificationOutboxMessage, ): DeployNotificationEvent { const event = message.template.replace(/^deploy\./, ''); - - if ( - event === 'created' || - event === 'queued' || - event === 'succeeded' || - event === 'failed' || - event === 'canceled' || - event === 'retried' - ) { - return event; - } - - return 'failed'; - } - - private toNotificationPayloadSummary( - value: Record | undefined, - ): DeployNotificationPayloadSummary { - return { - event: this.optionalString(value?.event), - title: this.optionalString(value?.title), - deployRunId: this.optionalString(value?.deployRunId), - projectKey: this.optionalString(value?.projectKey), - environment: this.optionalString(value?.environment), - ref: this.optionalString(value?.ref), - status: this.optionalString(value?.status), - operator: this.optionalString(value?.operator), - jenkinsQueueId: - typeof value?.jenkinsQueueId === 'string' || - typeof value?.jenkinsQueueId === 'number' - ? value.jenkinsQueueId - : undefined, - jenkinsBuildNumber: - typeof value?.jenkinsBuildNumber === 'number' - ? value.jenkinsBuildNumber - : undefined, - failureSummary: this.optionalString(value?.failureSummary), - publicUrl: this.optionalString(value?.publicUrl), - }; - } - - private markdownForPayload( - payload: DeployNotificationPayloadSummary, - title: string, - ): string { return [ - `> 事件:${title}`, - payload.projectKey ? `> 项目:${payload.projectKey}` : undefined, - payload.environment ? `> 环境:${payload.environment}` : undefined, - payload.ref ? `> Ref:${payload.ref}` : undefined, - payload.status ? `> 状态:${payload.status}` : undefined, - payload.operator ? `> 操作者:${payload.operator}` : undefined, - payload.deployRunId ? `> Run ID:${payload.deployRunId}` : undefined, - payload.jenkinsQueueId - ? `> Jenkins Queue:${payload.jenkinsQueueId}` - : undefined, - payload.jenkinsBuildNumber - ? `> Jenkins Build:#${payload.jenkinsBuildNumber}` - : undefined, - payload.failureSummary ? `> 失败摘要:${payload.failureSummary}` : undefined, - ] - .filter(Boolean) - .join('\n'); - } - - private plainTextForPayload( - payload: DeployNotificationPayloadSummary, - title: string, - ): string { - return [ - `事件:${title}`, - payload.projectKey ? `项目:${payload.projectKey}` : undefined, - payload.environment ? `环境:${payload.environment}` : undefined, - payload.ref ? `Ref:${payload.ref}` : undefined, - payload.status ? `状态:${payload.status}` : undefined, - payload.operator ? `操作者:${payload.operator}` : undefined, - payload.deployRunId ? `Run ID:${payload.deployRunId}` : undefined, - payload.failureSummary ? `失败摘要:${payload.failureSummary}` : undefined, - ] - .filter(Boolean) - .join('\n'); - } - - private optionalString(value: unknown): string | undefined { - return typeof value === 'string' && value.trim() ? value : undefined; + 'created', + 'queued', + 'succeeded', + 'failed', + 'canceled', + 'retried', + ].includes(event) + ? (event as DeployNotificationEvent) + : 'failed'; } } diff --git a/src/notifications/wecom/wecom.client.spec.ts b/src/notifications/wecom/wecom.client.spec.ts new file mode 100644 index 0000000..d7865b1 --- /dev/null +++ b/src/notifications/wecom/wecom.client.spec.ts @@ -0,0 +1,46 @@ +import { ConfigService } from '@nestjs/config'; +import { EnvConfig } from '../../config/env.schema'; +import { WeComClient } from './wecom.client'; + +describe('WeComClient', () => { + const config = { + get: () => 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-only', + } as unknown as ConfigService; + afterEach(() => jest.restoreAllMocks()); + it('rejects HTTP 200 responses whose WeCom business code is nonzero', async () => { + jest + .spyOn(global, 'fetch') + .mockResolvedValue( + new Response( + JSON.stringify({ errcode: 93000, errmsg: 'invalid webhook' }), + ), + ); + await expect( + new WeComClient(config).sendMarkdown({ title: '测试', markdown: '正文' }), + ).rejects.toMatchObject({ + code: 'INTEGRATION_REQUEST_FAILED', + details: { errcode: 93000 }, + }); + }); + it('requires errcode=0 and sends the Markdown body with a timeout', async () => { + const fetcher = jest + .spyOn(global, 'fetch') + .mockResolvedValue(new Response(JSON.stringify({ errcode: 0 }))); + await expect( + new WeComClient(config).sendMarkdown({ + title: '🌷 发布成功', + markdown: '> 项目:role-user', + }), + ).resolves.toEqual({ accepted: true }); + expect(fetcher).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ + signal: expect.any(AbortSignal), + body: JSON.stringify({ + msgtype: 'markdown', + markdown: { content: '# 🌷 发布成功\n\n> 项目:role-user' }, + }), + }), + ); + }); +}); diff --git a/src/notifications/wecom/wecom.client.ts b/src/notifications/wecom/wecom.client.ts index a4567e2..3a0e7d9 100644 --- a/src/notifications/wecom/wecom.client.ts +++ b/src/notifications/wecom/wecom.client.ts @@ -1,6 +1,9 @@ import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; -import { IntegrationRequestError, IntegrationUnavailableError } from '../../common/errors/integration-error'; +import { + IntegrationRequestError, + IntegrationUnavailableError, +} from '../../common/errors/integration-error'; import { redactSensitive } from '../../common/security/redact-sensitive'; import { EnvConfig } from '../../config/env.schema'; import { WeComMarkdownMessage, WeComSendResult } from './wecom.types'; @@ -17,7 +20,8 @@ export class WeComClient { async sendMarkdown(message: WeComMarkdownMessage): Promise { this.assertConfigured(); - const webhookUrl = this.config.get('WECOM_WEBHOOK_URL', { infer: true }) ?? ''; + const webhookUrl = + this.config.get('WECOM_WEBHOOK_URL', { infer: true }) ?? ''; const response = await fetch(webhookUrl, { method: 'POST', headers: { @@ -29,6 +33,7 @@ export class WeComClient { content: `# ${message.title}\n\n${message.markdown}`, }, }), + signal: AbortSignal.timeout(10000), }); if (!response.ok) { @@ -38,6 +43,17 @@ export class WeComClient { }); } + const result = (await response.json()) as { errcode?: number }; + if (result.errcode !== 0) { + throw new IntegrationRequestError( + 'wecom', + '企微未接受通知,请检查机器人是否可用', + { + errcode: result.errcode, + }, + ); + } + return { accepted: true }; } diff --git a/src/notifications/wecom/wecom.module.ts b/src/notifications/wecom/wecom.module.ts index 848a9f8..1216272 100644 --- a/src/notifications/wecom/wecom.module.ts +++ b/src/notifications/wecom/wecom.module.ts @@ -9,11 +9,21 @@ import { NotificationOutboxManualRetryController } from './notification-outbox-m import { NotificationOutboxManualRetryService } from './notification-outbox-manual-retry.service'; import { NotificationOutboxRetryService } from './notification-outbox-retry.service'; import { WeComClient } from './wecom.client'; +import { NotificationConfigController } from '../config/notification-config.controller'; +import { NotificationConfigRepository } from '../config/notification-config.repository'; +import { NotificationConfigService } from '../config/notification-config.service'; +import { NotificationTemplateService } from '../config/notification-template.service'; @Module({ imports: [NotificationOutboxModule, RedisModule], - controllers: [NotificationOutboxManualRetryController], + controllers: [ + NotificationOutboxManualRetryController, + NotificationConfigController, + ], providers: [ + NotificationConfigRepository, + NotificationConfigService, + NotificationTemplateService, WeComClient, DeployNotificationService, NotificationOutboxManualRetryService,