@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
@@ -0,0 +1,551 @@
1
+ require('reflect-metadata');
2
+ const assert = require('node:assert/strict');
3
+ const test = require('node:test');
4
+ const fs = require('node:fs/promises');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const express = require('express');
8
+ const { errors } = require('celebrate');
9
+ const { Container } = require('typedi');
10
+ const load = require('../helpers/load-security-module.cjs');
11
+ const { resolveFileAccess } = load(
12
+ path.join(__dirname, '../../back/shared/fileAccess.ts'),
13
+ );
14
+
15
+ test('script routes save, list, preview and restore, with validation and conflict responses', async (t) => {
16
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-history-api-'));
17
+ const scripts = path.join(root, 'scripts');
18
+ await fs.mkdir(scripts);
19
+ await fs.writeFile(path.join(scripts, 'test.js'), 'before');
20
+ const config = {
21
+ scriptPath: scripts,
22
+ configPath: path.join(root, 'config'),
23
+ dataPath: root,
24
+ bakPath: path.join(root, 'bak'),
25
+ blackFileList: ['auth.json'],
26
+ writePathList: [scripts, path.join(root, 'config')],
27
+ };
28
+ await fs.mkdir(config.bakPath);
29
+ await fs.mkdir(config.configPath);
30
+ let failure = '';
31
+ let beforeRealpath;
32
+ class ScriptService {
33
+ checkFilePath(dir, name) {
34
+ return resolveFileAccess(scripts, [dir || '', name]);
35
+ }
36
+ }
37
+ const mocks = {
38
+ '../config': { default: config, __esModule: true },
39
+ 'fs/promises': {
40
+ ...fs,
41
+ realpath: async (file, ...args) => {
42
+ if (beforeRealpath) await beforeRealpath(file);
43
+ return fs.realpath(file, ...args);
44
+ },
45
+ copyFile: async (from, to) => {
46
+ if (failure === 'backup' && path.dirname(to) === config.bakPath)
47
+ throw Object.assign(new Error('backup denied'), { code: 'EACCES' });
48
+ return fs.copyFile(from, to);
49
+ },
50
+ writeFile: async (file, ...args) => {
51
+ if (failure === 'history' && String(file).endsWith('.pending.tmp'))
52
+ throw Object.assign(new Error('history full'), { code: 'ENOSPC' });
53
+ return fs.writeFile(file, ...args);
54
+ },
55
+ },
56
+ '../config/util': {
57
+ rmPath: (file) => fs.rm(file, { force: true, recursive: true }),
58
+ fileExist: async (file) =>
59
+ fs.access(file).then(
60
+ () => true,
61
+ () => false,
62
+ ),
63
+ },
64
+ '../services/script': { default: ScriptService, __esModule: true },
65
+ '../shared/i18n': { t: (value) => value },
66
+ };
67
+ const cache = new Map();
68
+ const api = load(
69
+ path.join(__dirname, '../../back/api/script.ts'),
70
+ mocks,
71
+ cache,
72
+ );
73
+ const { default: ScriptHistoryService } = load(
74
+ path.join(__dirname, '../../back/services/scriptHistory.ts'),
75
+ mocks,
76
+ cache,
77
+ );
78
+ Container.set(ScriptService, new ScriptService());
79
+ t.after(() => {
80
+ Container.remove(ScriptHistoryService);
81
+ Container.remove(ScriptService);
82
+ });
83
+ assert.ok(Container.has(ScriptHistoryService));
84
+ const historyService = Container.get(ScriptHistoryService);
85
+ assert.strictEqual(Container.get(ScriptHistoryService), historyService);
86
+ // An empty history read must not create storage or other persistent resources.
87
+ assert.deepEqual((await historyService.list('', 'test.js')).versions, []);
88
+ await assert.rejects(fs.stat(path.join(root, 'script-history')), {
89
+ code: 'ENOENT',
90
+ });
91
+ const app = express();
92
+ app.use(express.json({ limit: '50mb' }));
93
+ api.default(app);
94
+ app.use(errors());
95
+ app.use((error, _req, res, _next) =>
96
+ res.status(500).json({ error: error.message }),
97
+ );
98
+ const server = app.listen(0, '127.0.0.1');
99
+ await new Promise((resolve) => server.once('listening', resolve));
100
+ t.after(async () => {
101
+ await new Promise((resolve) => server.close(resolve));
102
+ await fs.rm(root, { recursive: true, force: true });
103
+ });
104
+ const base = `http://127.0.0.1:${server.address().port}`;
105
+ const call = async (url, body, method = 'PUT') => {
106
+ const res = await fetch(
107
+ base + url,
108
+ body && {
109
+ method,
110
+ headers: { 'content-type': 'application/json' },
111
+ body: JSON.stringify(body),
112
+ },
113
+ );
114
+ return { status: res.status, body: await res.json() };
115
+ };
116
+ assert.equal(
117
+ (await call('/scripts', { filename: 'test.js', content: 'after' })).body
118
+ .code,
119
+ 200,
120
+ );
121
+ const list = await call('/scripts/history?filename=test.js');
122
+ assert.equal(list.status, 200);
123
+ assert.equal(list.body.data.versions.length, 1);
124
+ const id = list.body.data.versions[0].id;
125
+ const preview = await call(
126
+ `/scripts/history/detail?filename=test.js&id=${id}`,
127
+ );
128
+ assert.equal(preview.body.data.version.content, 'before');
129
+ assert.equal(preview.body.data.current, 'after');
130
+ assert.equal(
131
+ (await call('/scripts/history/restore', { filename: 'test.js', id }))
132
+ .status,
133
+ 400,
134
+ );
135
+ assert.equal(
136
+ (
137
+ await call('/scripts/history/restore', {
138
+ filename: 'test.js',
139
+ id,
140
+ expectedHash: '0'.repeat(64),
141
+ })
142
+ ).status,
143
+ 409,
144
+ );
145
+ assert.equal(
146
+ (
147
+ await call('/scripts/history/restore', {
148
+ filename: 'test.js',
149
+ id,
150
+ expectedHash: preview.body.data.currentHash,
151
+ })
152
+ ).status,
153
+ 200,
154
+ );
155
+ assert.equal(
156
+ await fs.readFile(path.join(scripts, 'test.js'), 'utf8'),
157
+ 'before',
158
+ );
159
+ assert.equal(
160
+ (await call('/scripts/history?filename=..%2Foutside')).status,
161
+ 403,
162
+ );
163
+ assert.equal((await call('/scripts/history?filename=missing')).status, 404);
164
+ for (const content of ['debug-C', 'debug-D']) {
165
+ const saved = await call(
166
+ '/scripts',
167
+ { filename: 'test.js', originFilename: 'test.js', path: '', content },
168
+ 'POST',
169
+ );
170
+ assert.equal(saved.status, 200);
171
+ assert.equal(saved.body.data.historyRecorded, true);
172
+ }
173
+ const debugList = await call('/scripts/history?filename=test.js');
174
+ const newest = await call(
175
+ `/scripts/history/detail?filename=test.js&id=${debugList.body.data.versions[0].id}`,
176
+ );
177
+ assert.equal(newest.body.data.version.content, 'debug-C');
178
+ assert.equal(newest.body.data.current, 'debug-D');
179
+
180
+ // develop allows script names that are protected only in the config root.
181
+ await fs.writeFile(path.join(scripts, 'auth.json'), 'script-original');
182
+ for (const method of ['PUT', 'POST']) {
183
+ const saved = await call(
184
+ '/scripts',
185
+ { filename: 'auth.json', path: '', content: `script-${method}` },
186
+ method,
187
+ );
188
+ assert.equal(saved.status, 200);
189
+ assert.equal(saved.body.data.historyRecorded, true);
190
+ }
191
+ const namedHistory = await call('/scripts/history?filename=auth.json');
192
+ assert.equal(namedHistory.body.data.versions.length, 2);
193
+ const namedPreview = await call(
194
+ `/scripts/history/detail?filename=auth.json&id=${namedHistory.body.data.versions[0].id}`,
195
+ );
196
+ assert.equal(namedPreview.body.data.version.content, 'script-PUT');
197
+ assert.equal(namedPreview.body.data.current, 'script-POST');
198
+ assert.equal(
199
+ (
200
+ await call('/scripts/history/restore', {
201
+ filename: 'auth.json',
202
+ id: namedHistory.body.data.versions[0].id,
203
+ expectedHash: namedPreview.body.data.currentHash,
204
+ })
205
+ ).status,
206
+ 200,
207
+ );
208
+ assert.equal(
209
+ await fs.readFile(path.join(scripts, 'auth.json'), 'utf8'),
210
+ 'script-PUT',
211
+ );
212
+
213
+ // Both editor PUT and debugger POST support the same explicit opt-out.
214
+ for (const method of ['PUT', 'POST']) {
215
+ await fs.writeFile(
216
+ path.join(scripts, 'large.js'),
217
+ 'x'.repeat(1024 * 1024 + 1),
218
+ );
219
+ const payload = { filename: 'large.js', path: '', content: 'small' };
220
+ const rejected = await call('/scripts', payload, method);
221
+ assert.equal(rejected.status, 413);
222
+ assert.equal(rejected.body.historyUnavailable, true);
223
+ assert.equal(
224
+ (await call('/scripts', { ...payload, skipHistory: true }, method))
225
+ .status,
226
+ 400,
227
+ );
228
+ const saved = await call(
229
+ '/scripts',
230
+ {
231
+ ...payload,
232
+ skipHistory: true,
233
+ expectedHash: rejected.body.currentHash,
234
+ },
235
+ method,
236
+ );
237
+ assert.equal(saved.status, 200);
238
+ assert.equal(saved.body.data.historyRecorded, false);
239
+ assert.equal(
240
+ await fs.readFile(path.join(scripts, 'large.js'), 'utf8'),
241
+ 'small',
242
+ );
243
+ }
244
+ await t.test(
245
+ 'save-as rejects paths outside writable roots before backup or history changes',
246
+ async () => {
247
+ const outside = path.join(root, 'outside');
248
+ const sibling = `${scripts}-sibling`;
249
+ for (const dir of [outside, sibling]) {
250
+ await fs.mkdir(dir);
251
+ await fs.writeFile(path.join(dir, 'source.js'), 'outside-source');
252
+ await fs.writeFile(path.join(dir, 'destination.js'), 'outside-target');
253
+ }
254
+ await fs.writeFile(
255
+ path.join(scripts, 'boundary-source.js'),
256
+ 'safe-source',
257
+ );
258
+ await fs.writeFile(
259
+ path.join(scripts, 'boundary-target.js'),
260
+ 'safe-target',
261
+ );
262
+ await fs.symlink(outside, path.join(scripts, 'outside-link'));
263
+ for (const escape of [
264
+ '../outside',
265
+ '../scripts-sibling',
266
+ 'outside-link',
267
+ ]) {
268
+ for (const escapedSide of ['source', 'target']) {
269
+ const result = await call(
270
+ '/scripts',
271
+ {
272
+ filename:
273
+ escapedSide === 'target'
274
+ ? `${escape}/destination.js`
275
+ : 'boundary-target.js',
276
+ originFilename:
277
+ escapedSide === 'source'
278
+ ? `${escape}/source.js`
279
+ : 'boundary-source.js',
280
+ content: 'changed',
281
+ },
282
+ 'POST',
283
+ );
284
+ assert.equal(result.body.code, 403);
285
+ }
286
+ }
287
+ assert.equal(
288
+ await fs.readFile(path.join(scripts, 'boundary-source.js'), 'utf8'),
289
+ 'safe-source',
290
+ );
291
+ assert.equal(
292
+ await fs.readFile(path.join(scripts, 'boundary-target.js'), 'utf8'),
293
+ 'safe-target',
294
+ );
295
+ for (const dir of [outside, sibling]) {
296
+ assert.equal(
297
+ await fs.readFile(path.join(dir, 'source.js'), 'utf8'),
298
+ 'outside-source',
299
+ );
300
+ assert.equal(
301
+ await fs.readFile(path.join(dir, 'destination.js'), 'utf8'),
302
+ 'outside-target',
303
+ );
304
+ }
305
+ assert.deepEqual(await fs.readdir(config.bakPath), []);
306
+ assert.equal(
307
+ (await call('/scripts/history?filename=boundary-target.js')).body.data
308
+ .versions.length,
309
+ 0,
310
+ );
311
+ },
312
+ );
313
+ for (const swappedSide of ['source', 'target']) {
314
+ await t.test(
315
+ `save-as rejects a ${swappedSide} symlink changed during real-path resolution`,
316
+ async () => {
317
+ const source = path.join(scripts, `${swappedSide}-race-source.js`);
318
+ const destination = path.join(scripts, `${swappedSide}-race-target.js`);
319
+ const outside = path.join(root, `${swappedSide}-race-outside.js`);
320
+ await fs.writeFile(source, 'safe-source');
321
+ await fs.writeFile(destination, 'safe-target');
322
+ await fs.writeFile(outside, 'outside-sentinel');
323
+ const swapped = swappedSide === 'source' ? source : destination;
324
+ let swappedOnce = false;
325
+ beforeRealpath = async (file) => {
326
+ if (file === swapped && !swappedOnce) {
327
+ swappedOnce = true;
328
+ await fs.unlink(swapped);
329
+ await fs.symlink(outside, swapped);
330
+ }
331
+ };
332
+ try {
333
+ const result = await call(
334
+ '/scripts',
335
+ {
336
+ filename: path.basename(destination),
337
+ originFilename: path.basename(source),
338
+ content: 'changed',
339
+ },
340
+ 'POST',
341
+ );
342
+ assert.equal(swappedOnce, true);
343
+ assert.equal(result.status, 403);
344
+ assert.equal(await fs.readFile(outside, 'utf8'), 'outside-sentinel');
345
+ assert.equal(
346
+ await fs.readFile(
347
+ swappedSide === 'source' ? destination : source,
348
+ 'utf8',
349
+ ),
350
+ swappedSide === 'source' ? 'safe-target' : 'safe-source',
351
+ );
352
+ assert.deepEqual(await fs.readdir(config.bakPath), []);
353
+ await fs.unlink(swapped);
354
+ await fs.writeFile(
355
+ swapped,
356
+ swappedSide === 'source' ? 'safe-source' : 'safe-target',
357
+ );
358
+ assert.equal(
359
+ (
360
+ await call(
361
+ `/scripts/history?filename=${path.basename(destination)}`,
362
+ )
363
+ ).body.data.versions.length,
364
+ 0,
365
+ );
366
+ } finally {
367
+ beforeRealpath = undefined;
368
+ }
369
+ },
370
+ );
371
+ }
372
+ await t.test(
373
+ 'save-as rechecks configuration secret names after resolving a changed source link',
374
+ async () => {
375
+ const secret = path.join(config.configPath, 'auth.json');
376
+ const source = path.join(config.configPath, 'ordinary.js');
377
+ const destination = path.join(scripts, 'config-race-target.js');
378
+ await fs.writeFile(secret, 'config-secret');
379
+ await fs.writeFile(source, 'ordinary-config');
380
+ await fs.writeFile(destination, 'safe-target');
381
+ let swapped = false;
382
+ beforeRealpath = async (file) => {
383
+ if (file === source && !swapped) {
384
+ swapped = true;
385
+ await fs.unlink(source);
386
+ await fs.symlink(secret, source);
387
+ }
388
+ };
389
+ try {
390
+ const result = await call(
391
+ '/scripts',
392
+ {
393
+ filename: path.basename(destination),
394
+ originFilename: '../config/ordinary.js',
395
+ content: 'changed',
396
+ },
397
+ 'POST',
398
+ );
399
+ assert.equal(swapped, true);
400
+ assert.equal(result.status, 403);
401
+ assert.equal(await fs.readFile(secret, 'utf8'), 'config-secret');
402
+ assert.equal(await fs.readFile(destination, 'utf8'), 'safe-target');
403
+ assert.deepEqual(await fs.readdir(config.bakPath), []);
404
+ assert.equal(
405
+ (await call('/scripts/history?filename=config-race-target.js')).body
406
+ .data.versions.length,
407
+ 0,
408
+ );
409
+ } finally {
410
+ beforeRealpath = undefined;
411
+ }
412
+ },
413
+ );
414
+ for (const scenario of ['target-link', 'source-link', 'normalized-path']) {
415
+ await t.test(
416
+ `save-as preserves aliases of the same file: ${scenario}`,
417
+ async () => {
418
+ const sourceName = `${scenario}-source.js`;
419
+ const aliasName = `${scenario}-alias.js`;
420
+ const sourcePath = path.join(scripts, sourceName);
421
+ await fs.writeFile(sourcePath, 'source-original');
422
+ if (scenario !== 'normalized-path')
423
+ await fs.symlink(sourceName, path.join(scripts, aliasName));
424
+ const filename =
425
+ scenario === 'target-link'
426
+ ? aliasName
427
+ : scenario === 'normalized-path'
428
+ ? `./${sourceName}`
429
+ : sourceName;
430
+ const originFilename =
431
+ scenario === 'source-link' ? aliasName : sourceName;
432
+ const saved = await call(
433
+ '/scripts',
434
+ { filename, originFilename, path: '', content: 'source-edited' },
435
+ 'POST',
436
+ );
437
+ assert.equal(saved.status, 200);
438
+ assert.equal(saved.body.code, 200);
439
+ assert.equal(await fs.readFile(sourcePath, 'utf8'), 'source-edited');
440
+ assert.equal(
441
+ await fs.readFile(path.join(scripts, filename), 'utf8'),
442
+ 'source-edited',
443
+ );
444
+ if (scenario !== 'normalized-path') {
445
+ assert.equal(
446
+ await fs.readlink(path.join(scripts, aliasName)),
447
+ sourceName,
448
+ );
449
+ const sourceHistory = await call(
450
+ `/scripts/history?filename=${sourceName}`,
451
+ );
452
+ const aliasHistory = await call(
453
+ `/scripts/history?filename=${aliasName}`,
454
+ );
455
+ assert.deepEqual(aliasHistory.body.data, sourceHistory.body.data);
456
+ }
457
+ const list = await call(
458
+ `/scripts/history?filename=${encodeURIComponent(filename)}`,
459
+ );
460
+ assert.equal(list.body.data.versions.length, 1);
461
+ const preview = await call(
462
+ `/scripts/history/detail?filename=${encodeURIComponent(
463
+ filename,
464
+ )}&id=${list.body.data.versions[0].id}`,
465
+ );
466
+ assert.equal(preview.body.data.version.content, 'source-original');
467
+ assert.equal(preview.body.data.current, 'source-edited');
468
+ },
469
+ );
470
+ }
471
+ await t.test(
472
+ 'save-as backs up the source and retains destination history before removing the source',
473
+ async () => {
474
+ await fs.writeFile(path.join(scripts, 'source.js'), 'source-original');
475
+ await fs.writeFile(
476
+ path.join(scripts, 'destination.js'),
477
+ 'destination-original',
478
+ );
479
+ const saved = await call(
480
+ '/scripts',
481
+ {
482
+ filename: 'destination.js',
483
+ originFilename: 'source.js',
484
+ path: '',
485
+ content: 'source-edited',
486
+ },
487
+ 'POST',
488
+ );
489
+ assert.equal(saved.status, 200);
490
+ await assert.rejects(fs.access(path.join(scripts, 'source.js')), {
491
+ code: 'ENOENT',
492
+ });
493
+ assert.equal(
494
+ await fs.readFile(path.join(config.bakPath, 'source.js'), 'utf8'),
495
+ 'source-original',
496
+ );
497
+ assert.equal(
498
+ await fs.readFile(path.join(scripts, 'destination.js'), 'utf8'),
499
+ 'source-edited',
500
+ );
501
+ const list = await call('/scripts/history?filename=destination.js');
502
+ const preview = await call(
503
+ `/scripts/history/detail?filename=destination.js&id=${list.body.data.versions[0].id}`,
504
+ );
505
+ assert.equal(preview.body.data.version.content, 'destination-original');
506
+ },
507
+ );
508
+ for (const step of ['backup', 'history']) {
509
+ await t.test(
510
+ `save-as ${step} failure preserves both original scripts`,
511
+ async () => {
512
+ const sourceName = `${step}-source.js`,
513
+ destinationName = `${step}-destination.js`;
514
+ await fs.writeFile(path.join(scripts, sourceName), 'source-original');
515
+ await fs.writeFile(
516
+ path.join(scripts, destinationName),
517
+ 'destination-original',
518
+ );
519
+ failure = step;
520
+ try {
521
+ const saved = await call(
522
+ '/scripts',
523
+ {
524
+ filename: destinationName,
525
+ originFilename: sourceName,
526
+ path: '',
527
+ content: 'source-edited',
528
+ },
529
+ 'POST',
530
+ );
531
+ assert.equal(saved.status, 500);
532
+ assert.equal(
533
+ await fs.readFile(path.join(scripts, sourceName), 'utf8'),
534
+ 'source-original',
535
+ );
536
+ assert.equal(
537
+ await fs.readFile(path.join(scripts, destinationName), 'utf8'),
538
+ 'destination-original',
539
+ );
540
+ assert.equal(
541
+ (await call(`/scripts/history?filename=${destinationName}`)).body
542
+ .data.versions.length,
543
+ 0,
544
+ );
545
+ } finally {
546
+ failure = '';
547
+ }
548
+ },
549
+ );
550
+ }
551
+ });