Skip to content

Commit

Permalink
feat: 🎸 增加对入参的严格校验
Browse files Browse the repository at this point in the history
  • Loading branch information
chentianyu committed Sep 29, 2023
1 parent 3638ff7 commit 5537a95
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 18 deletions.
24 changes: 11 additions & 13 deletions src/route/msg.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { formatAndSendMsg } = require('../service/msg')
const { getUnvalidParamsList } = require('../utils/index')

module.exports = function registerPushHook({ app, bot }) {

Expand All @@ -8,19 +9,16 @@ module.exports = function registerPushHook({ app, bot }) {
const { to, isRoom = false, type, content } = req.body;

//校验必填参数
const checkList = [
{ key: 'to', val: to },
{ key: 'type', val: type },
{ key: 'content', val: content }
]

if (checkList.some(({ val }) => !val)) {
const unValidParamsStr = checkList
.filter(({ val }) => !val)
.map(({ key }) => key)
.join(',')

return res.status(200).json({ success: false, message: `[${unValidParamsStr}] params is not valid, please checkout the api reference (https://github.com/danni-cool/docker-wechatbot-webhook#API)` });
const unValidParamsStr = getUnvalidParamsList([
{ key: 'to', val: to, required: true, type: 'string', unValidReason: '' },
{ key: 'type', val: type, required: true, type: 'string', enum: ['text', 'img'], unValidReason: '' },
{ key: 'content', val: content, required: true, type: 'string', unValidReason: '' },
{ key: 'isRoom', val: isRoom, required: false, type: 'boolean', unValidReason: '' }
])
.map(({ unValidReason }) => unValidReason).join(',')

if (unValidParamsStr) {
return res.status(200).json({ success: false, message: `[${unValidParamsStr}] params is not valid, please checkout the api reference (https://github.com/danni-cool/docker-wechat-roomBot#body-%E5%8F%82%E6%95%B0%E8%AF%B4%E6%98%8E)` });
}

const targetMsgReceiver = isRoom ?
Expand Down
6 changes: 3 additions & 3 deletions src/service/webhook.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ const sendMsg2RecvdAPI = async function (msg, webhookUrl) {
// 得到收消息api,并做格式检查
const getValidRecvdApi = () => {
let webhookUrl = ''
let errorText = (key, value) => console.error(chalk.red(`配置参数 ${key}: ${chalk.cyan(value)} <- 不符合 URL 规范, 该 API 将不会收到请求\n`))
let errorText = (key, value) => console.error(chalk.red(`配置参数 ${key}: ${chalk.cyan(value)} <- 不符合 URL 规范, 该 API 将不会收到请求\n`))

// 外部传入了以外部为准
if (RECVD_MSG_API !== '') {
if (!['', undefined].includes(RECVD_MSG_API)) {
webhookUrl = ('' + RECVD_MSG_API).startsWith('http') ? RECVD_MSG_API : ''
!webhookUrl && errorText('RECVD_MSG_API', RECVD_MSG_API)
// 无外部则用本地
} else if (LOCAL_RECVD_MSG_API !== '') {
} else if (!['', undefined].includes(LOCAL_RECVD_MSG_API)) {
webhookUrl = ('' + LOCAL_RECVD_MSG_API).startsWith('http') ? LOCAL_RECVD_MSG_API : ''
!webhookUrl && errorText('LOCAL_RECVD_MSG_API', LOCAL_RECVD_MSG_API)
}
Expand Down
36 changes: 35 additions & 1 deletion src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,42 @@ const getFileNameFromUrl = url => url.match(/.*\/([^/?]*)/)?.[1] || ''
const getMediaFromUrl = async url =>
FileBox.fromBuffer(await downloadImage(url), getFileNameFromUrl(url))

/**
* @example
* const checkList = [
{ key: 'to', val: '', required: true, type: 'string', unValidReason: '' },
]
@return {Array} 返回不通过校验的数组项,并填充上 unValidReason 的原因
*/
const getUnvalidParamsList = arr => {
return arr
.map(item => {

// 区分必填和非必填情况,校验非空和类型
if (item.required) {
if (item.val === '') {
item.unValidReason = `${item.key} 不能为空`
}
else if (typeof item.val !== item.type) {
item.unValidReason = `${item.key} 的参数类型不是 ${item.type}`
}
} else {
item.unValidReason = typeof item.val !== item.type ? `${item.key} 的参数类型不是 ${item.type}` : ''
}

//前者通过,如果遇到要校验指定枚举值的情况
if(item.unValidReason === '' && (item.enum && item.enum.length >0)) {
item.unValidReason = !item.enum.includes(item.val) ? `${item.key} 必须是 ${item.enum.join(' or ')}` : ''
}

return item
})
.filter(({ unValidReason }) => unValidReason)
}

module.exports = {
getFileNameFromUrl,
getMediaFromUrl
getMediaFromUrl,
getUnvalidParamsList
}

7 changes: 6 additions & 1 deletion src/wechaty/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,18 @@ module.exports = function init() {
.on('login', async user => {
console.log(`User ${user} logged in`)
})
// .on('room-topic', async (room, topic, oldTopic, changer) => {
// console.log(`Room ${await room.topic()} topic changed from ${oldTopic} to ${topic} by ${changer.name()}`)
// })
.on('message', async message => {
console.log(`Message: ${message}`)

//收到消息二次转发特殊处理
webhookUrl && await sendMsg2RecvdAPI(message, webhookUrl)

})
.on('error', (error) => {
console.error(`\n${chalk.red(error)}\n`)
})

bot.start()

Expand Down

0 comments on commit 5537a95

Please sign in to comment.