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
@@ -2,6 +2,7 @@
2
2
 
3
3
  import simpleGit, { SimpleGit } from 'simple-git';
4
4
  import { Context } from '@nocobase/actions';
5
+ import { createHash } from 'crypto';
5
6
  import * as path from 'path';
6
7
  import * as fs from 'fs';
7
8
  import { spawn, spawnSync } from 'child_process';
@@ -9,15 +10,26 @@ import { getEffectiveActionParams } from '../repository-access';
9
10
  import { redactError } from '../utils/redact';
10
11
  import { getRepoAccount } from '../utils/get-repo-account';
11
12
  import { assertUrlHasNoUserInfo } from '../utils/url-security';
13
+ import {
14
+ dispatchClusterGitInstall,
15
+ readClusterGitStatus,
16
+ type ClusterGitApp,
17
+ type ClusterGitStatus,
18
+ } from '../utils/cluster-git';
12
19
 
13
20
  // Disallow leading `-` to prevent argument-injection (e.g. `--upload-pack=...`)
14
21
  // when refs are passed as positional args to git.
15
22
  const REF_PATTERN = /^(?!-)[a-zA-Z0-9._/-]+$/;
23
+ const FALLBACK_GIT_PATHS = ['git', '/usr/bin/git', '/usr/local/bin/git', '/bin/git'];
24
+ const REPO_LOCK_TTL_MS = 5 * 60 * 1000;
16
25
 
17
- // Per-repo mutex to prevent PAT race conditions in withAuth
26
+ export interface RepoLockManager {
27
+ runExclusive<T>(key: string, fn: () => Promise<T>, ttl?: number): Promise<T>;
28
+ }
29
+
30
+ // Per-repo in-process mutex paired with app.lockManager (when available) for HA clusters
18
31
  const repoLocks = new Map<string, Promise<void>>();
19
- const GIT_BINARY = process.env.GIT_BINARY_PATH || process.env.GIT_EXECUTABLE || 'git';
20
- let gitAvailabilityChecked = false;
32
+ let cachedGitBinary: { envValue: string; binary: string } | null = null;
21
33
 
22
34
  interface GitActionParams {
23
35
  repositoryId?: number | string;
@@ -92,34 +104,85 @@ export function validateRepoUrl(repoUrl: string): void {
92
104
  }
93
105
  }
94
106
 
95
- export async function withAuth<T>(
96
- git: ReturnType<typeof simpleGit>,
107
+ export async function withRepoLock<T>(
97
108
  localPath: string,
109
+ fn: () => Promise<T>,
110
+ lockManager?: RepoLockManager,
111
+ ): Promise<T> {
112
+ const runLocal = async () => {
113
+ const lock = acquireLock(localPath);
114
+ await lock.promise;
115
+ try {
116
+ return await fn();
117
+ } finally {
118
+ lock.release();
119
+ }
120
+ };
121
+ if (lockManager?.runExclusive) {
122
+ const lockKey = `git-repo:${createHash('sha256').update(localPath).digest('hex')}`;
123
+ return lockManager.runExclusive(lockKey, runLocal, REPO_LOCK_TTL_MS);
124
+ }
125
+ return runLocal();
126
+ }
127
+
128
+ export function validateRepoRelativePath(rawPath: string, label = 'file path'): string {
129
+ if (rawPath.includes('\0')) {
130
+ throw new Error(`Invalid ${label}`);
131
+ }
132
+ const normalized = rawPath.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
133
+ if (!normalized || /^[a-zA-Z]:\//.test(normalized)) {
134
+ throw new Error(`Invalid ${label}`);
135
+ }
136
+ if (normalized.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
137
+ throw new Error(`Invalid ${label}`);
138
+ }
139
+ return normalized;
140
+ }
141
+
142
+ async function runAuthenticatedGitUnlocked<T>(
143
+ git: ReturnType<typeof simpleGit>,
98
144
  repoUrl: string,
99
145
  pat: string,
100
146
  fn: () => Promise<T>,
101
147
  username?: string,
102
148
  remoteName = 'origin',
103
149
  ): Promise<T> {
104
- validateRepoUrl(repoUrl);
105
- const lock = acquireLock(localPath);
106
- await lock.promise;
107
150
  try {
108
151
  git.env(credentialEnvironment(repoUrl, pat, username));
109
- // Persist only the clean URL. Authentication is scoped to this URL in the child process environment.
110
- await git.remote(['set-url', remoteName, repoUrl]);
152
+ // Persist only the clean URL when it differs from .git/config to avoid unnecessary lock contention across HA nodes.
153
+ const currentUrl =
154
+ typeof git.raw === 'function'
155
+ ? (await git.raw(['config', '--get', `remote.${remoteName}.url`]).catch(() => '')).trim()
156
+ : '';
157
+ if (currentUrl !== repoUrl) {
158
+ await git.remote(['set-url', remoteName, repoUrl]);
159
+ }
111
160
  return await fn();
112
161
  } catch (error) {
113
162
  throw redactGitCredentialError(error, pat, username);
114
163
  } finally {
115
- try {
116
- git.env(gitProcessEnvironment());
117
- } finally {
118
- lock.release();
119
- }
164
+ git.env(gitProcessEnvironment());
120
165
  }
121
166
  }
122
167
 
168
+ export async function withAuth<T>(
169
+ git: ReturnType<typeof simpleGit>,
170
+ localPath: string,
171
+ repoUrl: string,
172
+ pat: string,
173
+ fn: () => Promise<T>,
174
+ username?: string,
175
+ remoteName = 'origin',
176
+ lockManager?: RepoLockManager,
177
+ ): Promise<T> {
178
+ validateRepoUrl(repoUrl);
179
+ return withRepoLock(
180
+ localPath,
181
+ () => runAuthenticatedGitUnlocked(git, repoUrl, pat, fn, username, remoteName),
182
+ lockManager,
183
+ );
184
+ }
185
+
123
186
  function gitProcessEnvironment(): NodeJS.ProcessEnv {
124
187
  const env = { ...process.env };
125
188
  for (const key of Object.keys(env)) {
@@ -165,18 +228,94 @@ function redactGitCredentialError(error: unknown, pat: string, username?: string
165
228
  return redactError(new Error(safeMessage));
166
229
  }
167
230
 
168
- function getGitMissingMessage() {
169
- 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.`;
231
+ function configuredGitBinary(): string {
232
+ return (process.env.GIT_BINARY_PATH || process.env.GIT_EXECUTABLE || '').trim();
233
+ }
234
+
235
+ function canExecuteGit(binary: string): boolean {
236
+ if (path.isAbsolute(binary) && !fs.existsSync(binary)) {
237
+ return false;
238
+ }
239
+ const check = spawnSync(binary, ['--version'], { stdio: 'ignore' });
240
+ return !check.error && check.status === 0;
241
+ }
242
+
243
+ export function resolveGitBinary(): string | null {
244
+ const configured = configuredGitBinary();
245
+ if (
246
+ cachedGitBinary &&
247
+ cachedGitBinary.envValue === configured &&
248
+ (!path.isAbsolute(cachedGitBinary.binary) || fs.existsSync(cachedGitBinary.binary)) &&
249
+ canExecuteGit(cachedGitBinary.binary)
250
+ ) {
251
+ return cachedGitBinary.binary;
252
+ }
253
+ cachedGitBinary = null;
254
+
255
+ const candidates = configured ? [configured] : FALLBACK_GIT_PATHS;
256
+ for (const candidate of candidates) {
257
+ if (canExecuteGit(candidate)) {
258
+ cachedGitBinary = { envValue: configured, binary: candidate };
259
+ return candidate;
260
+ }
261
+ }
262
+ return null;
263
+ }
264
+
265
+ export function resetGitBinaryCacheForTests(): void {
266
+ cachedGitBinary = null;
267
+ }
268
+
269
+ export function isGitAvailable(): boolean {
270
+ return resolveGitBinary() !== null;
271
+ }
272
+
273
+ export function getGitMissingMessage(clusterStatus?: ClusterGitStatus): string {
274
+ const binary = configuredGitBinary() || 'git';
275
+ if (clusterStatus?.available && clusterStatus.status === 'running') {
276
+ return `Git executable "${binary}" is currently being installed via Cluster Manager. Please wait a moment and retry.`;
277
+ }
278
+ if (clusterStatus?.available) {
279
+ return `Git executable "${binary}" was not found on the server. Install git via Cluster Manager (Package Installer), or set GIT_BINARY_PATH to the absolute git binary path.`;
280
+ }
281
+ return `Git executable "${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.`;
170
282
  }
171
283
 
172
- function assertGitAvailable(ctx: Context) {
173
- if (gitAvailabilityChecked) return;
284
+ export async function assertGitAvailable(ctx: Context): Promise<string> {
285
+ const binary = resolveGitBinary();
286
+ if (binary) return binary;
174
287
 
175
- const check = spawnSync(GIT_BINARY, ['--version'], { stdio: 'ignore' });
176
- if (check.error || check.status !== 0) {
177
- ctx.throw(503, getGitMissingMessage());
288
+ const app = (ctx as Context & { app?: ClusterGitApp }).app;
289
+ const clusterStatus = await readClusterGitStatus(app).catch(() => undefined);
290
+ if (clusterStatus?.available && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
291
+ dispatchClusterGitInstall(app).catch((err) => {
292
+ app?.log?.warn?.('plugin-git-manager: background git restore via Cluster Manager failed', err);
293
+ });
294
+ const refreshedStatus: ClusterGitStatus = { ...clusterStatus, status: 'running' };
295
+ return ctx.throw(503, getGitMissingMessage(refreshedStatus));
296
+ }
297
+ return ctx.throw(503, getGitMissingMessage(clusterStatus));
298
+ }
299
+
300
+ export async function assertLocalGitReady(localPath: string, app?: ClusterGitApp): Promise<SimpleGit> {
301
+ if (!fs.existsSync(localPath)) {
302
+ const missingDirError = Object.assign(
303
+ new Error('Repository directory does not exist. Please clone the repository first.'),
304
+ { status: 400 },
305
+ );
306
+ throw missingDirError;
307
+ }
308
+ const binary = resolveGitBinary();
309
+ if (!binary) {
310
+ const clusterStatus = await readClusterGitStatus(app).catch(() => undefined);
311
+ if (clusterStatus?.available && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
312
+ dispatchClusterGitInstall(app).catch((err) => {
313
+ app?.log?.warn?.('plugin-git-manager: background git restore via Cluster Manager failed', err);
314
+ });
315
+ }
316
+ throw Object.assign(new Error(getGitMissingMessage(clusterStatus)), { status: 503 });
178
317
  }
179
- gitAvailabilityChecked = true;
318
+ return createGit(localPath);
180
319
  }
181
320
 
182
321
  function isMissingGitError(error: unknown) {
@@ -189,23 +328,65 @@ export function createGit(baseDir?: string): SimpleGit {
189
328
  // All config keys and values come from credentialEnvironment, never from request parameters.
190
329
  return simpleGit({
191
330
  baseDir,
192
- binary: GIT_BINARY,
331
+ binary: getGitBinaryPath(),
193
332
  unsafe: { allowUnsafeConfigEnvCount: true, allowUnsafeCredentialHelper: true },
194
333
  }).env(gitProcessEnvironment());
195
334
  }
196
335
 
197
336
  export function getGitBinaryPath(): string {
198
- return GIT_BINARY;
337
+ return resolveGitBinary() || configuredGitBinary() || 'git';
199
338
  }
200
339
 
201
- function getGit(ctx: Context, localPath: string): SimpleGit {
340
+ export async function getGit(ctx: Context, localPath: string): Promise<SimpleGit> {
202
341
  if (!fs.existsSync(localPath)) {
203
342
  ctx.throw(400, 'Repository directory does not exist. Please clone the repository first.');
204
343
  }
205
- assertGitAvailable(ctx);
344
+ await assertGitAvailable(ctx);
206
345
  return createGit(localPath);
207
346
  }
208
347
 
348
+ export async function runtimeStatus(ctx: Context, next: () => Promise<void>) {
349
+ const binary = resolveGitBinary();
350
+ const app = (ctx as Context & { app?: ClusterGitApp }).app;
351
+ const clusterStatus = await readClusterGitStatus(app);
352
+ if (!binary && clusterStatus.available && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
353
+ const restore = await dispatchClusterGitInstall(app).catch(() => ({ dispatched: false }));
354
+ if (restore.dispatched) {
355
+ clusterStatus.status = 'running';
356
+ }
357
+ }
358
+ ctx.body = {
359
+ success: true,
360
+ data: {
361
+ gitAvailable: binary !== null,
362
+ gitBinary: binary || configuredGitBinary() || 'git',
363
+ clusterManager: {
364
+ available: clusterStatus.available,
365
+ gitConfigured: clusterStatus.gitConfigured,
366
+ status: clusterStatus.status,
367
+ progressPercent: clusterStatus.progressPercent,
368
+ },
369
+ },
370
+ };
371
+ await next();
372
+ }
373
+
374
+ export async function installGit(ctx: Context, next: () => Promise<void>) {
375
+ const binary = resolveGitBinary();
376
+ if (binary) {
377
+ ctx.body = { success: true, data: { alreadyInstalled: true, gitBinary: binary } };
378
+ await next();
379
+ return;
380
+ }
381
+ const app = (ctx as Context & { app?: ClusterGitApp }).app;
382
+ const result = await dispatchClusterGitInstall(app, { ensureGitInConfig: true });
383
+ if (!result.dispatched && result.reason !== 'Cluster package installation is already running') {
384
+ ctx.throw(400, result.reason || 'Unable to dispatch git installation via Cluster Manager');
385
+ }
386
+ ctx.body = { success: true, data: { dispatched: true } };
387
+ await next();
388
+ }
389
+
209
390
  export async function getRepo(ctx: Context, requestedRepositoryId?: number | string) {
210
391
  const repositoryId = requestedRepositoryId ?? getGitActionParams(ctx).repositoryId;
211
392
  const repo = await ctx.db.getRepository('gitRepositories').findOne({
@@ -265,37 +446,60 @@ export async function clone(ctx: Context, next: () => Promise<void>) {
265
446
  validateRepoUrl(repoUrl);
266
447
  // Prevent argument-injection through `defaultBranch` (e.g. `--upload-pack=...`)
267
448
  validateBranch(defaultBranch);
449
+ await assertGitAvailable(ctx);
450
+
451
+ const app = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app;
452
+ await withRepoLock(
453
+ localPath,
454
+ async () => {
455
+ if (fs.existsSync(localPath)) {
456
+ const entries = fs.readdirSync(localPath);
457
+ if (entries.length > 0) {
458
+ if (fs.existsSync(path.join(localPath, '.git'))) {
459
+ const existingGit = createGit(localPath);
460
+ const existingOrigin = (
461
+ await existingGit.raw(['config', '--get', 'remote.origin.url']).catch(() => '')
462
+ ).trim();
463
+ if (existingOrigin === repoUrl) {
464
+ await runAuthenticatedGitUnlocked(existingGit, repoUrl, pat, () => existingGit.fetch(), username);
465
+ await ctx.db.getRepository('gitRepositories').update({
466
+ filterByTk: repo.get('id'),
467
+ values: { status: 'connected' },
468
+ });
469
+ ctx.body = { success: true, message: 'Repository reconnected successfully' };
470
+ return;
471
+ }
472
+ }
473
+ ctx.throw(400, 'Directory already exists. Remove it before cloning again.');
474
+ }
475
+ } else if (!fs.existsSync(path.dirname(localPath))) {
476
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
477
+ }
268
478
 
269
- // Check if directory already exists
270
- if (fs.existsSync(localPath)) {
271
- ctx.throw(400, 'Directory already exists. Remove it before cloning again.');
272
- }
273
-
274
- if (!fs.existsSync(path.dirname(localPath))) {
275
- fs.mkdirSync(path.dirname(localPath), { recursive: true });
276
- }
277
-
278
- assertGitAvailable(ctx);
279
- try {
280
- await createGit()
281
- .env(credentialEnvironment(repoUrl, pat, username))
282
- .clone(repoUrl, localPath, ['--branch', defaultBranch]);
283
- await ctx.db.getRepository('gitRepositories').update({
284
- filterByTk: repo.get('id'),
285
- values: { status: 'connected' },
286
- });
287
- ctx.body = { success: true, message: 'Repository cloned successfully' };
288
- } catch (err) {
289
- await ctx.db.getRepository('gitRepositories').update({
290
- filterByTk: repo.get('id'),
291
- values: { status: 'error' },
292
- });
293
- // Redact embedded PAT before the error reaches the client / log
294
- if (isMissingGitError(err)) {
295
- ctx.throw(503, getGitMissingMessage());
296
- }
297
- throw redactGitCredentialError(err, pat, username);
298
- }
479
+ try {
480
+ await createGit()
481
+ .env(credentialEnvironment(repoUrl, pat, username))
482
+ .clone(repoUrl, localPath, ['--branch', defaultBranch]);
483
+ await ctx.db.getRepository('gitRepositories').update({
484
+ filterByTk: repo.get('id'),
485
+ values: { status: 'connected' },
486
+ });
487
+ ctx.body = { success: true, message: 'Repository cloned successfully' };
488
+ } catch (err) {
489
+ await ctx.db.getRepository('gitRepositories').update({
490
+ filterByTk: repo.get('id'),
491
+ values: { status: 'error' },
492
+ });
493
+ // Redact embedded PAT before the error reaches the client / log
494
+ if (isMissingGitError(err) && !isGitAvailable()) {
495
+ const clusterStatus = await readClusterGitStatus(app as ClusterGitApp).catch(() => undefined);
496
+ ctx.throw(503, getGitMissingMessage(clusterStatus));
497
+ }
498
+ throw redactGitCredentialError(err, pat, username);
499
+ }
500
+ },
501
+ app?.lockManager,
502
+ );
299
503
  await next();
300
504
  }
301
505
 
@@ -308,8 +512,9 @@ export async function pull(ctx: Context, next: () => Promise<void>) {
308
512
  if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
309
513
  const { pat, username } = account;
310
514
 
311
- const git = getGit(ctx, localPath);
312
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.pull(), username);
515
+ const git = await getGit(ctx, localPath);
516
+ const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
517
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.pull(), username, 'origin', lockManager);
313
518
 
314
519
  ctx.body = { success: true, data: result };
315
520
  await next();
@@ -324,8 +529,9 @@ export async function push(ctx: Context, next: () => Promise<void>) {
324
529
  if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
325
530
  const { pat, username } = account;
326
531
 
327
- const git = getGit(ctx, localPath);
328
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.push(), username);
532
+ const git = await getGit(ctx, localPath);
533
+ const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
534
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.push(), username, 'origin', lockManager);
329
535
 
330
536
  ctx.body = { success: true, data: result };
331
537
  await next();
@@ -340,8 +546,9 @@ export async function fetch(ctx: Context, next: () => Promise<void>) {
340
546
  if (!account) return ctx.throw(400, 'Repository has no Git account configured. Please assign a Git account first.');
341
547
  const { pat, username } = account;
342
548
 
343
- const git = getGit(ctx, localPath);
344
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.fetch(), username);
549
+ const git = await getGit(ctx, localPath);
550
+ const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
551
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.fetch(), username, 'origin', lockManager);
345
552
 
346
553
  ctx.body = { success: true, data: result };
347
554
  await next();
@@ -352,7 +559,7 @@ export async function diff(ctx: Context, next: () => Promise<void>) {
352
559
  const localPath = validateLocalPath(repo.get('localPath'));
353
560
  const { file, commitHash, compareHash } = getGitActionParams(ctx);
354
561
 
355
- const git = getGit(ctx, localPath);
562
+ const git = await getGit(ctx, localPath);
356
563
  const args: string[] = [];
357
564
  if (commitHash && compareHash) {
358
565
  args.push(validateRef(commitHash), validateRef(compareHash));
@@ -360,8 +567,13 @@ export async function diff(ctx: Context, next: () => Promise<void>) {
360
567
  args.push(validateRef(commitHash) + '^', validateRef(commitHash));
361
568
  }
362
569
  if (file) {
363
- if (file.includes('..')) ctx.throw(400, 'Invalid file path');
364
- args.push('--', file);
570
+ let safeFile = '';
571
+ try {
572
+ safeFile = validateRepoRelativePath(file, 'file path');
573
+ } catch {
574
+ ctx.throw(400, 'Invalid file path');
575
+ }
576
+ args.push('--', safeFile);
365
577
  }
366
578
 
367
579
  const result = await git.diff(args);
@@ -372,7 +584,8 @@ export async function diff(ctx: Context, next: () => Promise<void>) {
372
584
  export async function status(ctx: Context, next: () => Promise<void>) {
373
585
  const repo = await getRepo(ctx);
374
586
  const localPath = validateLocalPath(repo.get('localPath'));
375
- const result = await getGit(ctx, localPath).status();
587
+ const git = await getGit(ctx, localPath);
588
+ const result = await git.status();
376
589
  ctx.body = { success: true, data: result };
377
590
  await next();
378
591
  }
@@ -383,10 +596,14 @@ export async function log(ctx: Context, next: () => Promise<void>) {
383
596
  const { maxCount = 50, file, branch, skip } = getGitActionParams(ctx);
384
597
 
385
598
  const parsed = Number.parseInt(String(maxCount), 10);
386
- const options: { maxCount: number; file?: string } = { maxCount: Math.min(Math.max(parsed || 50, 1), 500) };
599
+ const boundedMaxCount = Math.min(Math.max(parsed || 50, 1), 500);
600
+ let safeFile: string | undefined;
387
601
  if (file) {
388
- if (file.includes('..')) ctx.throw(400, 'Invalid file path');
389
- options.file = file;
602
+ try {
603
+ safeFile = validateRepoRelativePath(file, 'file path');
604
+ } catch {
605
+ ctx.throw(400, 'Invalid file path');
606
+ }
390
607
  }
391
608
 
392
609
  const args: string[] = [];
@@ -398,13 +615,11 @@ export async function log(ctx: Context, next: () => Promise<void>) {
398
615
  }
399
616
  args.push(`--skip=${parsedSkip}`);
400
617
  }
401
- const result = args.length
402
- ? await getGit(ctx, localPath).log([
403
- ...args,
404
- `--max-count=${options.maxCount}`,
405
- ...(file ? ['--follow', '--', file] : []),
406
- ])
407
- : await getGit(ctx, localPath).log(options);
618
+ const git = await getGit(ctx, localPath);
619
+ const result =
620
+ args.length || safeFile
621
+ ? await git.log([...args, `--max-count=${boundedMaxCount}`, ...(safeFile ? ['--follow', '--', safeFile] : [])])
622
+ : await git.log({ maxCount: boundedMaxCount });
408
623
  ctx.body = { success: true, data: result };
409
624
  await next();
410
625
  }
@@ -412,7 +627,8 @@ export async function log(ctx: Context, next: () => Promise<void>) {
412
627
  export async function branches(ctx: Context, next: () => Promise<void>) {
413
628
  const repo = await getRepo(ctx);
414
629
  const localPath = validateLocalPath(repo.get('localPath'));
415
- const result = await getGit(ctx, localPath).branch();
630
+ const git = await getGit(ctx, localPath);
631
+ const result = await git.branch();
416
632
  ctx.body = { success: true, data: result };
417
633
  await next();
418
634
  }
@@ -423,7 +639,9 @@ export async function checkout(ctx: Context, next: () => Promise<void>) {
423
639
  const { branch } = getGitActionParams(ctx);
424
640
  if (!branch) ctx.throw(400, 'branch is required');
425
641
  validateBranch(branch);
426
- await getGit(ctx, localPath).checkout(branch);
642
+ const git = await getGit(ctx, localPath);
643
+ const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
644
+ await withRepoLock(localPath, () => git.checkout(branch), lockManager);
427
645
  ctx.body = { success: true, message: `Switched to branch ${branch}` };
428
646
  await next();
429
647
  }
@@ -433,16 +651,21 @@ export async function fileTree(ctx: Context, next: () => Promise<void>) {
433
651
  const localPath = validateLocalPath(repo.get('localPath'));
434
652
  const { ref = 'HEAD', treePath = '', recursive } = getGitActionParams(ctx);
435
653
 
436
- const git = getGit(ctx, localPath);
654
+ const git = await getGit(ctx, localPath);
437
655
  validateRef(ref);
438
- if (treePath && treePath.includes('..')) {
439
- ctx.throw(400, 'Invalid tree path');
656
+ let safeTreePath = '';
657
+ if (treePath) {
658
+ try {
659
+ safeTreePath = validateRepoRelativePath(treePath, 'tree path');
660
+ } catch {
661
+ ctx.throw(400, 'Invalid tree path');
662
+ }
440
663
  }
441
664
 
442
- const detailArgs = ['ls-tree', '-l'];
665
+ const detailArgs = ['-c', 'core.quotePath=false', 'ls-tree', '-l'];
443
666
  if (recursive === true || recursive === 'true') detailArgs.push('-r');
444
- detailArgs.push(ref);
445
- if (treePath) detailArgs.push(treePath + '/');
667
+ detailArgs.push(ref, '--');
668
+ if (safeTreePath) detailArgs.push(`${safeTreePath}/`);
446
669
  const detailedResult = await git.raw(detailArgs);
447
670
  const items = detailedResult
448
671
  .trim()
@@ -485,14 +708,17 @@ export async function fileContent(ctx: Context, next: () => Promise<void>) {
485
708
  if (!filePath) {
486
709
  ctx.throw(400, 'filePath is required');
487
710
  }
488
- if (filePath.includes('..')) {
711
+ let safeFilePath = '';
712
+ try {
713
+ safeFilePath = validateRepoRelativePath(filePath, 'file path');
714
+ } catch {
489
715
  ctx.throw(400, 'Invalid file path');
490
716
  }
491
717
 
492
718
  validateRef(ref);
493
- const git = getGit(ctx, localPath);
494
- const content = await git.show([`${ref}:${filePath}`]);
495
- ctx.body = { success: true, data: { content, filePath, ref } };
719
+ const git = await getGit(ctx, localPath);
720
+ const content = await git.raw(['-c', 'core.quotePath=false', 'show', `${ref}:${safeFilePath}`]);
721
+ ctx.body = { success: true, data: { content, filePath: safeFilePath, ref } };
496
722
  await next();
497
723
  }
498
724
 
@@ -505,7 +731,7 @@ export async function commitDetail(ctx: Context, next: () => Promise<void>) {
505
731
  ctx.throw(400, 'commitHash is required');
506
732
  }
507
733
 
508
- const git = getGit(ctx, localPath);
734
+ const git = await getGit(ctx, localPath);
509
735
  validateRef(commitHash);
510
736
 
511
737
  // Use %x00 in format string to tell git to output null bytes, avoiding null bytes in args
@@ -550,7 +776,7 @@ export async function commitDetail(ctx: Context, next: () => Promise<void>) {
550
776
 
551
777
  async function readLimitedGitOutput(localPath: string, args: string[], maxBytes: number) {
552
778
  return new Promise<{ text: string; truncated: boolean }>((resolve, reject) => {
553
- const process = spawn(GIT_BINARY, args, {
779
+ const child = spawn(getGitBinaryPath(), args, {
554
780
  cwd: localPath,
555
781
  env: gitProcessEnvironment(),
556
782
  windowsHide: true,
@@ -559,7 +785,7 @@ async function readLimitedGitOutput(localPath: string, args: string[], maxBytes:
559
785
  const chunks: Buffer[] = [];
560
786
  let size = 0;
561
787
  let truncated = false;
562
- process.stdout.on('data', (chunk: Buffer) => {
788
+ child.stdout.on('data', (chunk: Buffer) => {
563
789
  const remaining = maxBytes - size;
564
790
  if (remaining > 0) {
565
791
  const data = chunk.subarray(0, remaining);
@@ -568,11 +794,11 @@ async function readLimitedGitOutput(localPath: string, args: string[], maxBytes:
568
794
  }
569
795
  if (chunk.length > remaining) {
570
796
  truncated = true;
571
- process.kill();
797
+ child.kill();
572
798
  }
573
799
  });
574
- process.on('error', reject);
575
- process.on('close', (code) => {
800
+ child.on('error', reject);
801
+ child.on('close', (code) => {
576
802
  if (code !== 0 && !truncated) {
577
803
  reject(new Error('Unable to read commit diff'));
578
804
  return;
@@ -596,7 +822,7 @@ export async function readChatCommit(
596
822
  if (!/^[a-f\d]{4,64}$/i.test(commitHash)) ctx.throw(400, 'Invalid commit hash');
597
823
  const repo = await getRepo(ctx, repositoryId);
598
824
  const localPath = validateLocalPath(repo.get('localPath'));
599
- const git = getGit(ctx, localPath);
825
+ const git = await getGit(ctx, localPath);
600
826
  const hash = (await git.raw(['rev-parse', '--verify', `${commitHash}^{commit}`])).trim();
601
827
  const [metadata, parentLine] = await Promise.all([
602
828
  git.raw(['show', '-s', '--format=%H%x00%an%x00%aI%x00%s%x00%b', hash]),