plugin-git-manager 1.2.20 → 1.2.23

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 (30) hide show
  1. package/dist/client/{434.1d19d4d6acc114f1.js → 434.b2eeaaef33aae6e0.js} +1 -1
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/{434.f8836ea116648de1.js → 434.7a27051db18526c0.js} +1 -1
  4. package/dist/client-v2/index.js +1 -1
  5. package/dist/externalVersion.js +8 -8
  6. package/dist/locale/en-US.json +1 -0
  7. package/dist/locale/vi-VN.json +1 -0
  8. package/dist/locale/zh-CN.json +1 -0
  9. package/dist/server/actions/git-actions.js +7 -0
  10. package/dist/server/actions/role-permissions.js +124 -54
  11. package/dist/server/collections/gitRepositories.js +8 -0
  12. package/dist/server/migrations/20260730000000-migrate-legacy-repository-permissions.js +78 -0
  13. package/dist/server/plugin.js +16 -4
  14. package/dist/server/repository-access.js +92 -0
  15. package/dist/server/services/registry-content-service.js +296 -0
  16. package/package.json +1 -1
  17. package/src/client/components/RepositoryConfig.tsx +4 -1
  18. package/src/locale/en-US.json +1 -0
  19. package/src/locale/vi-VN.json +1 -0
  20. package/src/locale/zh-CN.json +1 -0
  21. package/src/server/__tests__/repository-access.test.ts +58 -0
  22. package/src/server/__tests__/role-permissions.test.ts +26 -0
  23. package/src/server/actions/git-actions.ts +5 -1
  24. package/src/server/actions/role-permissions.ts +129 -59
  25. package/src/server/collections/gitRepositories.ts +8 -0
  26. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +66 -0
  27. package/src/server/plugin.ts +20 -4
  28. package/src/server/repository-access.ts +64 -0
  29. package/src/server/services/__tests__/registry-content-service.test.ts +149 -0
  30. package/src/server/services/registry-content-service.ts +315 -0
@@ -0,0 +1,296 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var registry_content_service_exports = {};
28
+ __export(registry_content_service_exports, {
29
+ REGISTRY_CONTENT_LIMIT_EXCEEDED: () => REGISTRY_CONTENT_LIMIT_EXCEEDED,
30
+ REGISTRY_EXPORT_NOT_GRANTED: () => REGISTRY_EXPORT_NOT_GRANTED,
31
+ REGISTRY_GIT_FILE_NOT_FOUND: () => REGISTRY_GIT_FILE_NOT_FOUND,
32
+ RegistryContentLimitError: () => RegistryContentLimitError,
33
+ RegistryExportNotGrantedError: () => RegistryExportNotGrantedError,
34
+ RegistryGitContentService: () => RegistryGitContentService,
35
+ RegistryGitFileNotFoundError: () => RegistryGitFileNotFoundError
36
+ });
37
+ module.exports = __toCommonJS(registry_content_service_exports);
38
+ var import_child_process = require("child_process");
39
+ var import_fs = require("fs");
40
+ var import_git_actions = require("../actions/git-actions");
41
+ function positiveLimit(value, fallback, maximum) {
42
+ const parsed = Number(value);
43
+ return Number.isSafeInteger(parsed) && parsed > 0 && parsed <= maximum ? parsed : fallback;
44
+ }
45
+ const DEFAULT_REGISTRY_GIT_CONTENT_LIMITS = Object.freeze({
46
+ maxFileBytes: positiveLimit(process.env.SKILL_REGISTRY_MAX_SOURCE_FILE_BYTES, 10 * 1024 * 1024, 250 * 1024 * 1024),
47
+ maxTreeEntries: positiveLimit(process.env.SKILL_REGISTRY_MAX_SOURCE_TREE_ENTRIES, 5e3, 1e5),
48
+ maxTreeOutputBytes: positiveLimit(
49
+ process.env.SKILL_REGISTRY_MAX_SOURCE_TREE_OUTPUT_BYTES,
50
+ 4 * 1024 * 1024,
51
+ 250 * 1024 * 1024
52
+ )
53
+ });
54
+ const REGISTRY_EXPORT_NOT_GRANTED = "REGISTRY_EXPORT_NOT_GRANTED";
55
+ const REGISTRY_CONTENT_LIMIT_EXCEEDED = "REGISTRY_CONTENT_LIMIT_EXCEEDED";
56
+ const REGISTRY_GIT_FILE_NOT_FOUND = "REGISTRY_GIT_FILE_NOT_FOUND";
57
+ const DEFAULT_GIT_TIMEOUT_MS = 3e4;
58
+ const MAX_STDERR_BYTES = 64 * 1024;
59
+ class RegistryExportNotGrantedError extends Error {
60
+ code = REGISTRY_EXPORT_NOT_GRANTED;
61
+ constructor() {
62
+ super("Registry export is not enabled for this repository.");
63
+ this.name = "RegistryExportNotGrantedError";
64
+ }
65
+ }
66
+ class RegistryContentLimitError extends Error {
67
+ code = REGISTRY_CONTENT_LIMIT_EXCEEDED;
68
+ constructor(message) {
69
+ super(message);
70
+ this.name = "RegistryContentLimitError";
71
+ }
72
+ }
73
+ class RegistryGitFileNotFoundError extends Error {
74
+ code = REGISTRY_GIT_FILE_NOT_FOUND;
75
+ constructor() {
76
+ super("Git file was not found at the pinned commit.");
77
+ this.name = "RegistryGitFileNotFoundError";
78
+ }
79
+ }
80
+ function boundedPositive(value, fallback, maximum) {
81
+ return Number.isSafeInteger(value) && Number(value) > 0 && Number(value) <= maximum ? Number(value) : fallback;
82
+ }
83
+ function runGitBuffer(localPath, args, maximumBytes, timeoutMs) {
84
+ return new Promise((resolve, reject) => {
85
+ const child = (0, import_child_process.spawn)((0, import_git_actions.getGitBinaryPath)(), ["-C", localPath, ...args], { stdio: ["ignore", "pipe", "pipe"] });
86
+ const chunks = [];
87
+ let outputBytes = 0;
88
+ let stderr = "";
89
+ let stderrBytes = 0;
90
+ let settled = false;
91
+ const fail = (error) => {
92
+ if (settled) {
93
+ return;
94
+ }
95
+ settled = true;
96
+ clearTimeout(timer);
97
+ child.kill();
98
+ reject(error);
99
+ };
100
+ const timer = setTimeout(() => {
101
+ fail(new RegistryContentLimitError("Git registry read exceeded its execution timeout."));
102
+ }, timeoutMs);
103
+ child.stdout.on("data", (chunk) => {
104
+ if (settled) {
105
+ return;
106
+ }
107
+ outputBytes += chunk.length;
108
+ if (outputBytes > maximumBytes) {
109
+ fail(new RegistryContentLimitError("Git registry read exceeded its output limit."));
110
+ return;
111
+ }
112
+ chunks.push(chunk);
113
+ });
114
+ child.stderr.on("data", (chunk) => {
115
+ if (stderrBytes >= MAX_STDERR_BYTES) {
116
+ return;
117
+ }
118
+ const remaining = MAX_STDERR_BYTES - stderrBytes;
119
+ const bounded = chunk.subarray(0, remaining);
120
+ stderrBytes += bounded.length;
121
+ stderr += bounded.toString("utf8");
122
+ });
123
+ child.once("error", (error) => fail(error));
124
+ child.once("close", (code) => {
125
+ if (settled) {
126
+ return;
127
+ }
128
+ settled = true;
129
+ clearTimeout(timer);
130
+ if (code !== 0) {
131
+ if (/does not exist in|exists on disk, but not in|path .* does not exist/i.test(stderr)) {
132
+ reject(new RegistryGitFileNotFoundError());
133
+ return;
134
+ }
135
+ reject(new Error(`git command failed: ${stderr.trim() || String(code)}`));
136
+ return;
137
+ }
138
+ resolve(Buffer.concat(chunks, outputBytes));
139
+ });
140
+ });
141
+ }
142
+ function normalizeRootPath(value) {
143
+ const normalized = value.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
144
+ if (!normalized) {
145
+ return "";
146
+ }
147
+ if (normalized.includes("\0") || normalized.split("/").some((part) => part === "." || part === ".." || part === "")) {
148
+ throw new Error("Invalid repository path");
149
+ }
150
+ return normalized;
151
+ }
152
+ function normalizeFilePath(value) {
153
+ const normalized = normalizeRootPath(value);
154
+ if (!normalized) {
155
+ throw new Error("File path is required");
156
+ }
157
+ return normalized;
158
+ }
159
+ function repositoryValue(repository, field) {
160
+ const value = repository.get(field);
161
+ return typeof value === "string" ? value : value === null || value === void 0 ? "" : String(value);
162
+ }
163
+ function parseTreeLine(line, rootPath) {
164
+ const match = line.match(/^(\d+)\s+(blob|tree)\s+([a-f0-9]+)\s+(-|\d+)\t(.+)$/);
165
+ if (!match) {
166
+ return null;
167
+ }
168
+ const candidatePath = match[5].replace(/\\/g, "/");
169
+ const prefix = rootPath ? `${rootPath}/` : "";
170
+ const path = candidatePath.startsWith(prefix) ? candidatePath.slice(prefix.length) : candidatePath;
171
+ return {
172
+ type: match[2],
173
+ path: normalizeRootPath(path),
174
+ size: match[4] === "-" ? 0 : Number.parseInt(match[4], 10)
175
+ };
176
+ }
177
+ class RegistryGitContentService {
178
+ constructor(database, limits = DEFAULT_REGISTRY_GIT_CONTENT_LIMITS) {
179
+ this.database = database;
180
+ this.limits = limits;
181
+ }
182
+ async resolveCommit(repositoryId, ref) {
183
+ const repository = await this.findRepository(repositoryId);
184
+ const localPath = (0, import_git_actions.validateLocalPath)(repositoryValue(repository, "localPath"));
185
+ if (!(0, import_fs.existsSync)(localPath)) {
186
+ throw new Error("Repository directory does not exist. Clone the repository before reading its content.");
187
+ }
188
+ const result = (await runGitBuffer(
189
+ localPath,
190
+ ["rev-parse", "--verify", `${(0, import_git_actions.validateRef)(ref)}^{commit}`],
191
+ 256,
192
+ DEFAULT_GIT_TIMEOUT_MS
193
+ )).toString("utf8").trim();
194
+ if (!/^[a-f0-9]{40,64}$/i.test(result)) {
195
+ throw new Error("Git reference did not resolve to a commit SHA");
196
+ }
197
+ return result.toLowerCase();
198
+ }
199
+ async listTree(input) {
200
+ const repository = await this.findRepository(input.repositoryId);
201
+ const localPath = (0, import_git_actions.validateLocalPath)(repositoryValue(repository, "localPath"));
202
+ if (!(0, import_fs.existsSync)(localPath)) {
203
+ throw new Error("Repository directory does not exist. Clone the repository before reading its content.");
204
+ }
205
+ const commitSha = this.assertCommitSha(input.commitSha);
206
+ const rootPath = normalizeRootPath(input.rootPath);
207
+ const target = rootPath ? `${commitSha}:${rootPath}` : commitSha;
208
+ const output = await runGitBuffer(
209
+ localPath,
210
+ ["ls-tree", "-l", ...input.recursive ? ["-r"] : [], target],
211
+ this.limits.maxTreeOutputBytes,
212
+ DEFAULT_GIT_TIMEOUT_MS
213
+ );
214
+ const lines = output.toString("utf8").trim().split("\n").filter(Boolean);
215
+ if (lines.length > this.limits.maxTreeEntries) {
216
+ throw new RegistryContentLimitError("Git tree contains too many entries for registry export.");
217
+ }
218
+ return lines.map((line) => parseTreeLine(line, rootPath)).filter((entry) => entry !== null).sort((left, right) => left.path.localeCompare(right.path));
219
+ }
220
+ async readFile(input) {
221
+ const repository = await this.findRepository(input.repositoryId);
222
+ const localPath = (0, import_git_actions.validateLocalPath)(repositoryValue(repository, "localPath"));
223
+ if (!(0, import_fs.existsSync)(localPath)) {
224
+ throw new Error("Repository directory does not exist. Clone the repository before reading its content.");
225
+ }
226
+ const commitSha = this.assertCommitSha(input.commitSha);
227
+ const filePath = normalizeFilePath(input.filePath);
228
+ const maximumBytes = boundedPositive(input.maxBytes, this.limits.maxFileBytes, this.limits.maxFileBytes);
229
+ try {
230
+ return await runGitBuffer(localPath, ["show", `${commitSha}:${filePath}`], maximumBytes, DEFAULT_GIT_TIMEOUT_MS);
231
+ } catch (error) {
232
+ if (error instanceof RegistryContentLimitError && error.message.includes("output limit")) {
233
+ throw new RegistryContentLimitError("Git file exceeds the registry source-file limit.");
234
+ }
235
+ throw error;
236
+ }
237
+ }
238
+ async archiveTree(input) {
239
+ const repository = await this.findRepository(input.repositoryId);
240
+ const localPath = (0, import_git_actions.validateLocalPath)(repositoryValue(repository, "localPath"));
241
+ if (!(0, import_fs.existsSync)(localPath)) {
242
+ throw new Error("Repository directory does not exist. Clone the repository before reading its content.");
243
+ }
244
+ const commitSha = this.assertCommitSha(input.commitSha);
245
+ const rootPath = normalizeRootPath(input.rootPath);
246
+ return new Promise((resolve, reject) => {
247
+ const child = (0, import_child_process.spawn)(
248
+ (0, import_git_actions.getGitBinaryPath)(),
249
+ ["-C", localPath, "archive", "--format=zip", commitSha, ...rootPath ? [rootPath] : []],
250
+ { stdio: ["ignore", "pipe", "pipe"] }
251
+ );
252
+ let stderr = "";
253
+ child.stderr.on("data", (chunk) => {
254
+ if (Buffer.byteLength(stderr, "utf8") >= MAX_STDERR_BYTES) {
255
+ return;
256
+ }
257
+ stderr += chunk.toString("utf8").slice(0, MAX_STDERR_BYTES - Buffer.byteLength(stderr, "utf8"));
258
+ });
259
+ child.once("error", reject);
260
+ child.once("spawn", () => resolve(child.stdout));
261
+ child.once("close", (code) => {
262
+ if (code !== 0) {
263
+ child.stdout.destroy(new Error(`git archive failed: ${stderr.trim() || String(code)}`));
264
+ }
265
+ });
266
+ });
267
+ }
268
+ async findRepository(repositoryId) {
269
+ const repository = await this.database.getRepository("gitRepositories").findOne({ filterByTk: repositoryId });
270
+ if (!repository) {
271
+ throw new RegistryExportNotGrantedError();
272
+ }
273
+ const repositoryModel = repository;
274
+ if (repositoryModel.get("registryExportEnabled") !== true) {
275
+ throw new RegistryExportNotGrantedError();
276
+ }
277
+ return repositoryModel;
278
+ }
279
+ assertCommitSha(value) {
280
+ const normalized = (0, import_git_actions.validateRef)(value);
281
+ if (!/^[a-f0-9]{40,64}$/i.test(normalized)) {
282
+ throw new Error("Registry reads require a full commit SHA");
283
+ }
284
+ return normalized.toLowerCase();
285
+ }
286
+ }
287
+ // Annotate the CommonJS export names for ESM import in node:
288
+ 0 && (module.exports = {
289
+ REGISTRY_CONTENT_LIMIT_EXCEEDED,
290
+ REGISTRY_EXPORT_NOT_GRANTED,
291
+ REGISTRY_GIT_FILE_NOT_FOUND,
292
+ RegistryContentLimitError,
293
+ RegistryExportNotGrantedError,
294
+ RegistryGitContentService,
295
+ RegistryGitFileNotFoundError
296
+ });
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "displayName": "Git Manager",
4
4
  "displayName.zh-CN": "Git 管理器",
5
5
  "description": "Manage Git repositories with PAT authentication - pull, push, fetch, diff, file browsing",
6
- "version": "1.2.20",
6
+ "version": "1.2.23",
7
7
  "license": "Apache-2.0",
8
8
  "main": "dist/server/index.js",
9
9
  "files": [
@@ -279,7 +279,7 @@ export const RepositoryConfig: React.FC = () => {
279
279
  }}
280
280
  width={520}
281
281
  >
282
- <Form form={form} layout="vertical" initialValues={{ defaultBranch: 'main' }}>
282
+ <Form form={form} layout="vertical" initialValues={{ defaultBranch: 'main', registryExportEnabled: false }}>
283
283
  <Form.Item name="name" label={t('Repository Name')} rules={[{ required: true }]}>
284
284
  <Input placeholder="my-project" />
285
285
  </Form.Item>
@@ -307,6 +307,9 @@ export const RepositoryConfig: React.FC = () => {
307
307
  <Form.Item name="defaultBranch" label={t('Default Branch')}>
308
308
  <Input placeholder="main" />
309
309
  </Form.Item>
310
+ <Form.Item name="registryExportEnabled" label={t('Allow Skill Registry export')} valuePropName="checked">
311
+ <Switch />
312
+ </Form.Item>
310
313
  <Form.Item
311
314
  name="autoReviewFlowId"
312
315
  label={t('Primary Auto Review Flow')}
@@ -11,6 +11,7 @@
11
11
  "Local Path": "Local Path",
12
12
  "Personal Access Token": "Personal Access Token",
13
13
  "Default Branch": "Default Branch",
14
+ "Allow Skill Registry export": "Allow Skill Registry export",
14
15
  "Add Repository": "Add Repository",
15
16
  "Edit Repository": "Edit Repository",
16
17
  "Clone": "Clone",
@@ -11,6 +11,7 @@
11
11
  "Local Path": "Đường dẫn cục bộ",
12
12
  "Personal Access Token": "Mã truy cập cá nhân",
13
13
  "Default Branch": "Nhánh mặc định",
14
+ "Allow Skill Registry export": "Cho phép Skill Registry xuất",
14
15
  "Add Repository": "Thêm kho",
15
16
  "Edit Repository": "Sửa kho",
16
17
  "Clone": "Sao chép",
@@ -1,5 +1,6 @@
1
1
  {
2
2
  "Git Manager": "Git 管理器",
3
+ "Allow Skill Registry export": "允许 Skill Registry 导出",
3
4
  "Subtree Splits": "Subtree 拆分",
4
5
  "Add subtree configuration": "添加 subtree 配置",
5
6
  "Edit subtree configuration": "编辑 subtree 配置",
@@ -0,0 +1,58 @@
1
+ import { enforceRepositoryAccess } from '../repository-access';
2
+ import { vi } from 'vitest';
3
+
4
+ function createContext(repositoryId: number, filter?: unknown, roles = ['developer']) {
5
+ const throwError = vi.fn((status: number, message: string) => {
6
+ const error = new Error(message) as Error & { status: number };
7
+ error.status = status;
8
+ throw error;
9
+ });
10
+ return {
11
+ action: { resourceName: 'gitManager', actionName: 'fileTree', params: { repositoryId } },
12
+ state: { currentRoles: roles },
13
+ app: {
14
+ acl: {
15
+ can: vi.fn().mockResolvedValue({ params: filter === undefined ? {} : { filter } }),
16
+ },
17
+ },
18
+ throw: throwError,
19
+ };
20
+ }
21
+
22
+ describe('Git Manager repository access', () => {
23
+ it('allows the repository included in the role scope', async () => {
24
+ const ctx = createContext(10, { $and: [{ id: { $in: [10] } }] });
25
+ const next = vi.fn().mockResolvedValue(undefined);
26
+
27
+ await enforceRepositoryAccess(ctx, next);
28
+
29
+ expect(next).toHaveBeenCalledTimes(1);
30
+ });
31
+
32
+ it('rejects another repository outside the role scope', async () => {
33
+ const ctx = createContext(20, { $and: [{ id: { $in: [10] } }] });
34
+
35
+ await expect(enforceRepositoryAccess(ctx, vi.fn())).rejects.toMatchObject({ status: 403 });
36
+ });
37
+
38
+ it('accepts a repository granted by one of multiple roles', async () => {
39
+ const ctx = createContext(20, {
40
+ $or: [{ $and: [{ id: { $in: [10] } }] }, { $and: [{ id: { $in: [20] } }] }],
41
+ });
42
+ const next = vi.fn().mockResolvedValue(undefined);
43
+
44
+ await enforceRepositoryAccess(ctx, next);
45
+
46
+ expect(next).toHaveBeenCalledTimes(1);
47
+ });
48
+
49
+ it('allows root without evaluating repository scope', async () => {
50
+ const ctx = createContext(20, { $and: [{ id: { $in: [10] } }] }, ['root']);
51
+ const next = vi.fn().mockResolvedValue(undefined);
52
+
53
+ await enforceRepositoryAccess(ctx, next);
54
+
55
+ expect(next).toHaveBeenCalledTimes(1);
56
+ expect(ctx.app.acl.can).not.toHaveBeenCalled();
57
+ });
58
+ });
@@ -0,0 +1,26 @@
1
+ import type { Model } from '@nocobase/database';
2
+
3
+ import { getRepositoryPermissionIds } from '../actions/role-permissions';
4
+
5
+ function permissionAction(name: string, repositoryIds: Array<number | string>) {
6
+ return {
7
+ toJSON: () => ({
8
+ name,
9
+ scope: { scope: { $and: [{ id: { $in: repositoryIds } }] } },
10
+ }),
11
+ } as unknown as Model;
12
+ }
13
+
14
+ describe('Git Manager role permissions', () => {
15
+ it('reads repository IDs from legacy scoped actions', () => {
16
+ const actions = [permissionAction('read', [1]), permissionAction('write', [1, 2])];
17
+
18
+ expect(getRepositoryPermissionIds(actions, ['read', 'write'])).toEqual([1, 2]);
19
+ });
20
+
21
+ it('does not include repository IDs from unrelated actions', () => {
22
+ const actions = [permissionAction('destroy', [3]), permissionAction('write', [1])];
23
+
24
+ expect(getRepositoryPermissionIds(actions, ['write'])).toEqual([1]);
25
+ });
26
+ });
@@ -26,7 +26,7 @@ export function acquireLock(key: string): { promise: Promise<void>; release: ()
26
26
  return { promise, release };
27
27
  }
28
28
 
29
- function validateRef(ref: string): string {
29
+ export function validateRef(ref: string): string {
30
30
  if (!REF_PATTERN.test(ref)) {
31
31
  throw new Error(`Invalid ref: ${ref}`);
32
32
  }
@@ -137,6 +137,10 @@ export function createGit(baseDir?: string): SimpleGit {
137
137
  return simpleGit({ baseDir, binary: GIT_BINARY } as any);
138
138
  }
139
139
 
140
+ export function getGitBinaryPath(): string {
141
+ return GIT_BINARY;
142
+ }
143
+
140
144
  function getGit(ctx: Context, localPath: string): SimpleGit {
141
145
  if (!fs.existsSync(localPath)) {
142
146
  ctx.throw(400, 'Repository directory does not exist. Please clone the repository first.');
@@ -1,5 +1,91 @@
1
- function getRecordValue(record: any, key: string) {
2
- return record?.get ? record.get(key) : record?.[key];
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 function getRepositoryPermissionIds(actions: Model[], names: readonly string[]) {
39
+ const ids = new Set<number | string>();
40
+ for (const action of actions) {
41
+ const actionData = action.toJSON() as Record<string, unknown>;
42
+ if (typeof actionData.name !== 'string' || !names.includes(actionData.name)) continue;
43
+ const scopeRow = actionData.scope as { scope?: unknown } | undefined;
44
+ const scope = scopeRow?.scope || scopeRow;
45
+ const scopedIds = (scope as { $and?: Array<{ id?: { $in?: unknown } }> } | undefined)?.$and?.[0]?.id?.$in;
46
+ if (Array.isArray(scopedIds)) scopedIds.forEach((id: number | string) => ids.add(id));
47
+ }
48
+ return [...ids];
49
+ }
50
+
51
+ export async function syncScopedActions(
52
+ db: Database,
53
+ resource: Model,
54
+ actionNames: readonly string[],
55
+ ids: Array<number | string>,
56
+ ) {
57
+ const rolesResourceId = getRecordValue(resource, 'id');
58
+ const actionsRepo = db.getRepository('rolesResourcesActions');
59
+ for (const storedActionName of actionNames) {
60
+ const action = await actionsRepo.findOne({
61
+ filter: { rolesResourceId, name: storedActionName },
62
+ appends: ['scope'],
63
+ });
64
+ if (ids.length === 0) {
65
+ if (action) await action.destroy();
66
+ continue;
67
+ }
68
+ const scopeJson = { $and: [{ id: { $in: ids } }] };
69
+ if (action) {
70
+ const actionData = action.toJSON() as Record<string, unknown>;
71
+ const actionScopeId =
72
+ getRecordValue(actionData.scope, 'id') || actionData.scopeId || getRecordValue(action, 'scopeId');
73
+ if (actionScopeId) {
74
+ await db.getRepository('rolesResourcesScopes').update({
75
+ filterByTk: actionScopeId,
76
+ values: { scope: scopeJson },
77
+ });
78
+ } else {
79
+ const newScope = await db.getRepository('rolesResourcesScopes').create({ values: { scope: scopeJson } });
80
+ await action.update({ scopeId: getRecordValue(newScope, 'id') });
81
+ }
82
+ } else {
83
+ const newScope = await db.getRepository('rolesResourcesScopes').create({ values: { scope: scopeJson } });
84
+ await actionsRepo.create({
85
+ values: { rolesResourceId, name: storedActionName, scopeId: getRecordValue(newScope, 'id') },
86
+ });
87
+ }
88
+ }
3
89
  }
4
90
 
5
91
  /**
@@ -27,27 +113,25 @@ export async function rolePermissions(ctx: any, _next: () => Promise<void>) {
27
113
  filter: { rolesResourceId: getRecordValue(resource, 'id') },
28
114
  appends: ['scope'],
29
115
  });
116
+ const gitManagerResource = await ctx.db.getRepository('rolesResources').findOne({
117
+ filter: { roleName, name: 'gitManager' },
118
+ });
119
+ const gitManagerActions = gitManagerResource
120
+ ? await ctx.db.getRepository('rolesResourcesActions').find({
121
+ filter: { rolesResourceId: getRecordValue(gitManagerResource, 'id') },
122
+ appends: ['scope'],
123
+ })
124
+ : [];
30
125
 
31
- const result = { read: [], write: [] };
32
- for (const action of actions) {
33
- const actionData = action.toJSON ? action.toJSON() : action;
34
- const actionName = actionData.name;
35
- if (result[actionName]) {
36
- const scopeRow = actionData.scope;
37
- const scope = scopeRow?.scope || scopeRow;
38
- try {
39
- if (scope && scope.$and && scope.$and[0] && scope.$and[0].id) {
40
- if (scope.$and[0].id.$in) {
41
- result[actionName] = scope.$and[0].id.$in;
42
- } else if (typeof scope.$and[0].id === 'number' || typeof scope.$and[0].id === 'string') {
43
- result[actionName] = [scope.$and[0].id];
44
- }
45
- }
46
- } catch (e) {
47
- // Unrecognized scope structure, skip
48
- }
49
- }
50
- }
126
+ const result = {
127
+ read: getRepositoryPermissionIds(actions, [...REPOSITORY_READ_ACTIONS, 'read']),
128
+ write: [
129
+ ...new Set([
130
+ ...getRepositoryPermissionIds(gitManagerActions, GIT_WRITE_ACTIONS),
131
+ ...getRepositoryPermissionIds(actions, ['write']),
132
+ ]),
133
+ ],
134
+ };
51
135
  ctx.body = result;
52
136
  }
53
137
 
@@ -77,50 +161,36 @@ export async function updateRolePermissions(ctx: any, _next: () => Promise<void>
77
161
  await resource.update({ usingActionsConfig: true });
78
162
  }
79
163
 
80
- const rolesResourceId = getRecordValue(resource, 'id');
81
164
  const actionsRepo = ctx.db.getRepository('rolesResourcesActions');
82
- for (const actionName of ['read', 'write']) {
83
- const ids = permissions[actionName] || [];
84
- const action = await actionsRepo.findOne({
85
- filter: { rolesResourceId, name: actionName },
86
- appends: ['scope'],
87
- });
165
+ const readIds = permissions.read || [];
166
+ const writeIds = permissions.write || [];
167
+ const effectiveReadIds = [...new Set([...readIds, ...writeIds])];
168
+ await syncScopedActions(ctx.db, resource, REPOSITORY_READ_ACTIONS, effectiveReadIds);
88
169
 
89
- if (ids.length === 0) {
90
- // Remove the action if no ids allowed
91
- if (action) await action.destroy();
92
- } else {
93
- const scopeJson = { $and: [{ id: { $in: ids } }] };
94
- if (action) {
95
- const actionData = action.toJSON ? action.toJSON() : action;
96
- const actionScope = actionData.scope;
97
- const actionScopeId =
98
- getRecordValue(actionScope, 'id') || actionData.scopeId || getRecordValue(action, 'scopeId');
99
- if (actionScopeId) {
100
- await ctx.db.getRepository('rolesResourcesScopes').update({
101
- filterByTk: actionScopeId,
102
- values: { scope: scopeJson },
103
- });
104
- } else {
105
- const newScope = await ctx.db.getRepository('rolesResourcesScopes').create({
106
- values: { scope: scopeJson },
107
- });
108
- await action.update({ scopeId: getRecordValue(newScope, 'id') });
109
- }
110
- } else {
111
- const newScope = await ctx.db.getRepository('rolesResourcesScopes').create({
112
- values: { scope: scopeJson },
113
- });
114
- await actionsRepo.create({
115
- values: { rolesResourceId, name: actionName, scopeId: getRecordValue(newScope, 'id') },
116
- });
117
- }
118
- }
170
+ let gitManagerResource = await resourceRepo.findOne({ filter: { roleName, name: 'gitManager' } });
171
+ if (!gitManagerResource) {
172
+ gitManagerResource = await resourceRepo.create({
173
+ values: { roleName, name: 'gitManager', usingActionsConfig: true },
174
+ });
175
+ } else if (!getRecordValue(gitManagerResource, 'usingActionsConfig')) {
176
+ await gitManagerResource.update({ usingActionsConfig: true });
119
177
  }
178
+ await syncScopedActions(ctx.db, gitManagerResource, GIT_READ_ACTIONS, effectiveReadIds);
179
+ await syncScopedActions(ctx.db, gitManagerResource, GIT_WRITE_ACTIONS, writeIds);
180
+
181
+ const legacyReadAction = await actionsRepo.findOne({
182
+ filter: { rolesResourceId: getRecordValue(resource, 'id'), name: 'read' },
183
+ });
184
+ if (legacyReadAction) await legacyReadAction.destroy();
185
+ const legacyWriteAction = await actionsRepo.findOne({
186
+ filter: { rolesResourceId: getRecordValue(resource, 'id'), name: 'write' },
187
+ });
188
+ if (legacyWriteAction) await legacyWriteAction.destroy();
120
189
 
121
190
  // Force reload the ACL cache in memory for this resource
122
191
  try {
123
192
  await resource.writeToACL({ acl: ctx.app.acl });
193
+ await gitManagerResource.writeToACL({ acl: ctx.app.acl });
124
194
  } catch (e) {
125
195
  ctx.logger?.warn?.('[git-manager] Failed to write resource to ACL memory cache:', e);
126
196
  }