feat(notifications): show task detail image comparisons

This commit is contained in:
WuYongJie 2026-11-12 13:09:37 +08:00
parent 43d863e2b3
commit 1d22538178
4 changed files with 129 additions and 6 deletions

View File

@ -35,6 +35,30 @@ const resolveRecipientAlias = async (recipientAlias: string) => {
throw new NotificationDirectoryError('RECIPIENT_ALIAS_NOT_FOUND', '花名未找到对应钉钉 userId', 422)
}
test('图片上传只接受已签名的小型 JPEG,并返回机器人的媒体 ID', async () => {
const received: Buffer[] = []
const server = createServer(projects, { uploadPreviewImage: async (image) => {
received.push(image)
return '@QaApprovalPreview_123'
} }).listen(0, '127.0.0.1')
await new Promise<void>((resolve) => server.once('listening', resolve))
const path = '/v1/notification-media/image'
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}${path}`
const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0xff, 0xd9])
const body = JSON.stringify({ image: jpeg.toString('base64') })
try {
assert.equal((await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body })).status, 401)
const invalid = JSON.stringify({ image: Buffer.from('not an image').toString('base64') })
assert.equal((await fetch(url, { method: 'POST', headers: headers('POST', path, invalid), body: invalid })).status, 400)
const ok = await fetch(url, { method: 'POST', headers: headers('POST', path, body), body })
assert.equal(ok.status, 200)
assert.deepEqual(await ok.json(), { mediaId: '@QaApprovalPreview_123' })
assert.deepEqual(received, [jpeg])
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()))
}
})
test('通知中心验证签名、花名目录和幂等键', async () => {
await prisma.requestNonce.deleteMany()
await prisma.notificationDelivery.deleteMany()

View File

@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { DingTalkError, sendRobotMessage } from '../dingtalk'
import { DingTalkError, sendRobotMessage, uploadRobotImage } from '../dingtalk'
import prisma from '../prisma'
import {
classifyDeliveryFailure,
@ -211,6 +211,56 @@ test('机器人 ActionCard 在正文顶部显示统一标题,并发送业务
}
})
test('机器人先上传 JPEG,再向指定主管发带媒体图片和审批入口的 Markdown', async () => {
const oldFetch = global.fetch
const oldRobotCode = process.env.DINGTALK_ROBOT_CODE
process.env.DINGTALK_ROBOT_CODE = 'test-robot-code'
const mediaId = '@QaApprovalPreview_123'
const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xd9])
let uploaded = false
global.fetch = (async (input, init) => {
const url = new URL(String(input))
if (url.pathname === '/gettoken') {
return Response.json({ errcode: 0, access_token: 'fixture-token', expires_in: 7200 })
}
if (url.pathname === '/media/upload') {
assert.equal(url.origin, 'https://oapi.dingtalk.com')
assert.equal(url.searchParams.get('type'), 'image')
assert.equal(new Headers(init?.headers).has('Content-Type'), false)
assert.ok(init?.body instanceof FormData)
const media = init.body.get('media')
assert.ok(media instanceof Blob)
assert.equal(media.type, 'image/jpeg')
assert.deepEqual(Buffer.from(await media.arrayBuffer()), jpeg)
uploaded = true
return Response.json({ errcode: 0, media_id: mediaId })
}
assert.equal(url.href, 'https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend')
assert.equal(uploaded, true)
const message = JSON.parse(String(init?.body))
assert.deepEqual(message.userIds, ['ding-user-1'])
assert.equal(message.msgKey, 'sampleMarkdown')
const text = JSON.parse(message.msgParam).text
assert.ok(text.includes(`![图片变更前后对照](${mediaId})`))
assert.ok(text.includes('[查看对比并审批](https://asset.example.com/review)'))
return Response.json({ processQueryKey: 'qa-image-message' })
}) as typeof fetch
try {
const uploadedId = await uploadRobotImage(jpeg)
assert.equal(uploadedId, mediaId)
assert.equal(await sendRobotMessage(actionCardInput({
content: `![图片变更前后对照](${uploadedId})`,
actionTitle: '查看对比并审批',
actionUrl: 'https://asset.example.com/review',
})), 'qa-image-message')
} finally {
global.fetch = oldFetch
if (oldRobotCode === undefined) delete process.env.DINGTALK_ROBOT_CODE
else process.env.DINGTALK_ROBOT_CODE = oldRobotCode
}
})
test('钉钉 HTTP 403 QPS 限流归一为中心标准错误并进入自动重试', async () => {
const originalFetch = global.fetch
const oldAppKey = process.env.DINGTALK_APP_KEY

View File

@ -26,10 +26,13 @@ const requestJson = async (
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 10_000)
try {
const headers = init?.body instanceof FormData
? init.headers
: { 'Content-Type': 'application/json', ...(init?.headers || {}) }
const response = await fetch(url, {
...init,
signal: controller.signal,
headers: { 'Content-Type': 'application/json', ...(init?.headers || {}) },
headers,
})
const data = await response.json().catch(() => ({})) as DingTalkPayload
if (!response.ok) {
@ -153,6 +156,23 @@ export const exchangeH5AuthCodeForUserId = async (code: string) => {
return userId
}
const mediaIdPattern = /^@[A-Za-z0-9_=-]{8,240}$/
const reviewImageMarkdown = /!\[图片变更前后对照\]\(@[A-Za-z0-9_=-]{8,240}\)/
export const uploadRobotImage = (image: Buffer) => withFreshTokenRetry(async () => {
const url = new URL('https://oapi.dingtalk.com/media/upload')
url.searchParams.set('access_token', await getToken())
url.searchParams.set('type', 'image')
const form = new FormData()
form.set('media', new Blob([Uint8Array.from(image)], { type: 'image/jpeg' }), 'preview.jpg')
const data = await requestJson(url.toString(), { method: 'POST', body: form })
const mediaId = clean(data.media_id)
if (!mediaIdPattern.test(mediaId)) {
throw new DingTalkError('钉钉未返回有效的图片媒体 ID', 'IMAGE_MEDIA_ID_MISSING')
}
return mediaId
})
export const sendRobotMessage = async (input: {
recipientUserId: string
title: string
@ -162,7 +182,13 @@ export const sendRobotMessage = async (input: {
}) => {
const { robotCode } = getDingTalkConfig()
const visibleTitle = input.title.slice(0, 120)
const visibleText = `### ${visibleTitle}\n\n${input.content}`.slice(0, 4800)
const hasMediaImage = reviewImageMarkdown.test(input.content)
const useActionCard = Boolean(input.actionUrl) && !hasMediaImage
const linkLabel = input.actionTitle.replace(/[\[\]\r\n]/g, '').slice(0, 20) || '查看详情'
const markdownLink = input.actionUrl && hasMediaImage
? `\n\n[${linkLabel}](${input.actionUrl.replace(/[()]/g, (char) => char === '(' ? '%28' : '%29')})`
: ''
const visibleText = `### ${visibleTitle}\n\n${input.content}`.slice(0, Math.max(0, 4800 - markdownLink.length)) + markdownLink
return withFreshTokenRetry(async () => {
const token = await getToken()
const data = await requestJson('https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend', {
@ -171,8 +197,8 @@ export const sendRobotMessage = async (input: {
body: JSON.stringify({
robotCode,
userIds: [input.recipientUserId],
msgKey: input.actionUrl ? 'sampleActionCard' : 'sampleMarkdown',
msgParam: JSON.stringify(input.actionUrl ? {
msgKey: useActionCard ? 'sampleActionCard' : 'sampleMarkdown',
msgParam: JSON.stringify(useActionCard ? {
title: visibleTitle,
text: visibleText,
singleTitle: input.actionTitle.slice(0, 20),

View File

@ -5,7 +5,7 @@ import { authenticateAdmin, type AdminRequest } from './admin-auth'
import { AdminApiError, AdminProjectRegistry, assertAdminRuntimeConfig, maskUserId, type ProjectRecipientInput, type ProjectUpdateInput, type ProjectUpsertInput } from './admin-project-registry'
import { assertRuntimeConfig, getDingTalkConfig, getPublicBaseUrl, loadProjectConfigs, type ProjectConfig, type ProjectLoginConfig } from './config'
import { NotificationDirectoryError, resolveRecipientAlias as resolveRecipientAliasFromDirectory } from './directory'
import { DingTalkError, exchangeH5AuthCodeForUserId, sendRobotMessage } from './dingtalk'
import { DingTalkError, exchangeH5AuthCodeForUserId, sendRobotMessage, uploadRobotImage } from './dingtalk'
import prisma from './prisma'
import { createCanonicalSignature, safeEqual, sha256 } from './signature'
import { classifyDeliveryFailure } from './worker'
@ -178,6 +178,7 @@ const renderActionUrl = (value: string, project: ProjectConfig) => {
type CreateServerDependencies = {
exchangeH5Code?: (code: string) => Promise<string>
sendTestMessage?: typeof sendRobotMessage
uploadPreviewImage?: typeof uploadRobotImage
resolveRecipientAlias?: (recipientAlias: string) => Promise<string>
}
@ -413,6 +414,7 @@ const writeAdminError = (res: Response, error: AdminApiError) =>
export const createServer = (projectSource: ProjectSource, dependencies: CreateServerDependencies = {}) => {
const exchangeH5Code = dependencies.exchangeH5Code || exchangeH5AuthCodeForUserId
const sendTestMessage = dependencies.sendTestMessage || sendRobotMessage
const uploadPreviewImage = dependencies.uploadPreviewImage || uploadRobotImage
const resolveRecipientAlias = dependencies.resolveRecipientAlias || resolveRecipientAliasFromDirectory
const app = express()
app.disable('x-powered-by')
@ -570,6 +572,27 @@ export const createServer = (projectSource: ProjectSource, dependencies: CreateS
}
}
app.post('/v1/notification-media/image', authenticate, async (req: SignedRequest, res, next) => {
const base64 = req.body?.image
if (typeof base64 !== 'string' || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) {
return res.status(400).json({ error: 'INVALID_IMAGE' })
}
const image = Buffer.from(base64, 'base64')
// JSON body stays below the existing 64 KiB limit after base64 encoding.
if (image.length < 5 || image.length > 44 * 1024 || image.toString('base64') !== base64
|| image[0] !== 0xff || image[1] !== 0xd8 || image[2] !== 0xff
|| image[image.length - 2] !== 0xff || image[image.length - 1] !== 0xd9) {
return res.status(400).json({ error: 'INVALID_IMAGE' })
}
try {
const mediaId = await uploadPreviewImage(image)
res.json({ mediaId })
} catch (error) {
if (error instanceof DingTalkError) return res.status(502).json({ error: 'IMAGE_UPLOAD_FAILED', code: error.code })
next(error)
}
})
app.post('/v1/notifications', authenticate, async (req: SignedRequest, res, next) => {
try {
const payload = await buildPublicNotificationInput({