plugin-git-manager 1.2.27 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/README.md +151 -108
  2. package/client-v2.d.ts +2 -2
  3. package/client-v2.js +1 -1
  4. package/client.d.ts +3 -3
  5. package/client.js +1 -1
  6. package/dist/client/{326.90c276058682b536.js → 313.d38fc1d40c4589b9.js} +1 -1
  7. package/dist/client/941.1793e67472872992.js +10 -0
  8. package/dist/client/index.js +1 -1
  9. package/dist/client-v2/156.445366026c1cc9a8.js +10 -0
  10. package/dist/client-v2/{326.42b7b53651ffab3a.js → 313.3c867179c3a1e817.js} +1 -1
  11. package/dist/client-v2/434.19c7579c06b9077c.js +10 -0
  12. package/dist/client-v2/928.bba701b5a1ece58e.js +10 -0
  13. package/dist/client-v2/941.b0d55429cd053f32.js +10 -0
  14. package/dist/client-v2/index.js +1 -1
  15. package/dist/externalVersion.js +9 -8
  16. package/dist/locale/en-US.json +396 -297
  17. package/dist/locale/vi-VN.json +384 -292
  18. package/dist/locale/zh-CN.json +150 -51
  19. package/dist/node_modules/simple-git/dist/cjs/index.js +25 -25
  20. package/dist/node_modules/simple-git/package.json +1 -1
  21. package/dist/node_modules/zod/index.cjs +1 -1
  22. package/dist/node_modules/zod/package.json +1 -1
  23. package/dist/server/actions/git-actions.js +90 -36
  24. package/dist/server/actions/gitlab-api.js +4 -2
  25. package/dist/server/actions/poller.js +5 -2
  26. package/dist/server/actions/review-cutover.js +137 -0
  27. package/dist/server/actions/review.js +150 -51
  28. package/dist/server/actions/role-permissions.js +1 -0
  29. package/dist/server/ai-tools.js +8 -9
  30. package/dist/server/collections/gitCodeReviews.js +10 -0
  31. package/dist/server/collections/gitReviewCutover.js +44 -0
  32. package/dist/server/collections/gitReviewFlows.js +3 -0
  33. package/dist/server/collections/gitReviewInbox.js +51 -0
  34. package/dist/server/collections/gitReviewProjects.js +43 -0
  35. package/dist/server/collections/gitReviewRequests.js +56 -0
  36. package/dist/server/index.js +8 -2
  37. package/dist/server/plugin.js +57 -20
  38. package/dist/server/poller.js +95 -74
  39. package/dist/server/repository-access.js +23 -5
  40. package/dist/server/request-method-policy.js +76 -0
  41. package/dist/server/review-control-access.js +79 -0
  42. package/dist/server/services/legacy-post-service.js +412 -0
  43. package/dist/server/services/registry-content-service.js +4 -3
  44. package/dist/server/services/review-service.js +1451 -0
  45. package/dist/server/services/review-source.js +325 -0
  46. package/dist/server/utils/get-repo-account.js +3 -2
  47. package/dist/server/utils/url-security.js +24 -0
  48. package/package.json +61 -43
  49. package/server.d.ts +2 -2
  50. package/server.js +1 -1
  51. package/src/client/__tests__/CommitHistory.test.tsx +79 -0
  52. package/src/client/__tests__/ReviewHistory.test.tsx +126 -0
  53. package/src/client/__tests__/RunReviewButton.test.tsx +84 -0
  54. package/src/client/__tests__/workflowRoutes.test.ts +65 -0
  55. package/src/client/ai-context.tsx +114 -114
  56. package/src/client/components/AIEmployeeSelect.tsx +63 -63
  57. package/src/client/components/CommitHistory.tsx +429 -374
  58. package/src/client/components/FileExplorer.tsx +386 -386
  59. package/src/client/components/GitAccounts.tsx +179 -179
  60. package/src/client/components/GitManagerSettings.tsx +160 -160
  61. package/src/client/components/GitOperations.tsx +220 -220
  62. package/src/client/components/LLMModelSelect.tsx +63 -63
  63. package/src/client/components/LLMServiceSelect.tsx +58 -58
  64. package/src/client/components/MarkdownView.tsx +80 -80
  65. package/src/client/components/MergeRequests.tsx +790 -790
  66. package/src/client/components/PollingStatus.tsx +225 -225
  67. package/src/client/components/RepositoryConfig.tsx +335 -335
  68. package/src/client/components/RepositoryPermissions.tsx +123 -123
  69. package/src/client/components/ReviewFlows.tsx +352 -303
  70. package/src/client/components/ReviewHistory.tsx +796 -566
  71. package/src/client/components/RunReviewButton.tsx +57 -173
  72. package/src/client/context/GitManagerContext.tsx +92 -92
  73. package/src/client/index.tsx +91 -82
  74. package/src/client/locale.ts +9 -9
  75. package/src/client/promptTemplates.ts +31 -31
  76. package/src/client/workflowRoutes.ts +42 -0
  77. package/src/client-v2/ai-context.tsx +99 -0
  78. package/src/client-v2/components/SubtreeSplits.tsx +547 -547
  79. package/src/client-v2/index.tsx +1 -1
  80. package/src/client-v2/locale.ts +8 -8
  81. package/src/client-v2/plugin.tsx +67 -39
  82. package/src/index.ts +2 -2
  83. package/src/locale/en-US.json +396 -297
  84. package/src/locale/vi-VN.json +384 -292
  85. package/src/locale/zh-CN.json +150 -51
  86. package/src/server/__tests__/git-actions.test.ts +24 -24
  87. package/src/server/__tests__/git-security.test.ts +170 -0
  88. package/src/server/__tests__/plugin-url-security.test.ts +17 -17
  89. package/src/server/__tests__/poller-lifecycle.test.ts +71 -0
  90. package/src/server/__tests__/poller.test.ts +37 -37
  91. package/src/server/__tests__/repository-access.test.ts +760 -752
  92. package/src/server/__tests__/review-service.integration.test.ts +1263 -0
  93. package/src/server/__tests__/review.test.ts +76 -137
  94. package/src/server/__tests__/role-permissions.test.ts +147 -147
  95. package/src/server/__tests__/smoke.test.ts +139 -17
  96. package/src/server/__tests__/subtree.test.ts +85 -85
  97. package/src/server/actions/git-actions.ts +540 -480
  98. package/src/server/actions/gitlab-api.ts +422 -411
  99. package/src/server/actions/poller.ts +39 -27
  100. package/src/server/actions/review-cutover.ts +121 -0
  101. package/src/server/actions/review.ts +1498 -1369
  102. package/src/server/actions/role-permissions.ts +331 -321
  103. package/src/server/actions/subtree.ts +508 -508
  104. package/src/server/ai-tools.ts +334 -319
  105. package/src/server/collections/gitAccounts.ts +56 -56
  106. package/src/server/collections/gitCodeReviews.ts +218 -199
  107. package/src/server/collections/gitRepositories.ts +87 -87
  108. package/src/server/collections/gitReviewCutover.ts +23 -0
  109. package/src/server/collections/gitReviewFlows.ts +120 -108
  110. package/src/server/collections/gitReviewInbox.ts +30 -0
  111. package/src/server/collections/gitReviewProjects.ts +22 -0
  112. package/src/server/collections/gitReviewRequests.ts +35 -0
  113. package/src/server/collections/gitSubtreeConfigs.ts +38 -38
  114. package/src/server/collections/gitSubtreeRuns.ts +30 -30
  115. package/src/server/index.ts +14 -2
  116. package/src/server/migrations/20260508000000-add-auto-review-flow-id.ts +29 -29
  117. package/src/server/migrations/20260712000000-add-git-accounts.ts +198 -198
  118. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +81 -81
  119. package/src/server/plugin.ts +409 -361
  120. package/src/server/poller.ts +365 -352
  121. package/src/server/repository-access.ts +803 -773
  122. package/src/server/request-method-policy.ts +56 -0
  123. package/src/server/review-control-access.ts +71 -0
  124. package/src/server/services/__tests__/registry-content-service.test.ts +359 -345
  125. package/src/server/services/__tests__/review-source.test.ts +226 -0
  126. package/src/server/services/legacy-post-service.ts +550 -0
  127. package/src/server/services/registry-content-service.ts +495 -484
  128. package/src/server/services/review-service.ts +1899 -0
  129. package/src/server/services/review-source.ts +359 -0
  130. package/src/server/utils/__tests__/redact.test.ts +56 -56
  131. package/src/server/utils/__tests__/url-security.test.ts +85 -85
  132. package/src/server/utils/get-repo-account.ts +51 -41
  133. package/src/server/utils/gitlab-url.ts +38 -38
  134. package/src/server/utils/redact.ts +87 -87
  135. package/src/server/utils/url-security.ts +128 -95
  136. package/dist/client/900.acf7d1fa22f95e71.js +0 -10
  137. package/dist/client-v2/434.7a27051db18526c0.js +0 -10
  138. package/dist/client-v2/900.f32b9dc85249fc0a.js +0 -10
@@ -1,361 +1,409 @@
1
- import { Plugin } from '@nocobase/server';
2
- import type { Database } from '@nocobase/database';
3
- import { resolve } from 'path';
4
- import { DataTypes } from 'sequelize';
5
- import * as gitActions from './actions/git-actions';
6
- import * as gitlabApi from './actions/gitlab-api';
7
- import * as reviewActions from './actions/review';
8
- import * as pollerActions from './actions/poller';
9
- import * as rolePermissionsActions from './actions/role-permissions';
10
- import * as subtreeActions from './actions/subtree';
11
- import { recoverStuckReviews, registerReviewQueue, unregisterReviewQueue } from './actions/review';
12
- import { registerGitReviewAiTools } from './ai-tools';
13
- import { startPoller, stopPoller } from './poller';
14
- import { RegistryGitContentService, SkillHubGitContentService } from './services/registry-content-service';
15
- import { enforceRepositoryAccess, enforceRepositoryCollectionAccess } from './repository-access';
16
- import { isGitManagerResourceResponse, redactCredentialFields } from './utils/redact';
17
- import { containsCredentialBearingUrlField, URL_USERINFO_NOT_ALLOWED } from './utils/url-security';
18
-
19
- const GIT_CONFIGURATION_URL_FIELDS = new Set(['repoUrl', 'baseUrl']);
20
-
21
- export function isGitConfigurationUrlMutation(resourceName: unknown, actionName: unknown): boolean {
22
- return (
23
- typeof actionName === 'string' &&
24
- ['create', 'update'].includes(actionName) &&
25
- isGitManagerResourceResponse(resourceName)
26
- );
27
- }
28
-
29
- export class PluginGitManagerServer extends Plugin {
30
- // @ts-ignore
31
- declare app: any;
32
- // @ts-ignore
33
- declare db: any;
34
- registryContentService!: RegistryGitContentService;
35
- skillHubContentService!: SkillHubGitContentService;
36
-
37
- async afterAdd() {
38
- this.registryContentService = new RegistryGitContentService(
39
- (this as unknown as { db: Database }).db,
40
- undefined,
41
- this.app.acl,
42
- );
43
- this.skillHubContentService = new SkillHubGitContentService(
44
- (this as unknown as { db: Database }).db,
45
- undefined,
46
- this.app.acl,
47
- );
48
- }
49
-
50
- async beforeLoad() {
51
- await (this as any).app.db.import({
52
- directory: resolve(__dirname, 'collections'),
53
- });
54
-
55
- (this as any).app.db.addMigrations({
56
- namespace: (this as any).name,
57
- directory: resolve(__dirname, 'migrations'),
58
- context: { plugin: this },
59
- });
60
- }
61
-
62
- async load() {
63
- // Ensure dayjs timezone + utc plugins are loaded globally to prevent 'm.startOf is not a function' errors
64
- const dayjsLib = require('dayjs');
65
- const utcPlugin = require('dayjs/plugin/utc');
66
- const timezonePlugin = require('dayjs/plugin/timezone');
67
- dayjsLib.extend(utcPlugin);
68
- dayjsLib.extend(timezonePlugin);
69
-
70
- (this as any).app.resourceManager.define({
71
- name: 'gitManager',
72
- actions: {
73
- clone: gitActions.clone,
74
- pull: gitActions.pull,
75
- push: gitActions.push,
76
- fetch: gitActions.fetch,
77
- diff: gitActions.diff,
78
- status: gitActions.status,
79
- log: gitActions.log,
80
- branches: gitActions.branches,
81
- checkout: gitActions.checkout,
82
- fileTree: gitActions.fileTree,
83
- fileContent: gitActions.fileContent,
84
- commitDetail: gitActions.commitDetail,
85
- mergeRequests: gitlabApi.mergeRequests,
86
- mergeRequestDetail: gitlabApi.mergeRequestDetail,
87
- mergeRequestNotes: gitlabApi.mergeRequestNotes,
88
- triggerReview: reviewActions.triggerReview,
89
- reviewApprovePost: reviewActions.reviewApprovePost,
90
- reviewReject: reviewActions.reviewReject,
91
- pollNow: pollerActions.pollNow,
92
- pollerStatus: pollerActions.pollerStatus,
93
- rolePermissions: rolePermissionsActions.rolePermissions,
94
- updateRolePermissions: rolePermissionsActions.updateRolePermissions,
95
- subtreePreview: subtreeActions.subtreePreview,
96
- subtreeOptions: subtreeActions.subtreeOptions,
97
- subtreeRun: subtreeActions.subtreeRunOnAppProcess,
98
- subtreeReplace: subtreeActions.subtreeRunOnAppProcess,
99
- },
100
- });
101
-
102
- (this as any).app.resourceManager.use(enforceRepositoryAccess);
103
- (this as any).app.resourceManager.use(enforceRepositoryCollectionAccess);
104
-
105
- // Suppress noisy workflow pre-action/post-action warnings for custom resources
106
- (this as any).app.use(async (ctx, next) => {
107
- if (ctx.logger && ctx.logger.warn) {
108
- const originalWarn = ctx.logger.warn.bind(ctx.logger);
109
- ctx.logger.warn = (message: any, ...args: any[]) => {
110
- if (
111
- typeof message === 'string' &&
112
- message.includes('[Workflow') &&
113
- message.includes('collection') &&
114
- message.includes('not found')
115
- ) {
116
- return ctx.logger;
117
- }
118
- return originalWarn(message, ...args);
119
- };
120
- }
121
- return next();
122
- });
123
-
124
- registerReviewQueue((this as any).app);
125
- registerGitReviewAiTools((this as any).app);
126
-
127
- (this as any).app.on('afterStart', async () => {
128
- await ensureAutoReviewFlowSchema((this as any).app).catch(
129
- (err) => (this as any).app.log?.error?.('plugin-git-manager: ensure schema error', err),
130
- );
131
- // Sweep any review left in `running` state from a previous process.
132
- recoverStuckReviews((this as any).app).catch(
133
- (err) => (this as any).app.log?.error?.('plugin-git-manager: recoverStuckReviews error', err),
134
- );
135
- subtreeActions
136
- .recoverStuckSubtreeRuns((this as any).app)
137
- .catch((err) => (this as any).app.log?.error?.('plugin-git-manager: recover subtree runs error', err));
138
- startPoller((this as any).app);
139
- });
140
- (this as any).app.on('beforeStop', () => {
141
- unregisterReviewQueue((this as any).app);
142
- stopPoller();
143
- });
144
- (this as any).app.on('beforeDestroy', () => {
145
- unregisterReviewQueue((this as any).app);
146
- stopPoller();
147
- });
148
-
149
- // Read-only operations available to all plugin users
150
- (this as any).app.acl.registerSnippet({
151
- name: `pm.${(this as any).name}.read`,
152
- actions: [
153
- 'gitRepositories:list',
154
- 'gitRepositories:get',
155
- 'gitAccounts:list',
156
- 'gitAccounts:get',
157
- 'gitReviewFlows:list',
158
- 'gitReviewFlows:get',
159
- 'gitCodeReviews:list',
160
- 'gitCodeReviews:get',
161
- 'gitSubtreeConfigs:list',
162
- 'gitSubtreeConfigs:get',
163
- 'gitSubtreeRuns:list',
164
- 'gitSubtreeRuns:get',
165
- 'gitManager:status',
166
- 'gitManager:log',
167
- 'gitManager:branches',
168
- 'gitManager:diff',
169
- 'gitManager:fileTree',
170
- 'gitManager:fileContent',
171
- 'gitManager:commitDetail',
172
- 'gitManager:mergeRequests',
173
- 'gitManager:mergeRequestDetail',
174
- 'gitManager:mergeRequestNotes',
175
- 'gitManager:pollerStatus',
176
- 'gitManager:subtreePreview',
177
- 'gitManager:subtreeOptions',
178
- ],
179
- });
180
-
181
- // Write operations require separate permission
182
- (this as any).app.acl.registerSnippet({
183
- name: `pm.${(this as any).name}.write`,
184
- actions: [
185
- 'gitRepositories:create',
186
- 'gitRepositories:update',
187
- 'gitRepositories:destroy',
188
- 'gitReviewFlows:create',
189
- 'gitReviewFlows:update',
190
- 'gitReviewFlows:destroy',
191
- 'gitCodeReviews:create',
192
- 'gitCodeReviews:update',
193
- 'gitCodeReviews:destroy',
194
- 'gitManager:clone',
195
- 'gitManager:pull',
196
- 'gitManager:push',
197
- 'gitManager:fetch',
198
- 'gitManager:checkout',
199
- 'gitManager:triggerReview',
200
- 'gitManager:reviewApprovePost',
201
- 'gitManager:reviewReject',
202
- 'gitManager:pollNow',
203
- 'gitSubtreeConfigs:create',
204
- 'gitSubtreeConfigs:update',
205
- 'gitSubtreeConfigs:destroy',
206
- 'gitManager:subtreeRun',
207
- ],
208
- });
209
-
210
- (this as any).app.acl.registerSnippet({
211
- name: `pm.${(this as any).name}.subtreeReplace`,
212
- actions: ['gitManager:subtreeReplace'],
213
- });
214
-
215
- // Repositories config — CRUD on gitRepositories and gitAccounts (no operations)
216
- (this as any).app.acl.registerSnippet({
217
- name: `pm.${(this as any).name}.repositories`,
218
- actions: ['gitRepositories:*', 'gitAccounts:*'],
219
- });
220
-
221
- // Full management — all git manager actions
222
- (this as any).app.acl.registerSnippet({
223
- name: `pm.${(this as any).name}.manage`,
224
- actions: [
225
- // ACL snippet actions are resource:action patterns; nested snippet names
226
- // are not expanded by the core snippet manager.
227
- 'gitRepositories:*',
228
- 'gitAccounts:*',
229
- 'gitReviewFlows:*',
230
- 'gitCodeReviews:*',
231
- 'gitSubtreeConfigs:*',
232
- 'gitSubtreeRuns:*',
233
- 'gitManager:*',
234
- ],
235
- });
236
-
237
- // Prevent overwriting PAT with obfuscated value on updates
238
- (this as any).app.resourceManager.use(async (ctx, next) => {
239
- const resource = ctx.action?.resourceName;
240
-
241
- if (
242
- resource === 'gitSubtreeConfigs' &&
243
- ['create', 'update'].includes(ctx.action?.actionName) &&
244
- ctx.action.params?.values
245
- ) {
246
- try {
247
- subtreeActions.validateSubtreeConfigInput(ctx.action.params.values);
248
- } catch (error) {
249
- const message = error instanceof Error ? error.message : String(error);
250
- ctx.throw(400, ctx.t(message, { ns: (this as any).name }));
251
- }
252
- }
253
-
254
- if (resource === 'gitAccounts' && ctx.action?.actionName === 'destroy') {
255
- const accounts = await ctx.db.getRepository('gitAccounts').find({
256
- filterByTk: ctx.action.params?.filterByTk,
257
- filter: ctx.action.params?.filter,
258
- fields: ['id'],
259
- });
260
- const accountIds: Array<number | string> = [];
261
- for (const account of accounts as Array<{ get: (attribute: string) => number | string }>) {
262
- accountIds.push(account.get('id'));
263
- }
264
- if (accountIds.length > 0) {
265
- const repositoryCount = await ctx.db.getRepository('gitRepositories').count({
266
- filter: { gitAccountId: { $in: accountIds } },
267
- });
268
- if (repositoryCount > 0) {
269
- ctx.throw(
270
- 409,
271
- ctx.t('Cannot delete this Git account because {{count}} repositories are using it', {
272
- ns: (this as any).name,
273
- count: repositoryCount,
274
- }),
275
- );
276
- }
277
- }
278
- }
279
-
280
- if (isGitConfigurationUrlMutation(resource, ctx.action?.actionName)) {
281
- const actionParams = ctx.action?.params;
282
- const requestBody = ctx.request?.body;
283
- const hasCredentialBearingUrl = [
284
- actionParams,
285
- actionParams?.values,
286
- requestBody,
287
- requestBody?.values,
288
- ctx.query,
289
- ctx.request?.query,
290
- ].some((source) => containsCredentialBearingUrlField(source, GIT_CONFIGURATION_URL_FIELDS));
291
-
292
- if (hasCredentialBearingUrl) {
293
- ctx.throw(400, ctx.t(URL_USERINFO_NOT_ALLOWED, { ns: (this as any).name }));
294
- }
295
-
296
- if (ctx.action.params?.values?.pat === '••••••••') {
297
- delete ctx.action.params.values.pat;
298
- }
299
- if (ctx.request.body?.pat === '••••••••') {
300
- delete ctx.request.body.pat;
301
- }
302
- }
303
- return next();
304
- });
305
-
306
- // Strip PAT from every Git Manager response, including nested association routes.
307
- (this as any).app.resourceManager.use(async (ctx, next) => {
308
- const resource = ctx.action?.resourceName;
309
- if (!isGitManagerResourceResponse(resource)) {
310
- return next();
311
- }
312
- await next();
313
- redactCredentialFields(ctx.body);
314
- });
315
- }
316
-
317
- async install() {
318
- await (this as any).app.db.getCollection('gitAccounts')?.sync();
319
- await (this as any).app.db.getCollection('gitRepositories')?.sync();
320
- await (this as any).app.db.getCollection('gitSubtreeConfigs')?.sync();
321
- await (this as any).app.db.getCollection('gitSubtreeRuns')?.sync();
322
- }
323
-
324
- async beforeDisable() {
325
- unregisterReviewQueue((this as any).app);
326
- stopPoller();
327
- }
328
-
329
- async beforeUnload() {
330
- unregisterReviewQueue((this as any).app);
331
- stopPoller();
332
- }
333
- }
334
-
335
- export async function ensureAutoReviewFlowSchema(app: any) {
336
- const sequelize = app.db?.sequelize;
337
- const queryInterface = sequelize?.getQueryInterface?.();
338
- if (!queryInterface) return;
339
-
340
- const tablePrefix = app.db.options?.tablePrefix || '';
341
-
342
- const repoTable = `${tablePrefix}gitRepositories`;
343
- const repoInfo = await queryInterface.describeTable(repoTable).catch(() => null);
344
- if (repoInfo && !repoInfo.autoReviewFlowId) {
345
- await queryInterface.addColumn(repoTable, 'autoReviewFlowId', {
346
- type: DataTypes.INTEGER,
347
- allowNull: true,
348
- });
349
- }
350
-
351
- const reviewTable = `${tablePrefix}gitCodeReviews`;
352
- const reviewInfo = await queryInterface.describeTable(reviewTable).catch(() => null);
353
- if (reviewInfo && !reviewInfo.folderPath) {
354
- await queryInterface.addColumn(reviewTable, 'folderPath', {
355
- type: DataTypes.STRING,
356
- allowNull: true,
357
- });
358
- }
359
- }
360
-
361
- export default PluginGitManagerServer;
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 { Plugin } from '@nocobase/server';
11
+ import type { Database } from '@nocobase/database';
12
+ import { resolve } from 'path';
13
+ import { DataTypes } from 'sequelize';
14
+ import * as gitActions from './actions/git-actions';
15
+ import * as gitlabApi from './actions/gitlab-api';
16
+ import * as reviewActions from './actions/review';
17
+ import * as reviewCutoverActions from './actions/review-cutover';
18
+ import * as pollerActions from './actions/poller';
19
+ import * as rolePermissionsActions from './actions/role-permissions';
20
+ import * as subtreeActions from './actions/subtree';
21
+ import { unregisterReviewQueue } from './actions/review';
22
+ import { registerGitReviewAiTools } from './ai-tools';
23
+ import { enforceGitRequestMethod } from './request-method-policy';
24
+ import { startPoller, stopPoller } from './poller';
25
+ import { RegistryGitContentService, SkillHubGitContentService } from './services/registry-content-service';
26
+ import { GitReviewService } from './services/review-service';
27
+ import { LegacyPostService } from './services/legacy-post-service';
28
+ import { enforceReviewControlAccess } from './review-control-access';
29
+ import { enforceRepositoryAccess, enforceRepositoryCollectionAccess } from './repository-access';
30
+ import { isGitManagerResourceResponse, redactCredentialFields } from './utils/redact';
31
+ import { containsCredentialBearingUrlField, URL_USERINFO_NOT_ALLOWED } from './utils/url-security';
32
+
33
+ const GIT_CONFIGURATION_URL_FIELDS = new Set(['repoUrl', 'baseUrl']);
34
+
35
+ export function isGitConfigurationUrlMutation(resourceName: unknown, actionName: unknown): boolean {
36
+ return (
37
+ typeof actionName === 'string' &&
38
+ ['create', 'update'].includes(actionName) &&
39
+ isGitManagerResourceResponse(resourceName)
40
+ );
41
+ }
42
+
43
+ export class PluginGitManagerServer extends Plugin {
44
+ // @ts-ignore
45
+ declare app: any;
46
+ // @ts-ignore
47
+ declare db: any;
48
+ registryContentService!: RegistryGitContentService;
49
+ skillHubContentService!: SkillHubGitContentService;
50
+ reviewService!: GitReviewService;
51
+ legacyPostService!: LegacyPostService;
52
+
53
+ async afterAdd() {
54
+ this.reviewService = new GitReviewService(this.app);
55
+ this.legacyPostService = new LegacyPostService(this.app);
56
+ this.registryContentService = new RegistryGitContentService(
57
+ (this as unknown as { db: Database }).db,
58
+ undefined,
59
+ this.app.acl,
60
+ );
61
+ this.skillHubContentService = new SkillHubGitContentService(
62
+ (this as unknown as { db: Database }).db,
63
+ undefined,
64
+ this.app.acl,
65
+ );
66
+ }
67
+
68
+ async beforeLoad() {
69
+ await (this as any).app.db.import({
70
+ directory: resolve(__dirname, 'collections'),
71
+ });
72
+
73
+ (this as any).app.db.addMigrations({
74
+ namespace: (this as any).name,
75
+ directory: resolve(__dirname, 'migrations'),
76
+ context: { plugin: this },
77
+ });
78
+ }
79
+
80
+ async load() {
81
+ // Ensure dayjs timezone + utc plugins are loaded globally to prevent 'm.startOf is not a function' errors
82
+ const dayjsLib = require('dayjs');
83
+ const utcPlugin = require('dayjs/plugin/utc');
84
+ const timezonePlugin = require('dayjs/plugin/timezone');
85
+ dayjsLib.extend(utcPlugin);
86
+ dayjsLib.extend(timezonePlugin);
87
+
88
+ (this as any).app.resourceManager.define({
89
+ name: 'gitManager',
90
+ actions: {
91
+ clone: gitActions.clone,
92
+ pull: gitActions.pull,
93
+ push: gitActions.push,
94
+ fetch: gitActions.fetch,
95
+ diff: gitActions.diff,
96
+ status: gitActions.status,
97
+ log: gitActions.log,
98
+ branches: gitActions.branches,
99
+ checkout: gitActions.checkout,
100
+ fileTree: gitActions.fileTree,
101
+ fileContent: gitActions.fileContent,
102
+ commitDetail: gitActions.commitDetail,
103
+ mergeRequests: gitlabApi.mergeRequests,
104
+ mergeRequestDetail: gitlabApi.mergeRequestDetail,
105
+ mergeRequestNotes: gitlabApi.mergeRequestNotes,
106
+ triggerReview: reviewActions.triggerReview,
107
+ reviewApprovePost: reviewActions.reviewApprovePost,
108
+ reviewLegacyPostStatus: reviewActions.reviewLegacyPostStatus,
109
+ reviewLegacyRetryPost: reviewActions.reviewLegacyRetryPost,
110
+ reviewLegacyReleaseHold: reviewActions.reviewLegacyReleaseHold,
111
+ reviewReject: reviewActions.reviewReject,
112
+ reviewWorkflowRetryPost: reviewActions.reviewWorkflowRetryPost,
113
+ reviewCutoverStatus: reviewCutoverActions.reviewCutoverStatus,
114
+ reviewConfirmCutover: reviewCutoverActions.reviewConfirmCutover,
115
+ reviewCancelLegacy: reviewCutoverActions.reviewCancelLegacy,
116
+ reviewRecover: reviewCutoverActions.reviewRecover,
117
+ reviewResetPostClaim: reviewCutoverActions.reviewResetPostClaim,
118
+ reviewCancelQueued: reviewCutoverActions.reviewCancelQueued,
119
+ pollNow: pollerActions.pollNow,
120
+ pollerStatus: pollerActions.pollerStatus,
121
+ rolePermissions: rolePermissionsActions.rolePermissions,
122
+ updateRolePermissions: rolePermissionsActions.updateRolePermissions,
123
+ subtreePreview: subtreeActions.subtreePreview,
124
+ subtreeOptions: subtreeActions.subtreeOptions,
125
+ subtreeRun: subtreeActions.subtreeRunOnAppProcess,
126
+ subtreeReplace: subtreeActions.subtreeRunOnAppProcess,
127
+ },
128
+ });
129
+
130
+ const legacyApprovalAction = this.app.acl.getAvailableAction('reviewApprovePost');
131
+ const priorAliases = legacyApprovalAction?.options?.aliases;
132
+ this.app.acl.setAvailableAction('reviewApprovePost', {
133
+ ...legacyApprovalAction?.options,
134
+ aliases: [
135
+ ...(Array.isArray(priorAliases) ? priorAliases : priorAliases ? [priorAliases] : []),
136
+ 'reviewLegacyPostStatus',
137
+ 'reviewLegacyRetryPost',
138
+ ],
139
+ });
140
+
141
+ this.app.resourceManager.use(enforceGitRequestMethod);
142
+ this.app.resourceManager.use(enforceReviewControlAccess);
143
+ (this as any).app.resourceManager.use(enforceRepositoryAccess);
144
+ (this as any).app.resourceManager.use(enforceRepositoryCollectionAccess);
145
+
146
+ // Suppress noisy workflow pre-action/post-action warnings for custom resources
147
+ (this as any).app.use(async (ctx, next) => {
148
+ if (ctx.logger && ctx.logger.warn) {
149
+ const originalWarn = ctx.logger.warn.bind(ctx.logger);
150
+ ctx.logger.warn = (message: any, ...args: any[]) => {
151
+ if (
152
+ typeof message === 'string' &&
153
+ message.includes('[Workflow') &&
154
+ message.includes('collection') &&
155
+ message.includes('not found')
156
+ ) {
157
+ return ctx.logger;
158
+ }
159
+ return originalWarn(message, ...args);
160
+ };
161
+ }
162
+ return next();
163
+ });
164
+
165
+ registerGitReviewAiTools((this as any).app);
166
+
167
+ (this as any).app.on('afterStart', async () => {
168
+ await ensureAutoReviewFlowSchema((this as any).app).catch(
169
+ (err) => (this as any).app.log?.error?.('plugin-git-manager: ensure schema error', err),
170
+ );
171
+ this.reviewService.start();
172
+ subtreeActions
173
+ .recoverStuckSubtreeRuns((this as any).app)
174
+ .catch((err) => (this as any).app.log?.error?.('plugin-git-manager: recover subtree runs error', err));
175
+ startPoller((this as any).app);
176
+ });
177
+ (this as any).app.on('beforeStop', () => {
178
+ unregisterReviewQueue((this as any).app);
179
+ this.reviewService.stop();
180
+ stopPoller(this.app);
181
+ });
182
+ (this as any).app.on('beforeDestroy', () => {
183
+ unregisterReviewQueue((this as any).app);
184
+ this.reviewService.stop();
185
+ stopPoller(this.app);
186
+ });
187
+
188
+ // Read-only operations available to all plugin users
189
+ (this as any).app.acl.registerSnippet({
190
+ name: `pm.${(this as any).name}.read`,
191
+ actions: [
192
+ 'gitRepositories:list',
193
+ 'gitRepositories:get',
194
+ 'gitAccounts:list',
195
+ 'gitAccounts:get',
196
+ 'gitReviewFlows:list',
197
+ 'gitReviewFlows:get',
198
+ 'gitCodeReviews:list',
199
+ 'gitCodeReviews:get',
200
+ 'gitSubtreeConfigs:list',
201
+ 'gitSubtreeConfigs:get',
202
+ 'gitSubtreeRuns:list',
203
+ 'gitSubtreeRuns:get',
204
+ 'gitManager:status',
205
+ 'gitManager:log',
206
+ 'gitManager:branches',
207
+ 'gitManager:diff',
208
+ 'gitManager:fileTree',
209
+ 'gitManager:fileContent',
210
+ 'gitManager:commitDetail',
211
+ 'gitManager:mergeRequests',
212
+ 'gitManager:mergeRequestDetail',
213
+ 'gitManager:mergeRequestNotes',
214
+ 'gitManager:pollerStatus',
215
+ 'gitManager:subtreePreview',
216
+ 'gitManager:subtreeOptions',
217
+ ],
218
+ });
219
+
220
+ // Write operations require separate permission
221
+ (this as any).app.acl.registerSnippet({
222
+ name: `pm.${(this as any).name}.write`,
223
+ actions: [
224
+ 'gitRepositories:create',
225
+ 'gitRepositories:update',
226
+ 'gitRepositories:destroy',
227
+ 'gitReviewFlows:create',
228
+ 'gitReviewFlows:update',
229
+ 'gitReviewFlows:destroy',
230
+ 'gitCodeReviews:create',
231
+ 'gitCodeReviews:update',
232
+ 'gitCodeReviews:destroy',
233
+ 'gitManager:clone',
234
+ 'gitManager:pull',
235
+ 'gitManager:push',
236
+ 'gitManager:fetch',
237
+ 'gitManager:checkout',
238
+ 'gitManager:triggerReview',
239
+ 'gitManager:reviewApprovePost',
240
+ 'gitManager:reviewLegacyPostStatus',
241
+ 'gitManager:reviewLegacyRetryPost',
242
+ 'gitManager:reviewReject',
243
+ 'gitManager:reviewWorkflowRetryPost',
244
+ 'gitManager:pollNow',
245
+ 'gitSubtreeConfigs:create',
246
+ 'gitSubtreeConfigs:update',
247
+ 'gitSubtreeConfigs:destroy',
248
+ 'gitManager:subtreeRun',
249
+ ],
250
+ });
251
+
252
+ (this as any).app.acl.registerSnippet({
253
+ name: `pm.${(this as any).name}.subtreeReplace`,
254
+ actions: ['gitManager:subtreeReplace'],
255
+ });
256
+
257
+ // Repositories config — CRUD on gitRepositories and gitAccounts (no operations)
258
+ (this as any).app.acl.registerSnippet({
259
+ name: `pm.${(this as any).name}.repositories`,
260
+ actions: ['gitRepositories:*', 'gitAccounts:*'],
261
+ });
262
+
263
+ // Full management — all git manager actions
264
+ (this as any).app.acl.registerSnippet({
265
+ name: `pm.${(this as any).name}.manage`,
266
+ actions: [
267
+ // ACL snippet actions are resource:action patterns; nested snippet names
268
+ // are not expanded by the core snippet manager.
269
+ 'gitRepositories:*',
270
+ 'gitAccounts:*',
271
+ 'gitReviewFlows:*',
272
+ 'gitCodeReviews:*',
273
+ 'gitSubtreeConfigs:*',
274
+ 'gitSubtreeRuns:*',
275
+ 'gitManager:*',
276
+ ],
277
+ });
278
+
279
+ // Prevent overwriting PAT with obfuscated value on updates
280
+ (this as any).app.resourceManager.use(async (ctx, next) => {
281
+ const resource = ctx.action?.resourceName;
282
+
283
+ if (
284
+ resource === 'gitSubtreeConfigs' &&
285
+ ['create', 'update'].includes(ctx.action?.actionName) &&
286
+ ctx.action.params?.values
287
+ ) {
288
+ try {
289
+ subtreeActions.validateSubtreeConfigInput(ctx.action.params.values);
290
+ } catch (error) {
291
+ const message = error instanceof Error ? error.message : String(error);
292
+ ctx.throw(400, ctx.t(message, { ns: (this as any).name }));
293
+ }
294
+ }
295
+
296
+ if (resource === 'gitAccounts' && ctx.action?.actionName === 'destroy') {
297
+ const accounts = await ctx.db.getRepository('gitAccounts').find({
298
+ filterByTk: ctx.action.params?.filterByTk,
299
+ filter: ctx.action.params?.filter,
300
+ fields: ['id'],
301
+ });
302
+ const accountIds: Array<number | string> = [];
303
+ for (const account of accounts as Array<{ get: (attribute: string) => number | string }>) {
304
+ accountIds.push(account.get('id'));
305
+ }
306
+ if (accountIds.length > 0) {
307
+ const repositoryCount = await ctx.db.getRepository('gitRepositories').count({
308
+ filter: { gitAccountId: { $in: accountIds } },
309
+ });
310
+ if (repositoryCount > 0) {
311
+ ctx.throw(
312
+ 409,
313
+ ctx.t('Cannot delete this Git account because {{count}} repositories are using it', {
314
+ ns: (this as any).name,
315
+ count: repositoryCount,
316
+ }),
317
+ );
318
+ }
319
+ }
320
+ }
321
+
322
+ if (isGitConfigurationUrlMutation(resource, ctx.action?.actionName)) {
323
+ const actionParams = ctx.action?.params;
324
+ const requestBody = ctx.request?.body;
325
+ const hasCredentialBearingUrl = [
326
+ actionParams,
327
+ actionParams?.values,
328
+ requestBody,
329
+ requestBody?.values,
330
+ ctx.query,
331
+ ctx.request?.query,
332
+ ].some((source) => containsCredentialBearingUrlField(source, GIT_CONFIGURATION_URL_FIELDS));
333
+
334
+ if (hasCredentialBearingUrl) {
335
+ ctx.throw(400, ctx.t(URL_USERINFO_NOT_ALLOWED, { ns: (this as any).name }));
336
+ }
337
+
338
+ if (ctx.action.params?.values?.pat === '••••••••') {
339
+ delete ctx.action.params.values.pat;
340
+ }
341
+ if (ctx.request.body?.pat === '••••••••') {
342
+ delete ctx.request.body.pat;
343
+ }
344
+ }
345
+ return next();
346
+ });
347
+
348
+ // Strip PAT from every Git Manager response, including nested association routes.
349
+ (this as any).app.resourceManager.use(async (ctx, next) => {
350
+ const resource = ctx.action?.resourceName;
351
+ if (!isGitManagerResourceResponse(resource)) {
352
+ return next();
353
+ }
354
+ await next();
355
+ redactCredentialFields(ctx.body);
356
+ });
357
+ }
358
+
359
+ async install() {
360
+ await (this as any).app.db.getCollection('gitAccounts')?.sync();
361
+ await (this as any).app.db.getCollection('gitRepositories')?.sync();
362
+ await (this as any).app.db.getCollection('gitSubtreeConfigs')?.sync();
363
+ await (this as any).app.db.getCollection('gitSubtreeRuns')?.sync();
364
+ await (this as any).app.db.getCollection('gitReviewProjects')?.sync();
365
+ await (this as any).app.db.getCollection('gitReviewInbox')?.sync();
366
+ await (this as any).app.db.getCollection('gitReviewRequests')?.sync();
367
+ await (this as any).app.db.getCollection('gitReviewCutover')?.sync();
368
+ }
369
+
370
+ async beforeDisable() {
371
+ unregisterReviewQueue((this as any).app);
372
+ this.reviewService.stop();
373
+ stopPoller(this.app);
374
+ }
375
+
376
+ async beforeUnload() {
377
+ unregisterReviewQueue((this as any).app);
378
+ this.reviewService.stop();
379
+ stopPoller(this.app);
380
+ }
381
+ }
382
+
383
+ export async function ensureAutoReviewFlowSchema(app: any) {
384
+ const sequelize = app.db?.sequelize;
385
+ const queryInterface = sequelize?.getQueryInterface?.();
386
+ if (!queryInterface) return;
387
+
388
+ const tablePrefix = app.db.options?.tablePrefix || '';
389
+
390
+ const repoTable = `${tablePrefix}gitRepositories`;
391
+ const repoInfo = await queryInterface.describeTable(repoTable).catch(() => null);
392
+ if (repoInfo && !repoInfo.autoReviewFlowId) {
393
+ await queryInterface.addColumn(repoTable, 'autoReviewFlowId', {
394
+ type: DataTypes.INTEGER,
395
+ allowNull: true,
396
+ });
397
+ }
398
+
399
+ const reviewTable = `${tablePrefix}gitCodeReviews`;
400
+ const reviewInfo = await queryInterface.describeTable(reviewTable).catch(() => null);
401
+ if (reviewInfo && !reviewInfo.folderPath) {
402
+ await queryInterface.addColumn(reviewTable, 'folderPath', {
403
+ type: DataTypes.STRING,
404
+ allowNull: true,
405
+ });
406
+ }
407
+ }
408
+
409
+ export default PluginGitManagerServer;