plugin-git-manager 1.2.27 → 1.3.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 (138) hide show
  1. package/README.md +151 -108
  2. package/client-v2.d.ts +2 -2
  3. package/client-v2.js +1 -1
  4. package/client.d.ts +3 -3
  5. package/client.js +1 -1
  6. package/dist/client/{326.90c276058682b536.js → 313.d38fc1d40c4589b9.js} +1 -1
  7. package/dist/client/941.1793e67472872992.js +10 -0
  8. package/dist/client/index.js +1 -1
  9. package/dist/client-v2/156.445366026c1cc9a8.js +10 -0
  10. package/dist/client-v2/{326.42b7b53651ffab3a.js → 313.3c867179c3a1e817.js} +1 -1
  11. package/dist/client-v2/434.19c7579c06b9077c.js +10 -0
  12. package/dist/client-v2/928.bba701b5a1ece58e.js +10 -0
  13. package/dist/client-v2/941.b0d55429cd053f32.js +10 -0
  14. package/dist/client-v2/index.js +1 -1
  15. package/dist/externalVersion.js +9 -8
  16. package/dist/locale/en-US.json +396 -297
  17. package/dist/locale/vi-VN.json +384 -292
  18. package/dist/locale/zh-CN.json +150 -51
  19. package/dist/node_modules/simple-git/dist/cjs/index.js +25 -25
  20. package/dist/node_modules/simple-git/package.json +1 -1
  21. package/dist/node_modules/zod/index.cjs +1 -1
  22. package/dist/node_modules/zod/package.json +1 -1
  23. package/dist/server/actions/git-actions.js +90 -36
  24. package/dist/server/actions/gitlab-api.js +4 -2
  25. package/dist/server/actions/poller.js +5 -2
  26. package/dist/server/actions/review-cutover.js +137 -0
  27. package/dist/server/actions/review.js +150 -51
  28. package/dist/server/actions/role-permissions.js +1 -0
  29. package/dist/server/ai-tools.js +8 -9
  30. package/dist/server/collections/gitCodeReviews.js +10 -0
  31. package/dist/server/collections/gitReviewCutover.js +44 -0
  32. package/dist/server/collections/gitReviewFlows.js +3 -0
  33. package/dist/server/collections/gitReviewInbox.js +51 -0
  34. package/dist/server/collections/gitReviewProjects.js +43 -0
  35. package/dist/server/collections/gitReviewRequests.js +56 -0
  36. package/dist/server/index.js +8 -2
  37. package/dist/server/plugin.js +57 -20
  38. package/dist/server/poller.js +95 -74
  39. package/dist/server/repository-access.js +23 -5
  40. package/dist/server/request-method-policy.js +76 -0
  41. package/dist/server/review-control-access.js +79 -0
  42. package/dist/server/services/legacy-post-service.js +412 -0
  43. package/dist/server/services/registry-content-service.js +4 -3
  44. package/dist/server/services/review-service.js +1451 -0
  45. package/dist/server/services/review-source.js +325 -0
  46. package/dist/server/utils/get-repo-account.js +3 -2
  47. package/dist/server/utils/url-security.js +24 -0
  48. package/package.json +61 -43
  49. package/server.d.ts +2 -2
  50. package/server.js +1 -1
  51. package/src/client/__tests__/CommitHistory.test.tsx +79 -0
  52. package/src/client/__tests__/ReviewHistory.test.tsx +126 -0
  53. package/src/client/__tests__/RunReviewButton.test.tsx +84 -0
  54. package/src/client/__tests__/workflowRoutes.test.ts +65 -0
  55. package/src/client/ai-context.tsx +114 -114
  56. package/src/client/components/AIEmployeeSelect.tsx +63 -63
  57. package/src/client/components/CommitHistory.tsx +429 -374
  58. package/src/client/components/FileExplorer.tsx +386 -386
  59. package/src/client/components/GitAccounts.tsx +179 -179
  60. package/src/client/components/GitManagerSettings.tsx +160 -160
  61. package/src/client/components/GitOperations.tsx +220 -220
  62. package/src/client/components/LLMModelSelect.tsx +63 -63
  63. package/src/client/components/LLMServiceSelect.tsx +58 -58
  64. package/src/client/components/MarkdownView.tsx +80 -80
  65. package/src/client/components/MergeRequests.tsx +790 -790
  66. package/src/client/components/PollingStatus.tsx +225 -225
  67. package/src/client/components/RepositoryConfig.tsx +335 -335
  68. package/src/client/components/RepositoryPermissions.tsx +123 -123
  69. package/src/client/components/ReviewFlows.tsx +352 -303
  70. package/src/client/components/ReviewHistory.tsx +796 -566
  71. package/src/client/components/RunReviewButton.tsx +57 -173
  72. package/src/client/context/GitManagerContext.tsx +92 -92
  73. package/src/client/index.tsx +91 -82
  74. package/src/client/locale.ts +9 -9
  75. package/src/client/promptTemplates.ts +31 -31
  76. package/src/client/workflowRoutes.ts +42 -0
  77. package/src/client-v2/ai-context.tsx +99 -0
  78. package/src/client-v2/components/SubtreeSplits.tsx +547 -547
  79. package/src/client-v2/index.tsx +1 -1
  80. package/src/client-v2/locale.ts +8 -8
  81. package/src/client-v2/plugin.tsx +67 -39
  82. package/src/index.ts +2 -2
  83. package/src/locale/en-US.json +396 -297
  84. package/src/locale/vi-VN.json +384 -292
  85. package/src/locale/zh-CN.json +150 -51
  86. package/src/server/__tests__/git-actions.test.ts +24 -24
  87. package/src/server/__tests__/git-security.test.ts +170 -0
  88. package/src/server/__tests__/plugin-url-security.test.ts +17 -17
  89. package/src/server/__tests__/poller-lifecycle.test.ts +71 -0
  90. package/src/server/__tests__/poller.test.ts +37 -37
  91. package/src/server/__tests__/repository-access.test.ts +760 -752
  92. package/src/server/__tests__/review-service.integration.test.ts +1263 -0
  93. package/src/server/__tests__/review.test.ts +76 -137
  94. package/src/server/__tests__/role-permissions.test.ts +147 -147
  95. package/src/server/__tests__/smoke.test.ts +139 -17
  96. package/src/server/__tests__/subtree.test.ts +85 -85
  97. package/src/server/actions/git-actions.ts +540 -480
  98. package/src/server/actions/gitlab-api.ts +422 -411
  99. package/src/server/actions/poller.ts +39 -27
  100. package/src/server/actions/review-cutover.ts +121 -0
  101. package/src/server/actions/review.ts +1498 -1369
  102. package/src/server/actions/role-permissions.ts +331 -321
  103. package/src/server/actions/subtree.ts +508 -508
  104. package/src/server/ai-tools.ts +334 -319
  105. package/src/server/collections/gitAccounts.ts +56 -56
  106. package/src/server/collections/gitCodeReviews.ts +218 -199
  107. package/src/server/collections/gitRepositories.ts +87 -87
  108. package/src/server/collections/gitReviewCutover.ts +23 -0
  109. package/src/server/collections/gitReviewFlows.ts +120 -108
  110. package/src/server/collections/gitReviewInbox.ts +30 -0
  111. package/src/server/collections/gitReviewProjects.ts +22 -0
  112. package/src/server/collections/gitReviewRequests.ts +35 -0
  113. package/src/server/collections/gitSubtreeConfigs.ts +38 -38
  114. package/src/server/collections/gitSubtreeRuns.ts +30 -30
  115. package/src/server/index.ts +14 -2
  116. package/src/server/migrations/20260508000000-add-auto-review-flow-id.ts +29 -29
  117. package/src/server/migrations/20260712000000-add-git-accounts.ts +198 -198
  118. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +81 -81
  119. package/src/server/plugin.ts +409 -361
  120. package/src/server/poller.ts +365 -352
  121. package/src/server/repository-access.ts +803 -773
  122. package/src/server/request-method-policy.ts +56 -0
  123. package/src/server/review-control-access.ts +71 -0
  124. package/src/server/services/__tests__/registry-content-service.test.ts +359 -345
  125. package/src/server/services/__tests__/review-source.test.ts +226 -0
  126. package/src/server/services/legacy-post-service.ts +550 -0
  127. package/src/server/services/registry-content-service.ts +495 -484
  128. package/src/server/services/review-service.ts +1899 -0
  129. package/src/server/services/review-source.ts +359 -0
  130. package/src/server/utils/__tests__/redact.test.ts +56 -56
  131. package/src/server/utils/__tests__/url-security.test.ts +85 -85
  132. package/src/server/utils/get-repo-account.ts +51 -41
  133. package/src/server/utils/gitlab-url.ts +38 -38
  134. package/src/server/utils/redact.ts +87 -87
  135. package/src/server/utils/url-security.ts +128 -95
  136. package/dist/client/900.acf7d1fa22f95e71.js +0 -10
  137. package/dist/client-v2/434.7a27051db18526c0.js +0 -10
  138. package/dist/client-v2/900.f32b9dc85249fc0a.js +0 -10
@@ -1,480 +1,540 @@
1
- import simpleGit, { SimpleGit } from 'simple-git';
2
- import { Context } from '@nocobase/actions';
3
- import * as path from 'path';
4
- import * as fs from 'fs';
5
- import { spawnSync } from 'child_process';
6
- import { getEffectiveActionParams } from '../repository-access';
7
- import { redactPat, redactError } from '../utils/redact';
8
- import { getRepoAccount } from '../utils/get-repo-account';
9
- import { assertUrlHasNoUserInfo } from '../utils/url-security';
10
-
11
- // Disallow leading `-` to prevent argument-injection (e.g. `--upload-pack=...`)
12
- // when refs are passed as positional args to git.
13
- const REF_PATTERN = /^(?!-)[a-zA-Z0-9._/-]+$/;
14
-
15
- // Per-repo mutex to prevent PAT race conditions in withAuth
16
- const repoLocks = new Map<string, Promise<any>>();
17
- const GIT_BINARY = process.env.GIT_BINARY_PATH || process.env.GIT_EXECUTABLE || 'git';
18
- let gitAvailabilityChecked = false;
19
-
20
- interface GitActionParams {
21
- repositoryId?: number | string;
22
- file?: string;
23
- commitHash?: string;
24
- compareHash?: string;
25
- maxCount?: number | string;
26
- branch?: string;
27
- ref?: string;
28
- treePath?: string;
29
- recursive?: boolean | string;
30
- filePath?: string;
31
- }
32
-
33
- function getGitActionParams(ctx: Context): GitActionParams {
34
- return getEffectiveActionParams(ctx) as GitActionParams;
35
- }
36
-
37
- export function acquireLock(key: string): { promise: Promise<void>; release: () => void } {
38
- const prev = repoLocks.get(key) || Promise.resolve();
39
- let release = () => {};
40
- const next = new Promise<void>((resolve) => {
41
- release = resolve;
42
- });
43
- const promise = prev.then(() => {});
44
- repoLocks.set(key, next);
45
- return { promise, release };
46
- }
47
-
48
- export function validateRef(ref: string): string {
49
- if (!REF_PATTERN.test(ref)) {
50
- throw new Error(`Invalid ref: ${ref}`);
51
- }
52
- return ref;
53
- }
54
-
55
- export function validateBranch(branch: string): string {
56
- const segments = branch.split('/');
57
- if (
58
- !branch ||
59
- !REF_PATTERN.test(branch) ||
60
- branch === '@' ||
61
- branch.includes('..') ||
62
- branch.includes('@{') ||
63
- branch.includes('//') ||
64
- branch.endsWith('/') ||
65
- branch.endsWith('.') ||
66
- segments.some((segment) => segment.startsWith('.') || segment.toLowerCase().endsWith('.lock'))
67
- ) {
68
- throw new Error(`Invalid branch name: ${branch}`);
69
- }
70
- return branch;
71
- }
72
-
73
- export function validateRepoUrl(repoUrl: string): void {
74
- assertUrlHasNoUserInfo(repoUrl);
75
- let parsed: URL;
76
- try {
77
- parsed = new URL(repoUrl);
78
- } catch {
79
- throw new Error('Invalid repository URL');
80
- }
81
- if (parsed.protocol !== 'https:') {
82
- throw new Error('Only HTTPS repository URLs are allowed');
83
- }
84
- }
85
-
86
- export async function withAuth<T>(
87
- git: ReturnType<typeof simpleGit>,
88
- localPath: string,
89
- repoUrl: string,
90
- pat: string,
91
- fn: () => Promise<T>,
92
- username?: string,
93
- remoteName = 'origin',
94
- ): Promise<T> {
95
- assertUrlHasNoUserInfo(repoUrl);
96
- // Lock by local working tree — that's what `git.remote('set-url', ...)`
97
- // mutates. Two repo records sharing a `repoUrl` but cloned to different
98
- // paths can run in parallel safely; conversely, two repos pointed at the
99
- // same `localPath` (config error) must NOT run concurrent set-url's.
100
- const lockKey = localPath;
101
- const lock = acquireLock(lockKey);
102
- await lock.promise;
103
- const authUrl = getAuthUrl(repoUrl, pat, username);
104
- await git.remote(['set-url', remoteName, authUrl]);
105
- try {
106
- return await fn();
107
- } catch (err) {
108
- // simple-git often echoes the authenticated URL in stderr — scrub before re-throw
109
- throw redactError(err);
110
- } finally {
111
- // H-2 fix: guard PAT cleanup — if reset fails, the PAT-embedded URL persists on disk
112
- try {
113
- await git.remote(['set-url', remoteName, repoUrl]);
114
- } catch (cleanupErr) {
115
- // Critical: PAT may be persisted in .git/config — attempt one more cleanup
116
- try {
117
- await git.remote(['set-url', remoteName, repoUrl]);
118
- } catch {
119
- // Log but don't throw — the original operation already completed
120
- console.error(
121
- `[plugin-git-manager] CRITICAL: failed to remove PAT from remote URL for ${redactPat(repoUrl)}. ` +
122
- `Manual cleanup of .git/config may be required.`,
123
- redactError(cleanupErr),
124
- );
125
- }
126
- }
127
- lock.release();
128
- }
129
- }
130
-
131
- function getAuthUrl(repoUrl: string, pat: string, username?: string): string {
132
- assertUrlHasNoUserInfo(repoUrl);
133
- const url = new URL(repoUrl.trim());
134
- url.username = (username || 'oauth2').trim();
135
- url.password = pat.trim();
136
- return url.toString();
137
- }
138
-
139
- function getGitMissingMessage() {
140
- return `Git executable "${GIT_BINARY}" was not found on the server. Install git in the app/worker container, or set GIT_BINARY_PATH to the absolute git binary path.`;
141
- }
142
-
143
- function assertGitAvailable(ctx: Context) {
144
- if (gitAvailabilityChecked) return;
145
-
146
- const check = spawnSync(GIT_BINARY, ['--version'], { stdio: 'ignore' });
147
- if (check.error || check.status !== 0) {
148
- ctx.throw(503, getGitMissingMessage());
149
- }
150
- gitAvailabilityChecked = true;
151
- }
152
-
153
- function isMissingGitError(error: any) {
154
- const message = error?.message || String(error);
155
- return error?.code === 'ENOENT' || /spawn .*git.*ENOENT/i.test(message);
156
- }
157
-
158
- export function createGit(baseDir?: string): SimpleGit {
159
- return simpleGit({ baseDir, binary: GIT_BINARY } as any);
160
- }
161
-
162
- export function getGitBinaryPath(): string {
163
- return GIT_BINARY;
164
- }
165
-
166
- function getGit(ctx: Context, localPath: string): SimpleGit {
167
- if (!fs.existsSync(localPath)) {
168
- ctx.throw(400, 'Repository directory does not exist. Please clone the repository first.');
169
- }
170
- assertGitAvailable(ctx);
171
- return createGit(localPath);
172
- }
173
-
174
- export async function getRepo(ctx: Context) {
175
- const { repositoryId } = getGitActionParams(ctx);
176
- const repo = await ctx.db.getRepository('gitRepositories').findOne({
177
- filterByTk: repositoryId,
178
- });
179
- if (!repo) {
180
- ctx.throw(404, 'Repository not found');
181
- }
182
- return repo;
183
- }
184
-
185
- // Validate localPath to prevent path traversal
186
- export function validateLocalPath(localPath: string): string {
187
- const basePath = process.env.GIT_REPOS_BASE_PATH || path.join(process.cwd(), 'storage', 'git-repos');
188
- const resolved = path.resolve(basePath, localPath);
189
-
190
- // Ensure the resolved path is strictly inside the basePath.
191
- // We add path.sep to prevent partial matches like /storage/git-repo-hack matching /storage/git-repo
192
- const strictBasePath = path.resolve(basePath) + path.sep;
193
-
194
- if (!resolved.startsWith(strictBasePath) && resolved !== path.resolve(basePath)) {
195
- throw new Error('Invalid local path: path traversal detected or path is outside the allowed base directory');
196
- }
197
- return resolved;
198
- }
199
-
200
- export async function clone(ctx: Context, next: () => Promise<void>) {
201
- const repo = await getRepo(ctx);
202
- const localPath = validateLocalPath(repo.get('localPath'));
203
- const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
204
- const defaultBranch = ((repo.get('defaultBranch') as string) || 'main').trim() || 'main';
205
-
206
- const account = await getRepoAccount(ctx.db, repo);
207
- if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
208
- const { pat, username } = account;
209
-
210
- validateRepoUrl(repoUrl);
211
- // Prevent argument-injection through `defaultBranch` (e.g. `--upload-pack=...`)
212
- validateBranch(defaultBranch);
213
-
214
- // Check if directory already exists
215
- if (fs.existsSync(localPath)) {
216
- ctx.throw(400, 'Directory already exists. Remove it before cloning again.');
217
- }
218
-
219
- if (!fs.existsSync(path.dirname(localPath))) {
220
- fs.mkdirSync(path.dirname(localPath), { recursive: true });
221
- }
222
-
223
- const authUrl = getAuthUrl(repoUrl, pat, username);
224
- assertGitAvailable(ctx);
225
- try {
226
- await createGit().clone(authUrl, localPath, ['--branch', defaultBranch]);
227
- // Remove PAT from the cloned repo's remote URL
228
- await createGit(localPath).remote(['set-url', 'origin', repoUrl]);
229
- await ctx.db.getRepository('gitRepositories').update({
230
- filterByTk: repo.get('id'),
231
- values: { status: 'connected' },
232
- });
233
- ctx.body = { success: true, message: 'Repository cloned successfully' };
234
- } catch (err) {
235
- await ctx.db.getRepository('gitRepositories').update({
236
- filterByTk: repo.get('id'),
237
- values: { status: 'error' },
238
- });
239
- // Redact embedded PAT before the error reaches the client / log
240
- if (isMissingGitError(err)) {
241
- ctx.throw(503, getGitMissingMessage());
242
- }
243
- throw redactError(err);
244
- }
245
- await next();
246
- }
247
-
248
- export async function pull(ctx: Context, next: () => Promise<void>) {
249
- const repo = await getRepo(ctx);
250
- const localPath = validateLocalPath(repo.get('localPath'));
251
- const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
252
-
253
- const account = await getRepoAccount(ctx.db, repo);
254
- if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
255
- const { pat, username } = account;
256
-
257
- const git = getGit(ctx, localPath);
258
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.pull(), username);
259
-
260
- ctx.body = { success: true, data: result };
261
- await next();
262
- }
263
-
264
- export async function push(ctx: Context, next: () => Promise<void>) {
265
- const repo = await getRepo(ctx);
266
- const localPath = validateLocalPath(repo.get('localPath'));
267
- const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
268
-
269
- const account = await getRepoAccount(ctx.db, repo);
270
- if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
271
- const { pat, username } = account;
272
-
273
- const git = getGit(ctx, localPath);
274
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.push(), username);
275
-
276
- ctx.body = { success: true, data: result };
277
- await next();
278
- }
279
-
280
- export async function fetch(ctx: Context, next: () => Promise<void>) {
281
- const repo = await getRepo(ctx);
282
- const localPath = validateLocalPath(repo.get('localPath'));
283
- const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
284
-
285
- const account = await getRepoAccount(ctx.db, repo);
286
- if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
287
- const { pat, username } = account;
288
-
289
- const git = getGit(ctx, localPath);
290
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.fetch(), username);
291
-
292
- ctx.body = { success: true, data: result };
293
- await next();
294
- }
295
-
296
- export async function diff(ctx: Context, next: () => Promise<void>) {
297
- const repo = await getRepo(ctx);
298
- const localPath = validateLocalPath(repo.get('localPath'));
299
- const { file, commitHash, compareHash } = getGitActionParams(ctx);
300
-
301
- const git = getGit(ctx, localPath);
302
- const args: string[] = [];
303
- if (commitHash && compareHash) {
304
- args.push(validateRef(commitHash), validateRef(compareHash));
305
- } else if (commitHash) {
306
- args.push(validateRef(commitHash) + '^', validateRef(commitHash));
307
- }
308
- if (file) {
309
- if (file.includes('..')) ctx.throw(400, 'Invalid file path');
310
- args.push('--', file);
311
- }
312
-
313
- const result = await git.diff(args);
314
- ctx.body = { success: true, data: result };
315
- await next();
316
- }
317
-
318
- export async function status(ctx: Context, next: () => Promise<void>) {
319
- const repo = await getRepo(ctx);
320
- const localPath = validateLocalPath(repo.get('localPath'));
321
- const result = await getGit(ctx, localPath).status();
322
- ctx.body = { success: true, data: result };
323
- await next();
324
- }
325
-
326
- export async function log(ctx: Context, next: () => Promise<void>) {
327
- const repo = await getRepo(ctx);
328
- const localPath = validateLocalPath(repo.get('localPath'));
329
- const { maxCount = 50, file } = getGitActionParams(ctx);
330
-
331
- const parsed = Number.parseInt(String(maxCount), 10);
332
- const options: Record<string, any> = { maxCount: Math.min(Math.max(parsed || 50, 1), 500) };
333
- if (file) {
334
- if (file.includes('..')) ctx.throw(400, 'Invalid file path');
335
- options.file = file;
336
- }
337
-
338
- const result = await getGit(ctx, localPath).log(options);
339
- ctx.body = { success: true, data: result };
340
- await next();
341
- }
342
-
343
- export async function branches(ctx: Context, next: () => Promise<void>) {
344
- const repo = await getRepo(ctx);
345
- const localPath = validateLocalPath(repo.get('localPath'));
346
- const result = await getGit(ctx, localPath).branch();
347
- ctx.body = { success: true, data: result };
348
- await next();
349
- }
350
-
351
- export async function checkout(ctx: Context, next: () => Promise<void>) {
352
- const repo = await getRepo(ctx);
353
- const localPath = validateLocalPath(repo.get('localPath'));
354
- const { branch } = getGitActionParams(ctx);
355
- if (!branch) ctx.throw(400, 'branch is required');
356
- validateBranch(branch);
357
- await getGit(ctx, localPath).checkout(branch);
358
- ctx.body = { success: true, message: `Switched to branch ${branch}` };
359
- await next();
360
- }
361
-
362
- export async function fileTree(ctx: Context, next: () => Promise<void>) {
363
- const repo = await getRepo(ctx);
364
- const localPath = validateLocalPath(repo.get('localPath'));
365
- const { ref = 'HEAD', treePath = '', recursive } = getGitActionParams(ctx);
366
-
367
- const git = getGit(ctx, localPath);
368
- validateRef(ref);
369
- if (treePath && treePath.includes('..')) {
370
- ctx.throw(400, 'Invalid tree path');
371
- }
372
-
373
- const detailArgs = ['ls-tree', '-l'];
374
- if (recursive === true || recursive === 'true') detailArgs.push('-r');
375
- detailArgs.push(ref);
376
- if (treePath) detailArgs.push(treePath + '/');
377
- const detailedResult = await git.raw(detailArgs);
378
- const items = detailedResult
379
- .trim()
380
- .split('\n')
381
- .filter(Boolean)
382
- .map((line) => {
383
- // format: <mode> <type> <hash> <size>\t<name>
384
- const match = line.match(/^(\d+)\s+(blob|tree)\s+([a-f0-9]+)\s+(-|\d+)\t(.+)$/);
385
- if (!match) return null;
386
- const fullPath = match[5];
387
- // Extract just the filename from the full path when using treePath prefix
388
- const parts = fullPath.split('/');
389
- const name = fullPath.includes('/') ? parts[parts.length - 1] : fullPath;
390
- return {
391
- mode: match[1],
392
- type: match[2] as 'blob' | 'tree',
393
- hash: match[3],
394
- size: match[4] === '-' ? 0 : parseInt(match[4], 10),
395
- name,
396
- path: fullPath,
397
- };
398
- })
399
- .filter((item): item is NonNullable<typeof item> => item !== null);
400
-
401
- // Sort: directories first, then files, both alphabetical
402
- items.sort((a, b) => {
403
- if (a.type !== b.type) return a.type === 'tree' ? -1 : 1;
404
- return a.name.localeCompare(b.name);
405
- });
406
-
407
- ctx.body = { success: true, data: items };
408
- await next();
409
- }
410
-
411
- export async function fileContent(ctx: Context, next: () => Promise<void>) {
412
- const repo = await getRepo(ctx);
413
- const localPath = validateLocalPath(repo.get('localPath'));
414
- const { ref = 'HEAD', filePath } = getGitActionParams(ctx);
415
-
416
- if (!filePath) {
417
- ctx.throw(400, 'filePath is required');
418
- }
419
- if (filePath.includes('..')) {
420
- ctx.throw(400, 'Invalid file path');
421
- }
422
-
423
- validateRef(ref);
424
- const git = getGit(ctx, localPath);
425
- const content = await git.show([`${ref}:${filePath}`]);
426
- ctx.body = { success: true, data: { content, filePath, ref } };
427
- await next();
428
- }
429
-
430
- export async function commitDetail(ctx: Context, next: () => Promise<void>) {
431
- const repo = await getRepo(ctx);
432
- const localPath = validateLocalPath(repo.get('localPath'));
433
- const { commitHash } = getGitActionParams(ctx);
434
-
435
- if (!commitHash) {
436
- ctx.throw(400, 'commitHash is required');
437
- }
438
-
439
- const git = getGit(ctx, localPath);
440
- validateRef(commitHash);
441
-
442
- // Use %x00 in format string to tell git to output null bytes, avoiding null bytes in args
443
- const DELIM_ARG = '%x00';
444
- const DELIM_OUT = '\x00';
445
- const format = `%H${DELIM_ARG}%an${DELIM_ARG}%ae${DELIM_ARG}%aI${DELIM_ARG}%s${DELIM_ARG}%b`;
446
-
447
- // Run show + diff in parallel for better performance
448
- const [show, diffResult] = await Promise.all([
449
- git.show([commitHash, '--stat', `--format=${format}`]),
450
- git.diff([`${commitHash}^`, commitHash, '--name-status']).catch(() =>
451
- // Root commit has no parent — use diff-tree --root instead
452
- git.raw(['diff-tree', '--root', '--name-status', '-r', commitHash]),
453
- ),
454
- ]);
455
-
456
- const parts = show.split(DELIM_OUT);
457
- const files = diffResult
458
- .trim()
459
- .split('\n')
460
- .filter(Boolean)
461
- .map((line) => {
462
- const [statusCode, ...fileParts] = line.split('\t');
463
- return { status: statusCode, file: fileParts.join('\t') };
464
- });
465
-
466
- ctx.body = {
467
- success: true,
468
- data: {
469
- hash: parts[0] || '',
470
- author: parts[1] || '',
471
- email: parts[2] || '',
472
- date: parts[3] || '',
473
- subject: parts[4] || '',
474
- body: (parts[5] || '').split('\n\n')[0].trim(), // body before --stat output
475
- files,
476
- raw: show,
477
- },
478
- };
479
- await next();
480
- }
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import simpleGit, { SimpleGit } from 'simple-git';
11
+ import { Context } from '@nocobase/actions';
12
+ import * as path from 'path';
13
+ import * as fs from 'fs';
14
+ import { spawnSync } from 'child_process';
15
+ import { getEffectiveActionParams } from '../repository-access';
16
+ import { redactError } from '../utils/redact';
17
+ import { getRepoAccount } from '../utils/get-repo-account';
18
+ import { assertUrlHasNoUserInfo } from '../utils/url-security';
19
+
20
+ // Disallow leading `-` to prevent argument-injection (e.g. `--upload-pack=...`)
21
+ // when refs are passed as positional args to git.
22
+ const REF_PATTERN = /^(?!-)[a-zA-Z0-9._/-]+$/;
23
+
24
+ // Per-repo mutex to prevent PAT race conditions in withAuth
25
+ const repoLocks = new Map<string, Promise<void>>();
26
+ const GIT_BINARY = process.env.GIT_BINARY_PATH || process.env.GIT_EXECUTABLE || 'git';
27
+ let gitAvailabilityChecked = false;
28
+
29
+ interface GitActionParams {
30
+ repositoryId?: number | string;
31
+ file?: string;
32
+ commitHash?: string;
33
+ compareHash?: string;
34
+ maxCount?: number | string;
35
+ branch?: string;
36
+ ref?: string;
37
+ treePath?: string;
38
+ recursive?: boolean | string;
39
+ filePath?: string;
40
+ }
41
+
42
+ function getGitActionParams(ctx: Context): GitActionParams {
43
+ return getEffectiveActionParams(ctx) as GitActionParams;
44
+ }
45
+
46
+ export function acquireLock(key: string): { promise: Promise<void>; release: () => void } {
47
+ const prev = repoLocks.get(key) || Promise.resolve();
48
+ let release = () => {};
49
+ const next = new Promise<void>((resolve) => {
50
+ release = resolve;
51
+ });
52
+ const promise = prev.then(() => {});
53
+ repoLocks.set(key, next);
54
+ return {
55
+ promise,
56
+ release: () => {
57
+ release();
58
+ if (repoLocks.get(key) === next) repoLocks.delete(key);
59
+ },
60
+ };
61
+ }
62
+
63
+ export function validateRef(ref: string): string {
64
+ if (!REF_PATTERN.test(ref)) {
65
+ throw new Error(`Invalid ref: ${ref}`);
66
+ }
67
+ return ref;
68
+ }
69
+
70
+ export function validateBranch(branch: string): string {
71
+ const segments = branch.split('/');
72
+ if (
73
+ !branch ||
74
+ !REF_PATTERN.test(branch) ||
75
+ branch === '@' ||
76
+ branch.includes('..') ||
77
+ branch.includes('@{') ||
78
+ branch.includes('//') ||
79
+ branch.endsWith('/') ||
80
+ branch.endsWith('.') ||
81
+ segments.some((segment) => segment.startsWith('.') || segment.toLowerCase().endsWith('.lock'))
82
+ ) {
83
+ throw new Error(`Invalid branch name: ${branch}`);
84
+ }
85
+ return branch;
86
+ }
87
+
88
+ export function validateRepoUrl(repoUrl: string): void {
89
+ assertUrlHasNoUserInfo(repoUrl);
90
+ let parsed: URL;
91
+ try {
92
+ parsed = new URL(repoUrl);
93
+ } catch {
94
+ throw new Error('Invalid repository URL');
95
+ }
96
+ if (parsed.protocol !== 'https:') {
97
+ throw new Error('Only HTTPS repository URLs are allowed');
98
+ }
99
+ }
100
+
101
+ export async function withAuth<T>(
102
+ git: ReturnType<typeof simpleGit>,
103
+ localPath: string,
104
+ repoUrl: string,
105
+ pat: string,
106
+ fn: () => Promise<T>,
107
+ username?: string,
108
+ remoteName = 'origin',
109
+ ): Promise<T> {
110
+ validateRepoUrl(repoUrl);
111
+ const lock = acquireLock(localPath);
112
+ await lock.promise;
113
+ try {
114
+ git.env(credentialEnvironment(repoUrl, pat, username));
115
+ // Persist only the clean URL. Authentication is scoped to this URL in the child process environment.
116
+ await git.remote(['set-url', remoteName, repoUrl]);
117
+ return await fn();
118
+ } catch (error) {
119
+ throw redactGitCredentialError(error, pat, username);
120
+ } finally {
121
+ try {
122
+ git.env(gitProcessEnvironment());
123
+ } finally {
124
+ lock.release();
125
+ }
126
+ }
127
+ }
128
+
129
+ function gitProcessEnvironment(): NodeJS.ProcessEnv {
130
+ const env = { ...process.env };
131
+ for (const key of Object.keys(env)) {
132
+ // Strip executable/config overrides and trace settings inherited from the server or test runner.
133
+ if (
134
+ (/^GIT_/i.test(key) && !/^GIT_SSL_CA(INFO|PATH)$/i.test(key)) ||
135
+ /^(EDITOR|PAGER|PREFIX|SSH_ASKPASS)$/i.test(key)
136
+ ) {
137
+ delete env[key];
138
+ }
139
+ }
140
+ return env;
141
+ }
142
+
143
+ export function credentialEnvironment(repoUrl: string, pat: string, username?: string): NodeJS.ProcessEnv {
144
+ validateRepoUrl(repoUrl);
145
+ const authorization = Buffer.from(`${(username || 'oauth2').trim()}:${pat.trim()}`).toString('base64');
146
+ const settings = [
147
+ ['http.extraHeader', ''],
148
+ [`http.${new URL(repoUrl).toString()}.extraHeader`, `Authorization: Basic ${authorization}`],
149
+ ['http.followRedirects', 'false'],
150
+ ['credential.helper', ''],
151
+ ];
152
+ const env: NodeJS.ProcessEnv = {
153
+ ...gitProcessEnvironment(),
154
+ GIT_TERMINAL_PROMPT: '0',
155
+ GIT_CONFIG_COUNT: String(settings.length),
156
+ };
157
+ settings.forEach(([key, value], index) => {
158
+ env[`GIT_CONFIG_KEY_${index}`] = key;
159
+ env[`GIT_CONFIG_VALUE_${index}`] = value;
160
+ });
161
+ return env;
162
+ }
163
+
164
+ function redactGitCredentialError(error: unknown, pat: string, username?: string): Error {
165
+ const message = error instanceof Error ? error.message : String(error);
166
+ const authorization = Buffer.from(`${(username || 'oauth2').trim()}:${pat.trim()}`).toString('base64');
167
+ let safeMessage = message;
168
+ for (const secret of [authorization, pat.trim()]) {
169
+ if (secret) safeMessage = safeMessage.split(secret).join('***');
170
+ }
171
+ return redactError(new Error(safeMessage));
172
+ }
173
+
174
+ function getGitMissingMessage() {
175
+ return `Git executable "${GIT_BINARY}" was not found on the server. Install git in the app/worker container, or set GIT_BINARY_PATH to the absolute git binary path.`;
176
+ }
177
+
178
+ function assertGitAvailable(ctx: Context) {
179
+ if (gitAvailabilityChecked) return;
180
+
181
+ const check = spawnSync(GIT_BINARY, ['--version'], { stdio: 'ignore' });
182
+ if (check.error || check.status !== 0) {
183
+ ctx.throw(503, getGitMissingMessage());
184
+ }
185
+ gitAvailabilityChecked = true;
186
+ }
187
+
188
+ function isMissingGitError(error: unknown) {
189
+ const message = error instanceof Error ? error.message : String(error);
190
+ return (error as NodeJS.ErrnoException)?.code === 'ENOENT' || /spawn .*git.*ENOENT/i.test(message);
191
+ }
192
+
193
+ export function createGit(baseDir?: string): SimpleGit {
194
+ // Only plugin-generated environment config and the empty credential helper reset are permitted.
195
+ // All config keys and values come from credentialEnvironment, never from request parameters.
196
+ return simpleGit({
197
+ baseDir,
198
+ binary: GIT_BINARY,
199
+ unsafe: { allowUnsafeConfigEnvCount: true, allowUnsafeCredentialHelper: true },
200
+ }).env(gitProcessEnvironment());
201
+ }
202
+
203
+ export function getGitBinaryPath(): string {
204
+ return GIT_BINARY;
205
+ }
206
+
207
+ function getGit(ctx: Context, localPath: string): SimpleGit {
208
+ if (!fs.existsSync(localPath)) {
209
+ ctx.throw(400, 'Repository directory does not exist. Please clone the repository first.');
210
+ }
211
+ assertGitAvailable(ctx);
212
+ return createGit(localPath);
213
+ }
214
+
215
+ export async function getRepo(ctx: Context) {
216
+ const { repositoryId } = getGitActionParams(ctx);
217
+ const repo = await ctx.db.getRepository('gitRepositories').findOne({
218
+ filterByTk: repositoryId,
219
+ });
220
+ if (!repo) {
221
+ ctx.throw(404, 'Repository not found');
222
+ }
223
+ return repo;
224
+ }
225
+
226
+ // Resolve existing ancestors too, so junctions and symlinks cannot escape through a new clone destination.
227
+ function canonicalPath(value: string): string {
228
+ try {
229
+ return fs.realpathSync.native(value);
230
+ } catch (error) {
231
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
232
+ // A dangling link must not be treated as an ordinary missing directory.
233
+ try {
234
+ if (fs.lstatSync(value).isSymbolicLink()) throw new Error('Invalid local path');
235
+ } catch (statError) {
236
+ if ((statError as NodeJS.ErrnoException).code !== 'ENOENT') throw statError;
237
+ }
238
+ const parent = path.dirname(value);
239
+ if (parent === value) throw error;
240
+ return path.join(canonicalPath(parent), path.basename(value));
241
+ }
242
+ }
243
+
244
+ export function validateLocalPath(localPath: string): string {
245
+ const basePath = path.resolve(process.env.GIT_REPOS_BASE_PATH || path.join(process.cwd(), 'storage', 'git-repos'));
246
+ const resolved = path.resolve(basePath, localPath);
247
+ const base = canonicalPath(basePath);
248
+ const candidate = canonicalPath(resolved);
249
+ for (const [root, target] of [
250
+ [basePath, resolved],
251
+ [base, candidate],
252
+ ]) {
253
+ const relative = path.relative(root, target);
254
+ if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
255
+ throw new Error('Invalid local path: path traversal detected or path is outside the allowed base directory');
256
+ }
257
+ }
258
+ return candidate;
259
+ }
260
+
261
+ export async function clone(ctx: Context, next: () => Promise<void>) {
262
+ const repo = await getRepo(ctx);
263
+ const localPath = validateLocalPath(repo.get('localPath'));
264
+ const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
265
+ const defaultBranch = ((repo.get('defaultBranch') as string) || 'main').trim() || 'main';
266
+
267
+ const account = await getRepoAccount(ctx.db, repo);
268
+ if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
269
+ const { pat, username } = account;
270
+
271
+ validateRepoUrl(repoUrl);
272
+ // Prevent argument-injection through `defaultBranch` (e.g. `--upload-pack=...`)
273
+ validateBranch(defaultBranch);
274
+
275
+ // Check if directory already exists
276
+ if (fs.existsSync(localPath)) {
277
+ ctx.throw(400, 'Directory already exists. Remove it before cloning again.');
278
+ }
279
+
280
+ if (!fs.existsSync(path.dirname(localPath))) {
281
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
282
+ }
283
+
284
+ assertGitAvailable(ctx);
285
+ try {
286
+ await createGit()
287
+ .env(credentialEnvironment(repoUrl, pat, username))
288
+ .clone(repoUrl, localPath, ['--branch', defaultBranch]);
289
+ await ctx.db.getRepository('gitRepositories').update({
290
+ filterByTk: repo.get('id'),
291
+ values: { status: 'connected' },
292
+ });
293
+ ctx.body = { success: true, message: 'Repository cloned successfully' };
294
+ } catch (err) {
295
+ await ctx.db.getRepository('gitRepositories').update({
296
+ filterByTk: repo.get('id'),
297
+ values: { status: 'error' },
298
+ });
299
+ // Redact embedded PAT before the error reaches the client / log
300
+ if (isMissingGitError(err)) {
301
+ ctx.throw(503, getGitMissingMessage());
302
+ }
303
+ throw redactGitCredentialError(err, pat, username);
304
+ }
305
+ await next();
306
+ }
307
+
308
+ export async function pull(ctx: Context, next: () => Promise<void>) {
309
+ const repo = await getRepo(ctx);
310
+ const localPath = validateLocalPath(repo.get('localPath'));
311
+ const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
312
+
313
+ const account = await getRepoAccount(ctx.db, repo);
314
+ if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
315
+ const { pat, username } = account;
316
+
317
+ const git = getGit(ctx, localPath);
318
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.pull(), username);
319
+
320
+ ctx.body = { success: true, data: result };
321
+ await next();
322
+ }
323
+
324
+ export async function push(ctx: Context, next: () => Promise<void>) {
325
+ const repo = await getRepo(ctx);
326
+ const localPath = validateLocalPath(repo.get('localPath'));
327
+ const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
328
+
329
+ const account = await getRepoAccount(ctx.db, repo);
330
+ if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
331
+ const { pat, username } = account;
332
+
333
+ const git = getGit(ctx, localPath);
334
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.push(), username);
335
+
336
+ ctx.body = { success: true, data: result };
337
+ await next();
338
+ }
339
+
340
+ export async function fetch(ctx: Context, next: () => Promise<void>) {
341
+ const repo = await getRepo(ctx);
342
+ const localPath = validateLocalPath(repo.get('localPath'));
343
+ const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
344
+
345
+ const account = await getRepoAccount(ctx.db, repo);
346
+ if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
347
+ const { pat, username } = account;
348
+
349
+ const git = getGit(ctx, localPath);
350
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.fetch(), username);
351
+
352
+ ctx.body = { success: true, data: result };
353
+ await next();
354
+ }
355
+
356
+ export async function diff(ctx: Context, next: () => Promise<void>) {
357
+ const repo = await getRepo(ctx);
358
+ const localPath = validateLocalPath(repo.get('localPath'));
359
+ const { file, commitHash, compareHash } = getGitActionParams(ctx);
360
+
361
+ const git = getGit(ctx, localPath);
362
+ const args: string[] = [];
363
+ if (commitHash && compareHash) {
364
+ args.push(validateRef(commitHash), validateRef(compareHash));
365
+ } else if (commitHash) {
366
+ args.push(validateRef(commitHash) + '^', validateRef(commitHash));
367
+ }
368
+ if (file) {
369
+ if (file.includes('..')) ctx.throw(400, 'Invalid file path');
370
+ args.push('--', file);
371
+ }
372
+
373
+ const result = await git.diff(args);
374
+ ctx.body = { success: true, data: result };
375
+ await next();
376
+ }
377
+
378
+ export async function status(ctx: Context, next: () => Promise<void>) {
379
+ const repo = await getRepo(ctx);
380
+ const localPath = validateLocalPath(repo.get('localPath'));
381
+ const result = await getGit(ctx, localPath).status();
382
+ ctx.body = { success: true, data: result };
383
+ await next();
384
+ }
385
+
386
+ export async function log(ctx: Context, next: () => Promise<void>) {
387
+ const repo = await getRepo(ctx);
388
+ const localPath = validateLocalPath(repo.get('localPath'));
389
+ const { maxCount = 50, file } = getGitActionParams(ctx);
390
+
391
+ const parsed = Number.parseInt(String(maxCount), 10);
392
+ const options: Record<string, any> = { maxCount: Math.min(Math.max(parsed || 50, 1), 500) };
393
+ if (file) {
394
+ if (file.includes('..')) ctx.throw(400, 'Invalid file path');
395
+ options.file = file;
396
+ }
397
+
398
+ const result = await getGit(ctx, localPath).log(options);
399
+ ctx.body = { success: true, data: result };
400
+ await next();
401
+ }
402
+
403
+ export async function branches(ctx: Context, next: () => Promise<void>) {
404
+ const repo = await getRepo(ctx);
405
+ const localPath = validateLocalPath(repo.get('localPath'));
406
+ const result = await getGit(ctx, localPath).branch();
407
+ ctx.body = { success: true, data: result };
408
+ await next();
409
+ }
410
+
411
+ export async function checkout(ctx: Context, next: () => Promise<void>) {
412
+ const repo = await getRepo(ctx);
413
+ const localPath = validateLocalPath(repo.get('localPath'));
414
+ const { branch } = getGitActionParams(ctx);
415
+ if (!branch) ctx.throw(400, 'branch is required');
416
+ validateBranch(branch);
417
+ await getGit(ctx, localPath).checkout(branch);
418
+ ctx.body = { success: true, message: `Switched to branch ${branch}` };
419
+ await next();
420
+ }
421
+
422
+ export async function fileTree(ctx: Context, next: () => Promise<void>) {
423
+ const repo = await getRepo(ctx);
424
+ const localPath = validateLocalPath(repo.get('localPath'));
425
+ const { ref = 'HEAD', treePath = '', recursive } = getGitActionParams(ctx);
426
+
427
+ const git = getGit(ctx, localPath);
428
+ validateRef(ref);
429
+ if (treePath && treePath.includes('..')) {
430
+ ctx.throw(400, 'Invalid tree path');
431
+ }
432
+
433
+ const detailArgs = ['ls-tree', '-l'];
434
+ if (recursive === true || recursive === 'true') detailArgs.push('-r');
435
+ detailArgs.push(ref);
436
+ if (treePath) detailArgs.push(treePath + '/');
437
+ const detailedResult = await git.raw(detailArgs);
438
+ const items = detailedResult
439
+ .trim()
440
+ .split('\n')
441
+ .filter(Boolean)
442
+ .map((line) => {
443
+ // format: <mode> <type> <hash> <size>\t<name>
444
+ const match = line.match(/^(\d+)\s+(blob|tree)\s+([a-f0-9]+)\s+(-|\d+)\t(.+)$/);
445
+ if (!match) return null;
446
+ const fullPath = match[5];
447
+ // Extract just the filename from the full path when using treePath prefix
448
+ const parts = fullPath.split('/');
449
+ const name = fullPath.includes('/') ? parts[parts.length - 1] : fullPath;
450
+ return {
451
+ mode: match[1],
452
+ type: match[2] as 'blob' | 'tree',
453
+ hash: match[3],
454
+ size: match[4] === '-' ? 0 : parseInt(match[4], 10),
455
+ name,
456
+ path: fullPath,
457
+ };
458
+ })
459
+ .filter((item): item is NonNullable<typeof item> => item !== null);
460
+
461
+ // Sort: directories first, then files, both alphabetical
462
+ items.sort((a, b) => {
463
+ if (a.type !== b.type) return a.type === 'tree' ? -1 : 1;
464
+ return a.name.localeCompare(b.name);
465
+ });
466
+
467
+ ctx.body = { success: true, data: items };
468
+ await next();
469
+ }
470
+
471
+ export async function fileContent(ctx: Context, next: () => Promise<void>) {
472
+ const repo = await getRepo(ctx);
473
+ const localPath = validateLocalPath(repo.get('localPath'));
474
+ const { ref = 'HEAD', filePath } = getGitActionParams(ctx);
475
+
476
+ if (!filePath) {
477
+ ctx.throw(400, 'filePath is required');
478
+ }
479
+ if (filePath.includes('..')) {
480
+ ctx.throw(400, 'Invalid file path');
481
+ }
482
+
483
+ validateRef(ref);
484
+ const git = getGit(ctx, localPath);
485
+ const content = await git.show([`${ref}:${filePath}`]);
486
+ ctx.body = { success: true, data: { content, filePath, ref } };
487
+ await next();
488
+ }
489
+
490
+ export async function commitDetail(ctx: Context, next: () => Promise<void>) {
491
+ const repo = await getRepo(ctx);
492
+ const localPath = validateLocalPath(repo.get('localPath'));
493
+ const { commitHash } = getGitActionParams(ctx);
494
+
495
+ if (!commitHash) {
496
+ ctx.throw(400, 'commitHash is required');
497
+ }
498
+
499
+ const git = getGit(ctx, localPath);
500
+ validateRef(commitHash);
501
+
502
+ // Use %x00 in format string to tell git to output null bytes, avoiding null bytes in args
503
+ const DELIM_ARG = '%x00';
504
+ const DELIM_OUT = '\x00';
505
+ const format = `%H${DELIM_ARG}%an${DELIM_ARG}%ae${DELIM_ARG}%aI${DELIM_ARG}%s${DELIM_ARG}%b`;
506
+
507
+ // Run show + diff in parallel for better performance
508
+ const [show, diffResult] = await Promise.all([
509
+ git.show([commitHash, '--stat', `--format=${format}`]),
510
+ git.diff([`${commitHash}^`, commitHash, '--name-status']).catch(() =>
511
+ // Root commit has no parent — use diff-tree --root instead
512
+ git.raw(['diff-tree', '--root', '--name-status', '-r', commitHash]),
513
+ ),
514
+ ]);
515
+
516
+ const parts = show.split(DELIM_OUT);
517
+ const files = diffResult
518
+ .trim()
519
+ .split('\n')
520
+ .filter(Boolean)
521
+ .map((line) => {
522
+ const [statusCode, ...fileParts] = line.split('\t');
523
+ return { status: statusCode, file: fileParts.join('\t') };
524
+ });
525
+
526
+ ctx.body = {
527
+ success: true,
528
+ data: {
529
+ hash: parts[0] || '',
530
+ author: parts[1] || '',
531
+ email: parts[2] || '',
532
+ date: parts[3] || '',
533
+ subject: parts[4] || '',
534
+ body: (parts[5] || '').split('\n\n')[0].trim(), // body before --stat output
535
+ files,
536
+ raw: show,
537
+ },
538
+ };
539
+ await next();
540
+ }