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,321 +1,331 @@
1
- import type { Database, Model } from '@nocobase/database';
2
-
3
- function getRecordValue(record: unknown, key: string) {
4
- if (!record || typeof record !== 'object') return undefined;
5
- const model = record as { get?: (attribute: string) => unknown } & Record<string, unknown>;
6
- return typeof model.get === 'function' ? model.get(key) : model[key];
7
- }
8
-
9
- export const REPOSITORY_READ_ACTIONS = ['list', 'get'] as const;
10
- export const GIT_READ_ACTIONS = [
11
- 'status',
12
- 'log',
13
- 'branches',
14
- 'diff',
15
- 'fileTree',
16
- 'fileContent',
17
- 'commitDetail',
18
- 'mergeRequests',
19
- 'mergeRequestDetail',
20
- 'mergeRequestNotes',
21
- 'pollerStatus',
22
- 'subtreePreview',
23
- 'subtreeOptions',
24
- ] as const;
25
- export const GIT_WRITE_ACTIONS = [
26
- 'clone',
27
- 'pull',
28
- 'push',
29
- 'fetch',
30
- 'checkout',
31
- 'triggerReview',
32
- 'reviewApprovePost',
33
- 'reviewReject',
34
- 'pollNow',
35
- 'subtreeRun',
36
- ] as const;
37
-
38
- export type RepositoryPermissionScope = {
39
- ids: Array<number | string>;
40
- unrestricted: boolean;
41
- supported: boolean;
42
- };
43
-
44
- type ScopeResolution = {
45
- ids: Set<number | string>;
46
- unrestricted: boolean;
47
- supported: boolean;
48
- };
49
-
50
- function supportedIds(ids: Iterable<number | string>): ScopeResolution {
51
- return { ids: new Set(ids), unrestricted: false, supported: true };
52
- }
53
-
54
- function unsupportedScope(): ScopeResolution {
55
- return { ids: new Set(), unrestricted: false, supported: false };
56
- }
57
-
58
- function combineScopeBranches(operator: '$and' | '$or', branches: unknown[]): ScopeResolution {
59
- const resolutions = branches.map(resolveRepositoryScope);
60
- if (resolutions.some((resolution) => !resolution.supported)) return unsupportedScope();
61
-
62
- if (operator === '$or') {
63
- if (resolutions.some((resolution) => resolution.unrestricted)) {
64
- return { ids: new Set(), unrestricted: true, supported: true };
65
- }
66
- return supportedIds(resolutions.flatMap((resolution) => [...resolution.ids]));
67
- }
68
-
69
- const restricted = resolutions.filter((resolution) => !resolution.unrestricted);
70
- if (restricted.length === 0) {
71
- return { ids: new Set(), unrestricted: true, supported: true };
72
- }
73
- const [first, ...rest] = restricted;
74
- const ids = new Set([...first.ids].filter((id) => rest.every((resolution) => resolution.ids.has(id))));
75
- return supportedIds(ids);
76
- }
77
-
78
- function resolveRepositoryScope(scope: unknown): ScopeResolution {
79
- if (scope == null) {
80
- return { ids: new Set(), unrestricted: true, supported: true };
81
- }
82
- if (typeof scope !== 'object' || Array.isArray(scope)) return unsupportedScope();
83
-
84
- const condition = scope as Record<string, unknown>;
85
- const keys = Object.keys(condition);
86
- if (keys.length === 0) {
87
- return { ids: new Set(), unrestricted: true, supported: true };
88
- }
89
-
90
- const operator = keys.find((key) => key === '$and' || key === '$or');
91
- if (operator) {
92
- if (keys.length !== 1 || !Array.isArray(condition[operator])) return unsupportedScope();
93
- return combineScopeBranches(operator as '$and' | '$or', condition[operator] as unknown[]);
94
- }
95
-
96
- if (keys.length !== 1 || !('id' in condition)) return unsupportedScope();
97
- const id = condition.id;
98
- if (typeof id === 'number' || typeof id === 'string') {
99
- return supportedIds([id]);
100
- }
101
- if (!id || typeof id !== 'object' || Array.isArray(id)) return unsupportedScope();
102
-
103
- const idCondition = id as Record<string, unknown>;
104
- const idKeys = Object.keys(idCondition);
105
- if (idKeys.length !== 1) return unsupportedScope();
106
- const equal = idCondition.$eq;
107
- if (typeof equal === 'number' || typeof equal === 'string') {
108
- return supportedIds([equal]);
109
- }
110
- const included = idCondition.$in;
111
- if (Array.isArray(included) && included.every((value) => typeof value === 'number' || typeof value === 'string')) {
112
- return supportedIds(included as Array<number | string>);
113
- }
114
- return unsupportedScope();
115
- }
116
-
117
- function actionScope(actionData: Record<string, unknown>): unknown {
118
- const scopeRow = actionData.scope;
119
- if (!scopeRow || typeof scopeRow !== 'object') return undefined;
120
- const scopeRecord = scopeRow as Record<string, unknown>;
121
- return 'scope' in scopeRecord ? scopeRecord.scope : scopeRecord;
122
- }
123
-
124
- export function getRepositoryPermissionScope(actions: Model[], names: readonly string[]): RepositoryPermissionScope {
125
- const ids = new Set<number | string>();
126
- let unrestricted = false;
127
- for (const action of actions) {
128
- const actionData = action.toJSON() as Record<string, unknown>;
129
- if (typeof actionData.name !== 'string' || !names.includes(actionData.name)) continue;
130
- const scope = actionScope(actionData);
131
- const resolution = resolveRepositoryScope(scope);
132
- if (!resolution.supported) {
133
- return { ids: [], unrestricted: false, supported: false };
134
- }
135
- if (resolution.unrestricted) {
136
- unrestricted = true;
137
- continue;
138
- }
139
- resolution.ids.forEach((id) => ids.add(id));
140
- }
141
- return { ids: [...ids], unrestricted, supported: true };
142
- }
143
-
144
- export function getRepositoryPermissionIds(actions: Model[], names: readonly string[]) {
145
- return getRepositoryPermissionScope(actions, names).ids;
146
- }
147
-
148
- export function repositoryPermissionIdsForDisplay(
149
- scope: RepositoryPermissionScope,
150
- repositoryIds: Array<number | string>,
151
- ): Array<number | string> {
152
- return scope.unrestricted ? repositoryIds : scope.ids;
153
- }
154
-
155
- export async function syncScopedActions(
156
- db: Database,
157
- resource: Model,
158
- actionNames: readonly string[],
159
- ids: Array<number | string>,
160
- options: { unrestricted?: boolean } = {},
161
- ) {
162
- const rolesResourceId = getRecordValue(resource, 'id');
163
- const actionsRepo = db.getRepository('rolesResourcesActions');
164
- for (const storedActionName of actionNames) {
165
- const action = await actionsRepo.findOne({
166
- filter: { rolesResourceId, name: storedActionName },
167
- appends: ['scope'],
168
- });
169
- if (action) {
170
- if (options.unrestricted) {
171
- await action.update({ scopeId: null });
172
- continue;
173
- }
174
- const scopeJson = { $and: [{ id: { $in: ids } }] };
175
- const actionData = action.toJSON() as Record<string, unknown>;
176
- const actionScopeId =
177
- getRecordValue(actionData.scope, 'id') || actionData.scopeId || getRecordValue(action, 'scopeId');
178
- if (actionScopeId) {
179
- await db.getRepository('rolesResourcesScopes').update({
180
- filterByTk: actionScopeId,
181
- values: { scope: scopeJson },
182
- });
183
- } else {
184
- const newScope = await db.getRepository('rolesResourcesScopes').create({ values: { scope: scopeJson } });
185
- await action.update({ scopeId: getRecordValue(newScope, 'id') });
186
- }
187
- } else {
188
- if (options.unrestricted) {
189
- await actionsRepo.create({
190
- values: { rolesResourceId, name: storedActionName },
191
- });
192
- continue;
193
- }
194
- const scopeJson = { $and: [{ id: { $in: ids } }] };
195
- const newScope = await db.getRepository('rolesResourcesScopes').create({ values: { scope: scopeJson } });
196
- await actionsRepo.create({
197
- values: { rolesResourceId, name: storedActionName, scopeId: getRecordValue(newScope, 'id') },
198
- });
199
- }
200
- }
201
- }
202
-
203
- /**
204
- * GET gitManager:rolePermissions
205
- * Returns parsed repository access permissions for a specific role.
206
- */
207
- export async function rolePermissions(ctx: any, _next: () => Promise<void>) {
208
- const currentRoles = Array.isArray(ctx.state?.currentRoles) ? ctx.state.currentRoles : [];
209
- if (!currentRoles.includes('root')) {
210
- const canAccessRoles = await ctx.app.acl.can({ roles: currentRoles, resource: 'roles', action: 'update' });
211
- if (!canAccessRoles) return ctx.throw(403, 'Permission denied');
212
- }
213
-
214
- const roleName = ctx.action.params.roleName;
215
- if (!roleName) return ctx.throw(400, 'roleName is required');
216
-
217
- const resource = await ctx.db.getRepository('rolesResources').findOne({
218
- filter: { roleName, name: 'gitRepositories' },
219
- });
220
- if (!resource) {
221
- ctx.body = { data: { read: [], write: [] } };
222
- return;
223
- }
224
- const actions = await ctx.db.getRepository('rolesResourcesActions').find({
225
- filter: { rolesResourceId: getRecordValue(resource, 'id') },
226
- appends: ['scope'],
227
- });
228
- const gitManagerResource = await ctx.db.getRepository('rolesResources').findOne({
229
- filter: { roleName, name: 'gitManager' },
230
- });
231
- const gitManagerActions = gitManagerResource
232
- ? await ctx.db.getRepository('rolesResourcesActions').find({
233
- filter: { rolesResourceId: getRecordValue(gitManagerResource, 'id') },
234
- appends: ['scope'],
235
- })
236
- : [];
237
-
238
- const readScope = getRepositoryPermissionScope(actions, [...REPOSITORY_READ_ACTIONS, 'read']);
239
- const gitWriteScope = getRepositoryPermissionScope(gitManagerActions, GIT_WRITE_ACTIONS);
240
- const repositoryWriteScope = getRepositoryPermissionScope(actions, ['write']);
241
- const requiresRepositoryList =
242
- readScope.unrestricted || gitWriteScope.unrestricted || repositoryWriteScope.unrestricted;
243
- const repositoryIds = requiresRepositoryList
244
- ? (await ctx.db.getRepository('gitRepositories').find({ fields: ['id'] })).map((repository: Model) =>
245
- getRecordValue(repository, 'id'),
246
- )
247
- : [];
248
- const result = {
249
- read: repositoryPermissionIdsForDisplay(readScope, repositoryIds),
250
- write: [
251
- ...new Set([
252
- ...repositoryPermissionIdsForDisplay(gitWriteScope, repositoryIds),
253
- ...repositoryPermissionIdsForDisplay(repositoryWriteScope, repositoryIds),
254
- ]),
255
- ],
256
- };
257
- ctx.body = result;
258
- }
259
-
260
- /**
261
- * POST gitManager:updateRolePermissions
262
- * Update Data Scopes in rolesResourcesActions for gitRepositories.
263
- */
264
- export async function updateRolePermissions(ctx: any, _next: () => Promise<void>) {
265
- const currentRoles = Array.isArray(ctx.state?.currentRoles) ? ctx.state.currentRoles : [];
266
- if (!currentRoles.includes('root')) {
267
- const canAccessRoles = await ctx.app.acl.can({ roles: currentRoles, resource: 'roles', action: 'update' });
268
- if (!canAccessRoles) return ctx.throw(403, 'Permission denied');
269
- }
270
-
271
- const payload = ctx.action.params.values || ctx.request.body || {};
272
- const roleName = payload.roleName || ctx.action.params.roleName;
273
- const permissions = payload.values || {};
274
- if (!roleName) return ctx.throw(400, 'roleName is required');
275
-
276
- const resourceRepo = ctx.db.getRepository('rolesResources');
277
- let resource = await resourceRepo.findOne({ filter: { roleName, name: 'gitRepositories' } });
278
- if (!resource) {
279
- resource = await resourceRepo.create({
280
- values: { roleName, name: 'gitRepositories', usingActionsConfig: true },
281
- });
282
- } else if (!getRecordValue(resource, 'usingActionsConfig')) {
283
- await resource.update({ usingActionsConfig: true });
284
- }
285
-
286
- const actionsRepo = ctx.db.getRepository('rolesResourcesActions');
287
- const readIds = permissions.read || [];
288
- const writeIds = permissions.write || [];
289
- const effectiveReadIds = [...new Set([...readIds, ...writeIds])];
290
- await syncScopedActions(ctx.db, resource, REPOSITORY_READ_ACTIONS, effectiveReadIds);
291
-
292
- let gitManagerResource = await resourceRepo.findOne({ filter: { roleName, name: 'gitManager' } });
293
- if (!gitManagerResource) {
294
- gitManagerResource = await resourceRepo.create({
295
- values: { roleName, name: 'gitManager', usingActionsConfig: true },
296
- });
297
- } else if (!getRecordValue(gitManagerResource, 'usingActionsConfig')) {
298
- await gitManagerResource.update({ usingActionsConfig: true });
299
- }
300
- await syncScopedActions(ctx.db, gitManagerResource, GIT_READ_ACTIONS, effectiveReadIds);
301
- await syncScopedActions(ctx.db, gitManagerResource, GIT_WRITE_ACTIONS, writeIds);
302
-
303
- const legacyReadAction = await actionsRepo.findOne({
304
- filter: { rolesResourceId: getRecordValue(resource, 'id'), name: 'read' },
305
- });
306
- if (legacyReadAction) await legacyReadAction.destroy();
307
- const legacyWriteAction = await actionsRepo.findOne({
308
- filter: { rolesResourceId: getRecordValue(resource, 'id'), name: 'write' },
309
- });
310
- if (legacyWriteAction) await legacyWriteAction.destroy();
311
-
312
- // Force reload the ACL cache in memory for this resource
313
- try {
314
- await resource.writeToACL({ acl: ctx.app.acl });
315
- await gitManagerResource.writeToACL({ acl: ctx.app.acl });
316
- } catch (e) {
317
- ctx.logger?.warn?.('[git-manager] Failed to write resource to ACL memory cache:', e);
318
- }
319
-
320
- ctx.body = { data: 'ok' };
321
- }
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 type { Database, Model } from '@nocobase/database';
11
+
12
+ function getRecordValue(record: unknown, key: string) {
13
+ if (!record || typeof record !== 'object') return undefined;
14
+ const model = record as { get?: (attribute: string) => unknown } & Record<string, unknown>;
15
+ return typeof model.get === 'function' ? model.get(key) : model[key];
16
+ }
17
+
18
+ export const REPOSITORY_READ_ACTIONS = ['list', 'get'] as const;
19
+ export const GIT_READ_ACTIONS = [
20
+ 'status',
21
+ 'log',
22
+ 'branches',
23
+ 'diff',
24
+ 'fileTree',
25
+ 'fileContent',
26
+ 'commitDetail',
27
+ 'mergeRequests',
28
+ 'mergeRequestDetail',
29
+ 'mergeRequestNotes',
30
+ 'pollerStatus',
31
+ 'subtreePreview',
32
+ 'subtreeOptions',
33
+ ] as const;
34
+ export const GIT_WRITE_ACTIONS = [
35
+ 'clone',
36
+ 'pull',
37
+ 'push',
38
+ 'fetch',
39
+ 'checkout',
40
+ 'triggerReview',
41
+ 'reviewApprovePost',
42
+ 'reviewReject',
43
+ 'reviewWorkflowRetryPost',
44
+ 'pollNow',
45
+ 'subtreeRun',
46
+ ] as const;
47
+
48
+ export type RepositoryPermissionScope = {
49
+ ids: Array<number | string>;
50
+ unrestricted: boolean;
51
+ supported: boolean;
52
+ };
53
+
54
+ type ScopeResolution = {
55
+ ids: Set<number | string>;
56
+ unrestricted: boolean;
57
+ supported: boolean;
58
+ };
59
+
60
+ function supportedIds(ids: Iterable<number | string>): ScopeResolution {
61
+ return { ids: new Set(ids), unrestricted: false, supported: true };
62
+ }
63
+
64
+ function unsupportedScope(): ScopeResolution {
65
+ return { ids: new Set(), unrestricted: false, supported: false };
66
+ }
67
+
68
+ function combineScopeBranches(operator: '$and' | '$or', branches: unknown[]): ScopeResolution {
69
+ const resolutions = branches.map(resolveRepositoryScope);
70
+ if (resolutions.some((resolution) => !resolution.supported)) return unsupportedScope();
71
+
72
+ if (operator === '$or') {
73
+ if (resolutions.some((resolution) => resolution.unrestricted)) {
74
+ return { ids: new Set(), unrestricted: true, supported: true };
75
+ }
76
+ return supportedIds(resolutions.flatMap((resolution) => [...resolution.ids]));
77
+ }
78
+
79
+ const restricted = resolutions.filter((resolution) => !resolution.unrestricted);
80
+ if (restricted.length === 0) {
81
+ return { ids: new Set(), unrestricted: true, supported: true };
82
+ }
83
+ const [first, ...rest] = restricted;
84
+ const ids = new Set([...first.ids].filter((id) => rest.every((resolution) => resolution.ids.has(id))));
85
+ return supportedIds(ids);
86
+ }
87
+
88
+ function resolveRepositoryScope(scope: unknown): ScopeResolution {
89
+ if (scope == null) {
90
+ return { ids: new Set(), unrestricted: true, supported: true };
91
+ }
92
+ if (typeof scope !== 'object' || Array.isArray(scope)) return unsupportedScope();
93
+
94
+ const condition = scope as Record<string, unknown>;
95
+ const keys = Object.keys(condition);
96
+ if (keys.length === 0) {
97
+ return { ids: new Set(), unrestricted: true, supported: true };
98
+ }
99
+
100
+ const operator = keys.find((key) => key === '$and' || key === '$or');
101
+ if (operator) {
102
+ if (keys.length !== 1 || !Array.isArray(condition[operator])) return unsupportedScope();
103
+ return combineScopeBranches(operator as '$and' | '$or', condition[operator] as unknown[]);
104
+ }
105
+
106
+ if (keys.length !== 1 || !('id' in condition)) return unsupportedScope();
107
+ const id = condition.id;
108
+ if (typeof id === 'number' || typeof id === 'string') {
109
+ return supportedIds([id]);
110
+ }
111
+ if (!id || typeof id !== 'object' || Array.isArray(id)) return unsupportedScope();
112
+
113
+ const idCondition = id as Record<string, unknown>;
114
+ const idKeys = Object.keys(idCondition);
115
+ if (idKeys.length !== 1) return unsupportedScope();
116
+ const equal = idCondition.$eq;
117
+ if (typeof equal === 'number' || typeof equal === 'string') {
118
+ return supportedIds([equal]);
119
+ }
120
+ const included = idCondition.$in;
121
+ if (Array.isArray(included) && included.every((value) => typeof value === 'number' || typeof value === 'string')) {
122
+ return supportedIds(included as Array<number | string>);
123
+ }
124
+ return unsupportedScope();
125
+ }
126
+
127
+ function actionScope(actionData: Record<string, unknown>): unknown {
128
+ const scopeRow = actionData.scope;
129
+ if (!scopeRow || typeof scopeRow !== 'object') return undefined;
130
+ const scopeRecord = scopeRow as Record<string, unknown>;
131
+ return 'scope' in scopeRecord ? scopeRecord.scope : scopeRecord;
132
+ }
133
+
134
+ export function getRepositoryPermissionScope(actions: Model[], names: readonly string[]): RepositoryPermissionScope {
135
+ const ids = new Set<number | string>();
136
+ let unrestricted = false;
137
+ for (const action of actions) {
138
+ const actionData = action.toJSON() as Record<string, unknown>;
139
+ if (typeof actionData.name !== 'string' || !names.includes(actionData.name)) continue;
140
+ const scope = actionScope(actionData);
141
+ const resolution = resolveRepositoryScope(scope);
142
+ if (!resolution.supported) {
143
+ return { ids: [], unrestricted: false, supported: false };
144
+ }
145
+ if (resolution.unrestricted) {
146
+ unrestricted = true;
147
+ continue;
148
+ }
149
+ resolution.ids.forEach((id) => ids.add(id));
150
+ }
151
+ return { ids: [...ids], unrestricted, supported: true };
152
+ }
153
+
154
+ export function getRepositoryPermissionIds(actions: Model[], names: readonly string[]) {
155
+ return getRepositoryPermissionScope(actions, names).ids;
156
+ }
157
+
158
+ export function repositoryPermissionIdsForDisplay(
159
+ scope: RepositoryPermissionScope,
160
+ repositoryIds: Array<number | string>,
161
+ ): Array<number | string> {
162
+ return scope.unrestricted ? repositoryIds : scope.ids;
163
+ }
164
+
165
+ export async function syncScopedActions(
166
+ db: Database,
167
+ resource: Model,
168
+ actionNames: readonly string[],
169
+ ids: Array<number | string>,
170
+ options: { unrestricted?: boolean } = {},
171
+ ) {
172
+ const rolesResourceId = getRecordValue(resource, 'id');
173
+ const actionsRepo = db.getRepository('rolesResourcesActions');
174
+ for (const storedActionName of actionNames) {
175
+ const action = await actionsRepo.findOne({
176
+ filter: { rolesResourceId, name: storedActionName },
177
+ appends: ['scope'],
178
+ });
179
+ if (action) {
180
+ if (options.unrestricted) {
181
+ await action.update({ scopeId: null });
182
+ continue;
183
+ }
184
+ const scopeJson = { $and: [{ id: { $in: ids } }] };
185
+ const actionData = action.toJSON() as Record<string, unknown>;
186
+ const actionScopeId =
187
+ getRecordValue(actionData.scope, 'id') || actionData.scopeId || getRecordValue(action, 'scopeId');
188
+ if (actionScopeId) {
189
+ await db.getRepository('rolesResourcesScopes').update({
190
+ filterByTk: actionScopeId,
191
+ values: { scope: scopeJson },
192
+ });
193
+ } else {
194
+ const newScope = await db.getRepository('rolesResourcesScopes').create({ values: { scope: scopeJson } });
195
+ await action.update({ scopeId: getRecordValue(newScope, 'id') });
196
+ }
197
+ } else {
198
+ if (options.unrestricted) {
199
+ await actionsRepo.create({
200
+ values: { rolesResourceId, name: storedActionName },
201
+ });
202
+ continue;
203
+ }
204
+ const scopeJson = { $and: [{ id: { $in: ids } }] };
205
+ const newScope = await db.getRepository('rolesResourcesScopes').create({ values: { scope: scopeJson } });
206
+ await actionsRepo.create({
207
+ values: { rolesResourceId, name: storedActionName, scopeId: getRecordValue(newScope, 'id') },
208
+ });
209
+ }
210
+ }
211
+ }
212
+
213
+ /**
214
+ * GET gitManager:rolePermissions
215
+ * Returns parsed repository access permissions for a specific role.
216
+ */
217
+ export async function rolePermissions(ctx: any, _next: () => Promise<void>) {
218
+ const currentRoles = Array.isArray(ctx.state?.currentRoles) ? ctx.state.currentRoles : [];
219
+ if (!currentRoles.includes('root')) {
220
+ const canAccessRoles = await ctx.app.acl.can({ roles: currentRoles, resource: 'roles', action: 'update' });
221
+ if (!canAccessRoles) return ctx.throw(403, 'Permission denied');
222
+ }
223
+
224
+ const roleName = ctx.action.params.roleName;
225
+ if (!roleName) return ctx.throw(400, 'roleName is required');
226
+
227
+ const resource = await ctx.db.getRepository('rolesResources').findOne({
228
+ filter: { roleName, name: 'gitRepositories' },
229
+ });
230
+ if (!resource) {
231
+ ctx.body = { data: { read: [], write: [] } };
232
+ return;
233
+ }
234
+ const actions = await ctx.db.getRepository('rolesResourcesActions').find({
235
+ filter: { rolesResourceId: getRecordValue(resource, 'id') },
236
+ appends: ['scope'],
237
+ });
238
+ const gitManagerResource = await ctx.db.getRepository('rolesResources').findOne({
239
+ filter: { roleName, name: 'gitManager' },
240
+ });
241
+ const gitManagerActions = gitManagerResource
242
+ ? await ctx.db.getRepository('rolesResourcesActions').find({
243
+ filter: { rolesResourceId: getRecordValue(gitManagerResource, 'id') },
244
+ appends: ['scope'],
245
+ })
246
+ : [];
247
+
248
+ const readScope = getRepositoryPermissionScope(actions, [...REPOSITORY_READ_ACTIONS, 'read']);
249
+ const gitWriteScope = getRepositoryPermissionScope(gitManagerActions, GIT_WRITE_ACTIONS);
250
+ const repositoryWriteScope = getRepositoryPermissionScope(actions, ['write']);
251
+ const requiresRepositoryList =
252
+ readScope.unrestricted || gitWriteScope.unrestricted || repositoryWriteScope.unrestricted;
253
+ const repositoryIds = requiresRepositoryList
254
+ ? (await ctx.db.getRepository('gitRepositories').find({ fields: ['id'] })).map((repository: Model) =>
255
+ getRecordValue(repository, 'id'),
256
+ )
257
+ : [];
258
+ const result = {
259
+ read: repositoryPermissionIdsForDisplay(readScope, repositoryIds),
260
+ write: [
261
+ ...new Set([
262
+ ...repositoryPermissionIdsForDisplay(gitWriteScope, repositoryIds),
263
+ ...repositoryPermissionIdsForDisplay(repositoryWriteScope, repositoryIds),
264
+ ]),
265
+ ],
266
+ };
267
+ ctx.body = result;
268
+ }
269
+
270
+ /**
271
+ * POST gitManager:updateRolePermissions
272
+ * Update Data Scopes in rolesResourcesActions for gitRepositories.
273
+ */
274
+ export async function updateRolePermissions(ctx: any, _next: () => Promise<void>) {
275
+ const currentRoles = Array.isArray(ctx.state?.currentRoles) ? ctx.state.currentRoles : [];
276
+ if (!currentRoles.includes('root')) {
277
+ const canAccessRoles = await ctx.app.acl.can({ roles: currentRoles, resource: 'roles', action: 'update' });
278
+ if (!canAccessRoles) return ctx.throw(403, 'Permission denied');
279
+ }
280
+
281
+ const payload = ctx.action.params.values || ctx.request.body || {};
282
+ const roleName = payload.roleName || ctx.action.params.roleName;
283
+ const permissions = payload.values || {};
284
+ if (!roleName) return ctx.throw(400, 'roleName is required');
285
+
286
+ const resourceRepo = ctx.db.getRepository('rolesResources');
287
+ let resource = await resourceRepo.findOne({ filter: { roleName, name: 'gitRepositories' } });
288
+ if (!resource) {
289
+ resource = await resourceRepo.create({
290
+ values: { roleName, name: 'gitRepositories', usingActionsConfig: true },
291
+ });
292
+ } else if (!getRecordValue(resource, 'usingActionsConfig')) {
293
+ await resource.update({ usingActionsConfig: true });
294
+ }
295
+
296
+ const actionsRepo = ctx.db.getRepository('rolesResourcesActions');
297
+ const readIds = permissions.read || [];
298
+ const writeIds = permissions.write || [];
299
+ const effectiveReadIds = [...new Set([...readIds, ...writeIds])];
300
+ await syncScopedActions(ctx.db, resource, REPOSITORY_READ_ACTIONS, effectiveReadIds);
301
+
302
+ let gitManagerResource = await resourceRepo.findOne({ filter: { roleName, name: 'gitManager' } });
303
+ if (!gitManagerResource) {
304
+ gitManagerResource = await resourceRepo.create({
305
+ values: { roleName, name: 'gitManager', usingActionsConfig: true },
306
+ });
307
+ } else if (!getRecordValue(gitManagerResource, 'usingActionsConfig')) {
308
+ await gitManagerResource.update({ usingActionsConfig: true });
309
+ }
310
+ await syncScopedActions(ctx.db, gitManagerResource, GIT_READ_ACTIONS, effectiveReadIds);
311
+ await syncScopedActions(ctx.db, gitManagerResource, GIT_WRITE_ACTIONS, writeIds);
312
+
313
+ const legacyReadAction = await actionsRepo.findOne({
314
+ filter: { rolesResourceId: getRecordValue(resource, 'id'), name: 'read' },
315
+ });
316
+ if (legacyReadAction) await legacyReadAction.destroy();
317
+ const legacyWriteAction = await actionsRepo.findOne({
318
+ filter: { rolesResourceId: getRecordValue(resource, 'id'), name: 'write' },
319
+ });
320
+ if (legacyWriteAction) await legacyWriteAction.destroy();
321
+
322
+ // Force reload the ACL cache in memory for this resource
323
+ try {
324
+ await resource.writeToACL({ acl: ctx.app.acl });
325
+ await gitManagerResource.writeToACL({ acl: ctx.app.acl });
326
+ } catch (e) {
327
+ ctx.logger?.warn?.('[git-manager] Failed to write resource to ACL memory cache:', e);
328
+ }
329
+
330
+ ctx.body = { data: 'ok' };
331
+ }