web.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import {readFileSync, existsSync} from 'fs';
  2. import path from 'path';
  3. import {ENV} from '../utils/env.js';
  4. import COOKIE from '../utils/cookieManager.js';
  5. const COOKIE_AUTH_CODE = process.env.COOKIE_AUTH_CODE || 'drpys';
  6. export default (fastify, options, done) => {
  7. // 读取 views 目录下的 encoder.html 文件并返回
  8. fastify.get('/admin/encoder', async (request, reply) => {
  9. const encoderFilePath = path.join(options.viewsDir, 'encoder.html'); // 获取 encoder.html 文件的路径
  10. // 检查文件是否存在
  11. if (!existsSync(encoderFilePath)) {
  12. return reply.status(404).send({error: 'encoder.html not found'});
  13. }
  14. try {
  15. // 读取 HTML 文件内容
  16. const htmlContent = readFileSync(encoderFilePath, 'utf-8');
  17. reply.type('text/html').send(htmlContent); // 返回 HTML 文件内容
  18. } catch (error) {
  19. fastify.log.error(`Failed to read encoder.html: ${error.message}`);
  20. return reply.status(500).send({error: 'Failed to load encoder page'});
  21. }
  22. });
  23. fastify.post('/admin/cookie-set', async (request, reply) => {
  24. try {
  25. // 从请求体中获取参数
  26. const {cookie_auth_code, key, value} = request.body;
  27. // 验证参数完整性
  28. if (!cookie_auth_code || !key || !value) {
  29. return reply.code(400).send({
  30. success: false,
  31. message: 'Missing required parameters: cookie_auth_code, key, or value',
  32. });
  33. }
  34. // 验证 cookie_auth_code 是否正确
  35. if (cookie_auth_code !== COOKIE_AUTH_CODE) {
  36. return reply.code(403).send({
  37. success: false,
  38. message: 'Invalid cookie_auth_code',
  39. });
  40. }
  41. let cookie_obj = COOKIE.parse(value);
  42. let cookie_str = value;
  43. if (['quark_cookie', 'uc_cookie'].includes(key)) {
  44. // console.log(cookie_obj);
  45. cookie_str = COOKIE.stringify({
  46. __pus: cookie_obj.__pus || '',
  47. __puus: cookie_obj.__puus || '',
  48. });
  49. console.log(cookie_str);
  50. }
  51. // 调用 ENV.set 设置环境变量
  52. ENV.set(key, cookie_str);
  53. // 返回成功响应
  54. return reply.code(200).send({
  55. success: true,
  56. message: 'Cookie value has been successfully set',
  57. data: {key, value},
  58. });
  59. } catch (error) {
  60. // 捕获异常并返回错误响应
  61. console.error('Error setting cookie:', error.message);
  62. return reply.code(500).send({
  63. success: false,
  64. message: 'Internal server error',
  65. });
  66. }
  67. });
  68. done();
  69. };