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,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
+ }
@@ -1,56 +1,56 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { isGitManagerResourceResponse, REDACTED_PAT, redactCredentialFields } from '../redact';
3
-
4
- describe('Git Manager credential response redaction', () => {
5
- it('redacts PATs recursively through nested associations and dataValues', () => {
6
- const response = {
7
- data: [
8
- {
9
- gitAccount: {
10
- pat: 'top-level-secret',
11
- dataValues: { pat: 'top-level-data-values-secret' },
12
- },
13
- dataValues: {
14
- gitAccount: {
15
- pat: 'nested-secret',
16
- dataValues: { pat: 'nested-data-values-secret' },
17
- },
18
- },
19
- },
20
- ],
21
- };
22
-
23
- redactCredentialFields(response);
24
-
25
- expect(response.data[0].gitAccount.pat).toBe(REDACTED_PAT);
26
- expect(response.data[0].gitAccount.dataValues.pat).toBe(REDACTED_PAT);
27
- expect(response.data[0].dataValues.gitAccount.pat).toBe(REDACTED_PAT);
28
- expect(response.data[0].dataValues.gitAccount.dataValues.pat).toBe(REDACTED_PAT);
29
- });
30
-
31
- it('handles circular response objects without leaving a PAT exposed', () => {
32
- const response: { pat: string; self?: unknown } = { pat: 'secret' };
33
- response.self = response;
34
-
35
- redactCredentialFields(response);
36
-
37
- expect(response.pat).toBe(REDACTED_PAT);
38
- });
39
-
40
- it.each([
41
- 'gitManager',
42
- 'gitRepositories',
43
- 'gitReviewFlows',
44
- 'gitCodeReviews',
45
- 'gitSubtreeConfigs',
46
- 'gitSubtreeRuns',
47
- 'gitAccounts.1.repositories',
48
- 'gitRepositories.10.gitAccount',
49
- ])('recognizes nested Git Manager response route %s', (resourceName) => {
50
- expect(isGitManagerResourceResponse(resourceName)).toBe(true);
51
- });
52
-
53
- it('does not scrub unrelated resource responses', () => {
54
- expect(isGitManagerResourceResponse('users')).toBe(false);
55
- });
56
- });
1
+ import { describe, expect, it } from 'vitest';
2
+ import { isGitManagerResourceResponse, REDACTED_PAT, redactCredentialFields } from '../redact';
3
+
4
+ describe('Git Manager credential response redaction', () => {
5
+ it('redacts PATs recursively through nested associations and dataValues', () => {
6
+ const response = {
7
+ data: [
8
+ {
9
+ gitAccount: {
10
+ pat: 'top-level-secret',
11
+ dataValues: { pat: 'top-level-data-values-secret' },
12
+ },
13
+ dataValues: {
14
+ gitAccount: {
15
+ pat: 'nested-secret',
16
+ dataValues: { pat: 'nested-data-values-secret' },
17
+ },
18
+ },
19
+ },
20
+ ],
21
+ };
22
+
23
+ redactCredentialFields(response);
24
+
25
+ expect(response.data[0].gitAccount.pat).toBe(REDACTED_PAT);
26
+ expect(response.data[0].gitAccount.dataValues.pat).toBe(REDACTED_PAT);
27
+ expect(response.data[0].dataValues.gitAccount.pat).toBe(REDACTED_PAT);
28
+ expect(response.data[0].dataValues.gitAccount.dataValues.pat).toBe(REDACTED_PAT);
29
+ });
30
+
31
+ it('handles circular response objects without leaving a PAT exposed', () => {
32
+ const response: { pat: string; self?: unknown } = { pat: 'secret' };
33
+ response.self = response;
34
+
35
+ redactCredentialFields(response);
36
+
37
+ expect(response.pat).toBe(REDACTED_PAT);
38
+ });
39
+
40
+ it.each([
41
+ 'gitManager',
42
+ 'gitRepositories',
43
+ 'gitReviewFlows',
44
+ 'gitCodeReviews',
45
+ 'gitSubtreeConfigs',
46
+ 'gitSubtreeRuns',
47
+ 'gitAccounts.1.repositories',
48
+ 'gitRepositories.10.gitAccount',
49
+ ])('recognizes nested Git Manager response route %s', (resourceName) => {
50
+ expect(isGitManagerResourceResponse(resourceName)).toBe(true);
51
+ });
52
+
53
+ it('does not scrub unrelated resource responses', () => {
54
+ expect(isGitManagerResourceResponse('users')).toBe(false);
55
+ });
56
+ });
@@ -1,85 +1,85 @@
1
- import { describe, expect, it } from 'vitest';
2
-
3
- import { validateRepoUrl } from '../../actions/git-actions';
4
- import { parseGitLabProject } from '../gitlab-url';
5
- import { redactCredentialFields } from '../redact';
6
- import {
7
- assertUrlHasNoUserInfo,
8
- containsCredentialBearingUrlField,
9
- hasUrlUserInfo,
10
- redactUrlUserInfo,
11
- URL_USERINFO_NOT_ALLOWED,
12
- } from '../url-security';
13
-
14
- const CREDENTIAL_URL = 'https://user:secret@example.test/group/repository.git';
15
- const USERNAME_ONLY_URL = 'https://user@example.test/group/repository.git';
16
- const REPOSITORY_URL_FIELDS = new Set(['repoUrl']);
17
- const ACCOUNT_URL_FIELDS = new Set(['baseUrl']);
18
- const GIT_CONFIGURATION_URL_FIELDS = new Set(['repoUrl', 'baseUrl']);
19
-
20
- describe('Git Manager URL credential security', () => {
21
- it('rejects URLs with a username or password', () => {
22
- expect(hasUrlUserInfo(CREDENTIAL_URL)).toBe(true);
23
- expect(hasUrlUserInfo(USERNAME_ONLY_URL)).toBe(true);
24
- expect(() => assertUrlHasNoUserInfo(CREDENTIAL_URL)).toThrow(URL_USERINFO_NOT_ALLOWED);
25
- expect(() => assertUrlHasNoUserInfo(USERNAME_ONLY_URL)).toThrow(URL_USERINFO_NOT_ALLOWED);
26
- });
27
-
28
- it.each([
29
- ['direct repository URL', { repoUrl: CREDENTIAL_URL }, REPOSITORY_URL_FIELDS],
30
- ['dotted repository URL', { 'values.repoUrl': CREDENTIAL_URL }, REPOSITORY_URL_FIELDS],
31
- ['bracket account URL', { 'values[baseUrl]': USERNAME_ONLY_URL }, ACCOUNT_URL_FIELDS],
32
- ['nested account URL', { values: { updateAssociationValues: { baseUrl: CREDENTIAL_URL } } }, ACCOUNT_URL_FIELDS],
33
- [
34
- 'repository association account URL',
35
- { values: { gitAccount: { baseUrl: CREDENTIAL_URL } } },
36
- GIT_CONFIGURATION_URL_FIELDS,
37
- ],
38
- [
39
- 'account association repository URL',
40
- { values: { repositories: [{ repoUrl: CREDENTIAL_URL }] } },
41
- GIT_CONFIGURATION_URL_FIELDS,
42
- ],
43
- ['serialized query values', JSON.stringify({ values: { repoUrl: CREDENTIAL_URL } }), REPOSITORY_URL_FIELDS],
44
- ])('finds a credential-bearing URL in %s', (_source, value, fields) => {
45
- expect(containsCredentialBearingUrlField(value, fields)).toBe(true);
46
- });
47
-
48
- it('allows clean URLs and ignores other field names', () => {
49
- expect(
50
- containsCredentialBearingUrlField(
51
- { values: { repoUrl: 'https://example.test/group/repository.git' } },
52
- REPOSITORY_URL_FIELDS,
53
- ),
54
- ).toBe(false);
55
- expect(containsCredentialBearingUrlField({ otherUrl: CREDENTIAL_URL }, REPOSITORY_URL_FIELDS)).toBe(false);
56
- expect(() => validateRepoUrl('https://example.test/group/repository.git')).not.toThrow();
57
- });
58
-
59
- it('rejects credential-bearing URLs in Git entry points', () => {
60
- expect(() => validateRepoUrl(CREDENTIAL_URL)).toThrow(URL_USERINFO_NOT_ALLOWED);
61
- expect(() => parseGitLabProject(USERNAME_ONLY_URL)).toThrow(URL_USERINFO_NOT_ALLOWED);
62
- });
63
-
64
- it('redacts userinfo from nested repository and account responses', () => {
65
- const response = {
66
- data: {
67
- repoUrl: CREDENTIAL_URL,
68
- gitAccount: {
69
- baseUrl: USERNAME_ONLY_URL,
70
- },
71
- },
72
- };
73
-
74
- redactCredentialFields(response);
75
-
76
- expect(response.data.repoUrl).toBe('https://***:***@example.test/group/repository.git');
77
- expect(response.data.gitAccount.baseUrl).toBe('https://***:***@example.test/group/repository.git');
78
- });
79
-
80
- it('does not leak a password segment when legacy userinfo contains another at sign', () => {
81
- expect(redactUrlUserInfo('https://user:secret@still-secret@example.test/repository.git')).toBe(
82
- 'https://***:***@example.test/repository.git',
83
- );
84
- });
85
- });
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { validateRepoUrl } from '../../actions/git-actions';
4
+ import { parseGitLabProject } from '../gitlab-url';
5
+ import { redactCredentialFields } from '../redact';
6
+ import {
7
+ assertUrlHasNoUserInfo,
8
+ containsCredentialBearingUrlField,
9
+ hasUrlUserInfo,
10
+ redactUrlUserInfo,
11
+ URL_USERINFO_NOT_ALLOWED,
12
+ } from '../url-security';
13
+
14
+ const CREDENTIAL_URL = 'https://user:secret@example.test/group/repository.git';
15
+ const USERNAME_ONLY_URL = 'https://user@example.test/group/repository.git';
16
+ const REPOSITORY_URL_FIELDS = new Set(['repoUrl']);
17
+ const ACCOUNT_URL_FIELDS = new Set(['baseUrl']);
18
+ const GIT_CONFIGURATION_URL_FIELDS = new Set(['repoUrl', 'baseUrl']);
19
+
20
+ describe('Git Manager URL credential security', () => {
21
+ it('rejects URLs with a username or password', () => {
22
+ expect(hasUrlUserInfo(CREDENTIAL_URL)).toBe(true);
23
+ expect(hasUrlUserInfo(USERNAME_ONLY_URL)).toBe(true);
24
+ expect(() => assertUrlHasNoUserInfo(CREDENTIAL_URL)).toThrow(URL_USERINFO_NOT_ALLOWED);
25
+ expect(() => assertUrlHasNoUserInfo(USERNAME_ONLY_URL)).toThrow(URL_USERINFO_NOT_ALLOWED);
26
+ });
27
+
28
+ it.each([
29
+ ['direct repository URL', { repoUrl: CREDENTIAL_URL }, REPOSITORY_URL_FIELDS],
30
+ ['dotted repository URL', { 'values.repoUrl': CREDENTIAL_URL }, REPOSITORY_URL_FIELDS],
31
+ ['bracket account URL', { 'values[baseUrl]': USERNAME_ONLY_URL }, ACCOUNT_URL_FIELDS],
32
+ ['nested account URL', { values: { updateAssociationValues: { baseUrl: CREDENTIAL_URL } } }, ACCOUNT_URL_FIELDS],
33
+ [
34
+ 'repository association account URL',
35
+ { values: { gitAccount: { baseUrl: CREDENTIAL_URL } } },
36
+ GIT_CONFIGURATION_URL_FIELDS,
37
+ ],
38
+ [
39
+ 'account association repository URL',
40
+ { values: { repositories: [{ repoUrl: CREDENTIAL_URL }] } },
41
+ GIT_CONFIGURATION_URL_FIELDS,
42
+ ],
43
+ ['serialized query values', JSON.stringify({ values: { repoUrl: CREDENTIAL_URL } }), REPOSITORY_URL_FIELDS],
44
+ ])('finds a credential-bearing URL in %s', (_source, value, fields) => {
45
+ expect(containsCredentialBearingUrlField(value, fields)).toBe(true);
46
+ });
47
+
48
+ it('allows clean URLs and ignores other field names', () => {
49
+ expect(
50
+ containsCredentialBearingUrlField(
51
+ { values: { repoUrl: 'https://example.test/group/repository.git' } },
52
+ REPOSITORY_URL_FIELDS,
53
+ ),
54
+ ).toBe(false);
55
+ expect(containsCredentialBearingUrlField({ otherUrl: CREDENTIAL_URL }, REPOSITORY_URL_FIELDS)).toBe(false);
56
+ expect(() => validateRepoUrl('https://example.test/group/repository.git')).not.toThrow();
57
+ });
58
+
59
+ it('rejects credential-bearing URLs in Git entry points', () => {
60
+ expect(() => validateRepoUrl(CREDENTIAL_URL)).toThrow(URL_USERINFO_NOT_ALLOWED);
61
+ expect(() => parseGitLabProject(USERNAME_ONLY_URL)).toThrow(URL_USERINFO_NOT_ALLOWED);
62
+ });
63
+
64
+ it('redacts userinfo from nested repository and account responses', () => {
65
+ const response = {
66
+ data: {
67
+ repoUrl: CREDENTIAL_URL,
68
+ gitAccount: {
69
+ baseUrl: USERNAME_ONLY_URL,
70
+ },
71
+ },
72
+ };
73
+
74
+ redactCredentialFields(response);
75
+
76
+ expect(response.data.repoUrl).toBe('https://***:***@example.test/group/repository.git');
77
+ expect(response.data.gitAccount.baseUrl).toBe('https://***:***@example.test/group/repository.git');
78
+ });
79
+
80
+ it('does not leak a password segment when legacy userinfo contains another at sign', () => {
81
+ expect(redactUrlUserInfo('https://user:secret@still-secret@example.test/repository.git')).toBe(
82
+ 'https://***:***@example.test/repository.git',
83
+ );
84
+ });
85
+ });