plugin-git-manager 1.2.20 → 1.2.21
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/externalVersion.js +8 -8
- package/dist/locale/en-US.json +1 -0
- package/dist/locale/vi-VN.json +1 -0
- package/dist/locale/zh-CN.json +1 -0
- package/dist/server/actions/git-actions.js +7 -0
- package/dist/server/collections/gitRepositories.js +8 -0
- package/dist/server/plugin.js +14 -4
- package/dist/server/services/registry-content-service.js +296 -0
- package/package.json +1 -1
- package/src/locale/en-US.json +1 -0
- package/src/locale/vi-VN.json +1 -0
- package/src/locale/zh-CN.json +1 -0
- package/src/server/actions/git-actions.ts +5 -1
- package/src/server/collections/gitRepositories.ts +8 -0
- package/src/server/plugin.ts +17 -4
- package/src/server/services/__tests__/registry-content-service.test.ts +149 -0
- package/src/server/services/registry-content-service.ts +315 -0
package/dist/externalVersion.js
CHANGED
|
@@ -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.
|
|
15
|
-
"@nocobase/plugin-acl": "2.1.
|
|
16
|
-
"@nocobase/client-v2": "2.1.
|
|
17
|
-
"@nocobase/flow-engine": "2.1.
|
|
18
|
-
"@nocobase/server": "2.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",
|
|
19
20
|
"sequelize": "6.35.2",
|
|
20
21
|
"dayjs": "1.11.13",
|
|
21
|
-
"@nocobase/plugin-ai": "2.1.
|
|
22
|
-
"@nocobase/actions": "2.1.
|
|
23
|
-
"@nocobase/database": "2.1.27"
|
|
22
|
+
"@nocobase/plugin-ai": "2.1.30",
|
|
23
|
+
"@nocobase/actions": "2.1.30"
|
|
24
24
|
};
|
package/dist/locale/en-US.json
CHANGED
|
@@ -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",
|
package/dist/locale/vi-VN.json
CHANGED
|
@@ -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",
|
package/dist/locale/zh-CN.json
CHANGED
|
@@ -46,12 +46,14 @@ __export(git_actions_exports, {
|
|
|
46
46
|
fetch: () => fetch,
|
|
47
47
|
fileContent: () => fileContent,
|
|
48
48
|
fileTree: () => fileTree,
|
|
49
|
+
getGitBinaryPath: () => getGitBinaryPath,
|
|
49
50
|
log: () => log,
|
|
50
51
|
pull: () => pull,
|
|
51
52
|
push: () => push,
|
|
52
53
|
status: () => status,
|
|
53
54
|
validateBranch: () => validateBranch,
|
|
54
55
|
validateLocalPath: () => validateLocalPath,
|
|
56
|
+
validateRef: () => validateRef,
|
|
55
57
|
withAuth: () => withAuth
|
|
56
58
|
});
|
|
57
59
|
module.exports = __toCommonJS(git_actions_exports);
|
|
@@ -151,6 +153,9 @@ function isMissingGitError(error) {
|
|
|
151
153
|
function createGit(baseDir) {
|
|
152
154
|
return (0, import_simple_git.default)({ baseDir, binary: GIT_BINARY });
|
|
153
155
|
}
|
|
156
|
+
function getGitBinaryPath() {
|
|
157
|
+
return GIT_BINARY;
|
|
158
|
+
}
|
|
154
159
|
function getGit(ctx, localPath) {
|
|
155
160
|
if (!fs.existsSync(localPath)) {
|
|
156
161
|
ctx.throw(400, "Repository directory does not exist. Please clone the repository first.");
|
|
@@ -413,11 +418,13 @@ async function commitDetail(ctx, next) {
|
|
|
413
418
|
fetch,
|
|
414
419
|
fileContent,
|
|
415
420
|
fileTree,
|
|
421
|
+
getGitBinaryPath,
|
|
416
422
|
log,
|
|
417
423
|
pull,
|
|
418
424
|
push,
|
|
419
425
|
status,
|
|
420
426
|
validateBranch,
|
|
421
427
|
validateLocalPath,
|
|
428
|
+
validateRef,
|
|
422
429
|
withAuth
|
|
423
430
|
});
|
|
@@ -88,6 +88,14 @@ var gitRepositories_default = (0, import_database.defineCollection)({
|
|
|
88
88
|
interface: "checkbox",
|
|
89
89
|
uiSchema: { title: "Auto Review", type: "boolean", "x-component": "Checkbox" }
|
|
90
90
|
},
|
|
91
|
+
{
|
|
92
|
+
type: "boolean",
|
|
93
|
+
name: "registryExportEnabled",
|
|
94
|
+
allowNull: false,
|
|
95
|
+
defaultValue: false,
|
|
96
|
+
interface: "checkbox",
|
|
97
|
+
uiSchema: { title: "Allow Skill Registry export", type: "boolean", "x-component": "Checkbox" }
|
|
98
|
+
},
|
|
91
99
|
{
|
|
92
100
|
type: "belongsTo",
|
|
93
101
|
name: "autoReviewFlow",
|
package/dist/server/plugin.js
CHANGED
|
@@ -53,7 +53,12 @@ var subtreeActions = __toESM(require("./actions/subtree"));
|
|
|
53
53
|
var import_review = require("./actions/review");
|
|
54
54
|
var import_ai_tools = require("./ai-tools");
|
|
55
55
|
var import_poller = require("./poller");
|
|
56
|
+
var import_registry_content_service = require("./services/registry-content-service");
|
|
56
57
|
class PluginGitManagerServer extends import_server.Plugin {
|
|
58
|
+
registryContentService;
|
|
59
|
+
async afterAdd() {
|
|
60
|
+
this.registryContentService = new import_registry_content_service.RegistryGitContentService(this.db);
|
|
61
|
+
}
|
|
57
62
|
async beforeLoad() {
|
|
58
63
|
await this.app.db.import({
|
|
59
64
|
directory: (0, import_path.resolve)(__dirname, "collections")
|
|
@@ -210,10 +215,15 @@ class PluginGitManagerServer extends import_server.Plugin {
|
|
|
210
215
|
this.app.acl.registerSnippet({
|
|
211
216
|
name: `pm.${this.name}.manage`,
|
|
212
217
|
actions: [
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
218
|
+
// ACL snippet actions are resource:action patterns; nested snippet names
|
|
219
|
+
// are not expanded by the core snippet manager.
|
|
220
|
+
"gitRepositories:*",
|
|
221
|
+
"gitAccounts:*",
|
|
222
|
+
"gitReviewFlows:*",
|
|
223
|
+
"gitCodeReviews:*",
|
|
224
|
+
"gitSubtreeConfigs:*",
|
|
225
|
+
"gitSubtreeRuns:*",
|
|
226
|
+
"gitManager:*"
|
|
217
227
|
]
|
|
218
228
|
});
|
|
219
229
|
this.app.resourceManager.use(async (ctx, next) => {
|
|
@@ -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.
|
|
6
|
+
"version": "1.2.21",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"main": "dist/server/index.js",
|
|
9
9
|
"files": [
|
package/src/locale/en-US.json
CHANGED
|
@@ -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",
|
package/src/locale/vi-VN.json
CHANGED
|
@@ -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",
|
package/src/locale/zh-CN.json
CHANGED
|
@@ -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.');
|
|
@@ -58,6 +58,14 @@ export default defineCollection({
|
|
|
58
58
|
interface: 'checkbox',
|
|
59
59
|
uiSchema: { title: 'Auto Review', type: 'boolean', 'x-component': 'Checkbox' },
|
|
60
60
|
},
|
|
61
|
+
{
|
|
62
|
+
type: 'boolean',
|
|
63
|
+
name: 'registryExportEnabled',
|
|
64
|
+
allowNull: false,
|
|
65
|
+
defaultValue: false,
|
|
66
|
+
interface: 'checkbox',
|
|
67
|
+
uiSchema: { title: 'Allow Skill Registry export', type: 'boolean', 'x-component': 'Checkbox' },
|
|
68
|
+
},
|
|
61
69
|
{
|
|
62
70
|
type: 'belongsTo',
|
|
63
71
|
name: 'autoReviewFlow',
|
package/src/server/plugin.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Plugin } from '@nocobase/server';
|
|
2
|
+
import type { Database } from '@nocobase/database';
|
|
2
3
|
import { resolve } from 'path';
|
|
3
4
|
import { DataTypes } from 'sequelize';
|
|
4
5
|
import * as gitActions from './actions/git-actions';
|
|
@@ -10,12 +11,19 @@ import * as subtreeActions from './actions/subtree';
|
|
|
10
11
|
import { recoverStuckReviews, registerReviewQueue, unregisterReviewQueue } from './actions/review';
|
|
11
12
|
import { registerGitReviewAiTools } from './ai-tools';
|
|
12
13
|
import { startPoller, stopPoller } from './poller';
|
|
14
|
+
import { RegistryGitContentService } from './services/registry-content-service';
|
|
13
15
|
|
|
14
16
|
export class PluginGitManagerServer extends Plugin {
|
|
15
17
|
// @ts-ignore
|
|
16
18
|
declare app: any;
|
|
17
19
|
// @ts-ignore
|
|
18
20
|
declare db: any;
|
|
21
|
+
registryContentService: RegistryGitContentService;
|
|
22
|
+
|
|
23
|
+
async afterAdd() {
|
|
24
|
+
this.registryContentService = new RegistryGitContentService((this as unknown as { db: Database }).db);
|
|
25
|
+
}
|
|
26
|
+
|
|
19
27
|
async beforeLoad() {
|
|
20
28
|
await (this as any).app.db.import({
|
|
21
29
|
directory: resolve(__dirname, 'collections'),
|
|
@@ -188,10 +196,15 @@ export class PluginGitManagerServer extends Plugin {
|
|
|
188
196
|
(this as any).app.acl.registerSnippet({
|
|
189
197
|
name: `pm.${(this as any).name}.manage`,
|
|
190
198
|
actions: [
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
199
|
+
// ACL snippet actions are resource:action patterns; nested snippet names
|
|
200
|
+
// are not expanded by the core snippet manager.
|
|
201
|
+
'gitRepositories:*',
|
|
202
|
+
'gitAccounts:*',
|
|
203
|
+
'gitReviewFlows:*',
|
|
204
|
+
'gitCodeReviews:*',
|
|
205
|
+
'gitSubtreeConfigs:*',
|
|
206
|
+
'gitSubtreeRuns:*',
|
|
207
|
+
'gitManager:*',
|
|
195
208
|
],
|
|
196
209
|
});
|
|
197
210
|
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { execFileSync } from 'child_process';
|
|
2
|
+
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
|
|
3
|
+
import { tmpdir } from 'os';
|
|
4
|
+
import { join } from 'path';
|
|
5
|
+
|
|
6
|
+
import type { Database } from '@nocobase/database';
|
|
7
|
+
|
|
8
|
+
import { RegistryGitContentService } from '../registry-content-service';
|
|
9
|
+
|
|
10
|
+
describe('RegistryGitContentService', () => {
|
|
11
|
+
const originalRepositoryRoot = process.env.GIT_REPOS_BASE_PATH;
|
|
12
|
+
let repositoryRoot = '';
|
|
13
|
+
let repositoryPath = '';
|
|
14
|
+
let commitSha = '';
|
|
15
|
+
|
|
16
|
+
beforeEach(() => {
|
|
17
|
+
repositoryRoot = mkdtempSync(join(tmpdir(), 'registry-git-content-'));
|
|
18
|
+
repositoryPath = join(repositoryRoot, 'skills');
|
|
19
|
+
mkdirSync(repositoryPath, { recursive: true });
|
|
20
|
+
process.env.GIT_REPOS_BASE_PATH = repositoryRoot;
|
|
21
|
+
execFileSync('git', ['init', repositoryPath], { stdio: 'ignore' });
|
|
22
|
+
execFileSync('git', ['-C', repositoryPath, 'config', 'user.email', 'registry@example.test'], { stdio: 'ignore' });
|
|
23
|
+
execFileSync('git', ['-C', repositoryPath, 'config', 'user.name', 'Registry Test'], { stdio: 'ignore' });
|
|
24
|
+
writeFileSync(join(repositoryPath, 'payload.bin'), Buffer.from([0, 255, 128, 17]));
|
|
25
|
+
execFileSync('git', ['-C', repositoryPath, 'add', 'payload.bin'], { stdio: 'ignore' });
|
|
26
|
+
execFileSync('git', ['-C', repositoryPath, 'commit', '-m', 'binary payload'], { stdio: 'ignore' });
|
|
27
|
+
commitSha = execFileSync('git', ['-C', repositoryPath, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
afterEach(() => {
|
|
31
|
+
rmSync(repositoryRoot, { recursive: true, force: true });
|
|
32
|
+
if (originalRepositoryRoot === undefined) {
|
|
33
|
+
delete process.env.GIT_REPOS_BASE_PATH;
|
|
34
|
+
} else {
|
|
35
|
+
process.env.GIT_REPOS_BASE_PATH = originalRepositoryRoot;
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('preserves binary skill files when reading from a pinned commit', async () => {
|
|
40
|
+
const database = {
|
|
41
|
+
getRepository: () => ({
|
|
42
|
+
findOne: vi.fn().mockResolvedValue({
|
|
43
|
+
get: (attribute: string) => {
|
|
44
|
+
if (attribute === 'localPath') {
|
|
45
|
+
return 'skills';
|
|
46
|
+
}
|
|
47
|
+
if (attribute === 'registryExportEnabled') {
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
},
|
|
52
|
+
}),
|
|
53
|
+
}),
|
|
54
|
+
} as unknown as Database;
|
|
55
|
+
const service = new RegistryGitContentService(database);
|
|
56
|
+
|
|
57
|
+
await expect(service.readFile({ repositoryId: 1, commitSha, filePath: 'payload.bin' })).resolves.toEqual(
|
|
58
|
+
Buffer.from([0, 255, 128, 17]),
|
|
59
|
+
);
|
|
60
|
+
await expect(service.readFile({ repositoryId: 1, commitSha, filePath: 'missing.json' })).rejects.toMatchObject({
|
|
61
|
+
code: 'REGISTRY_GIT_FILE_NOT_FOUND',
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('rejects repository reads unless Git Manager explicitly grants registry export', async () => {
|
|
66
|
+
const database = {
|
|
67
|
+
getRepository: () => ({
|
|
68
|
+
findOne: vi.fn().mockResolvedValue({
|
|
69
|
+
get: (attribute: string) => (attribute === 'registryExportEnabled' ? false : 'skills'),
|
|
70
|
+
}),
|
|
71
|
+
}),
|
|
72
|
+
} as unknown as Database;
|
|
73
|
+
const service = new RegistryGitContentService(database);
|
|
74
|
+
|
|
75
|
+
await expect(service.resolveCommit(1, 'HEAD')).rejects.toMatchObject({
|
|
76
|
+
code: 'REGISTRY_EXPORT_NOT_GRANTED',
|
|
77
|
+
});
|
|
78
|
+
await expect(
|
|
79
|
+
service.readFile({ repositoryId: 1, commitSha, filePath: 'payload.bin' }),
|
|
80
|
+
).rejects.toMatchObject({
|
|
81
|
+
code: 'REGISTRY_EXPORT_NOT_GRANTED',
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('does not distinguish a missing repository from an ungranted repository', async () => {
|
|
86
|
+
const database = {
|
|
87
|
+
getRepository: () => ({ findOne: vi.fn().mockResolvedValue(null) }),
|
|
88
|
+
} as unknown as Database;
|
|
89
|
+
const service = new RegistryGitContentService(database);
|
|
90
|
+
|
|
91
|
+
await expect(service.resolveCommit(404, 'HEAD')).rejects.toMatchObject({
|
|
92
|
+
code: 'REGISTRY_EXPORT_NOT_GRANTED',
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it('stops buffering a Git file after the configured source-file limit', async () => {
|
|
97
|
+
const database = {
|
|
98
|
+
getRepository: () => ({
|
|
99
|
+
findOne: vi.fn().mockResolvedValue({
|
|
100
|
+
get: (attribute: string) => {
|
|
101
|
+
if (attribute === 'localPath') {
|
|
102
|
+
return 'skills';
|
|
103
|
+
}
|
|
104
|
+
if (attribute === 'registryExportEnabled') {
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
return null;
|
|
108
|
+
},
|
|
109
|
+
}),
|
|
110
|
+
}),
|
|
111
|
+
} as unknown as Database;
|
|
112
|
+
const service = new RegistryGitContentService(database, {
|
|
113
|
+
maxFileBytes: 2,
|
|
114
|
+
maxTreeEntries: 10,
|
|
115
|
+
maxTreeOutputBytes: 1024,
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
await expect(service.readFile({ repositoryId: 1, commitSha, filePath: 'payload.bin' })).rejects.toThrow(
|
|
119
|
+
'Git file exceeds the registry source-file limit.',
|
|
120
|
+
);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('rejects a Git tree that exceeds the configured entry limit', async () => {
|
|
124
|
+
const database = {
|
|
125
|
+
getRepository: () => ({
|
|
126
|
+
findOne: vi.fn().mockResolvedValue({
|
|
127
|
+
get: (attribute: string) => {
|
|
128
|
+
if (attribute === 'localPath') {
|
|
129
|
+
return 'skills';
|
|
130
|
+
}
|
|
131
|
+
if (attribute === 'registryExportEnabled') {
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
},
|
|
136
|
+
}),
|
|
137
|
+
}),
|
|
138
|
+
} as unknown as Database;
|
|
139
|
+
const service = new RegistryGitContentService(database, {
|
|
140
|
+
maxFileBytes: 1024,
|
|
141
|
+
maxTreeEntries: 0,
|
|
142
|
+
maxTreeOutputBytes: 1024,
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
await expect(
|
|
146
|
+
service.listTree({ repositoryId: 1, commitSha, rootPath: '', recursive: true }),
|
|
147
|
+
).rejects.toThrow('Git tree contains too many entries for registry export.');
|
|
148
|
+
});
|
|
149
|
+
});
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { spawn } from 'child_process';
|
|
2
|
+
import { existsSync } from 'fs';
|
|
3
|
+
import type { Readable } from 'stream';
|
|
4
|
+
|
|
5
|
+
import type { Database } from '@nocobase/database';
|
|
6
|
+
|
|
7
|
+
import { getGitBinaryPath, validateLocalPath, validateRef } from '../actions/git-actions';
|
|
8
|
+
|
|
9
|
+
function positiveLimit(value: string | undefined, fallback: number, maximum: number): number {
|
|
10
|
+
const parsed = Number(value);
|
|
11
|
+
return Number.isSafeInteger(parsed) && parsed > 0 && parsed <= maximum ? parsed : fallback;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Registry reads are bounded before their buffers can be handed to a provider.
|
|
15
|
+
// The defaults stay below the Registry artifact limits and can be tightened per deployment.
|
|
16
|
+
export interface RegistryGitContentLimits {
|
|
17
|
+
maxFileBytes: number;
|
|
18
|
+
maxTreeEntries: number;
|
|
19
|
+
maxTreeOutputBytes: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const DEFAULT_REGISTRY_GIT_CONTENT_LIMITS: RegistryGitContentLimits = Object.freeze({
|
|
23
|
+
maxFileBytes: positiveLimit(process.env.SKILL_REGISTRY_MAX_SOURCE_FILE_BYTES, 10 * 1024 * 1024, 250 * 1024 * 1024),
|
|
24
|
+
maxTreeEntries: positiveLimit(process.env.SKILL_REGISTRY_MAX_SOURCE_TREE_ENTRIES, 5000, 100_000),
|
|
25
|
+
maxTreeOutputBytes: positiveLimit(
|
|
26
|
+
process.env.SKILL_REGISTRY_MAX_SOURCE_TREE_OUTPUT_BYTES,
|
|
27
|
+
4 * 1024 * 1024,
|
|
28
|
+
250 * 1024 * 1024,
|
|
29
|
+
),
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
export interface RegistryGitTreeEntry {
|
|
33
|
+
type: 'blob' | 'tree';
|
|
34
|
+
path: string;
|
|
35
|
+
size: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
type RepositoryModel = {
|
|
39
|
+
get(attribute: string): unknown;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export const REGISTRY_EXPORT_NOT_GRANTED = 'REGISTRY_EXPORT_NOT_GRANTED';
|
|
43
|
+
export const REGISTRY_CONTENT_LIMIT_EXCEEDED = 'REGISTRY_CONTENT_LIMIT_EXCEEDED';
|
|
44
|
+
export const REGISTRY_GIT_FILE_NOT_FOUND = 'REGISTRY_GIT_FILE_NOT_FOUND';
|
|
45
|
+
|
|
46
|
+
const DEFAULT_GIT_TIMEOUT_MS = 30_000;
|
|
47
|
+
const MAX_STDERR_BYTES = 64 * 1024;
|
|
48
|
+
|
|
49
|
+
export class RegistryExportNotGrantedError extends Error {
|
|
50
|
+
readonly code = REGISTRY_EXPORT_NOT_GRANTED;
|
|
51
|
+
|
|
52
|
+
constructor() {
|
|
53
|
+
super('Registry export is not enabled for this repository.');
|
|
54
|
+
this.name = 'RegistryExportNotGrantedError';
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export class RegistryContentLimitError extends Error {
|
|
59
|
+
readonly code = REGISTRY_CONTENT_LIMIT_EXCEEDED;
|
|
60
|
+
|
|
61
|
+
constructor(message: string) {
|
|
62
|
+
super(message);
|
|
63
|
+
this.name = 'RegistryContentLimitError';
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export class RegistryGitFileNotFoundError extends Error {
|
|
68
|
+
readonly code = REGISTRY_GIT_FILE_NOT_FOUND;
|
|
69
|
+
|
|
70
|
+
constructor() {
|
|
71
|
+
super('Git file was not found at the pinned commit.');
|
|
72
|
+
this.name = 'RegistryGitFileNotFoundError';
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function boundedPositive(value: number | undefined, fallback: number, maximum: number): number {
|
|
77
|
+
return Number.isSafeInteger(value) && Number(value) > 0 && Number(value) <= maximum ? Number(value) : fallback;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function runGitBuffer(localPath: string, args: string[], maximumBytes: number, timeoutMs: number): Promise<Buffer> {
|
|
81
|
+
return new Promise<Buffer>((resolve, reject) => {
|
|
82
|
+
const child = spawn(getGitBinaryPath(), ['-C', localPath, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
83
|
+
const chunks: Buffer[] = [];
|
|
84
|
+
let outputBytes = 0;
|
|
85
|
+
let stderr = '';
|
|
86
|
+
let stderrBytes = 0;
|
|
87
|
+
let settled = false;
|
|
88
|
+
const fail = (error: Error) => {
|
|
89
|
+
if (settled) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
settled = true;
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
child.kill();
|
|
95
|
+
reject(error);
|
|
96
|
+
};
|
|
97
|
+
const timer = setTimeout(() => {
|
|
98
|
+
fail(new RegistryContentLimitError('Git registry read exceeded its execution timeout.'));
|
|
99
|
+
}, timeoutMs);
|
|
100
|
+
|
|
101
|
+
child.stdout.on('data', (chunk: Buffer) => {
|
|
102
|
+
if (settled) {
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
outputBytes += chunk.length;
|
|
106
|
+
if (outputBytes > maximumBytes) {
|
|
107
|
+
fail(new RegistryContentLimitError('Git registry read exceeded its output limit.'));
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
chunks.push(chunk);
|
|
111
|
+
});
|
|
112
|
+
child.stderr.on('data', (chunk: Buffer) => {
|
|
113
|
+
if (stderrBytes >= MAX_STDERR_BYTES) {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const remaining = MAX_STDERR_BYTES - stderrBytes;
|
|
117
|
+
const bounded = chunk.subarray(0, remaining);
|
|
118
|
+
stderrBytes += bounded.length;
|
|
119
|
+
stderr += bounded.toString('utf8');
|
|
120
|
+
});
|
|
121
|
+
child.once('error', (error) => fail(error));
|
|
122
|
+
child.once('close', (code) => {
|
|
123
|
+
if (settled) {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
settled = true;
|
|
127
|
+
clearTimeout(timer);
|
|
128
|
+
if (code !== 0) {
|
|
129
|
+
if (/does not exist in|exists on disk, but not in|path .* does not exist/i.test(stderr)) {
|
|
130
|
+
reject(new RegistryGitFileNotFoundError());
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
reject(new Error(`git command failed: ${stderr.trim() || String(code)}`));
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
resolve(Buffer.concat(chunks, outputBytes));
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function normalizeRootPath(value: string): string {
|
|
142
|
+
const normalized = value.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
|
|
143
|
+
if (!normalized) {
|
|
144
|
+
return '';
|
|
145
|
+
}
|
|
146
|
+
if (normalized.includes('\0') || normalized.split('/').some((part) => part === '.' || part === '..' || part === '')) {
|
|
147
|
+
throw new Error('Invalid repository path');
|
|
148
|
+
}
|
|
149
|
+
return normalized;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function normalizeFilePath(value: string): string {
|
|
153
|
+
const normalized = normalizeRootPath(value);
|
|
154
|
+
if (!normalized) {
|
|
155
|
+
throw new Error('File path is required');
|
|
156
|
+
}
|
|
157
|
+
return normalized;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function repositoryValue(repository: RepositoryModel, field: string): string {
|
|
161
|
+
const value = repository.get(field);
|
|
162
|
+
return typeof value === 'string' ? value : value === null || value === undefined ? '' : String(value);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function parseTreeLine(line: string, rootPath: string): RegistryGitTreeEntry | null {
|
|
166
|
+
const match = line.match(/^(\d+)\s+(blob|tree)\s+([a-f0-9]+)\s+(-|\d+)\t(.+)$/);
|
|
167
|
+
if (!match) {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
const candidatePath = match[5].replace(/\\/g, '/');
|
|
171
|
+
const prefix = rootPath ? `${rootPath}/` : '';
|
|
172
|
+
const path = candidatePath.startsWith(prefix) ? candidatePath.slice(prefix.length) : candidatePath;
|
|
173
|
+
return {
|
|
174
|
+
type: match[2] as 'blob' | 'tree',
|
|
175
|
+
path: normalizeRootPath(path),
|
|
176
|
+
size: match[4] === '-' ? 0 : Number.parseInt(match[4], 10),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export class RegistryGitContentService {
|
|
181
|
+
constructor(
|
|
182
|
+
private readonly database: Database,
|
|
183
|
+
private readonly limits: RegistryGitContentLimits = DEFAULT_REGISTRY_GIT_CONTENT_LIMITS,
|
|
184
|
+
) {}
|
|
185
|
+
|
|
186
|
+
async resolveCommit(repositoryId: string | number, ref: string): Promise<string> {
|
|
187
|
+
const repository = await this.findRepository(repositoryId);
|
|
188
|
+
const localPath = validateLocalPath(repositoryValue(repository, 'localPath'));
|
|
189
|
+
if (!existsSync(localPath)) {
|
|
190
|
+
throw new Error('Repository directory does not exist. Clone the repository before reading its content.');
|
|
191
|
+
}
|
|
192
|
+
const result = (
|
|
193
|
+
await runGitBuffer(
|
|
194
|
+
localPath,
|
|
195
|
+
['rev-parse', '--verify', `${validateRef(ref)}^{commit}`],
|
|
196
|
+
256,
|
|
197
|
+
DEFAULT_GIT_TIMEOUT_MS,
|
|
198
|
+
)
|
|
199
|
+
)
|
|
200
|
+
.toString('utf8')
|
|
201
|
+
.trim();
|
|
202
|
+
if (!/^[a-f0-9]{40,64}$/i.test(result)) {
|
|
203
|
+
throw new Error('Git reference did not resolve to a commit SHA');
|
|
204
|
+
}
|
|
205
|
+
return result.toLowerCase();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async listTree(input: {
|
|
209
|
+
repositoryId: string | number;
|
|
210
|
+
commitSha: string;
|
|
211
|
+
rootPath: string;
|
|
212
|
+
recursive: boolean;
|
|
213
|
+
}): Promise<RegistryGitTreeEntry[]> {
|
|
214
|
+
const repository = await this.findRepository(input.repositoryId);
|
|
215
|
+
const localPath = validateLocalPath(repositoryValue(repository, 'localPath'));
|
|
216
|
+
if (!existsSync(localPath)) {
|
|
217
|
+
throw new Error('Repository directory does not exist. Clone the repository before reading its content.');
|
|
218
|
+
}
|
|
219
|
+
const commitSha = this.assertCommitSha(input.commitSha);
|
|
220
|
+
const rootPath = normalizeRootPath(input.rootPath);
|
|
221
|
+
const target = rootPath ? `${commitSha}:${rootPath}` : commitSha;
|
|
222
|
+
const output = await runGitBuffer(
|
|
223
|
+
localPath,
|
|
224
|
+
['ls-tree', '-l', ...(input.recursive ? ['-r'] : []), target],
|
|
225
|
+
this.limits.maxTreeOutputBytes,
|
|
226
|
+
DEFAULT_GIT_TIMEOUT_MS,
|
|
227
|
+
);
|
|
228
|
+
const lines = output.toString('utf8').trim().split('\n').filter(Boolean);
|
|
229
|
+
if (lines.length > this.limits.maxTreeEntries) {
|
|
230
|
+
throw new RegistryContentLimitError('Git tree contains too many entries for registry export.');
|
|
231
|
+
}
|
|
232
|
+
return lines
|
|
233
|
+
.map((line) => parseTreeLine(line, rootPath))
|
|
234
|
+
.filter((entry): entry is RegistryGitTreeEntry => entry !== null)
|
|
235
|
+
.sort((left, right) => left.path.localeCompare(right.path));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async readFile(input: {
|
|
239
|
+
repositoryId: string | number;
|
|
240
|
+
commitSha: string;
|
|
241
|
+
filePath: string;
|
|
242
|
+
maxBytes?: number;
|
|
243
|
+
}): Promise<Buffer> {
|
|
244
|
+
const repository = await this.findRepository(input.repositoryId);
|
|
245
|
+
const localPath = validateLocalPath(repositoryValue(repository, 'localPath'));
|
|
246
|
+
if (!existsSync(localPath)) {
|
|
247
|
+
throw new Error('Repository directory does not exist. Clone the repository before reading its content.');
|
|
248
|
+
}
|
|
249
|
+
const commitSha = this.assertCommitSha(input.commitSha);
|
|
250
|
+
const filePath = normalizeFilePath(input.filePath);
|
|
251
|
+
const maximumBytes = boundedPositive(input.maxBytes, this.limits.maxFileBytes, this.limits.maxFileBytes);
|
|
252
|
+
try {
|
|
253
|
+
return await runGitBuffer(localPath, ['show', `${commitSha}:${filePath}`], maximumBytes, DEFAULT_GIT_TIMEOUT_MS);
|
|
254
|
+
} catch (error) {
|
|
255
|
+
if (error instanceof RegistryContentLimitError && error.message.includes('output limit')) {
|
|
256
|
+
throw new RegistryContentLimitError('Git file exceeds the registry source-file limit.');
|
|
257
|
+
}
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async archiveTree(input: { repositoryId: string | number; commitSha: string; rootPath: string }): Promise<Readable> {
|
|
263
|
+
const repository = await this.findRepository(input.repositoryId);
|
|
264
|
+
const localPath = validateLocalPath(repositoryValue(repository, 'localPath'));
|
|
265
|
+
if (!existsSync(localPath)) {
|
|
266
|
+
throw new Error('Repository directory does not exist. Clone the repository before reading its content.');
|
|
267
|
+
}
|
|
268
|
+
const commitSha = this.assertCommitSha(input.commitSha);
|
|
269
|
+
const rootPath = normalizeRootPath(input.rootPath);
|
|
270
|
+
return new Promise<Readable>((resolve, reject) => {
|
|
271
|
+
const child = spawn(
|
|
272
|
+
getGitBinaryPath(),
|
|
273
|
+
['-C', localPath, 'archive', '--format=zip', commitSha, ...(rootPath ? [rootPath] : [])],
|
|
274
|
+
{ stdio: ['ignore', 'pipe', 'pipe'] },
|
|
275
|
+
);
|
|
276
|
+
let stderr = '';
|
|
277
|
+
child.stderr.on('data', (chunk: Buffer) => {
|
|
278
|
+
if (Buffer.byteLength(stderr, 'utf8') >= MAX_STDERR_BYTES) {
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
stderr += chunk.toString('utf8').slice(0, MAX_STDERR_BYTES - Buffer.byteLength(stderr, 'utf8'));
|
|
282
|
+
});
|
|
283
|
+
child.once('error', reject);
|
|
284
|
+
child.once('spawn', () => resolve(child.stdout));
|
|
285
|
+
child.once('close', (code) => {
|
|
286
|
+
if (code !== 0) {
|
|
287
|
+
child.stdout.destroy(new Error(`git archive failed: ${stderr.trim() || String(code)}`));
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private async findRepository(repositoryId: string | number): Promise<RepositoryModel> {
|
|
294
|
+
const repository = await this.database.getRepository('gitRepositories').findOne({ filterByTk: repositoryId });
|
|
295
|
+
if (!repository) {
|
|
296
|
+
// Do not distinguish a missing repository from one that exists but has not
|
|
297
|
+
// granted registry export. Callers cannot use this bridge to enumerate
|
|
298
|
+
// repository IDs or infer private repository existence.
|
|
299
|
+
throw new RegistryExportNotGrantedError();
|
|
300
|
+
}
|
|
301
|
+
const repositoryModel = repository as unknown as RepositoryModel;
|
|
302
|
+
if (repositoryModel.get('registryExportEnabled') !== true) {
|
|
303
|
+
throw new RegistryExportNotGrantedError();
|
|
304
|
+
}
|
|
305
|
+
return repositoryModel;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
private assertCommitSha(value: string): string {
|
|
309
|
+
const normalized = validateRef(value);
|
|
310
|
+
if (!/^[a-f0-9]{40,64}$/i.test(normalized)) {
|
|
311
|
+
throw new Error('Registry reads require a full commit SHA');
|
|
312
|
+
}
|
|
313
|
+
return normalized.toLowerCase();
|
|
314
|
+
}
|
|
315
|
+
}
|