@sentropic/artifacts 0.2.17 → 0.2.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/README.md +14 -0
- package/dist/adapters/github-forge.d.ts +4 -0
- package/dist/adapters/github-forge.js +88 -0
- package/dist/adapters/github-git-port.d.ts +5 -0
- package/dist/adapters/github-git-port.js +102 -0
- package/dist/adapters/github-http.d.ts +5 -0
- package/dist/adapters/github-http.js +57 -0
- package/dist/adapters/github-receive-pack.d.ts +4 -0
- package/dist/adapters/github-receive-pack.js +49 -0
- package/dist/adapters/postgres-git-bindings.d.ts +7 -0
- package/dist/adapters/postgres-git-bindings.js +131 -0
- package/dist/adapters/postgres-live.d.ts +4 -0
- package/dist/adapters/postgres-live.js +97 -0
- package/dist/adapters/postgres.d.ts +1 -0
- package/dist/adapters/postgres.js +1 -0
- package/dist/git-tool-definitions.d.ts +606 -0
- package/dist/git-tool-definitions.js +14 -0
- package/dist/http.d.ts +9 -0
- package/dist/http.js +31 -2
- package/dist/index.d.ts +14 -0
- package/dist/index.js +13 -0
- package/dist/live-host/accept.d.ts +30 -0
- package/dist/live-host/accept.js +43 -0
- package/dist/live-host/api.d.ts +67 -0
- package/dist/live-host/api.js +60 -0
- package/dist/live-host/candidate.d.ts +21 -0
- package/dist/live-host/candidate.js +41 -0
- package/dist/live-host/errors.d.ts +9 -0
- package/dist/live-host/errors.js +14 -0
- package/dist/live-host/handoff.d.ts +63 -0
- package/dist/live-host/handoff.js +66 -0
- package/dist/live-host/index.d.ts +10 -0
- package/dist/live-host/index.js +10 -0
- package/dist/live-host/keys.d.ts +14 -0
- package/dist/live-host/keys.js +8 -0
- package/dist/live-host/live-format.d.ts +70 -0
- package/dist/live-host/live-format.js +100 -0
- package/dist/live-host/recheck.d.ts +59 -0
- package/dist/live-host/recheck.js +45 -0
- package/dist/mcp-core.d.ts +3 -3
- package/dist/mcp-core.js +18 -2
- package/dist/profile/contracts.d.ts +1 -1
- package/dist/profile/contracts.js +4 -0
- package/dist/profile/index.js +8 -1
- package/dist/profile/schemas.js +19 -0
- package/dist/profile/validation.js +5 -1
- package/dist/server/build-contract.d.ts +64 -0
- package/dist/server/build-contract.js +58 -0
- package/dist/server/build-dependencies.d.ts +3 -0
- package/dist/server/build-dependencies.js +122 -0
- package/dist/server/consent-grant.d.ts +91 -0
- package/dist/server/consent-grant.js +89 -0
- package/dist/server/consent-screen.d.ts +21 -0
- package/dist/server/consent-screen.js +52 -0
- package/dist/server/failures.d.ts +3 -2
- package/dist/server/failures.js +30 -0
- package/dist/server/git-bindings.d.ts +10 -0
- package/dist/server/git-bindings.js +138 -0
- package/dist/server/git-contracts.d.ts +115 -0
- package/dist/server/git-contracts.js +1 -0
- package/dist/server/git-port-policy.d.ts +9 -0
- package/dist/server/git-port-policy.js +76 -0
- package/dist/server/git-port-read.d.ts +3 -0
- package/dist/server/git-port-read.js +95 -0
- package/dist/server/git-port-session.d.ts +38 -0
- package/dist/server/git-port-session.js +59 -0
- package/dist/server/git-port-tree.d.ts +8 -0
- package/dist/server/git-port-tree.js +92 -0
- package/dist/server/git-port-write.d.ts +6 -0
- package/dist/server/git-port-write.js +102 -0
- package/dist/server/git-port.d.ts +147 -0
- package/dist/server/git-port.js +8 -0
- package/dist/server/git-projection.d.ts +16 -0
- package/dist/server/git-projection.js +20 -0
- package/dist/server/git-registry.d.ts +37 -0
- package/dist/server/git-registry.js +39 -0
- package/dist/server/git-tools-attach.d.ts +8 -0
- package/dist/server/git-tools-attach.js +139 -0
- package/dist/server/git-tools-contracts.d.ts +59 -0
- package/dist/server/git-tools-contracts.js +1 -0
- package/dist/server/git-tools-fetch.d.ts +21 -0
- package/dist/server/git-tools-fetch.js +65 -0
- package/dist/server/git-tools-publish.d.ts +13 -0
- package/dist/server/git-tools-publish.js +66 -0
- package/dist/server/git-tools.d.ts +4 -0
- package/dist/server/git-tools.js +18 -0
- package/dist/server/live-body.d.ts +3 -0
- package/dist/server/live-body.js +28 -0
- package/dist/server/live-commit-outcome.d.ts +6 -0
- package/dist/server/live-commit-outcome.js +10 -0
- package/dist/server/live-commit.d.ts +11 -0
- package/dist/server/live-commit.js +133 -0
- package/dist/server/live-contracts.d.ts +62 -0
- package/dist/server/live-contracts.js +8 -0
- package/dist/server/live-crypto.d.ts +14 -0
- package/dist/server/live-crypto.js +50 -0
- package/dist/server/live-drafts.d.ts +61 -0
- package/dist/server/live-drafts.js +119 -0
- package/dist/server/live-errors.d.ts +23 -0
- package/dist/server/live-errors.js +9 -0
- package/dist/server/live-mutations.d.ts +18 -0
- package/dist/server/live-mutations.js +83 -0
- package/dist/server/live-read.d.ts +15 -0
- package/dist/server/live-read.js +95 -0
- package/dist/server/live-service.d.ts +3 -0
- package/dist/server/live-service.js +181 -0
- package/dist/server/live-store.d.ts +111 -0
- package/dist/server/live-store.js +80 -0
- package/dist/server/live-tree.d.ts +22 -0
- package/dist/server/live-tree.js +148 -0
- package/dist/server/live-worker.d.ts +10 -0
- package/dist/server/live-worker.js +55 -0
- package/dist/server/templates.js +26 -1
- package/migrations/0010_git_bindings.sql +82 -0
- package/migrations/0011_live_drafts.sql +42 -0
- package/migrations/0012_git_attach_intents.sql +19 -0
- package/package.json +17 -1
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/** G0 FROZEN v3 §2. Host records; never release profile or tool-definition state. */
|
|
2
|
+
export interface GitLiveSession {
|
|
3
|
+
liveSessionId: string;
|
|
4
|
+
bindingGeneration: number;
|
|
5
|
+
requestedBy: string;
|
|
6
|
+
state: 'starting' | 'running' | 'stopping' | 'stopped' | 'failed';
|
|
7
|
+
targetCommitSha: string;
|
|
8
|
+
appliedCommitSha: string | null;
|
|
9
|
+
previewPath: string | null;
|
|
10
|
+
startedAt: string;
|
|
11
|
+
lastActivityAt: string;
|
|
12
|
+
expiresAt: string;
|
|
13
|
+
stateDetail?: string;
|
|
14
|
+
}
|
|
15
|
+
export interface GitBinding {
|
|
16
|
+
artifactId: string;
|
|
17
|
+
storageScopeId: string;
|
|
18
|
+
repoId: string;
|
|
19
|
+
branch: string;
|
|
20
|
+
channel: 'personal' | 'shared';
|
|
21
|
+
personalPrincipalId: string | null;
|
|
22
|
+
subPath: string;
|
|
23
|
+
baseCommitSha: string;
|
|
24
|
+
headCommitSha: string | null;
|
|
25
|
+
releaseCommitSha: string | null;
|
|
26
|
+
autoPublish: boolean;
|
|
27
|
+
executor: 'caller' | 'ci' | 'sandbox';
|
|
28
|
+
pendingJobId: string | null;
|
|
29
|
+
pendingCommitSha: string | null;
|
|
30
|
+
state: 'attached' | 'syncing' | 'build_pending' | 'build_failed' | 'diverged' | 'paused' | 'detached' | 'error';
|
|
31
|
+
stateDetail?: string;
|
|
32
|
+
generation: number;
|
|
33
|
+
version: number;
|
|
34
|
+
attachedBy: string;
|
|
35
|
+
attachedAt: string;
|
|
36
|
+
updatedAt: string;
|
|
37
|
+
live?: GitLiveSession | null;
|
|
38
|
+
}
|
|
39
|
+
export interface GitBindingEvent {
|
|
40
|
+
id: string;
|
|
41
|
+
artifactId: string;
|
|
42
|
+
storageScopeId: string;
|
|
43
|
+
actorId: string;
|
|
44
|
+
action: 'attach' | 'pause' | 'resume' | 'detach' | 'commit' | 'inbound' | 'publish' | 'conflict' | 'resolve' | 'error';
|
|
45
|
+
beforeSha?: string;
|
|
46
|
+
afterSha?: string;
|
|
47
|
+
deliveryId?: string;
|
|
48
|
+
invocationId?: string;
|
|
49
|
+
/** A-LIVE §5.3.1: only on the attach event that verified creation of the branch; initialUnpublishedBranchEligible input. */
|
|
50
|
+
branchCreated?: true;
|
|
51
|
+
createdAt: string;
|
|
52
|
+
}
|
|
53
|
+
export interface GitReleaseIndex {
|
|
54
|
+
releaseId: string;
|
|
55
|
+
artifactId: string;
|
|
56
|
+
repoId: string;
|
|
57
|
+
branch: string;
|
|
58
|
+
commitSha: string;
|
|
59
|
+
treeSha?: string;
|
|
60
|
+
manifestDigest: string;
|
|
61
|
+
candidateDigest: string;
|
|
62
|
+
executor: 'caller' | 'ci' | 'sandbox';
|
|
63
|
+
verification: 'declared' | 'sha-verified' | 'builder-attested';
|
|
64
|
+
receiptId: string;
|
|
65
|
+
jobId: string;
|
|
66
|
+
buildRunId?: string;
|
|
67
|
+
attempt?: number;
|
|
68
|
+
createdAt: string;
|
|
69
|
+
}
|
|
70
|
+
/** Trusted storage input: SG3 derives commandHash and actor from the invocation, never tool arguments. */
|
|
71
|
+
export interface GitBindingWrite {
|
|
72
|
+
binding: GitBinding;
|
|
73
|
+
expectedVersion: number | null;
|
|
74
|
+
actorId: string;
|
|
75
|
+
idempotencyKey: string;
|
|
76
|
+
commandHash: string;
|
|
77
|
+
event: Pick<GitBindingEvent, 'action' | 'beforeSha' | 'afterSha' | 'deliveryId' | 'invocationId' | 'branchCreated'>;
|
|
78
|
+
}
|
|
79
|
+
/** Written before createBranch, keyed like the replay receipt, so a same-key retry knows the branch is its own. */
|
|
80
|
+
export interface GitAttachIntent {
|
|
81
|
+
storageScopeId: string;
|
|
82
|
+
artifactId: string;
|
|
83
|
+
actorId: string;
|
|
84
|
+
idempotencyKey: string;
|
|
85
|
+
commandHash: string;
|
|
86
|
+
repoId: string;
|
|
87
|
+
branch: string;
|
|
88
|
+
baseCommitSha: string;
|
|
89
|
+
createdAt: string;
|
|
90
|
+
}
|
|
91
|
+
export interface GitBindingStore {
|
|
92
|
+
get(storageScopeId: string, artifactId: string): Promise<GitBinding | undefined>;
|
|
93
|
+
/** Binding, audit and principal-scoped replay receipt commit atomically. */
|
|
94
|
+
write(input: GitBindingWrite): Promise<{
|
|
95
|
+
binding: GitBinding;
|
|
96
|
+
replayed: boolean;
|
|
97
|
+
}>;
|
|
98
|
+
events(storageScopeId: string, artifactId: string): Promise<GitBindingEvent[]>;
|
|
99
|
+
/** Durable put-if-absent by (scope, actor, key); returns the stored intent, which wins over the input. */
|
|
100
|
+
reserveAttachIntent(intent: GitAttachIntent): Promise<GitAttachIntent>;
|
|
101
|
+
attachIntent(storageScopeId: string, actorId: string, idempotencyKey: string): Promise<GitAttachIntent | undefined>;
|
|
102
|
+
}
|
|
103
|
+
/** SG4 writes the index using its release-transaction client; SG1 provides the record/read port. */
|
|
104
|
+
export interface GitReleaseIndexStore {
|
|
105
|
+
get(storageScopeId: string, releaseId: string): Promise<GitReleaseIndex | undefined>;
|
|
106
|
+
forCommit(storageScopeId: string, artifactId: string, commitSha: string): Promise<GitReleaseIndex[]>;
|
|
107
|
+
}
|
|
108
|
+
/** Repository code access is independent of artifact/page/source grants and shell roles. */
|
|
109
|
+
export interface GitCodeRightsPort {
|
|
110
|
+
canReadCode(input: {
|
|
111
|
+
storageScopeId: string;
|
|
112
|
+
repoId: string;
|
|
113
|
+
actorId: string;
|
|
114
|
+
}): Promise<boolean>;
|
|
115
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { GitPortRepository, GitPortTarget } from './git-port.js';
|
|
2
|
+
export declare const isGitSha: (sha: string) => boolean;
|
|
3
|
+
export declare function assertGitSha(sha: string): void;
|
|
4
|
+
export declare function assertGitBranch(branch: string): void;
|
|
5
|
+
export declare function assertGitReadRef(ref: string): void;
|
|
6
|
+
export declare function assertGitTarget(repo: GitPortRepository, target: GitPortTarget, write: boolean): void;
|
|
7
|
+
/** Small host-glob language: * stays inside one segment; ** spans complete subtrees. */
|
|
8
|
+
export declare function matchesGitGlob(path: string, glob: string): boolean;
|
|
9
|
+
export declare function gitPath(repo: GitPortRepository, target: GitPortTarget, path: string, write: boolean): string;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { ArtifactOperationError } from './failures.js';
|
|
2
|
+
export const isGitSha = (sha) => /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(sha);
|
|
3
|
+
export function assertGitSha(sha) {
|
|
4
|
+
if (!isGitSha(sha))
|
|
5
|
+
throw new ArtifactOperationError('invalid_request');
|
|
6
|
+
}
|
|
7
|
+
export function assertGitBranch(branch) {
|
|
8
|
+
if (!branch.startsWith('artifact/') || /[\x00-\x20\x7f~^:?*\[\\]/.test(branch) ||
|
|
9
|
+
branch.includes('..') || branch.includes('@{') || branch.endsWith('.') ||
|
|
10
|
+
branch.split('/').some(p => !p || p.startsWith('.') || p.endsWith('.lock'))) {
|
|
11
|
+
throw new ArtifactOperationError('git_ref_not_allowed');
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function assertGitReadRef(ref) {
|
|
15
|
+
if (!ref || ref.length > 1024 || /[\x00-\x20\x7f~^:?*\[\\]/.test(ref) || ref.includes('..') ||
|
|
16
|
+
ref.includes('@{') || ref.endsWith('.') || ref.split('/').some(p => !p || p.startsWith('.') || p.endsWith('.lock'))) {
|
|
17
|
+
throw new ArtifactOperationError('git_ref_not_allowed');
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export function assertGitTarget(repo, target, write) {
|
|
21
|
+
if (repo.storageScopeId !== target.storageScopeId || repo.repoId !== target.repoId) {
|
|
22
|
+
throw new ArtifactOperationError('git_repo_not_registered');
|
|
23
|
+
}
|
|
24
|
+
if (!repo.allowedSubPaths.includes(target.subPath) || (write && !repo.canWrite)) {
|
|
25
|
+
throw new ArtifactOperationError('git_ref_not_allowed');
|
|
26
|
+
}
|
|
27
|
+
if (write)
|
|
28
|
+
assertGitBranch(target.branch);
|
|
29
|
+
else
|
|
30
|
+
assertGitReadRef(target.branch);
|
|
31
|
+
if (target.subPath)
|
|
32
|
+
safePath(target.subPath);
|
|
33
|
+
safePath(target.outputDir);
|
|
34
|
+
}
|
|
35
|
+
function refused(path, reason) {
|
|
36
|
+
throw new ArtifactOperationError('git_path_refused', { publicDetails: { path, reason } });
|
|
37
|
+
}
|
|
38
|
+
function safePath(path) {
|
|
39
|
+
if (!path || Buffer.byteLength(path) > 1024 || Buffer.from(path).toString('utf8') !== path ||
|
|
40
|
+
/[\x00-\x1f\x7f\\%:?#]/.test(path) || path !== path.normalize('NFC') ||
|
|
41
|
+
path.split('/').some(p => !p || p === '.' || p === '..' || /[. ]$/.test(p)))
|
|
42
|
+
refused(path, 'noncanonical');
|
|
43
|
+
for (const part of path.split('/')) {
|
|
44
|
+
if (/^(?:\.git|\.github|\.ssh|\.npmrc)$/i.test(part) || /^\.yarnrc/i.test(part) || /^\.env/i.test(part) ||
|
|
45
|
+
/\.(?:pem|key|p12|pfx|p8|jks|keystore)$/i.test(part) ||
|
|
46
|
+
/^(?:id_(?:rsa|dsa|ecdsa|ed25519)|private[_-]?key)(?:\.|$)/i.test(part))
|
|
47
|
+
refused(path, 'reserved');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** Small host-glob language: * stays inside one segment; ** spans complete subtrees. */
|
|
51
|
+
export function matchesGitGlob(path, glob) {
|
|
52
|
+
const segment = (part) => new RegExp(`^${part.split('*').map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*')}$`);
|
|
53
|
+
const parts = path.split('/');
|
|
54
|
+
const pattern = glob.split('/');
|
|
55
|
+
function match(i, j) {
|
|
56
|
+
if (j === pattern.length)
|
|
57
|
+
return i === parts.length;
|
|
58
|
+
if (pattern[j] === '**')
|
|
59
|
+
return match(i, j + 1) || (i < parts.length && match(i + 1, j));
|
|
60
|
+
return i < parts.length && segment(pattern[j]).test(parts[i]) && match(i + 1, j + 1);
|
|
61
|
+
}
|
|
62
|
+
// A basename-only denial (package*.json) applies at every depth.
|
|
63
|
+
return !glob.includes('/') ? segment(glob).test(parts.at(-1)) : match(0, 0);
|
|
64
|
+
}
|
|
65
|
+
export function gitPath(repo, target, path, write) {
|
|
66
|
+
safePath(path);
|
|
67
|
+
const full = target.subPath ? `${target.subPath}/${path}` : path;
|
|
68
|
+
safePath(full);
|
|
69
|
+
if (write) {
|
|
70
|
+
const output = target.outputDir;
|
|
71
|
+
if (`/${path}/`.includes(`/${output}/`) || repo.refusedWritePaths.some(g => matchesGitGlob(full, g)) ||
|
|
72
|
+
!repo.writablePaths.some(g => matchesGitGlob(full, g)))
|
|
73
|
+
refused(path, 'write_policy');
|
|
74
|
+
}
|
|
75
|
+
return full;
|
|
76
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { GitPort, GitPortRepository, GitPortTarget, GitSourcePage } from './git-port.js';
|
|
2
|
+
import type { GitPortOptions, GitPortSession } from './git-port-session.js';
|
|
3
|
+
export declare function gitSourceReader(options: GitPortOptions, open: (repo: GitPortRepository) => Promise<GitPortSession>): (repo: GitPortRepository, target: GitPortTarget, input: Parameters<GitPort['read']>[1]) => Promise<GitSourcePage>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { ArtifactOperationError } from './failures.js';
|
|
3
|
+
import { assertGitSha, gitPath } from './git-port-policy.js';
|
|
4
|
+
import { gitTrees } from './git-port-tree.js';
|
|
5
|
+
export function gitSourceReader(options, open) {
|
|
6
|
+
const mac = (data) => createHmac('sha256', options.cursorKey).update(data).digest('base64url');
|
|
7
|
+
return async (repo, target, input) => {
|
|
8
|
+
assertGitSha(input.commitSha);
|
|
9
|
+
if (input.paths && (!input.paths.length || input.paths.length > 255 || new Set(input.paths).size !== input.paths.length)) {
|
|
10
|
+
throw new ArtifactOperationError('invalid_request');
|
|
11
|
+
}
|
|
12
|
+
input.paths?.forEach(path => gitPath(repo, target, path, false));
|
|
13
|
+
const identity = mac(JSON.stringify([target, input.commitSha, input.paths ?? null]));
|
|
14
|
+
let offset = 0;
|
|
15
|
+
let total = 0;
|
|
16
|
+
if (input.cursor) {
|
|
17
|
+
try {
|
|
18
|
+
if (input.cursor.length > 4096)
|
|
19
|
+
throw new Error();
|
|
20
|
+
const parts = input.cursor.split('.');
|
|
21
|
+
if (parts.length !== 2 || !timingSafeEqual(Buffer.from(mac(parts[0])), Buffer.from(parts[1])))
|
|
22
|
+
throw new Error();
|
|
23
|
+
const data = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8'));
|
|
24
|
+
if (data.identity !== identity || !Number.isSafeInteger(data.offset) || data.offset < 0 ||
|
|
25
|
+
!Number.isSafeInteger(data.total) || data.total < 0)
|
|
26
|
+
throw new Error();
|
|
27
|
+
offset = data.offset;
|
|
28
|
+
total = data.total;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new ArtifactOperationError('invalid_request');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const session = await open(repo);
|
|
35
|
+
const trees = gitTrees(session);
|
|
36
|
+
const root = await trees.root(input.commitSha);
|
|
37
|
+
let entries;
|
|
38
|
+
if (input.paths) {
|
|
39
|
+
entries = [];
|
|
40
|
+
for (const path of input.paths) {
|
|
41
|
+
const entry = await trees.lookup(root, gitPath(repo, target, path, false));
|
|
42
|
+
if (!entry)
|
|
43
|
+
throw new ArtifactOperationError('not_found');
|
|
44
|
+
if (entry.type !== 'blob')
|
|
45
|
+
throw new ArtifactOperationError('git_path_refused', { publicDetails: { path, reason: 'not_file' } });
|
|
46
|
+
entries.push({ ...entry, path });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
else
|
|
50
|
+
entries = await trees.enumerate(root, target);
|
|
51
|
+
if (offset > entries.length)
|
|
52
|
+
throw new ArtifactOperationError('invalid_request');
|
|
53
|
+
const files = [];
|
|
54
|
+
const page = entries.slice(offset, offset + (options.pageSize ?? 100));
|
|
55
|
+
for (const entry of page) {
|
|
56
|
+
let reason;
|
|
57
|
+
const maxFile = options.maxFileBytes ?? 1024 * 1024;
|
|
58
|
+
const maxTotal = options.maxTotalBytes ?? 8 * 1024 * 1024;
|
|
59
|
+
if ((entry.size ?? 0) > maxFile)
|
|
60
|
+
reason = 'too_large';
|
|
61
|
+
else if (total + (entry.size ?? 0) > maxTotal)
|
|
62
|
+
reason = 'over_total_budget';
|
|
63
|
+
if (reason) {
|
|
64
|
+
files.push({ path: entry.path, omitted: reason });
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const bytes = await session.call((forge, context) => forge.blob(context, entry.sha));
|
|
68
|
+
if (bytes.length > maxFile)
|
|
69
|
+
reason = 'too_large';
|
|
70
|
+
else if (total + bytes.length > maxTotal)
|
|
71
|
+
reason = 'over_total_budget';
|
|
72
|
+
if (reason) {
|
|
73
|
+
files.push({ path: entry.path, omitted: reason });
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (/-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/.test(Buffer.from(bytes).toString('utf8'))) {
|
|
77
|
+
throw new ArtifactOperationError('git_path_refused', { publicDetails: { path: entry.path, reason: 'private_key' } });
|
|
78
|
+
}
|
|
79
|
+
total += bytes.length;
|
|
80
|
+
try {
|
|
81
|
+
const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
82
|
+
if (bytes.includes(0))
|
|
83
|
+
throw new Error();
|
|
84
|
+
files.push({ path: entry.path, text, encoding: 'utf-8' });
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
files.push({ path: entry.path, base64: Buffer.from(bytes).toString('base64'), encoding: 'base64' });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const next = offset + page.length;
|
|
91
|
+
const payload = Buffer.from(JSON.stringify({ identity, offset: next, total })).toString('base64url');
|
|
92
|
+
return { commitSha: input.commitSha, treeSha: root, files,
|
|
93
|
+
nextCursor: next < entries.length ? `${payload}.${mac(payload)}` : null };
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { ArtifactOperationError } from './failures.js';
|
|
2
|
+
import type { GitForge, GitForgeContext, GitHumanDirectory, GitIdentity, GitInstallationLeasePort, GitPortRepository, GitPortTarget } from './git-port.js';
|
|
3
|
+
export interface GitPortOptions {
|
|
4
|
+
registry: {
|
|
5
|
+
get(scope: string, repoId: string): Promise<GitPortRepository | undefined>;
|
|
6
|
+
};
|
|
7
|
+
leases?: GitInstallationLeasePort;
|
|
8
|
+
forge: GitForge;
|
|
9
|
+
directory: GitHumanDirectory;
|
|
10
|
+
committer: GitIdentity;
|
|
11
|
+
/** Current code rights, plus owner-only on writes; host resolves identity and binding. */
|
|
12
|
+
authorize(target: GitPortTarget, write: boolean): Promise<boolean>;
|
|
13
|
+
/** Host-owned stable cursor MAC key; never a forge/App credential. */
|
|
14
|
+
cursorKey: Uint8Array;
|
|
15
|
+
now?: () => number;
|
|
16
|
+
pageSize?: number;
|
|
17
|
+
maxFileBytes?: number;
|
|
18
|
+
maxTotalBytes?: number;
|
|
19
|
+
}
|
|
20
|
+
export interface GitPortSession {
|
|
21
|
+
repo: GitPortRepository;
|
|
22
|
+
call<T>(action: (forge: GitForge, context: GitForgeContext) => Promise<T>): Promise<T>;
|
|
23
|
+
}
|
|
24
|
+
/** A lost receive-pack acknowledgement must be reconciled by SG3, never retried as a new invocation. */
|
|
25
|
+
export declare class GitPortAdvanceUnknown extends ArtifactOperationError {
|
|
26
|
+
readonly commitState = "unknown";
|
|
27
|
+
constructor();
|
|
28
|
+
}
|
|
29
|
+
export declare function gitSessions(options: GitPortOptions): {
|
|
30
|
+
admit: (target: GitPortTarget, write: boolean) => Promise<GitPortRepository>;
|
|
31
|
+
open: (repo: GitPortRepository) => Promise<GitPortSession>;
|
|
32
|
+
invalidate(input: {
|
|
33
|
+
storageScopeId: string;
|
|
34
|
+
repoId: string;
|
|
35
|
+
installationRef: string;
|
|
36
|
+
credentialVersion: string;
|
|
37
|
+
}): void;
|
|
38
|
+
};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { ArtifactOperationError } from './failures.js';
|
|
2
|
+
import { GitForgeError } from './git-port.js';
|
|
3
|
+
import { assertGitTarget } from './git-port-policy.js';
|
|
4
|
+
/** A lost receive-pack acknowledgement must be reconciled by SG3, never retried as a new invocation. */
|
|
5
|
+
export class GitPortAdvanceUnknown extends ArtifactOperationError {
|
|
6
|
+
commitState = 'unknown';
|
|
7
|
+
constructor() { super('provider_unavailable'); }
|
|
8
|
+
}
|
|
9
|
+
export function gitSessions(options) {
|
|
10
|
+
const invalidated = new Set();
|
|
11
|
+
const key = (target, version) => JSON.stringify([target.storageScopeId, target.repoId, target.installationRef, version]);
|
|
12
|
+
async function admit(target, write) {
|
|
13
|
+
if (!await options.authorize(target, write))
|
|
14
|
+
throw new ArtifactOperationError('access_denied');
|
|
15
|
+
const repo = await options.registry.get(target.storageScopeId, target.repoId);
|
|
16
|
+
if (!repo)
|
|
17
|
+
throw new ArtifactOperationError('git_repo_not_registered');
|
|
18
|
+
assertGitTarget(repo, target, write);
|
|
19
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repo.locator) || !repo.installationRef)
|
|
20
|
+
throw new ArtifactOperationError('provider_unavailable');
|
|
21
|
+
return repo;
|
|
22
|
+
}
|
|
23
|
+
async function open(repo) {
|
|
24
|
+
if (!options.leases)
|
|
25
|
+
throw new ArtifactOperationError('provider_unavailable');
|
|
26
|
+
let lease;
|
|
27
|
+
try {
|
|
28
|
+
lease = await options.leases.acquire({ storageScopeId: repo.storageScopeId, repoId: repo.repoId, installationRef: repo.installationRef });
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
// SG0-app errors cross a structural port; never carry their message/body/cause onward.
|
|
32
|
+
throw new ArtifactOperationError(error?.code === 'access_denied' ? 'access_denied' : 'provider_unavailable');
|
|
33
|
+
}
|
|
34
|
+
const valid = () => lease && typeof lease.token === 'string' && !!lease.token &&
|
|
35
|
+
typeof lease.repositoryId === 'string' && !!lease.repositoryId && typeof lease.credentialVersion === 'string' && !!lease.credentialVersion &&
|
|
36
|
+
Date.parse(lease.expiresAt) > (options.now?.() ?? Date.now()) + 30_000 &&
|
|
37
|
+
lease.permissions?.contents === 'write' && lease.permissions.metadata === 'read' &&
|
|
38
|
+
Object.keys(lease.permissions).length === 2 && !invalidated.has(key(repo, lease.credentialVersion));
|
|
39
|
+
const session = { repo, async call(action) {
|
|
40
|
+
if (!valid())
|
|
41
|
+
throw new ArtifactOperationError('provider_unavailable');
|
|
42
|
+
try {
|
|
43
|
+
return await action(options.forge, { locator: repo.locator, token: lease.token });
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (error instanceof GitForgeError)
|
|
47
|
+
throw error;
|
|
48
|
+
throw new ArtifactOperationError('provider_unavailable');
|
|
49
|
+
}
|
|
50
|
+
} };
|
|
51
|
+
if (await session.call((forge, context) => forge.repositoryId(context)) !== lease.repositoryId) {
|
|
52
|
+
throw new ArtifactOperationError('access_denied');
|
|
53
|
+
}
|
|
54
|
+
return session;
|
|
55
|
+
}
|
|
56
|
+
return { admit, open, invalidate(input) {
|
|
57
|
+
invalidated.add(key(input, input.credentialVersion));
|
|
58
|
+
} };
|
|
59
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { GitPortTarget, GitTreeEntry } from './git-port.js';
|
|
2
|
+
import type { GitPortSession } from './git-port-session.js';
|
|
3
|
+
export declare function gitTrees(session: GitPortSession): {
|
|
4
|
+
root: (commitSha: string) => Promise<string>;
|
|
5
|
+
tree: (sha: string) => Promise<GitTreeEntry[]>;
|
|
6
|
+
lookup: (treeSha: string, path: string) => Promise<GitTreeEntry | undefined>;
|
|
7
|
+
enumerate: (treeSha: string, target: GitPortTarget) => Promise<GitTreeEntry[]>;
|
|
8
|
+
};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { ArtifactOperationError } from './failures.js';
|
|
2
|
+
import { GitForgeError } from './git-port.js';
|
|
3
|
+
import { assertGitSha, gitPath } from './git-port-policy.js';
|
|
4
|
+
export function gitTrees(session) {
|
|
5
|
+
const cache = new Map();
|
|
6
|
+
let entries = 0;
|
|
7
|
+
async function tree(sha) {
|
|
8
|
+
assertGitSha(sha);
|
|
9
|
+
if (!cache.has(sha)) {
|
|
10
|
+
if (cache.size >= 4096)
|
|
11
|
+
throw new ArtifactOperationError('limit_exceeded');
|
|
12
|
+
const result = await session.call((forge, context) => forge.tree(context, sha));
|
|
13
|
+
entries += result.length;
|
|
14
|
+
if (entries > 1_000_000)
|
|
15
|
+
throw new ArtifactOperationError('limit_exceeded');
|
|
16
|
+
const names = new Set();
|
|
17
|
+
for (const entry of result) {
|
|
18
|
+
if (!entry.path || entry.path.includes('/') || names.has(entry.path))
|
|
19
|
+
throw new ArtifactOperationError('provider_unavailable');
|
|
20
|
+
names.add(entry.path);
|
|
21
|
+
assertGitSha(entry.sha);
|
|
22
|
+
}
|
|
23
|
+
cache.set(sha, result);
|
|
24
|
+
}
|
|
25
|
+
return cache.get(sha);
|
|
26
|
+
}
|
|
27
|
+
async function root(commitSha) {
|
|
28
|
+
try {
|
|
29
|
+
const commit = await session.call((forge, context) => forge.resolve(context, commitSha));
|
|
30
|
+
if (commit.sha !== commitSha)
|
|
31
|
+
throw new ArtifactOperationError('provider_unavailable');
|
|
32
|
+
assertGitSha(commit.treeSha);
|
|
33
|
+
return commit.treeSha;
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error instanceof GitForgeError && error.code === 'missing')
|
|
37
|
+
throw new ArtifactOperationError('not_found');
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function lookup(treeSha, path) {
|
|
42
|
+
const parts = path.split('/');
|
|
43
|
+
for (const [i, part] of parts.entries()) {
|
|
44
|
+
const entry = (await tree(treeSha)).find(e => e.path === part);
|
|
45
|
+
if (!entry)
|
|
46
|
+
return undefined;
|
|
47
|
+
if (!['040000', '100644', '100755'].includes(entry.mode) || entry.type === 'commit') {
|
|
48
|
+
throw new ArtifactOperationError('git_path_refused', { publicDetails: { path, reason: 'path_alias' } });
|
|
49
|
+
}
|
|
50
|
+
if (i === parts.length - 1)
|
|
51
|
+
return entry;
|
|
52
|
+
if (entry.type !== 'tree' || entry.mode !== '040000') {
|
|
53
|
+
throw new ArtifactOperationError('git_path_refused', { publicDetails: { path, reason: 'not_directory' } });
|
|
54
|
+
}
|
|
55
|
+
treeSha = entry.sha;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function enumerate(treeSha, target) {
|
|
59
|
+
if (target.subPath) {
|
|
60
|
+
const base = await lookup(treeSha, target.subPath);
|
|
61
|
+
if (!base || base.type !== 'tree')
|
|
62
|
+
throw new ArtifactOperationError('not_found');
|
|
63
|
+
treeSha = base.sha;
|
|
64
|
+
}
|
|
65
|
+
const files = [];
|
|
66
|
+
let traversed = 0;
|
|
67
|
+
async function walk(sha, prefix, depth) {
|
|
68
|
+
if (depth > 128)
|
|
69
|
+
throw new ArtifactOperationError('limit_exceeded');
|
|
70
|
+
for (const entry of await tree(sha)) {
|
|
71
|
+
if (++traversed > 1_000_000)
|
|
72
|
+
throw new ArtifactOperationError('limit_exceeded');
|
|
73
|
+
const path = `${prefix}${entry.path}`;
|
|
74
|
+
try {
|
|
75
|
+
gitPath(session.repo, target, path, false);
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (error instanceof ArtifactOperationError && error.kind === 'git_path_refused')
|
|
79
|
+
continue;
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
if (entry.type === 'tree' && entry.mode === '040000')
|
|
83
|
+
await walk(entry.sha, `${path}/`, depth + 1);
|
|
84
|
+
else if (entry.type === 'blob' && ['100644', '100755'].includes(entry.mode))
|
|
85
|
+
files.push({ ...entry, path });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
await walk(treeSha, '', 0);
|
|
89
|
+
return files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
90
|
+
}
|
|
91
|
+
return { root, tree, lookup, enumerate };
|
|
92
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { GitCommitInput } from './git-port.js';
|
|
2
|
+
import type { GitPortOptions, gitSessions } from './git-port-session.js';
|
|
3
|
+
export declare function gitWriter(options: GitPortOptions, sessions: ReturnType<typeof gitSessions>): (input: GitCommitInput) => Promise<{
|
|
4
|
+
commitSha: string;
|
|
5
|
+
treeSha: string;
|
|
6
|
+
}>;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { ArtifactOperationError } from './failures.js';
|
|
2
|
+
import { GitForgeError } from './git-port.js';
|
|
3
|
+
import { GitPortAdvanceUnknown } from './git-port-session.js';
|
|
4
|
+
import { assertGitSha, gitPath } from './git-port-policy.js';
|
|
5
|
+
import { gitTrees } from './git-port-tree.js';
|
|
6
|
+
const validIdentity = (identity) => !!identity &&
|
|
7
|
+
!!identity.name.trim() && identity.name.length <= 256 && /^[^\s<>@]+@[^\s<>@]+$/.test(identity.email) &&
|
|
8
|
+
!/[\r\n\x00<>]/.test(identity.name);
|
|
9
|
+
export function gitWriter(options, sessions) {
|
|
10
|
+
return async (input) => {
|
|
11
|
+
const { target, expectedHeadSha } = input;
|
|
12
|
+
const repo = await sessions.admit(target, true);
|
|
13
|
+
assertGitSha(expectedHeadSha);
|
|
14
|
+
if (!input.files.length || input.files.length > 255 || !input.message.trim() || input.message.length > 16384 ||
|
|
15
|
+
/^Artifacts-(?:Artifact|Invocation|Base):/mi.test(input.message) ||
|
|
16
|
+
!Number.isFinite(Date.parse(input.createdAt)) || new Date(input.createdAt).toISOString() !== input.createdAt ||
|
|
17
|
+
!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(input.artifactId) ||
|
|
18
|
+
!/^[\w.-]{1,128}$/.test(input.invocationId))
|
|
19
|
+
throw new ArtifactOperationError('invalid_request');
|
|
20
|
+
const paths = input.files.map(file => gitPath(repo, target, file.path, true));
|
|
21
|
+
if (new Set(paths).size !== paths.length)
|
|
22
|
+
throw new ArtifactOperationError('invalid_request');
|
|
23
|
+
let bytes = 0;
|
|
24
|
+
for (const file of input.files) {
|
|
25
|
+
if (file.text === null)
|
|
26
|
+
continue;
|
|
27
|
+
if (typeof file.text !== 'string' || /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/.test(file.text) ||
|
|
28
|
+
file.text.includes('\0') || Buffer.from(file.text).toString('utf8') !== file.text) {
|
|
29
|
+
throw new ArtifactOperationError('git_path_refused', { publicDetails: { path: file.path, reason: 'not_source_text' } });
|
|
30
|
+
}
|
|
31
|
+
const size = Buffer.byteLength(file.text);
|
|
32
|
+
bytes += size;
|
|
33
|
+
if (size > (options.maxFileBytes ?? 1024 * 1024) || bytes > (options.maxTotalBytes ?? 8 * 1024 * 1024)) {
|
|
34
|
+
throw new ArtifactOperationError('limit_exceeded');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
let author;
|
|
38
|
+
try {
|
|
39
|
+
author = await options.directory.resolve({ storageScopeId: target.storageScopeId, principalId: target.principalId });
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw new ArtifactOperationError('access_denied');
|
|
43
|
+
}
|
|
44
|
+
if (!validIdentity(author))
|
|
45
|
+
throw new ArtifactOperationError('access_denied');
|
|
46
|
+
if (!validIdentity(options.committer))
|
|
47
|
+
throw new ArtifactOperationError('provider_unavailable');
|
|
48
|
+
const session = await sessions.open(repo);
|
|
49
|
+
const head = async () => {
|
|
50
|
+
try {
|
|
51
|
+
return await session.call((forge, context) => forge.resolve(context, target.branch));
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (error instanceof GitForgeError && error.code === 'missing') {
|
|
55
|
+
throw new ArtifactOperationError('git_branch_missing', { publicDetails: { branch: target.branch } });
|
|
56
|
+
}
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
const moved = (actualHeadSha) => new ArtifactOperationError('git_head_moved', {
|
|
61
|
+
publicDetails: { expectedHeadSha, actualHeadSha },
|
|
62
|
+
});
|
|
63
|
+
const observed = await head();
|
|
64
|
+
if (observed.sha !== expectedHeadSha)
|
|
65
|
+
throw moved(observed.sha);
|
|
66
|
+
const trees = gitTrees(session);
|
|
67
|
+
const baseTree = await trees.root(expectedHeadSha);
|
|
68
|
+
const changes = [];
|
|
69
|
+
for (const [i, file] of input.files.entries()) {
|
|
70
|
+
const existing = await trees.lookup(baseTree, paths[i]);
|
|
71
|
+
if (existing?.type === 'tree')
|
|
72
|
+
throw new ArtifactOperationError('git_path_refused', { publicDetails: { path: file.path, reason: 'not_file' } });
|
|
73
|
+
if (!existing && file.text === null)
|
|
74
|
+
throw new ArtifactOperationError('invalid_request');
|
|
75
|
+
changes.push({ path: paths[i], text: file.text, mode: existing?.mode ?? '100644' });
|
|
76
|
+
}
|
|
77
|
+
if (!await options.authorize(target, true))
|
|
78
|
+
throw new ArtifactOperationError('access_denied');
|
|
79
|
+
const treeSha = await session.call((forge, context) => forge.createTree(context, baseTree, changes));
|
|
80
|
+
assertGitSha(treeSha);
|
|
81
|
+
const message = `${input.message}\n\nArtifacts-Artifact: ${input.artifactId}\nArtifacts-Invocation: ${input.invocationId}\nArtifacts-Base: ${expectedHeadSha}`;
|
|
82
|
+
const commitSha = await session.call((forge, context) => forge.createCommit(context, { parentSha: expectedHeadSha, treeSha, message, author, committer: options.committer, createdAt: input.createdAt }));
|
|
83
|
+
assertGitSha(commitSha);
|
|
84
|
+
if (!await options.authorize(target, true))
|
|
85
|
+
throw new ArtifactOperationError('access_denied');
|
|
86
|
+
let submitted = false;
|
|
87
|
+
try {
|
|
88
|
+
await session.call((forge, context) => { submitted = true; return forge.advance(context, target.branch, expectedHeadSha, commitSha); });
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (!submitted)
|
|
92
|
+
throw error;
|
|
93
|
+
if (error instanceof GitForgeError && error.code === 'conflict') {
|
|
94
|
+
const actual = (await head()).sha;
|
|
95
|
+
throw actual === expectedHeadSha ? new ArtifactOperationError('git_ref_not_allowed') : moved(actual);
|
|
96
|
+
}
|
|
97
|
+
// A transport failure after submission cannot prove whether the ref advanced.
|
|
98
|
+
throw new GitPortAdvanceUnknown();
|
|
99
|
+
}
|
|
100
|
+
return { commitSha, treeSha };
|
|
101
|
+
};
|
|
102
|
+
}
|