@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.
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +561 -2
- package/SECURITY.md +11 -0
- package/bin/git-release-guardrails.mjs +148 -0
- package/package.json +44 -4
- package/src/deployment.mjs +26 -0
- package/src/errors.mjs +12 -0
- package/src/index.d.mts +55 -0
- package/src/index.mjs +4 -0
- package/src/node/backup.mjs +370 -0
- package/src/node/bundle-process.mjs +51 -0
- package/src/node/config.mjs +110 -0
- package/src/node/index.d.mts +86 -0
- package/src/node/index.mjs +4 -0
- package/src/node/inspect.mjs +167 -0
- package/src/node/live-remote.mjs +136 -0
- package/src/node/process.mjs +106 -0
- package/src/node/retire.mjs +294 -0
- package/src/plan.mjs +89 -0
- package/src/remote.mjs +46 -0
- package/src/validation.mjs +87 -0
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { open, realpath, lstat, link, unlink, mkdtemp, rm, constants } from 'node:fs/promises';
|
|
2
|
+
import { resolve, join, dirname } from 'node:path';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { fail } from '../errors.mjs';
|
|
6
|
+
import { fields, list, LIMITS, text } from '../validation.mjs';
|
|
7
|
+
import { inspectRetirementState, retirementPlanId } from './inspect.mjs';
|
|
8
|
+
import { createRetirementBackup, verifyRetirementBackup, assertBackupCoversRetirement } from './backup.mjs';
|
|
9
|
+
import { unambiguousJson } from './config.mjs';
|
|
10
|
+
import { gitReader, runBounded, GIT_LOCAL_ARGS } from './process.mjs';
|
|
11
|
+
import { approvedDestinations, pushRetirements, queryHeads } from './live-remote.mjs';
|
|
12
|
+
|
|
13
|
+
const MAX_JOURNAL_BYTES = 4 * 1024 * 1024;
|
|
14
|
+
const ID = /^[a-f0-9]{64}$/u;
|
|
15
|
+
const JOURNAL = 'retirement.json';
|
|
16
|
+
|
|
17
|
+
function parameters(input) {
|
|
18
|
+
const data = fields(input, ['inspection', 'directory', 'expectedPlanId', 'signal', 'timeoutMs', 'maxBackupBytes'], 'Retirement options');
|
|
19
|
+
if (process.platform === 'win32' || !(constants.O_NOFOLLOW > 0) || !(constants.O_NONBLOCK > 0)) {
|
|
20
|
+
fail('ERR_RETIREMENT_PLATFORM', 'Apply and recovery require a supported POSIX filesystem.');
|
|
21
|
+
}
|
|
22
|
+
if (typeof data.expectedPlanId !== 'string' || !ID.test(data.expectedPlanId)) {
|
|
23
|
+
fail('ERR_RETIREMENT_PLAN', 'Supply the full plan ID from an approved live preview.');
|
|
24
|
+
}
|
|
25
|
+
const spec = fields(data.inspection, ['cwd', 'repository', 'expectedRemoteUrls', 'remote', 'integrationBranch',
|
|
26
|
+
'permanent', 'reviewedHeads', 'temporaryPrefixes', 'timeoutMs', 'maxOutputBytes', 'httpsAuthorization'], 'Retirement inspection');
|
|
27
|
+
for (const key of ['permanent', 'temporaryPrefixes', 'expectedRemoteUrls']) {
|
|
28
|
+
if (spec[key] !== undefined) spec[key] = list(spec[key], key);
|
|
29
|
+
}
|
|
30
|
+
if (spec.reviewedHeads !== undefined) {
|
|
31
|
+
spec.reviewedHeads = list(spec.reviewedHeads, 'Reviewed heads', LIMITS.reviews).map(review =>
|
|
32
|
+
fields(review, ['repository', 'branch', 'head', 'target', 'evidence'], 'Reviewed head'));
|
|
33
|
+
}
|
|
34
|
+
if (spec.httpsAuthorization !== undefined) {
|
|
35
|
+
spec.httpsAuthorization = fields(spec.httpsAuthorization, ['endpoint', 'value'], 'HTTPS authorization');
|
|
36
|
+
}
|
|
37
|
+
const signal = data.signal;
|
|
38
|
+
if (signal !== undefined && !(signal instanceof AbortSignal)) fail('ERR_INPUT', 'Supply an AbortSignal.');
|
|
39
|
+
if (signal?.aborted) fail('ERR_ABORTED', 'Retirement was cancelled.');
|
|
40
|
+
const backupOptions = { timeoutMs: data.timeoutMs, maxBackupBytes: data.maxBackupBytes, signal };
|
|
41
|
+
const directory = resolve(text(data.directory, 'Backup directory', 4096));
|
|
42
|
+
return { spec, expectedPlanId: data.expectedPlanId, directory, signal, backupOptions };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function connection(ctx, state) {
|
|
46
|
+
return { cwd: state.source.root, timeoutMs: ctx.spec.timeoutMs ?? 10000,
|
|
47
|
+
maxOutputBytes: ctx.spec.maxOutputBytes ?? 4 * 1024 * 1024, signal: ctx.signal };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function commonDirectory(ctx, state) {
|
|
51
|
+
const run = gitReader(connection(ctx, state));
|
|
52
|
+
const result = await run(['rev-parse', '--path-format=absolute', '--git-common-dir']);
|
|
53
|
+
return realpath(result.stdout.trim());
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function syncDirectory(path) {
|
|
57
|
+
const handle = await open(path, constants.O_RDONLY);
|
|
58
|
+
try { await handle.sync(); } finally { await handle.close(); }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function exclusiveWrite(directory, name, data) {
|
|
62
|
+
const encoded = JSON.stringify(data, null, 2) + '\n';
|
|
63
|
+
if (Buffer.byteLength(encoded) > MAX_JOURNAL_BYTES) fail('ERR_RETIREMENT_LIMIT', 'Retirement journal is too large.');
|
|
64
|
+
const pending = join(directory, '.retirement-' + randomUUID());
|
|
65
|
+
const handle = await open(pending, 'wx', 0o600);
|
|
66
|
+
try {
|
|
67
|
+
try { await handle.writeFile(encoded); await handle.sync(); } finally { await handle.close(); }
|
|
68
|
+
await link(pending, join(directory, name));
|
|
69
|
+
} finally { await unlink(pending); }
|
|
70
|
+
await syncDirectory(directory);
|
|
71
|
+
await syncDirectory(dirname(directory));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function withLock(ctx, action) {
|
|
75
|
+
const initial = await current(ctx);
|
|
76
|
+
ctx.spec.cwd = initial.state.source.root;
|
|
77
|
+
const common = await commonDirectory(ctx, initial.state);
|
|
78
|
+
const path = join(common, 'ehven-retirement.lock');
|
|
79
|
+
let lock;
|
|
80
|
+
try { lock = await open(path, 'wx', 0o600); }
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (error.code === 'EEXIST') fail('ERR_RETIREMENT_LOCK', 'This repository already has a retirement lock. Resolve the prior operation before retrying.');
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
await lock.writeFile(JSON.stringify({ pid: process.pid, directory: ctx.directory, createdAt: new Date().toISOString() }) + '\n');
|
|
87
|
+
await lock.sync();
|
|
88
|
+
const locked = await current(ctx);
|
|
89
|
+
if (await commonDirectory(ctx, locked.state) !== common) fail('ERR_RETIREMENT_CHANGED', 'The Git directory changed during lock acquisition.');
|
|
90
|
+
return await action(locked);
|
|
91
|
+
} finally {
|
|
92
|
+
try { await lock.close(); } finally { await unlink(path); }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function current(ctx, live = false) {
|
|
97
|
+
return inspectRetirementState({ ...ctx.spec, signal: ctx.signal }, { execution: true, live });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function same(left, right) { return JSON.stringify(left) === JSON.stringify(right); }
|
|
101
|
+
|
|
102
|
+
function finalRefs(state) {
|
|
103
|
+
const retiredLocal = new Set(state.plan.local.map(entry => entry.branch));
|
|
104
|
+
const retiredRemote = new Set(state.plan.remote.map(entry => entry.branch));
|
|
105
|
+
const local = new Map(state.refs.local.filter(([name]) => !retiredLocal.has(name)));
|
|
106
|
+
for (const name of state.plan.align) local.set(name, state.plan.target);
|
|
107
|
+
return {
|
|
108
|
+
local: [...local].sort(),
|
|
109
|
+
tracking: state.refs.tracking.filter(([name]) => !retiredRemote.has(name)),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function writeDestination(data) {
|
|
114
|
+
const destinations = approvedDestinations(data.state.raw, data.approved, data.authorization);
|
|
115
|
+
if (destinations[0].url !== destinations[1].url) {
|
|
116
|
+
fail('ERR_RETIREMENT_DESTINATION', 'Apply and recovery require the same effective fetch and push endpoint.');
|
|
117
|
+
}
|
|
118
|
+
return destinations[1];
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function stateIdentity(state) {
|
|
122
|
+
return { source: state.source, transport: state.transport, raw: state.raw, permanent: state.permanent };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function localPhase(observed, expected, after) {
|
|
126
|
+
if (!same(stateIdentity(observed), stateIdentity(expected))) {
|
|
127
|
+
fail('ERR_RETIREMENT_CHANGED', 'The source, endpoint or permanent-branch policy changed since approval.');
|
|
128
|
+
}
|
|
129
|
+
if (retirementPlanId(observed) === retirementPlanId(expected)) return 'before';
|
|
130
|
+
if (same(observed.refs, after)) return 'after';
|
|
131
|
+
fail('ERR_RETIREMENT_CHANGED', 'Local refs or reviewed work differ from both approved retirement states.');
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function confirmPlan(state, id) {
|
|
135
|
+
if (retirementPlanId(state) !== id) fail('ERR_RETIREMENT_PLAN', 'The current plan differs from the approved live preview.');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function remotePhase(ctx, data, destination, original, after) {
|
|
139
|
+
const heads = await queryHeads(destination, original.source.objectFormat, data.authorization, connection(ctx, original));
|
|
140
|
+
const actual = [...heads].sort();
|
|
141
|
+
if (same(actual, after.tracking)) return 'after';
|
|
142
|
+
if (same(actual, original.refs.tracking)) return 'before';
|
|
143
|
+
fail('ERR_RETIREMENT_CHANGED', 'Live refs differ from both approved retirement states. Preserve the backup and inspect the journal.');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function isolatedPush(ctx, data, destination, state) {
|
|
147
|
+
const directory = await mkdtemp(join(tmpdir(), 'ehven-retirement-push-'));
|
|
148
|
+
try {
|
|
149
|
+
const options = { ...connection(ctx, state), cwd: directory };
|
|
150
|
+
const initialized = await runBounded('git', [...GIT_LOCAL_ARGS, 'init', '--bare', '--quiet', '--template=',
|
|
151
|
+
`--object-format=${state.source.objectFormat}`, '--', directory], { ...options, isolatedConfig: true });
|
|
152
|
+
if (initialized.status !== 0) fail('ERR_RETIREMENT_PUSH', 'Could not prepare an isolated push repository.');
|
|
153
|
+
await pushRetirements(destination, state.plan.remote, data.authorization, options, directory);
|
|
154
|
+
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function transactLocal(ctx, state, after) {
|
|
158
|
+
const changes = ['start'];
|
|
159
|
+
const zero = '0'.repeat(state.source.head.length);
|
|
160
|
+
for (const [scope, prefix] of [['local', 'refs/heads/'], ['tracking', `refs/remotes/${state.source.remote}/`]]) {
|
|
161
|
+
const before = new Map(state.refs[scope]), desired = new Map(after[scope]);
|
|
162
|
+
for (const name of new Set([...before.keys(), ...desired.keys()])) {
|
|
163
|
+
const ref = prefix + name, prior = before.get(name), next = desired.get(name);
|
|
164
|
+
changes.push('option no-deref');
|
|
165
|
+
if (prior === next) changes.push(`verify ${ref} ${prior}`);
|
|
166
|
+
else if (!next) changes.push(`delete ${ref} ${prior}`);
|
|
167
|
+
else changes.push(`update ${ref} ${next} ${prior ?? zero}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
changes.push('prepare', '');
|
|
171
|
+
let result;
|
|
172
|
+
try {
|
|
173
|
+
result = await runBounded('git', [...GIT_LOCAL_ARGS, 'update-ref', '--stdin'], {
|
|
174
|
+
...connection(ctx, state),
|
|
175
|
+
input: changes.join('\n'),
|
|
176
|
+
beforeCommit: async () => confirmPlan((await current(ctx)).state, ctx.expectedPlanId),
|
|
177
|
+
});
|
|
178
|
+
} catch (error) {
|
|
179
|
+
if (error.code !== 'ERR_GIT_INPUT') throw error;
|
|
180
|
+
}
|
|
181
|
+
if (result?.status !== 0 || result.stdout !== 'start: ok\nprepare: ok\ncommit: ok\n') {
|
|
182
|
+
fail('ERR_RETIREMENT_LOCAL', 'The local ref transaction failed or its result is uncertain. Review the journal before retrying.');
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function readJournal(directory, expectedPlanId) {
|
|
187
|
+
const path = await realpath(directory);
|
|
188
|
+
if (!(await lstat(directory)).isDirectory()) fail('ERR_RETIREMENT_JOURNAL', 'The journal must be in the original backup directory.');
|
|
189
|
+
const handle = await open(join(path, JOURNAL), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
190
|
+
let bytes;
|
|
191
|
+
try {
|
|
192
|
+
const stat = await handle.stat();
|
|
193
|
+
if (!stat.isFile() || stat.size > MAX_JOURNAL_BYTES) fail('ERR_RETIREMENT_JOURNAL', 'The journal must be a bounded regular file.');
|
|
194
|
+
bytes = Buffer.alloc(MAX_JOURNAL_BYTES + 1);
|
|
195
|
+
let offset = 0;
|
|
196
|
+
while (offset < bytes.length) {
|
|
197
|
+
const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset);
|
|
198
|
+
if (!bytesRead) break;
|
|
199
|
+
offset += bytesRead;
|
|
200
|
+
}
|
|
201
|
+
if (offset !== stat.size || offset > MAX_JOURNAL_BYTES) fail('ERR_RETIREMENT_JOURNAL', 'The journal changed while it was read.');
|
|
202
|
+
bytes = bytes.subarray(0, offset);
|
|
203
|
+
} finally { await handle.close(); }
|
|
204
|
+
try {
|
|
205
|
+
const document = unambiguousJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
206
|
+
if (document.schemaVersion !== 1 || document.planId !== expectedPlanId || !ID.test(document.backupSha256)
|
|
207
|
+
|| retirementPlanId(document.state) !== expectedPlanId) throw new Error();
|
|
208
|
+
return { ...document, directory: path };
|
|
209
|
+
} catch {
|
|
210
|
+
fail('ERR_RETIREMENT_JOURNAL', 'The journal does not match the approved plan ID.');
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function complete(ctx, state, directory, initial, recovery) {
|
|
215
|
+
const after = finalRefs(state);
|
|
216
|
+
const destination = writeDestination(initial);
|
|
217
|
+
const phase = localPhase(initial.state, state, after);
|
|
218
|
+
let server = await remotePhase(ctx, initial, destination, state, after);
|
|
219
|
+
if (phase === 'after' && server === 'before') {
|
|
220
|
+
fail('ERR_RETIREMENT_CHANGED', 'Local completion disagrees with live refs. Preserve the backup and inspect before retrying.');
|
|
221
|
+
}
|
|
222
|
+
if (!recovery && phase === 'before' && state.plan.remote.length && server !== 'before') {
|
|
223
|
+
fail('ERR_RETIREMENT_CHANGED', 'Remote refs changed before the initial mutation. Use recovery only after inspection.');
|
|
224
|
+
}
|
|
225
|
+
if (server === 'before') {
|
|
226
|
+
const checked = await current(ctx);
|
|
227
|
+
confirmPlan(checked.state, ctx.expectedPlanId);
|
|
228
|
+
await isolatedPush(ctx, checked, writeDestination(checked), state);
|
|
229
|
+
server = await remotePhase(ctx, checked, destination, state, after);
|
|
230
|
+
if (server !== 'after') fail('ERR_RETIREMENT_PUSH', 'Live verification did not confirm the remote deletion.');
|
|
231
|
+
}
|
|
232
|
+
const beforeLocal = await current(ctx);
|
|
233
|
+
if (localPhase(beforeLocal.state, state, after) === 'before' && !same(state.refs, after)) {
|
|
234
|
+
await transactLocal(ctx, state, after);
|
|
235
|
+
}
|
|
236
|
+
const final = await current(ctx);
|
|
237
|
+
if (!same(stateIdentity(final.state), stateIdentity(state)) || !same(final.state.refs, after)
|
|
238
|
+
|| await remotePhase(ctx, final, writeDestination(final), state, after) !== 'after') {
|
|
239
|
+
fail('ERR_RETIREMENT_CHANGED', 'Final live and local snapshots did not confirm completion. Preserve the journal.');
|
|
240
|
+
}
|
|
241
|
+
return { completed: true, recovered: recovery, planId: ctx.expectedPlanId,
|
|
242
|
+
directory, remoteRetired: state.plan.remote.length, localRetired: state.plan.local.length,
|
|
243
|
+
localAligned: state.plan.align.length };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function guarded(action) {
|
|
247
|
+
try { return await action(); } catch (error) {
|
|
248
|
+
if (error.code?.startsWith('ERR_')) throw error;
|
|
249
|
+
fail('ERR_RETIREMENT_IO', 'Retirement could not access its repository, lock, backup or journal. Preserve the backup directory and inspect before retrying.');
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Requires an explicit reviewed plan ID. All write intent is durable before the first mutation. */
|
|
254
|
+
export async function applyRetirement(input) {
|
|
255
|
+
return guarded(async () => {
|
|
256
|
+
const ctx = parameters(input);
|
|
257
|
+
return withLock(ctx, async () => {
|
|
258
|
+
const first = await current(ctx, true);
|
|
259
|
+
confirmPlan(first.state, ctx.expectedPlanId);
|
|
260
|
+
writeDestination(first);
|
|
261
|
+
const plan = first.state.plan;
|
|
262
|
+
if (plan.remote.length === 0 && plan.local.length === 0 && plan.align.length === 0) {
|
|
263
|
+
return { completed: true, recovered: false, planId: ctx.expectedPlanId, directory: null,
|
|
264
|
+
remoteRetired: 0, localRetired: 0, localAligned: 0 };
|
|
265
|
+
}
|
|
266
|
+
if (plan.remote.length > 64) fail('ERR_RETIREMENT_LIMIT', 'The plan exceeds the supported size of one atomic push.');
|
|
267
|
+
const { httpsAuthorization, ...inspection } = ctx.spec;
|
|
268
|
+
const backup = await createRetirementBackup({ directory: ctx.directory, inspection, ...ctx.backupOptions });
|
|
269
|
+
const fresh = await current(ctx, true);
|
|
270
|
+
confirmPlan(fresh.state, ctx.expectedPlanId);
|
|
271
|
+
await assertBackupCoversRetirement(backup.directory, fresh.state, backup.bundleSha256, ctx.signal);
|
|
272
|
+
await exclusiveWrite(backup.directory, JOURNAL, { schemaVersion: 1, createdAt: new Date().toISOString(),
|
|
273
|
+
planId: ctx.expectedPlanId, backupSha256: backup.bundleSha256, state: fresh.state });
|
|
274
|
+
return complete(ctx, fresh.state, backup.directory, fresh, false);
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Reconcile the exact recorded before/after states. Recovery never rolls refs back. */
|
|
280
|
+
export async function recoverRetirement(input) {
|
|
281
|
+
return guarded(async () => {
|
|
282
|
+
const ctx = parameters(input);
|
|
283
|
+
return withLock(ctx, async initial => {
|
|
284
|
+
const journal = await readJournal(ctx.directory, ctx.expectedPlanId);
|
|
285
|
+
writeDestination(initial);
|
|
286
|
+
localPhase(initial.state, journal.state, finalRefs(journal.state));
|
|
287
|
+
const verified = await verifyRetirementBackup({ directory: journal.directory, ...ctx.backupOptions });
|
|
288
|
+
if (verified.bundleSha256 !== journal.backupSha256) fail('ERR_RETIREMENT_BACKUP', 'The backup digest differs from the journal.');
|
|
289
|
+
await assertBackupCoversRetirement(journal.directory, journal.state, journal.backupSha256, ctx.signal);
|
|
290
|
+
const fresh = await current(ctx);
|
|
291
|
+
return complete(ctx, journal.state, journal.directory, fresh, true);
|
|
292
|
+
});
|
|
293
|
+
});
|
|
294
|
+
}
|
package/src/plan.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { GitReleaseGuardError, fail } from './errors.mjs';
|
|
2
|
+
import { LIMITS, fields, list, text, branch, branchList, objectFormat, objectId, refMap } from './validation.mjs';
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_TEMPORARY_PREFIXES = Object.freeze(['docs/', 'feat/', 'fix/', 'refactor/', 'chore/']);
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Plan retirement from complete caller-supplied snapshots. No Git or filesystem I/O.
|
|
8
|
+
* A review is a trusted caller assertion, not authenticated approval or merge proof.
|
|
9
|
+
*/
|
|
10
|
+
export async function planRetirements(input) {
|
|
11
|
+
const options = fields(input, ['repository', 'permanent', 'remote', 'local', 'reviewedHeads', 'temporaryPrefixes', 'objectFormat', 'isAncestor'], 'Planner options');
|
|
12
|
+
const repository = text(options.repository, 'Repository identity');
|
|
13
|
+
const format = objectFormat(options.objectFormat);
|
|
14
|
+
const permanent = branchList(options.permanent, 'Permanent branches');
|
|
15
|
+
const remote = refMap(options.remote, format, 'Remote refs');
|
|
16
|
+
const local = refMap(options.local, format, 'Local refs');
|
|
17
|
+
const prefixes = list(options.temporaryPrefixes === undefined ? DEFAULT_TEMPORARY_PREFIXES : options.temporaryPrefixes, 'Temporary prefixes').map(prefix => {
|
|
18
|
+
text(prefix, 'Temporary prefix');
|
|
19
|
+
if (!prefix.endsWith('/')) fail('ERR_INPUT', 'Each temporary prefix must end with a slash.');
|
|
20
|
+
branch(prefix.slice(0, -1), 'Temporary prefix');
|
|
21
|
+
return prefix;
|
|
22
|
+
});
|
|
23
|
+
if (!prefixes.length || new Set(prefixes).size !== prefixes.length) fail('ERR_INPUT', 'Supply distinct temporary prefixes.');
|
|
24
|
+
if (typeof options.isAncestor !== 'function') fail('ERR_INPUT', 'Supply an ancestry resolver.');
|
|
25
|
+
const isAncestor = options.isAncestor;
|
|
26
|
+
const reviews = list(options.reviewedHeads === undefined ? [] : options.reviewedHeads, 'Reviewed heads', LIMITS.reviews).map(item => {
|
|
27
|
+
const review = fields(item, ['repository', 'branch', 'head', 'target', 'evidence'], 'Reviewed head');
|
|
28
|
+
return {
|
|
29
|
+
repository: text(review.repository, 'Reviewed repository'),
|
|
30
|
+
branch: branch(review.branch, 'Reviewed branch'),
|
|
31
|
+
head: objectId(review.head, format, 'Reviewed head'),
|
|
32
|
+
target: objectId(review.target, format, 'Reviewed target'),
|
|
33
|
+
evidence: text(review.evidence, 'Review evidence reference', LIMITS.evidence),
|
|
34
|
+
};
|
|
35
|
+
});
|
|
36
|
+
const reviewIndex = new Map();
|
|
37
|
+
const key = (repo, name, head, target) => JSON.stringify([repo, name, head, target]);
|
|
38
|
+
for (const review of reviews) {
|
|
39
|
+
const identity = key(review.repository, review.branch, review.head, review.target);
|
|
40
|
+
if (reviewIndex.has(identity)) fail('ERR_INPUT', 'Duplicate reviewed-head identities are ambiguous.');
|
|
41
|
+
reviewIndex.set(identity, review);
|
|
42
|
+
}
|
|
43
|
+
const target = remote[permanent[0]];
|
|
44
|
+
if (!target || permanent.some(name => !Object.hasOwn(remote, name) || remote[name] !== target)) {
|
|
45
|
+
fail('ERR_PERMANENT_ALIGNMENT', 'Permanent remote branches must identify the same commit before retirement.');
|
|
46
|
+
}
|
|
47
|
+
const permanentSet = new Set(permanent);
|
|
48
|
+
// Validate the entire snapshot before executing even the ancestry callback.
|
|
49
|
+
for (const refs of [remote, local]) {
|
|
50
|
+
if (Object.keys(refs).some(name => !permanentSet.has(name) && !prefixes.some(prefix => name.startsWith(prefix)))) {
|
|
51
|
+
fail('ERR_UNKNOWN_BRANCH', 'An unrecognized branch requires review before cleanup.');
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const ancestry = new Map();
|
|
55
|
+
async function ancestor(head) {
|
|
56
|
+
if (head === target) return true;
|
|
57
|
+
if (!ancestry.has(head)) {
|
|
58
|
+
let result;
|
|
59
|
+
try { result = await isAncestor(head, target); }
|
|
60
|
+
catch (cause) { throw new GitReleaseGuardError('ERR_ANCESTRY_CHECK', 'Ancestry inspection failed; retirement refused.', { cause }); }
|
|
61
|
+
if (typeof result !== 'boolean') fail('ERR_ANCESTRY_CHECK', 'The ancestry resolver must return a boolean.');
|
|
62
|
+
ancestry.set(head, result);
|
|
63
|
+
}
|
|
64
|
+
return ancestry.get(head);
|
|
65
|
+
}
|
|
66
|
+
const plan = {
|
|
67
|
+
repository, objectFormat: format, target, remote: [], local: [],
|
|
68
|
+
align: permanent.filter(name => local[name] !== target).sort(),
|
|
69
|
+
};
|
|
70
|
+
for (const name of permanent) {
|
|
71
|
+
if (Object.hasOwn(local, name) && !await ancestor(local[name])) {
|
|
72
|
+
fail('ERR_LOCAL_UNMERGED', 'A local permanent branch has unique history; preserve and reconcile it first.');
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
for (const [scope, refs] of [['remote', remote], ['local', local]]) {
|
|
76
|
+
for (const name of Object.keys(refs).sort()) {
|
|
77
|
+
if (permanentSet.has(name)) continue;
|
|
78
|
+
const sha = refs[name];
|
|
79
|
+
if (await ancestor(sha)) {
|
|
80
|
+
plan[scope].push({ branch: name, sha, basis: 'ancestry' });
|
|
81
|
+
} else {
|
|
82
|
+
const review = reviewIndex.get(key(repository, name, sha, target));
|
|
83
|
+
if (!review) fail('ERR_UNREVIEWED_WORK', 'Temporary work lacks ancestry or an exact repository/head/target review.');
|
|
84
|
+
plan[scope].push({ branch: name, sha, basis: 'reviewed-head', evidence: review.evidence });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return plan;
|
|
89
|
+
}
|
package/src/remote.mjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { fail } from './errors.mjs';
|
|
2
|
+
import { fields, list, text } from './validation.mjs';
|
|
3
|
+
|
|
4
|
+
/** Normalize endpoint syntax, not repository identity across different transports. */
|
|
5
|
+
export function normalizeRemoteUrl(input) {
|
|
6
|
+
text(input, 'Remote URL', 4096);
|
|
7
|
+
if (/[\\\s?#]/u.test(input)) fail('ERR_REMOTE_URL', 'Use an explicit credential-free HTTPS or SSH endpoint.');
|
|
8
|
+
let source = input;
|
|
9
|
+
if (!source.includes('://')) {
|
|
10
|
+
const scp = /^([a-zA-Z0-9._-]+)@([a-zA-Z0-9.-]+):(.+)$/u.exec(source);
|
|
11
|
+
if (!scp) fail('ERR_REMOTE_URL', 'Use an explicit credential-free HTTPS or SSH endpoint.');
|
|
12
|
+
source = `ssh://${scp[1]}@${scp[2]}/${scp[3]}`;
|
|
13
|
+
}
|
|
14
|
+
// Refuse path aliases before URL parsing can erase dot segments.
|
|
15
|
+
const path = source.match(/^[a-z]+:\/\/[^/]+(\/.*)$/iu)?.[1];
|
|
16
|
+
if (!path || path === '/') fail('ERR_REMOTE_URL', 'The endpoint must identify a repository path.');
|
|
17
|
+
for (const part of path.slice(1).split('/')) {
|
|
18
|
+
let decoded;
|
|
19
|
+
try { decoded = decodeURIComponent(part); } catch { fail('ERR_REMOTE_URL', 'Malformed remote URL encoding.'); }
|
|
20
|
+
if (!part || decoded === '.' || decoded === '..' || /[\/\\\u0000-\u0020\u007f?#]/u.test(decoded)) {
|
|
21
|
+
fail('ERR_REMOTE_URL', 'Ambiguous remote path components are unsupported.');
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
let url;
|
|
25
|
+
try { url = new URL(source); } catch { fail('ERR_REMOTE_URL', 'Malformed remote endpoint.'); }
|
|
26
|
+
if (!['https:', 'ssh:'].includes(url.protocol) || !url.hostname || url.password || url.search || url.hash
|
|
27
|
+
|| (url.protocol === 'https:' && url.username)
|
|
28
|
+
|| (url.protocol === 'ssh:' && url.username && !/^[a-zA-Z0-9._-]+$/u.test(url.username))) {
|
|
29
|
+
fail('ERR_REMOTE_URL', 'Use an explicit credential-free HTTPS or SSH endpoint.');
|
|
30
|
+
}
|
|
31
|
+
url.hostname = url.hostname.toLowerCase();
|
|
32
|
+
if (url.protocol === 'ssh:' && url.port === '22') url.port = '';
|
|
33
|
+
return url.href;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** All effective destinations must match intentionally configured endpoints. */
|
|
37
|
+
export function assertRemoteDestinations(input) {
|
|
38
|
+
const options = fields(input, ['expectedRemoteUrls', 'fetchUrls', 'pushUrls'], 'Remote destination options');
|
|
39
|
+
const allowed = list(options.expectedRemoteUrls, 'Expected remote URLs', 8).map(normalizeRemoteUrl);
|
|
40
|
+
if (!allowed.length || new Set(allowed).size !== allowed.length) fail('ERR_INPUT', 'Supply distinct approved remote endpoints.');
|
|
41
|
+
const fetch = list(options.fetchUrls, 'Effective fetch URLs', 8).map(normalizeRemoteUrl);
|
|
42
|
+
const push = list(options.pushUrls, 'Effective push URLs', 8).map(normalizeRemoteUrl);
|
|
43
|
+
if (fetch.length !== 1 || push.length !== 1) fail('ERR_REMOTE_DESTINATION', 'Require exactly one effective fetch and one effective push destination.');
|
|
44
|
+
if (!allowed.includes(fetch[0]) || !allowed.includes(push[0])) fail('ERR_REMOTE_DESTINATION', 'An effective remote destination differs from the approved endpoints.');
|
|
45
|
+
return { fetchUrl: fetch[0], pushUrl: push[0] };
|
|
46
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { fail } from './errors.mjs';
|
|
2
|
+
|
|
3
|
+
export const LIMITS = Object.freeze({ refs: 10000, reviews: 10000, branches: 100, text: 1024, evidence: 2048 });
|
|
4
|
+
|
|
5
|
+
/** Copy ordinary data properties before awaiting caller-supplied code. */
|
|
6
|
+
export function record(value, label, limit = LIMITS.refs) {
|
|
7
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
8
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value))) {
|
|
9
|
+
fail('ERR_INPUT', `${label} must be a plain data object.`);
|
|
10
|
+
}
|
|
11
|
+
const keys = Reflect.ownKeys(value);
|
|
12
|
+
if (keys.length > limit) fail('ERR_INPUT', `${label} exceeds the supported entry limit.`);
|
|
13
|
+
const copy = Object.create(null);
|
|
14
|
+
for (const key of keys) {
|
|
15
|
+
const entry = Object.getOwnPropertyDescriptor(value, key);
|
|
16
|
+
if (typeof key !== 'string' || !entry || !Object.hasOwn(entry, 'value')) {
|
|
17
|
+
fail('ERR_INPUT', `${label} must contain only string-keyed data properties.`);
|
|
18
|
+
}
|
|
19
|
+
copy[key] = entry.value;
|
|
20
|
+
}
|
|
21
|
+
return copy;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function fields(value, allowed, label, limit = allowed.length) {
|
|
25
|
+
const copy = record(value, label, limit);
|
|
26
|
+
if (Object.keys(copy).some(key => !allowed.includes(key))) fail('ERR_INPUT', `${label} contains an unsupported field.`);
|
|
27
|
+
return copy;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function list(value, label, max = LIMITS.branches) {
|
|
31
|
+
if (!Array.isArray(value) || value.length > max) fail('ERR_INPUT', `${label} must be an array within the supported limit.`);
|
|
32
|
+
const result = [];
|
|
33
|
+
for (let i = 0; i < value.length; i++) {
|
|
34
|
+
const entry = Object.getOwnPropertyDescriptor(value, String(i));
|
|
35
|
+
if (!entry || !Object.hasOwn(entry, 'value')) fail('ERR_INPUT', `${label} must be a dense array of data values.`);
|
|
36
|
+
result.push(entry.value);
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function text(value, label, max = LIMITS.text) {
|
|
42
|
+
if (typeof value !== 'string' || !value.trim() || value !== value.trim()
|
|
43
|
+
|| value.length > max || /[\u0000-\u001f\u007f]/u.test(value)) {
|
|
44
|
+
fail('ERR_INPUT', `${label} must be bounded, nonempty text without control characters or surrounding whitespace.`);
|
|
45
|
+
}
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function branch(value, label = 'Branch') {
|
|
50
|
+
text(value, label);
|
|
51
|
+
if (value === '@' || value.startsWith('-') || value.endsWith('.') || value.includes('..')
|
|
52
|
+
|| value.includes('@{') || /[\s~^:?*\[\\]/u.test(value)
|
|
53
|
+
|| value.split('/').some(part => !part || part.startsWith('.') || part.endsWith('.lock'))) {
|
|
54
|
+
fail('ERR_INPUT', `${label} is not a supported short Git branch name.`);
|
|
55
|
+
}
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function branchList(value, label, minimum = 1) {
|
|
60
|
+
const result = list(value, label).map(item => branch(item, label));
|
|
61
|
+
if (result.length < minimum || new Set(result).size !== result.length) {
|
|
62
|
+
fail('ERR_INPUT', `${label} must contain distinct branch names.`);
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function objectFormat(value = 'sha1') {
|
|
68
|
+
if (!['sha1', 'sha256'].includes(value)) fail('ERR_INPUT', 'Choose the sha1 or sha256 object format.');
|
|
69
|
+
return value;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function objectId(value, format, label = 'Commit ID') {
|
|
73
|
+
const pattern = format === 'sha1' ? /^[a-f0-9]{40}$/u : /^[a-f0-9]{64}$/u;
|
|
74
|
+
if (typeof value !== 'string' || !pattern.test(value) || /^0+$/u.test(value)) {
|
|
75
|
+
fail('ERR_INPUT', `${label} must be a full, nonzero lowercase commit ID in the selected object format.`);
|
|
76
|
+
}
|
|
77
|
+
return value;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function refMap(value, format, label) {
|
|
81
|
+
const copy = record(value, label);
|
|
82
|
+
for (const [name, sha] of Object.entries(copy)) {
|
|
83
|
+
branch(name, label);
|
|
84
|
+
objectId(sha, format, label);
|
|
85
|
+
}
|
|
86
|
+
return copy;
|
|
87
|
+
}
|