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
@@ -0,0 +1,325 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var review_source_exports = {};
28
+ __export(review_source_exports, {
29
+ assertCurrentMrHead: () => assertCurrentMrHead,
30
+ findLegacyPublishedReview: () => findLegacyPublishedReview,
31
+ findPublishedReview: () => findPublishedReview,
32
+ publishPinnedReview: () => publishPinnedReview,
33
+ readPinnedReviewSource: () => readPinnedReviewSource,
34
+ resolveReviewProjectKey: () => resolveReviewProjectKey,
35
+ resolveReviewSource: () => resolveReviewSource
36
+ });
37
+ module.exports = __toCommonJS(review_source_exports);
38
+ var import_crypto = require("crypto");
39
+ var import_git_actions = require("../actions/git-actions");
40
+ var import_get_repo_account = require("../utils/get-repo-account");
41
+ var import_gitlab_url = require("../utils/gitlab-url");
42
+ function object(value) {
43
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
44
+ }
45
+ function text(value) {
46
+ return typeof value === "string" && value ? value : null;
47
+ }
48
+ function sha(value) {
49
+ var _a;
50
+ const result = (_a = text(value)) == null ? void 0 : _a.toLowerCase();
51
+ if (!result || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(result)) {
52
+ throw new Error("Unable to resolve an immutable Git commit");
53
+ }
54
+ return result;
55
+ }
56
+ async function responseJson(url, headers) {
57
+ const response = await fetch(url, { headers, redirect: "error" });
58
+ if (!response.ok) throw new Error(`Git provider request failed (${response.status})`);
59
+ const size = Number(response.headers.get("content-length") || 0);
60
+ if (size > 4e6) throw new Error("Git provider response is too large");
61
+ const body = await response.text();
62
+ if (Buffer.byteLength(body) > 4e6) throw new Error("Git provider response is too large");
63
+ return object(JSON.parse(body));
64
+ }
65
+ async function provider(db, repo) {
66
+ const repoUrl = String(repo.get("repoUrl") || "");
67
+ const account = await (0, import_get_repo_account.getRepoAccount)(db, repo);
68
+ const parsed = (0, import_gitlab_url.parseGitLabProject)(repoUrl);
69
+ const isGitHub = new URL(repoUrl).hostname.toLowerCase() === "github.com";
70
+ if ((account == null ? void 0 : account.provider) === "github" && !isGitHub) throw new Error("Unsupported GitHub origin");
71
+ if (!isGitHub && !(account == null ? void 0 : account.pat)) throw new Error("GitLab account is required");
72
+ const headers = { Accept: "application/json" };
73
+ if (account == null ? void 0 : account.pat)
74
+ headers[isGitHub ? "Authorization" : "PRIVATE-TOKEN"] = isGitHub ? `Bearer ${account.pat}` : account.pat;
75
+ const root = isGitHub ? `https://api.github.com/repos/${parsed.projectPath}` : `${parsed.apiBase}/projects/${parsed.encodedProject}`;
76
+ const project = await responseJson(root, headers);
77
+ const projectId = project.id;
78
+ const canonical = text(isGitHub ? project.html_url : project.web_url);
79
+ if (typeof projectId !== "number" && typeof projectId !== "string" || !canonical) {
80
+ throw new Error("Git provider did not return a canonical project identity");
81
+ }
82
+ const canonicalUrl = new URL(canonical);
83
+ if (canonicalUrl.protocol !== "https:" || canonicalUrl.username || canonicalUrl.password) {
84
+ throw new Error("Invalid canonical project origin");
85
+ }
86
+ const identity = `${isGitHub ? "github" : "gitlab"}:${canonicalUrl.origin.toLowerCase()}:${projectId}`;
87
+ return {
88
+ root,
89
+ headers,
90
+ isGitHub,
91
+ userApi: isGitHub ? "https://api.github.com/user" : `${parsed.apiBase}/user`,
92
+ projectKey: (0, import_crypto.createHash)("sha256").update(identity).digest("hex"),
93
+ pat: (account == null ? void 0 : account.pat) || ""
94
+ };
95
+ }
96
+ async function resolveReviewProjectKey(db, repo) {
97
+ return (await provider(db, repo)).projectKey;
98
+ }
99
+ async function validateCheckoutProject(db, repo, expectedProjectKey) {
100
+ const git = (0, import_git_actions.createGit)((0, import_git_actions.validateLocalPath)(String(repo.get("localPath") || "")));
101
+ let origin;
102
+ try {
103
+ origin = (await git.raw(["remote", "get-url", "origin"])).trim();
104
+ const remote = new URL(origin);
105
+ if (remote.protocol !== "https:" || remote.username || remote.password) throw new Error("Invalid origin");
106
+ } catch {
107
+ throw new Error("Checkout origin is missing or unsupported");
108
+ }
109
+ const checkout = { get: (name) => name === "repoUrl" ? origin : repo.get(name) };
110
+ let projectKey;
111
+ try {
112
+ projectKey = (await provider(db, checkout)).projectKey;
113
+ } catch {
114
+ throw new Error("Checkout origin project could not be verified");
115
+ }
116
+ if (projectKey !== expectedProjectKey) throw new Error("Checkout origin does not match the configured project");
117
+ }
118
+ function safeFolder(value) {
119
+ const folder = value.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
120
+ if (folder.split("/").some((part) => part === ".." || part === ".") || value.includes("\0")) {
121
+ throw new Error("Invalid folder path");
122
+ }
123
+ return folder;
124
+ }
125
+ async function resolveReviewSource(db, repo, input) {
126
+ const remote = await provider(db, repo);
127
+ let headSha;
128
+ let baseSha = null;
129
+ let branch = input.branch || null;
130
+ const folderPath = input.targetType === "folder" ? safeFolder(input.folderPath || "") : null;
131
+ if (input.targetType === "mr") {
132
+ if (!input.mrIid || !Number.isSafeInteger(input.mrIid) || input.mrIid < 1) throw new Error("Invalid merge request");
133
+ const mr = await responseJson(
134
+ `${remote.root}/${remote.isGitHub ? "pulls" : "merge_requests"}/${input.mrIid}`,
135
+ remote.headers
136
+ );
137
+ headSha = sha(remote.isGitHub ? object(mr.head).sha : mr.sha || object(mr.diff_refs).head_sha);
138
+ baseSha = sha(remote.isGitHub ? object(mr.base).sha : object(mr.diff_refs).base_sha);
139
+ branch = text(remote.isGitHub ? object(mr.head).ref : mr.source_branch);
140
+ if (input.headSha && sha(input.headSha) !== headSha)
141
+ throw new Error("Merge request head changed before review admission");
142
+ } else {
143
+ await validateCheckoutProject(db, repo, remote.projectKey);
144
+ const git = (0, import_git_actions.createGit)((0, import_git_actions.validateLocalPath)(String(repo.get("localPath") || "")));
145
+ const ref = input.headSha || (input.targetType === "commit" ? input.commitSha : input.branch || "HEAD");
146
+ if (!ref) throw new Error("Git ref is required");
147
+ (0, import_git_actions.validateRef)(ref);
148
+ headSha = sha((await git.raw(["rev-parse", "--verify", `${ref}^{commit}`])).trim());
149
+ if (input.targetType === "branch") {
150
+ const base = (0, import_git_actions.validateBranch)(String(repo.get("defaultBranch") || "main"));
151
+ const baseCommit = sha((await git.raw(["rev-parse", "--verify", `${base}^{commit}`])).trim());
152
+ baseSha = sha((await git.raw(["merge-base", baseCommit, headSha])).trim());
153
+ }
154
+ }
155
+ return {
156
+ projectKey: remote.projectKey,
157
+ repositoryId: Number(repo.get("id")),
158
+ targetType: input.targetType,
159
+ mrIid: input.targetType === "mr" ? input.mrIid || null : null,
160
+ branch,
161
+ folderPath,
162
+ headSha,
163
+ baseSha
164
+ };
165
+ }
166
+ async function readPinnedReviewSource(db, repo, source) {
167
+ const remote = await provider(db, repo);
168
+ if (remote.projectKey !== source.projectKey) throw new Error("Repository project changed after admission");
169
+ let content = "";
170
+ if (source.targetType === "mr") {
171
+ const base = sha(source.baseSha);
172
+ const head = sha(source.headSha);
173
+ if (remote.isGitHub) {
174
+ const comparison = await responseJson(`${remote.root}/compare/${base}...${head}?per_page=100`, remote.headers);
175
+ const files = comparison.files;
176
+ if (!Array.isArray(files) || files.length >= 300) throw new Error("GitHub comparison is incomplete");
177
+ content = files.map((item) => {
178
+ const file = object(item);
179
+ if (typeof file.filename !== "string" || typeof file.patch !== "string")
180
+ throw new Error("GitHub comparison contains an unavailable patch");
181
+ if (/[\r\n]/.test(file.filename)) throw new Error("GitHub comparison has an unsupported filename");
182
+ return `--- a/${file.filename}
183
+ +++ b/${file.filename}
184
+ ${file.patch}`;
185
+ }).join("\n");
186
+ } else {
187
+ const comparison = await responseJson(
188
+ `${remote.root}/repository/compare?from=${base}&to=${head}`,
189
+ remote.headers
190
+ );
191
+ if (comparison.compare_timeout || comparison.overflow || !Array.isArray(comparison.diffs)) {
192
+ throw new Error("GitLab comparison is incomplete");
193
+ }
194
+ content = comparison.diffs.map((item) => {
195
+ const file = object(item);
196
+ if (file.too_large || file.collapsed || typeof file.diff !== "string")
197
+ throw new Error("GitLab comparison contains an unavailable patch");
198
+ const oldPath = String(file.old_path || "");
199
+ const newPath = String(file.new_path || "");
200
+ if (/[\r\n]/.test(oldPath + newPath)) throw new Error("GitLab comparison has an unsupported filename");
201
+ return `--- a/${oldPath}
202
+ +++ b/${newPath}
203
+ ${file.diff}`;
204
+ }).join("\n");
205
+ }
206
+ } else {
207
+ await validateCheckoutProject(db, repo, source.projectKey);
208
+ const git = (0, import_git_actions.createGit)((0, import_git_actions.validateLocalPath)(String(repo.get("localPath") || "")));
209
+ const head = sha(source.headSha);
210
+ if (source.targetType === "folder") {
211
+ const folder = safeFolder(source.folderPath || "");
212
+ const tree = await git.raw(["ls-tree", "-r", "--name-only", "-z", head, "--", folder || "."]);
213
+ const paths = tree.split("\0").filter(Boolean);
214
+ if (paths.length > 200) throw new Error("Folder contains too many files to review safely");
215
+ for (const path of paths) {
216
+ if (/[\r\n]/.test(path)) throw new Error("Folder contains an unsupported filename");
217
+ const file = await git.raw(["show", `${head}:${path}`]);
218
+ if (file.includes("\0")) throw new Error("Folder contains an unsupported binary file");
219
+ const lines = file.split("\n");
220
+ content += `
221
+ --- /dev/null
222
+ +++ b/${path}
223
+ @@ -0,0 +1,${lines.length} @@
224
+ ${lines.map((line) => `+${line}`).join("\n")}`;
225
+ if (Buffer.byteLength(content) > 2e5) throw new Error("Review context exceeds the size limit");
226
+ }
227
+ } else if (source.targetType === "commit") {
228
+ content = await git.raw(["show", "--format=", "--no-ext-diff", "--no-color", head]);
229
+ } else {
230
+ content = await git.raw(["diff", "--no-ext-diff", "--no-color", sha(source.baseSha), head, "--"]);
231
+ }
232
+ }
233
+ if (Buffer.byteLength(content) > 2e5) throw new Error("Review context exceeds the size limit");
234
+ return remote.pat ? content.split(remote.pat).join("[REDACTED]") : content;
235
+ }
236
+ async function assertCurrentMrHead(db, repo, source) {
237
+ const current = await resolveReviewSource(db, repo, { targetType: "mr", mrIid: source.mrIid });
238
+ if (current.projectKey !== source.projectKey || current.headSha !== source.headSha) {
239
+ throw new Error("Merge request head changed after review");
240
+ }
241
+ if (!source.baseSha || current.baseSha !== source.baseSha) {
242
+ throw new Error("Merge request base changed after review");
243
+ }
244
+ }
245
+ async function findPublishedReview(db, repo, source, markdown, marker) {
246
+ const result = await findReviewComment(db, repo, source, markdown, marker, false);
247
+ return (result == null ? void 0 : result.noteId) ?? null;
248
+ }
249
+ async function findLegacyPublishedReview(db, repo, source, markdown, marker) {
250
+ return findReviewComment(db, repo, source, markdown, marker, true);
251
+ }
252
+ async function findReviewComment(db, repo, source, markdown, marker, includeUnmarked) {
253
+ if (!source.mrIid) throw new Error("Only merge request reviews can be published");
254
+ const remote = await provider(db, repo);
255
+ if (!remote.pat || remote.projectKey !== source.projectKey)
256
+ throw new Error("Repository credentials or project changed");
257
+ const authenticated = await responseJson(remote.userApi, remote.headers);
258
+ if (typeof authenticated.id !== "number" && typeof authenticated.id !== "string")
259
+ throw new Error("Unable to verify Git account identity");
260
+ const expectedBody = `${markdown}
261
+
262
+ ${marker}`;
263
+ const url = `${remote.root}/${remote.isGitHub ? `issues/${source.mrIid}/comments` : `merge_requests/${source.mrIid}/notes`}`;
264
+ let unmarkedNoteId = null;
265
+ for (let page = 1; page <= 100; page++) {
266
+ const response = await fetch(`${url}?per_page=100&page=${page}`, { headers: remote.headers, redirect: "error" });
267
+ if (!response.ok) throw new Error(`Unable to check existing review comments (${response.status})`);
268
+ const notes = await response.json();
269
+ if (!Array.isArray(notes)) throw new Error("Invalid review comment response");
270
+ for (const note of notes.map(object)) {
271
+ if (typeof note.body !== "string") continue;
272
+ const author = object(remote.isGitHub ? note.user : note.author);
273
+ if (note.body.includes(marker)) {
274
+ if (note.body !== expectedBody || String(author.id) !== String(authenticated.id))
275
+ throw new Error("Review comment marker is ambiguous");
276
+ if (typeof note.id !== "number" && typeof note.id !== "string")
277
+ throw new Error("Review comment identifier is unavailable");
278
+ return { kind: "marked", noteId: String(note.id) };
279
+ }
280
+ if (includeUnmarked && note.body === markdown && String(author.id) === String(authenticated.id)) {
281
+ if (typeof note.id !== "number" && typeof note.id !== "string")
282
+ throw new Error("Review comment identifier is unavailable");
283
+ unmarkedNoteId = String(note.id);
284
+ }
285
+ }
286
+ if (notes.length < 100) break;
287
+ if (page === 100) throw new Error("Too many review comments to check safely");
288
+ }
289
+ return unmarkedNoteId ? { kind: "unmarked", noteId: unmarkedNoteId } : null;
290
+ }
291
+ async function publishPinnedReview(db, repo, source, markdown, marker, initiate) {
292
+ const existing = await findPublishedReview(db, repo, source, markdown, marker);
293
+ if (existing) return existing;
294
+ const remote = await provider(db, repo);
295
+ if (!remote.pat || remote.projectKey !== source.projectKey || !source.mrIid)
296
+ throw new Error("Repository credentials or project changed");
297
+ const url = `${remote.root}/${remote.isGitHub ? `issues/${source.mrIid}/comments` : `merge_requests/${source.mrIid}/notes`}`;
298
+ await assertCurrentMrHead(db, repo, source);
299
+ const { response: pending } = await initiate(
300
+ () => fetch(url, {
301
+ method: "POST",
302
+ redirect: "error",
303
+ headers: { ...remote.headers, "Content-Type": "application/json" },
304
+ body: JSON.stringify({ body: `${markdown}
305
+
306
+ ${marker}` })
307
+ })
308
+ );
309
+ const response = await pending;
310
+ if (!response.ok) throw new Error(`Review comment outcome is unknown (${response.status})`);
311
+ const result = object(await response.json());
312
+ if (typeof result.id !== "number" && typeof result.id !== "string")
313
+ throw new Error("Review comment outcome is unknown");
314
+ return String(result.id);
315
+ }
316
+ // Annotate the CommonJS export names for ESM import in node:
317
+ 0 && (module.exports = {
318
+ assertCurrentMrHead,
319
+ findLegacyPublishedReview,
320
+ findPublishedReview,
321
+ publishPinnedReview,
322
+ readPinnedReviewSource,
323
+ resolveReviewProjectKey,
324
+ resolveReviewSource
325
+ });
@@ -38,12 +38,13 @@ async function getRepoAccount(db, repo) {
38
38
  });
39
39
  if (!account) return null;
40
40
  const baseUrl = (account.get("baseUrl") || "").trim() || null;
41
- if (baseUrl) (0, import_url_security.assertUrlHasNoUserInfo)(baseUrl);
41
+ const provider = (account.get("provider") || "gitlab").trim();
42
+ (0, import_url_security.assertAccountRepositoryUrl)(String(repo.get("repoUrl") || ""), baseUrl, provider);
42
43
  return {
43
44
  pat: (account.get("pat") || "").trim(),
44
45
  username: (account.get("username") || "").trim(),
45
46
  baseUrl,
46
- provider: (account.get("provider") || "gitlab").trim()
47
+ provider
47
48
  };
48
49
  }
49
50
  // Annotate the CommonJS export names for ESM import in node:
@@ -27,6 +27,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
27
27
  var url_security_exports = {};
28
28
  __export(url_security_exports, {
29
29
  URL_USERINFO_NOT_ALLOWED: () => URL_USERINFO_NOT_ALLOWED,
30
+ assertAccountRepositoryUrl: () => assertAccountRepositoryUrl,
30
31
  assertUrlHasNoUserInfo: () => assertUrlHasNoUserInfo,
31
32
  containsCredentialBearingUrlField: () => containsCredentialBearingUrlField,
32
33
  hasUrlUserInfo: () => hasUrlUserInfo,
@@ -34,6 +35,28 @@ __export(url_security_exports, {
34
35
  });
35
36
  module.exports = __toCommonJS(url_security_exports);
36
37
  const URL_USERINFO_NOT_ALLOWED = "Credential-bearing URLs are not allowed";
38
+ function assertAccountRepositoryUrl(repoUrl, baseUrl, provider) {
39
+ assertUrlHasNoUserInfo(repoUrl);
40
+ const trustedUrl = baseUrl || (provider === "github" ? "https://github.com" : "https://gitlab.com");
41
+ assertUrlHasNoUserInfo(trustedUrl);
42
+ let repository;
43
+ let account;
44
+ try {
45
+ repository = new URL(repoUrl);
46
+ account = new URL(trustedUrl);
47
+ } catch {
48
+ throw new Error("Invalid repository or account URL");
49
+ }
50
+ if (repository.protocol !== "https:" || account.protocol !== "https:") {
51
+ throw new Error("Only HTTPS repository and account URLs are allowed");
52
+ }
53
+ if (repository.origin !== account.origin) {
54
+ throw new Error("Repository URL must match the Git account origin");
55
+ }
56
+ if (provider === "github" && repository.origin !== "https://github.com") {
57
+ throw new Error("GitHub accounts currently require github.com");
58
+ }
59
+ }
37
60
  function pathSegments(value) {
38
61
  return value.split(/[.[\],:/()=\s'"]+/);
39
62
  }
@@ -102,6 +125,7 @@ function redactUrlUserInfo(value) {
102
125
  // Annotate the CommonJS export names for ESM import in node:
103
126
  0 && (module.exports = {
104
127
  URL_USERINFO_NOT_ALLOWED,
128
+ assertAccountRepositoryUrl,
105
129
  assertUrlHasNoUserInfo,
106
130
  containsCredentialBearingUrlField,
107
131
  hasUrlUserInfo,
package/package.json CHANGED
@@ -1,43 +1,61 @@
1
- {
2
- "name": "plugin-git-manager",
3
- "displayName": "Git Manager",
4
- "displayName.zh-CN": "Git 管理器",
5
- "description": "Manage Git repositories with PAT authentication - pull, push, fetch, diff, file browsing",
6
- "version": "1.2.27",
7
- "license": "Apache-2.0",
8
- "main": "dist/server/index.js",
9
- "files": [
10
- "dist",
11
- "src",
12
- "client.js",
13
- "server.js",
14
- "client.d.ts",
15
- "server.d.ts",
16
- "client-v2.js",
17
- "client-v2.d.ts"
18
- ],
19
- "nocobase": {
20
- "supportedVersions": [
21
- "2.x"
22
- ],
23
- "editionLevel": 0
24
- },
25
- "peerDependencies": {
26
- "@nocobase/client": "2.x",
27
- "@nocobase/server": "2.x",
28
- "@nocobase/database": "2.x",
29
- "@nocobase/test": "2.x",
30
- "@nocobase/client-v2": "2.x",
31
- "@nocobase/flow-engine": "2.x"
32
- },
33
- "optionalPeerDependencies": {
34
- "@nocobase/ai": "2.x",
35
- "@nocobase/plugin-ai": "2.x",
36
- "@nocobase/plugin-field-markdown-vditor": "2.x"
37
- },
38
- "dependencies": {
39
- "simple-git": "^3.27.0"
40
- }
41
- ,
42
- "keywords": "System management"
43
- }
1
+ {
2
+ "name": "plugin-git-manager",
3
+ "displayName": "Git Manager",
4
+ "displayName.zh-CN": "Git 管理器",
5
+ "description": "Manage Git repositories with PAT authentication - pull, push, fetch, diff, file browsing",
6
+ "version": "1.3.1",
7
+ "license": "Apache-2.0",
8
+ "main": "dist/server/index.js",
9
+ "files": [
10
+ "dist",
11
+ "src",
12
+ "client.js",
13
+ "server.js",
14
+ "client.d.ts",
15
+ "server.d.ts",
16
+ "client-v2.js",
17
+ "client-v2.d.ts"
18
+ ],
19
+ "nocobase": {
20
+ "supportedVersions": [
21
+ "2.x"
22
+ ],
23
+ "editionLevel": 0
24
+ },
25
+ "peerDependencies": {
26
+ "@nocobase/client": "2.x",
27
+ "@nocobase/server": "2.x",
28
+ "@nocobase/database": "2.x",
29
+ "@nocobase/test": "2.x",
30
+ "@nocobase/client-v2": "2.x",
31
+ "@nocobase/flow-engine": "2.x",
32
+ "@nocobase/ai": "2.x",
33
+ "@nocobase/plugin-ai": "2.x",
34
+ "@nocobase/plugin-field-markdown-vditor": "2.x"
35
+ },
36
+ "dependencies": {
37
+ "simple-git": "^3.27.0"
38
+ },
39
+ "keywords": "System management",
40
+ "peerDependenciesMeta": {
41
+ "@nocobase/ai": {
42
+ "optional": true
43
+ },
44
+ "@nocobase/plugin-ai": {
45
+ "optional": true
46
+ },
47
+ "@nocobase/plugin-field-markdown-vditor": {
48
+ "optional": true
49
+ }
50
+ },
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/OrgGem/nocobase-beta.git",
54
+ "directory": "packages/plugins/plugin-git-manager"
55
+ },
56
+ "gitHead": "8c03d274bef1d07bed5b40f79db9fe946c43adc8",
57
+ "publishConfig": {
58
+ "access": "public",
59
+ "registry": "https://registry.npmjs.org/"
60
+ }
61
+ }
package/server.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from './dist/server';
2
- export { default } from './dist/server';
1
+ export * from './dist/server';
2
+ export { default } from './dist/server';
package/server.js CHANGED
@@ -1 +1 @@
1
- module.exports = require('./dist/server/index.js');
1
+ module.exports = require('./dist/server/index.js');
@@ -0,0 +1,79 @@
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 React from 'react';
11
+ import { cleanup, render, screen, waitFor } from '@testing-library/react';
12
+ import { CommitHistory } from '../components/CommitHistory';
13
+
14
+ const mocks = vi.hoisted(() => {
15
+ const request = vi.fn();
16
+ return {
17
+ request,
18
+ apiClient: { request },
19
+ selectedRepo: { id: 7, status: 'connected' },
20
+ };
21
+ });
22
+
23
+ vi.mock('@nocobase/client-v2', () => ({
24
+ useApp: () => ({ apiClient: mocks.apiClient }),
25
+ }));
26
+ vi.mock('../context/GitManagerContext', () => ({
27
+ useGitManager: () => ({ selectedRepo: mocks.selectedRepo }),
28
+ }));
29
+ vi.mock('../locale', () => ({ useT: () => (key: string) => key }));
30
+ vi.mock('../components/RunReviewButton', () => ({
31
+ RunReviewButton: ({ target }: { target: { type: string; branch?: string } }) => (
32
+ <button data-testid="run-review" data-branch={target.branch} data-target-type={target.type} />
33
+ ),
34
+ }));
35
+
36
+ describe('CommitHistory branch review entry point', () => {
37
+ beforeEach(() => {
38
+ vi.clearAllMocks();
39
+ mocks.request.mockImplementation(async ({ url }: { url: string }) => {
40
+ if (url === 'gitManager:branches') {
41
+ return {
42
+ data: {
43
+ data: { current: 'main', all: ['main', 'feature'], detached: false },
44
+ },
45
+ };
46
+ }
47
+ return { data: { data: { all: [] } } };
48
+ });
49
+ });
50
+ afterEach(cleanup);
51
+
52
+ it('mounts branch review only for a confirmed current branch', async () => {
53
+ render(<CommitHistory />);
54
+
55
+ const reviewButton = await screen.findByTestId('run-review');
56
+ expect(reviewButton).toHaveAttribute('data-target-type', 'branch');
57
+ expect(reviewButton).toHaveAttribute('data-branch', 'main');
58
+ expect(mocks.request).toHaveBeenCalledWith({ url: 'gitManager:branches', params: { repositoryId: 7 } });
59
+ });
60
+
61
+ it('does not treat a detached HEAD as a branch', async () => {
62
+ mocks.request.mockImplementation(async ({ url }: { url: string }) => {
63
+ if (url === 'gitManager:branches') {
64
+ return {
65
+ data: {
66
+ data: { current: 'main', all: ['main'], detached: true },
67
+ },
68
+ };
69
+ }
70
+ return { data: { data: { all: [] } } };
71
+ });
72
+ render(<CommitHistory />);
73
+
74
+ await waitFor(() => {
75
+ expect(mocks.request).toHaveBeenCalledWith({ url: 'gitManager:branches', params: { repositoryId: 7 } });
76
+ });
77
+ expect(screen.queryByTestId('run-review')).not.toBeInTheDocument();
78
+ });
79
+ });