@whyour/qinglong 2.22.0 → 2.23.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 (150) hide show
  1. package/back/protos/cron.proto +4 -0
  2. package/docs/development/node-cron-migration.md +49 -0
  3. package/docs/development/task-startup.md +78 -0
  4. package/docs/releases/2.22.0.md +8 -0
  5. package/docs/releases/2.23.0.md +33 -0
  6. package/docs/script-history.md +53 -0
  7. package/package.json +9 -8
  8. package/scripts/benchmark-script-history.cjs +39 -0
  9. package/scripts/publish-static.sh +34 -0
  10. package/scripts/sync-static.sh +20 -0
  11. package/scripts/wait-for-mirror.sh +214 -0
  12. package/shell/api.sh +56 -70
  13. package/shell/node_path_cache.sh +10 -2
  14. package/shell/otask.sh +7 -9
  15. package/shell/preload/sitecustomize.js +6 -2
  16. package/shell/preload/sitecustomize.py +4 -2
  17. package/shell/share.sh +1 -1
  18. package/shell/task-timeout.sh +63 -0
  19. package/shell/task.sh +8 -6
  20. package/shell/update.sh +40 -95
  21. package/shell/upgrade.cjs +8 -0
  22. package/static/build/api/config.js +2 -6
  23. package/static/build/api/env.js +15 -14
  24. package/static/build/api/open.js +2 -1
  25. package/static/build/api/script.js +155 -9
  26. package/static/build/api/subscription.js +3 -6
  27. package/static/build/api/system.js +35 -3
  28. package/static/build/config/grpcCerts.js +89 -40
  29. package/static/build/config/subscription.js +19 -11
  30. package/static/build/config/util.js +6 -4
  31. package/static/build/loaders/express.js +2 -0
  32. package/static/build/loaders/initData.js +20 -30
  33. package/static/build/loaders/initTask.js +11 -1
  34. package/static/build/middlewares/uniqueConstraintError.js +15 -0
  35. package/static/build/protos/cron.js +63 -2
  36. package/static/build/schedule/addCron.js +45 -63
  37. package/static/build/schedule/client.js +19 -1
  38. package/static/build/schedule/delCron.js +1 -1
  39. package/static/build/schedule/setConcurrency.js +27 -0
  40. package/static/build/services/config.js +2 -3
  41. package/static/build/services/cron.js +36 -10
  42. package/static/build/services/env.js +1 -1
  43. package/static/build/services/grpc.js +2 -1
  44. package/static/build/services/log.js +1 -1
  45. package/static/build/services/open.js +106 -31
  46. package/static/build/services/schedule.js +20 -10
  47. package/static/build/services/script.js +1 -1
  48. package/static/build/services/scriptHistory.js +30 -0
  49. package/static/build/services/sshKey.js +39 -14
  50. package/static/build/services/subscription.js +104 -53
  51. package/static/build/services/system.js +67 -32
  52. package/static/build/services/user.js +15 -10
  53. package/static/build/shared/cronCommand.js +17 -0
  54. package/static/build/shared/cronSchedule.js +101 -0
  55. package/static/build/shared/cronScheduler.js +73 -0
  56. package/static/build/shared/i18n.js +3 -2
  57. package/static/build/shared/logPath.js +15 -0
  58. package/static/build/shared/loginThrottle.js +45 -0
  59. package/static/build/shared/pLimit.js +19 -6
  60. package/static/build/shared/runCron.js +13 -4
  61. package/static/build/shared/scriptHistory.js +445 -0
  62. package/static/build/shared/shellQuote.js +11 -0
  63. package/static/build/shared/subscriptionMutationLock.js +34 -0
  64. package/static/build/shared/subscriptionPath.js +41 -0
  65. package/static/build/shared/subscriptionStorage.js +98 -0
  66. package/static/build/shared/utils.js +2 -1
  67. package/static/build/token.js +3 -14
  68. package/static/build/validation/schedule.js +3 -18
  69. package/static/dist/292.264757f0.async.js +1 -0
  70. package/static/dist/3512.95e41255.async.js +1 -0
  71. package/static/dist/index.html +2 -2
  72. package/static/dist/preload_helper.01fcd534.js +1 -0
  73. package/static/dist/src__pages__dependence__modal.0fa8b421.async.js +1 -0
  74. package/static/dist/src__pages__diff__index.b94e5dc5.async.js +1 -0
  75. package/static/dist/src__pages__script__editModal.afabf073.async.js +1 -0
  76. package/static/dist/src__pages__script__editNameModal.789ad87b.async.js +1 -0
  77. package/static/dist/src__pages__script__historyDrawer.8c58d958.async.js +1 -0
  78. package/static/dist/src__pages__script__historyDrawer.a449193a.chunk.css +1 -0
  79. package/static/dist/src__pages__script__index.ab360776.chunk.css +1 -0
  80. package/static/dist/src__pages__script__index.fc575945.async.js +1 -0
  81. package/static/dist/src__pages__script__saveModal.8fca1a22.async.js +1 -0
  82. package/static/dist/src__pages__script__saveWithHistory.99ece830.async.js +1 -0
  83. package/static/dist/src__pages__subscription__modal.30868ba8.async.js +1 -0
  84. package/static/dist/{umi.fc019050.js → umi.3a24a9fa.js} +1 -1
  85. package/test/back/advisory-input-security.test.cjs +416 -0
  86. package/test/back/code-scanning-security.test.cjs +189 -0
  87. package/test/back/cron-macros.test.cjs +51 -0
  88. package/test/back/cron-schedule-compatibility.test.cjs +69 -0
  89. package/test/back/cron-scheduler-routing.test.cjs +59 -0
  90. package/test/back/draft-path-security.test.cjs +235 -0
  91. package/test/back/env-import-security.test.cjs +91 -0
  92. package/test/back/execution-lifecycle.test.cjs +1 -1
  93. package/test/back/file-access-scope.test.cjs +180 -0
  94. package/test/back/grpc-mtls-security.test.cjs +136 -0
  95. package/test/back/http-security.test.cjs +105 -5
  96. package/test/back/legacy-cron-recovery.test.cjs +76 -0
  97. package/test/back/linux-mirror-result.test.cjs +176 -0
  98. package/test/back/listen-security.test.cjs +1 -0
  99. package/test/back/mirror-status.test.cjs +257 -0
  100. package/test/back/node-cron-migration.test.cjs +65 -0
  101. package/test/back/node-path-cache.test.cjs +29 -0
  102. package/test/back/node-path-lock.test.cjs +6 -2
  103. package/test/back/preload-lazy-notify.test.cjs +168 -0
  104. package/test/back/queued-cron-invalidation.test.cjs +98 -0
  105. package/test/back/restart-instance-recovery.test.cjs +116 -0
  106. package/test/back/scheduler-bulk-recovery.test.cjs +40 -0
  107. package/test/back/scheduler-concurrency.test.cjs +411 -0
  108. package/test/back/scheduler-reconciliation.test.cjs +58 -4
  109. package/test/back/script-file-access.test.cjs +210 -0
  110. package/test/back/script-history-api.test.cjs +551 -0
  111. package/test/back/script-history.test.cjs +383 -0
  112. package/test/back/shell-api-parsing.test.cjs +4 -4
  113. package/test/back/shell-translation-output.test.cjs +16 -0
  114. package/test/back/shell-upgrade.test.cjs +312 -0
  115. package/test/back/shellApiToken.test.cjs +151 -0
  116. package/test/back/ssh-config-home.test.cjs +113 -0
  117. package/test/back/static-mirror-trigger.test.cjs +441 -0
  118. package/test/back/static-mirror.test.cjs +179 -0
  119. package/test/back/stop-race.test.cjs +5 -1
  120. package/test/back/subscription-mutation-lock.test.cjs +83 -0
  121. package/test/back/subscription-review-regression.test.cjs +607 -0
  122. package/test/back/subscription-storage-regression.test.cjs +553 -0
  123. package/test/back/system-dependence-cache.test.cjs +1 -0
  124. package/test/back/system-export-history.test.cjs +119 -0
  125. package/test/back/systemTokenRenewal.test.cjs +497 -0
  126. package/test/back/task-shell-lifecycle.test.cjs +194 -0
  127. package/test/back/unique-constraint-error.test.cjs +72 -0
  128. package/test/back/upgrade-guards.test.cjs +285 -0
  129. package/test/back/upgrade-lifecycle.test.cjs +288 -0
  130. package/test/back/upgrade-transaction.test.cjs +133 -0
  131. package/test/back/user-security.test.cjs +102 -1
  132. package/test/back/wpush-grpc.test.cjs +1 -0
  133. package/test/fixtures/legacy-cron.json +1371 -0
  134. package/test/front/diff-file-routing.test.cjs +126 -0
  135. package/test/front/script-history-save.test.cjs +121 -0
  136. package/test/helpers/upgrade-fixture.cjs +30 -0
  137. package/version.yaml +14 -19
  138. package/static/dist/2096.6d98fd12.async.js +0 -1
  139. package/static/dist/4859.97d6653c.async.js +0 -1
  140. package/static/dist/6707.801b886b.async.js +0 -1
  141. package/static/dist/preload_helper.cf7de3fa.js +0 -1
  142. package/static/dist/src__pages__dependence__modal.a29c1a0f.async.js +0 -1
  143. package/static/dist/src__pages__diff__index.1714b941.async.js +0 -1
  144. package/static/dist/src__pages__script__editModal.22acdf7c.async.js +0 -1
  145. package/static/dist/src__pages__script__editNameModal.1a521cc0.async.js +0 -1
  146. package/static/dist/src__pages__script__index.60b6f827.chunk.css +0 -1
  147. package/static/dist/src__pages__script__index.a18b2692.async.js +0 -1
  148. package/static/dist/src__pages__script__saveModal.8965b74c.async.js +0 -1
  149. package/static/dist/src__pages__subscription__modal.38991e1e.async.js +0 -1
  150. /package/static/dist/{4859.1b962b29.chunk.css → 292.1b962b29.chunk.css} +0 -0
@@ -223,7 +223,7 @@ let EnvService = class EnvService {
223
223
  .map((x) => x.value)
224
224
  .join('&')
225
225
  .replace(/\\/g, '\\\\')}`;
226
- js_env_string += `process.env.${key}=\`${_env_value.replace(/\`/g, '\\`')}\`;\n`;
226
+ js_env_string += `process.env[${JSON.stringify(key)}]=${JSON.stringify(group.map((x) => x.value).join('&'))};\n`;
227
227
  py_env_string += `os.environ['${key}']='''${_env_value.replace(/\'/g, "\\'")}'''\n`;
228
228
  }
229
229
  }
@@ -39,6 +39,7 @@ const health_1 = require("../protos/health");
39
39
  const api_1 = require("../protos/api");
40
40
  const addCron_1 = require("../schedule/addCron");
41
41
  const delCron_1 = require("../schedule/delCron");
42
+ const setConcurrency_1 = require("../schedule/setConcurrency");
42
43
  const health_2 = require("../schedule/health");
43
44
  const Api = __importStar(require("../schedule/api"));
44
45
  const logger_1 = __importDefault(require("../loaders/logger"));
@@ -60,7 +61,7 @@ let GrpcServerService = class GrpcServerService {
60
61
  async initialize() {
61
62
  try {
62
63
  this.server.addService(health_1.HealthService, { check: health_2.check });
63
- this.server.addService(cron_1.CronService, { addCron: addCron_1.addCron, delCron: delCron_1.delCron });
64
+ this.server.addService(cron_1.CronService, { addCron: addCron_1.addCron, delCron: delCron_1.delCron, setConcurrency: setConcurrency_1.setConcurrency });
64
65
  this.server.addService(api_1.ApiService, Api);
65
66
  const tlsConfig = await (0, grpcCerts_1.initGrpcCerts)();
66
67
  const credentials = grpc_js_1.ServerCredentials.createSsl(Buffer.from(tlsConfig.caCert), [{ cert_chain: Buffer.from(tlsConfig.serverCert), private_key: Buffer.from(tlsConfig.serverKey) }], true);
@@ -24,7 +24,7 @@ let LogService = class LogService {
24
24
  this.logger = logger;
25
25
  }
26
26
  checkFilePath(filePath, fileName) {
27
- return (0, fileAccess_1.resolveFileAccess)(config_1.default.logPath, [filePath || '', fileName], config_1.default.blackFileList);
27
+ return (0, fileAccess_1.resolveFileAccess)(config_1.default.logPath, [filePath || '', fileName]);
28
28
  }
29
29
  };
30
30
  LogService = __decorate([
@@ -23,22 +23,68 @@ const uuid_1 = require("uuid");
23
23
  const sequelize_1 = require("sequelize");
24
24
  const store_1 = require("../shared/store");
25
25
  const i18n_1 = require("../shared/i18n");
26
+ const proper_lockfile_1 = require("proper-lockfile");
27
+ const path_1 = __importDefault(require("path"));
28
+ const os_1 = __importDefault(require("os"));
29
+ const promises_1 = require("fs/promises");
30
+ const config_1 = __importDefault(require("../config"));
26
31
  let OpenService = class OpenService {
27
32
  constructor(logger) {
28
33
  this.logger = logger;
29
34
  }
35
+ // Every database mutation and full authentication-cache publication shares
36
+ // this cross-process lock. Lock a separate marker, not token.json itself.
37
+ async withAppsLock(operation) {
38
+ const target = path_1.default.join(config_1.default.configPath, '.apps-state');
39
+ const release = await (0, proper_lockfile_1.lock)(target, {
40
+ realpath: false,
41
+ stale: 10000,
42
+ retries: { retries: 10, factor: 2, minTimeout: 100, maxTimeout: 3000 },
43
+ });
44
+ try {
45
+ return await operation();
46
+ }
47
+ finally {
48
+ await release();
49
+ }
50
+ }
51
+ async initializeSystemApp() {
52
+ await this.withAppsLock(async () => {
53
+ const doc = await open_1.AppModel.findOne({ where: { name: 'system' } });
54
+ const app = doc === null || doc === void 0 ? void 0 : doc.get({ plain: true });
55
+ if (!app) {
56
+ await this.insert({
57
+ name: 'system',
58
+ scopes: ['crons', 'system', 'dashboard'],
59
+ client_id: (0, util_1.createRandomString)(12, 12),
60
+ client_secret: (0, util_1.createRandomString)(24, 24),
61
+ });
62
+ }
63
+ else if (!app.scopes.includes('dashboard')) {
64
+ await open_1.AppModel.update({ scopes: [...app.scopes, 'dashboard'] }, { where: { id: app.id } });
65
+ }
66
+ await store_1.shareStore.updateApps(await this.find({}));
67
+ });
68
+ }
69
+ async refreshApps() {
70
+ await this.withAppsLock(async () => {
71
+ await store_1.shareStore.updateApps(await this.find({}));
72
+ });
73
+ }
30
74
  async findApps() {
31
75
  const docs = await this.find({});
32
76
  return docs;
33
77
  }
34
78
  async create(payload) {
35
- const tab = Object.assign({}, payload);
36
- tab.client_id = (0, util_1.createRandomString)(12, 12);
37
- tab.client_secret = (0, util_1.createRandomString)(24, 24);
38
- const doc = await this.insert(tab);
39
- const apps = await this.find({});
40
- await store_1.shareStore.updateApps(apps);
41
- return Object.assign(Object.assign({}, doc), { tokens: [] });
79
+ return this.withAppsLock(async () => {
80
+ const tab = Object.assign({}, payload);
81
+ tab.client_id = (0, util_1.createRandomString)(12, 12);
82
+ tab.client_secret = (0, util_1.createRandomString)(24, 24);
83
+ const doc = await this.insert(tab);
84
+ const apps = await this.find({});
85
+ await store_1.shareStore.updateApps(apps);
86
+ return Object.assign(Object.assign({}, doc), { tokens: [] });
87
+ });
42
88
  }
43
89
  async insert(payload) {
44
90
  const doc = await open_1.AppModel.create(payload, { returning: true });
@@ -53,10 +99,12 @@ let OpenService = class OpenService {
53
99
  return Object.assign(Object.assign({}, newDoc), { tokens: [] });
54
100
  }
55
101
  async updateDb(payload) {
56
- await open_1.AppModel.update(payload, { where: { id: payload.id } });
57
- const apps = await this.find({});
58
- await store_1.shareStore.updateApps(apps);
59
- return apps === null || apps === void 0 ? void 0 : apps.find((x) => x.id === payload.id);
102
+ return this.withAppsLock(async () => {
103
+ await open_1.AppModel.update(payload, { where: { id: payload.id } });
104
+ const apps = await this.find({});
105
+ await store_1.shareStore.updateApps(apps);
106
+ return apps === null || apps === void 0 ? void 0 : apps.find((x) => x.id === payload.id);
107
+ });
60
108
  }
61
109
  async getDb(query) {
62
110
  const doc = await open_1.AppModel.findOne({ where: query });
@@ -66,9 +114,11 @@ let OpenService = class OpenService {
66
114
  return doc.get({ plain: true });
67
115
  }
68
116
  async remove(ids) {
69
- await open_1.AppModel.destroy({ where: { id: ids } });
70
- const apps = await this.find({});
71
- await store_1.shareStore.updateApps(apps);
117
+ return this.withAppsLock(async () => {
118
+ await open_1.AppModel.destroy({ where: { id: ids } });
119
+ const apps = await this.find({});
120
+ await store_1.shareStore.updateApps(apps);
121
+ });
72
122
  }
73
123
  async resetSecret(id) {
74
124
  const tab = {
@@ -111,7 +161,11 @@ let OpenService = class OpenService {
111
161
  const docs = await open_1.AppModel.findAll({ where: Object.assign({}, query) });
112
162
  return docs.map((x) => x.get({ plain: true }));
113
163
  }
114
- async authToken({ client_id, client_secret, }) {
164
+ async authToken(credentials) {
165
+ return this.withAppsLock(() => this.issueToken(credentials));
166
+ }
167
+ // Caller holds withAppsLock through database update and cache publication.
168
+ async issueToken({ client_id, client_secret, }) {
115
169
  let token = (0, uuid_1.v4)();
116
170
  const expiration = Math.round(Date.now() / 1000) + 2592000; // 2592000 30天
117
171
  const doc = await open_1.AppModel.findOne({ where: { client_id, client_secret } });
@@ -145,23 +199,44 @@ let OpenService = class OpenService {
145
199
  return { code: 400, message: (0, i18n_1.t)('client_id 或 client_seret 有误') };
146
200
  }
147
201
  }
148
- async generateSystemToken() {
149
- var _a;
150
- const apps = await store_1.shareStore.getApps();
151
- const systemApp = apps === null || apps === void 0 ? void 0 : apps.find((x) => x.name === 'system');
152
- if (!systemApp) {
153
- throw new Error('system app not found');
154
- }
155
- const now = Math.round(Date.now() / 1000);
156
- const currentToken = (_a = systemApp.tokens) === null || _a === void 0 ? void 0 : _a.find((x) => x.expiration > now);
157
- if (currentToken) {
158
- return currentToken;
159
- }
160
- const { data } = await this.authToken({
161
- client_id: systemApp.client_id,
162
- client_secret: systemApp.client_secret,
202
+ async generateSystemToken(renew = false) {
203
+ return this.withAppsLock(async () => {
204
+ var _a;
205
+ // Read after acquiring the lock; a concurrent issuer may have renewed.
206
+ const systemApp = await this.getDb({ name: 'system' });
207
+ const now = Math.round(Date.now() / 1000);
208
+ let appToken = (_a = systemApp.tokens) === null || _a === void 0 ? void 0 : _a.filter((token) => token.expiration > now).sort((left, right) => right.expiration - left.expiration)[0];
209
+ if (renew || !appToken) {
210
+ const { data } = await this.issueToken({
211
+ client_id: systemApp.client_id,
212
+ client_secret: systemApp.client_secret,
213
+ });
214
+ appToken = { value: data.token, expiration: data.expiration };
215
+ }
216
+ else {
217
+ // Recover a prior database commit whose cache publication failed.
218
+ await store_1.shareStore.updateApps(await this.find({}));
219
+ }
220
+ const tokenFile = path_1.default.join(config_1.default.configPath, 'token.json');
221
+ const temporaryFile = `${tokenFile}.${process.pid}.tmp`;
222
+ const mode = await (0, promises_1.stat)(tokenFile).then((file) => file.mode & 0o777, (error) => {
223
+ if (error.code === 'ENOENT')
224
+ return 0o600;
225
+ throw error;
226
+ });
227
+ try {
228
+ await (0, promises_1.writeFile)(temporaryFile, `${JSON.stringify(appToken)}${os_1.default.EOL}`, {
229
+ mode,
230
+ });
231
+ await (0, promises_1.chmod)(temporaryFile, mode);
232
+ // Shell readers see a complete old or new document, never a partial one.
233
+ await (0, promises_1.rename)(temporaryFile, tokenFile);
234
+ }
235
+ finally {
236
+ await (0, promises_1.rm)(temporaryFile, { force: true });
237
+ }
238
+ return appToken;
163
239
  });
164
- return Object.assign(Object.assign({}, data), { value: data.token });
165
240
  }
166
241
  };
167
242
  OpenService = __decorate([
@@ -28,7 +28,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
29
  const typedi_1 = require("typedi");
30
30
  const winston_1 = __importDefault(require("winston"));
31
- const node_schedule_1 = __importDefault(require("node-schedule"));
31
+ const cronScheduler_1 = require("../shared/cronScheduler");
32
32
  const toad_scheduler_1 = require("toad-scheduler");
33
33
  const dayjs_1 = __importDefault(require("dayjs"));
34
34
  const pLimit_1 = __importDefault(require("../shared/pLimit"));
@@ -110,17 +110,27 @@ let ScheduleService = class ScheduleService {
110
110
  return completionTime === 'start' ? startResult : completion;
111
111
  }
112
112
  async createCronTask({ id = 0, command, name, schedule = '', runOrigin }, callbacks, runImmediately = false) {
113
+ var _a;
113
114
  const _id = this.formatId(id);
114
115
  this.logger.info('[panel][创建cron任务] 任务ID: %s, cron: %s, 任务名: %s, 执行命令: %s', _id, schedule, name, command);
115
- this.scheduleStacks.set(_id, node_schedule_1.default.scheduleJob(_id, schedule, async () => {
116
- this.runTask(command, callbacks, {
117
- name,
118
- schedule,
119
- command,
120
- id: _id,
121
- runOrigin,
122
- });
123
- }));
116
+ if (schedule) {
117
+ try {
118
+ const job = (0, cronScheduler_1.createCronJob)(schedule, () => this.runTask(command, callbacks, {
119
+ name,
120
+ schedule,
121
+ command,
122
+ id: _id,
123
+ runOrigin,
124
+ }), { name: `${_id}: ${name || ''}`, logger: this.logger, start: false });
125
+ (_a = this.scheduleStacks.get(_id)) === null || _a === void 0 ? void 0 : _a.cancel();
126
+ this.scheduleStacks.set(_id, job);
127
+ job.start();
128
+ }
129
+ catch (error) {
130
+ // A persisted invalid subscription must not become an unhandled startup rejection.
131
+ this.logger.warn('[panel][跳过无效定时任务] 任务ID: %s, cron: %s, 错误: %s', _id, schedule, (0, childProcess_1.asError)(error).message);
132
+ }
133
+ }
124
134
  if (runImmediately) {
125
135
  this.runTask(command, callbacks, {
126
136
  name,
@@ -70,7 +70,7 @@ let ScriptService = class ScriptService {
70
70
  return { code: 200 };
71
71
  }
72
72
  checkFilePath(filePath, fileName) {
73
- return (0, fileAccess_1.resolveFileAccess)(config_1.default.scriptPath, [filePath || '', fileName], config_1.default.blackFileList);
73
+ return (0, fileAccess_1.resolveFileAccess)(config_1.default.scriptPath, [filePath || '', fileName]);
74
74
  }
75
75
  async getFile(filePath, fileName) {
76
76
  const finalPath = this.checkFilePath(filePath, fileName);
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const path_1 = __importDefault(require("path"));
16
+ const typedi_1 = require("typedi");
17
+ const config_1 = __importDefault(require("../config"));
18
+ const scriptHistory_1 = require("../shared/scriptHistory");
19
+ /** Panel configuration and lifecycle; the storage core stays independently testable. */
20
+ let ScriptHistoryService = class ScriptHistoryService extends scriptHistory_1.ScriptHistory {
21
+ constructor() {
22
+ super(config_1.default.scriptPath, path_1.default.join(config_1.default.dataPath, 'script-history'));
23
+ }
24
+ };
25
+ ScriptHistoryService = __decorate([
26
+ (0, typedi_1.Service)(),
27
+ __metadata("design:paramtypes", [])
28
+ ], ScriptHistoryService);
29
+ exports.default = ScriptHistoryService;
30
+ //# sourceMappingURL=scriptHistory.js.map
@@ -24,16 +24,30 @@ const subscription_1 = require("../config/subscription");
24
24
  const config_1 = __importDefault(require("../config"));
25
25
  const util_1 = require("../config/util");
26
26
  const utils_1 = require("../shared/utils");
27
+ const subscriptionPath_1 = require("../shared/subscriptionPath");
27
28
  let SshKeyService = class SshKeyService {
29
+ // OpenSSH uses the effective user's passwd entry, not the HOME override.
30
+ get homedir() {
31
+ try {
32
+ return os_1.default.userInfo().homedir;
33
+ }
34
+ catch (_a) {
35
+ // Custom container UIDs may have no passwd entry. Keep startup working.
36
+ return os_1.default.homedir();
37
+ }
38
+ }
28
39
  constructor(logger) {
29
40
  this.logger = logger;
30
- this.homedir = os_1.default.homedir();
31
41
  this.sshPath = config_1.default.sshdPath;
32
42
  this.sshConfigFilePath = path_1.default.resolve(this.homedir, '.ssh', 'config');
33
43
  this.sshConfigHeader = `Include ${path_1.default.join(this.sshPath, '*.config')}`;
34
44
  this.initSshConfigFile();
35
45
  }
36
46
  async initSshConfigFile() {
47
+ await promises_1.default.mkdir(path_1.default.dirname(this.sshConfigFilePath), {
48
+ recursive: true,
49
+ mode: 0o700,
50
+ });
37
51
  let config = '';
38
52
  const _exist = await (0, util_1.fileExist)(this.sshConfigFilePath);
39
53
  if (_exist) {
@@ -48,7 +62,7 @@ let SshKeyService = class SshKeyService {
48
62
  }
49
63
  async generatePrivateKeyFile(alias, key) {
50
64
  try {
51
- const filePath = path_1.default.join(this.sshPath, alias);
65
+ const filePath = (0, subscriptionPath_1.resolveSubscriptionPath)(this.sshPath, alias);
52
66
  try {
53
67
  await (0, util_1.rmPath)(filePath);
54
68
  }
@@ -61,7 +75,7 @@ let SshKeyService = class SshKeyService {
61
75
  }
62
76
  async removePrivateKeyFile(alias) {
63
77
  try {
64
- const filePath = path_1.default.join(this.sshPath, alias);
78
+ const filePath = (0, subscriptionPath_1.resolveSubscriptionPath)(this.sshPath, alias);
65
79
  await (0, util_1.rmPath)(filePath);
66
80
  }
67
81
  catch (error) {
@@ -69,21 +83,25 @@ let SshKeyService = class SshKeyService {
69
83
  }
70
84
  }
71
85
  async generateSingleSshConfig(alias, host, proxy) {
86
+ if (!/^[a-zA-Z0-9.-]+$/.test(host) ||
87
+ (proxy && !/^[a-zA-Z0-9.:[\]-]+$/.test(proxy))) {
88
+ throw Object.assign(new Error('Invalid SSH host or proxy'), { status: 400 });
89
+ }
72
90
  if (host === 'github.com') {
73
91
  host = `ssh.github.com\n Port 443\n HostkeyAlgorithms +ssh-rsa`;
74
92
  }
75
93
  const proxyStr = proxy
76
94
  ? ` ProxyCommand nc -v -x ${proxy} %h %p 2>/dev/null\n`
77
95
  : '';
78
- const config = `Host ${alias}\n Hostname ${host}\n IdentityFile ${path_1.default.join(this.sshPath, alias)}\n StrictHostKeyChecking no\n${proxyStr}`;
79
- await (0, utils_1.writeFileWithLock)(`${path_1.default.join(this.sshPath, `${alias}.config`)}`, config, {
96
+ const config = `Host ${alias}\n Hostname ${host}\n IdentityFile ${(0, subscriptionPath_1.resolveSubscriptionPath)(this.sshPath, alias)}\n StrictHostKeyChecking no\n${proxyStr}`;
97
+ await (0, utils_1.writeFileWithLock)(`${(0, subscriptionPath_1.resolveSubscriptionPath)(this.sshPath, alias, '.config')}`, config, {
80
98
  encoding: 'utf8',
81
99
  mode: '600',
82
100
  });
83
101
  }
84
102
  async removeSshConfig(alias) {
85
103
  try {
86
- const filePath = path_1.default.join(this.sshPath, `${alias}.config`);
104
+ const filePath = (0, subscriptionPath_1.resolveSubscriptionPath)(this.sshPath, alias, '.config');
87
105
  await (0, util_1.rmPath)(filePath);
88
106
  }
89
107
  catch (error) {
@@ -91,22 +109,29 @@ let SshKeyService = class SshKeyService {
91
109
  }
92
110
  }
93
111
  async addSSHKey(key, alias, host, proxy) {
112
+ alias = (0, subscriptionPath_1.getSubscriptionSshAlias)(alias);
94
113
  await this.generatePrivateKeyFile(alias, key);
95
114
  await this.generateSingleSshConfig(alias, host, proxy);
96
115
  }
97
116
  async removeSSHKey(alias, host, proxy) {
117
+ alias = (0, subscriptionPath_1.getSubscriptionSshAlias)(alias);
98
118
  await this.removePrivateKeyFile(alias);
99
119
  await this.removeSshConfig(alias);
100
120
  }
101
121
  async setSshConfig(docs) {
102
122
  for (const doc of docs) {
103
123
  if (doc.type === 'private-repo' && doc.pull_type === 'ssh-key') {
104
- const { alias, proxy } = doc;
105
- const { host } = (0, subscription_1.formatUrl)(doc);
106
- await this.removePrivateKeyFile(alias);
107
- await this.removeSshConfig(alias);
108
- await this.generatePrivateKeyFile(alias, doc.pull_option.private_key);
109
- await this.generateSingleSshConfig(alias, host, proxy);
124
+ try {
125
+ const alias = (0, subscriptionPath_1.getSubscriptionSshAlias)(doc.alias);
126
+ const { host } = (0, subscription_1.formatUrl)(doc);
127
+ await this.removePrivateKeyFile(alias);
128
+ await this.removeSshConfig(alias);
129
+ await this.generatePrivateKeyFile(alias, doc.pull_option.private_key);
130
+ await this.generateSingleSshConfig(alias, host, doc.proxy);
131
+ }
132
+ catch (error) {
133
+ this.logger.warn('跳过订阅 %s 的无效 SSH 配置: %s', doc.id, error);
134
+ }
110
135
  }
111
136
  }
112
137
  }
@@ -122,8 +147,8 @@ let SshKeyService = class SshKeyService {
122
147
  }
123
148
  async generateGlobalSshConfig(alias) {
124
149
  // Create a config that matches all hosts, making this key globally available
125
- const config = `Host *\n IdentityFile ${path_1.default.join(this.sshPath, alias)}\n StrictHostKeyChecking no\n`;
126
- await (0, utils_1.writeFileWithLock)(`${path_1.default.join(this.sshPath, `${alias}.config`)}`, config, {
150
+ const config = `Host *\n IdentityFile ${(0, subscriptionPath_1.resolveSubscriptionPath)(this.sshPath, alias)}\n StrictHostKeyChecking no\n`;
151
+ await (0, utils_1.writeFileWithLock)(`${(0, subscriptionPath_1.resolveSubscriptionPath)(this.sshPath, alias, '.config')}`, config, {
127
152
  encoding: 'utf8',
128
153
  mode: '600',
129
154
  });