plugin-git-manager 1.2.23 → 1.2.26

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 (53) hide show
  1. package/dist/client/900.acf7d1fa22f95e71.js +10 -0
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/900.f32b9dc85249fc0a.js +10 -0
  4. package/dist/client-v2/index.js +1 -1
  5. package/dist/externalVersion.js +8 -8
  6. package/dist/locale/en-US.json +4 -3
  7. package/dist/locale/vi-VN.json +4 -3
  8. package/dist/locale/zh-CN.json +4 -3
  9. package/dist/server/actions/git-actions.js +21 -8
  10. package/dist/server/actions/gitlab-api.js +5 -8
  11. package/dist/server/actions/poller.js +2 -1
  12. package/dist/server/actions/review.js +50 -13
  13. package/dist/server/actions/role-permissions.js +109 -16
  14. package/dist/server/actions/subtree.js +4 -8
  15. package/dist/server/migrations/20260730000000-migrate-legacy-repository-permissions.js +23 -7
  16. package/dist/server/plugin.js +42 -19
  17. package/dist/server/repository-access.js +505 -27
  18. package/dist/server/services/registry-content-service.js +149 -32
  19. package/dist/server/utils/get-repo-account.js +5 -2
  20. package/dist/server/utils/gitlab-url.js +2 -0
  21. package/dist/server/utils/redact.js +51 -5
  22. package/dist/server/utils/url-security.js +109 -0
  23. package/package.json +4 -2
  24. package/src/client/components/RunReviewButton.tsx +437 -436
  25. package/src/client/index.tsx +2 -1
  26. package/src/locale/en-US.json +4 -3
  27. package/src/locale/vi-VN.json +4 -3
  28. package/src/locale/zh-CN.json +4 -3
  29. package/src/server/__tests__/git-actions.test.ts +24 -0
  30. package/src/server/__tests__/plugin-url-security.test.ts +17 -0
  31. package/src/server/__tests__/poller.test.ts +37 -0
  32. package/src/server/__tests__/repository-access.test.ts +695 -1
  33. package/src/server/__tests__/review.test.ts +137 -0
  34. package/src/server/__tests__/role-permissions.test.ts +123 -2
  35. package/src/server/actions/git-actions.ts +33 -10
  36. package/src/server/actions/gitlab-api.ts +5 -8
  37. package/src/server/actions/poller.ts +2 -1
  38. package/src/server/actions/review.ts +74 -15
  39. package/src/server/actions/role-permissions.ts +136 -14
  40. package/src/server/actions/subtree.ts +4 -8
  41. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +23 -8
  42. package/src/server/plugin.ts +46 -25
  43. package/src/server/repository-access.ts +737 -28
  44. package/src/server/services/__tests__/registry-content-service.test.ts +209 -13
  45. package/src/server/services/registry-content-service.ts +473 -315
  46. package/src/server/utils/__tests__/redact.test.ts +56 -0
  47. package/src/server/utils/__tests__/url-security.test.ts +85 -0
  48. package/src/server/utils/get-repo-account.ts +22 -4
  49. package/src/server/utils/gitlab-url.ts +3 -0
  50. package/src/server/utils/redact.ts +68 -5
  51. package/src/server/utils/url-security.ts +95 -0
  52. package/dist/client/900.ee2fa037aff389e2.js +0 -10
  53. package/dist/client-v2/900.bef1c41d267e50c5.js +0 -10
@@ -0,0 +1,137 @@
1
+ import type { Application } from '@nocobase/server';
2
+ import { vi } from 'vitest';
3
+
4
+ import { resolveBackgroundReviewRoles, resolveImmutableReviewActorId, triggerReviewInternal } from '../actions/review';
5
+
6
+ function record(values: Record<string, unknown>) {
7
+ return {
8
+ get(attribute: string) {
9
+ return values[attribute];
10
+ },
11
+ };
12
+ }
13
+
14
+ function createReviewApp(flowRepositoryId: number | null, existingReview: Record<string, unknown> | null = null) {
15
+ const flow = record({
16
+ id: 8,
17
+ enabled: true,
18
+ repositoryId: flowRepositoryId,
19
+ aiEmployeeUsername: 'reviewer',
20
+ name: 'Review flow',
21
+ postMode: 'manual',
22
+ llmService: null,
23
+ model: null,
24
+ instructions: null,
25
+ branchFilter: null,
26
+ });
27
+ const flowsRepository = {
28
+ findOne: vi.fn().mockResolvedValue(flow),
29
+ };
30
+ const repositoriesRepository = {
31
+ findOne: vi.fn().mockResolvedValue(record({ id: 20 })),
32
+ };
33
+ const reviewsRepository = {
34
+ findOne: vi.fn().mockResolvedValue(existingReview ? record(existingReview) : null),
35
+ create: vi.fn().mockResolvedValue(record({ id: 99 })),
36
+ update: vi.fn().mockResolvedValue(undefined),
37
+ };
38
+ const getRepository = vi.fn((name: string) => {
39
+ if (name === 'gitReviewFlows') return flowsRepository;
40
+ if (name === 'gitRepositories') return repositoriesRepository;
41
+ if (name === 'gitCodeReviews') return reviewsRepository;
42
+ throw new Error(`Unexpected repository ${name}`);
43
+ });
44
+ const app = {
45
+ db: { getRepository },
46
+ lockManager: {
47
+ runExclusive: vi.fn(async (_key: string, callback: () => Promise<unknown>) => callback()),
48
+ },
49
+ serving: vi.fn().mockReturnValue(false),
50
+ eventQueue: {
51
+ publish: vi.fn().mockResolvedValue(undefined),
52
+ },
53
+ } as unknown as Application;
54
+
55
+ return { app, repositoriesRepository, reviewsRepository };
56
+ }
57
+
58
+ describe('Git Manager review flows', () => {
59
+ it('rejects an explicitly selected flow from another repository', async () => {
60
+ const { app, repositoriesRepository } = createReviewApp(10);
61
+
62
+ await expect(
63
+ triggerReviewInternal(app, {
64
+ flowId: 8,
65
+ repositoryId: 20,
66
+ targetType: 'branch',
67
+ branch: 'main',
68
+ }),
69
+ ).rejects.toMatchObject({ status: 400, message: 'Review flow does not belong to this repository' });
70
+
71
+ expect(repositoriesRepository.findOne).not.toHaveBeenCalled();
72
+ });
73
+
74
+ it('allows an explicitly selected global flow', async () => {
75
+ const { app, repositoriesRepository, reviewsRepository } = createReviewApp(null);
76
+
77
+ const reviewId = await triggerReviewInternal(app, {
78
+ flowId: 8,
79
+ repositoryId: 20,
80
+ targetType: 'branch',
81
+ branch: 'main',
82
+ userId: 7,
83
+ });
84
+
85
+ expect(reviewId).toBe(99);
86
+ expect(repositoriesRepository.findOne).toHaveBeenCalledWith({ filterByTk: 20 });
87
+ expect(reviewsRepository.create).toHaveBeenCalledWith({
88
+ values: expect.objectContaining({ flowId: 8, repositoryId: 20, createdById: 7 }),
89
+ });
90
+ });
91
+
92
+ it('uses the immutable creator field instead of review metadata for worker identity', () => {
93
+ expect(resolveImmutableReviewActorId(record({ createdById: 7, metadata: { userId: 1 } }))).toBe(7);
94
+ expect(resolveImmutableReviewActorId(record({ createdById: null, metadata: { userId: 1 } }))).toBeNull();
95
+ });
96
+
97
+ it('fails closed when a manual review actor has no resolvable roles', async () => {
98
+ const db = {
99
+ getRepository: vi.fn().mockReturnValue({ find: vi.fn().mockResolvedValue([]) }),
100
+ };
101
+
102
+ await expect(resolveBackgroundReviewRoles(db, 7)).rejects.toThrow('Unable to resolve roles for review actor');
103
+ await expect(resolveBackgroundReviewRoles(db, null)).resolves.toEqual(['admin']);
104
+ });
105
+
106
+ it.each(['completed', 'failed'])(
107
+ 'refreshes the immutable actor when a different user requeues a %s review',
108
+ async (status) => {
109
+ const { app, reviewsRepository } = createReviewApp(null, {
110
+ id: 99,
111
+ status,
112
+ latestSha: null,
113
+ createdById: 1,
114
+ });
115
+
116
+ await triggerReviewInternal(app, {
117
+ flowId: 8,
118
+ repositoryId: 20,
119
+ targetType: 'branch',
120
+ branch: 'main',
121
+ triggeredBy: 'manual',
122
+ userId: 7,
123
+ });
124
+
125
+ expect(reviewsRepository.update).toHaveBeenCalledWith({
126
+ filterByTk: 99,
127
+ values: expect.objectContaining({
128
+ createdById: 7,
129
+ triggeredBy: 'manual',
130
+ status: 'pending',
131
+ metadata: expect.objectContaining({ userId: 7 }),
132
+ }),
133
+ });
134
+ expect(reviewsRepository.create).not.toHaveBeenCalled();
135
+ },
136
+ );
137
+ });
@@ -1,6 +1,12 @@
1
- import type { Model } from '@nocobase/database';
1
+ import type { Database, Model } from '@nocobase/database';
2
+ import { vi } from 'vitest';
2
3
 
3
- import { getRepositoryPermissionIds } from '../actions/role-permissions';
4
+ import {
5
+ getRepositoryPermissionIds,
6
+ getRepositoryPermissionScope,
7
+ repositoryPermissionIdsForDisplay,
8
+ syncScopedActions,
9
+ } from '../actions/role-permissions';
4
10
 
5
11
  function permissionAction(name: string, repositoryIds: Array<number | string>) {
6
12
  return {
@@ -23,4 +29,119 @@ describe('Git Manager role permissions', () => {
23
29
 
24
30
  expect(getRepositoryPermissionIds(actions, ['write'])).toEqual([1]);
25
31
  });
32
+
33
+ it('preserves direct and equality repository scopes from legacy roles', () => {
34
+ const directScope = {
35
+ toJSON: () => ({
36
+ name: 'read',
37
+ scope: { scope: { $and: [{ id: 42 }] } },
38
+ }),
39
+ } as unknown as Model;
40
+ const equalityScope = {
41
+ toJSON: () => ({
42
+ name: 'write',
43
+ scope: { scope: { $or: [{ id: { $eq: '43' } }, { id: { $in: [44] } }] } },
44
+ }),
45
+ } as unknown as Model;
46
+
47
+ expect(getRepositoryPermissionIds([directScope, equalityScope], ['read', 'write'])).toEqual([42, '43', 44]);
48
+ });
49
+
50
+ it('recognizes an unscoped legacy permission as access to every repository', () => {
51
+ const unscopedAction = {
52
+ toJSON: () => ({ name: 'read' }),
53
+ } as unknown as Model;
54
+
55
+ expect(getRepositoryPermissionScope([unscopedAction], ['read'])).toEqual({
56
+ ids: [],
57
+ unrestricted: true,
58
+ supported: true,
59
+ });
60
+ });
61
+
62
+ it('expands an unrestricted scope to the repository IDs shown by the role editor', () => {
63
+ expect(repositoryPermissionIdsForDisplay({ ids: [], unrestricted: true, supported: true }, [1, 2])).toEqual([1, 2]);
64
+ expect(repositoryPermissionIdsForDisplay({ ids: [], unrestricted: false, supported: true }, [1, 2])).toEqual([]);
65
+ });
66
+
67
+ it('does not widen a legacy scope whose repository conditions intersect', () => {
68
+ const intersectingScope = {
69
+ toJSON: () => ({
70
+ name: 'read',
71
+ scope: { scope: { $and: [{ id: { $in: [1, 2] } }, { id: { $in: [2, 3] } }] } },
72
+ }),
73
+ } as unknown as Model;
74
+
75
+ expect(getRepositoryPermissionScope([intersectingScope], ['read'])).toEqual({
76
+ ids: [2],
77
+ unrestricted: false,
78
+ supported: true,
79
+ });
80
+ });
81
+
82
+ it('marks unsupported legacy scopes as unsafe to migrate', () => {
83
+ const unsupportedScope = {
84
+ toJSON: () => ({
85
+ name: 'read',
86
+ scope: { scope: { $and: [{ id: { $in: [1] } }, { status: 'active' }] } },
87
+ }),
88
+ } as unknown as Model;
89
+
90
+ expect(getRepositoryPermissionScope([unsupportedScope], ['read'])).toEqual({
91
+ ids: [],
92
+ unrestricted: false,
93
+ supported: false,
94
+ });
95
+ });
96
+
97
+ it('creates unscoped v2 actions when migrating an unrestricted legacy permission', async () => {
98
+ const actionsRepository = {
99
+ findOne: vi.fn().mockResolvedValue(null),
100
+ create: vi.fn().mockResolvedValue(undefined),
101
+ };
102
+ const db = {
103
+ getRepository: vi.fn((name: string) => {
104
+ if (name === 'rolesResourcesActions') return actionsRepository;
105
+ throw new Error(`Unexpected repository ${name}`);
106
+ }),
107
+ } as unknown as Database;
108
+ const resource = {
109
+ get: (attribute: string) => (attribute === 'id' ? 1 : undefined),
110
+ } as unknown as Model;
111
+
112
+ await syncScopedActions(db, resource, ['fileContent'], [], { unrestricted: true });
113
+
114
+ expect(actionsRepository.create).toHaveBeenCalledWith({
115
+ values: { rolesResourceId: 1, name: 'fileContent' },
116
+ });
117
+ });
118
+
119
+ it('persists a deny-all scope instead of deleting a zero-selection action', async () => {
120
+ const actionsRepository = {
121
+ findOne: vi.fn().mockResolvedValue(null),
122
+ create: vi.fn().mockResolvedValue(undefined),
123
+ };
124
+ const scopesRepository = {
125
+ create: vi.fn().mockResolvedValue({ get: (attribute: string) => (attribute === 'id' ? 99 : undefined) }),
126
+ };
127
+ const db = {
128
+ getRepository: vi.fn((name: string) => {
129
+ if (name === 'rolesResourcesActions') return actionsRepository;
130
+ if (name === 'rolesResourcesScopes') return scopesRepository;
131
+ throw new Error(`Unexpected repository ${name}`);
132
+ }),
133
+ } as unknown as Database;
134
+ const resource = {
135
+ get: (attribute: string) => (attribute === 'id' ? 1 : undefined),
136
+ } as unknown as Model;
137
+
138
+ await syncScopedActions(db, resource, ['fileContent'], []);
139
+
140
+ expect(scopesRepository.create).toHaveBeenCalledWith({
141
+ values: { scope: { $and: [{ id: { $in: [] } }] } },
142
+ });
143
+ expect(actionsRepository.create).toHaveBeenCalledWith({
144
+ values: { rolesResourceId: 1, name: 'fileContent', scopeId: 99 },
145
+ });
146
+ });
26
147
  });
@@ -3,8 +3,10 @@ import { Context } from '@nocobase/actions';
3
3
  import * as path from 'path';
4
4
  import * as fs from 'fs';
5
5
  import { spawnSync } from 'child_process';
6
+ import { getEffectiveActionParams } from '../repository-access';
6
7
  import { redactPat, redactError } from '../utils/redact';
7
8
  import { getRepoAccount } from '../utils/get-repo-account';
9
+ import { assertUrlHasNoUserInfo } from '../utils/url-security';
8
10
 
9
11
  // Disallow leading `-` to prevent argument-injection (e.g. `--upload-pack=...`)
10
12
  // when refs are passed as positional args to git.
@@ -15,6 +17,23 @@ const repoLocks = new Map<string, Promise<any>>();
15
17
  const GIT_BINARY = process.env.GIT_BINARY_PATH || process.env.GIT_EXECUTABLE || 'git';
16
18
  let gitAvailabilityChecked = false;
17
19
 
20
+ interface GitActionParams {
21
+ repositoryId?: number | string;
22
+ file?: string;
23
+ commitHash?: string;
24
+ compareHash?: string;
25
+ maxCount?: number | string;
26
+ branch?: string;
27
+ ref?: string;
28
+ treePath?: string;
29
+ recursive?: boolean | string;
30
+ filePath?: string;
31
+ }
32
+
33
+ function getGitActionParams(ctx: Context): GitActionParams {
34
+ return getEffectiveActionParams(ctx) as GitActionParams;
35
+ }
36
+
18
37
  export function acquireLock(key: string): { promise: Promise<void>; release: () => void } {
19
38
  const prev = repoLocks.get(key) || Promise.resolve();
20
39
  let release = () => {};
@@ -51,7 +70,8 @@ export function validateBranch(branch: string): string {
51
70
  return branch;
52
71
  }
53
72
 
54
- function validateRepoUrl(repoUrl: string): void {
73
+ export function validateRepoUrl(repoUrl: string): void {
74
+ assertUrlHasNoUserInfo(repoUrl);
55
75
  let parsed: URL;
56
76
  try {
57
77
  parsed = new URL(repoUrl);
@@ -72,6 +92,7 @@ export async function withAuth<T>(
72
92
  username?: string,
73
93
  remoteName = 'origin',
74
94
  ): Promise<T> {
95
+ assertUrlHasNoUserInfo(repoUrl);
75
96
  // Lock by local working tree — that's what `git.remote('set-url', ...)`
76
97
  // mutates. Two repo records sharing a `repoUrl` but cloned to different
77
98
  // paths can run in parallel safely; conversely, two repos pointed at the
@@ -108,6 +129,7 @@ export async function withAuth<T>(
108
129
  }
109
130
 
110
131
  function getAuthUrl(repoUrl: string, pat: string, username?: string): string {
132
+ assertUrlHasNoUserInfo(repoUrl);
111
133
  const url = new URL(repoUrl.trim());
112
134
  url.username = (username || 'oauth2').trim();
113
135
  url.password = pat.trim();
@@ -149,8 +171,8 @@ function getGit(ctx: Context, localPath: string): SimpleGit {
149
171
  return createGit(localPath);
150
172
  }
151
173
 
152
- async function getRepo(ctx: Context) {
153
- const { repositoryId } = ctx.action.params;
174
+ export async function getRepo(ctx: Context) {
175
+ const { repositoryId } = getGitActionParams(ctx);
154
176
  const repo = await ctx.db.getRepository('gitRepositories').findOne({
155
177
  filterByTk: repositoryId,
156
178
  });
@@ -274,7 +296,7 @@ export async function fetch(ctx: Context, next: () => Promise<void>) {
274
296
  export async function diff(ctx: Context, next: () => Promise<void>) {
275
297
  const repo = await getRepo(ctx);
276
298
  const localPath = validateLocalPath(repo.get('localPath'));
277
- const { file, commitHash, compareHash } = ctx.action.params;
299
+ const { file, commitHash, compareHash } = getGitActionParams(ctx);
278
300
 
279
301
  const git = getGit(ctx, localPath);
280
302
  const args: string[] = [];
@@ -304,9 +326,9 @@ export async function status(ctx: Context, next: () => Promise<void>) {
304
326
  export async function log(ctx: Context, next: () => Promise<void>) {
305
327
  const repo = await getRepo(ctx);
306
328
  const localPath = validateLocalPath(repo.get('localPath'));
307
- const { maxCount = 50, file } = ctx.action.params;
329
+ const { maxCount = 50, file } = getGitActionParams(ctx);
308
330
 
309
- const parsed = parseInt(maxCount, 10);
331
+ const parsed = Number.parseInt(String(maxCount), 10);
310
332
  const options: Record<string, any> = { maxCount: Math.min(Math.max(parsed || 50, 1), 500) };
311
333
  if (file) {
312
334
  if (file.includes('..')) ctx.throw(400, 'Invalid file path');
@@ -329,7 +351,8 @@ export async function branches(ctx: Context, next: () => Promise<void>) {
329
351
  export async function checkout(ctx: Context, next: () => Promise<void>) {
330
352
  const repo = await getRepo(ctx);
331
353
  const localPath = validateLocalPath(repo.get('localPath'));
332
- const { branch } = ctx.action.params;
354
+ const { branch } = getGitActionParams(ctx);
355
+ if (!branch) ctx.throw(400, 'branch is required');
333
356
  validateBranch(branch);
334
357
  await getGit(ctx, localPath).checkout(branch);
335
358
  ctx.body = { success: true, message: `Switched to branch ${branch}` };
@@ -339,7 +362,7 @@ export async function checkout(ctx: Context, next: () => Promise<void>) {
339
362
  export async function fileTree(ctx: Context, next: () => Promise<void>) {
340
363
  const repo = await getRepo(ctx);
341
364
  const localPath = validateLocalPath(repo.get('localPath'));
342
- const { ref = 'HEAD', treePath = '', recursive } = ctx.action.params;
365
+ const { ref = 'HEAD', treePath = '', recursive } = getGitActionParams(ctx);
343
366
 
344
367
  const git = getGit(ctx, localPath);
345
368
  validateRef(ref);
@@ -388,7 +411,7 @@ export async function fileTree(ctx: Context, next: () => Promise<void>) {
388
411
  export async function fileContent(ctx: Context, next: () => Promise<void>) {
389
412
  const repo = await getRepo(ctx);
390
413
  const localPath = validateLocalPath(repo.get('localPath'));
391
- const { ref = 'HEAD', filePath } = ctx.action.params;
414
+ const { ref = 'HEAD', filePath } = getGitActionParams(ctx);
392
415
 
393
416
  if (!filePath) {
394
417
  ctx.throw(400, 'filePath is required');
@@ -407,7 +430,7 @@ export async function fileContent(ctx: Context, next: () => Promise<void>) {
407
430
  export async function commitDetail(ctx: Context, next: () => Promise<void>) {
408
431
  const repo = await getRepo(ctx);
409
432
  const localPath = validateLocalPath(repo.get('localPath'));
410
- const { commitHash } = ctx.action.params;
433
+ const { commitHash } = getGitActionParams(ctx);
411
434
 
412
435
  if (!commitHash) {
413
436
  ctx.throw(400, 'commitHash is required');
@@ -1,11 +1,8 @@
1
1
  import { Context } from '@nocobase/actions';
2
+ import { getEffectiveActionParams } from '../repository-access';
2
3
  import { parseGitLabProject } from '../utils/gitlab-url';
3
4
  import { getRepoAccount } from '../utils/get-repo-account';
4
5
 
5
- function getActionParams(ctx: Context) {
6
- return { ...ctx.action.params, ...ctx.action.params?.values, ...((ctx as any).request?.body || {}) };
7
- }
8
-
9
6
  async function gitlabFetch(apiBase: string, endpoint: string, pat: string, params?: Record<string, any>) {
10
7
  const url = new URL(`${apiBase}${endpoint}`);
11
8
  if (params) {
@@ -38,7 +35,7 @@ async function gitlabFetch(apiBase: string, endpoint: string, pat: string, param
38
35
 
39
36
  async function getRepoApiContext(ctx: Context) {
40
37
  // Fix for POST requests where data might be in ctx.request.body
41
- const params = getActionParams(ctx);
38
+ const params = getEffectiveActionParams(ctx);
42
39
  const { repositoryId } = params;
43
40
 
44
41
  const repo = await ctx.db.getRepository('gitRepositories').findOne({
@@ -97,7 +94,7 @@ async function githubFetch(endpoint: string, pat: string, params?: Record<string
97
94
  export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
98
95
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
99
96
  // Merge params from query and body
100
- const params = getActionParams(ctx);
97
+ const params = getEffectiveActionParams(ctx);
101
98
  const { state = 'opened', search, page = 1, perPage = 20, orderBy = 'updated_at', sort = 'desc' } = params;
102
99
 
103
100
  let result;
@@ -221,7 +218,7 @@ export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
221
218
 
222
219
  export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>) {
223
220
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
224
- const params = getActionParams(ctx);
221
+ const params = getEffectiveActionParams(ctx);
225
222
  const { mrIid } = params;
226
223
 
227
224
  if (!mrIid) {
@@ -351,7 +348,7 @@ export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>
351
348
 
352
349
  export async function mergeRequestNotes(ctx: Context, next: () => Promise<void>) {
353
350
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
354
- const params = getActionParams(ctx);
351
+ const params = getEffectiveActionParams(ctx);
355
352
  const { mrIid, page = 1, perPage = 50 } = params;
356
353
 
357
354
  if (!mrIid) {
@@ -1,5 +1,6 @@
1
1
  import { Context } from '@nocobase/actions';
2
2
  import { pollAllRepos, pollOneRepo, getPollerStatus } from '../poller';
3
+ import { getEffectiveActionParams } from '../repository-access';
3
4
 
4
5
  /**
5
6
  * Manually trigger a poll cycle. If repositoryId is provided, only that repo
@@ -7,7 +8,7 @@ import { pollAllRepos, pollOneRepo, getPollerStatus } from '../poller';
7
8
  * with autoReview=true.
8
9
  */
9
10
  export async function pollNow(ctx: Context, next: () => Promise<void>) {
10
- const { repositoryId } = ctx.action.params;
11
+ const { repositoryId } = getEffectiveActionParams(ctx);
11
12
  if (repositoryId) {
12
13
  const repo = await ctx.db.getRepository('gitRepositories').findOne({ filterByTk: repositoryId });
13
14
  if (!repo) ctx.throw(404, 'Repository not found');
@@ -1,5 +1,6 @@
1
1
  import { Context } from '@nocobase/actions';
2
2
  import type { Application } from '@nocobase/server';
3
+ import { getEffectiveActionParams } from '../repository-access';
3
4
  import { parseGitLabProject } from '../utils/gitlab-url';
4
5
  import { redactPat } from '../utils/redact';
5
6
  import { getRepoAccount } from '../utils/get-repo-account';
@@ -74,10 +75,6 @@ let reviewQueueKickTimer: NodeJS.Timeout | null = null;
74
75
  let reviewQueueProcessing = false;
75
76
  let reviewWakeHandler: ((message?: any) => Promise<void>) | null = null;
76
77
 
77
- function getActionParams(ctx: Context) {
78
- return { ...ctx.action.params, ...ctx.action.params?.values, ...((ctx as any).request?.body || {}) };
79
- }
80
-
81
78
  /**
82
79
  * Per-target mutex to prevent two concurrent calls to
83
80
  * `triggerReviewInternal` for the same MR / commit / branch from racing
@@ -112,7 +109,7 @@ async function withTriggerLock<T>(app: Application, key: string, fn: () => Promi
112
109
  * git-review worker. The action returns immediately with the reviewId.
113
110
  */
114
111
  export async function triggerReview(ctx: Context, next: () => Promise<void>) {
115
- const params = getActionParams(ctx);
112
+ const params = getEffectiveActionParams(ctx);
116
113
  const { flowId, repositoryId, targetType, mrIid, commitSha, branch, folderPath, extraInstructions } = params;
117
114
 
118
115
  if (!repositoryId) ctx.throw(400, 'repositoryId is required');
@@ -165,6 +162,10 @@ async function triggerReviewInternalLocked(app: Application, args: TriggerArgs):
165
162
  flow = await flowsRepo.findOne({ filterByTk: args.flowId });
166
163
  if (!flow) throwHttp(404, 'Review flow not found');
167
164
  if (!flow.get('enabled')) throwHttp(400, 'Review flow is disabled');
165
+ const flowRepositoryId = flow.get('repositoryId');
166
+ if (flowRepositoryId != null && String(flowRepositoryId) !== String(args.repositoryId)) {
167
+ throwHttp(400, 'Review flow does not belong to this repository');
168
+ }
168
169
  } else {
169
170
  // Find flows scoped to repo or global, prefer repo-specific
170
171
  const candidates = await flowsRepo.find({
@@ -213,6 +214,11 @@ async function triggerReviewInternalLocked(app: Application, args: TriggerArgs):
213
214
  const existing = await reviewsRepo.findOne({ filter: targetFilter });
214
215
  // Preserve a poller-tracked latestSha if we don't have a fresher one.
215
216
  const existingLatestSha = existing?.get('latestSha') as string | null | undefined;
217
+ // The actor must be selected from a server-owned field when the worker
218
+ // executes. Refresh it on every manual requeue so an old, more-privileged
219
+ // creator cannot be reused. Poll-triggered reviews deliberately have no
220
+ // user and retain the established system/admin worker behavior.
221
+ const queuedActorId = args.triggeredBy === 'poll' ? null : args.userId ?? null;
216
222
  const baseValues: any = {
217
223
  flowId: flow.get('id'),
218
224
  repositoryId: args.repositoryId,
@@ -254,11 +260,21 @@ async function triggerReviewInternalLocked(app: Application, args: TriggerArgs):
254
260
  }
255
261
  await reviewsRepo.update({
256
262
  filterByTk: existing.get('id'),
257
- values: baseValues,
263
+ values: {
264
+ ...baseValues,
265
+ createdById: queuedActorId,
266
+ },
258
267
  });
259
268
  reviewId = existing.get('id') as number;
260
269
  } else {
261
- const review = await reviewsRepo.create({ values: baseValues });
270
+ const review = await reviewsRepo.create({
271
+ values: {
272
+ ...baseValues,
273
+ // The worker later derives its acting user from this server-owned
274
+ // field rather than mutable review metadata.
275
+ createdById: queuedActorId,
276
+ },
277
+ });
262
278
  reviewId = review.get('id') as number;
263
279
  }
264
280
 
@@ -494,6 +510,26 @@ function getQueuedReviewMetadata(review: any): QueuedReviewMetadata {
494
510
  return typeof raw === 'object' ? raw : {};
495
511
  }
496
512
 
513
+ type ReviewRecord = {
514
+ get(attribute: string): unknown;
515
+ };
516
+
517
+ /**
518
+ * A queued review's metadata can be changed by database mutations, so it must
519
+ * never select the user whose roles the background AI run receives. The
520
+ * server-owned field is refreshed only by the trusted queueing path.
521
+ */
522
+ export function resolveImmutableReviewActorId(review: ReviewRecord): number | string | null {
523
+ const createdById = review.get('createdById');
524
+ if (typeof createdById === 'number' && Number.isFinite(createdById)) {
525
+ return createdById;
526
+ }
527
+ if (typeof createdById === 'string' && createdById.trim()) {
528
+ return createdById;
529
+ }
530
+ return null;
531
+ }
532
+
497
533
  function toNullableNumber(value: any): number | null {
498
534
  if (value === null || value === undefined || value === '') return null;
499
535
  const parsed = Number(value);
@@ -605,6 +641,11 @@ async function processQueuedReview(app: Application, message: ReviewQueueMessage
605
641
  const targetType = (message.targetType || review.get('targetType')) as 'mr' | 'commit' | 'branch' | 'folder';
606
642
 
607
643
  try {
644
+ const actorUserId = resolveImmutableReviewActorId(review);
645
+ if (actorUserId == null && review.get('triggeredBy') !== 'poll') {
646
+ throw new Error('Manual review has no immutable triggering user');
647
+ }
648
+
608
649
  const repo = await db.getRepository('gitRepositories').findOne({
609
650
  filterByTk: message.repositoryId || review.get('repositoryId'),
610
651
  });
@@ -614,6 +655,11 @@ async function processQueuedReview(app: Application, message: ReviewQueueMessage
614
655
  const storedFlow = await db.getRepository('gitReviewFlows').findOne({
615
656
  filterByTk: flowSnapshot?.id || review.get('flowId'),
616
657
  });
658
+ if (!storedFlow) throw new Error('Review flow not found');
659
+ const flowRepositoryId = storedFlow.get('repositoryId');
660
+ if (flowRepositoryId != null && String(flowRepositoryId) !== String(repo.get('id'))) {
661
+ throw new Error('Review flow does not belong to this repository');
662
+ }
617
663
  const flow = createFlowFromSnapshot(flowSnapshot, storedFlow);
618
664
  const aiEmployeeUsername =
619
665
  message.aiEmployeeUsername || metadata.aiEmployeeUsername || (flow.get('aiEmployeeUsername') as string);
@@ -632,7 +678,7 @@ async function processQueuedReview(app: Application, message: ReviewQueueMessage
632
678
  headSha: message.headSha || (review.get('headSha') as string | null),
633
679
  aiEmployeeUsername,
634
680
  extraInstructions: message.extraInstructions ?? metadata.extraInstructions ?? undefined,
635
- userId: message.userId ?? metadata.userId ?? null,
681
+ userId: actorUserId,
636
682
  });
637
683
  } catch (err) {
638
684
  app.log?.error?.('git review queue: failed before review execution', err);
@@ -645,7 +691,7 @@ async function processQueuedReview(app: Application, message: ReviewQueueMessage
645
691
  * Mark a review as approved and post its content to GitLab as an MR note.
646
692
  */
647
693
  export async function reviewApprovePost(ctx: Context, next: () => Promise<void>) {
648
- const params = getActionParams(ctx);
694
+ const params = getEffectiveActionParams(ctx);
649
695
  const { reviewId, editedMarkdown } = params;
650
696
  if (!reviewId) ctx.throw(400, 'reviewId is required');
651
697
 
@@ -686,7 +732,7 @@ export async function reviewApprovePost(ctx: Context, next: () => Promise<void>)
686
732
  * Reject a pending review (do not post to GitLab).
687
733
  */
688
734
  export async function reviewReject(ctx: Context, next: () => Promise<void>) {
689
- const params = getActionParams(ctx);
735
+ const params = getEffectiveActionParams(ctx);
690
736
  const { reviewId, reason } = params;
691
737
  if (!reviewId) ctx.throw(400, 'reviewId is required');
692
738
 
@@ -944,13 +990,24 @@ async function runReview(app: Application, args: RunReviewArgs) {
944
990
  }
945
991
  }
946
992
 
947
- async function resolveBackgroundReviewRoles(db: any, userId?: number | string | null): Promise<string[]> {
993
+ type BackgroundReviewRoleRepository = {
994
+ find(input: { filter?: { userId: number | string }; raw: true }): Promise<unknown>;
995
+ };
996
+
997
+ type BackgroundReviewRoleDatabase = {
998
+ getRepository(name: 'users.roles' | 'rolesUsers', sourceKey?: number | string): BackgroundReviewRoleRepository;
999
+ };
1000
+
1001
+ export async function resolveBackgroundReviewRoles(
1002
+ db: BackgroundReviewRoleDatabase,
1003
+ userId?: number | string | null,
1004
+ ): Promise<string[]> {
948
1005
  if (!userId) return ['admin'];
949
1006
 
950
1007
  try {
951
1008
  const roles = await db.getRepository('users.roles', userId).find({ raw: true });
952
1009
  const roleNames = (Array.isArray(roles) ? roles : [])
953
- .map((role: any) => role?.name)
1010
+ .map((role: unknown) => (role && typeof role === 'object' ? (role as { name?: unknown }).name : undefined))
954
1011
  .filter((name: unknown): name is string => typeof name === 'string' && !!name);
955
1012
  if (roleNames.length) return roleNames;
956
1013
  } catch {
@@ -964,14 +1021,16 @@ async function resolveBackgroundReviewRoles(db: any, userId?: number | string |
964
1021
  raw: true,
965
1022
  });
966
1023
  const roleNames = (Array.isArray(mappings) ? mappings : [])
967
- .map((mapping: any) => mapping?.roleName)
1024
+ .map((mapping: unknown) =>
1025
+ mapping && typeof mapping === 'object' ? (mapping as { roleName?: unknown }).roleName : undefined,
1026
+ )
968
1027
  .filter((name: unknown): name is string => typeof name === 'string' && !!name);
969
1028
  if (roleNames.length) return roleNames;
970
1029
  } catch {
971
- // Keep the synthetic ctx valid even if role lookup is unavailable.
1030
+ // The manual actor must not inherit an administrative fallback.
972
1031
  }
973
1032
 
974
- return ['admin'];
1033
+ throw new Error('Unable to resolve roles for review actor');
975
1034
  }
976
1035
 
977
1036
  function buildReviewPrompt(args: RunReviewArgs): string {