twikoo-func 1.7.23 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js DELETED
@@ -1,1175 +0,0 @@
1
- /*!
2
- * Twikoo cloudbase function
3
- * (c) 2020-present iMaeGoo
4
- * Released under the MIT License.
5
- */
6
-
7
- const { version: VERSION } = require('./package.json')
8
- const tcb = require('@cloudbase/node-sdk') // 云开发 SDK
9
- const {
10
- getHtmlToText,
11
- getDomPurify,
12
- getMd5,
13
- getSha256,
14
- getXml2js
15
- } = require('./utils/lib')
16
- const {
17
- getFuncVersion,
18
- getUrlQuery,
19
- getUrlsQuery,
20
- parseComment,
21
- parseCommentForAdmin,
22
- normalizeMail,
23
- equalsMail,
24
- getMailMd5,
25
- getAvatar,
26
- isQQ,
27
- addQQMailSuffix,
28
- getQQAvatar,
29
- getQQNick,
30
- getPasswordStatus,
31
- preCheckSpam,
32
- checkTurnstileCaptcha,
33
- checkGeeTestCaptcha,
34
- checkCapCaptcha,
35
- getConfig,
36
- getConfigForAdmin,
37
- validate,
38
- checkCommentOwnership,
39
- isValidEmail
40
- } = require('./utils')
41
- const {
42
- createCap,
43
- tcbStorage,
44
- createChallenge,
45
- redeemChallenge,
46
- isBuiltinCap
47
- } = require('./utils/cap')
48
- const {
49
- jsonParse,
50
- commentImportValine,
51
- commentImportDisqus,
52
- commentImportArtalk,
53
- commentImportArtalk2,
54
- commentImportTwikoo
55
- } = require('./utils/import')
56
- const { postCheckSpam } = require('./utils/spam')
57
- const { sendNotice, emailTest } = require('./utils/notify')
58
- const { uploadImage } = require('./utils/image')
59
- const logger = require('./utils/logger')
60
-
61
- // 云函数 SDK / tencent cloudbase sdk
62
- const app = tcb.init({ env: tcb.SYMBOL_CURRENT_ENV })
63
- const auth = app.auth()
64
- const db = app.database()
65
- const _ = db.command
66
- const htmlToText = getHtmlToText()
67
- const DOMPurify = getDomPurify()
68
- const md5 = getMd5()
69
- const sha256 = getSha256()
70
- const xml2js = getXml2js()
71
-
72
- // 常量 / constants
73
- const { RES_CODE, MAX_REQUEST_TIMES } = require('./utils/constants')
74
- const ADMIN_USER_ID = 'admin'
75
-
76
- // 全局变量 / variables
77
- // 警告:全局定义的变量,会被云函数缓存,请慎重定义全局变量
78
- // 参考 https://docs.cloudbase.net/cloud-function/deep-principle.html 中的 “实例复用”
79
- let config
80
- const requestTimes = {}
81
-
82
- // 云函数入口点 / entry point
83
- exports.main = async (event, context) => {
84
- logger.log('请求 IP:', auth.getClientIP())
85
- logger.log('请求函数:', event.event)
86
- logger.log('请求参数:', event)
87
- let res = {}
88
- try {
89
- protect()
90
- await readConfig()
91
- switch (event.event) {
92
- case 'GET_FUNC_VERSION':
93
- res = getFuncVersion({ VERSION })
94
- break
95
- case 'COMMENT_GET':
96
- res = await commentGet(event)
97
- break
98
- case 'COMMENT_GET_FOR_ADMIN':
99
- res = await commentGetForAdmin(event)
100
- break
101
- case 'COMMENT_SET_FOR_ADMIN':
102
- res = await commentSetForAdmin(event)
103
- break
104
- case 'COMMENT_DELETE_FOR_ADMIN':
105
- res = await commentDeleteForAdmin(event)
106
- break
107
- case 'COMMENT_IMPORT_FOR_ADMIN':
108
- res = await commentImportForAdmin(event)
109
- break
110
- case 'COMMENT_LIKE':
111
- res = await commentLike(event)
112
- break
113
- case 'COMMENT_SUBMIT':
114
- res = await commentSubmit(event, context)
115
- break
116
- case 'POST_SUBMIT':
117
- res = await postSubmit(event.comment, context)
118
- break
119
- case 'COUNTER_GET':
120
- res = await counterGet(event)
121
- break
122
- case 'GET_PASSWORD_STATUS':
123
- res = await getPasswordStatus(config, VERSION)
124
- break
125
- case 'SET_PASSWORD':
126
- res = await setPassword(event)
127
- break
128
- case 'GET_CONFIG':
129
- res = getConfig({ config, VERSION, isAdmin: await isAdmin() })
130
- break
131
- case 'GET_CONFIG_FOR_ADMIN':
132
- res = await getConfigForAdmin({ config, isAdmin: await isAdmin() })
133
- break
134
- case 'SET_CONFIG':
135
- res = await setConfig(event)
136
- break
137
- case 'LOGIN':
138
- res = await login(event.password)
139
- break
140
- case 'GET_COMMENTS_COUNT': // >= 0.2.7
141
- res = await getCommentsCount(event)
142
- break
143
- case 'GET_RECENT_COMMENTS': // >= 0.2.7
144
- res = await getRecentComments(event)
145
- break
146
- case 'EMAIL_TEST': // >= 1.4.6
147
- res = await emailTest(event, config, await isAdmin())
148
- break
149
- case 'UPLOAD_IMAGE': // >= 1.5.0
150
- res = await uploadImage(event, config)
151
- break
152
- case 'GET_QQ_NICK': // >= 1.7.0
153
- res = await qqNickGet(event)
154
- break
155
- case 'COMMENT_EXPORT_FOR_ADMIN': // >= 1.6.13
156
- res = await commentExportForAdmin(event)
157
- break
158
- case 'COMMENT_DELETE_FOR_USER':
159
- res = await commentDeleteForUser(event)
160
- break
161
- case 'CAP_CHALLENGE': // embedded Cap.js
162
- res = await capChallenge()
163
- break
164
- case 'CAP_REDEEM':
165
- res = await capRedeem(event)
166
- break
167
- default:
168
- if (event.event) {
169
- res.code = RES_CODE.EVENT_NOT_EXIST
170
- res.message = '请更新 Twikoo 云函数至最新版本'
171
- } else {
172
- res.code = RES_CODE.SUCCESS
173
- res.message = 'Twikoo 云函数运行正常,请参考 https://twikoo.js.org/frontend.html 完成前端的配置'
174
- }
175
- }
176
- } catch (e) {
177
- logger.error('Twikoo 遇到错误,请参考以下错误信息。如有疑问,请反馈至 https://github.com/twikoojs/twikoo/issues')
178
- logger.error('请求参数:', event)
179
- logger.error('错误信息:', e)
180
- res.code = RES_CODE.FAIL
181
- res.message = e.message
182
- }
183
- logger.log('请求返回:', res)
184
- return res
185
- }
186
-
187
- // 写入管理密码
188
- async function setPassword (event) {
189
- const isAdminUser = await isAdmin()
190
- // 如果数据库里没有密码,则写入密码
191
- // 如果数据库里有密码,则只有管理员可以写入密码
192
- if (config.ADMIN_PASS && !isAdminUser) {
193
- return { code: RES_CODE.PASS_EXIST, message: '请先登录再修改密码' }
194
- }
195
- if (!config.CREDENTIALS && !event.credentials) {
196
- return { code: RES_CODE.CREDENTIALS_NOT_EXIST, message: '未配置登录私钥' }
197
- }
198
- if (!config.CREDENTIALS && event.credentials) {
199
- const checkResult = await checkAndSaveCredentials(event.credentials)
200
- if (!checkResult) {
201
- return { code: RES_CODE.CREDENTIALS_INVALID, message: '无效的私钥文件' }
202
- }
203
- }
204
- const ADMIN_PASS = md5(event.password)
205
- await writeConfig({ ADMIN_PASS })
206
- return {
207
- code: RES_CODE.SUCCESS
208
- }
209
- }
210
-
211
- async function checkAndSaveCredentials (credentials) {
212
- try {
213
- const ticket = getAdminTicket(JSON.parse(credentials))
214
- if (!ticket) return false
215
- await writeConfig({ CREDENTIALS: credentials })
216
- return true
217
- } catch (e) {
218
- logger.error('私钥文件异常:', e)
219
- return false
220
- }
221
- }
222
-
223
- // 管理员登录
224
- async function login (password) {
225
- if (!config) {
226
- return { code: RES_CODE.CONFIG_NOT_EXIST, message: '数据库无配置' }
227
- }
228
- if (!config.CREDENTIALS) {
229
- return { code: RES_CODE.CREDENTIALS_NOT_EXIST, message: '未配置登录私钥' }
230
- }
231
- if (!config.ADMIN_PASS) {
232
- return { code: RES_CODE.PASS_NOT_EXIST, message: '未配置管理密码' }
233
- }
234
- if (config.ADMIN_PASS !== md5(password)) {
235
- return { code: RES_CODE.PASS_NOT_MATCH, message: '密码错误' }
236
- }
237
- return {
238
- code: RES_CODE.SUCCESS,
239
- ticket: getAdminTicket(JSON.parse(config.CREDENTIALS))
240
- }
241
- }
242
-
243
- // 获取管理员登录 ticket
244
- function getAdminTicket (credentials) {
245
- const adminApp = tcb.init({ env: tcb.SYMBOL_CURRENT_ENV, credentials })
246
- const ticket = adminApp.auth().createTicket(ADMIN_USER_ID, {
247
- refresh: 3600 * 1000 // access_token的刷新时间
248
- })
249
- return ticket
250
- }
251
-
252
- function getSearchKeyword (event) {
253
- if (event.keyword === undefined || event.keyword === null) return ''
254
- if (typeof event.keyword !== 'string') throw new Error('搜索关键词必须是字符串')
255
- const keyword = event.keyword.trim()
256
- if (keyword.length > 100) throw new Error('搜索关键词不能超过 100 个字符')
257
- return keyword
258
- }
259
-
260
- function commentMatchesKeyword (comment, keyword) {
261
- return [comment.nick, comment.comment].some(value =>
262
- typeof value === 'string' && value.toLowerCase().includes(keyword)
263
- )
264
- }
265
-
266
- function escapeRegExp (value) {
267
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
268
- }
269
-
270
- // 读取评论
271
- async function commentGet (event) {
272
- const res = {}
273
- try {
274
- validate(event, ['url'])
275
- if (getSearchKeyword(event)) return commentSearch(event)
276
- const uid = await auth.getEndUserInfo().userInfo.uid
277
- const isAdminUser = await isAdmin()
278
- const limit = parseInt(config.COMMENT_PAGE_SIZE) || 8
279
- const sort = event.sort || 'newest'
280
- let more = false
281
- let condition
282
- let query
283
- condition = {
284
- url: _.in(getUrlQuery(event.url)),
285
- rid: _.in(['', null])
286
- }
287
- // 按当前用户和配置查询可见评论
288
- query = getCommentQuery({ condition, uid, isAdminUser })
289
- // 读取总条数
290
- const count = await db
291
- .collection('comment')
292
- .where(query)
293
- .count()
294
- // 读取主楼
295
- if (event.before) {
296
- condition.created = _.lt(event.before)
297
- }
298
- // 不包含置顶
299
- condition.top = _.neq(true)
300
- query = getCommentQuery({ condition, uid, isAdminUser })
301
-
302
- let orderField = 'created'
303
- let orderDirection = 'desc'
304
- if (sort === 'oldest') {
305
- orderField = 'created'
306
- orderDirection = 'asc'
307
- } else if (sort === 'popular') {
308
- orderField = 'ups'
309
- orderDirection = 'desc'
310
- }
311
-
312
- const main = await db
313
- .collection('comment')
314
- .where(query)
315
- .orderBy(orderField, orderDirection)
316
- // 流式分页,通过多读 1 条的方式,确认是否还有更多评论
317
- .limit(limit + 1)
318
- .get()
319
- if (main.data.length > limit) {
320
- // 还有更多评论
321
- more = true
322
- // 删除多读的 1 条
323
- main.data.splice(limit, 1)
324
- }
325
- let top = []
326
- if (!config.TOP_DISABLED && !event.before) {
327
- // 查询置顶评论
328
- query = getCommentQuery({ condition: { ...condition, top: true }, uid, isAdminUser })
329
- top = await db
330
- .collection('comment')
331
- .where(query)
332
- .orderBy('updated', 'desc')
333
- .get()
334
- // 合并置顶评论和非置顶评论
335
- main.data = [
336
- ...top.data,
337
- ...main.data
338
- ]
339
- }
340
- condition = {
341
- rid: _.in(main.data.map((item) => item._id))
342
- }
343
- query = getCommentQuery({ condition, uid, isAdminUser })
344
- // 读取回复楼
345
- const reply = await db
346
- .collection('comment')
347
- .where(query)
348
- .get()
349
- res.data = parseComment([...main.data, ...reply.data], uid, config)
350
- res.more = more
351
- res.count = count.total
352
- } catch (e) {
353
- res.data = []
354
- res.message = e.message
355
- }
356
- return res
357
- }
358
-
359
- async function commentSearch (event) {
360
- const res = {}
361
- try {
362
- validate(event, ['url'])
363
- const keyword = getSearchKeyword(event).toLowerCase()
364
- const page = Math.max(parseInt(event.page) || 1, 1)
365
- const uid = await auth.getEndUserInfo().userInfo.uid
366
- const isAdminUser = await isAdmin()
367
- const limit = parseInt(config.COMMENT_PAGE_SIZE) || 8
368
- const sort = event.sort || 'newest'
369
- let more = false
370
-
371
- const condition = { url: _.in(getUrlQuery(event.url)) }
372
- const query = getCommentQuery({ condition, uid, isAdminUser })
373
- const searchComments = []
374
- let cursor
375
- while (true) {
376
- const batchQuery = cursor
377
- ? _.and(query, _.or(
378
- { created: _.gt(cursor.created) },
379
- { created: cursor.created, _id: _.gt(cursor._id) }
380
- ))
381
- : query
382
- const batch = await db.collection('comment')
383
- .where(batchQuery)
384
- .orderBy('created', 'asc')
385
- .orderBy('_id', 'asc')
386
- .limit(100)
387
- .get()
388
- searchComments.push(...batch.data)
389
- if (batch.data.length < 100) break
390
- cursor = batch.data[batch.data.length - 1]
391
- }
392
- const matchedRoots = new Set(searchComments
393
- .filter(comment => commentMatchesKeyword(comment, keyword))
394
- .map(comment => String(comment.rid || comment._id)))
395
- let main = searchComments.filter(comment =>
396
- (!comment.rid || comment.rid === '') && matchedRoots.has(String(comment._id))
397
- )
398
- const count = main.length
399
-
400
- main.sort((a, b) => {
401
- if (sort === 'oldest') return a.created - b.created
402
- if (sort === 'popular') {
403
- const ups = (b.ups || []).length - (a.ups || []).length
404
- if (ups) return ups
405
- }
406
- return b.created - a.created
407
- })
408
- let top = []
409
- if (!config.TOP_DISABLED) {
410
- if (page === 1) top = main.filter(comment => comment.top === true)
411
- main = main.filter(comment => comment.top !== true)
412
- }
413
- main = main.slice((page - 1) * limit, page * limit + 1)
414
-
415
- if (main.length > limit) {
416
- more = true
417
- main = main.slice(0, limit)
418
- }
419
- main = [...top, ...main]
420
-
421
- const mainIds = new Set(main.map(comment => String(comment._id)))
422
- const reply = searchComments.filter(comment => mainIds.has(String(comment.rid)))
423
- res.data = parseComment([...main, ...reply], uid, config)
424
- res.more = more
425
- res.count = count
426
- } catch (e) {
427
- res.data = []
428
- res.message = e.message
429
- }
430
- return res
431
- }
432
-
433
- function getCommentQuery ({ condition, uid, isAdminUser }) {
434
- if (config.HIDE_SPAM === 'true') {
435
- return { ...condition, isSpam: _.neq(true) }
436
- }
437
- return _.or(
438
- { ...condition, isSpam: _.neq(isAdminUser ? 'imaegoo' : true) },
439
- { ...condition, uid }
440
- )
441
- }
442
-
443
- // 管理员读取评论
444
- async function commentGetForAdmin (event) {
445
- const res = {}
446
- const isAdminUser = await isAdmin()
447
- if (isAdminUser) {
448
- validate(event, ['per', 'page'])
449
- const collection = db
450
- .collection('comment')
451
- const condition = getCommentSearchCondition(event)
452
- const count = await collection
453
- .where(condition)
454
- .count()
455
- const data = await collection
456
- .where(condition)
457
- .orderBy('created', 'desc')
458
- .skip(event.per * (event.page - 1))
459
- .limit(event.per)
460
- .get()
461
- res.code = RES_CODE.SUCCESS
462
- res.count = count.total
463
- res.data = parseCommentForAdmin(data.data)
464
- } else {
465
- res.code = RES_CODE.NEED_LOGIN
466
- res.message = '请先登录'
467
- }
468
- return res
469
- }
470
-
471
- function getCommentSearchCondition (event) {
472
- let condition = {}
473
- if (event.type) {
474
- switch (event.type) {
475
- case 'VISIBLE':
476
- condition = { isSpam: _.neq(true) }
477
- break
478
- case 'HIDDEN':
479
- condition = { isSpam: true }
480
- break
481
- }
482
- }
483
- const keyword = getSearchKeyword(event)
484
- if (keyword) {
485
- const regExp = new db.RegExp({
486
- regexp: escapeRegExp(keyword),
487
- options: 'i'
488
- })
489
- condition = _.or(
490
- { ...condition, nick: regExp },
491
- { ...condition, mail: regExp },
492
- { ...condition, link: regExp },
493
- { ...condition, ip: regExp },
494
- { ...condition, comment: regExp },
495
- { ...condition, url: regExp },
496
- { ...condition, href: regExp }
497
- )
498
- }
499
- return condition
500
- }
501
-
502
- // 管理员修改评论
503
- async function commentSetForAdmin (event) {
504
- const res = {}
505
- const isAdminUser = await isAdmin()
506
- if (isAdminUser) {
507
- validate(event, ['id', 'set'])
508
- const data = await db
509
- .collection('comment')
510
- .doc(event.id)
511
- .update({
512
- ...event.set,
513
- updated: Date.now()
514
- })
515
- res.code = RES_CODE.SUCCESS
516
- res.updated = data.updated
517
- } else {
518
- res.code = RES_CODE.NEED_LOGIN
519
- res.message = '请先登录'
520
- }
521
- return res
522
- }
523
-
524
- // 管理员删除评论
525
- async function commentDeleteForAdmin (event) {
526
- const res = {}
527
- const isAdminUser = await isAdmin()
528
- if (isAdminUser) {
529
- validate(event, ['id'])
530
- const data = await db
531
- .collection('comment')
532
- .doc(event.id)
533
- .delete()
534
- res.code = RES_CODE.SUCCESS
535
- res.deleted = data.deleted
536
- } else {
537
- res.code = RES_CODE.NEED_LOGIN
538
- res.message = '请先登录'
539
- }
540
- return res
541
- }
542
-
543
- // 用户删除自己的评论
544
- async function commentDeleteForUser (event) {
545
- const res = {}
546
- try {
547
- const uid = await getUid()
548
- await checkCommentOwnership(event.id, uid, async (id) => {
549
- const doc = await db.collection('comment').doc(id).get()
550
- return doc.data && doc.data.length > 0 ? doc.data[0] : null
551
- })
552
- const data = await db.collection('comment').doc(event.id).delete()
553
- res.code = RES_CODE.SUCCESS
554
- res.deleted = data.deleted
555
- } catch (e) {
556
- res.code = RES_CODE.FAIL
557
- res.message = e.message
558
- }
559
- return res
560
- }
561
-
562
- // 管理员导入评论
563
- async function commentImportForAdmin (event) {
564
- const res = {}
565
- let logText = ''
566
- const log = (message) => {
567
- logText += `${new Date().toLocaleString()} ${message}\n`
568
- }
569
- const isAdminUser = await isAdmin()
570
- if (isAdminUser) {
571
- try {
572
- validate(event, ['source', 'fileId'])
573
- log(`开始导入 ${event.source}`)
574
- let comments
575
- switch (event.source) {
576
- case 'valine': {
577
- const valineDb = await readFile(event.fileId, 'json', log)
578
- comments = await commentImportValine(valineDb, log)
579
- break
580
- }
581
- case 'disqus': {
582
- const disqusDb = await readFile(event.fileId, 'xml', log)
583
- comments = await commentImportDisqus(disqusDb, log)
584
- break
585
- }
586
- case 'artalk': {
587
- const artalkDb = await readFile(event.fileId, 'json', log)
588
- comments = await commentImportArtalk(artalkDb, log)
589
- break
590
- }
591
- case 'artalk2': {
592
- const artalkDb = await readFile(event.fileId, 'json', log)
593
- comments = await commentImportArtalk2(artalkDb, log)
594
- break
595
- }
596
- case 'twikoo': {
597
- const twikooDb = await readFile(event.fileId, 'json', log)
598
- comments = await commentImportTwikoo(twikooDb, log)
599
- break
600
- }
601
- default:
602
- throw new Error(`不支持 ${event.source} 的导入,请更新 Twikoo 云函数至最新版本`)
603
- }
604
- const ids = await bulkSaveComments(comments)
605
- log(`导入成功 ${ids.length} 条评论`)
606
- // 删除导入完成的文件
607
- await app.deleteFile({ fileList: [event.fileId] })
608
- } catch (e) {
609
- log(e.message)
610
- }
611
- res.code = RES_CODE.SUCCESS
612
- res.log = logText
613
- logger.info(logText)
614
- } else {
615
- res.code = RES_CODE.NEED_LOGIN
616
- res.message = '请先登录'
617
- }
618
- return res
619
- }
620
-
621
- async function commentExportForAdmin (event) {
622
- const res = {}
623
- const isAdminUser = await isAdmin()
624
- if (isAdminUser) {
625
- const collection = event.collection || 'comment'
626
- const data = await db
627
- .collection(collection)
628
- .get()
629
- res.code = RES_CODE.SUCCESS
630
- res.data = data.data
631
- } else {
632
- res.code = RES_CODE.NEED_LOGIN
633
- res.message = '请先登录'
634
- }
635
- return res
636
- }
637
-
638
- // 读取云存储中的文件并转为 js object
639
- async function readFile (fileId, type, log) {
640
- try {
641
- const result = await app.downloadFile({ fileID: fileId })
642
- log('评论文件下载成功')
643
- let content = result.fileContent.toString('utf8')
644
- log('评论文件读取成功')
645
- if (type === 'json') {
646
- content = jsonParse(content)
647
- log('评论文件 JSON 解析成功')
648
- } else if (type === 'xml') {
649
- content = await xml2js.parseStringPromise(content)
650
- log('评论文件 XML 解析成功')
651
- }
652
- return content
653
- } catch (e) {
654
- log(`评论文件读取失败:${e.message}`)
655
- }
656
- }
657
-
658
- // 批量导入评论
659
- async function bulkSaveComments (comments) {
660
- const batchRes = await db
661
- .collection('comment')
662
- .add(comments)
663
- return batchRes.ids
664
- }
665
-
666
- // 点赞 / 反对 / 取消点赞
667
- async function commentLike (event) {
668
- const res = {}
669
- let uid
670
- try {
671
- validate(event, ['id'])
672
- uid = await auth.getEndUserInfo().userInfo.uid
673
- } catch (e) {
674
- res.message = e.message
675
- return res
676
- }
677
- const type = event.type || 'up'
678
- res.updated = await like(event.id, uid, type)
679
- return res
680
- }
681
-
682
- // 点赞 / 反对 / 取消
683
- async function like (id, uid, type) {
684
- const record = db
685
- .collection('comment')
686
- .where({ _id: id })
687
- const comment = await record.get()
688
- const commentData = comment.data[0] || {}
689
- const ups = commentData.ups || []
690
- const downs = commentData.downs || []
691
-
692
- let newUps = [...ups]
693
- let newDowns = [...downs]
694
-
695
- if (type === 'up') {
696
- if (ups.includes(uid)) {
697
- newUps = ups.filter((item) => item !== uid)
698
- } else {
699
- newUps.push(uid)
700
- newDowns = downs.filter((item) => item !== uid)
701
- }
702
- } else if (type === 'down') {
703
- if (downs.includes(uid)) {
704
- newDowns = downs.filter((item) => item !== uid)
705
- } else {
706
- newDowns.push(uid)
707
- newUps = ups.filter((item) => item !== uid)
708
- }
709
- }
710
-
711
- const result = await record.update({ ups: newUps, downs: newDowns })
712
- return result.updated
713
- }
714
-
715
- /**
716
- * 提交评论。分为多个步骤
717
- * 1. 参数校验
718
- * 2. 预检测垃圾评论(包括限流、人工审核、违禁词检测等)
719
- * 3. 保存到数据库
720
- * 4. 触发异步任务(包括 IM 通知、邮件通知、第三方垃圾评论检测
721
- * 等,因为这些任务比较耗时,所以要放在另一个线程进行)
722
- * @param {String} event.nick 昵称
723
- * @param {String} event.mail 邮箱
724
- * @param {String} event.link 网址
725
- * @param {String} event.ua UserAgent
726
- * @param {String} event.url 评论页地址
727
- * @param {String} event.comment 评论内容
728
- * @param {String} event.pid 回复的 ID
729
- * @param {String} event.rid 评论楼 ID
730
- */
731
- async function commentSubmit (event, context) {
732
- const res = {}
733
- // 参数校验
734
- validate(event, ['url', 'ua', 'comment'])
735
- // 限流
736
- await limitFilter()
737
- // 验证码
738
- await checkCaptcha(event)
739
- // 预检测、转换
740
- const data = await parse(event)
741
- // 保存
742
- const comment = await save(data)
743
- res.id = comment.id
744
- // 异步垃圾检测、发送评论通知
745
- try {
746
- await app.callFunction({
747
- name: context.function_name,
748
- data: { event: 'POST_SUBMIT', comment }
749
- }, { timeout: 300 }) // 设置较短的 timeout 来实现异步
750
- } catch (e) {
751
- logger.log('开始异步垃圾检测、发送评论通知')
752
- }
753
- return res
754
- }
755
-
756
- // 保存评论
757
- async function save (data) {
758
- const result = await db
759
- .collection('comment')
760
- .add(data)
761
- data.id = result.id
762
- return data
763
- }
764
-
765
- async function getParentComment (currentComment) {
766
- const parentComment = await db
767
- .collection('comment')
768
- .where({ _id: currentComment.pid })
769
- .get()
770
- return parentComment.data[0]
771
- }
772
-
773
- // 异步垃圾检测、发送评论通知
774
- async function postSubmit (comment, context) {
775
- if (!isRecursion(context)) return { code: RES_CODE.FORBIDDEN }
776
- // 垃圾检测
777
- const isSpam = await postCheckSpam(comment, config)
778
- await saveSpamCheckResult(comment, isSpam)
779
- // 发送通知
780
- await sendNotice(comment, config, getParentComment)
781
- return { code: RES_CODE.SUCCESS }
782
- }
783
-
784
- // 将评论转为数据库存储格式
785
- async function parse (comment) {
786
- const timestamp = Date.now()
787
- const isAdminUser = await isAdmin()
788
- const isBloggerMail = equalsMail(comment.mail, config.BLOGGER_EMAIL)
789
- if (isBloggerMail && !isAdminUser) throw new Error('请先登录管理面板,再使用博主身份发送评论')
790
- if (comment.mail && !isValidEmail(comment.mail)) throw new Error('邮箱格式不合法')
791
- const hashMethod = config.GRAVATAR_CDN === 'cravatar.cn' ? md5 : sha256
792
- const commentDo = {
793
- uid: await getUid(),
794
- nick: comment.nick ? comment.nick : '匿名',
795
- mail: comment.mail ? comment.mail : '',
796
- mailMd5: comment.mail ? hashMethod(normalizeMail(comment.mail)) : '',
797
- link: comment.link ? comment.link : '',
798
- ua: comment.ua,
799
- ip: auth.getClientIP(),
800
- master: isBloggerMail,
801
- url: comment.url,
802
- href: comment.href,
803
- comment: DOMPurify.sanitize(comment.comment, { FORBID_TAGS: ['style'], FORBID_ATTR: ['style'] }),
804
- pid: comment.pid ? comment.pid : comment.rid,
805
- rid: comment.rid,
806
- isSpam: isAdminUser ? false : preCheckSpam(comment, config),
807
- created: timestamp,
808
- updated: timestamp
809
- }
810
- if (isQQ(comment.mail)) {
811
- commentDo.mail = addQQMailSuffix(comment.mail)
812
- commentDo.mailMd5 = hashMethod(normalizeMail(commentDo.mail))
813
- commentDo.avatar = await getQQAvatar(comment.mail)
814
- }
815
- return commentDo
816
- }
817
-
818
- // 限流
819
- async function limitFilter () {
820
- // 限制每个 IP 每 10 分钟发表的评论数量
821
- let limitPerMinute = parseInt(config.LIMIT_PER_MINUTE)
822
- if (Number.isNaN(limitPerMinute)) limitPerMinute = 10
823
- if (limitPerMinute) {
824
- let count = await db
825
- .collection('comment')
826
- .where({
827
- ip: auth.getClientIP(),
828
- created: _.gt(Date.now() - 600000)
829
- })
830
- .count()
831
- count = count.total
832
- if (count > limitPerMinute) {
833
- throw new Error('发言频率过高')
834
- }
835
- }
836
- // 限制所有 IP 每 10 分钟发表的评论数量
837
- let limitPerMinuteAll = parseInt(config.LIMIT_PER_MINUTE_ALL)
838
- if (Number.isNaN(limitPerMinuteAll)) limitPerMinuteAll = 10
839
- if (limitPerMinuteAll) {
840
- let count = await db
841
- .collection('comment')
842
- .where({
843
- created: _.gt(Date.now() - 600000)
844
- })
845
- .count()
846
- count = count.total
847
- if (count > limitPerMinuteAll) {
848
- throw new Error('评论太火爆啦 >_< 请稍后再试')
849
- }
850
- }
851
- }
852
-
853
- async function checkCaptcha (comment) {
854
- const provider = config.CAPTCHA_PROVIDER
855
- if (provider === 'Turnstile' && config.TURNSTILE_SITE_KEY && config.TURNSTILE_SECRET_KEY) {
856
- await checkTurnstileCaptcha({
857
- ip: auth.getClientIP(),
858
- turnstileToken: comment.turnstileToken,
859
- turnstileTokenSecretKey: config.TURNSTILE_SECRET_KEY
860
- })
861
- } else if (provider === 'Geetest' && config.GEETEST_CAPTCHA_ID && config.GEETEST_CAPTCHA_KEY) {
862
- await checkGeeTestCaptcha({
863
- geeTestCaptchaId: config.GEETEST_CAPTCHA_ID,
864
- geeTestCaptchaKey: config.GEETEST_CAPTCHA_KEY,
865
- geeTestLotNumber: comment.geeTestLotNumber,
866
- geeTestCaptchaOutput: comment.geeTestCaptchaOutput,
867
- geeTestPassToken: comment.geeTestPassToken,
868
- geeTestGenTime: comment.geeTestGenTime
869
- })
870
- } else if (provider === 'Cap' && isBuiltinCap(config)) {
871
- if (!comment.capToken) {
872
- throw new Error('验证码 token 缺失,请刷新页面重试')
873
- }
874
- await checkCapCaptcha({
875
- capToken: comment.capToken,
876
- cap: createCap(tcbStorage(db))
877
- })
878
- } else if (provider === 'Cap' && config.CAP_API_ENDPOINT && config.CAP_SECRET_KEY) {
879
- if (!comment.capToken) {
880
- throw new Error('验证码 token 缺失,请刷新页面重试')
881
- }
882
- await checkCapCaptcha({
883
- capToken: comment.capToken,
884
- capSecretKey: config.CAP_SECRET_KEY,
885
- capApiEndpoint: config.CAP_API_ENDPOINT
886
- })
887
- } else if (provider === 'Cap') {
888
- throw new Error('Cap 验证码配置不完整:内嵌模式无需额外配置,外部模式需填写 CAP_API_ENDPOINT 与 CAP_SECRET_KEY')
889
- } else if (provider) {
890
- throw new Error(`不支持的验证码类型: ${provider}`)
891
- }
892
- }
893
-
894
- async function saveSpamCheckResult (comment, isSpam) {
895
- comment.isSpam = isSpam
896
- if (isSpam) {
897
- await db
898
- .collection('comment')
899
- .doc(comment.id)
900
- .update({
901
- isSpam,
902
- updated: Date.now()
903
- })
904
- }
905
- }
906
-
907
- /**
908
- * 获取文章点击量
909
- * @param {String} event.url 文章地址
910
- */
911
- async function counterGet (event) {
912
- const res = {}
913
- try {
914
- validate(event, ['url'])
915
- const record = await readCounter(event.url)
916
- res.data = record.data[0] ? record.data[0] : {}
917
- res.time = res.data ? res.data.time : 0
918
- res.updated = await incCounter(event)
919
- } catch (e) {
920
- res.message = e.message
921
- return res
922
- }
923
- return res
924
- }
925
-
926
- // 读取阅读数
927
- async function readCounter (url) {
928
- return await db
929
- .collection('counter')
930
- .where({ url })
931
- .get()
932
- }
933
-
934
- /**
935
- * 更新阅读数
936
- * @param {String} event.url 文章地址
937
- * @param {String} event.title 文章标题
938
- */
939
- async function incCounter (event) {
940
- let result
941
- result = await db
942
- .collection('counter')
943
- .where({ url: event.url })
944
- .update({
945
- title: event.title,
946
- time: _.inc(1),
947
- updated: Date.now()
948
- })
949
- if (result.updated === 0) {
950
- result = await db
951
- .collection('counter')
952
- .add({
953
- url: event.url,
954
- title: event.title,
955
- time: 1,
956
- created: Date.now(),
957
- updated: Date.now()
958
- })
959
- }
960
- return result.updated || result.inserted
961
- }
962
-
963
- /**
964
- * 批量获取文章评论数 API
965
- * @param {Array} event.urls 不包含协议和域名的文章路径列表,必传参数
966
- * @param {Boolean} event.includeReply 评论数是否包括回复,默认:false
967
- */
968
- async function getCommentsCount (event) {
969
- const res = {}
970
- try {
971
- validate(event, ['urls'])
972
- const query = {}
973
- query.isSpam = _.neq(true)
974
- query.url = _.in(getUrlsQuery(event.urls))
975
- if (!event.includeReply) {
976
- query.rid = _.in(['', null])
977
- }
978
- const result = await db
979
- .collection('comment')
980
- .aggregate()
981
- .match(query)
982
- .group({ _id: '$url', count: _.aggregate.sum(1) })
983
- .end()
984
- res.data = []
985
- for (const url of event.urls) {
986
- const record = result.data.find((item) => item._id === url)
987
- res.data.push({
988
- url,
989
- count: record ? record.count : 0
990
- })
991
- }
992
- } catch (e) {
993
- res.message = e.message
994
- return res
995
- }
996
- return res
997
- }
998
-
999
- /**
1000
- * 获取最新评论 API
1001
- * @param {Boolean} event.includeReply 评论数是否包括回复,默认:false
1002
- */
1003
- async function getRecentComments (event) {
1004
- const res = {}
1005
- try {
1006
- const query = {}
1007
- query.isSpam = _.neq(true)
1008
- if (event.urls && event.urls.length) {
1009
- query.url = _.in(getUrlsQuery(event.urls))
1010
- }
1011
- if (!event.includeReply) query.rid = _.in(['', null])
1012
- if (event.pageSize > 100) event.pageSize = 100
1013
- const result = await db
1014
- .collection('comment')
1015
- .where(query)
1016
- .orderBy('created', 'desc')
1017
- .limit(event.pageSize || 10)
1018
- .get()
1019
- res.data = result.data.map((comment) => {
1020
- return {
1021
- id: comment._id,
1022
- url: comment.url,
1023
- href: comment.href,
1024
- nick: comment.nick,
1025
- avatar: getAvatar(comment, config),
1026
- mailMd5: getMailMd5(comment),
1027
- link: comment.link,
1028
- comment: comment.comment,
1029
- commentText: htmlToText(comment.comment),
1030
- created: comment.created
1031
- }
1032
- })
1033
- } catch (e) {
1034
- res.message = e.message
1035
- return res
1036
- }
1037
- return res
1038
- }
1039
-
1040
- // 获取 QQ 昵称
1041
- async function qqNickGet (event) {
1042
- const res = {}
1043
- try {
1044
- validate(event, ['qq'])
1045
- const nick = await getQQNick(event.qq, config.QQ_API_KEY)
1046
- res.code = RES_CODE.SUCCESS
1047
- res.nick = nick
1048
- } catch (e) {
1049
- res.code = RES_CODE.FAIL
1050
- res.message = e.message
1051
- }
1052
- return res
1053
- }
1054
-
1055
- // 修改配置
1056
- async function setConfig (event) {
1057
- const isAdminUser = await isAdmin()
1058
- if (isAdminUser) {
1059
- writeConfig(event.config)
1060
- return {
1061
- code: RES_CODE.SUCCESS
1062
- }
1063
- } else {
1064
- return {
1065
- code: RES_CODE.NEED_LOGIN,
1066
- message: '请先登录'
1067
- }
1068
- }
1069
- }
1070
-
1071
- function protect () {
1072
- // 防御
1073
- const ip = auth.getClientIP()
1074
- requestTimes[ip] = (requestTimes[ip] || 0) + 1
1075
- if (requestTimes[ip] > MAX_REQUEST_TIMES) {
1076
- logger.warn(`${ip} 当前请求次数为 ${requestTimes[ip]},已超过最大请求次数`)
1077
- throw new Error('Too Many Requests')
1078
- } else {
1079
- logger.log(`${ip} 当前请求次数为 ${requestTimes[ip]}`)
1080
- }
1081
- }
1082
-
1083
- // 读取配置
1084
- async function readConfig () {
1085
- try {
1086
- const res = await db
1087
- .collection('config')
1088
- .limit(1)
1089
- .get()
1090
- config = res.data[0] || {}
1091
- return config
1092
- } catch (e) {
1093
- logger.error('读取配置失败:', e)
1094
- await createCollections()
1095
- config = {}
1096
- return config
1097
- }
1098
- }
1099
-
1100
- // 写入配置
1101
- async function writeConfig (newConfig) {
1102
- if (!Object.keys(newConfig).length) return 0
1103
- logger.info('写入配置:', newConfig)
1104
- try {
1105
- let updated
1106
- let res = await db
1107
- .collection('config')
1108
- .where({}) // 不加 where 会报错 Error: param should have required property 'query'
1109
- .limit(1)
1110
- .update(newConfig)
1111
- updated = res.updated
1112
- if (updated === 0) {
1113
- res = await db
1114
- .collection('config')
1115
- .add(newConfig)
1116
- updated = res.id ? 1 : 0
1117
- }
1118
- // 更新后重置配置缓存
1119
- if (updated > 0) config = null
1120
- return updated
1121
- } catch (e) {
1122
- logger.error('写入配置失败:', e)
1123
- return null
1124
- }
1125
- }
1126
-
1127
- // 获取用户 ID
1128
- async function getUid () {
1129
- const { userInfo } = await auth.getEndUserInfo()
1130
- return userInfo.uid
1131
- }
1132
-
1133
- // 判断用户是否管理员
1134
- async function isAdmin () {
1135
- const userInfo = await auth.getEndUserInfo()
1136
- return ADMIN_USER_ID === userInfo.userInfo.customUserId
1137
- }
1138
-
1139
- // 判断是否为递归调用(即云函数调用自身)
1140
- function isRecursion (context) {
1141
- const envObj = tcb.getCloudbaseContext(context)
1142
- return envObj.TCB_SOURCE.substr(-3, 3) === 'scf'
1143
- }
1144
-
1145
- async function capChallenge () {
1146
- if (!isBuiltinCap(config)) {
1147
- return { code: RES_CODE.FAIL, message: '内嵌 Cap 未启用' }
1148
- }
1149
- const cap = createCap(tcbStorage(db))
1150
- const data = await createChallenge(cap)
1151
- return { code: RES_CODE.SUCCESS, ...data }
1152
- }
1153
-
1154
- async function capRedeem (event) {
1155
- if (!isBuiltinCap(config)) {
1156
- return { code: RES_CODE.FAIL, message: '内嵌 Cap 未启用' }
1157
- }
1158
- const cap = createCap(tcbStorage(db))
1159
- const data = await redeemChallenge(cap, event)
1160
- return { code: RES_CODE.SUCCESS, ...data }
1161
- }
1162
-
1163
- // 建立数据库 collections
1164
- async function createCollections () {
1165
- const collections = ['comment', 'config', 'counter', 'cap_challenges', 'cap_tokens']
1166
- const res = {}
1167
- for (const collection of collections) {
1168
- try {
1169
- res[collection] = await db.createCollection(collection)
1170
- } catch (e) {
1171
- logger.error('建立数据库失败:', e)
1172
- }
1173
- }
1174
- return res
1175
- }