@ehven/git-release-guardrails 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,167 @@
1
+ import { realpath, lstat } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { fields, list, text, branch, branchList, objectFormat, objectId } from '../validation.mjs';
5
+ import { fail } from '../errors.mjs';
6
+ import { assertRemoteDestinations, normalizeRemoteUrl } from '../remote.mjs';
7
+ import { planRetirements } from '../plan.mjs';
8
+ import { gitReader } from './process.mjs';
9
+ import { readLiveAuthorization, validateAdvertisements } from './live-remote.mjs';
10
+
11
+ function lines(value) { return value === '' ? [] : value.replace(/\n$/u, '').split('\n'); }
12
+
13
+ function refs(value, remote, format, permanent) {
14
+ const local = Object.create(null), tracking = Object.create(null);
15
+ for (const line of lines(value)) {
16
+ const parts = line.split('\0');
17
+ if (parts.length !== 3) fail('ERR_GIT_PARSE', 'Git returned malformed ref data.');
18
+ const [name, sha, symbolic] = parts;
19
+ if (name === `refs/remotes/${remote}/HEAD` && symbolic) {
20
+ if (permanent && !permanent.some(branch => symbolic === `refs/remotes/${remote}/${branch}`)) {
21
+ fail('ERR_SYMBOLIC_REF', 'The remote-tracking HEAD must point to a permanent branch for execution.');
22
+ }
23
+ continue;
24
+ }
25
+ if (symbolic) fail('ERR_SYMBOLIC_REF', 'A branch ref is symbolic; review it before retirement.');
26
+ const map = name.startsWith('refs/heads/') ? local : name.startsWith(`refs/remotes/${remote}/`) ? tracking : undefined;
27
+ if (!map) fail('ERR_GIT_PARSE', 'Git returned an unexpected ref namespace.');
28
+ const short = name.slice(map === local ? 'refs/heads/'.length : `refs/remotes/${remote}/`.length);
29
+ branch(short); objectId(sha, format);
30
+ if (Object.hasOwn(map, short)) fail('ERR_GIT_PARSE', 'Git returned duplicate branch refs.');
31
+ map[short] = sha;
32
+ }
33
+ return { local, remote: tracking };
34
+ }
35
+
36
+ function worktrees(value, root, head, integration, format) {
37
+ const records = []; let record = Object.create(null);
38
+ for (const item of value.split('\0')) {
39
+ if (!item) { if (Object.keys(record).length) records.push(record); record = Object.create(null); continue; }
40
+ const index = item.indexOf(' '), key = index < 0 ? item : item.slice(0, index), data = index < 0 ? true : item.slice(index + 1);
41
+ if (!['worktree', 'HEAD', 'branch', 'bare', 'detached', 'locked', 'prunable'].includes(key) || Object.hasOwn(record, key)) {
42
+ fail('ERR_GIT_PARSE', 'Git returned unsupported worktree data.');
43
+ }
44
+ record[key] = data;
45
+ }
46
+ if (Object.keys(record).length) records.push(record);
47
+ if (records.length !== 1 || records[0].worktree !== root || records[0].branch !== `refs/heads/${integration}`
48
+ || records[0].HEAD !== head || ['bare', 'detached', 'locked', 'prunable'].some(key => Object.hasOwn(records[0], key))) {
49
+ fail('ERR_WORKTREE', 'Require one clean attached worktree; linked, detached or uncertain worktrees need review.');
50
+ }
51
+ objectId(records[0].HEAD, format);
52
+ return [{ path: root, branch: integration, head }];
53
+ }
54
+
55
+ /** Local-cache inspection only. */
56
+ export async function inspectRetirements(input) { return (await inspectRetirementState(input)).result; }
57
+
58
+ /** Read-only live comparison against the effective fetch and push endpoints. */
59
+ export async function validateLiveRetirement(input) { return (await inspectRetirementState(input, { live: true })).result; }
60
+
61
+ export function retirementPlanId(state) {
62
+ return createHash('sha256').update(JSON.stringify(state)).digest('hex');
63
+ }
64
+
65
+ export async function inspectRetirementState(input, { live = false, execution = false } = {}) {
66
+ const keys = ['cwd', 'repository', 'expectedRemoteUrls', 'remote', 'integrationBranch', 'permanent', 'reviewedHeads', 'temporaryPrefixes', 'timeoutMs', 'maxOutputBytes', 'signal'];
67
+ if (live || execution) keys.push('httpsAuthorization');
68
+ const options = fields(input, keys, 'Inspection options');
69
+ const authorization = live || execution ? readLiveAuthorization(options.httpsAuthorization) : undefined;
70
+ const cwd = text(options.cwd, 'Repository root', 4096);
71
+ const repository = text(options.repository, 'Repository identity');
72
+ const remote = options.remote === undefined ? 'origin' : text(options.remote, 'Remote name', 64);
73
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/u.test(remote) || remote.includes('..')) fail('ERR_INPUT', 'Use a supported simple remote name.');
74
+ const integration = branch(options.integrationBranch, 'Integration branch');
75
+ const permanent = branchList(options.permanent, 'Permanent branches');
76
+ if (!permanent.includes(integration)) fail('ERR_INPUT', 'The integration branch must be permanent.');
77
+ // Validate expected endpoints before starting a subprocess; preserve an owned snapshot.
78
+ const approved = list(options.expectedRemoteUrls, 'Expected remote URLs', 8);
79
+ const expectedRemoteUrls = approved.map(normalizeRemoteUrl);
80
+ assertRemoteDestinations({ expectedRemoteUrls, fetchUrls: expectedRemoteUrls.slice(0, 1), pushUrls: expectedRemoteUrls.slice(0, 1) });
81
+ const reviewedHeads = options.reviewedHeads === undefined ? undefined : list(options.reviewedHeads, 'Reviewed heads', 10000)
82
+ .map(item => fields(item, ['repository', 'branch', 'head', 'target', 'evidence'], 'Reviewed head'));
83
+ const temporaryPrefixes = options.temporaryPrefixes === undefined ? undefined : list(options.temporaryPrefixes, 'Temporary prefixes');
84
+ const timeoutMs = options.timeoutMs === undefined ? 10000 : options.timeoutMs;
85
+ const maxOutputBytes = options.maxOutputBytes === undefined ? 4 * 1024 * 1024 : options.maxOutputBytes;
86
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30000
87
+ || !Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1024 || maxOutputBytes > 16 * 1024 * 1024
88
+ || (options.signal !== undefined && !(options.signal instanceof AbortSignal))) fail('ERR_INPUT', 'Supply supported inspection limits and an optional AbortSignal.');
89
+ if (options.signal?.aborted) fail('ERR_ABORTED', 'Inspection was cancelled.');
90
+ let root;
91
+ try { root = await realpath(resolve(cwd)); } catch { fail('ERR_REPOSITORY_PATH', 'The supplied repository root is unavailable.'); }
92
+ const deadline = AbortSignal.timeout(timeoutMs);
93
+ const signal = options.signal ? AbortSignal.any([deadline, options.signal]) : deadline;
94
+ const run = gitReader({ cwd: root, timeoutMs, maxOutputBytes, signal });
95
+ if ((await run(['rev-parse', '--is-inside-work-tree'])).stdout.trim() !== 'true'
96
+ || (await run(['rev-parse', '--is-bare-repository'])).stdout.trim() !== 'false') fail('ERR_REPOSITORY', 'Require a non-bare Git working tree.');
97
+ let top;
98
+ try { top = await realpath((await run(['rev-parse', '--show-toplevel'])).stdout.trim()); }
99
+ catch (error) { if (error.code?.startsWith('ERR_')) throw error; fail('ERR_REPOSITORY_PATH', 'The Git working tree root is unavailable.'); }
100
+ if (top !== root) fail('ERR_REPOSITORY_ROOT', 'Run inspection from the repository root.');
101
+ if ((await run(['rev-parse', '--is-shallow-repository'])).stdout.trim() !== 'false') fail('ERR_SHALLOW_HISTORY', 'Full Git history is required.');
102
+ const format = objectFormat((await run(['rev-parse', '--show-object-format'])).stdout.trim());
103
+ if ((await run(['for-each-ref', '--format=%(refname)', 'refs/replace/'])).stdout) fail('ERR_REPLACED_HISTORY', 'Replacement refs require review before retirement.');
104
+ const graft = resolve(root, (await run(['rev-parse', '--git-path', 'info/grafts'])).stdout.trim());
105
+ try { const info = await lstat(graft); if (!info.isFile() || info.size !== 0) fail('ERR_REPLACED_HISTORY', 'Grafted or uncertain history requires review before retirement.'); }
106
+ catch (error) { if (error.code?.startsWith('ERR_')) throw error; if (error.code !== 'ENOENT') fail('ERR_INSPECTION_FS', 'Git history metadata could not be inspected.'); }
107
+ const partial = await run(['config', '--get', 'extensions.partialClone'], [0, 1]);
108
+ const promisors = await run(['config', '--type=bool', '--get-regexp', '^remote\..*\.promisor$'], [0, 1]);
109
+ if (partial.status === 0 || lines(promisors.stdout).some(line => !line.endsWith(' false'))) fail('ERR_PARTIAL_HISTORY', 'Partial/promisor repositories are unsupported for retirement inspection.');
110
+ const filters = await run(['config', '--get-regexp', '^filter\..*\.(clean|process|smudge)$'], [0, 1]);
111
+ if (filters.stdout) fail('ERR_EXTERNAL_FILTER', 'Executable content filters need review before status inspection.');
112
+
113
+ async function transport() {
114
+ const fetchUrls = lines((await run(['remote', 'get-url', '--all', remote])).stdout);
115
+ const pushUrls = lines((await run(['remote', 'get-url', '--push', '--all', remote])).stdout);
116
+ const destinations = assertRemoteDestinations({ expectedRemoteUrls, fetchUrls, pushUrls });
117
+ const fetch = lines((await run(['config', '--get-all', `remote.${remote}.fetch`], [0, 1])).stdout);
118
+ const expected = `refs/heads/*:refs/remotes/${remote}/*`;
119
+ if (fetch.length !== 1 || ![expected, '+' + expected].includes(fetch[0])) fail('ERR_FETCH_REFSPEC', 'Require one complete branch fetch refspec without exclusions or extra destinations.');
120
+ const mirror = await run(['config', '--type=bool', '--get', `remote.${remote}.mirror`], [0, 1]);
121
+ const push = await run(['config', '--get-all', `remote.${remote}.push`], [0, 1]);
122
+ const tags = await run(['config', '--type=bool', '--get', 'push.followTags'], [0, 1]);
123
+ if ((mirror.status === 0 && mirror.stdout.trim() !== 'false') || push.stdout
124
+ || (tags.status === 0 && tags.stdout.trim() !== 'false')) fail('ERR_PUSH_CONFIGURATION', 'Mirror, implicit push-refspec or follow-tags configuration requires review.');
125
+ return { ...destinations, fetchRefspec: fetch[0], ...(live || execution ? { raw: { fetch: fetchUrls[0], push: pushUrls[0] } } : {}) };
126
+ }
127
+ async function snapshot() {
128
+ const current = await run(['symbolic-ref', '--quiet', '--short', 'HEAD'], [0, 1]);
129
+ if (current.status === 1) fail('ERR_DETACHED_SOURCE', 'Use the attached integration branch for retirement inspection.');
130
+ if (current.stdout.trim() !== integration) fail('ERR_SOURCE_BRANCH', 'Use the configured integration branch.');
131
+ const head = objectId((await run(['rev-parse', '--verify', 'HEAD^{commit}'])).stdout.trim(), format);
132
+ if ((await run(['status', '--porcelain=v1', '-z', '--untracked-files=all'])).stdout !== '') fail('ERR_DIRTY_SOURCE', 'Preserve tracked and untracked changes before retirement inspection.');
133
+ const allRefs = (await run(['for-each-ref', '--format=%(refname)%00%(objectname)%00%(symref)', 'refs/heads/', `refs/remotes/${remote}/`])).stdout;
134
+ const trees = (await run(['worktree', 'list', '--porcelain', '-z'])).stdout;
135
+ return { head, allRefs, trees, transport: await transport() };
136
+ }
137
+ const before = await snapshot();
138
+ const maps = refs(before.allRefs, remote, format, execution ? permanent : undefined);
139
+ if (maps.local[integration] !== before.head || maps.remote[integration] !== before.head) fail('ERR_SOURCE_ALIGNMENT', 'The local integration branch must match its remote-tracking head. Refresh and review separately.');
140
+ const checkedWorktrees = worktrees(before.trees, root, before.head, integration, format);
141
+ const isAncestor = async (head, target) => (await run(['merge-base', '--is-ancestor', head, target], [0, 1])).status === 0;
142
+ const plan = await planRetirements({ repository, permanent, ...maps, reviewedHeads,
143
+ temporaryPrefixes, objectFormat: format, isAncestor });
144
+ const after = await snapshot();
145
+ if (JSON.stringify(before) !== JSON.stringify(after)) fail('ERR_INSPECTION_CHANGED', 'Git state changed during inspection; settle concurrent work and retry.');
146
+ const { raw, ...publicTransport } = before.transport;
147
+ const result = { inspectionOnly: true, remoteFreshness: 'unverified-local-cache', networkAccess: false, refMutations: false,
148
+ source: { root, branch: integration, head: before.head, objectFormat: format, remote },
149
+ transport: publicTransport, worktrees: checkedWorktrees, plan };
150
+ const state = {
151
+ source: result.source,
152
+ transport: publicTransport,
153
+ raw,
154
+ permanent: [...permanent].sort(),
155
+ refs: { local: Object.entries(maps.local).sort(), tracking: Object.entries(maps.remote).sort() },
156
+ plan,
157
+ };
158
+ const data = { result, state, approved, authorization };
159
+ if (!live) return data;
160
+ const observation = await validateAdvertisements({ raw, approved, authorization, cached: maps.remote, format,
161
+ options: { cwd: root, timeoutMs, maxOutputBytes, signal } });
162
+ if (JSON.stringify(before) !== JSON.stringify(await snapshot())) {
163
+ fail('ERR_INSPECTION_CHANGED', 'Git state changed during live validation; settle concurrent work and retry.');
164
+ }
165
+ return { ...data, result: { ...result, remoteFreshness: 'matched-live-advertisement', networkAccess: true, observation,
166
+ planId: retirementPlanId(state) } };
167
+ }
@@ -0,0 +1,136 @@
1
+ import { fail } from '../errors.mjs';
2
+ import { normalizeRemoteUrl } from '../remote.mjs';
3
+ import { branch, fields, LIMITS, objectId } from '../validation.mjs';
4
+ import { GIT_LOCAL_ARGS, runBounded } from './process.mjs';
5
+
6
+ // Keep the accepted network syntax narrower than Git's general URL parser.
7
+ // SCP-style paths are relative on generic SSH servers. Keep that distinction.
8
+ const host = '[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?';
9
+ const user = '[a-zA-Z0-9_][a-zA-Z0-9._-]*';
10
+ const path = '[a-zA-Z0-9._-]+(?:/[a-zA-Z0-9._-]+)*';
11
+ const https = new RegExp(`^https://${host}(?::[0-9]+)?/${path}$`, 'u');
12
+ const ssh = new RegExp(`^ssh://${user}@${host}(?::[0-9]+)?/${path}$`, 'u');
13
+ const scp = new RegExp(`^(${user})@(${host}):(${path})$`, 'u');
14
+
15
+ function endpoint(value) {
16
+ const normalized = normalizeRemoteUrl(value);
17
+ if (https.test(value)) return { protocol: 'https', url: normalized };
18
+ if (ssh.test(value)) return { protocol: 'ssh', url: normalized };
19
+ const match = scp.exec(value);
20
+ if (match && !match[3].startsWith('-')) {
21
+ return { protocol: 'ssh', url: `${match[1]}@${match[2].toLowerCase()}:${match[3]}` };
22
+ }
23
+ fail('ERR_LIVE_REMOTE_URL', 'Use an explicit HTTPS or SSH endpoint with a simple host and repository path for live validation.');
24
+ }
25
+
26
+ export function readLiveAuthorization(value) {
27
+ if (value === undefined) return undefined;
28
+ const data = fields(value, ['endpoint', 'value'], 'HTTPS authorization');
29
+ const target = endpoint(data.endpoint);
30
+ if (target.protocol !== 'https' || typeof data.value !== 'string' || data.value.length > 8192
31
+ || !/^(?:Bearer|Basic) [A-Za-z0-9._~+/=-]+$/u.test(data.value)) {
32
+ fail('ERR_LIVE_AUTHORIZATION', 'Supply a Basic or Bearer authorization value for one approved HTTPS endpoint.');
33
+ }
34
+ return { endpoint: target.url, value: data.value };
35
+ }
36
+
37
+ export function approvedDestinations(raw, approved, authorization) {
38
+ const urls = new Set(approved.map(endpoint).map(entry => entry.url));
39
+ const destinations = [
40
+ { role: 'fetch', ...endpoint(raw.fetch) },
41
+ { role: 'push', ...endpoint(raw.push) },
42
+ ];
43
+ if (destinations.some(destination => !urls.has(destination.url))) {
44
+ fail('ERR_LIVE_REMOTE_URL', 'Each effective live endpoint must match an approved URL with the same path semantics.');
45
+ }
46
+ if (authorization && !destinations.some(destination => destination.protocol === 'https' && destination.url === authorization.endpoint)) {
47
+ fail('ERR_LIVE_AUTHORIZATION', 'The authorization endpoint must match an effective approved HTTPS destination.');
48
+ }
49
+ return destinations;
50
+ }
51
+
52
+ function advertisedHeads(output, format) {
53
+ if (output !== '' && !output.endsWith('\n')) fail('ERR_LIVE_REMOTE_REFS', 'Git returned incomplete remote ref output.');
54
+ const heads = new Map();
55
+ const lines = output === '' ? [] : output.slice(0, -1).split('\n');
56
+ if (lines.length > LIMITS.refs) fail('ERR_LIVE_REMOTE_REFS', 'Remote branch count exceeds the supported limit.');
57
+ for (const line of lines) {
58
+ const parts = line.split('\t');
59
+ if (parts.length !== 2 || !parts[1].startsWith('refs/heads/')) fail('ERR_LIVE_REMOTE_REFS', 'Git returned unsupported remote ref output.');
60
+ let name, oid;
61
+ try {
62
+ name = branch(parts[1].slice('refs/heads/'.length), 'Remote branch');
63
+ oid = objectId(parts[0], format, 'Remote commit');
64
+ } catch { fail('ERR_LIVE_REMOTE_REFS', 'Git returned an unsupported remote branch or object ID.'); }
65
+ if (heads.has(name)) fail('ERR_LIVE_REMOTE_REFS', 'Git advertised a duplicate remote branch.');
66
+ heads.set(name, oid);
67
+ }
68
+ return heads;
69
+ }
70
+
71
+ const SSH_COMMAND = [
72
+ 'ssh -F /dev/null', '-o BatchMode=yes', '-o StrictHostKeyChecking=yes',
73
+ '-o UpdateHostKeys=no', '-o ClearAllForwardings=yes', '-o ForwardAgent=no',
74
+ '-o ForwardX11=no', '-o PermitLocalCommand=no', '-o ControlMaster=no', '-o ControlPath=none',
75
+ ].join(' ');
76
+
77
+ function transportOptions(destination, authorization, options) {
78
+ const { protocol, url } = destination;
79
+ const transport = { protocol, authorization: url === authorization?.endpoint ? authorization.value : undefined };
80
+ const args = [
81
+ ...GIT_LOCAL_ARGS, '-c', `protocol.${protocol}.allow=always`,
82
+ '-c', 'http.followRedirects=false', '-c', 'http.sslVerify=true',
83
+ '-c', 'ssh.variant=ssh', '-c', `core.sshCommand=${SSH_COMMAND}`,
84
+ ];
85
+ return { args, options: { ...options, isolatedConfig: true, transport } };
86
+ }
87
+
88
+ export async function queryHeads(destination, format, authorization, options) {
89
+ const { url, role } = destination;
90
+ const transport = transportOptions(destination, authorization, options);
91
+ const result = await runBounded('git', ['--git-dir=/dev/null', ...transport.args, 'ls-remote', '--refs', '--heads', '--', url], transport.options);
92
+ if (result.status !== 0 || result.stderrBytes) {
93
+ fail('ERR_LIVE_REMOTE_QUERY', `The ${role} endpoint did not return a clean read-only Git advertisement. Check access, TLS or SSH host trust, then retry.`);
94
+ }
95
+ return advertisedHeads(result.stdout, format);
96
+ }
97
+
98
+ export async function pushRetirements(destination, deletions, authorization, options, gitDir) {
99
+ const leases = deletions.map(({ branch, sha }) => `--force-with-lease=refs/heads/${branch}:${sha}`);
100
+ const refspecs = deletions.map(({ branch }) => `:refs/heads/${branch}`);
101
+ if (refspecs.length > 64 || Buffer.byteLength([...leases, ...refspecs].join('\n')) > 49152) {
102
+ fail('ERR_RETIREMENT_LIMIT', 'The plan exceeds the supported size of one atomic push.');
103
+ }
104
+ const transport = transportOptions(destination, authorization, options);
105
+ const result = await runBounded('git', [
106
+ `--git-dir=${gitDir}`, ...transport.args, 'push', '--atomic', '--no-follow-tags', '--no-verify', '--porcelain',
107
+ ...leases, '--', destination.url, ...refspecs,
108
+ ], transport.options);
109
+ if (result.status !== 0) fail('ERR_RETIREMENT_PUSH', 'The atomic push failed or its result is uncertain. Review the journal before any retry.');
110
+ }
111
+
112
+ export async function validateAdvertisements({ raw, approved, authorization, cached, format, options }) {
113
+ const destinations = approvedDestinations(raw, approved, authorization);
114
+ const observations = new Map();
115
+ for (const destination of destinations) {
116
+ if (observations.has(destination.url)) continue;
117
+ const heads = await queryHeads(destination, format, authorization, options);
118
+ const cachedEntries = Object.entries(cached);
119
+ let missing = 0, moved = 0, added = 0;
120
+ for (const [name, oid] of cachedEntries) {
121
+ if (!heads.has(name)) missing++;
122
+ else if (heads.get(name) !== oid) moved++;
123
+ }
124
+ for (const name of heads.keys()) if (!Object.hasOwn(cached, name)) added++;
125
+ if (missing || moved || added) {
126
+ fail('ERR_LIVE_REMOTE_STALE', `The ${destination.role} endpoint differs from local tracking refs (${added} added, ${missing} missing, ${moved} moved). Refresh deliberately and review again.`);
127
+ }
128
+ observations.set(destination.url, heads.size);
129
+ }
130
+ return {
131
+ checkedAt: new Date().toISOString(),
132
+ fetchBranchCount: observations.get(destinations[0].url),
133
+ pushBranchCount: observations.get(destinations[1].url),
134
+ distinctEndpointsChecked: observations.size,
135
+ };
136
+ }
@@ -0,0 +1,106 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { GitReleaseGuardError, fail } from '../errors.mjs';
3
+
4
+ /** Preserve configuration locations, but do not forward tokens or Git repository overrides. */
5
+ export function inspectionEnvironment(isolatedConfig = false, transport) {
6
+ const result = Object.create(null);
7
+ for (const key of ['PATH', 'HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'XDG_CONFIG_HOME', 'SystemRoot', 'SYSTEMROOT', 'WINDIR', 'TMPDIR', 'TMP', 'TEMP', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_SYSTEM', 'GIT_CONFIG_NOSYSTEM']) {
8
+ if (typeof process.env[key] === 'string') result[key] = process.env[key];
9
+ }
10
+ if (isolatedConfig) Object.assign(result, { GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', XDG_CONFIG_HOME: '/dev/null' });
11
+ if (transport?.protocol === 'ssh' && typeof process.env.SSH_AUTH_SOCK === 'string') {
12
+ result.SSH_AUTH_SOCK = process.env.SSH_AUTH_SOCK;
13
+ }
14
+ if (transport?.authorization) {
15
+ Object.assign(result, {
16
+ GIT_CONFIG_COUNT: '1',
17
+ GIT_CONFIG_KEY_0: 'http.extraHeader',
18
+ GIT_CONFIG_VALUE_0: `Authorization: ${transport.authorization}`,
19
+ });
20
+ }
21
+ return { ...result, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_OPTIONAL_LOCKS: '0',
22
+ GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1', LC_ALL: 'C' };
23
+ }
24
+
25
+ /** Internal bounded subprocess primitive; never uses a shell or logs output. */
26
+ export async function runBounded(executable, args, { cwd, timeoutMs, maxOutputBytes, signal, isolatedConfig = false, transport, input, beforeCommit }) {
27
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30000
28
+ || !Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1024 || maxOutputBytes > 16 * 1024 * 1024) {
29
+ fail('ERR_INPUT', 'Subprocess limits are outside the supported bounds.');
30
+ }
31
+ if (signal !== undefined && !(signal instanceof AbortSignal)) fail('ERR_INPUT', 'Supply a valid AbortSignal.');
32
+ if (signal?.aborted) fail(signal.reason?.name === 'TimeoutError' ? 'ERR_GIT_TIMEOUT' : 'ERR_ABORTED', 'Inspection was cancelled or exceeded its deadline.');
33
+ return new Promise((resolve, reject) => {
34
+ const out = [], err = [];
35
+ let bytes = 0, failure, settled = false;
36
+ // Own a process group on POSIX so cancellation also stops Git helpers that
37
+ // inherited the output pipes. Never signal the caller's process group.
38
+ const ownGroup = process.platform !== 'win32';
39
+ const child = spawn(executable, args, { cwd, env: inspectionEnvironment(isolatedConfig, transport), stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], windowsHide: true, detached: ownGroup });
40
+ function stop(code, message) {
41
+ failure ??= new GitReleaseGuardError(code, message);
42
+ if (ownGroup && child.pid) {
43
+ try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); }
44
+ } else child.kill('SIGKILL');
45
+ }
46
+ const timer = setTimeout(() => stop('ERR_GIT_TIMEOUT', 'Git inspection exceeded its command deadline.'), timeoutMs);
47
+ const abort = () => stop(signal.reason?.name === 'TimeoutError' ? 'ERR_GIT_TIMEOUT' : 'ERR_ABORTED', 'Inspection was cancelled or exceeded its deadline.');
48
+ signal?.addEventListener('abort', abort, { once: true });
49
+ // Close the small race between the initial check and listener installation.
50
+ if (signal?.aborted) abort();
51
+ function collect(target, chunk) {
52
+ bytes += chunk.length;
53
+ if (bytes > maxOutputBytes) { stop('ERR_GIT_OUTPUT_LIMIT', 'Git inspection exceeded its output limit.'); return; }
54
+ if (!failure) target.push(chunk);
55
+ }
56
+ let preparation = '', prepared = false;
57
+ child.stdout.on('data', chunk => {
58
+ collect(out, chunk);
59
+ if (!beforeCommit || prepared || failure) return;
60
+ preparation += chunk.toString('utf8');
61
+ const expected = 'start: ok\nprepare: ok\n';
62
+ if (!expected.startsWith(preparation)) {
63
+ stop('ERR_GIT_INPUT', 'Git returned unexpected transaction preparation output.');
64
+ } else if (preparation === expected) {
65
+ prepared = true;
66
+ Promise.resolve().then(beforeCommit).then(() => {
67
+ if (!failure && !settled) child.stdin.end('commit\n');
68
+ }, error => {
69
+ if (failure || settled) return;
70
+ failure = error;
71
+ child.stdin.end('abort\n');
72
+ });
73
+ }
74
+ });
75
+ child.stderr.on('data', chunk => collect(err, chunk));
76
+ if (input !== undefined) {
77
+ child.stdin.on('error', () => stop('ERR_GIT_INPUT', 'Git closed its transaction input early.'));
78
+ if (beforeCommit) child.stdin.write(input);
79
+ else child.stdin.end(input);
80
+ }
81
+ child.on('error', () => { failure ??= new GitReleaseGuardError('ERR_GIT_START', 'Git could not be started.'); });
82
+ child.on('close', (status, killedBy) => {
83
+ if (settled) return;
84
+ settled = true; clearTimeout(timer); signal?.removeEventListener('abort', abort);
85
+ if (failure) { reject(failure); return; }
86
+ if (killedBy || status === null) { reject(new GitReleaseGuardError('ERR_GIT_COMMAND', 'Git inspection ended unexpectedly.')); return; }
87
+ const stdout = Buffer.concat(out), stderr = Buffer.concat(err);
88
+ const decoded = stdout.toString('utf8');
89
+ if (!Buffer.from(decoded, 'utf8').equals(stdout)) {
90
+ reject(new GitReleaseGuardError('ERR_GIT_ENCODING', 'Git returned unsupported non-UTF-8 output.')); return;
91
+ }
92
+ resolve({ status, stdout: decoded, stderrBytes: stderr.length });
93
+ });
94
+ });
95
+ }
96
+
97
+ export const GIT_LOCAL_ARGS = Object.freeze(['--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.untrackedCache=false',
98
+ '-c', 'core.hooksPath=/dev/null', '-c', 'protocol.allow=never']);
99
+
100
+ export function gitReader(options) {
101
+ return async (args, allowedStatuses = [0]) => {
102
+ const result = await runBounded('git', [...GIT_LOCAL_ARGS, ...args], options);
103
+ if (!allowedStatuses.includes(result.status)) fail('ERR_GIT_COMMAND', 'A required local Git inspection failed.');
104
+ return result;
105
+ };
106
+ }