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