plugin-git-manager 1.2.27 → 1.2.28

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