plugin-git-manager 1.2.20 → 1.2.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/client/{434.1d19d4d6acc114f1.js → 434.b2eeaaef33aae6e0.js} +1 -1
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/{434.f8836ea116648de1.js → 434.7a27051db18526c0.js} +1 -1
  4. package/dist/client-v2/index.js +1 -1
  5. package/dist/externalVersion.js +8 -8
  6. package/dist/locale/en-US.json +1 -0
  7. package/dist/locale/vi-VN.json +1 -0
  8. package/dist/locale/zh-CN.json +1 -0
  9. package/dist/server/actions/git-actions.js +7 -0
  10. package/dist/server/actions/role-permissions.js +124 -54
  11. package/dist/server/collections/gitRepositories.js +8 -0
  12. package/dist/server/migrations/20260730000000-migrate-legacy-repository-permissions.js +78 -0
  13. package/dist/server/plugin.js +16 -4
  14. package/dist/server/repository-access.js +92 -0
  15. package/dist/server/services/registry-content-service.js +296 -0
  16. package/package.json +1 -1
  17. package/src/client/components/RepositoryConfig.tsx +4 -1
  18. package/src/locale/en-US.json +1 -0
  19. package/src/locale/vi-VN.json +1 -0
  20. package/src/locale/zh-CN.json +1 -0
  21. package/src/server/__tests__/repository-access.test.ts +58 -0
  22. package/src/server/__tests__/role-permissions.test.ts +26 -0
  23. package/src/server/actions/git-actions.ts +5 -1
  24. package/src/server/actions/role-permissions.ts +129 -59
  25. package/src/server/collections/gitRepositories.ts +8 -0
  26. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +66 -0
  27. package/src/server/plugin.ts +20 -4
  28. package/src/server/repository-access.ts +64 -0
  29. package/src/server/services/__tests__/registry-content-service.test.ts +149 -0
  30. package/src/server/services/registry-content-service.ts +315 -0
@@ -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',
@@ -0,0 +1,66 @@
1
+ import { Migration } from '@nocobase/server';
2
+ import type { Model } from '@nocobase/database';
3
+
4
+ import {
5
+ GIT_READ_ACTIONS,
6
+ GIT_WRITE_ACTIONS,
7
+ REPOSITORY_READ_ACTIONS,
8
+ getRepositoryPermissionIds,
9
+ syncScopedActions,
10
+ } from '../actions/role-permissions';
11
+
12
+ function getRecordValue(record: unknown, key: string) {
13
+ if (!record || typeof record !== 'object') return undefined;
14
+ const model = record as { get?: (attribute: string) => unknown } & Record<string, unknown>;
15
+ return typeof model.get === 'function' ? model.get(key) : model[key];
16
+ }
17
+
18
+ export default class MigrateLegacyRepositoryPermissions extends Migration {
19
+ on = 'afterLoad';
20
+
21
+ async up() {
22
+ const resourceRepo = this.db.getRepository('rolesResources');
23
+ const actionsRepo = this.db.getRepository('rolesResourcesActions');
24
+ const repositoryResources = await resourceRepo.find({ filter: { name: 'gitRepositories' } });
25
+
26
+ for (const repositoryResource of repositoryResources) {
27
+ const rolesResourceId = getRecordValue(repositoryResource, 'id');
28
+ const roleName = getRecordValue(repositoryResource, 'roleName');
29
+ if (!rolesResourceId || !roleName) continue;
30
+
31
+ const actions = await actionsRepo.find({
32
+ filter: { rolesResourceId },
33
+ appends: ['scope'],
34
+ });
35
+ const legacyRead = actions.filter((action) => getRecordValue(action, 'name') === 'read') as Model[];
36
+ const legacyWrite = actions.filter((action) => getRecordValue(action, 'name') === 'write') as Model[];
37
+ if (legacyRead.length === 0 && legacyWrite.length === 0) continue;
38
+
39
+ const readIds = getRepositoryPermissionIds(legacyRead, ['read']);
40
+ const writeIds = getRepositoryPermissionIds(legacyWrite, ['write']);
41
+ const effectiveReadIds = [...new Set([...readIds, ...writeIds])];
42
+ if (effectiveReadIds.length === 0 && writeIds.length === 0) continue;
43
+
44
+ await syncScopedActions(this.db, repositoryResource, REPOSITORY_READ_ACTIONS, effectiveReadIds);
45
+
46
+ let gitManagerResource = await resourceRepo.findOne({ filter: { roleName, name: 'gitManager' } });
47
+ if (!gitManagerResource) {
48
+ gitManagerResource = await resourceRepo.create({
49
+ values: { roleName, name: 'gitManager', usingActionsConfig: true },
50
+ });
51
+ } else if (!getRecordValue(gitManagerResource, 'usingActionsConfig')) {
52
+ await gitManagerResource.update({ usingActionsConfig: true });
53
+ }
54
+
55
+ await syncScopedActions(this.db, gitManagerResource, GIT_READ_ACTIONS, effectiveReadIds);
56
+ await syncScopedActions(this.db, gitManagerResource, GIT_WRITE_ACTIONS, writeIds);
57
+
58
+ for (const action of [...legacyRead, ...legacyWrite]) {
59
+ await action.destroy();
60
+ }
61
+
62
+ await repositoryResource.writeToACL({ acl: this.app.acl });
63
+ await gitManagerResource.writeToACL({ acl: this.app.acl });
64
+ }
65
+ }
66
+ }
@@ -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,20 @@ 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';
15
+ import { enforceRepositoryAccess } from './repository-access';
13
16
 
14
17
  export class PluginGitManagerServer extends Plugin {
15
18
  // @ts-ignore
16
19
  declare app: any;
17
20
  // @ts-ignore
18
21
  declare db: any;
22
+ registryContentService: RegistryGitContentService;
23
+
24
+ async afterAdd() {
25
+ this.registryContentService = new RegistryGitContentService((this as unknown as { db: Database }).db);
26
+ }
27
+
19
28
  async beforeLoad() {
20
29
  await (this as any).app.db.import({
21
30
  directory: resolve(__dirname, 'collections'),
@@ -68,6 +77,8 @@ export class PluginGitManagerServer extends Plugin {
68
77
  },
69
78
  });
70
79
 
80
+ (this as any).app.resourceManager.use(enforceRepositoryAccess);
81
+
71
82
  // Suppress noisy workflow pre-action/post-action warnings for custom resources
72
83
  (this as any).app.use(async (ctx, next) => {
73
84
  if (ctx.logger && ctx.logger.warn) {
@@ -188,10 +199,15 @@ export class PluginGitManagerServer extends Plugin {
188
199
  (this as any).app.acl.registerSnippet({
189
200
  name: `pm.${(this as any).name}.manage`,
190
201
  actions: [
191
- `pm.${(this as any).name}.repositories`,
192
- `pm.${(this as any).name}.read`,
193
- `pm.${(this as any).name}.write`,
194
- `pm.${(this as any).name}.subtreeReplace`,
202
+ // ACL snippet actions are resource:action patterns; nested snippet names
203
+ // are not expanded by the core snippet manager.
204
+ 'gitRepositories:*',
205
+ 'gitAccounts:*',
206
+ 'gitReviewFlows:*',
207
+ 'gitCodeReviews:*',
208
+ 'gitSubtreeConfigs:*',
209
+ 'gitSubtreeRuns:*',
210
+ 'gitManager:*',
195
211
  ],
196
212
  });
197
213
 
@@ -0,0 +1,64 @@
1
+ const REPOSITORY_SCOPED_ACTIONS = new Set([
2
+ 'clone',
3
+ 'pull',
4
+ 'push',
5
+ 'fetch',
6
+ 'diff',
7
+ 'status',
8
+ 'log',
9
+ 'branches',
10
+ 'checkout',
11
+ 'fileTree',
12
+ 'fileContent',
13
+ 'commitDetail',
14
+ 'mergeRequests',
15
+ 'mergeRequestDetail',
16
+ 'mergeRequestNotes',
17
+ 'triggerReview',
18
+ 'pollNow',
19
+ 'subtreePreview',
20
+ 'subtreeOptions',
21
+ ]);
22
+
23
+ type PermissionResult = { params?: { filter?: unknown } } | null;
24
+
25
+ function scopeIncludesRepository(filter: unknown, repositoryId: number | string): boolean {
26
+ if (!filter || typeof filter !== 'object') return true;
27
+ const scope = filter as Record<string, unknown>;
28
+ if (Object.keys(scope).length === 0) return true;
29
+ if (Array.isArray(scope.$and)) {
30
+ return scope.$and.every((condition) => scopeIncludesRepository(condition, repositoryId));
31
+ }
32
+ if (Array.isArray(scope.$or)) {
33
+ return scope.$or.some((condition) => scopeIncludesRepository(condition, repositoryId));
34
+ }
35
+ const id = scope.id;
36
+ if (id && typeof id === 'object') {
37
+ const allowedIds = (id as { $in?: Array<number | string> }).$in;
38
+ return Array.isArray(allowedIds) && allowedIds.some((allowedId) => String(allowedId) === String(repositoryId));
39
+ }
40
+ return false;
41
+ }
42
+
43
+ export async function enforceRepositoryAccess(ctx: any, next: () => Promise<void>) {
44
+ if (ctx.action?.resourceName !== 'gitManager' || !REPOSITORY_SCOPED_ACTIONS.has(ctx.action?.actionName)) {
45
+ return next();
46
+ }
47
+
48
+ const repositoryId = ctx.action.params?.repositoryId;
49
+ if (repositoryId == null) return next();
50
+
51
+ const roles = Array.isArray(ctx.state?.currentRoles) ? ctx.state.currentRoles : [];
52
+ if (roles.includes('root')) return next();
53
+
54
+ const permission = (await ctx.app.acl.can({
55
+ roles,
56
+ resource: 'gitManager',
57
+ action: ctx.action.actionName,
58
+ })) as PermissionResult;
59
+ if (!permission || !scopeIncludesRepository(permission.params?.filter, repositoryId)) {
60
+ return ctx.throw(403, 'Permission denied');
61
+ }
62
+
63
+ return next();
64
+ }
@@ -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
+ }