plugin-git-manager 1.2.26 → 1.2.28

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 (108) hide show
  1. package/README.md +133 -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/900.a48beac7e2ebee7d.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/900.e6155002a9c97e7f.js +10 -0
  13. package/dist/client-v2/928.bba701b5a1ece58e.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 +307 -297
  17. package/dist/locale/vi-VN.json +295 -292
  18. package/dist/locale/zh-CN.json +61 -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.js +20 -10
  27. package/dist/server/plugin.js +6 -4
  28. package/dist/server/poller.js +46 -45
  29. package/dist/server/request-method-policy.js +75 -0
  30. package/dist/server/services/registry-content-service.js +23 -10
  31. package/dist/server/utils/get-repo-account.js +3 -2
  32. package/dist/server/utils/url-security.js +24 -0
  33. package/package.json +61 -43
  34. package/server.d.ts +2 -2
  35. package/server.js +1 -1
  36. package/src/client/__tests__/RunReviewButton.test.tsx +73 -0
  37. package/src/client/ai-context.tsx +114 -114
  38. package/src/client/components/AIEmployeeSelect.tsx +63 -63
  39. package/src/client/components/CommitHistory.tsx +374 -374
  40. package/src/client/components/FileExplorer.tsx +386 -386
  41. package/src/client/components/GitAccounts.tsx +179 -179
  42. package/src/client/components/GitManagerSettings.tsx +160 -160
  43. package/src/client/components/GitOperations.tsx +220 -220
  44. package/src/client/components/LLMModelSelect.tsx +63 -63
  45. package/src/client/components/LLMServiceSelect.tsx +58 -58
  46. package/src/client/components/MarkdownView.tsx +80 -80
  47. package/src/client/components/MergeRequests.tsx +790 -790
  48. package/src/client/components/PollingStatus.tsx +225 -225
  49. package/src/client/components/RepositoryConfig.tsx +335 -335
  50. package/src/client/components/RepositoryPermissions.tsx +123 -123
  51. package/src/client/components/ReviewFlows.tsx +303 -303
  52. package/src/client/components/ReviewHistory.tsx +566 -566
  53. package/src/client/components/RunReviewButton.tsx +63 -55
  54. package/src/client/context/GitManagerContext.tsx +92 -92
  55. package/src/client/index.tsx +91 -82
  56. package/src/client/locale.ts +9 -9
  57. package/src/client/promptTemplates.ts +31 -31
  58. package/src/client-v2/ai-context.tsx +99 -0
  59. package/src/client-v2/components/SubtreeSplits.tsx +547 -547
  60. package/src/client-v2/index.tsx +1 -1
  61. package/src/client-v2/locale.ts +8 -8
  62. package/src/client-v2/plugin.tsx +67 -39
  63. package/src/index.ts +2 -2
  64. package/src/locale/en-US.json +307 -297
  65. package/src/locale/vi-VN.json +295 -292
  66. package/src/locale/zh-CN.json +61 -51
  67. package/src/server/__tests__/git-actions.test.ts +24 -24
  68. package/src/server/__tests__/git-security.test.ts +170 -0
  69. package/src/server/__tests__/plugin-url-security.test.ts +17 -17
  70. package/src/server/__tests__/poller-lifecycle.test.ts +71 -0
  71. package/src/server/__tests__/poller.test.ts +37 -37
  72. package/src/server/__tests__/repository-access.test.ts +752 -752
  73. package/src/server/__tests__/review.test.ts +137 -137
  74. package/src/server/__tests__/role-permissions.test.ts +147 -147
  75. package/src/server/__tests__/smoke.test.ts +139 -17
  76. package/src/server/__tests__/subtree.test.ts +85 -85
  77. package/src/server/actions/git-actions.ts +540 -480
  78. package/src/server/actions/gitlab-api.ts +422 -411
  79. package/src/server/actions/poller.ts +39 -27
  80. package/src/server/actions/review.ts +1388 -1369
  81. package/src/server/actions/role-permissions.ts +321 -321
  82. package/src/server/actions/subtree.ts +508 -508
  83. package/src/server/ai-tools.ts +319 -319
  84. package/src/server/collections/gitAccounts.ts +56 -56
  85. package/src/server/collections/gitCodeReviews.ts +199 -199
  86. package/src/server/collections/gitRepositories.ts +87 -87
  87. package/src/server/collections/gitReviewFlows.ts +108 -108
  88. package/src/server/collections/gitSubtreeConfigs.ts +38 -38
  89. package/src/server/collections/gitSubtreeRuns.ts +30 -30
  90. package/src/server/index.ts +2 -2
  91. package/src/server/migrations/20260508000000-add-auto-review-flow-id.ts +29 -29
  92. package/src/server/migrations/20260712000000-add-git-accounts.ts +198 -198
  93. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +81 -81
  94. package/src/server/plugin.ts +372 -361
  95. package/src/server/poller.ts +351 -352
  96. package/src/server/repository-access.ts +773 -773
  97. package/src/server/request-method-policy.ts +55 -0
  98. package/src/server/services/__tests__/registry-content-service.test.ts +359 -345
  99. package/src/server/services/registry-content-service.ts +33 -11
  100. package/src/server/utils/__tests__/redact.test.ts +56 -56
  101. package/src/server/utils/__tests__/url-security.test.ts +85 -85
  102. package/src/server/utils/get-repo-account.ts +51 -41
  103. package/src/server/utils/gitlab-url.ts +38 -38
  104. package/src/server/utils/redact.ts +87 -87
  105. package/src/server/utils/url-security.ts +128 -95
  106. package/dist/client/900.acf7d1fa22f95e71.js +0 -10
  107. package/dist/client-v2/434.7a27051db18526c0.js +0 -10
  108. package/dist/client-v2/900.f32b9dc85249fc0a.js +0 -10
@@ -1,321 +1,321 @@
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
+ 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
+ }