plugin-git-manager 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/client/317.e7b1d59371812c30.js +10 -0
  2. package/dist/client/434.05d0ba2b821105dc.js +10 -0
  3. package/dist/client/453.cdcba6d2d0c9522b.js +10 -0
  4. package/dist/client/454.625da741a7e1161f.js +10 -0
  5. package/dist/client/index.js +1 -1
  6. package/dist/client-v2/317.4e116f84ed9081b6.js +10 -0
  7. package/dist/client-v2/434.764113d20743a45b.js +10 -0
  8. package/dist/client-v2/453.5ab80c06d8e61a7e.js +10 -0
  9. package/dist/client-v2/454.b885b1d35ef7ff72.js +10 -0
  10. package/dist/client-v2/index.js +1 -1
  11. package/dist/locale/en-US.json +12 -1
  12. package/dist/locale/vi-VN.json +12 -1
  13. package/dist/locale/zh-CN.json +12 -1
  14. package/dist/node_modules/simple-git/package.json +1 -1
  15. package/dist/node_modules/zod/package.json +1 -1
  16. package/dist/server/actions/git-actions.js +299 -87
  17. package/dist/server/actions/gitlab-api.js +19 -12
  18. package/dist/server/actions/subtree.js +20 -10
  19. package/dist/server/plugin.js +134 -10
  20. package/dist/server/repository-access.js +2 -2
  21. package/dist/server/request-method-policy.js +2 -1
  22. package/dist/server/services/review-source.js +2 -1
  23. package/dist/server/utils/cluster-git.js +181 -0
  24. package/package.json +2 -2
  25. package/src/client/__tests__/FileExplorerAndManage.test.tsx +236 -0
  26. package/src/client/__tests__/workflowRoutes.test.ts +3 -1
  27. package/src/client/components/CommitHistory.tsx +19 -7
  28. package/src/client/components/FileExplorer.tsx +80 -34
  29. package/src/client/components/GitManagerSettings.tsx +21 -5
  30. package/src/client/components/GitOperations.tsx +25 -4
  31. package/src/client/components/GitRuntimeBanner.tsx +97 -0
  32. package/src/client/components/RepositoryConfig.tsx +28 -6
  33. package/src/client/context/GitManagerContext.tsx +156 -13
  34. package/src/client/workflowRoutes.ts +11 -0
  35. package/src/locale/en-US.json +12 -1
  36. package/src/locale/vi-VN.json +12 -1
  37. package/src/locale/zh-CN.json +12 -1
  38. package/src/server/__tests__/git-actions.test.ts +329 -4
  39. package/src/server/__tests__/smoke.test.ts +32 -1
  40. package/src/server/actions/git-actions.ts +322 -96
  41. package/src/server/actions/gitlab-api.ts +20 -14
  42. package/src/server/actions/subtree.ts +23 -6
  43. package/src/server/plugin.ts +152 -3
  44. package/src/server/repository-access.ts +2 -2
  45. package/src/server/request-method-policy.ts +1 -0
  46. package/src/server/services/review-source.ts +3 -2
  47. package/src/server/utils/cluster-git.ts +209 -0
  48. package/dist/client/317.2d0d33871e24ee24.js +0 -10
  49. package/dist/client/434.2401f7257495b66e.js +0 -10
  50. package/dist/client/453.58657b9ba0904477.js +0 -10
  51. package/dist/client-v2/317.d2466574d00f94d0.js +0 -10
  52. package/dist/client-v2/434.32b0a07b821b9329.js +0 -10
  53. package/dist/client-v2/453.f9a0ec6d8e1bd1cc.js +0 -10
@@ -1,9 +1,60 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { execFileSync } from 'child_process';
4
+ import { existsSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
5
+ import { tmpdir } from 'os';
6
+ import { join } from 'path';
1
7
  import { Context } from '@nocobase/actions';
2
- import { vi } from 'vitest';
8
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
9
+ import {
10
+ clone,
11
+ fileContent,
12
+ fileTree,
13
+ getRepo,
14
+ installGit,
15
+ resetGitBinaryCacheForTests,
16
+ runtimeStatus,
17
+ validateRepoRelativePath,
18
+ withAuth,
19
+ } from '../actions/git-actions';
20
+ import { mergeRequestDetail, mergeRequestNotes, readChatMergeRequest } from '../actions/gitlab-api';
21
+ import { subtreeOptions } from '../actions/subtree';
22
+ import { resolveReviewSource } from '../services/review-source';
23
+ import { resetClusterGitDispatchCooldownForTests } from '../utils/cluster-git';
24
+
25
+ const record = (values: Record<string, unknown>) => ({ get: (key: string) => values[key] });
26
+
27
+ function createThrower() {
28
+ return vi.fn((status: number, message: string): never => {
29
+ throw Object.assign(new Error(message), { status });
30
+ });
31
+ }
32
+
33
+ describe('Git Manager git actions & security fixes', () => {
34
+ let fixture: string;
35
+ const originalBase = process.env.GIT_REPOS_BASE_PATH;
36
+ const originalGitBinary = process.env.GIT_BINARY_PATH;
37
+
38
+ beforeEach(() => {
39
+ fixture = mkdtempSync(join(tmpdir(), 'git-actions-test-'));
40
+ process.env.GIT_REPOS_BASE_PATH = fixture;
41
+ delete process.env.GIT_BINARY_PATH;
42
+ resetGitBinaryCacheForTests();
43
+ resetClusterGitDispatchCooldownForTests();
44
+ });
3
45
 
4
- import { getRepo } from '../actions/git-actions';
46
+ afterEach(() => {
47
+ vi.restoreAllMocks();
48
+ vi.unstubAllGlobals();
49
+ if (originalBase === undefined) delete process.env.GIT_REPOS_BASE_PATH;
50
+ else process.env.GIT_REPOS_BASE_PATH = originalBase;
51
+ if (originalGitBinary === undefined) delete process.env.GIT_BINARY_PATH;
52
+ else process.env.GIT_BINARY_PATH = originalGitBinary;
53
+ resetGitBinaryCacheForTests();
54
+ resetClusterGitDispatchCooldownForTests();
55
+ rmSync(fixture, { recursive: true, force: true });
56
+ });
5
57
 
6
- describe('Git Manager git actions', () => {
7
58
  it('uses the repository ID from the request body over the URL parameter', async () => {
8
59
  const repository = { id: 20 };
9
60
  const findOne = vi.fn().mockResolvedValue(repository);
@@ -13,7 +64,7 @@ describe('Git Manager git actions', () => {
13
64
  db: {
14
65
  getRepository: vi.fn().mockReturnValue({ findOne }),
15
66
  },
16
- throw: vi.fn(),
67
+ throw: createThrower(),
17
68
  };
18
69
 
19
70
  const result = await getRepo(context as unknown as Context);
@@ -21,4 +72,278 @@ describe('Git Manager git actions', () => {
21
72
  expect(findOne).toHaveBeenCalledWith({ filterByTk: 20 });
22
73
  expect(result).toBe(repository);
23
74
  });
75
+
76
+ it.each(['../../../other-org/secret-repo/pulls/1', '../variables', '0', '-4', '12/files', 'abc'])(
77
+ 'blocks path traversal and non-integer mrIid (%s) before calling provider API',
78
+ async (badMrIid) => {
79
+ const fetchMock = vi.fn();
80
+ vi.stubGlobal('fetch', fetchMock);
81
+ const repoRecord = record({ id: 1, gitAccountId: 1, repoUrl: 'https://github.com/org/allowed-repo.git' });
82
+ const accountRecord = record({ provider: 'github', baseUrl: null, pat: 'ghp_secret', username: 'bot' });
83
+ const db = {
84
+ getRepository: (name: string) => ({
85
+ findOne: async () => (name === 'gitAccounts' ? accountRecord : repoRecord),
86
+ }),
87
+ };
88
+
89
+ const makeCtx = () =>
90
+ ({
91
+ db,
92
+ action: { params: { repositoryId: 1, mrIid: badMrIid } },
93
+ throw: createThrower(),
94
+ }) as unknown as Context;
95
+
96
+ await expect(mergeRequestDetail(makeCtx(), async () => {})).rejects.toMatchObject({
97
+ status: 400,
98
+ message: 'Invalid merge request ID',
99
+ });
100
+ await expect(mergeRequestNotes(makeCtx(), async () => {})).rejects.toMatchObject({
101
+ status: 400,
102
+ message: 'Invalid merge request ID',
103
+ });
104
+ await expect(readChatMergeRequest(makeCtx(), badMrIid as unknown as number, 1)).rejects.toMatchObject({
105
+ status: 400,
106
+ message: 'Invalid merge request ID',
107
+ });
108
+ expect(fetchMock).not.toHaveBeenCalled();
109
+ },
110
+ );
111
+
112
+ it('validates repository-relative paths by segment while allowing filenames containing double dots', () => {
113
+ expect(validateRepoRelativePath('docs/v1..v2-migration.md')).toBe('docs/v1..v2-migration.md');
114
+ expect(validateRepoRelativePath('/src/index.ts/')).toBe('src/index.ts');
115
+ for (const unsafe of ['../secret', 'src/../../etc/passwd', 'src/./file.ts', 'C:/windows/win.ini', 'bad\0file.ts']) {
116
+ expect(() => validateRepoRelativePath(unsafe)).toThrow('Invalid file path');
117
+ }
118
+ });
119
+
120
+ it('reads UTF-8 Vietnamese filenames without octal quoting in fileTree and fileContent', async () => {
121
+ const repoDir = join(fixture, 'utf8-repo');
122
+ mkdirSync(repoDir);
123
+ execFileSync('git', ['init', '-b', 'main', repoDir], { stdio: 'ignore' });
124
+ const utf8File = 'tài-liệu..v2.md';
125
+ writeFileSync(join(repoDir, utf8File), 'Xin chào NocoBase', 'utf8');
126
+ execFileSync('git', ['-C', repoDir, 'add', utf8File], { stdio: 'ignore' });
127
+ execFileSync(
128
+ 'git',
129
+ ['-C', repoDir, '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-m', 'utf8'],
130
+ { stdio: 'ignore' },
131
+ );
132
+
133
+ const repoRecord = record({ id: 1, localPath: 'utf8-repo', repoUrl: 'https://github.com/org/utf8.git' });
134
+ const db = {
135
+ getRepository: () => ({ findOne: async () => repoRecord }),
136
+ };
137
+
138
+ const treeCtx = {
139
+ db,
140
+ action: { params: { repositoryId: 1, ref: 'HEAD' } },
141
+ body: undefined as unknown,
142
+ throw: createThrower(),
143
+ };
144
+ await fileTree(treeCtx as unknown as Context, async () => {});
145
+ const treeItems = (treeCtx.body as { data: Array<{ name: string; path: string }> }).data;
146
+ expect(treeItems).toEqual([expect.objectContaining({ name: utf8File, path: utf8File })]);
147
+
148
+ const contentCtx = {
149
+ db,
150
+ action: { params: { repositoryId: 1, ref: 'HEAD', filePath: utf8File } },
151
+ body: undefined as unknown,
152
+ throw: createThrower(),
153
+ };
154
+ await fileContent(contentCtx as unknown as Context, async () => {});
155
+ expect(contentCtx.body).toMatchObject({
156
+ success: true,
157
+ data: { content: 'Xin chào NocoBase', filePath: utf8File, ref: 'HEAD' },
158
+ });
159
+ });
160
+
161
+ it('uses distributed lockManager in withAuth and skips rewriting remote URL when unchanged', async () => {
162
+ const runExclusive = vi.fn(async (_key: string, fn: () => Promise<unknown>) => fn());
163
+ const git = {
164
+ env: vi.fn(),
165
+ raw: vi.fn().mockResolvedValue('https://github.com/org/repo.git\n'),
166
+ remote: vi.fn(),
167
+ };
168
+
169
+ const result = await withAuth(
170
+ git as never,
171
+ join(fixture, 'locked-repo'),
172
+ 'https://github.com/org/repo.git',
173
+ 'ghp_token',
174
+ async () => 'ok',
175
+ 'bot',
176
+ 'origin',
177
+ { runExclusive },
178
+ );
179
+
180
+ expect(result).toBe('ok');
181
+ expect(runExclusive).toHaveBeenCalledTimes(1);
182
+ expect(git.remote).not.toHaveBeenCalled();
183
+ });
184
+
185
+ it('reports accurate missing-directory and missing-git errors in subtree and review-source', async () => {
186
+ const repoRecord = record({
187
+ id: 1,
188
+ gitAccountId: 1,
189
+ localPath: 'not-cloned-yet',
190
+ repoUrl: 'https://github.com/org/repo.git',
191
+ defaultBranch: 'main',
192
+ });
193
+ const accountRecord = record({ provider: 'github', baseUrl: null, pat: 'ghp_token', username: 'bot' });
194
+ const db = {
195
+ getRepository: (name: string) => ({
196
+ findOne: async () => (name === 'gitAccounts' ? accountRecord : repoRecord),
197
+ }),
198
+ };
199
+
200
+ const subtreeCtx = {
201
+ db,
202
+ action: { params: { repositoryId: 1 } },
203
+ t: (msg: string) => msg,
204
+ throw: createThrower(),
205
+ };
206
+ await expect(subtreeOptions(subtreeCtx as unknown as Context, async () => {})).rejects.toMatchObject({
207
+ status: 400,
208
+ message: 'Repository directory does not exist. Please clone the repository first.',
209
+ });
210
+
211
+ vi.stubGlobal(
212
+ 'fetch',
213
+ vi
214
+ .fn()
215
+ .mockResolvedValue(
216
+ new Response(JSON.stringify({ id: 99, html_url: 'https://github.com/org/repo' }), { status: 200 }),
217
+ ),
218
+ );
219
+ await expect(
220
+ resolveReviewSource(db as never, repoRecord, { targetType: 'branch', branch: 'main' }),
221
+ ).rejects.toMatchObject({
222
+ status: 400,
223
+ message: 'Repository directory does not exist. Please clone the repository first.',
224
+ });
225
+ });
226
+
227
+ it('reconnects an existing matching git directory during clone instead of failing with directory exists', async () => {
228
+ const remoteBare = join(fixture, 'remote.git');
229
+ const existingClone = join(fixture, 'existing-clone');
230
+ mkdirSync(remoteBare);
231
+ mkdirSync(existingClone);
232
+ execFileSync('git', ['init', '--bare', remoteBare], { stdio: 'ignore' });
233
+ execFileSync('git', ['init', '-b', 'main', existingClone], { stdio: 'ignore' });
234
+ execFileSync('git', ['-C', existingClone, 'remote', 'add', 'origin', 'https://github.com/org/repo.git'], {
235
+ stdio: 'ignore',
236
+ });
237
+ execFileSync(
238
+ 'git',
239
+ [
240
+ '-C',
241
+ existingClone,
242
+ 'config',
243
+ `url.${remoteBare.replace(/\\/g, '/')}.insteadOf`,
244
+ 'https://github.com/org/repo.git',
245
+ ],
246
+ { stdio: 'ignore' },
247
+ );
248
+
249
+ const update = vi.fn().mockResolvedValue(undefined);
250
+ const repoRecord = record({
251
+ id: 5,
252
+ gitAccountId: 1,
253
+ localPath: 'existing-clone',
254
+ repoUrl: 'https://github.com/org/repo.git',
255
+ defaultBranch: 'main',
256
+ });
257
+ const accountRecord = record({ provider: 'github', baseUrl: null, pat: 'ghp_token', username: 'bot' });
258
+
259
+ const ctx = {
260
+ db: {
261
+ getRepository: (name: string) => ({
262
+ findOne: async () => (name === 'gitAccounts' ? accountRecord : repoRecord),
263
+ update,
264
+ }),
265
+ },
266
+ action: { params: { repositoryId: 5 } },
267
+ body: undefined as unknown,
268
+ throw: createThrower(),
269
+ };
270
+
271
+ await clone(ctx as unknown as Context, async () => {});
272
+ expect(update).toHaveBeenCalledWith({ filterByTk: 5, values: { status: 'connected' } });
273
+ expect(ctx.body).toMatchObject({ success: true, message: 'Repository reconnected successfully' });
274
+ expect(existsSync(existingClone)).toBe(true);
275
+ });
276
+
277
+ it('auto-dispatches Cluster Manager git installation when git is missing and recovers dynamically once installed', async () => {
278
+ const missingBin = join(fixture, 'missing-git-bin');
279
+ process.env.GIT_BINARY_PATH = missingBin;
280
+ resetGitBinaryCacheForTests();
281
+
282
+ const publish = vi.fn().mockResolvedValue(undefined);
283
+ const updateConfig = vi.fn().mockResolvedValue(undefined);
284
+ const pkgConfig = record({
285
+ id: 1,
286
+ aptPackages: 'python3\ngit',
287
+ initStatus: 'succeeded',
288
+ lastInitAt: '2026-11-25T19:02:33.000Z',
289
+ initProgressPercent: 100,
290
+ aptMirrorUrl: '',
291
+ });
292
+
293
+ const app = {
294
+ pm: { get: (name: string) => (name === 'plugin-cluster-manager' ? {} : undefined) },
295
+ db: {
296
+ getCollection: (name: string) => (name === 'workerPackagesConfigs' ? {} : undefined),
297
+ getRepository: (name: string) =>
298
+ name === 'workerPackagesConfigs'
299
+ ? { findOne: async () => pkgConfig, create: vi.fn(), update: updateConfig }
300
+ : undefined,
301
+ },
302
+ pubSubManager: { isConnected: async () => true, publish },
303
+ };
304
+
305
+ const statusCtx = {
306
+ app,
307
+ body: undefined as unknown,
308
+ throw: createThrower(),
309
+ };
310
+ await runtimeStatus(statusCtx as unknown as Context, async () => {});
311
+
312
+ expect(publish).toHaveBeenCalledWith('cluster-manager.install-packages', {
313
+ targetRole: 'all',
314
+ packages: { apt: ['git'] },
315
+ registryConfig: { aptMirrorUrl: undefined },
316
+ });
317
+ expect(statusCtx.body).toMatchObject({
318
+ success: true,
319
+ data: {
320
+ gitAvailable: false,
321
+ clusterManager: { available: true, gitConfigured: true, status: 'running' },
322
+ },
323
+ });
324
+
325
+ // Simulate Cluster Manager finishing git installation on the running node without restarting the server
326
+ delete process.env.GIT_BINARY_PATH;
327
+ const recoveredCtx = {
328
+ app,
329
+ body: undefined as unknown,
330
+ throw: createThrower(),
331
+ };
332
+ await runtimeStatus(recoveredCtx as unknown as Context, async () => {});
333
+ expect(recoveredCtx.body).toMatchObject({
334
+ success: true,
335
+ data: { gitAvailable: true },
336
+ });
337
+
338
+ const installCtx = {
339
+ app,
340
+ body: undefined as unknown,
341
+ throw: createThrower(),
342
+ };
343
+ await installGit(installCtx as unknown as Context, async () => {});
344
+ expect(installCtx.body).toMatchObject({
345
+ success: true,
346
+ data: { alreadyInstalled: true },
347
+ });
348
+ });
24
349
  });
@@ -1,7 +1,7 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
3
  import { execFileSync } from 'child_process';
4
- import { mkdtempSync, mkdirSync, rmSync, symlinkSync, unlinkSync } from 'fs';
4
+ import { existsSync, mkdtempSync, mkdirSync, rmSync, symlinkSync, unlinkSync } from 'fs';
5
5
  import { tmpdir } from 'os';
6
6
  import { join } from 'path';
7
7
  import { createMockServer, type MockServer } from '@nocobase/test';
@@ -329,4 +329,35 @@ describe('Git Manager HTTP integration', () => {
329
329
  'marker',
330
330
  );
331
331
  });
332
+
333
+ it('serves runtimeStatus on GET, enforces POST on installGit, validates repository mutations, and cleans up deleted localPath', async () => {
334
+ const statusRes = await agent.get('/gitManager:runtimeStatus');
335
+ expect(statusRes.status).toBe(200);
336
+ expect(statusRes.body.data.data).toMatchObject({ gitAvailable: true });
337
+
338
+ const badMethod = await agent.get('/gitManager:installGit');
339
+ expect(badMethod.status).toBe(405);
340
+
341
+ const badUrl = await agent.resource('gitRepositories').create({
342
+ values: { name: 'bad-http', localPath: 'bad-http', repoUrl: 'http://gitlab.com/team/repo.git' },
343
+ });
344
+ expect(badUrl.status).toBe(400);
345
+
346
+ const badPath = await agent.resource('gitRepositories').create({
347
+ values: { name: 'bad-path', localPath: '../escape', repoUrl: 'https://gitlab.com/team/repo.git' },
348
+ });
349
+ expect(badPath.status).toBe(400);
350
+
351
+ const tempRepoDir = join(fixture, 'disposable-repo');
352
+ mkdirSync(tempRepoDir);
353
+ const created = await agent.resource('gitRepositories').create({
354
+ values: { name: 'disposable', localPath: 'disposable-repo', repoUrl: 'https://gitlab.com/team/disposable.git' },
355
+ });
356
+ expect(created.status).toBe(200);
357
+ expect(existsSync(tempRepoDir)).toBe(true);
358
+
359
+ const destroyed = await agent.resource('gitRepositories').destroy({ filterByTk: created.body.data.id });
360
+ expect(destroyed.status).toBe(200);
361
+ expect(existsSync(tempRepoDir)).toBe(false);
362
+ });
332
363
  });