@whyour/qinglong 2.21.0 → 2.22.0

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.
Files changed (279) hide show
  1. package/.dockerignore +13 -0
  2. package/.env.example +7 -0
  3. package/AGENTS.md +2 -2
  4. package/README-en.md +24 -0
  5. package/README.md +24 -0
  6. package/back/protos/api.proto +9 -1
  7. package/back/protos/cron.proto +4 -1
  8. package/deploy/kubernetes/README.md +81 -0
  9. package/deploy/kubernetes/base/kustomization.yaml +5 -0
  10. package/deploy/kubernetes/base/qinglong.yaml +95 -0
  11. package/deploy/kubernetes/overlays/example/kustomization.yaml +10 -0
  12. package/docker/Dockerfile +31 -12
  13. package/docker/Dockerfile.310 +31 -12
  14. package/docker/Dockerfile.debian +22 -14
  15. package/docker/Dockerfile.debian310 +24 -14
  16. package/docker/build-manifest.cjs +28 -0
  17. package/docker/verify-build.cjs +49 -0
  18. package/docs/releases/2.22.0-validation.md +49 -0
  19. package/docs/releases/2.22.0.md +54 -0
  20. package/ecosystem.config.js +10 -1
  21. package/package.json +11 -6
  22. package/sample/config.sample.sh +17 -2
  23. package/sample/notify.js +118 -0
  24. package/sample/notify.py +93 -0
  25. package/scripts/benchmark-execution.cjs +96 -0
  26. package/scripts/write-build-info.cjs +27 -0
  27. package/shell/api.sh +41 -14
  28. package/shell/check.sh +59 -19
  29. package/shell/lang/en.sh +6 -0
  30. package/shell/lang/zh.sh +6 -0
  31. package/shell/node_path_cache.sh +128 -0
  32. package/shell/otask.sh +10 -1
  33. package/shell/preload/sitecustomize.js +5 -1
  34. package/shell/share.sh +26 -9
  35. package/shell/start.sh +6 -3
  36. package/shell/task.sh +13 -3
  37. package/shell/update.sh +65 -4
  38. package/static/build/api/clientIp.js +42 -0
  39. package/static/build/api/config.js +8 -16
  40. package/static/build/api/cron.js +39 -3
  41. package/static/build/api/dashboard.js +50 -6
  42. package/static/build/api/env.js +2 -2
  43. package/static/build/api/health.js +2 -2
  44. package/static/build/api/index.js +4 -0
  45. package/static/build/api/log.js +39 -19
  46. package/static/build/api/retention.js +63 -0
  47. package/static/build/api/script.js +23 -22
  48. package/static/build/api/subscription.js +16 -2
  49. package/static/build/api/system.js +31 -9
  50. package/static/build/api/user.js +75 -15
  51. package/static/build/app.js +63 -54
  52. package/static/build/bootstrap/database.js +51 -0
  53. package/static/build/config/const.js +2 -0
  54. package/static/build/config/grpcCerts.js +4 -4
  55. package/static/build/config/index.js +0 -4
  56. package/static/build/config/share.js +5 -4
  57. package/static/build/config/util.js +136 -41
  58. package/static/build/data/cron.js +1 -0
  59. package/static/build/data/notify.js +18 -1
  60. package/static/build/data/sock.js +1 -0
  61. package/static/build/loaders/app.js +8 -6
  62. package/static/build/loaders/db.js +5 -35
  63. package/static/build/loaders/deps.js +30 -22
  64. package/static/build/loaders/express.js +44 -32
  65. package/static/build/loaders/initData.js +10 -7
  66. package/static/build/loaders/initFile.js +1 -1
  67. package/static/build/loaders/initTask.js +3 -2
  68. package/static/build/loaders/server.js +1 -1
  69. package/static/build/loaders/sock.js +72 -6
  70. package/static/build/middlewares/monitoring.js +12 -33
  71. package/static/build/middlewares/protectedPathCase.js +17 -0
  72. package/static/build/protos/api.js +78 -2
  73. package/static/build/protos/cron.js +21 -4
  74. package/static/build/protos/health.js +1 -1
  75. package/static/build/schedule/addCron.js +76 -10
  76. package/static/build/schedule/api.js +5 -2
  77. package/static/build/schedule/client.js +38 -6
  78. package/static/build/schedule/delCron.js +11 -1
  79. package/static/build/schedule/health.js +72 -7
  80. package/static/build/services/config.js +5 -42
  81. package/static/build/services/cron.js +353 -164
  82. package/static/build/services/dependence.js +66 -18
  83. package/static/build/services/grpc.js +2 -2
  84. package/static/build/services/health.js +4 -7
  85. package/static/build/services/http.js +9 -3
  86. package/static/build/services/log.js +2 -3
  87. package/static/build/services/metrics.js +46 -14
  88. package/static/build/services/notify.js +73 -5
  89. package/static/build/services/retention.js +123 -0
  90. package/static/build/services/schedule.js +57 -33
  91. package/static/build/services/script.js +4 -5
  92. package/static/build/services/subscription.js +57 -34
  93. package/static/build/services/system.js +49 -11
  94. package/static/build/services/user.js +244 -31
  95. package/static/build/shared/auth.js +22 -3
  96. package/static/build/shared/authMutation.js +17 -0
  97. package/static/build/shared/childProcess.js +82 -0
  98. package/static/build/shared/clientIp.js +27 -0
  99. package/static/build/shared/errors.js +9 -0
  100. package/static/build/shared/fileAccess.js +60 -0
  101. package/static/build/shared/i18n.js +62 -4
  102. package/static/build/shared/logReader.js +85 -0
  103. package/static/build/shared/logStreamManager.js +80 -60
  104. package/static/build/shared/pLimit.js +3 -2
  105. package/static/build/shared/password.js +30 -0
  106. package/static/build/shared/retention.js +58 -0
  107. package/static/build/shared/runCron.js +28 -15
  108. package/static/build/shared/schedulerMutationLock.js +44 -0
  109. package/static/build/shared/schedulerReadiness.js +82 -0
  110. package/static/build/shared/schemaMigrations.js +58 -0
  111. package/static/build/shared/startupProcess.js +48 -0
  112. package/static/build/shared/store.js +7 -0
  113. package/static/build/shared/trustProxy.js +119 -0
  114. package/static/build/validation/schedule.js +12 -3
  115. package/static/dist/{1885.e1ea09f6.async.js → 1885.b8f427bf.async.js} +1 -1
  116. package/static/dist/2031.6af40025.async.js +1 -0
  117. package/static/dist/2693.51c2636b.async.js +1 -0
  118. package/static/dist/{2890.9e373f5b.async.js → 2890.add55e85.async.js} +1 -1
  119. package/static/dist/2901.2ca95295.async.js +1 -0
  120. package/static/dist/445.a65ff63b.async.js +1 -0
  121. package/static/dist/4736.1d2b5cb6.async.js +1 -0
  122. package/static/dist/{4859.6592cebb.async.js → 4859.97d6653c.async.js} +1 -1
  123. package/static/dist/{6013.4e38de36.async.js → 6013.db535339.async.js} +1 -1
  124. package/static/dist/6212.9e6d9913.async.js +1 -0
  125. package/static/dist/{6339.ab305e96.async.js → 6431.4603ad0e.async.js} +1 -1
  126. package/static/dist/{6872.42f939f1.async.js → 6872.a503ef55.async.js} +1 -1
  127. package/static/dist/7231.f7e5b668.async.js +1 -0
  128. package/static/dist/{7355.f9f263d8.async.js → 7355.fca746f5.async.js} +1 -1
  129. package/static/dist/{7508.7dcee91c.async.js → 7508.d90eac63.async.js} +1 -1
  130. package/static/dist/{7984.594296a5.async.js → 7984.eaac7402.async.js} +1 -1
  131. package/static/dist/8844.a0fef08e.async.js +1 -0
  132. package/static/dist/index.html +2 -2
  133. package/static/dist/layouts__index.633d3553.async.js +1 -0
  134. package/static/dist/preload_helper.cf7de3fa.js +1 -0
  135. package/static/dist/{src__pages__config__index.a22ff7dc.async.js → src__pages__config__index.9aba4054.async.js} +1 -1
  136. package/static/dist/src__pages__crontab__detail.86b2eebb.async.js +1 -0
  137. package/static/dist/src__pages__crontab__index.ae4e06f2.async.js +1 -0
  138. package/static/dist/{src__pages__crontab__logModal.0b8cce8c.async.js → src__pages__crontab__logModal.930535e2.async.js} +1 -1
  139. package/static/dist/src__pages__crontab__modal.a2c8fdcc.async.js +1 -0
  140. package/static/dist/src__pages__crontab__viewCreateModal.7b4f9cbe.async.js +1 -0
  141. package/static/dist/src__pages__crontab__viewManageModal.cd454ea0.async.js +1 -0
  142. package/static/dist/src__pages__dashboard__index.243c5a35.async.js +1 -0
  143. package/static/dist/src__pages__dashboard__taskResultModal.7795d6e1.async.js +1 -0
  144. package/static/dist/src__pages__dependence__index.874d501f.async.js +1 -0
  145. package/static/dist/src__pages__dependence__logModal.154efe7a.async.js +1 -0
  146. package/static/dist/src__pages__dependence__modal.a29c1a0f.async.js +1 -0
  147. package/static/dist/{src__pages__diff__index.013b7c75.async.js → src__pages__diff__index.1714b941.async.js} +1 -1
  148. package/static/dist/src__pages__env__editNameModal.c13d47d2.async.js +1 -0
  149. package/static/dist/src__pages__env__index.fd6fd2b0.async.js +1 -0
  150. package/static/dist/src__pages__env__modal.4d71adb3.async.js +1 -0
  151. package/static/dist/src__pages__error__index.aae50c94.async.js +1 -0
  152. package/static/dist/src__pages__initialization__index.82a2e967.async.js +1 -0
  153. package/static/dist/src__pages__log__index.71250e0d.async.js +1 -0
  154. package/static/dist/{src__pages__login__index.8c813eb1.async.js → src__pages__login__index.a0fd5ed8.async.js} +1 -1
  155. package/static/dist/src__pages__script__editModal.22acdf7c.async.js +1 -0
  156. package/static/dist/src__pages__script__editNameModal.1a521cc0.async.js +1 -0
  157. package/static/dist/src__pages__script__index.a18b2692.async.js +1 -0
  158. package/static/dist/src__pages__script__renameModal.0ab029e7.async.js +1 -0
  159. package/static/dist/src__pages__script__saveModal.8965b74c.async.js +1 -0
  160. package/static/dist/src__pages__script__setting.35ad4f02.async.js +1 -0
  161. package/static/dist/src__pages__setting__appModal.7eaeb9d3.async.js +1 -0
  162. package/static/dist/src__pages__setting__checkUpdate.d175b154.async.js +1 -0
  163. package/static/dist/src__pages__setting__clientIp.3a8711ed.async.js +1 -0
  164. package/static/dist/src__pages__setting__dependence.9c0f749b.async.js +1 -0
  165. package/static/dist/src__pages__setting__index.cb397741.async.js +1 -0
  166. package/static/dist/src__pages__setting__loginLog.e0a1f54d.async.js +1 -0
  167. package/static/dist/src__pages__setting__notification.2ffe4e5a.async.js +1 -0
  168. package/static/dist/src__pages__setting__other.3d0b8492.async.js +1 -0
  169. package/static/dist/{src__pages__setting__progress.8823ac90.async.js → src__pages__setting__progress.2ccae3d7.async.js} +1 -1
  170. package/static/dist/src__pages__setting__security.e2d71ebb.async.js +1 -0
  171. package/static/dist/src__pages__setting__systemLog.b3046955.async.js +1 -0
  172. package/static/dist/src__pages__subscription__index.43086a06.async.js +1 -0
  173. package/static/dist/src__pages__subscription__logModal.cdba5139.async.js +1 -0
  174. package/static/dist/src__pages__subscription__modal.38991e1e.async.js +1 -0
  175. package/static/dist/{umi.ca04a019.js → umi.fc019050.js} +1 -1
  176. package/test/back/auth-security.test.cjs +74 -0
  177. package/test/back/build-provenance.test.cjs +150 -0
  178. package/test/back/cron-log-name.test.cjs +110 -0
  179. package/test/back/cron-validation.test.cjs +45 -0
  180. package/test/back/dashboard-failures.test.cjs +173 -0
  181. package/test/back/database-bootstrap.test.cjs +193 -0
  182. package/test/back/dependence-cache-status.test.cjs +125 -0
  183. package/test/back/deprecated-file-routes.test.cjs +82 -0
  184. package/test/back/ecosystem.test.cjs +28 -0
  185. package/test/back/env-name-parsing.test.cjs +96 -0
  186. package/test/back/execution-lifecycle.test.cjs +236 -0
  187. package/test/back/file-access-security.test.cjs +47 -0
  188. package/test/back/fileTreeListing.test.cjs +57 -0
  189. package/test/back/grpc-cron-response.test.cjs +60 -0
  190. package/test/back/http-exclusive-listen.test.cjs +31 -0
  191. package/test/back/http-security.test.cjs +213 -0
  192. package/test/back/listen-security.test.cjs +67 -0
  193. package/test/back/log-path-security.test.cjs +158 -0
  194. package/test/back/logReader.test.cjs +72 -0
  195. package/test/back/manual-execution.test.cjs +85 -0
  196. package/test/back/manual-stop-claim.test.cjs +220 -0
  197. package/test/back/metrics.test.cjs +34 -0
  198. package/test/back/monitoring.test.cjs +73 -0
  199. package/test/back/node-path-cache.test.cjs +173 -0
  200. package/test/back/node-path-lock.test.cjs +178 -0
  201. package/test/back/npm-publication.test.cjs +70 -0
  202. package/test/back/primary-apm.test.cjs +24 -0
  203. package/test/back/process-exit-state.test.cjs +81 -0
  204. package/test/back/process-stop-signal.test.cjs +77 -0
  205. package/test/back/protected-path-case.test.cjs +58 -0
  206. package/test/back/qlServiceLogCommand.test.cjs +128 -0
  207. package/test/back/retention.test.cjs +131 -0
  208. package/test/back/role-loading.test.cjs +118 -0
  209. package/test/back/schedule-health.test.cjs +86 -0
  210. package/test/back/scheduler-file-lock.test.cjs +51 -0
  211. package/test/back/scheduler-mutation.test.cjs +312 -0
  212. package/test/back/scheduler-readiness.test.cjs +85 -0
  213. package/test/back/scheduler-reconciliation.test.cjs +152 -0
  214. package/test/back/scheduler-rpc-timeout.test.cjs +49 -0
  215. package/test/back/schema-migrations.test.cjs +127 -0
  216. package/test/back/shell-api-parsing.test.cjs +184 -0
  217. package/test/back/sock-polling.test.cjs +297 -0
  218. package/test/back/sock-security.test.cjs +72 -0
  219. package/test/back/start-env-preservation.test.cjs +53 -0
  220. package/test/back/stop-failure-feedback.test.cjs +158 -0
  221. package/test/back/stop-race.test.cjs +167 -0
  222. package/test/back/subscription-cleanup.test.cjs +53 -0
  223. package/test/back/subscription-stop-state.test.cjs +66 -0
  224. package/test/back/system-dependence-cache.test.cjs +126 -0
  225. package/test/back/task-time.test.cjs +116 -0
  226. package/test/back/user-api.test.cjs +99 -0
  227. package/test/back/user-security.test.cjs +248 -0
  228. package/test/back/worker-apm.test.cjs +84 -0
  229. package/test/back/wpush-grpc.test.cjs +115 -0
  230. package/test/front/cron-log-pagination.test.cjs +214 -0
  231. package/test/front/http-auth.test.cjs +152 -0
  232. package/test/front/http-error.test.cjs +29 -0
  233. package/test/helpers/load-security-module.cjs +42 -0
  234. package/version.yaml +19 -34
  235. package/CLAUDE.md +0 -43
  236. package/static/dist/1147.c420132e.async.js +0 -1
  237. package/static/dist/134.54df9e38.async.js +0 -1
  238. package/static/dist/2208.f7ba3dfa.async.js +0 -1
  239. package/static/dist/2286.164bb089.async.js +0 -1
  240. package/static/dist/3191.63263871.async.js +0 -1
  241. package/static/dist/4902.555f92ab.async.js +0 -1
  242. package/static/dist/5520.ff2cfd6b.async.js +0 -1
  243. package/static/dist/6431.c50479be.async.js +0 -1
  244. package/static/dist/8826.2447a104.async.js +0 -1
  245. package/static/dist/layouts__index.a7a2bfe0.async.js +0 -1
  246. package/static/dist/preload_helper.0431c0f3.js +0 -1
  247. package/static/dist/src__pages__crontab__detail.b9c36808.async.js +0 -1
  248. package/static/dist/src__pages__crontab__index.fed99fd0.async.js +0 -1
  249. package/static/dist/src__pages__crontab__modal.f7041c7c.async.js +0 -1
  250. package/static/dist/src__pages__crontab__viewCreateModal.4d589f66.async.js +0 -1
  251. package/static/dist/src__pages__crontab__viewManageModal.0e317746.async.js +0 -1
  252. package/static/dist/src__pages__dashboard__index.b30f2f47.async.js +0 -1
  253. package/static/dist/src__pages__dependence__index.3d87ceac.async.js +0 -1
  254. package/static/dist/src__pages__dependence__logModal.0681830b.async.js +0 -1
  255. package/static/dist/src__pages__dependence__modal.11124896.async.js +0 -1
  256. package/static/dist/src__pages__env__editNameModal.5d264b25.async.js +0 -1
  257. package/static/dist/src__pages__env__index.baa27d4e.async.js +0 -1
  258. package/static/dist/src__pages__env__modal.7f2ef1bc.async.js +0 -1
  259. package/static/dist/src__pages__error__index.f156b45e.async.js +0 -1
  260. package/static/dist/src__pages__initialization__index.e96d4ba8.async.js +0 -1
  261. package/static/dist/src__pages__log__index.e0978bae.async.js +0 -1
  262. package/static/dist/src__pages__script__editModal.cbf4ec0e.async.js +0 -1
  263. package/static/dist/src__pages__script__editNameModal.3e7e100d.async.js +0 -1
  264. package/static/dist/src__pages__script__index.2765d1b8.async.js +0 -1
  265. package/static/dist/src__pages__script__renameModal.5e987ef5.async.js +0 -1
  266. package/static/dist/src__pages__script__saveModal.3f9d23d6.async.js +0 -1
  267. package/static/dist/src__pages__script__setting.a535793a.async.js +0 -1
  268. package/static/dist/src__pages__setting__appModal.251cd14f.async.js +0 -1
  269. package/static/dist/src__pages__setting__checkUpdate.46efe057.async.js +0 -1
  270. package/static/dist/src__pages__setting__dependence.8a7a9529.async.js +0 -1
  271. package/static/dist/src__pages__setting__index.cc85fdfb.async.js +0 -1
  272. package/static/dist/src__pages__setting__loginLog.cea6056c.async.js +0 -1
  273. package/static/dist/src__pages__setting__notification.390fc905.async.js +0 -1
  274. package/static/dist/src__pages__setting__other.b22d2165.async.js +0 -1
  275. package/static/dist/src__pages__setting__security.598720a8.async.js +0 -1
  276. package/static/dist/src__pages__setting__systemLog.67406721.async.js +0 -1
  277. package/static/dist/src__pages__subscription__index.d0ab2abc.async.js +0 -1
  278. package/static/dist/src__pages__subscription__logModal.3864b37f.async.js +0 -1
  279. package/static/dist/src__pages__subscription__modal.3562c670.async.js +0 -1
@@ -27,53 +27,76 @@ const schedule_1 = __importDefault(require("./schedule"));
27
27
  const sock_1 = __importDefault(require("./sock"));
28
28
  const dayjs_1 = __importDefault(require("dayjs"));
29
29
  const ip2region_1 = __importDefault(require("ip2region"));
30
- const request_ip_1 = __importDefault(require("request-ip"));
31
30
  const uniq_1 = __importDefault(require("lodash/uniq"));
32
31
  const pickBy_1 = __importDefault(require("lodash/pickBy"));
33
32
  const isNil_1 = __importDefault(require("lodash/isNil"));
34
33
  const store_1 = require("../shared/store");
35
34
  const i18n_1 = require("../shared/i18n");
35
+ const clientIp_1 = require("../shared/clientIp");
36
+ const auth_1 = require("../shared/auth");
37
+ const password_1 = require("../shared/password");
38
+ const authMutation_1 = require("../shared/authMutation");
36
39
  let UserService = class UserService {
37
40
  constructor(logger, scheduleService, sockService) {
38
41
  this.logger = logger;
39
42
  this.scheduleService = scheduleService;
40
43
  this.sockService = sockService;
41
44
  }
42
- async login(payloads, req, needTwoFactor = true) {
45
+ async login(payloads, req) {
46
+ return this.authenticate(payloads, req);
47
+ }
48
+ async authenticate(payloads, req, needTwoFactor = true) {
43
49
  let { username, password } = payloads;
44
50
  const content = await this.getAuthInfo();
51
+ if ((0, auth_1.isDefaultAuthInfo)(content)) {
52
+ return { code: 450, message: (0, i18n_1.t)('请先初始化') };
53
+ }
45
54
  const timestamp = Date.now();
46
- let { username: cUsername, password: cPassword, retries = 0, lastlogon, lastip, lastaddr, twoFactorActivated, tokens = {}, platform, } = content;
55
+ const ip = (0, clientIp_1.getClientIp)(req);
56
+ const query = new ip2region_1.default();
57
+ const ipAddress = query.search(ip);
58
+ let address = '';
59
+ if (ipAddress) {
60
+ const { country, province, city, isp } = ipAddress;
61
+ address = (0, uniq_1.default)([country, province, city, isp]).filter(Boolean).join(' ');
62
+ }
63
+ let { username: cUsername, password: cPassword, retries = 0, lastlogon, lastip, lastaddr, twoFactorActivated, tokens = {}, platform, blockedIps = [], } = content;
64
+ if (ip &&
65
+ blockedIps.some((blockedIp) => (0, clientIp_1.normalizeClientIp)(blockedIp) === ip)) {
66
+ await this.insertDb({
67
+ type: system_1.AuthDataType.loginLog,
68
+ info: {
69
+ timestamp,
70
+ address,
71
+ ip,
72
+ platform: req.platform,
73
+ status: system_1.LoginStatus.fail,
74
+ },
75
+ });
76
+ this.getLoginLog();
77
+ return { code: 403, message: (0, i18n_1.t)('该 IP 已被列入黑名单') };
78
+ }
47
79
  const retriesTime = Math.pow(3, retries) * 1000;
48
80
  if (retries > 2 && timestamp - lastlogon < retriesTime) {
49
81
  const waitTime = Math.ceil((retriesTime - (timestamp - lastlogon)) / 1000);
50
82
  return {
51
83
  code: 410,
52
- message: `失败次数过多,请${waitTime}秒后重试`,
84
+ message: (0, i18n_1.tf)('失败次数过多,请%s秒后重试', waitTime),
53
85
  data: waitTime,
54
86
  };
55
87
  }
56
- if (username === cUsername &&
57
- password === cPassword &&
58
- twoFactorActivated &&
59
- needTwoFactor) {
88
+ const passwordMatches = username === cUsername && (await (0, password_1.verifyPassword)(password, cPassword));
89
+ if (passwordMatches && twoFactorActivated && needTwoFactor) {
60
90
  await this.updateAuthInfo(content, {
61
91
  isTwoFactorChecking: true,
92
+ twoFactorExpiresAt: timestamp + 5 * 60 * 1000,
62
93
  });
63
94
  return {
64
95
  code: 420,
65
96
  message: '',
66
97
  };
67
98
  }
68
- const ip = request_ip_1.default.getClientIp(req) || '';
69
- const query = new ip2region_1.default();
70
- const ipAddress = query.search(ip);
71
- let address = '';
72
- if (ipAddress) {
73
- const { country, province, city, isp } = ipAddress;
74
- address = (0, uniq_1.default)([country, province, city, isp]).filter(Boolean).join(' ');
75
- }
76
- if (username === cUsername && password === cPassword) {
99
+ if (passwordMatches) {
77
100
  const data = (0, util_1.createRandomString)(50, 100);
78
101
  const expiration = twoFactorActivated ? '60d' : '20d';
79
102
  let token = jsonwebtoken_1.default.sign({ data }, config_1.default.jwt.secret, {
@@ -89,6 +112,9 @@ let UserService = class UserService {
89
112
  };
90
113
  const updatedTokens = this.addTokenToList(tokens, req.platform, tokenInfo);
91
114
  await this.updateAuthInfo(content, {
115
+ password: (0, password_1.isPasswordHash)(cPassword)
116
+ ? cPassword
117
+ : await (0, password_1.hashPassword)(password),
92
118
  token,
93
119
  tokens: updatedTokens,
94
120
  lastlogon: timestamp,
@@ -97,8 +123,20 @@ let UserService = class UserService {
97
123
  lastaddr: address,
98
124
  platform: req.platform,
99
125
  isTwoFactorChecking: false,
126
+ twoFactorExpiresAt: 0,
100
127
  });
101
- this.notificationService.notify('登录通知', `你于${(0, dayjs_1.default)(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${req.platform}端 登录成功,ip地址 ${ip}`);
128
+ this.notificationService.notify((0, i18n_1.t)('登录通知'), (0, i18n_1.t)('你于') +
129
+ (0, dayjs_1.default)(timestamp).format('YYYY-MM-DD HH:mm:ss') +
130
+ (0, i18n_1.t)('在') +
131
+ address +
132
+ ' ' +
133
+ req.platform +
134
+ (0, i18n_1.t)('端') +
135
+ ' ' +
136
+ (0, i18n_1.t)('登录成功') +
137
+ (0, i18n_1.t)(',ip地址') +
138
+ ' ' +
139
+ ip);
102
140
  await this.insertDb({
103
141
  type: system_1.AuthDataType.loginLog,
104
142
  info: {
@@ -130,7 +168,18 @@ let UserService = class UserService {
130
168
  lastaddr: address,
131
169
  platform: req.platform,
132
170
  });
133
- this.notificationService.notify('登录通知', `你于${(0, dayjs_1.default)(timestamp).format('YYYY-MM-DD HH:mm:ss')}在 ${address} ${req.platform}端 登录失败,ip地址 ${ip}`);
171
+ this.notificationService.notify((0, i18n_1.t)('登录通知'), (0, i18n_1.t)('你于') +
172
+ (0, dayjs_1.default)(timestamp).format('YYYY-MM-DD HH:mm:ss') +
173
+ (0, i18n_1.t)('在') +
174
+ address +
175
+ ' ' +
176
+ req.platform +
177
+ (0, i18n_1.t)('端') +
178
+ ' ' +
179
+ (0, i18n_1.t)('登录失败') +
180
+ (0, i18n_1.t)(',ip地址') +
181
+ ' ' +
182
+ ip);
134
183
  await this.insertDb({
135
184
  type: system_1.AuthDataType.loginLog,
136
185
  info: {
@@ -146,12 +195,12 @@ let UserService = class UserService {
146
195
  const waitTime = Math.round(Math.pow(3, retries + 1));
147
196
  return {
148
197
  code: 410,
149
- message: `失败次数过多,请${waitTime}秒后重试`,
198
+ message: (0, i18n_1.tf)('失败次数过多,请%s秒后重试', waitTime),
150
199
  data: waitTime,
151
200
  };
152
201
  }
153
202
  else {
154
- return { code: 400, message: config_1.default.authError };
203
+ return { code: 400, message: (0, i18n_1.t)('错误的用户名密码,请重试') };
155
204
  }
156
205
  }
157
206
  }
@@ -190,16 +239,63 @@ let UserService = class UserService {
190
239
  }
191
240
  return [];
192
241
  }
242
+ async getIpBlacklist() {
243
+ const authInfo = await this.getAuthInfo();
244
+ return (0, uniq_1.default)((authInfo.blockedIps || []).map(clientIp_1.normalizeClientIp)).filter(Boolean);
245
+ }
246
+ async blockIp(ip) {
247
+ const authInfo = await this.getAuthInfo();
248
+ const blockedIps = (0, uniq_1.default)([
249
+ ...(authInfo.blockedIps || []).map(clientIp_1.normalizeClientIp),
250
+ (0, clientIp_1.normalizeClientIp)(ip),
251
+ ]).filter(Boolean);
252
+ await this.updateAuthInfo(authInfo, { blockedIps });
253
+ return blockedIps;
254
+ }
255
+ async unblockIp(ip) {
256
+ const authInfo = await this.getAuthInfo();
257
+ const normalizedIp = (0, clientIp_1.normalizeClientIp)(ip);
258
+ const blockedIps = (authInfo.blockedIps || [])
259
+ .map(clientIp_1.normalizeClientIp)
260
+ .filter((blockedIp) => blockedIp && blockedIp !== normalizedIp);
261
+ await this.updateAuthInfo(authInfo, { blockedIps });
262
+ return blockedIps;
263
+ }
193
264
  async insertDb(payload) {
194
265
  const doc = await system_1.SystemModel.create(Object.assign({}, payload), { returning: true });
195
266
  return doc;
196
267
  }
268
+ async initializeUser({ username, password, }) {
269
+ const authInfo = await this.getAuthInfo();
270
+ if (!(0, auth_1.isDefaultAuthInfo)(authInfo)) {
271
+ return { code: 450, message: (0, i18n_1.t)('未知错误') };
272
+ }
273
+ if (password === 'admin') {
274
+ return { code: 400, message: (0, i18n_1.t)('密码不能设置为admin') };
275
+ }
276
+ await this.updateAuthInfo(authInfo, {
277
+ username,
278
+ password: await (0, password_1.hashPassword)(password),
279
+ token: '',
280
+ tokens: {},
281
+ isTwoFactorChecking: false,
282
+ twoFactorExpiresAt: 0,
283
+ });
284
+ return { code: 200, message: (0, i18n_1.t)('更新成功') };
285
+ }
197
286
  async updateUsernameAndPassword({ username, password, }) {
198
287
  if (password === 'admin') {
199
288
  return { code: 400, message: (0, i18n_1.t)('密码不能设置为admin') };
200
289
  }
201
290
  const authInfo = await this.getAuthInfo();
202
- await this.updateAuthInfo(authInfo, { username, password });
291
+ await this.updateAuthInfo(authInfo, {
292
+ username,
293
+ password: await (0, password_1.hashPassword)(password),
294
+ token: '',
295
+ tokens: {},
296
+ isTwoFactorChecking: false,
297
+ twoFactorExpiresAt: 0,
298
+ });
203
299
  return { code: 200, message: (0, i18n_1.t)('更新成功') };
204
300
  }
205
301
  async updateAvatar(avatar) {
@@ -210,6 +306,9 @@ let UserService = class UserService {
210
306
  async initTwoFactor() {
211
307
  const secret = preset_default_1.authenticator.generateSecret();
212
308
  const authInfo = await this.getAuthInfo();
309
+ if (authInfo.twoFactorActivated) {
310
+ throw new Error((0, i18n_1.t)('请先关闭两步验证'));
311
+ }
213
312
  const otpauth = preset_default_1.authenticator.keyuri(authInfo.username, 'qinglong', secret);
214
313
  await this.updateAuthInfo(authInfo, { twoFactorSecret: secret });
215
314
  return { secret, url: otpauth };
@@ -221,25 +320,41 @@ let UserService = class UserService {
221
320
  secret: authInfo.twoFactorSecret,
222
321
  });
223
322
  if (isValid) {
224
- await this.updateAuthInfo(authInfo, { twoFactorActivated: true });
323
+ await this.updateAuthInfo(authInfo, {
324
+ twoFactorActivated: true,
325
+ token: '',
326
+ tokens: {},
327
+ isTwoFactorChecking: false,
328
+ twoFactorExpiresAt: 0,
329
+ });
225
330
  }
226
331
  return isValid;
227
332
  }
228
333
  async twoFactorLogin({ username, password, code, }, req) {
229
334
  const authInfo = await this.getAuthInfo();
230
335
  const { isTwoFactorChecking, twoFactorSecret } = authInfo;
231
- if (!isTwoFactorChecking) {
336
+ const now = Date.now();
337
+ const retries = authInfo.retries || 0;
338
+ if (retries > 2 && now - authInfo.lastlogon < Math.pow(3, retries) * 1000) {
339
+ return { code: 410, message: (0, i18n_1.t)('失败次数过多,请稍后重试') };
340
+ }
341
+ if (!isTwoFactorChecking ||
342
+ !authInfo.twoFactorActivated ||
343
+ !authInfo.twoFactorExpiresAt ||
344
+ authInfo.twoFactorExpiresAt <= now) {
232
345
  return { code: 450, message: (0, i18n_1.t)('未知错误') };
233
346
  }
234
- const isValid = preset_default_1.authenticator.verify({
235
- token: code,
236
- secret: twoFactorSecret,
237
- });
347
+ const step = Math.floor(now / 30000);
348
+ const isValid = username === authInfo.username &&
349
+ (await (0, password_1.verifyPassword)(password, authInfo.password)) &&
350
+ authInfo.lastTwoFactorStep !== step &&
351
+ preset_default_1.authenticator.verify({ token: code, secret: twoFactorSecret });
238
352
  if (isValid) {
239
- return this.login({ username, password }, req, false);
353
+ await this.updateAuthInfo(authInfo, { lastTwoFactorStep: step });
354
+ return this.authenticate({ username, password }, req, false);
240
355
  }
241
356
  else {
242
- const ip = request_ip_1.default.getClientIp(req) || '';
357
+ const ip = (0, clientIp_1.getClientIp)(req);
243
358
  const query = new ip2region_1.default();
244
359
  const ipAddress = query.search(ip);
245
360
  let address = '';
@@ -250,6 +365,9 @@ let UserService = class UserService {
250
365
  .join(' ');
251
366
  }
252
367
  await this.updateAuthInfo(authInfo, {
368
+ retries: retries + 1,
369
+ lastlogon: now,
370
+ isTwoFactorChecking: retries + 1 < 5,
253
371
  lastip: ip,
254
372
  lastaddr: address,
255
373
  platform: req.platform,
@@ -262,6 +380,10 @@ let UserService = class UserService {
262
380
  await this.updateAuthInfo(authInfo, {
263
381
  twoFactorActivated: false,
264
382
  twoFactorSecret: '',
383
+ token: '',
384
+ tokens: {},
385
+ isTwoFactorChecking: false,
386
+ twoFactorExpiresAt: 0,
265
387
  });
266
388
  return true;
267
389
  }
@@ -280,6 +402,9 @@ let UserService = class UserService {
280
402
  type: system_1.AuthDataType.authConfig,
281
403
  info: result,
282
404
  });
405
+ if (info.tokens && Object.keys(info.tokens).length === 0) {
406
+ this.sockService.getClients().forEach((conn) => conn.close('401'));
407
+ }
283
408
  }
284
409
  async getNotificationMode() {
285
410
  const doc = await this.getDb({ type: system_1.AuthDataType.notification });
@@ -308,7 +433,7 @@ let UserService = class UserService {
308
433
  }
309
434
  async updateNotificationMode(notificationInfo) {
310
435
  const code = Math.random().toString().slice(-6);
311
- const isSuccess = await this.notificationService.testNotify(notificationInfo, '青龙', `【蛟龙】测试通知 https://t.me/jiao_long`);
436
+ const isSuccess = await this.notificationService.testNotify(notificationInfo, (0, i18n_1.t)('青龙'), (0, i18n_1.t)('【蛟龙】测试通知 https://t.me/jiao_long'));
312
437
  if (isSuccess) {
313
438
  const result = await this.updateAuthDb({
314
439
  type: system_1.AuthDataType.notification,
@@ -381,6 +506,9 @@ let UserService = class UserService {
381
506
  }
382
507
  async resetAuthInfo(info) {
383
508
  const { retries, twoFactorActivated, password, username } = info;
509
+ if (password === 'admin') {
510
+ return { code: 400, message: (0, i18n_1.t)('密码不能设置为admin') };
511
+ }
384
512
  const authInfo = await this.getAuthInfo();
385
513
  const payload = (0, pickBy_1.default)({
386
514
  retries,
@@ -388,6 +516,19 @@ let UserService = class UserService {
388
516
  password,
389
517
  username,
390
518
  }, (x) => !(0, isNil_1.default)(x));
519
+ if (password !== undefined) {
520
+ payload.password = await (0, password_1.hashPassword)(password);
521
+ }
522
+ if (password !== undefined ||
523
+ username !== undefined ||
524
+ twoFactorActivated !== undefined) {
525
+ Object.assign(payload, {
526
+ token: '',
527
+ tokens: {},
528
+ isTwoFactorChecking: false,
529
+ twoFactorExpiresAt: 0,
530
+ });
531
+ }
391
532
  await this.updateAuthInfo(authInfo, payload);
392
533
  }
393
534
  };
@@ -395,6 +536,78 @@ __decorate([
395
536
  (0, typedi_1.Inject)((type) => notify_1.default),
396
537
  __metadata("design:type", notify_1.default)
397
538
  ], UserService.prototype, "notificationService", void 0);
539
+ __decorate([
540
+ authMutation_1.serializeAuthMutation,
541
+ __metadata("design:type", Function),
542
+ __metadata("design:paramtypes", [Object, Object]),
543
+ __metadata("design:returntype", Promise)
544
+ ], UserService.prototype, "login", null);
545
+ __decorate([
546
+ authMutation_1.serializeAuthMutation,
547
+ __metadata("design:type", Function),
548
+ __metadata("design:paramtypes", [String, String]),
549
+ __metadata("design:returntype", Promise)
550
+ ], UserService.prototype, "logout", null);
551
+ __decorate([
552
+ authMutation_1.serializeAuthMutation,
553
+ __metadata("design:type", Function),
554
+ __metadata("design:paramtypes", [String]),
555
+ __metadata("design:returntype", Promise)
556
+ ], UserService.prototype, "blockIp", null);
557
+ __decorate([
558
+ authMutation_1.serializeAuthMutation,
559
+ __metadata("design:type", Function),
560
+ __metadata("design:paramtypes", [String]),
561
+ __metadata("design:returntype", Promise)
562
+ ], UserService.prototype, "unblockIp", null);
563
+ __decorate([
564
+ authMutation_1.serializeAuthMutation,
565
+ __metadata("design:type", Function),
566
+ __metadata("design:paramtypes", [Object]),
567
+ __metadata("design:returntype", Promise)
568
+ ], UserService.prototype, "initializeUser", null);
569
+ __decorate([
570
+ authMutation_1.serializeAuthMutation,
571
+ __metadata("design:type", Function),
572
+ __metadata("design:paramtypes", [Object]),
573
+ __metadata("design:returntype", Promise)
574
+ ], UserService.prototype, "updateUsernameAndPassword", null);
575
+ __decorate([
576
+ authMutation_1.serializeAuthMutation,
577
+ __metadata("design:type", Function),
578
+ __metadata("design:paramtypes", [String]),
579
+ __metadata("design:returntype", Promise)
580
+ ], UserService.prototype, "updateAvatar", null);
581
+ __decorate([
582
+ authMutation_1.serializeAuthMutation,
583
+ __metadata("design:type", Function),
584
+ __metadata("design:paramtypes", []),
585
+ __metadata("design:returntype", Promise)
586
+ ], UserService.prototype, "initTwoFactor", null);
587
+ __decorate([
588
+ authMutation_1.serializeAuthMutation,
589
+ __metadata("design:type", Function),
590
+ __metadata("design:paramtypes", [String]),
591
+ __metadata("design:returntype", Promise)
592
+ ], UserService.prototype, "activeTwoFactor", null);
593
+ __decorate([
594
+ authMutation_1.serializeAuthMutation,
595
+ __metadata("design:type", Function),
596
+ __metadata("design:paramtypes", [Object, Object]),
597
+ __metadata("design:returntype", Promise)
598
+ ], UserService.prototype, "twoFactorLogin", null);
599
+ __decorate([
600
+ authMutation_1.serializeAuthMutation,
601
+ __metadata("design:type", Function),
602
+ __metadata("design:paramtypes", []),
603
+ __metadata("design:returntype", Promise)
604
+ ], UserService.prototype, "deactivateTwoFactor", null);
605
+ __decorate([
606
+ authMutation_1.serializeAuthMutation,
607
+ __metadata("design:type", Function),
608
+ __metadata("design:paramtypes", [Object]),
609
+ __metadata("design:returntype", Promise)
610
+ ], UserService.prototype, "resetAuthInfo", null);
398
611
  UserService = __decorate([
399
612
  (0, typedi_1.Service)(),
400
613
  __param(0, (0, typedi_1.Inject)('logger')),
@@ -1,6 +1,14 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isValidToken = void 0;
6
+ exports.isValidToken = exports.isDefaultAuthInfo = void 0;
7
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
+ function isDefaultAuthInfo(authInfo) {
9
+ return authInfo.username === 'admin' && authInfo.password === 'admin';
10
+ }
11
+ exports.isDefaultAuthInfo = isDefaultAuthInfo;
4
12
  /**
5
13
  * Validates if a token exists in the authentication info.
6
14
  * Supports both legacy string tokens and new TokenInfo array format.
@@ -10,10 +18,19 @@ exports.isValidToken = void 0;
10
18
  * @param platform - The platform (desktop, mobile)
11
19
  * @returns true if the token is valid, false otherwise
12
20
  */
13
- function isValidToken(authInfo, headerToken, platform) {
21
+ function isValidToken(authInfo, headerToken, platform, secret) {
14
22
  if (!authInfo || !headerToken) {
15
23
  return false;
16
24
  }
25
+ try {
26
+ const claims = jsonwebtoken_1.default.verify(headerToken, secret, { algorithms: ['HS384'] });
27
+ if (typeof claims === 'string' || typeof claims.exp !== 'number') {
28
+ return false;
29
+ }
30
+ }
31
+ catch (_a) {
32
+ return false;
33
+ }
17
34
  const { token = '', tokens = {} } = authInfo;
18
35
  // Check legacy token field
19
36
  if (headerToken === token) {
@@ -31,7 +48,9 @@ function isValidToken(authInfo, headerToken, platform) {
31
48
  }
32
49
  else if (Array.isArray(platformTokens)) {
33
50
  // New format: array of TokenInfo objects
34
- return platformTokens.some((t) => t && t.value === headerToken);
51
+ return platformTokens.some((t) => t &&
52
+ t.value === headerToken &&
53
+ (t.expiration === undefined || t.expiration > Date.now() / 1000));
35
54
  }
36
55
  // Unexpected type - log warning and reject
37
56
  return false;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.serializeAuthMutation = void 0;
4
+ // All account mutations in the HTTP service share one queue. In particular,
5
+ // a login that read old credentials must finish before a password reset revokes
6
+ // its session, and two initialization requests must not both claim the account.
7
+ let pending = Promise.resolve();
8
+ function serializeAuthMutation(_target, _key, descriptor) {
9
+ const method = descriptor.value;
10
+ descriptor.value = function (...args) {
11
+ const result = pending.then(() => method.apply(this, args));
12
+ pending = result.catch(() => undefined);
13
+ return result;
14
+ };
15
+ }
16
+ exports.serializeAuthMutation = serializeAuthMutation;
17
+ //# sourceMappingURL=authMutation.js.map
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
3
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4
+ var m = o[Symbol.asyncIterator], i;
5
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
6
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
7
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.observeChildProcess = exports.asError = void 0;
11
+ function asError(error) {
12
+ return error instanceof Error ? error : new Error(String(error));
13
+ }
14
+ exports.asError = asError;
15
+ /** Attach immediately after spawn, before awaiting database or user callbacks. */
16
+ function observeChildProcess(child, callbacks = {}) {
17
+ let failure;
18
+ const recordError = (error) => {
19
+ failure !== null && failure !== void 0 ? failure : (failure = asError(error));
20
+ };
21
+ const spawned = new Promise((resolve, reject) => {
22
+ child.once('spawn', resolve);
23
+ // Keep the listener through close: errors can occur after a successful spawn.
24
+ child.on('error', (error) => {
25
+ recordError(error);
26
+ reject(error);
27
+ });
28
+ });
29
+ const closed = new Promise((resolve) => {
30
+ child.once('close', (code, signal) => resolve({ code, signal }));
31
+ });
32
+ const started = spawned.then(async () => {
33
+ var _a;
34
+ await ((_a = callbacks.onStart) === null || _a === void 0 ? void 0 : _a.call(callbacks));
35
+ return child.pid;
36
+ });
37
+ // The caller can ask only for completion, without an unhandled start rejection.
38
+ const ready = started.catch(recordError);
39
+ const consume = async (stream, callback) => {
40
+ var _a, e_1, _b, _c;
41
+ // StringDecoder in Readable preserves UTF-8 characters split across chunks.
42
+ stream.setEncoding('utf8');
43
+ let callbackFailed = false;
44
+ try {
45
+ try {
46
+ for (var _d = true, stream_1 = __asyncValues(stream), stream_1_1; stream_1_1 = await stream_1.next(), _a = stream_1_1.done, !_a; _d = true) {
47
+ _c = stream_1_1.value;
48
+ _d = false;
49
+ const chunk = _c;
50
+ await ready;
51
+ if (!callbackFailed && callback) {
52
+ try {
53
+ await callback(String(chunk));
54
+ }
55
+ catch (error) {
56
+ recordError(error);
57
+ callbackFailed = true;
58
+ }
59
+ }
60
+ }
61
+ }
62
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
63
+ finally {
64
+ try {
65
+ if (!_d && !_a && (_b = stream_1.return)) await _b.call(stream_1);
66
+ }
67
+ finally { if (e_1) throw e_1.error; }
68
+ }
69
+ }
70
+ catch (error) {
71
+ recordError(error);
72
+ }
73
+ };
74
+ const output = Promise.all([
75
+ consume(child.stdout, callbacks.onStdout),
76
+ consume(child.stderr, callbacks.onStderr),
77
+ ]);
78
+ const completed = Promise.all([closed, ready, output]).then(([result]) => (Object.assign(Object.assign({}, result), { error: failure })));
79
+ return { started, completed };
80
+ }
81
+ exports.observeChildProcess = observeChildProcess;
82
+ //# sourceMappingURL=childProcess.js.map
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getClientIp = exports.normalizeClientIp = void 0;
4
+ const IPV4_MAPPED_PREFIX = '::ffff:';
5
+ function normalizeClientIp(value) {
6
+ let ip = (value || '').trim().toLowerCase();
7
+ if (!ip) {
8
+ return '';
9
+ }
10
+ if (ip.startsWith('[') && ip.endsWith(']')) {
11
+ ip = ip.slice(1, -1);
12
+ }
13
+ const zoneIndex = ip.indexOf('%');
14
+ if (zoneIndex !== -1) {
15
+ ip = ip.slice(0, zoneIndex);
16
+ }
17
+ if (ip.startsWith(IPV4_MAPPED_PREFIX)) {
18
+ return ip.slice(IPV4_MAPPED_PREFIX.length);
19
+ }
20
+ return ip;
21
+ }
22
+ exports.normalizeClientIp = normalizeClientIp;
23
+ function getClientIp(req) {
24
+ return normalizeClientIp(req.ip || req.socket.remoteAddress);
25
+ }
26
+ exports.getClientIp = getClientIp;
27
+ //# sourceMappingURL=clientIp.js.map
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.errStack = void 0;
4
+ // Keep error formatting independent of database, HTTP and gRPC dependencies.
5
+ function errStack(error) {
6
+ return error instanceof Error && error.stack ? error.stack : String(error);
7
+ }
8
+ exports.errStack = errStack;
9
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.resolveFileAccess = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ function isWithin(root, target) {
10
+ const relative = path_1.default.relative(root, target);
11
+ return (relative === '' ||
12
+ (!relative.startsWith(`..${path_1.default.sep}`) &&
13
+ relative !== '..' &&
14
+ !path_1.default.isAbsolute(relative)));
15
+ }
16
+ /** Resolve existing files and not-yet-created children without following an
17
+ * existing symlink outside the root. Blacklisted directories cover descendants. */
18
+ function resolveFileAccess(root, parts, blacklist = []) {
19
+ if (parts.some((part) => typeof part !== 'string' || part.includes('\0'))) {
20
+ return '';
21
+ }
22
+ const resolvedRoot = path_1.default.resolve(root);
23
+ const target = path_1.default.resolve(resolvedRoot, ...parts);
24
+ if (target === resolvedRoot || !isWithin(resolvedRoot, target))
25
+ return '';
26
+ const isBlocked = (relative) => relative.split(path_1.default.sep).some((part) => blacklist.includes(part));
27
+ if (isBlocked(path_1.default.relative(resolvedRoot, target)))
28
+ return '';
29
+ try {
30
+ const realRoot = fs_1.default.realpathSync(resolvedRoot);
31
+ let existing = target;
32
+ const missing = [];
33
+ while (!fs_1.default.existsSync(existing)) {
34
+ // existsSync is false for a dangling symlink; never treat one as absent.
35
+ try {
36
+ fs_1.default.lstatSync(existing);
37
+ return '';
38
+ }
39
+ catch (error) {
40
+ if (error.code !== 'ENOENT')
41
+ return '';
42
+ }
43
+ if (existing === resolvedRoot)
44
+ return '';
45
+ missing.unshift(path_1.default.basename(existing));
46
+ existing = path_1.default.dirname(existing);
47
+ }
48
+ const realTarget = path_1.default.resolve(fs_1.default.realpathSync(existing), ...missing);
49
+ if (!isWithin(realRoot, realTarget) ||
50
+ isBlocked(path_1.default.relative(realRoot, realTarget))) {
51
+ return '';
52
+ }
53
+ return target;
54
+ }
55
+ catch (_a) {
56
+ return '';
57
+ }
58
+ }
59
+ exports.resolveFileAccess = resolveFileAccess;
60
+ //# sourceMappingURL=fileAccess.js.map