plugin-git-manager 1.2.28 → 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 (67) hide show
  1. package/README.md +58 -40
  2. package/dist/client/941.1793e67472872992.js +10 -0
  3. package/dist/client/index.js +1 -1
  4. package/dist/client-v2/941.b0d55429cd053f32.js +10 -0
  5. package/dist/client-v2/index.js +1 -1
  6. package/dist/locale/en-US.json +90 -1
  7. package/dist/locale/vi-VN.json +90 -1
  8. package/dist/locale/zh-CN.json +90 -1
  9. package/dist/node_modules/simple-git/package.json +1 -1
  10. package/dist/node_modules/zod/package.json +1 -1
  11. package/dist/server/actions/review-cutover.js +137 -0
  12. package/dist/server/actions/review.js +132 -43
  13. package/dist/server/actions/role-permissions.js +1 -0
  14. package/dist/server/ai-tools.js +8 -9
  15. package/dist/server/collections/gitCodeReviews.js +10 -0
  16. package/dist/server/collections/gitReviewCutover.js +44 -0
  17. package/dist/server/collections/gitReviewFlows.js +3 -0
  18. package/dist/server/collections/gitReviewInbox.js +51 -0
  19. package/dist/server/collections/gitReviewProjects.js +43 -0
  20. package/dist/server/collections/gitReviewRequests.js +56 -0
  21. package/dist/server/index.js +8 -2
  22. package/dist/server/plugin.js +51 -16
  23. package/dist/server/poller.js +54 -34
  24. package/dist/server/repository-access.js +23 -5
  25. package/dist/server/request-method-policy.js +2 -1
  26. package/dist/server/review-control-access.js +79 -0
  27. package/dist/server/services/legacy-post-service.js +412 -0
  28. package/dist/server/services/review-service.js +1451 -0
  29. package/dist/server/services/review-source.js +325 -0
  30. package/package.json +2 -2
  31. package/src/client/__tests__/CommitHistory.test.tsx +79 -0
  32. package/src/client/__tests__/ReviewHistory.test.tsx +126 -0
  33. package/src/client/__tests__/RunReviewButton.test.tsx +46 -35
  34. package/src/client/__tests__/workflowRoutes.test.ts +65 -0
  35. package/src/client/components/CommitHistory.tsx +61 -6
  36. package/src/client/components/ReviewFlows.tsx +90 -41
  37. package/src/client/components/ReviewHistory.tsx +245 -15
  38. package/src/client/components/RunReviewButton.tsx +12 -136
  39. package/src/client/workflowRoutes.ts +42 -0
  40. package/src/locale/en-US.json +90 -1
  41. package/src/locale/vi-VN.json +90 -1
  42. package/src/locale/zh-CN.json +90 -1
  43. package/src/server/__tests__/repository-access.test.ts +11 -3
  44. package/src/server/__tests__/review-service.integration.test.ts +1263 -0
  45. package/src/server/__tests__/review.test.ts +37 -98
  46. package/src/server/actions/review-cutover.ts +121 -0
  47. package/src/server/actions/review.ts +148 -38
  48. package/src/server/actions/role-permissions.ts +10 -0
  49. package/src/server/ai-tools.ts +23 -8
  50. package/src/server/collections/gitCodeReviews.ts +19 -0
  51. package/src/server/collections/gitReviewCutover.ts +23 -0
  52. package/src/server/collections/gitReviewFlows.ts +12 -0
  53. package/src/server/collections/gitReviewInbox.ts +30 -0
  54. package/src/server/collections/gitReviewProjects.ts +22 -0
  55. package/src/server/collections/gitReviewRequests.ts +35 -0
  56. package/src/server/index.ts +12 -0
  57. package/src/server/plugin.ts +43 -6
  58. package/src/server/poller.ts +54 -40
  59. package/src/server/repository-access.ts +32 -2
  60. package/src/server/request-method-policy.ts +1 -0
  61. package/src/server/review-control-access.ts +71 -0
  62. package/src/server/services/__tests__/review-source.test.ts +226 -0
  63. package/src/server/services/legacy-post-service.ts +550 -0
  64. package/src/server/services/review-service.ts +1899 -0
  65. package/src/server/services/review-source.ts +359 -0
  66. package/dist/client/900.a48beac7e2ebee7d.js +0 -10
  67. package/dist/client-v2/900.e6155002a9c97e7f.js +0 -10
@@ -0,0 +1,359 @@
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 { createHash } from 'crypto';
11
+ import type { Database } from '@nocobase/database';
12
+ import { createGit, validateBranch, validateLocalPath, validateRef } from '../actions/git-actions';
13
+ import { getRepoAccount } from '../utils/get-repo-account';
14
+ import { parseGitLabProject } from '../utils/gitlab-url';
15
+
16
+ type RecordGetter = { get(name: string): unknown };
17
+ type ObjectValue = Record<string, unknown>;
18
+
19
+ export type ReviewTarget = 'mr' | 'commit' | 'branch' | 'folder';
20
+
21
+ export interface PinnedReviewSource {
22
+ projectKey: string;
23
+ repositoryId: number;
24
+ targetType: ReviewTarget;
25
+ mrIid: number | null;
26
+ branch: string | null;
27
+ folderPath: string | null;
28
+ headSha: string;
29
+ baseSha: string | null;
30
+ }
31
+
32
+ function object(value: unknown): ObjectValue {
33
+ return value && typeof value === 'object' && !Array.isArray(value) ? (value as ObjectValue) : {};
34
+ }
35
+
36
+ function text(value: unknown): string | null {
37
+ return typeof value === 'string' && value ? value : null;
38
+ }
39
+
40
+ function sha(value: unknown): string {
41
+ const result = text(value)?.toLowerCase();
42
+ if (!result || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(result)) {
43
+ throw new Error('Unable to resolve an immutable Git commit');
44
+ }
45
+ return result;
46
+ }
47
+
48
+ async function responseJson(url: string, headers: Record<string, string>): Promise<ObjectValue> {
49
+ const response = await fetch(url, { headers, redirect: 'error' });
50
+ if (!response.ok) throw new Error(`Git provider request failed (${response.status})`);
51
+ const size = Number(response.headers.get('content-length') || 0);
52
+ if (size > 4_000_000) throw new Error('Git provider response is too large');
53
+ const body = await response.text();
54
+ if (Buffer.byteLength(body) > 4_000_000) throw new Error('Git provider response is too large');
55
+ return object(JSON.parse(body));
56
+ }
57
+
58
+ async function provider(db: Database, repo: RecordGetter) {
59
+ const repoUrl = String(repo.get('repoUrl') || '');
60
+ const account = await getRepoAccount(db, repo);
61
+ const parsed = parseGitLabProject(repoUrl);
62
+ const isGitHub = new URL(repoUrl).hostname.toLowerCase() === 'github.com';
63
+ if (account?.provider === 'github' && !isGitHub) throw new Error('Unsupported GitHub origin');
64
+ if (!isGitHub && !account?.pat) throw new Error('GitLab account is required');
65
+ const headers: Record<string, string> = { Accept: 'application/json' };
66
+ if (account?.pat)
67
+ headers[isGitHub ? 'Authorization' : 'PRIVATE-TOKEN'] = isGitHub ? `Bearer ${account.pat}` : account.pat;
68
+ const root = isGitHub
69
+ ? `https://api.github.com/repos/${parsed.projectPath}`
70
+ : `${parsed.apiBase}/projects/${parsed.encodedProject}`;
71
+ const project = await responseJson(root, headers);
72
+ const projectId = project.id;
73
+ const canonical = text(isGitHub ? project.html_url : project.web_url);
74
+ if ((typeof projectId !== 'number' && typeof projectId !== 'string') || !canonical) {
75
+ throw new Error('Git provider did not return a canonical project identity');
76
+ }
77
+ const canonicalUrl = new URL(canonical);
78
+ if (canonicalUrl.protocol !== 'https:' || canonicalUrl.username || canonicalUrl.password) {
79
+ throw new Error('Invalid canonical project origin');
80
+ }
81
+ const identity = `${isGitHub ? 'github' : 'gitlab'}:${canonicalUrl.origin.toLowerCase()}:${projectId}`;
82
+ return {
83
+ root,
84
+ headers,
85
+ isGitHub,
86
+ userApi: isGitHub ? 'https://api.github.com/user' : `${parsed.apiBase}/user`,
87
+ projectKey: createHash('sha256').update(identity).digest('hex'),
88
+ pat: account?.pat || '',
89
+ };
90
+ }
91
+
92
+ export async function resolveReviewProjectKey(db: Database, repo: RecordGetter): Promise<string> {
93
+ return (await provider(db, repo)).projectKey;
94
+ }
95
+
96
+ async function validateCheckoutProject(db: Database, repo: RecordGetter, expectedProjectKey: string): Promise<void> {
97
+ const git = createGit(validateLocalPath(String(repo.get('localPath') || '')));
98
+ let origin: string;
99
+ try {
100
+ origin = (await git.raw(['remote', 'get-url', 'origin'])).trim();
101
+ const remote = new URL(origin);
102
+ if (remote.protocol !== 'https:' || remote.username || remote.password) throw new Error('Invalid origin');
103
+ } catch {
104
+ throw new Error('Checkout origin is missing or unsupported');
105
+ }
106
+ const checkout = { get: (name: string) => (name === 'repoUrl' ? origin : repo.get(name)) };
107
+ let projectKey: string;
108
+ try {
109
+ projectKey = (await provider(db, checkout)).projectKey;
110
+ } catch {
111
+ throw new Error('Checkout origin project could not be verified');
112
+ }
113
+ if (projectKey !== expectedProjectKey) throw new Error('Checkout origin does not match the configured project');
114
+ }
115
+
116
+ function safeFolder(value: string): string {
117
+ const folder = value.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
118
+ if (folder.split('/').some((part) => part === '..' || part === '.') || value.includes('\0')) {
119
+ throw new Error('Invalid folder path');
120
+ }
121
+ return folder;
122
+ }
123
+
124
+ export async function resolveReviewSource(
125
+ db: Database,
126
+ repo: RecordGetter,
127
+ input: {
128
+ targetType: ReviewTarget;
129
+ mrIid?: number | null;
130
+ commitSha?: string | null;
131
+ branch?: string | null;
132
+ folderPath?: string | null;
133
+ headSha?: string | null;
134
+ },
135
+ ): Promise<PinnedReviewSource> {
136
+ const remote = await provider(db, repo);
137
+ let headSha: string;
138
+ let baseSha: string | null = null;
139
+ let branch = input.branch || null;
140
+ const folderPath = input.targetType === 'folder' ? safeFolder(input.folderPath || '') : null;
141
+ if (input.targetType === 'mr') {
142
+ if (!input.mrIid || !Number.isSafeInteger(input.mrIid) || input.mrIid < 1) throw new Error('Invalid merge request');
143
+ const mr = await responseJson(
144
+ `${remote.root}/${remote.isGitHub ? 'pulls' : 'merge_requests'}/${input.mrIid}`,
145
+ remote.headers,
146
+ );
147
+ headSha = sha(remote.isGitHub ? object(mr.head).sha : mr.sha || object(mr.diff_refs).head_sha);
148
+ baseSha = sha(remote.isGitHub ? object(mr.base).sha : object(mr.diff_refs).base_sha);
149
+ branch = text(remote.isGitHub ? object(mr.head).ref : mr.source_branch);
150
+ if (input.headSha && sha(input.headSha) !== headSha)
151
+ throw new Error('Merge request head changed before review admission');
152
+ } else {
153
+ await validateCheckoutProject(db, repo, remote.projectKey);
154
+ const git = createGit(validateLocalPath(String(repo.get('localPath') || '')));
155
+ const ref = input.headSha || (input.targetType === 'commit' ? input.commitSha : input.branch || 'HEAD');
156
+ if (!ref) throw new Error('Git ref is required');
157
+ validateRef(ref);
158
+ headSha = sha((await git.raw(['rev-parse', '--verify', `${ref}^{commit}`])).trim());
159
+ if (input.targetType === 'branch') {
160
+ const base = validateBranch(String(repo.get('defaultBranch') || 'main'));
161
+ const baseCommit = sha((await git.raw(['rev-parse', '--verify', `${base}^{commit}`])).trim());
162
+ baseSha = sha((await git.raw(['merge-base', baseCommit, headSha])).trim());
163
+ }
164
+ }
165
+ return {
166
+ projectKey: remote.projectKey,
167
+ repositoryId: Number(repo.get('id')),
168
+ targetType: input.targetType,
169
+ mrIid: input.targetType === 'mr' ? input.mrIid || null : null,
170
+ branch,
171
+ folderPath,
172
+ headSha,
173
+ baseSha,
174
+ };
175
+ }
176
+
177
+ export async function readPinnedReviewSource(
178
+ db: Database,
179
+ repo: RecordGetter,
180
+ source: PinnedReviewSource,
181
+ ): Promise<string> {
182
+ const remote = await provider(db, repo);
183
+ if (remote.projectKey !== source.projectKey) throw new Error('Repository project changed after admission');
184
+ let content = '';
185
+ if (source.targetType === 'mr') {
186
+ const base = sha(source.baseSha);
187
+ const head = sha(source.headSha);
188
+ if (remote.isGitHub) {
189
+ const comparison = await responseJson(`${remote.root}/compare/${base}...${head}?per_page=100`, remote.headers);
190
+ const files = comparison.files;
191
+ if (!Array.isArray(files) || files.length >= 300) throw new Error('GitHub comparison is incomplete');
192
+ content = files
193
+ .map((item) => {
194
+ const file = object(item);
195
+ if (typeof file.filename !== 'string' || typeof file.patch !== 'string')
196
+ throw new Error('GitHub comparison contains an unavailable patch');
197
+ if (/[\r\n]/.test(file.filename)) throw new Error('GitHub comparison has an unsupported filename');
198
+ return `--- a/${file.filename}\n+++ b/${file.filename}\n${file.patch}`;
199
+ })
200
+ .join('\n');
201
+ } else {
202
+ const comparison = await responseJson(
203
+ `${remote.root}/repository/compare?from=${base}&to=${head}`,
204
+ remote.headers,
205
+ );
206
+ if (comparison.compare_timeout || comparison.overflow || !Array.isArray(comparison.diffs)) {
207
+ throw new Error('GitLab comparison is incomplete');
208
+ }
209
+ content = comparison.diffs
210
+ .map((item) => {
211
+ const file = object(item);
212
+ if (file.too_large || file.collapsed || typeof file.diff !== 'string')
213
+ throw new Error('GitLab comparison contains an unavailable patch');
214
+ const oldPath = String(file.old_path || '');
215
+ const newPath = String(file.new_path || '');
216
+ if (/[\r\n]/.test(oldPath + newPath)) throw new Error('GitLab comparison has an unsupported filename');
217
+ return `--- a/${oldPath}\n+++ b/${newPath}\n${file.diff}`;
218
+ })
219
+ .join('\n');
220
+ }
221
+ } else {
222
+ await validateCheckoutProject(db, repo, source.projectKey);
223
+ const git = createGit(validateLocalPath(String(repo.get('localPath') || '')));
224
+ const head = sha(source.headSha);
225
+ if (source.targetType === 'folder') {
226
+ const folder = safeFolder(source.folderPath || '');
227
+ const tree = await git.raw(['ls-tree', '-r', '--name-only', '-z', head, '--', folder || '.']);
228
+ const paths = tree.split('\0').filter(Boolean);
229
+ if (paths.length > 200) throw new Error('Folder contains too many files to review safely');
230
+ for (const path of paths) {
231
+ if (/[\r\n]/.test(path)) throw new Error('Folder contains an unsupported filename');
232
+ const file = await git.raw(['show', `${head}:${path}`]);
233
+ if (file.includes('\0')) throw new Error('Folder contains an unsupported binary file');
234
+ const lines = file.split('\n');
235
+ content += `\n--- /dev/null\n+++ b/${path}\n@@ -0,0 +1,${lines.length} @@\n${lines
236
+ .map((line) => `+${line}`)
237
+ .join('\n')}`;
238
+ if (Buffer.byteLength(content) > 200_000) throw new Error('Review context exceeds the size limit');
239
+ }
240
+ } else if (source.targetType === 'commit') {
241
+ content = await git.raw(['show', '--format=', '--no-ext-diff', '--no-color', head]);
242
+ } else {
243
+ content = await git.raw(['diff', '--no-ext-diff', '--no-color', sha(source.baseSha), head, '--']);
244
+ }
245
+ }
246
+ if (Buffer.byteLength(content) > 200_000) throw new Error('Review context exceeds the size limit');
247
+ return remote.pat ? content.split(remote.pat).join('[REDACTED]') : content;
248
+ }
249
+
250
+ export async function assertCurrentMrHead(db: Database, repo: RecordGetter, source: PinnedReviewSource): Promise<void> {
251
+ const current = await resolveReviewSource(db, repo, { targetType: 'mr', mrIid: source.mrIid });
252
+ if (current.projectKey !== source.projectKey || current.headSha !== source.headSha) {
253
+ throw new Error('Merge request head changed after review');
254
+ }
255
+ if (!source.baseSha || current.baseSha !== source.baseSha) {
256
+ throw new Error('Merge request base changed after review');
257
+ }
258
+ }
259
+
260
+ export async function findPublishedReview(
261
+ db: Database,
262
+ repo: RecordGetter,
263
+ source: PinnedReviewSource,
264
+ markdown: string,
265
+ marker: string,
266
+ ): Promise<string | null> {
267
+ const result = await findReviewComment(db, repo, source, markdown, marker, false);
268
+ return result?.noteId ?? null;
269
+ }
270
+
271
+ export async function findLegacyPublishedReview(
272
+ db: Database,
273
+ repo: RecordGetter,
274
+ source: PinnedReviewSource,
275
+ markdown: string,
276
+ marker: string,
277
+ ): Promise<{ kind: 'marked' | 'unmarked'; noteId: string } | null> {
278
+ return findReviewComment(db, repo, source, markdown, marker, true);
279
+ }
280
+
281
+ async function findReviewComment(
282
+ db: Database,
283
+ repo: RecordGetter,
284
+ source: PinnedReviewSource,
285
+ markdown: string,
286
+ marker: string,
287
+ includeUnmarked: boolean,
288
+ ): Promise<{ kind: 'marked' | 'unmarked'; noteId: string } | null> {
289
+ if (!source.mrIid) throw new Error('Only merge request reviews can be published');
290
+ const remote = await provider(db, repo);
291
+ if (!remote.pat || remote.projectKey !== source.projectKey)
292
+ throw new Error('Repository credentials or project changed');
293
+ const authenticated = await responseJson(remote.userApi, remote.headers);
294
+ if (typeof authenticated.id !== 'number' && typeof authenticated.id !== 'string')
295
+ throw new Error('Unable to verify Git account identity');
296
+ const expectedBody = `${markdown}\n\n${marker}`;
297
+ const url = `${remote.root}/${
298
+ remote.isGitHub ? `issues/${source.mrIid}/comments` : `merge_requests/${source.mrIid}/notes`
299
+ }`;
300
+ let unmarkedNoteId: string | null = null;
301
+ for (let page = 1; page <= 100; page++) {
302
+ const response = await fetch(`${url}?per_page=100&page=${page}`, { headers: remote.headers, redirect: 'error' });
303
+ if (!response.ok) throw new Error(`Unable to check existing review comments (${response.status})`);
304
+ const notes: unknown = await response.json();
305
+ if (!Array.isArray(notes)) throw new Error('Invalid review comment response');
306
+ for (const note of notes.map(object)) {
307
+ if (typeof note.body !== 'string') continue;
308
+ const author = object(remote.isGitHub ? note.user : note.author);
309
+ if (note.body.includes(marker)) {
310
+ if (note.body !== expectedBody || String(author.id) !== String(authenticated.id))
311
+ throw new Error('Review comment marker is ambiguous');
312
+ if (typeof note.id !== 'number' && typeof note.id !== 'string')
313
+ throw new Error('Review comment identifier is unavailable');
314
+ return { kind: 'marked', noteId: String(note.id) };
315
+ }
316
+ if (includeUnmarked && note.body === markdown && String(author.id) === String(authenticated.id)) {
317
+ if (typeof note.id !== 'number' && typeof note.id !== 'string')
318
+ throw new Error('Review comment identifier is unavailable');
319
+ unmarkedNoteId = String(note.id);
320
+ }
321
+ }
322
+ if (notes.length < 100) break;
323
+ if (page === 100) throw new Error('Too many review comments to check safely');
324
+ }
325
+ return unmarkedNoteId ? { kind: 'unmarked', noteId: unmarkedNoteId } : null;
326
+ }
327
+
328
+ export async function publishPinnedReview(
329
+ db: Database,
330
+ repo: RecordGetter,
331
+ source: PinnedReviewSource,
332
+ markdown: string,
333
+ marker: string,
334
+ initiate: (start: () => ReturnType<typeof fetch>) => Promise<{ response: ReturnType<typeof fetch> }>,
335
+ ): Promise<string> {
336
+ const existing = await findPublishedReview(db, repo, source, markdown, marker);
337
+ if (existing) return existing;
338
+ const remote = await provider(db, repo);
339
+ if (!remote.pat || remote.projectKey !== source.projectKey || !source.mrIid)
340
+ throw new Error('Repository credentials or project changed');
341
+ const url = `${remote.root}/${
342
+ remote.isGitHub ? `issues/${source.mrIid}/comments` : `merge_requests/${source.mrIid}/notes`
343
+ }`;
344
+ await assertCurrentMrHead(db, repo, source);
345
+ const { response: pending } = await initiate(() =>
346
+ fetch(url, {
347
+ method: 'POST',
348
+ redirect: 'error',
349
+ headers: { ...remote.headers, 'Content-Type': 'application/json' },
350
+ body: JSON.stringify({ body: `${markdown}\n\n${marker}` }),
351
+ }),
352
+ );
353
+ const response = await pending;
354
+ if (!response.ok) throw new Error(`Review comment outcome is unknown (${response.status})`);
355
+ const result = object(await response.json());
356
+ if (typeof result.id !== 'number' && typeof result.id !== 'string')
357
+ throw new Error('Review comment outcome is unknown');
358
+ return String(result.id);
359
+ }