plugin-git-manager 1.3.3 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/{156.c27c2392746e7866.js → 156.8e36af3e2cee173e.js} +1 -1
- package/dist/client/317.e7b1d59371812c30.js +10 -0
- package/dist/client/434.05d0ba2b821105dc.js +10 -0
- package/dist/client/453.cdcba6d2d0c9522b.js +10 -0
- package/dist/client/454.625da741a7e1161f.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/317.4e116f84ed9081b6.js +10 -0
- package/dist/client-v2/434.764113d20743a45b.js +10 -0
- package/dist/client-v2/453.5ab80c06d8e61a7e.js +10 -0
- package/dist/client-v2/454.b885b1d35ef7ff72.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +10 -9
- package/dist/locale/en-US.json +38 -1
- package/dist/locale/vi-VN.json +38 -1
- package/dist/locale/zh-CN.json +41 -1
- package/dist/node_modules/simple-git/package.json +1 -1
- package/dist/node_modules/zod/package.json +1 -1
- package/dist/server/actions/chat-context.js +282 -0
- package/dist/server/actions/git-actions.js +387 -80
- package/dist/server/actions/gitlab-api.js +101 -15
- package/dist/server/actions/subtree.js +20 -10
- package/dist/server/chat-context-admission.js +187 -0
- package/dist/server/plugin.js +142 -10
- package/dist/server/repository-access.js +2 -2
- package/dist/server/request-method-policy.js +4 -1
- package/dist/server/services/review-source.js +2 -1
- package/dist/server/utils/cluster-git.js +181 -0
- package/package.json +2 -2
- package/src/client/__tests__/FileExplorerAndManage.test.tsx +236 -0
- package/src/client/__tests__/GitContextPicker.test.tsx +120 -0
- package/src/client/__tests__/ai-context.test.tsx +119 -0
- package/src/client/__tests__/workflowRoutes.test.ts +3 -1
- package/src/client/ai-context.tsx +3 -113
- package/src/client/components/CommitHistory.tsx +19 -7
- package/src/client/components/FileExplorer.tsx +80 -34
- package/src/client/components/GitManagerSettings.tsx +21 -5
- package/src/client/components/GitOperations.tsx +25 -4
- package/src/client/components/GitRuntimeBanner.tsx +97 -0
- package/src/client/components/RepositoryConfig.tsx +28 -6
- package/src/client/context/GitManagerContext.tsx +174 -15
- package/src/client/index.tsx +3 -5
- package/src/client/workflowRoutes.ts +11 -0
- package/src/client-v2/ai-context.tsx +135 -72
- package/src/client-v2/components/GitContextPicker.tsx +418 -0
- package/src/client-v2/git-context-api.ts +59 -0
- package/src/client-v2/plugin.tsx +2 -4
- package/src/locale/en-US.json +38 -1
- package/src/locale/vi-VN.json +38 -1
- package/src/locale/zh-CN.json +41 -1
- package/src/server/__tests__/chat-context-admission.test.ts +276 -0
- package/src/server/__tests__/chat-context-options.test.ts +144 -0
- package/src/server/__tests__/git-actions.test.ts +329 -4
- package/src/server/__tests__/git-chat-context.test.ts +138 -0
- package/src/server/__tests__/git-security.test.ts +52 -0
- package/src/server/__tests__/smoke.test.ts +232 -1
- package/src/server/actions/chat-context.ts +302 -0
- package/src/server/actions/git-actions.ts +428 -89
- package/src/server/actions/gitlab-api.ts +113 -14
- package/src/server/actions/subtree.ts +23 -6
- package/src/server/chat-context-admission.ts +182 -0
- package/src/server/plugin.ts +163 -3
- package/src/server/repository-access.ts +2 -2
- package/src/server/request-method-policy.ts +3 -0
- package/src/server/services/review-source.ts +3 -2
- package/src/server/utils/cluster-git.ts +209 -0
- package/dist/client/317.17ed0018e3e7db00.js +0 -10
- package/dist/client/434.b2eeaaef33aae6e0.js +0 -10
- package/dist/client/453.fc3042c9740d8fab.js +0 -10
- package/dist/client-v2/317.d2466574d00f94d0.js +0 -10
- package/dist/client-v2/434.19c7579c06b9077c.js +0 -10
- package/dist/client-v2/453.5e507c94c59277b1.js +0 -10
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
// SPDX-License-Identifier: Apache-2.0
|
|
2
2
|
|
|
3
3
|
import { execFileSync } from 'child_process';
|
|
4
|
-
import { mkdtempSync, mkdirSync, rmSync, symlinkSync, unlinkSync } from 'fs';
|
|
4
|
+
import { existsSync, mkdtempSync, mkdirSync, rmSync, symlinkSync, unlinkSync } from 'fs';
|
|
5
5
|
import { tmpdir } from 'os';
|
|
6
6
|
import { join } from 'path';
|
|
7
7
|
import { createMockServer, type MockServer } from '@nocobase/test';
|
|
8
|
+
import { UNION_ROLE_KEY } from '../../../../@nocobase/plugin-acl/src/server/constants';
|
|
9
|
+
import { SystemRoleMode } from '../../../../@nocobase/plugin-acl/src/server/enum';
|
|
8
10
|
import PluginGitManagerServer from '../plugin';
|
|
9
11
|
|
|
10
12
|
describe('Git Manager HTTP integration', () => {
|
|
@@ -13,6 +15,8 @@ describe('Git Manager HTTP integration', () => {
|
|
|
13
15
|
let fixture: string;
|
|
14
16
|
let repoPath: string;
|
|
15
17
|
let repositoryId: number;
|
|
18
|
+
let otherRepositoryId: number;
|
|
19
|
+
let rootCommitHash: string;
|
|
16
20
|
const originalBase = process.env.GIT_REPOS_BASE_PATH;
|
|
17
21
|
|
|
18
22
|
beforeAll(async () => {
|
|
@@ -38,6 +42,7 @@ describe('Git Manager HTTP integration', () => {
|
|
|
38
42
|
{ stdio: 'ignore' },
|
|
39
43
|
);
|
|
40
44
|
execFileSync('git', ['-C', repoPath, 'branch', 'marker'], { stdio: 'ignore' });
|
|
45
|
+
rootCommitHash = execFileSync('git', ['-C', repoPath, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
|
|
41
46
|
app = await createMockServer({
|
|
42
47
|
acl: true,
|
|
43
48
|
registerActions: true,
|
|
@@ -57,6 +62,29 @@ describe('Git Manager HTTP integration', () => {
|
|
|
57
62
|
values: { name: 'fixture', localPath: 'repository', repoUrl: 'https://gitlab.com/team/fixture.git' },
|
|
58
63
|
});
|
|
59
64
|
repositoryId = repository.get('id');
|
|
65
|
+
const otherRepoPath = join(fixture, 'other-repository');
|
|
66
|
+
mkdirSync(otherRepoPath);
|
|
67
|
+
execFileSync('git', ['init', '-b', 'main', otherRepoPath], { stdio: 'ignore' });
|
|
68
|
+
execFileSync(
|
|
69
|
+
'git',
|
|
70
|
+
[
|
|
71
|
+
'-C',
|
|
72
|
+
otherRepoPath,
|
|
73
|
+
'-c',
|
|
74
|
+
'user.name=Test',
|
|
75
|
+
'-c',
|
|
76
|
+
'user.email=test@example.invalid',
|
|
77
|
+
'commit',
|
|
78
|
+
'--allow-empty',
|
|
79
|
+
'-m',
|
|
80
|
+
'other fixture',
|
|
81
|
+
],
|
|
82
|
+
{ stdio: 'ignore' },
|
|
83
|
+
);
|
|
84
|
+
const otherRepository = await app.db.getRepository('gitRepositories').create({
|
|
85
|
+
values: { name: 'other-fixture', localPath: 'other-repository', repoUrl: 'https://gitlab.com/team/other.git' },
|
|
86
|
+
});
|
|
87
|
+
otherRepositoryId = otherRepository.get('id');
|
|
60
88
|
agent = await app.agent().login(await app.db.getRepository('users').findOne());
|
|
61
89
|
});
|
|
62
90
|
|
|
@@ -75,6 +103,178 @@ describe('Git Manager HTTP integration', () => {
|
|
|
75
103
|
expect(response.body.data).toBeTruthy();
|
|
76
104
|
});
|
|
77
105
|
|
|
106
|
+
it('filters chat context options and rechecks content against SQLite ACL scopes', async () => {
|
|
107
|
+
const createReaderAgent = async (
|
|
108
|
+
roleName: string,
|
|
109
|
+
includeCommitActions: boolean,
|
|
110
|
+
fields = ['id', 'name', 'defaultBranch', 'status'],
|
|
111
|
+
) => {
|
|
112
|
+
await app.db.getRepository('roles').create({ values: { name: roleName } });
|
|
113
|
+
const scope = await agent.resource('dataSourcesRolesResourcesScopes').create({
|
|
114
|
+
values: {
|
|
115
|
+
name: `${roleName} repository scope`,
|
|
116
|
+
resourceName: 'gitRepositories',
|
|
117
|
+
scope: { $and: [{ id: { $in: [repositoryId] } }] },
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
const scopeId = scope.body.data.id;
|
|
121
|
+
const repositoryResource = {
|
|
122
|
+
name: 'gitRepositories',
|
|
123
|
+
usingActionsConfig: true,
|
|
124
|
+
actions: [
|
|
125
|
+
{ name: 'list', fields, scopeId },
|
|
126
|
+
{ name: 'get', fields, scopeId },
|
|
127
|
+
],
|
|
128
|
+
};
|
|
129
|
+
await agent.resource('roles.resources', roleName).create({ values: repositoryResource });
|
|
130
|
+
if (includeCommitActions) {
|
|
131
|
+
const commitResource = {
|
|
132
|
+
name: 'gitManager',
|
|
133
|
+
usingActionsConfig: true,
|
|
134
|
+
actions: ['branches', 'log', 'commitDetail', 'diff'].map((name) => ({ name, scopeId })),
|
|
135
|
+
};
|
|
136
|
+
await agent.resource('roles.resources', roleName).create({ values: commitResource });
|
|
137
|
+
}
|
|
138
|
+
const user = await app.db.getRepository('users').create({ values: { roles: [roleName] } });
|
|
139
|
+
return app.agent().login(user);
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const repoReader = await createReaderAgent('git-chat-repo-reader', false);
|
|
143
|
+
const repoResponse = await repoReader.get('/gitManager:chatContextOptions').query({ kind: 'repository' });
|
|
144
|
+
expect(repoResponse.status).toBe(200);
|
|
145
|
+
const repoPayload = repoResponse.body.data.data as {
|
|
146
|
+
capabilities: Record<string, boolean>;
|
|
147
|
+
items: Array<Record<string, unknown>>;
|
|
148
|
+
};
|
|
149
|
+
expect(repoPayload.capabilities.repository).toBe(true);
|
|
150
|
+
expect(repoPayload.capabilities.commit).toBe(false);
|
|
151
|
+
expect(repoPayload.capabilities['merge-request']).toBe(false);
|
|
152
|
+
expect(repoPayload.items).toEqual([
|
|
153
|
+
{ id: repositoryId, name: 'fixture', defaultBranch: 'main', status: expect.any(String) },
|
|
154
|
+
]);
|
|
155
|
+
expect(JSON.stringify(repoResponse.body)).not.toContain('localPath');
|
|
156
|
+
expect(JSON.stringify(repoResponse.body)).not.toContain('repoUrl');
|
|
157
|
+
|
|
158
|
+
const commitReader = await createReaderAgent('git-chat-commit-reader', true);
|
|
159
|
+
const commitOptions = await commitReader
|
|
160
|
+
.get('/gitManager:chatContextOptions')
|
|
161
|
+
.query({ kind: 'commit', repositoryId, pageSize: 1 });
|
|
162
|
+
expect(commitOptions.status).toBe(200);
|
|
163
|
+
const commitPayload = commitOptions.body.data.data as {
|
|
164
|
+
capabilities: Record<string, boolean>;
|
|
165
|
+
items: Array<{ id: number }>;
|
|
166
|
+
};
|
|
167
|
+
expect(commitPayload.capabilities.commit).toBe(true);
|
|
168
|
+
expect(commitPayload.items.map((item) => item.id)).toEqual([repositoryId]);
|
|
169
|
+
|
|
170
|
+
const unauthorizedPreselection = await commitReader
|
|
171
|
+
.get('/gitManager:chatContextOptions')
|
|
172
|
+
.query({ kind: 'commit', repositoryId: otherRepositoryId, pageSize: 1 });
|
|
173
|
+
expect(unauthorizedPreselection.status).toBe(200);
|
|
174
|
+
expect(unauthorizedPreselection.body.data.data.items).toEqual([]);
|
|
175
|
+
|
|
176
|
+
const authorizedContent = await commitReader.get('/gitManager:chatContextContent').query({
|
|
177
|
+
kind: 'commit',
|
|
178
|
+
repositoryId,
|
|
179
|
+
commitHash: rootCommitHash,
|
|
180
|
+
});
|
|
181
|
+
expect(authorizedContent.status).toBe(200);
|
|
182
|
+
const content = authorizedContent.body.data.data as Record<string, unknown>;
|
|
183
|
+
expect(content).toMatchObject({
|
|
184
|
+
type: 'git-commit',
|
|
185
|
+
repositoryId: String(repositoryId),
|
|
186
|
+
commitSha: rootCommitHash,
|
|
187
|
+
});
|
|
188
|
+
expect(JSON.stringify(authorizedContent.body)).not.toContain('localPath');
|
|
189
|
+
expect(JSON.stringify(authorizedContent.body)).not.toContain('repoUrl');
|
|
190
|
+
|
|
191
|
+
const revokedContent = await commitReader.get('/gitManager:chatContextContent').query({
|
|
192
|
+
kind: 'commit',
|
|
193
|
+
repositoryId: otherRepositoryId,
|
|
194
|
+
commitHash: rootCommitHash,
|
|
195
|
+
});
|
|
196
|
+
expect(revokedContent.status).toBe(403);
|
|
197
|
+
|
|
198
|
+
const hiddenNameReader = await createReaderAgent('git-chat-hidden-name-reader', false, [
|
|
199
|
+
'id',
|
|
200
|
+
'defaultBranch',
|
|
201
|
+
'status',
|
|
202
|
+
]);
|
|
203
|
+
const visibleFields = await hiddenNameReader.get('/gitManager:chatContextOptions').query({ kind: 'repository' });
|
|
204
|
+
expect(visibleFields.status).toBe(200);
|
|
205
|
+
expect(visibleFields.body.data.data.items).toEqual([
|
|
206
|
+
{ id: repositoryId, defaultBranch: 'main', status: expect.any(String) },
|
|
207
|
+
]);
|
|
208
|
+
const hiddenNameSearch = await hiddenNameReader
|
|
209
|
+
.get('/gitManager:chatContextOptions')
|
|
210
|
+
.query({ kind: 'repository', search: 'fixture' });
|
|
211
|
+
expect(hiddenNameSearch.status).toBe(200);
|
|
212
|
+
expect(hiddenNameSearch.body.data.data.items).toEqual([]);
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it('combines repository and Git action permissions from current union roles', async () => {
|
|
216
|
+
const repositoryRole = 'git-chat-union-repository-reader';
|
|
217
|
+
const commitRole = 'git-chat-union-commit-reader';
|
|
218
|
+
await app.db.getRepository('roles').create({ values: { name: repositoryRole } });
|
|
219
|
+
await app.db.getRepository('roles').create({ values: { name: commitRole } });
|
|
220
|
+
const scope = await agent.resource('dataSourcesRolesResourcesScopes').create({
|
|
221
|
+
values: {
|
|
222
|
+
name: 'Git chat union repository scope',
|
|
223
|
+
resourceName: 'gitRepositories',
|
|
224
|
+
scope: { $and: [{ id: { $in: [repositoryId] } }] },
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
const scopeId = scope.body.data.id;
|
|
228
|
+
await agent.resource('roles.resources', repositoryRole).create({
|
|
229
|
+
values: {
|
|
230
|
+
name: 'gitRepositories',
|
|
231
|
+
usingActionsConfig: true,
|
|
232
|
+
actions: [
|
|
233
|
+
{ name: 'list', fields: ['id', 'name', 'defaultBranch', 'status'], scopeId },
|
|
234
|
+
{ name: 'get', fields: ['id', 'name', 'defaultBranch', 'status'], scopeId },
|
|
235
|
+
],
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
await agent.resource('roles.resources', commitRole).create({
|
|
239
|
+
values: {
|
|
240
|
+
name: 'gitManager',
|
|
241
|
+
usingActionsConfig: true,
|
|
242
|
+
actions: ['branches', 'log', 'commitDetail', 'diff'].map((name) => ({ name, scopeId })),
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
const unionUser = await app.db.getRepository('users').create({
|
|
246
|
+
values: { roles: [repositoryRole, commitRole] },
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
await agent.resource('roles').setSystemRoleMode({ values: { roleMode: SystemRoleMode.allowUseUnion } });
|
|
250
|
+
try {
|
|
251
|
+
const unionAgent = await app.agent().login(unionUser, UNION_ROLE_KEY);
|
|
252
|
+
const response = await unionAgent
|
|
253
|
+
.get('/gitManager:chatContextOptions')
|
|
254
|
+
.query({ kind: 'commit', repositoryId, pageSize: 1 });
|
|
255
|
+
|
|
256
|
+
expect(response.status).toBe(200);
|
|
257
|
+
expect(response.body.data.data.capabilities.commit).toBe(true);
|
|
258
|
+
expect(response.body.data.data.items).toEqual([
|
|
259
|
+
{ id: repositoryId, name: 'fixture', defaultBranch: 'main', status: expect.any(String) },
|
|
260
|
+
]);
|
|
261
|
+
} finally {
|
|
262
|
+
await agent.resource('roles').setSystemRoleMode({ values: { roleMode: SystemRoleMode.default } });
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it('does not expose Git context capabilities to an authenticated user without Git permissions', async () => {
|
|
267
|
+
await app.db.getRepository('roles').create({ values: { name: 'git-chat-no-access' } });
|
|
268
|
+
const user = await app.db.getRepository('users').create({ values: { roles: ['git-chat-no-access'] } });
|
|
269
|
+
const noGitAgent = await app.agent().login(user);
|
|
270
|
+
|
|
271
|
+
const response = await noGitAgent.get('/gitManager:chatContextOptions');
|
|
272
|
+
|
|
273
|
+
expect(response.status).toBe(200);
|
|
274
|
+
expect(response.body.data.data.capabilities).toEqual({ repository: false, 'merge-request': false, commit: false });
|
|
275
|
+
expect(response.body.data.data.items).toEqual([]);
|
|
276
|
+
});
|
|
277
|
+
|
|
78
278
|
it.each([
|
|
79
279
|
'clone',
|
|
80
280
|
'pull',
|
|
@@ -129,4 +329,35 @@ describe('Git Manager HTTP integration', () => {
|
|
|
129
329
|
'marker',
|
|
130
330
|
);
|
|
131
331
|
});
|
|
332
|
+
|
|
333
|
+
it('serves runtimeStatus on GET, enforces POST on installGit, validates repository mutations, and cleans up deleted localPath', async () => {
|
|
334
|
+
const statusRes = await agent.get('/gitManager:runtimeStatus');
|
|
335
|
+
expect(statusRes.status).toBe(200);
|
|
336
|
+
expect(statusRes.body.data.data).toMatchObject({ gitAvailable: true });
|
|
337
|
+
|
|
338
|
+
const badMethod = await agent.get('/gitManager:installGit');
|
|
339
|
+
expect(badMethod.status).toBe(405);
|
|
340
|
+
|
|
341
|
+
const badUrl = await agent.resource('gitRepositories').create({
|
|
342
|
+
values: { name: 'bad-http', localPath: 'bad-http', repoUrl: 'http://gitlab.com/team/repo.git' },
|
|
343
|
+
});
|
|
344
|
+
expect(badUrl.status).toBe(400);
|
|
345
|
+
|
|
346
|
+
const badPath = await agent.resource('gitRepositories').create({
|
|
347
|
+
values: { name: 'bad-path', localPath: '../escape', repoUrl: 'https://gitlab.com/team/repo.git' },
|
|
348
|
+
});
|
|
349
|
+
expect(badPath.status).toBe(400);
|
|
350
|
+
|
|
351
|
+
const tempRepoDir = join(fixture, 'disposable-repo');
|
|
352
|
+
mkdirSync(tempRepoDir);
|
|
353
|
+
const created = await agent.resource('gitRepositories').create({
|
|
354
|
+
values: { name: 'disposable', localPath: 'disposable-repo', repoUrl: 'https://gitlab.com/team/disposable.git' },
|
|
355
|
+
});
|
|
356
|
+
expect(created.status).toBe(200);
|
|
357
|
+
expect(existsSync(tempRepoDir)).toBe(true);
|
|
358
|
+
|
|
359
|
+
const destroyed = await agent.resource('gitRepositories').destroy({ filterByTk: created.body.data.id });
|
|
360
|
+
expect(destroyed.status).toBe(200);
|
|
361
|
+
expect(existsSync(tempRepoDir)).toBe(false);
|
|
362
|
+
});
|
|
132
363
|
});
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@nocobase/actions';
|
|
4
|
+
import type { Filter } from '@nocobase/database';
|
|
5
|
+
import { getEffectiveActionParams, resolveRepositoryScope, scopeIncludesRepository } from '../repository-access';
|
|
6
|
+
import { readChatCommit } from './git-actions';
|
|
7
|
+
import { readChatMergeRequest } from './gitlab-api';
|
|
8
|
+
|
|
9
|
+
const MAX_FILES = 50;
|
|
10
|
+
const MAX_DIFF_BYTES = 24 * 1024;
|
|
11
|
+
const REPOSITORY_FIELDS = ['id', 'name', 'defaultBranch', 'status'] as const;
|
|
12
|
+
const KINDS = ['repository', 'merge-request', 'commit'] as const;
|
|
13
|
+
type Kind = (typeof KINDS)[number];
|
|
14
|
+
type RepositoryField = (typeof REPOSITORY_FIELDS)[number];
|
|
15
|
+
type RepositoryId = number | string;
|
|
16
|
+
type Permission = {
|
|
17
|
+
params?: {
|
|
18
|
+
filter?: unknown;
|
|
19
|
+
fields?: unknown;
|
|
20
|
+
whitelist?: unknown;
|
|
21
|
+
except?: unknown;
|
|
22
|
+
blacklist?: unknown;
|
|
23
|
+
};
|
|
24
|
+
} | null;
|
|
25
|
+
type Scope = { unrestricted: boolean; ids: RepositoryId[] };
|
|
26
|
+
type Access = { scope: Scope; fields: RepositoryField[] } | null;
|
|
27
|
+
type GitContextChange = {
|
|
28
|
+
oldPath?: string;
|
|
29
|
+
newPath?: string;
|
|
30
|
+
status?: string;
|
|
31
|
+
newFile: boolean;
|
|
32
|
+
deletedFile: boolean;
|
|
33
|
+
renamedFile: boolean;
|
|
34
|
+
diff?: string;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const ACTIONS: Record<Kind, string[]> = {
|
|
38
|
+
repository: [],
|
|
39
|
+
'merge-request': ['mergeRequests', 'mergeRequestDetail'],
|
|
40
|
+
commit: ['branches', 'log', 'commitDetail', 'diff'],
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
function rolesFor(ctx: Context): string[] {
|
|
44
|
+
const roles: unknown = ctx.state?.currentRoles;
|
|
45
|
+
if (!ctx.state?.currentUser?.id || !Array.isArray(roles) || roles.some((role) => typeof role !== 'string')) {
|
|
46
|
+
return ctx.throw(403, 'Permission denied');
|
|
47
|
+
}
|
|
48
|
+
return roles;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function allowedField(permission: Permission, field: string): boolean {
|
|
52
|
+
if (!permission) return false;
|
|
53
|
+
const params = permission.params || {};
|
|
54
|
+
for (const key of ['fields', 'whitelist'] as const) {
|
|
55
|
+
const value = params[key];
|
|
56
|
+
if (value !== undefined && !Array.isArray(value)) return false;
|
|
57
|
+
if (Array.isArray(value) && value.length && !value.includes(field) && !value.includes('*')) return false;
|
|
58
|
+
}
|
|
59
|
+
for (const key of ['except', 'blacklist'] as const) {
|
|
60
|
+
const value = params[key];
|
|
61
|
+
if (value !== undefined && !Array.isArray(value)) return false;
|
|
62
|
+
if (Array.isArray(value) && (value.includes(field) || value.includes('*'))) return false;
|
|
63
|
+
}
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function intersectScopes(scopes: Scope[]): Scope {
|
|
68
|
+
const restricted = scopes.filter((scope) => !scope.unrestricted);
|
|
69
|
+
if (!restricted.length) return { unrestricted: true, ids: [] };
|
|
70
|
+
const [first, ...rest] = restricted;
|
|
71
|
+
return {
|
|
72
|
+
unrestricted: false,
|
|
73
|
+
ids: first.ids.filter((id) => rest.every((scope) => scope.ids.some((other) => String(other) === String(id)))),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function permissionsFor(ctx: Context, roles: string[]) {
|
|
78
|
+
if (roles.includes('root')) {
|
|
79
|
+
return new Map<string, Permission>(
|
|
80
|
+
[
|
|
81
|
+
'gitRepositories:list',
|
|
82
|
+
'gitRepositories:get',
|
|
83
|
+
...Object.values(ACTIONS)
|
|
84
|
+
.flat()
|
|
85
|
+
.map((name) => `gitManager:${name}`),
|
|
86
|
+
].map((action) => [action, { params: {} }]),
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
const pairs: Array<[string, string]> = [
|
|
90
|
+
['gitRepositories', 'list'],
|
|
91
|
+
['gitRepositories', 'get'],
|
|
92
|
+
...Array.from(new Set(Object.values(ACTIONS).flat())).map((name): [string, string] => ['gitManager', name]),
|
|
93
|
+
];
|
|
94
|
+
const values = await Promise.all(
|
|
95
|
+
pairs.map(
|
|
96
|
+
async ([resource, action]) =>
|
|
97
|
+
[`${resource}:${action}`, (await ctx.app.acl.can({ roles, resource, action })) as Permission] as const,
|
|
98
|
+
),
|
|
99
|
+
);
|
|
100
|
+
return new Map<string, Permission>(values);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function accessFor(permissions: Map<string, Permission>, kind: Kind): Access {
|
|
104
|
+
const list = permissions.get('gitRepositories:list') || null;
|
|
105
|
+
const get = permissions.get('gitRepositories:get') || null;
|
|
106
|
+
const required = [list, get, ...ACTIONS[kind].map((action) => permissions.get(`gitManager:${action}`) || null)];
|
|
107
|
+
if (required.some((permission) => !permission)) return null;
|
|
108
|
+
const scopes = required.map((permission) => resolveRepositoryScope(permission?.params?.filter));
|
|
109
|
+
if (scopes.some((scope) => !scope.supported)) return null;
|
|
110
|
+
const scope = intersectScopes(scopes);
|
|
111
|
+
if (!scope.unrestricted && !scope.ids.length) return null;
|
|
112
|
+
const fields = REPOSITORY_FIELDS.filter((field) => allowedField(list, field) && allowedField(get, field));
|
|
113
|
+
if (!fields.includes('id')) return null;
|
|
114
|
+
return { scope, fields };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function scopeFilter(scope: Scope): Filter {
|
|
118
|
+
return scope.unrestricted ? {} : { id: { $in: scope.ids } };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function readRepositoryValue(record: unknown, field: string): unknown {
|
|
122
|
+
if (!record || typeof record !== 'object') return undefined;
|
|
123
|
+
const value = record as { get?: (key: string) => unknown } & Record<string, unknown>;
|
|
124
|
+
return typeof value.get === 'function' ? value.get(field) : value[field];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function repositorySummary(record: unknown, fields: RepositoryField[]) {
|
|
128
|
+
return Object.fromEntries(fields.map((field) => [field, readRepositoryValue(record, field)]));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function kindFrom(value: unknown): Kind | undefined {
|
|
132
|
+
return typeof value === 'string' && KINDS.includes(value as Kind) ? (value as Kind) : undefined;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function positiveInteger(value: unknown, fallback: number, max: number): number {
|
|
136
|
+
const parsed = Number(value);
|
|
137
|
+
return Number.isSafeInteger(parsed) && parsed > 0 ? Math.min(parsed, max) : fallback;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function chatContextOptions(ctx: Context, next: () => Promise<void>) {
|
|
141
|
+
const roles = rolesFor(ctx);
|
|
142
|
+
const params = getEffectiveActionParams(ctx);
|
|
143
|
+
const kind = kindFrom(params.kind);
|
|
144
|
+
if (params.kind !== undefined && !kind) ctx.throw(400, 'Invalid chat context type');
|
|
145
|
+
const permissions = await permissionsFor(ctx, roles);
|
|
146
|
+
const accesses = Object.fromEntries(KINDS.map((name) => [name, accessFor(permissions, name)])) as Record<
|
|
147
|
+
Kind,
|
|
148
|
+
Access
|
|
149
|
+
>;
|
|
150
|
+
const repo = ctx.db.getRepository('gitRepositories');
|
|
151
|
+
const capabilityValues = await Promise.all(
|
|
152
|
+
KINDS.map(async (name) => {
|
|
153
|
+
const access = accesses[name];
|
|
154
|
+
return Boolean(access && (await repo.findOne({ filter: scopeFilter(access.scope), fields: ['id'] })));
|
|
155
|
+
}),
|
|
156
|
+
);
|
|
157
|
+
const capabilities = Object.fromEntries(KINDS.map((name, index) => [name, capabilityValues[index]])) as Record<
|
|
158
|
+
Kind,
|
|
159
|
+
boolean
|
|
160
|
+
>;
|
|
161
|
+
const page = positiveInteger(params.page, 1, 100000);
|
|
162
|
+
const pageSize = positiveInteger(params.pageSize, 20, 100);
|
|
163
|
+
const access = kind ? accesses[kind] : null;
|
|
164
|
+
const search = typeof params.search === 'string' ? params.search.trim().slice(0, 200) : '';
|
|
165
|
+
const repositoryId = params.repositoryId;
|
|
166
|
+
if (
|
|
167
|
+
repositoryId !== undefined &&
|
|
168
|
+
((typeof repositoryId !== 'string' && typeof repositoryId !== 'number') || !String(repositoryId).trim())
|
|
169
|
+
) {
|
|
170
|
+
ctx.throw(400, 'Invalid repository');
|
|
171
|
+
}
|
|
172
|
+
let records: unknown[] = [];
|
|
173
|
+
if (access && (!search || access.fields.includes('name'))) {
|
|
174
|
+
const conditions: Filter[] = [scopeFilter(access.scope)];
|
|
175
|
+
if (search) conditions.push({ name: { $includes: search } });
|
|
176
|
+
if (typeof repositoryId === 'string' || typeof repositoryId === 'number') conditions.push({ id: repositoryId });
|
|
177
|
+
const filter = conditions.length === 1 ? conditions[0] : { $and: conditions };
|
|
178
|
+
records = await repo.find({
|
|
179
|
+
filter,
|
|
180
|
+
fields: access.fields,
|
|
181
|
+
sort: ['id'],
|
|
182
|
+
limit: pageSize + 1,
|
|
183
|
+
offset: (page - 1) * pageSize,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
ctx.body = {
|
|
187
|
+
success: true,
|
|
188
|
+
data: {
|
|
189
|
+
capabilities,
|
|
190
|
+
items: records.slice(0, pageSize).map((record) => repositorySummary(record, access?.fields || [])),
|
|
191
|
+
page,
|
|
192
|
+
pageSize,
|
|
193
|
+
hasMore: records.length > pageSize,
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
await next();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function boundedDiff(value: string, limit: number): { value: string; truncated: boolean; bytes: number } {
|
|
200
|
+
const bytes = Buffer.from(value, 'utf8');
|
|
201
|
+
if (bytes.length <= limit) return { value, truncated: false, bytes: bytes.length };
|
|
202
|
+
const text = bytes
|
|
203
|
+
.subarray(0, limit)
|
|
204
|
+
.toString('utf8')
|
|
205
|
+
.replace(/\uFFFD$/, '');
|
|
206
|
+
return { value: text, truncated: true, bytes: Buffer.byteLength(text, 'utf8') };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export async function loadChatContext(ctx: Context, params: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
210
|
+
const roles = rolesFor(ctx);
|
|
211
|
+
const kind = kindFrom(params.kind);
|
|
212
|
+
const repositoryId = params.repositoryId;
|
|
213
|
+
if (!kind || (typeof repositoryId !== 'number' && typeof repositoryId !== 'string') || !String(repositoryId).trim()) {
|
|
214
|
+
return ctx.throw(400, 'Invalid chat context');
|
|
215
|
+
}
|
|
216
|
+
const access = accessFor(await permissionsFor(ctx, roles), kind);
|
|
217
|
+
if (
|
|
218
|
+
!access ||
|
|
219
|
+
(!access.scope.unrestricted && !scopeIncludesRepository({ id: { $in: access.scope.ids } }, repositoryId))
|
|
220
|
+
) {
|
|
221
|
+
return ctx.throw(403, 'Permission denied');
|
|
222
|
+
}
|
|
223
|
+
const repository = await ctx.db.getRepository('gitRepositories').findOne({
|
|
224
|
+
filter: { $and: [scopeFilter(access.scope), { id: repositoryId }] },
|
|
225
|
+
fields: access.fields,
|
|
226
|
+
});
|
|
227
|
+
if (!repository) return ctx.throw(404, 'Repository not found');
|
|
228
|
+
const summary = repositorySummary(repository, access.fields);
|
|
229
|
+
const repositoryName = summary.name;
|
|
230
|
+
let content: Record<string, unknown>;
|
|
231
|
+
if (kind === 'repository') {
|
|
232
|
+
content = {
|
|
233
|
+
type: 'git-repository',
|
|
234
|
+
repositoryId,
|
|
235
|
+
name: summary.name,
|
|
236
|
+
defaultBranch: summary.defaultBranch,
|
|
237
|
+
status: summary.status,
|
|
238
|
+
};
|
|
239
|
+
} else if (kind === 'commit') {
|
|
240
|
+
const commitHash = typeof params.commitHash === 'string' ? params.commitHash : '';
|
|
241
|
+
const commit = await readChatCommit(ctx, commitHash, MAX_FILES, MAX_DIFF_BYTES, repositoryId);
|
|
242
|
+
content = {
|
|
243
|
+
type: 'git-commit',
|
|
244
|
+
repositoryId,
|
|
245
|
+
repositoryName,
|
|
246
|
+
...commit,
|
|
247
|
+
hash: commit.commitSha,
|
|
248
|
+
files: commit.files.map((file) => ({ ...file, file: file.newPath })),
|
|
249
|
+
limitations: commit.limitations.map((limitation) => ctx.t(limitation, { ns: 'plugin-git-manager' })),
|
|
250
|
+
};
|
|
251
|
+
} else {
|
|
252
|
+
const mrIid = Number(params.mrIid);
|
|
253
|
+
if (!Number.isSafeInteger(mrIid) || mrIid <= 0) return ctx.throw(400, 'Invalid merge request');
|
|
254
|
+
const result = await readChatMergeRequest(ctx, mrIid, repositoryId);
|
|
255
|
+
let remaining = MAX_DIFF_BYTES;
|
|
256
|
+
let truncated = result.files.length > MAX_FILES;
|
|
257
|
+
const changes: GitContextChange[] = result.files
|
|
258
|
+
.slice(0, MAX_FILES)
|
|
259
|
+
.map((file: { oldPath?: string; newPath?: string; status?: string; diff?: string; unavailable?: boolean }) => {
|
|
260
|
+
const diff = typeof file.diff === 'string' && !file.unavailable ? boundedDiff(file.diff, remaining) : undefined;
|
|
261
|
+
if (diff) {
|
|
262
|
+
remaining -= diff.bytes;
|
|
263
|
+
truncated ||= diff.truncated;
|
|
264
|
+
}
|
|
265
|
+
return {
|
|
266
|
+
oldPath: file.oldPath,
|
|
267
|
+
newPath: file.newPath,
|
|
268
|
+
status: file.status,
|
|
269
|
+
newFile: file.status === 'added',
|
|
270
|
+
deletedFile: file.status === 'removed',
|
|
271
|
+
renamedFile: file.status === 'renamed',
|
|
272
|
+
diff: diff?.value,
|
|
273
|
+
};
|
|
274
|
+
});
|
|
275
|
+
const limitations = [...result.limitations];
|
|
276
|
+
if (truncated) limitations.push('Additional changed files or diff content were omitted.');
|
|
277
|
+
if (limitations.length) truncated = true;
|
|
278
|
+
content = {
|
|
279
|
+
type: 'git-merge-request',
|
|
280
|
+
repositoryId,
|
|
281
|
+
repositoryName,
|
|
282
|
+
mrIid,
|
|
283
|
+
title: result.title,
|
|
284
|
+
description: result.description,
|
|
285
|
+
state: result.state,
|
|
286
|
+
sourceBranch: result.sourceBranch,
|
|
287
|
+
targetBranch: result.targetBranch,
|
|
288
|
+
author: result.author,
|
|
289
|
+
files: changes.map(({ diff: _diff, ...file }) => file),
|
|
290
|
+
changes,
|
|
291
|
+
truncated,
|
|
292
|
+
limitations: limitations.map((limitation) => ctx.t(limitation, { ns: 'plugin-git-manager' })),
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
return content;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export async function chatContextContent(ctx: Context, next: () => Promise<void>) {
|
|
299
|
+
const content = await loadChatContext(ctx, getEffectiveActionParams(ctx));
|
|
300
|
+
ctx.body = { success: true, data: content };
|
|
301
|
+
await next();
|
|
302
|
+
}
|