plugin-git-manager 1.2.23 → 1.2.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/client/900.acf7d1fa22f95e71.js +10 -0
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/900.f32b9dc85249fc0a.js +10 -0
  4. package/dist/client-v2/index.js +1 -1
  5. package/dist/externalVersion.js +8 -8
  6. package/dist/locale/en-US.json +4 -3
  7. package/dist/locale/vi-VN.json +4 -3
  8. package/dist/locale/zh-CN.json +4 -3
  9. package/dist/server/actions/git-actions.js +21 -8
  10. package/dist/server/actions/gitlab-api.js +5 -8
  11. package/dist/server/actions/poller.js +2 -1
  12. package/dist/server/actions/review.js +50 -13
  13. package/dist/server/actions/role-permissions.js +109 -16
  14. package/dist/server/actions/subtree.js +4 -8
  15. package/dist/server/migrations/20260730000000-migrate-legacy-repository-permissions.js +23 -7
  16. package/dist/server/plugin.js +42 -19
  17. package/dist/server/repository-access.js +505 -27
  18. package/dist/server/services/registry-content-service.js +149 -32
  19. package/dist/server/utils/get-repo-account.js +5 -2
  20. package/dist/server/utils/gitlab-url.js +2 -0
  21. package/dist/server/utils/redact.js +51 -5
  22. package/dist/server/utils/url-security.js +109 -0
  23. package/package.json +4 -2
  24. package/src/client/components/RunReviewButton.tsx +437 -436
  25. package/src/client/index.tsx +2 -1
  26. package/src/locale/en-US.json +4 -3
  27. package/src/locale/vi-VN.json +4 -3
  28. package/src/locale/zh-CN.json +4 -3
  29. package/src/server/__tests__/git-actions.test.ts +24 -0
  30. package/src/server/__tests__/plugin-url-security.test.ts +17 -0
  31. package/src/server/__tests__/poller.test.ts +37 -0
  32. package/src/server/__tests__/repository-access.test.ts +695 -1
  33. package/src/server/__tests__/review.test.ts +137 -0
  34. package/src/server/__tests__/role-permissions.test.ts +123 -2
  35. package/src/server/actions/git-actions.ts +33 -10
  36. package/src/server/actions/gitlab-api.ts +5 -8
  37. package/src/server/actions/poller.ts +2 -1
  38. package/src/server/actions/review.ts +74 -15
  39. package/src/server/actions/role-permissions.ts +136 -14
  40. package/src/server/actions/subtree.ts +4 -8
  41. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +23 -8
  42. package/src/server/plugin.ts +46 -25
  43. package/src/server/repository-access.ts +737 -28
  44. package/src/server/services/__tests__/registry-content-service.test.ts +209 -13
  45. package/src/server/services/registry-content-service.ts +473 -315
  46. package/src/server/utils/__tests__/redact.test.ts +56 -0
  47. package/src/server/utils/__tests__/url-security.test.ts +85 -0
  48. package/src/server/utils/get-repo-account.ts +22 -4
  49. package/src/server/utils/gitlab-url.ts +3 -0
  50. package/src/server/utils/redact.ts +68 -5
  51. package/src/server/utils/url-security.ts +95 -0
  52. package/dist/client/900.ee2fa037aff389e2.js +0 -10
  53. package/dist/client-v2/900.bef1c41d267e50c5.js +0 -10
@@ -1,315 +1,473 @@
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
- }
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
+ import {
9
+ hasRepositoryAccess,
10
+ type RegistryGitAccessContext,
11
+ type RepositoryPermissionChecker,
12
+ } from '../repository-access';
13
+
14
+ export type { RegistryGitAccessContext } from '../repository-access';
15
+
16
+ function positiveLimit(value: string | undefined, fallback: number, maximum = Number.MAX_SAFE_INTEGER): number {
17
+ const parsed = Number(value);
18
+ return Number.isSafeInteger(parsed) && parsed > 0 && parsed <= maximum ? parsed : fallback;
19
+ }
20
+
21
+ // Registry reads are bounded before their buffers can be handed to a provider.
22
+ // The defaults stay below the Registry artifact limits and can be tightened per deployment.
23
+ export interface RegistryGitContentLimits {
24
+ maxFileBytes: number;
25
+ maxTreeEntries: number;
26
+ maxTreeOutputBytes: number;
27
+ }
28
+
29
+ // Getter-based limits re-read env vars on every access, so runtime settings
30
+ // applied via Skill Registry's applyRuntimeOverrides() take effect without restart.
31
+ const DEFAULT_REGISTRY_GIT_CONTENT_LIMITS: RegistryGitContentLimits = {
32
+ get maxFileBytes() {
33
+ return positiveLimit(process.env.SKILL_REGISTRY_MAX_SOURCE_FILE_BYTES, 10 * 1024 * 1024);
34
+ },
35
+ get maxTreeEntries() {
36
+ return positiveLimit(process.env.SKILL_REGISTRY_MAX_SOURCE_TREE_ENTRIES, 5000);
37
+ },
38
+ get maxTreeOutputBytes() {
39
+ return positiveLimit(process.env.SKILL_REGISTRY_MAX_SOURCE_TREE_OUTPUT_BYTES, 4 * 1024 * 1024);
40
+ },
41
+ };
42
+
43
+ export interface RegistryGitTreeEntry {
44
+ type: 'blob' | 'tree';
45
+ path: string;
46
+ size: number;
47
+ }
48
+
49
+ type RepositoryModel = {
50
+ get(attribute: string): unknown;
51
+ };
52
+
53
+ export const REGISTRY_EXPORT_NOT_GRANTED = 'REGISTRY_EXPORT_NOT_GRANTED';
54
+ export const REGISTRY_REPOSITORY_ACCESS_DENIED = 'REGISTRY_REPOSITORY_ACCESS_DENIED';
55
+ export const SKILL_HUB_REPOSITORY_ACCESS_DENIED = 'SKILL_HUB_REPOSITORY_ACCESS_DENIED';
56
+ export const REGISTRY_CONTENT_LIMIT_EXCEEDED = 'REGISTRY_CONTENT_LIMIT_EXCEEDED';
57
+ export const REGISTRY_GIT_FILE_NOT_FOUND = 'REGISTRY_GIT_FILE_NOT_FOUND';
58
+ export const REGISTRY_GIT_CONTENT_CONTRACT_VERSION = 2;
59
+ export const REGISTRY_GIT_CONTENT_CAPABILITIES = [
60
+ 'registry-content-with-actor',
61
+ 'registry-content-authorize-source',
62
+ ] as const;
63
+ export const SKILL_HUB_GIT_CONTENT_CONTRACT_VERSION = 2;
64
+ export const SKILL_HUB_GIT_CONTENT_CAPABILITIES = ['skill-hub-content-with-actor'] as const;
65
+
66
+ const DEFAULT_GIT_TIMEOUT_MS = 30_000;
67
+ const MAX_STDERR_BYTES = 64 * 1024;
68
+
69
+ export class RegistryExportNotGrantedError extends Error {
70
+ readonly code = REGISTRY_EXPORT_NOT_GRANTED;
71
+
72
+ constructor() {
73
+ super('Registry export is not enabled for this repository.');
74
+ this.name = 'RegistryExportNotGrantedError';
75
+ }
76
+ }
77
+
78
+ export class RegistryRepositoryAccessDeniedError extends Error {
79
+ readonly code = REGISTRY_REPOSITORY_ACCESS_DENIED;
80
+
81
+ constructor() {
82
+ super('The current actor is not authorized to read this repository for registry export.');
83
+ this.name = 'RegistryRepositoryAccessDeniedError';
84
+ }
85
+ }
86
+
87
+ export class SkillHubRepositoryAccessDeniedError extends Error {
88
+ readonly code = SKILL_HUB_REPOSITORY_ACCESS_DENIED;
89
+
90
+ constructor() {
91
+ super('The current actor is not authorized to read this repository for Skill Hub.');
92
+ this.name = 'SkillHubRepositoryAccessDeniedError';
93
+ }
94
+ }
95
+
96
+ export class RegistryContentLimitError extends Error {
97
+ readonly code = REGISTRY_CONTENT_LIMIT_EXCEEDED;
98
+
99
+ constructor(message: string) {
100
+ super(message);
101
+ this.name = 'RegistryContentLimitError';
102
+ }
103
+ }
104
+
105
+ export class RegistryGitFileNotFoundError extends Error {
106
+ readonly code = REGISTRY_GIT_FILE_NOT_FOUND;
107
+
108
+ constructor() {
109
+ super('Git file was not found at the pinned commit.');
110
+ this.name = 'RegistryGitFileNotFoundError';
111
+ }
112
+ }
113
+
114
+ interface GitContentAccessPolicy {
115
+ contractVersion: number;
116
+ capabilities: readonly string[];
117
+ allowsSystemScheduledSync: boolean;
118
+ requiresRegistryExport: boolean;
119
+ createAccessDeniedError(): Error;
120
+ createRepositoryUnavailableError(): Error;
121
+ }
122
+
123
+ const REGISTRY_CONTENT_ACCESS_POLICY: GitContentAccessPolicy = {
124
+ contractVersion: REGISTRY_GIT_CONTENT_CONTRACT_VERSION,
125
+ capabilities: REGISTRY_GIT_CONTENT_CAPABILITIES,
126
+ allowsSystemScheduledSync: true,
127
+ requiresRegistryExport: true,
128
+ createAccessDeniedError: () => new RegistryRepositoryAccessDeniedError(),
129
+ createRepositoryUnavailableError: () => new RegistryExportNotGrantedError(),
130
+ };
131
+
132
+ const SKILL_HUB_CONTENT_ACCESS_POLICY: GitContentAccessPolicy = {
133
+ contractVersion: SKILL_HUB_GIT_CONTENT_CONTRACT_VERSION,
134
+ capabilities: SKILL_HUB_GIT_CONTENT_CAPABILITIES,
135
+ allowsSystemScheduledSync: false,
136
+ requiresRegistryExport: false,
137
+ createAccessDeniedError: () => new SkillHubRepositoryAccessDeniedError(),
138
+ createRepositoryUnavailableError: () => new SkillHubRepositoryAccessDeniedError(),
139
+ };
140
+
141
+ function boundedPositive(value: number | undefined, fallback: number, maximum: number): number {
142
+ return Number.isSafeInteger(value) && Number(value) > 0 && Number(value) <= maximum ? Number(value) : fallback;
143
+ }
144
+
145
+ function runGitBuffer(localPath: string, args: string[], maximumBytes: number, timeoutMs: number): Promise<Buffer> {
146
+ return new Promise<Buffer>((resolve, reject) => {
147
+ const child = spawn(getGitBinaryPath(), ['-C', localPath, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
148
+ const chunks: Buffer[] = [];
149
+ let outputBytes = 0;
150
+ let stderr = '';
151
+ let stderrBytes = 0;
152
+ let settled = false;
153
+ let pendingFailure: Error | undefined;
154
+ const stop = (error: Error) => {
155
+ if (settled || pendingFailure) {
156
+ return;
157
+ }
158
+ pendingFailure = error;
159
+ clearTimeout(timer);
160
+ child.kill();
161
+ };
162
+ const timer = setTimeout(() => {
163
+ stop(new RegistryContentLimitError('Git registry read exceeded its execution timeout.'));
164
+ }, timeoutMs);
165
+
166
+ child.stdout.on('data', (chunk: Buffer) => {
167
+ if (settled) {
168
+ return;
169
+ }
170
+ outputBytes += chunk.length;
171
+ if (outputBytes > maximumBytes) {
172
+ stop(new RegistryContentLimitError('Git registry read exceeded its output limit.'));
173
+ return;
174
+ }
175
+ chunks.push(chunk);
176
+ });
177
+ child.stderr.on('data', (chunk: Buffer) => {
178
+ if (stderrBytes >= MAX_STDERR_BYTES) {
179
+ return;
180
+ }
181
+ const remaining = MAX_STDERR_BYTES - stderrBytes;
182
+ const bounded = chunk.subarray(0, remaining);
183
+ stderrBytes += bounded.length;
184
+ stderr += bounded.toString('utf8');
185
+ });
186
+ child.once('error', (error) => {
187
+ if (!pendingFailure) {
188
+ pendingFailure = error;
189
+ clearTimeout(timer);
190
+ }
191
+ });
192
+ child.once('close', (code) => {
193
+ if (settled) {
194
+ return;
195
+ }
196
+ settled = true;
197
+ clearTimeout(timer);
198
+ // `close` guarantees that the child process and both stdio streams have
199
+ // released their handles. In particular, Windows otherwise may still
200
+ // hold a temporary Git repository directory after an output-limit kill.
201
+ if (pendingFailure) {
202
+ reject(pendingFailure);
203
+ return;
204
+ }
205
+ if (code !== 0) {
206
+ if (/does not exist in|exists on disk, but not in|path .* does not exist/i.test(stderr)) {
207
+ reject(new RegistryGitFileNotFoundError());
208
+ return;
209
+ }
210
+ reject(new Error(`git command failed: ${stderr.trim() || String(code)}`));
211
+ return;
212
+ }
213
+ resolve(Buffer.concat(chunks, outputBytes));
214
+ });
215
+ });
216
+ }
217
+
218
+ function normalizeRootPath(value: string): string {
219
+ const normalized = value.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
220
+ if (!normalized) {
221
+ return '';
222
+ }
223
+ if (normalized.includes('\0') || normalized.split('/').some((part) => part === '.' || part === '..' || part === '')) {
224
+ throw new Error('Invalid repository path');
225
+ }
226
+ return normalized;
227
+ }
228
+
229
+ function normalizeFilePath(value: string): string {
230
+ const normalized = normalizeRootPath(value);
231
+ if (!normalized) {
232
+ throw new Error('File path is required');
233
+ }
234
+ return normalized;
235
+ }
236
+
237
+ function repositoryValue(repository: RepositoryModel, field: string): string {
238
+ const value = repository.get(field);
239
+ return typeof value === 'string' ? value : value === null || value === undefined ? '' : String(value);
240
+ }
241
+
242
+ function parseTreeLine(line: string, rootPath: string): RegistryGitTreeEntry | null {
243
+ const match = line.match(/^(\d+)\s+(blob|tree)\s+([a-f0-9]+)\s+(-|\d+)\t(.+)$/);
244
+ if (!match) {
245
+ return null;
246
+ }
247
+ const candidatePath = match[5].replace(/\\/g, '/');
248
+ const prefix = rootPath ? `${rootPath}/` : '';
249
+ const path = candidatePath.startsWith(prefix) ? candidatePath.slice(prefix.length) : candidatePath;
250
+ return {
251
+ type: match[2] as 'blob' | 'tree',
252
+ path: normalizeRootPath(path),
253
+ size: match[4] === '-' ? 0 : Number.parseInt(match[4], 10),
254
+ };
255
+ }
256
+
257
+ class GitContentService {
258
+ readonly contractVersion: number;
259
+ readonly capabilities: readonly string[];
260
+
261
+ constructor(
262
+ private readonly database: Database,
263
+ private readonly limits: RegistryGitContentLimits = DEFAULT_REGISTRY_GIT_CONTENT_LIMITS,
264
+ private readonly acl?: RepositoryPermissionChecker,
265
+ private readonly accessPolicy: GitContentAccessPolicy = REGISTRY_CONTENT_ACCESS_POLICY,
266
+ ) {
267
+ this.contractVersion = accessPolicy.contractVersion;
268
+ this.capabilities = accessPolicy.capabilities;
269
+ }
270
+
271
+ /**
272
+ * Validates actor access before a cross-plugin service binds or reads a
273
+ * repository. The concrete service policy decides whether Registry export
274
+ * opt-in or scheduled system access is permitted.
275
+ */
276
+ async assertRepositoryAccess(repositoryId: string | number, access?: RegistryGitAccessContext): Promise<void> {
277
+ await this.findRepository(repositoryId, access);
278
+ }
279
+
280
+ async resolveCommit(repositoryId: string | number, ref: string, access?: RegistryGitAccessContext): Promise<string> {
281
+ const repository = await this.findRepository(repositoryId, access);
282
+ const localPath = validateLocalPath(repositoryValue(repository, 'localPath'));
283
+ if (!existsSync(localPath)) {
284
+ throw new Error('Repository directory does not exist. Clone the repository before reading its content.');
285
+ }
286
+ const result = (
287
+ await runGitBuffer(
288
+ localPath,
289
+ ['rev-parse', '--verify', `${validateRef(ref)}^{commit}`],
290
+ 256,
291
+ DEFAULT_GIT_TIMEOUT_MS,
292
+ )
293
+ )
294
+ .toString('utf8')
295
+ .trim();
296
+ if (!/^[a-f0-9]{40,64}$/i.test(result)) {
297
+ throw new Error('Git reference did not resolve to a commit SHA');
298
+ }
299
+ return result.toLowerCase();
300
+ }
301
+
302
+ async listTree(
303
+ input: {
304
+ repositoryId: string | number;
305
+ commitSha: string;
306
+ rootPath: string;
307
+ recursive: boolean;
308
+ },
309
+ access?: RegistryGitAccessContext,
310
+ ): Promise<RegistryGitTreeEntry[]> {
311
+ const repository = await this.findRepository(input.repositoryId, access);
312
+ const localPath = validateLocalPath(repositoryValue(repository, 'localPath'));
313
+ if (!existsSync(localPath)) {
314
+ throw new Error('Repository directory does not exist. Clone the repository before reading its content.');
315
+ }
316
+ const commitSha = this.assertCommitSha(input.commitSha);
317
+ const rootPath = normalizeRootPath(input.rootPath);
318
+ const target = rootPath ? `${commitSha}:${rootPath}` : commitSha;
319
+ const output = await runGitBuffer(
320
+ localPath,
321
+ ['ls-tree', '-l', ...(input.recursive ? ['-r'] : []), target],
322
+ this.limits.maxTreeOutputBytes,
323
+ DEFAULT_GIT_TIMEOUT_MS,
324
+ );
325
+ const lines = output.toString('utf8').trim().split('\n').filter(Boolean);
326
+ if (lines.length > this.limits.maxTreeEntries) {
327
+ throw new RegistryContentLimitError('Git tree contains too many entries for registry export.');
328
+ }
329
+ return lines
330
+ .map((line) => parseTreeLine(line, rootPath))
331
+ .filter((entry): entry is RegistryGitTreeEntry => entry !== null)
332
+ .sort((left, right) => left.path.localeCompare(right.path));
333
+ }
334
+
335
+ async readFile(
336
+ input: {
337
+ repositoryId: string | number;
338
+ commitSha: string;
339
+ filePath: string;
340
+ maxBytes?: number;
341
+ },
342
+ access?: RegistryGitAccessContext,
343
+ ): Promise<Buffer> {
344
+ const repository = await this.findRepository(input.repositoryId, access);
345
+ const localPath = validateLocalPath(repositoryValue(repository, 'localPath'));
346
+ if (!existsSync(localPath)) {
347
+ throw new Error('Repository directory does not exist. Clone the repository before reading its content.');
348
+ }
349
+ const commitSha = this.assertCommitSha(input.commitSha);
350
+ const filePath = normalizeFilePath(input.filePath);
351
+ const maximumBytes = boundedPositive(input.maxBytes, this.limits.maxFileBytes, this.limits.maxFileBytes);
352
+ try {
353
+ return await runGitBuffer(localPath, ['show', `${commitSha}:${filePath}`], maximumBytes, DEFAULT_GIT_TIMEOUT_MS);
354
+ } catch (error) {
355
+ if (error instanceof RegistryContentLimitError && error.message.includes('output limit')) {
356
+ throw new RegistryContentLimitError('Git file exceeds the registry source-file limit.');
357
+ }
358
+ throw error;
359
+ }
360
+ }
361
+
362
+ async archiveTree(
363
+ input: { repositoryId: string | number; commitSha: string; rootPath: string },
364
+ access?: RegistryGitAccessContext,
365
+ ): Promise<Readable> {
366
+ const repository = await this.findRepository(input.repositoryId, access);
367
+ const localPath = validateLocalPath(repositoryValue(repository, 'localPath'));
368
+ if (!existsSync(localPath)) {
369
+ throw new Error('Repository directory does not exist. Clone the repository before reading its content.');
370
+ }
371
+ const commitSha = this.assertCommitSha(input.commitSha);
372
+ const rootPath = normalizeRootPath(input.rootPath);
373
+ return new Promise<Readable>((resolve, reject) => {
374
+ const child = spawn(
375
+ getGitBinaryPath(),
376
+ ['-C', localPath, 'archive', '--format=zip', commitSha, ...(rootPath ? [rootPath] : [])],
377
+ { stdio: ['ignore', 'pipe', 'pipe'] },
378
+ );
379
+ let stderr = '';
380
+ child.stderr.on('data', (chunk: Buffer) => {
381
+ if (Buffer.byteLength(stderr, 'utf8') >= MAX_STDERR_BYTES) {
382
+ return;
383
+ }
384
+ stderr += chunk.toString('utf8').slice(0, MAX_STDERR_BYTES - Buffer.byteLength(stderr, 'utf8'));
385
+ });
386
+ child.once('error', reject);
387
+ child.once('spawn', () => resolve(child.stdout));
388
+ child.once('close', (code) => {
389
+ if (code !== 0) {
390
+ child.stdout.destroy(new Error(`git archive failed: ${stderr.trim() || String(code)}`));
391
+ }
392
+ });
393
+ });
394
+ }
395
+
396
+ private async findRepository(
397
+ repositoryId: string | number,
398
+ access?: RegistryGitAccessContext,
399
+ ): Promise<RepositoryModel> {
400
+ await this.assertAccess(repositoryId, access);
401
+ const repository = await this.database.getRepository('gitRepositories').findOne({ filterByTk: repositoryId });
402
+ if (!repository) {
403
+ // Do not distinguish a missing repository from one that exists but has not
404
+ // granted registry export. Callers cannot use this bridge to enumerate
405
+ // repository IDs or infer private repository existence.
406
+ throw this.accessPolicy.createRepositoryUnavailableError();
407
+ }
408
+ const repositoryModel = repository as unknown as RepositoryModel;
409
+ if (this.accessPolicy.requiresRegistryExport && repositoryModel.get('registryExportEnabled') !== true) {
410
+ throw new RegistryExportNotGrantedError();
411
+ }
412
+ return repositoryModel;
413
+ }
414
+
415
+ private async assertAccess(repositoryId: string | number, access?: RegistryGitAccessContext): Promise<void> {
416
+ if (!access) {
417
+ // The old call shape is intentionally retained for a stable TypeScript
418
+ // boundary, but treating missing identity as a system caller would let
419
+ // user-triggered cross-plugin calls bypass repository-scoped ACL.
420
+ throw this.accessPolicy.createAccessDeniedError();
421
+ }
422
+ if (access.kind === 'system') {
423
+ if (this.accessPolicy.allowsSystemScheduledSync && access.reason === 'scheduled-sync') {
424
+ return;
425
+ }
426
+ throw this.accessPolicy.createAccessDeniedError();
427
+ }
428
+ if (
429
+ access.kind !== 'user' ||
430
+ !Array.isArray(access.roles) ||
431
+ !access.roles.every((role) => typeof role === 'string')
432
+ ) {
433
+ throw this.accessPolicy.createAccessDeniedError();
434
+ }
435
+ const allowed = await hasRepositoryAccess({
436
+ acl: this.acl,
437
+ roles: access.roles,
438
+ repositoryId,
439
+ action: 'fileContent',
440
+ });
441
+ if (!allowed) {
442
+ throw this.accessPolicy.createAccessDeniedError();
443
+ }
444
+ }
445
+
446
+ private assertCommitSha(value: string): string {
447
+ const normalized = validateRef(value);
448
+ if (!/^[a-f0-9]{40,64}$/i.test(normalized)) {
449
+ throw new Error('Registry reads require a full commit SHA');
450
+ }
451
+ return normalized.toLowerCase();
452
+ }
453
+ }
454
+
455
+ export class RegistryGitContentService extends GitContentService {
456
+ constructor(
457
+ database: Database,
458
+ limits: RegistryGitContentLimits = DEFAULT_REGISTRY_GIT_CONTENT_LIMITS,
459
+ acl?: RepositoryPermissionChecker,
460
+ ) {
461
+ super(database, limits, acl, REGISTRY_CONTENT_ACCESS_POLICY);
462
+ }
463
+ }
464
+
465
+ export class SkillHubGitContentService extends GitContentService {
466
+ constructor(
467
+ database: Database,
468
+ limits: RegistryGitContentLimits = DEFAULT_REGISTRY_GIT_CONTENT_LIMITS,
469
+ acl?: RepositoryPermissionChecker,
470
+ ) {
471
+ super(database, limits, acl, SKILL_HUB_CONTENT_ACCESS_POLICY);
472
+ }
473
+ }