plugin-git-manager 1.2.23 → 1.2.24

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 (45) hide show
  1. package/dist/externalVersion.js +8 -8
  2. package/dist/locale/en-US.json +4 -3
  3. package/dist/locale/vi-VN.json +4 -3
  4. package/dist/locale/zh-CN.json +4 -3
  5. package/dist/server/actions/git-actions.js +21 -8
  6. package/dist/server/actions/gitlab-api.js +5 -8
  7. package/dist/server/actions/poller.js +2 -1
  8. package/dist/server/actions/review.js +50 -13
  9. package/dist/server/actions/role-permissions.js +109 -16
  10. package/dist/server/actions/subtree.js +4 -8
  11. package/dist/server/migrations/20260730000000-migrate-legacy-repository-permissions.js +23 -7
  12. package/dist/server/plugin.js +42 -19
  13. package/dist/server/repository-access.js +505 -27
  14. package/dist/server/services/registry-content-service.js +137 -22
  15. package/dist/server/utils/get-repo-account.js +5 -2
  16. package/dist/server/utils/gitlab-url.js +2 -0
  17. package/dist/server/utils/redact.js +51 -5
  18. package/dist/server/utils/url-security.js +109 -0
  19. package/package.json +1 -1
  20. package/src/locale/en-US.json +4 -3
  21. package/src/locale/vi-VN.json +4 -3
  22. package/src/locale/zh-CN.json +4 -3
  23. package/src/server/__tests__/git-actions.test.ts +24 -0
  24. package/src/server/__tests__/plugin-url-security.test.ts +17 -0
  25. package/src/server/__tests__/poller.test.ts +37 -0
  26. package/src/server/__tests__/repository-access.test.ts +695 -1
  27. package/src/server/__tests__/review.test.ts +137 -0
  28. package/src/server/__tests__/role-permissions.test.ts +123 -2
  29. package/src/server/actions/git-actions.ts +33 -10
  30. package/src/server/actions/gitlab-api.ts +5 -8
  31. package/src/server/actions/poller.ts +2 -1
  32. package/src/server/actions/review.ts +74 -15
  33. package/src/server/actions/role-permissions.ts +136 -14
  34. package/src/server/actions/subtree.ts +4 -8
  35. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +23 -8
  36. package/src/server/plugin.ts +46 -25
  37. package/src/server/repository-access.ts +737 -28
  38. package/src/server/services/__tests__/registry-content-service.test.ts +209 -13
  39. package/src/server/services/registry-content-service.ts +184 -30
  40. package/src/server/utils/__tests__/redact.test.ts +56 -0
  41. package/src/server/utils/__tests__/url-security.test.ts +85 -0
  42. package/src/server/utils/get-repo-account.ts +22 -4
  43. package/src/server/utils/gitlab-url.ts +3 -0
  44. package/src/server/utils/redact.ts +68 -5
  45. package/src/server/utils/url-security.ts +95 -0
@@ -11,14 +11,14 @@ module.exports = {
11
11
  "react": "18.2.0",
12
12
  "antd": "5.24.2",
13
13
  "@ant-design/icons": "5.6.1",
14
- "@nocobase/client": "2.1.30",
15
- "@nocobase/plugin-acl": "2.1.30",
16
- "@nocobase/client-v2": "2.1.30",
17
- "@nocobase/flow-engine": "2.1.30",
18
- "@nocobase/server": "2.1.30",
19
- "@nocobase/database": "2.1.30",
14
+ "@nocobase/client": "2.1.32",
15
+ "@nocobase/plugin-acl": "2.1.32",
16
+ "@nocobase/client-v2": "2.1.32",
17
+ "@nocobase/flow-engine": "2.1.32",
18
+ "@nocobase/server": "2.1.32",
19
+ "@nocobase/database": "2.1.32",
20
20
  "sequelize": "6.35.2",
21
21
  "dayjs": "1.11.13",
22
- "@nocobase/plugin-ai": "2.1.30",
23
- "@nocobase/actions": "2.1.30"
22
+ "@nocobase/plugin-ai": "2.1.32",
23
+ "@nocobase/actions": "2.1.32"
24
24
  };
@@ -290,7 +290,8 @@
290
290
  "Policy": "Policy",
291
291
  "Split SHA": "Split SHA",
292
292
  "Target before": "Target before",
293
- "Target after": "Target after"
294
- ,"Execution mode": "Execution mode"
295
- ,"App process": "App process"
293
+ "Target after": "Target after",
294
+ "Execution mode": "Execution mode",
295
+ "App process": "App process",
296
+ "Credential-bearing URLs are not allowed": "Credential-bearing URLs are not allowed"
296
297
  }
@@ -285,7 +285,8 @@
285
285
  "Policy": "Chính sách",
286
286
  "Split SHA": "SHA subtree",
287
287
  "Target before": "Nhánh đích trước đó",
288
- "Target after": "Nhánh đích sau đó"
289
- ,"Execution mode": "Chế độ thực thi"
290
- ,"App process": "App process"
288
+ "Target after": "Nhánh đích sau đó",
289
+ "Execution mode": "Chế độ thực thi",
290
+ "App process": "App process",
291
+ "Credential-bearing URLs are not allowed": "URL không được chứa tên người dùng hoặc thông tin xác thực"
291
292
  }
@@ -44,7 +44,8 @@
44
44
  "Split SHA": "拆分 SHA",
45
45
  "Target before": "更新前目标",
46
46
  "Target after": "更新后目标",
47
- "Error": "错误"
48
- ,"Execution mode": "执行模式"
49
- ,"App process": "应用进程"
47
+ "Error": "错误",
48
+ "Execution mode": "执行模式",
49
+ "App process": "应用进程",
50
+ "Credential-bearing URLs are not allowed": "URL 中不允许包含用户名或凭据"
50
51
  }
@@ -47,6 +47,7 @@ __export(git_actions_exports, {
47
47
  fileContent: () => fileContent,
48
48
  fileTree: () => fileTree,
49
49
  getGitBinaryPath: () => getGitBinaryPath,
50
+ getRepo: () => getRepo,
50
51
  log: () => log,
51
52
  pull: () => pull,
52
53
  push: () => push,
@@ -54,6 +55,7 @@ __export(git_actions_exports, {
54
55
  validateBranch: () => validateBranch,
55
56
  validateLocalPath: () => validateLocalPath,
56
57
  validateRef: () => validateRef,
58
+ validateRepoUrl: () => validateRepoUrl,
57
59
  withAuth: () => withAuth
58
60
  });
59
61
  module.exports = __toCommonJS(git_actions_exports);
@@ -61,12 +63,17 @@ var import_simple_git = __toESM(require("simple-git"));
61
63
  var path = __toESM(require("path"));
62
64
  var fs = __toESM(require("fs"));
63
65
  var import_child_process = require("child_process");
66
+ var import_repository_access = require("../repository-access");
64
67
  var import_redact = require("../utils/redact");
65
68
  var import_get_repo_account = require("../utils/get-repo-account");
69
+ var import_url_security = require("../utils/url-security");
66
70
  const REF_PATTERN = /^(?!-)[a-zA-Z0-9._/-]+$/;
67
71
  const repoLocks = /* @__PURE__ */ new Map();
68
72
  const GIT_BINARY = process.env.GIT_BINARY_PATH || process.env.GIT_EXECUTABLE || "git";
69
73
  let gitAvailabilityChecked = false;
74
+ function getGitActionParams(ctx) {
75
+ return (0, import_repository_access.getEffectiveActionParams)(ctx);
76
+ }
70
77
  function acquireLock(key) {
71
78
  const prev = repoLocks.get(key) || Promise.resolve();
72
79
  let release = () => {
@@ -93,6 +100,7 @@ function validateBranch(branch) {
93
100
  return branch;
94
101
  }
95
102
  function validateRepoUrl(repoUrl) {
103
+ (0, import_url_security.assertUrlHasNoUserInfo)(repoUrl);
96
104
  let parsed;
97
105
  try {
98
106
  parsed = new URL(repoUrl);
@@ -104,6 +112,7 @@ function validateRepoUrl(repoUrl) {
104
112
  }
105
113
  }
106
114
  async function withAuth(git, localPath, repoUrl, pat, fn, username, remoteName = "origin") {
115
+ (0, import_url_security.assertUrlHasNoUserInfo)(repoUrl);
107
116
  const lockKey = localPath;
108
117
  const lock = acquireLock(lockKey);
109
118
  await lock.promise;
@@ -130,6 +139,7 @@ async function withAuth(git, localPath, repoUrl, pat, fn, username, remoteName =
130
139
  }
131
140
  }
132
141
  function getAuthUrl(repoUrl, pat, username) {
142
+ (0, import_url_security.assertUrlHasNoUserInfo)(repoUrl);
133
143
  const url = new URL(repoUrl.trim());
134
144
  url.username = (username || "oauth2").trim();
135
145
  url.password = pat.trim();
@@ -164,7 +174,7 @@ function getGit(ctx, localPath) {
164
174
  return createGit(localPath);
165
175
  }
166
176
  async function getRepo(ctx) {
167
- const { repositoryId } = ctx.action.params;
177
+ const { repositoryId } = getGitActionParams(ctx);
168
178
  const repo = await ctx.db.getRepository("gitRepositories").findOne({
169
179
  filterByTk: repositoryId
170
180
  });
@@ -259,7 +269,7 @@ async function fetch(ctx, next) {
259
269
  async function diff(ctx, next) {
260
270
  const repo = await getRepo(ctx);
261
271
  const localPath = validateLocalPath(repo.get("localPath"));
262
- const { file, commitHash, compareHash } = ctx.action.params;
272
+ const { file, commitHash, compareHash } = getGitActionParams(ctx);
263
273
  const git = getGit(ctx, localPath);
264
274
  const args = [];
265
275
  if (commitHash && compareHash) {
@@ -285,8 +295,8 @@ async function status(ctx, next) {
285
295
  async function log(ctx, next) {
286
296
  const repo = await getRepo(ctx);
287
297
  const localPath = validateLocalPath(repo.get("localPath"));
288
- const { maxCount = 50, file } = ctx.action.params;
289
- const parsed = parseInt(maxCount, 10);
298
+ const { maxCount = 50, file } = getGitActionParams(ctx);
299
+ const parsed = Number.parseInt(String(maxCount), 10);
290
300
  const options = { maxCount: Math.min(Math.max(parsed || 50, 1), 500) };
291
301
  if (file) {
292
302
  if (file.includes("..")) ctx.throw(400, "Invalid file path");
@@ -306,7 +316,8 @@ async function branches(ctx, next) {
306
316
  async function checkout(ctx, next) {
307
317
  const repo = await getRepo(ctx);
308
318
  const localPath = validateLocalPath(repo.get("localPath"));
309
- const { branch } = ctx.action.params;
319
+ const { branch } = getGitActionParams(ctx);
320
+ if (!branch) ctx.throw(400, "branch is required");
310
321
  validateBranch(branch);
311
322
  await getGit(ctx, localPath).checkout(branch);
312
323
  ctx.body = { success: true, message: `Switched to branch ${branch}` };
@@ -315,7 +326,7 @@ async function checkout(ctx, next) {
315
326
  async function fileTree(ctx, next) {
316
327
  const repo = await getRepo(ctx);
317
328
  const localPath = validateLocalPath(repo.get("localPath"));
318
- const { ref = "HEAD", treePath = "", recursive } = ctx.action.params;
329
+ const { ref = "HEAD", treePath = "", recursive } = getGitActionParams(ctx);
319
330
  const git = getGit(ctx, localPath);
320
331
  validateRef(ref);
321
332
  if (treePath && treePath.includes("..")) {
@@ -351,7 +362,7 @@ async function fileTree(ctx, next) {
351
362
  async function fileContent(ctx, next) {
352
363
  const repo = await getRepo(ctx);
353
364
  const localPath = validateLocalPath(repo.get("localPath"));
354
- const { ref = "HEAD", filePath } = ctx.action.params;
365
+ const { ref = "HEAD", filePath } = getGitActionParams(ctx);
355
366
  if (!filePath) {
356
367
  ctx.throw(400, "filePath is required");
357
368
  }
@@ -367,7 +378,7 @@ async function fileContent(ctx, next) {
367
378
  async function commitDetail(ctx, next) {
368
379
  const repo = await getRepo(ctx);
369
380
  const localPath = validateLocalPath(repo.get("localPath"));
370
- const { commitHash } = ctx.action.params;
381
+ const { commitHash } = getGitActionParams(ctx);
371
382
  if (!commitHash) {
372
383
  ctx.throw(400, "commitHash is required");
373
384
  }
@@ -419,6 +430,7 @@ async function commitDetail(ctx, next) {
419
430
  fileContent,
420
431
  fileTree,
421
432
  getGitBinaryPath,
433
+ getRepo,
422
434
  log,
423
435
  pull,
424
436
  push,
@@ -426,5 +438,6 @@ async function commitDetail(ctx, next) {
426
438
  validateBranch,
427
439
  validateLocalPath,
428
440
  validateRef,
441
+ validateRepoUrl,
429
442
  withAuth
430
443
  });
@@ -31,12 +31,9 @@ __export(gitlab_api_exports, {
31
31
  mergeRequests: () => mergeRequests
32
32
  });
33
33
  module.exports = __toCommonJS(gitlab_api_exports);
34
+ var import_repository_access = require("../repository-access");
34
35
  var import_gitlab_url = require("../utils/gitlab-url");
35
36
  var import_get_repo_account = require("../utils/get-repo-account");
36
- function getActionParams(ctx) {
37
- var _a, _b;
38
- return { ...ctx.action.params, ...(_a = ctx.action.params) == null ? void 0 : _a.values, ...((_b = ctx.request) == null ? void 0 : _b.body) || {} };
39
- }
40
37
  async function gitlabFetch(apiBase, endpoint, pat, params) {
41
38
  const url = new URL(`${apiBase}${endpoint}`);
42
39
  if (params) {
@@ -62,7 +59,7 @@ async function gitlabFetch(apiBase, endpoint, pat, params) {
62
59
  return { data, totalPages: totalPages ? parseInt(totalPages, 10) : null, total: total ? parseInt(total, 10) : null };
63
60
  }
64
61
  async function getRepoApiContext(ctx) {
65
- const params = getActionParams(ctx);
62
+ const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
66
63
  const { repositoryId } = params;
67
64
  const repo = await ctx.db.getRepository("gitRepositories").findOne({
68
65
  filterByTk: repositoryId
@@ -111,7 +108,7 @@ async function githubFetch(endpoint, pat, params) {
111
108
  }
112
109
  async function mergeRequests(ctx, next) {
113
110
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
114
- const params = getActionParams(ctx);
111
+ const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
115
112
  const { state = "opened", search, page = 1, perPage = 20, orderBy = "updated_at", sort = "desc" } = params;
116
113
  let result;
117
114
  let items;
@@ -226,7 +223,7 @@ async function mergeRequests(ctx, next) {
226
223
  async function mergeRequestDetail(ctx, next) {
227
224
  var _a, _b, _c;
228
225
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
229
- const params = getActionParams(ctx);
226
+ const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
230
227
  const { mrIid } = params;
231
228
  if (!mrIid) {
232
229
  ctx.throw(400, "mrIid is required");
@@ -342,7 +339,7 @@ async function mergeRequestDetail(ctx, next) {
342
339
  }
343
340
  async function mergeRequestNotes(ctx, next) {
344
341
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
345
- const params = getActionParams(ctx);
342
+ const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
346
343
  const { mrIid, page = 1, perPage = 50 } = params;
347
344
  if (!mrIid) {
348
345
  ctx.throw(400, "mrIid is required");
@@ -31,8 +31,9 @@ __export(poller_exports, {
31
31
  });
32
32
  module.exports = __toCommonJS(poller_exports);
33
33
  var import_poller = require("../poller");
34
+ var import_repository_access = require("../repository-access");
34
35
  async function pollNow(ctx, next) {
35
- const { repositoryId } = ctx.action.params;
36
+ const { repositoryId } = (0, import_repository_access.getEffectiveActionParams)(ctx);
36
37
  if (repositoryId) {
37
38
  const repo = await ctx.db.getRepository("gitRepositories").findOne({ filterByTk: repositoryId });
38
39
  if (!repo) ctx.throw(404, "Repository not found");
@@ -31,6 +31,8 @@ __export(review_exports, {
31
31
  pickFlowMatchingBranch: () => pickFlowMatchingBranch,
32
32
  recoverStuckReviews: () => recoverStuckReviews,
33
33
  registerReviewQueue: () => registerReviewQueue,
34
+ resolveBackgroundReviewRoles: () => resolveBackgroundReviewRoles,
35
+ resolveImmutableReviewActorId: () => resolveImmutableReviewActorId,
34
36
  reviewApprovePost: () => reviewApprovePost,
35
37
  reviewReject: () => reviewReject,
36
38
  triggerReview: () => triggerReview,
@@ -38,6 +40,7 @@ __export(review_exports, {
38
40
  unregisterReviewQueue: () => unregisterReviewQueue
39
41
  });
40
42
  module.exports = __toCommonJS(review_exports);
43
+ var import_repository_access = require("../repository-access");
41
44
  var import_gitlab_url = require("../utils/gitlab-url");
42
45
  var import_redact = require("../utils/redact");
43
46
  var import_get_repo_account = require("../utils/get-repo-account");
@@ -63,10 +66,6 @@ let reviewQueueTimer = null;
63
66
  let reviewQueueKickTimer = null;
64
67
  let reviewQueueProcessing = false;
65
68
  let reviewWakeHandler = null;
66
- function getActionParams(ctx) {
67
- var _a, _b;
68
- return { ...ctx.action.params, ...(_a = ctx.action.params) == null ? void 0 : _a.values, ...((_b = ctx.request) == null ? void 0 : _b.body) || {} };
69
- }
70
69
  function targetKey(args) {
71
70
  if (args.targetType === "mr") return `${args.repositoryId}:mr:${args.mrIid}`;
72
71
  if (args.targetType === "commit") return `${args.repositoryId}:commit:${args.commitSha}`;
@@ -82,7 +81,7 @@ async function withTriggerLock(app, key, fn) {
82
81
  }
83
82
  async function triggerReview(ctx, next) {
84
83
  var _a, _b;
85
- const params = getActionParams(ctx);
84
+ const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
86
85
  const { flowId, repositoryId, targetType, mrIid, commitSha, branch, folderPath, extraInstructions } = params;
87
86
  if (!repositoryId) ctx.throw(400, "repositoryId is required");
88
87
  if (!targetType) ctx.throw(400, "targetType is required");
@@ -125,6 +124,10 @@ async function triggerReviewInternalLocked(app, args) {
125
124
  flow = await flowsRepo.findOne({ filterByTk: args.flowId });
126
125
  if (!flow) throwHttp(404, "Review flow not found");
127
126
  if (!flow.get("enabled")) throwHttp(400, "Review flow is disabled");
127
+ const flowRepositoryId = flow.get("repositoryId");
128
+ if (flowRepositoryId != null && String(flowRepositoryId) !== String(args.repositoryId)) {
129
+ throwHttp(400, "Review flow does not belong to this repository");
130
+ }
128
131
  } else {
129
132
  const candidates = await flowsRepo.find({
130
133
  filter: {
@@ -161,6 +164,7 @@ async function triggerReviewInternalLocked(app, args) {
161
164
  }
162
165
  const existing = await reviewsRepo.findOne({ filter: targetFilter });
163
166
  const existingLatestSha = existing == null ? void 0 : existing.get("latestSha");
167
+ const queuedActorId = args.triggeredBy === "poll" ? null : args.userId ?? null;
164
168
  const baseValues = {
165
169
  flowId: flow.get("id"),
166
170
  repositoryId: args.repositoryId,
@@ -196,11 +200,21 @@ async function triggerReviewInternalLocked(app, args) {
196
200
  }
197
201
  await reviewsRepo.update({
198
202
  filterByTk: existing.get("id"),
199
- values: baseValues
203
+ values: {
204
+ ...baseValues,
205
+ createdById: queuedActorId
206
+ }
200
207
  });
201
208
  reviewId = existing.get("id");
202
209
  } else {
203
- const review = await reviewsRepo.create({ values: baseValues });
210
+ const review = await reviewsRepo.create({
211
+ values: {
212
+ ...baseValues,
213
+ // The worker later derives its acting user from this server-owned
214
+ // field rather than mutable review metadata.
215
+ createdById: queuedActorId
216
+ }
217
+ });
204
218
  reviewId = review.get("id");
205
219
  }
206
220
  await enqueueReview(app, {
@@ -420,6 +434,16 @@ function getQueuedReviewMetadata(review) {
420
434
  }
421
435
  return typeof raw === "object" ? raw : {};
422
436
  }
437
+ function resolveImmutableReviewActorId(review) {
438
+ const createdById = review.get("createdById");
439
+ if (typeof createdById === "number" && Number.isFinite(createdById)) {
440
+ return createdById;
441
+ }
442
+ if (typeof createdById === "string" && createdById.trim()) {
443
+ return createdById;
444
+ }
445
+ return null;
446
+ }
423
447
  function toNullableNumber(value) {
424
448
  if (value === null || value === void 0 || value === "") return null;
425
449
  const parsed = Number(value);
@@ -521,6 +545,10 @@ async function processQueuedReview(app, message) {
521
545
  const metadata = getQueuedReviewMetadata(review);
522
546
  const targetType = message.targetType || review.get("targetType");
523
547
  try {
548
+ const actorUserId = resolveImmutableReviewActorId(review);
549
+ if (actorUserId == null && review.get("triggeredBy") !== "poll") {
550
+ throw new Error("Manual review has no immutable triggering user");
551
+ }
524
552
  const repo = await db.getRepository("gitRepositories").findOne({
525
553
  filterByTk: message.repositoryId || review.get("repositoryId")
526
554
  });
@@ -529,6 +557,11 @@ async function processQueuedReview(app, message) {
529
557
  const storedFlow = await db.getRepository("gitReviewFlows").findOne({
530
558
  filterByTk: (flowSnapshot == null ? void 0 : flowSnapshot.id) || review.get("flowId")
531
559
  });
560
+ if (!storedFlow) throw new Error("Review flow not found");
561
+ const flowRepositoryId = storedFlow.get("repositoryId");
562
+ if (flowRepositoryId != null && String(flowRepositoryId) !== String(repo.get("id"))) {
563
+ throw new Error("Review flow does not belong to this repository");
564
+ }
532
565
  const flow = createFlowFromSnapshot(flowSnapshot, storedFlow);
533
566
  const aiEmployeeUsername = message.aiEmployeeUsername || metadata.aiEmployeeUsername || flow.get("aiEmployeeUsername");
534
567
  if (!aiEmployeeUsername) throw new Error("Flow has no AI employee configured");
@@ -544,7 +577,7 @@ async function processQueuedReview(app, message) {
544
577
  headSha: message.headSha || review.get("headSha"),
545
578
  aiEmployeeUsername,
546
579
  extraInstructions: message.extraInstructions ?? metadata.extraInstructions ?? void 0,
547
- userId: message.userId ?? metadata.userId ?? null
580
+ userId: actorUserId
548
581
  });
549
582
  } catch (err) {
550
583
  (_f = (_e = app.log) == null ? void 0 : _e.error) == null ? void 0 : _f.call(_e, "git review queue: failed before review execution", err);
@@ -554,7 +587,7 @@ async function processQueuedReview(app, message) {
554
587
  }
555
588
  async function reviewApprovePost(ctx, next) {
556
589
  var _a, _b;
557
- const params = getActionParams(ctx);
590
+ const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
558
591
  const { reviewId, editedMarkdown } = params;
559
592
  if (!reviewId) ctx.throw(400, "reviewId is required");
560
593
  const reviewsRepo = ctx.db.getRepository("gitCodeReviews");
@@ -586,7 +619,7 @@ async function reviewApprovePost(ctx, next) {
586
619
  }
587
620
  async function reviewReject(ctx, next) {
588
621
  var _a, _b;
589
- const params = getActionParams(ctx);
622
+ const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
590
623
  const { reviewId, reason } = params;
591
624
  if (!reviewId) ctx.throw(400, "reviewId is required");
592
625
  const reviewsRepo = ctx.db.getRepository("gitCodeReviews");
@@ -800,7 +833,7 @@ async function resolveBackgroundReviewRoles(db, userId) {
800
833
  if (!userId) return ["admin"];
801
834
  try {
802
835
  const roles = await db.getRepository("users.roles", userId).find({ raw: true });
803
- const roleNames = (Array.isArray(roles) ? roles : []).map((role) => role == null ? void 0 : role.name).filter((name) => typeof name === "string" && !!name);
836
+ const roleNames = (Array.isArray(roles) ? roles : []).map((role) => role && typeof role === "object" ? role.name : void 0).filter((name) => typeof name === "string" && !!name);
804
837
  if (roleNames.length) return roleNames;
805
838
  } catch {
806
839
  }
@@ -809,11 +842,13 @@ async function resolveBackgroundReviewRoles(db, userId) {
809
842
  filter: { userId },
810
843
  raw: true
811
844
  });
812
- const roleNames = (Array.isArray(mappings) ? mappings : []).map((mapping) => mapping == null ? void 0 : mapping.roleName).filter((name) => typeof name === "string" && !!name);
845
+ const roleNames = (Array.isArray(mappings) ? mappings : []).map(
846
+ (mapping) => mapping && typeof mapping === "object" ? mapping.roleName : void 0
847
+ ).filter((name) => typeof name === "string" && !!name);
813
848
  if (roleNames.length) return roleNames;
814
849
  } catch {
815
850
  }
816
- return ["admin"];
851
+ throw new Error("Unable to resolve roles for review actor");
817
852
  }
818
853
  function buildReviewPrompt(args) {
819
854
  const lines = [];
@@ -1089,6 +1124,8 @@ async function recoverStuckReviews(app) {
1089
1124
  pickFlowMatchingBranch,
1090
1125
  recoverStuckReviews,
1091
1126
  registerReviewQueue,
1127
+ resolveBackgroundReviewRoles,
1128
+ resolveImmutableReviewActorId,
1092
1129
  reviewApprovePost,
1093
1130
  reviewReject,
1094
1131
  triggerReview,
@@ -30,6 +30,8 @@ __export(role_permissions_exports, {
30
30
  GIT_WRITE_ACTIONS: () => GIT_WRITE_ACTIONS,
31
31
  REPOSITORY_READ_ACTIONS: () => REPOSITORY_READ_ACTIONS,
32
32
  getRepositoryPermissionIds: () => getRepositoryPermissionIds,
33
+ getRepositoryPermissionScope: () => getRepositoryPermissionScope,
34
+ repositoryPermissionIdsForDisplay: () => repositoryPermissionIdsForDisplay,
33
35
  rolePermissions: () => rolePermissions,
34
36
  syncScopedActions: () => syncScopedActions,
35
37
  updateRolePermissions: () => updateRolePermissions
@@ -68,20 +70,95 @@ const GIT_WRITE_ACTIONS = [
68
70
  "pollNow",
69
71
  "subtreeRun"
70
72
  ];
71
- function getRepositoryPermissionIds(actions, names) {
72
- var _a, _b, _c;
73
+ function supportedIds(ids) {
74
+ return { ids: new Set(ids), unrestricted: false, supported: true };
75
+ }
76
+ function unsupportedScope() {
77
+ return { ids: /* @__PURE__ */ new Set(), unrestricted: false, supported: false };
78
+ }
79
+ function combineScopeBranches(operator, branches) {
80
+ const resolutions = branches.map(resolveRepositoryScope);
81
+ if (resolutions.some((resolution) => !resolution.supported)) return unsupportedScope();
82
+ if (operator === "$or") {
83
+ if (resolutions.some((resolution) => resolution.unrestricted)) {
84
+ return { ids: /* @__PURE__ */ new Set(), unrestricted: true, supported: true };
85
+ }
86
+ return supportedIds(resolutions.flatMap((resolution) => [...resolution.ids]));
87
+ }
88
+ const restricted = resolutions.filter((resolution) => !resolution.unrestricted);
89
+ if (restricted.length === 0) {
90
+ return { ids: /* @__PURE__ */ new Set(), unrestricted: true, supported: true };
91
+ }
92
+ const [first, ...rest] = restricted;
93
+ const ids = new Set([...first.ids].filter((id) => rest.every((resolution) => resolution.ids.has(id))));
94
+ return supportedIds(ids);
95
+ }
96
+ function resolveRepositoryScope(scope) {
97
+ if (scope == null) {
98
+ return { ids: /* @__PURE__ */ new Set(), unrestricted: true, supported: true };
99
+ }
100
+ if (typeof scope !== "object" || Array.isArray(scope)) return unsupportedScope();
101
+ const condition = scope;
102
+ const keys = Object.keys(condition);
103
+ if (keys.length === 0) {
104
+ return { ids: /* @__PURE__ */ new Set(), unrestricted: true, supported: true };
105
+ }
106
+ const operator = keys.find((key) => key === "$and" || key === "$or");
107
+ if (operator) {
108
+ if (keys.length !== 1 || !Array.isArray(condition[operator])) return unsupportedScope();
109
+ return combineScopeBranches(operator, condition[operator]);
110
+ }
111
+ if (keys.length !== 1 || !("id" in condition)) return unsupportedScope();
112
+ const id = condition.id;
113
+ if (typeof id === "number" || typeof id === "string") {
114
+ return supportedIds([id]);
115
+ }
116
+ if (!id || typeof id !== "object" || Array.isArray(id)) return unsupportedScope();
117
+ const idCondition = id;
118
+ const idKeys = Object.keys(idCondition);
119
+ if (idKeys.length !== 1) return unsupportedScope();
120
+ const equal = idCondition.$eq;
121
+ if (typeof equal === "number" || typeof equal === "string") {
122
+ return supportedIds([equal]);
123
+ }
124
+ const included = idCondition.$in;
125
+ if (Array.isArray(included) && included.every((value) => typeof value === "number" || typeof value === "string")) {
126
+ return supportedIds(included);
127
+ }
128
+ return unsupportedScope();
129
+ }
130
+ function actionScope(actionData) {
131
+ const scopeRow = actionData.scope;
132
+ if (!scopeRow || typeof scopeRow !== "object") return void 0;
133
+ const scopeRecord = scopeRow;
134
+ return "scope" in scopeRecord ? scopeRecord.scope : scopeRecord;
135
+ }
136
+ function getRepositoryPermissionScope(actions, names) {
73
137
  const ids = /* @__PURE__ */ new Set();
138
+ let unrestricted = false;
74
139
  for (const action of actions) {
75
140
  const actionData = action.toJSON();
76
141
  if (typeof actionData.name !== "string" || !names.includes(actionData.name)) continue;
77
- const scopeRow = actionData.scope;
78
- const scope = (scopeRow == null ? void 0 : scopeRow.scope) || scopeRow;
79
- const scopedIds = (_c = (_b = (_a = scope == null ? void 0 : scope.$and) == null ? void 0 : _a[0]) == null ? void 0 : _b.id) == null ? void 0 : _c.$in;
80
- if (Array.isArray(scopedIds)) scopedIds.forEach((id) => ids.add(id));
142
+ const scope = actionScope(actionData);
143
+ const resolution = resolveRepositoryScope(scope);
144
+ if (!resolution.supported) {
145
+ return { ids: [], unrestricted: false, supported: false };
146
+ }
147
+ if (resolution.unrestricted) {
148
+ unrestricted = true;
149
+ continue;
150
+ }
151
+ resolution.ids.forEach((id) => ids.add(id));
81
152
  }
82
- return [...ids];
153
+ return { ids: [...ids], unrestricted, supported: true };
154
+ }
155
+ function getRepositoryPermissionIds(actions, names) {
156
+ return getRepositoryPermissionScope(actions, names).ids;
83
157
  }
84
- async function syncScopedActions(db, resource, actionNames, ids) {
158
+ function repositoryPermissionIdsForDisplay(scope, repositoryIds) {
159
+ return scope.unrestricted ? repositoryIds : scope.ids;
160
+ }
161
+ async function syncScopedActions(db, resource, actionNames, ids, options = {}) {
85
162
  const rolesResourceId = getRecordValue(resource, "id");
86
163
  const actionsRepo = db.getRepository("rolesResourcesActions");
87
164
  for (const storedActionName of actionNames) {
@@ -89,12 +166,12 @@ async function syncScopedActions(db, resource, actionNames, ids) {
89
166
  filter: { rolesResourceId, name: storedActionName },
90
167
  appends: ["scope"]
91
168
  });
92
- if (ids.length === 0) {
93
- if (action) await action.destroy();
94
- continue;
95
- }
96
- const scopeJson = { $and: [{ id: { $in: ids } }] };
97
169
  if (action) {
170
+ if (options.unrestricted) {
171
+ await action.update({ scopeId: null });
172
+ continue;
173
+ }
174
+ const scopeJson = { $and: [{ id: { $in: ids } }] };
98
175
  const actionData = action.toJSON();
99
176
  const actionScopeId = getRecordValue(actionData.scope, "id") || actionData.scopeId || getRecordValue(action, "scopeId");
100
177
  if (actionScopeId) {
@@ -107,6 +184,13 @@ async function syncScopedActions(db, resource, actionNames, ids) {
107
184
  await action.update({ scopeId: getRecordValue(newScope, "id") });
108
185
  }
109
186
  } else {
187
+ if (options.unrestricted) {
188
+ await actionsRepo.create({
189
+ values: { rolesResourceId, name: storedActionName }
190
+ });
191
+ continue;
192
+ }
193
+ const scopeJson = { $and: [{ id: { $in: ids } }] };
110
194
  const newScope = await db.getRepository("rolesResourcesScopes").create({ values: { scope: scopeJson } });
111
195
  await actionsRepo.create({
112
196
  values: { rolesResourceId, name: storedActionName, scopeId: getRecordValue(newScope, "id") }
@@ -141,12 +225,19 @@ async function rolePermissions(ctx, _next) {
141
225
  filter: { rolesResourceId: getRecordValue(gitManagerResource, "id") },
142
226
  appends: ["scope"]
143
227
  }) : [];
228
+ const readScope = getRepositoryPermissionScope(actions, [...REPOSITORY_READ_ACTIONS, "read"]);
229
+ const gitWriteScope = getRepositoryPermissionScope(gitManagerActions, GIT_WRITE_ACTIONS);
230
+ const repositoryWriteScope = getRepositoryPermissionScope(actions, ["write"]);
231
+ const requiresRepositoryList = readScope.unrestricted || gitWriteScope.unrestricted || repositoryWriteScope.unrestricted;
232
+ const repositoryIds = requiresRepositoryList ? (await ctx.db.getRepository("gitRepositories").find({ fields: ["id"] })).map(
233
+ (repository) => getRecordValue(repository, "id")
234
+ ) : [];
144
235
  const result = {
145
- read: getRepositoryPermissionIds(actions, [...REPOSITORY_READ_ACTIONS, "read"]),
236
+ read: repositoryPermissionIdsForDisplay(readScope, repositoryIds),
146
237
  write: [
147
238
  .../* @__PURE__ */ new Set([
148
- ...getRepositoryPermissionIds(gitManagerActions, GIT_WRITE_ACTIONS),
149
- ...getRepositoryPermissionIds(actions, ["write"])
239
+ ...repositoryPermissionIdsForDisplay(gitWriteScope, repositoryIds),
240
+ ...repositoryPermissionIdsForDisplay(repositoryWriteScope, repositoryIds)
150
241
  ])
151
242
  ]
152
243
  };
@@ -209,6 +300,8 @@ async function updateRolePermissions(ctx, _next) {
209
300
  GIT_WRITE_ACTIONS,
210
301
  REPOSITORY_READ_ACTIONS,
211
302
  getRepositoryPermissionIds,
303
+ getRepositoryPermissionScope,
304
+ repositoryPermissionIdsForDisplay,
212
305
  rolePermissions,
213
306
  syncScopedActions,
214
307
  updateRolePermissions
@@ -53,14 +53,10 @@ var fs = __toESM(require("fs"));
53
53
  var os = __toESM(require("os"));
54
54
  var path = __toESM(require("path"));
55
55
  var import_git_actions = require("./git-actions");
56
+ var import_repository_access = require("../repository-access");
56
57
  var import_get_repo_account = require("../utils/get-repo-account");
57
58
  var import_redact = require("../utils/redact");
58
59
  const SUBTREE_EXECUTION_MODE = "app";
59
- function getActionParams(ctx) {
60
- var _a, _b;
61
- const requestBody = ((_a = ctx.request) == null ? void 0 : _a.body) || {};
62
- return { ...ctx.action.params, ...(_b = ctx.action.params) == null ? void 0 : _b.values, ...requestBody };
63
- }
64
60
  function stringValue(value, fallback = "") {
65
61
  return typeof value === "string" ? value.trim() : fallback;
66
62
  }
@@ -292,7 +288,7 @@ async function loadConfigAndRepository(ctx, configId) {
292
288
  return { configRecord, config, repo, account };
293
289
  }
294
290
  async function subtreeOptions(ctx, next) {
295
- const params = getActionParams(ctx);
291
+ const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
296
292
  const repositoryId = params.repositoryId;
297
293
  if (!repositoryId) ctx.throw(400, "repositoryId is required");
298
294
  const remoteName = validateRemoteName(stringValue(params.remoteName, "origin") || "origin");
@@ -342,7 +338,7 @@ async function subtreeOptions(ctx, next) {
342
338
  await next();
343
339
  }
344
340
  async function subtreePreview(ctx, next) {
345
- const params = getActionParams(ctx);
341
+ const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
346
342
  const configId = params.configId;
347
343
  if (!configId) ctx.throw(400, "configId is required");
348
344
  const { config, repo, account } = await loadConfigAndRepository(ctx, configId);
@@ -368,7 +364,7 @@ async function subtreePreview(ctx, next) {
368
364
  }
369
365
  async function subtreeRunOnAppProcess(ctx, next) {
370
366
  var _a, _b;
371
- const params = getActionParams(ctx);
367
+ const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
372
368
  const runParams = {
373
369
  configId: params.configId,
374
370
  policy: validateSubtreePolicy(params.policy),