tkserver 1.7.24 → 2.0.0-beta.2

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