@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,370 @@
|
|
|
1
|
+
import { open, mkdir, mkdtemp, realpath, lstat, rm, link, unlink, constants } from 'node:fs/promises';
|
|
2
|
+
import { resolve, dirname, basename, join, relative, isAbsolute } from 'node:path';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { fields, list, branch, text, objectFormat, objectId } from '../validation.mjs';
|
|
6
|
+
import { fail } from '../errors.mjs';
|
|
7
|
+
import { inspectRetirements } from './inspect.mjs';
|
|
8
|
+
import { gitReader } from './process.mjs';
|
|
9
|
+
import { writeBundle } from './bundle-process.mjs';
|
|
10
|
+
import { unambiguousJson } from './config.mjs';
|
|
11
|
+
|
|
12
|
+
const MAX_MANIFEST = 4 * 1024 * 1024;
|
|
13
|
+
const REF_FORMAT = '--format=%(refname)%00%(objectname)%00%(symref)';
|
|
14
|
+
|
|
15
|
+
function operation(input, extra = []) {
|
|
16
|
+
const data = fields(input, ['directory', 'timeoutMs', 'maxBackupBytes', 'signal', ...extra], 'Backup options');
|
|
17
|
+
if (process.platform === 'win32' || !(constants.O_NOFOLLOW > 0) || !(constants.O_NONBLOCK > 0)) fail('ERR_BACKUP_PLATFORM', 'Backup requires supported POSIX process and regular-file protections.');
|
|
18
|
+
const timeoutMs = data.timeoutMs === undefined ? 30000 : data.timeoutMs;
|
|
19
|
+
const maxBackupBytes = data.maxBackupBytes === undefined ? 256 * 1024 * 1024 : data.maxBackupBytes;
|
|
20
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30000
|
|
21
|
+
|| !Number.isSafeInteger(maxBackupBytes) || maxBackupBytes < 1024 || maxBackupBytes > 1024 * 1024 * 1024
|
|
22
|
+
|| (data.signal !== undefined && !(data.signal instanceof AbortSignal))) fail('ERR_INPUT', 'Supply supported backup limits and an optional AbortSignal.');
|
|
23
|
+
const directory = resolve(text(data.directory, 'Backup directory', 4096));
|
|
24
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
25
|
+
const signal = data.signal ? AbortSignal.any([deadline, data.signal]) : deadline;
|
|
26
|
+
const options = { timeoutMs, maxBackupBytes, maxOutputBytes: 4 * 1024 * 1024, signal };
|
|
27
|
+
check(options);
|
|
28
|
+
return { data, directory, options };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function check({ signal }) {
|
|
32
|
+
if (signal?.aborted) fail(signal.reason?.name === 'TimeoutError' ? 'ERR_GIT_TIMEOUT' : 'ERR_ABORTED', 'Backup operation was cancelled or exceeded its deadline.');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function inside(child, parent) {
|
|
36
|
+
const path = relative(parent, child);
|
|
37
|
+
return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith('../'));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function newPath(path) {
|
|
41
|
+
try { return join(await realpath(dirname(path)), basename(path)); }
|
|
42
|
+
catch { fail('ERR_BACKUP_PATH', 'Use an available trusted parent directory.'); }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function exclusiveDirectory(path) {
|
|
46
|
+
try { await mkdir(path, { mode: 0o700 }); }
|
|
47
|
+
catch { fail('ERR_BACKUP_DESTINATION', 'The destination must be a new directory in an available trusted parent.'); }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function protectExistingRepositories(path) {
|
|
51
|
+
async function exists(entry) {
|
|
52
|
+
try { await lstat(entry); return true; }
|
|
53
|
+
catch (error) { if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return false; throw error; }
|
|
54
|
+
}
|
|
55
|
+
for (let parent = dirname(path); ; parent = dirname(parent)) {
|
|
56
|
+
if (await exists(join(parent, '.git')) || (
|
|
57
|
+
await exists(join(parent, 'HEAD')) && await exists(join(parent, 'objects')) && await exists(join(parent, 'refs'))
|
|
58
|
+
)) fail('ERR_BACKUP_DESTINATION', 'Recover outside existing Git working trees and metadata directories.');
|
|
59
|
+
if (parent === dirname(parent)) break;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function existingDirectory(path) {
|
|
64
|
+
try {
|
|
65
|
+
if (!(await lstat(path)).isDirectory()) throw new Error();
|
|
66
|
+
return await realpath(path);
|
|
67
|
+
} catch { fail('ERR_BACKUP_PATH', 'Backup must be an available directory without a final symlink.'); }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function regular(path) {
|
|
71
|
+
let handle;
|
|
72
|
+
try {
|
|
73
|
+
handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
74
|
+
if (!(await handle.stat()).isFile()) throw new Error();
|
|
75
|
+
return handle;
|
|
76
|
+
} catch {
|
|
77
|
+
await handle?.close();
|
|
78
|
+
fail('ERR_BACKUP_FILE', 'Backup input must be an available regular file without a final symlink.');
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const unchanged = (a, b) => ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].every(key => a[key] === b[key]);
|
|
83
|
+
|
|
84
|
+
async function transfer(handle, options, maximum, target) {
|
|
85
|
+
const before = await handle.stat({ bigint: true });
|
|
86
|
+
if (!before.isFile()) fail('ERR_BACKUP_FILE', 'Backup input must remain a regular file.');
|
|
87
|
+
if (before.size > BigInt(maximum)) fail('ERR_BACKUP_LIMIT', 'Backup input exceeds the supported byte limit.');
|
|
88
|
+
const hash = createHash('sha256'), header = [];
|
|
89
|
+
let bytes = 0, headerBytes = 0, ended = false, previous = -1;
|
|
90
|
+
while (true) {
|
|
91
|
+
check(options);
|
|
92
|
+
const buffer = Buffer.alloc(65536);
|
|
93
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
|
|
94
|
+
if (!bytesRead) break;
|
|
95
|
+
bytes += bytesRead;
|
|
96
|
+
if (bytes > maximum) fail('ERR_BACKUP_LIMIT', 'Backup input exceeds the supported byte limit.');
|
|
97
|
+
const data = buffer.subarray(0, bytesRead); hash.update(data);
|
|
98
|
+
if (!ended) {
|
|
99
|
+
let index = 0;
|
|
100
|
+
for (; index < data.length; index++) {
|
|
101
|
+
const value = data[index];
|
|
102
|
+
if (++headerBytes > MAX_MANIFEST) fail('ERR_BACKUP_LIMIT', 'Bundle header exceeds the supported limit.');
|
|
103
|
+
if (value === 10 && previous === 10) { ended = true; index++; break; }
|
|
104
|
+
previous = value;
|
|
105
|
+
}
|
|
106
|
+
header.push(data.subarray(0, index));
|
|
107
|
+
}
|
|
108
|
+
if (target) {
|
|
109
|
+
let offset = 0;
|
|
110
|
+
while (offset < data.length) {
|
|
111
|
+
check(options);
|
|
112
|
+
const { bytesWritten } = await target.write(data, offset, data.length - offset, null);
|
|
113
|
+
if (!bytesWritten) fail('ERR_BACKUP_IO', 'Backup copy could not be written.');
|
|
114
|
+
offset += bytesWritten;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const after = await handle.stat({ bigint: true });
|
|
119
|
+
if (!unchanged(before, after) || after.size !== BigInt(bytes)) fail('ERR_BACKUP_CHANGED', 'Backup input changed while being read.');
|
|
120
|
+
check(options);
|
|
121
|
+
return { bytes, sha256: hash.digest('hex'), header: Buffer.concat(header), ended };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function fullRef(name) {
|
|
125
|
+
branch(name, 'Full ref name');
|
|
126
|
+
if (!name.startsWith('refs/')) fail('ERR_BACKUP_MANIFEST', 'Backup refs must use full refs/ names.');
|
|
127
|
+
return name;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function refList(value, format) {
|
|
131
|
+
const refs = list(value, 'Backup refs', 10000).map(item => {
|
|
132
|
+
const ref = fields(item, ['name', 'oid', 'symbolicTarget'], 'Backup ref');
|
|
133
|
+
const result = { name: fullRef(ref.name), oid: objectId(ref.oid, format) };
|
|
134
|
+
if (ref.symbolicTarget !== undefined) result.symbolicTarget = fullRef(ref.symbolicTarget);
|
|
135
|
+
return result;
|
|
136
|
+
}).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
137
|
+
const map = new Map(refs.map(ref => [ref.name, ref]));
|
|
138
|
+
if (!refs.length || map.size !== refs.length) fail('ERR_BACKUP_MANIFEST', 'Backup refs must be nonempty and distinct.');
|
|
139
|
+
if (refs.filter(ref => ref.symbolicTarget).length > 100) fail('ERR_BACKUP_LIMIT', 'Too many symbolic refs for supported recovery.');
|
|
140
|
+
for (const ref of refs) {
|
|
141
|
+
let current = ref; const seen = new Set();
|
|
142
|
+
while (current.symbolicTarget) {
|
|
143
|
+
if (seen.has(current.name)) fail('ERR_BACKUP_MANIFEST', 'Symbolic backup refs must not form cycles.');
|
|
144
|
+
seen.add(current.name); current = map.get(current.symbolicTarget);
|
|
145
|
+
if (!current || current.oid !== ref.oid) fail('ERR_BACKUP_MANIFEST', 'Symbolic backup refs require matching recorded targets.');
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return refs;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function manifest(value) {
|
|
152
|
+
const data = fields(value, ['schemaVersion', 'kind', 'createdAt', 'repository', 'source', 'bundle', 'refs'], 'Backup manifest');
|
|
153
|
+
if (data.schemaVersion !== 1 || data.kind !== 'git-release-guardrails-backup'
|
|
154
|
+
|| typeof data.createdAt !== 'string' || !/^\d{4}-\d{2}-\d{2}T/u.test(data.createdAt) || Number.isNaN(Date.parse(data.createdAt))) fail('ERR_BACKUP_MANIFEST', 'Use a supported backup manifest.');
|
|
155
|
+
const source = fields(data.source, ['branch', 'head', 'objectFormat'], 'Backup source');
|
|
156
|
+
if (!Object.hasOwn(source, 'objectFormat')) fail('ERR_BACKUP_MANIFEST', 'Backup source must declare its object format.');
|
|
157
|
+
const format = objectFormat(source.objectFormat);
|
|
158
|
+
const branchName = branch(source.branch), head = objectId(source.head, format);
|
|
159
|
+
const bundle = fields(data.bundle, ['file', 'bytes', 'sha256'], 'Backup bundle');
|
|
160
|
+
if (bundle.file !== 'repository.bundle' || !Number.isSafeInteger(bundle.bytes) || bundle.bytes < 1
|
|
161
|
+
|| bundle.bytes > 1024 * 1024 * 1024 || typeof bundle.sha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(bundle.sha256)) fail('ERR_BACKUP_MANIFEST', 'Backup bundle identity is invalid.');
|
|
162
|
+
const refs = refList(data.refs, format), attached = refs.find(ref => ref.name === `refs/heads/${branchName}`);
|
|
163
|
+
if (!attached || attached.symbolicTarget || attached.oid !== head) fail('ERR_BACKUP_MANIFEST', 'Backup HEAD must match its attached recorded branch.');
|
|
164
|
+
return { schemaVersion: 1, kind: data.kind, createdAt: data.createdAt, repository: text(data.repository, 'Backup repository'),
|
|
165
|
+
source: { branch: branchName, head, objectFormat: format }, bundle: { file: bundle.file, bytes: bundle.bytes, sha256: bundle.sha256 }, refs };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function readManifest(directory, options) {
|
|
169
|
+
const handle = await regular(join(directory, 'manifest.json'));
|
|
170
|
+
try {
|
|
171
|
+
const chunks = []; let bytes = 0;
|
|
172
|
+
const before = await handle.stat({ bigint: true });
|
|
173
|
+
if (before.size > BigInt(MAX_MANIFEST)) fail('ERR_BACKUP_LIMIT', 'Backup manifest exceeds the supported limit.');
|
|
174
|
+
while (true) {
|
|
175
|
+
check(options); const buffer = Buffer.alloc(65536);
|
|
176
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
|
|
177
|
+
if (!bytesRead) break;
|
|
178
|
+
bytes += bytesRead;
|
|
179
|
+
if (bytes > MAX_MANIFEST) fail('ERR_BACKUP_LIMIT', 'Backup manifest exceeds the supported limit.');
|
|
180
|
+
chunks.push(buffer.subarray(0, bytesRead));
|
|
181
|
+
}
|
|
182
|
+
if (!unchanged(before, await handle.stat({ bigint: true })) || before.size !== BigInt(bytes)) fail('ERR_BACKUP_CHANGED', 'Backup manifest changed while being read.');
|
|
183
|
+
let value;
|
|
184
|
+
try { value = unambiguousJson(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(Buffer.concat(chunks))); }
|
|
185
|
+
catch { fail('ERR_BACKUP_MANIFEST', 'Backup manifest must be unambiguous UTF-8 JSON.'); }
|
|
186
|
+
return manifest(value);
|
|
187
|
+
} finally { await handle.close(); }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function validateHeader(input, data) {
|
|
191
|
+
const string = input.header.toString('utf8');
|
|
192
|
+
if (!input.ended || !Buffer.from(string).equals(input.header)) fail('ERR_BACKUP_BUNDLE', 'Bundle header is incomplete or not UTF-8.');
|
|
193
|
+
const lines = string.slice(0, -2).split('\n'), signature = lines.shift();
|
|
194
|
+
let format = 'sha1';
|
|
195
|
+
if (signature === '# v3 git bundle') {
|
|
196
|
+
if (!['@object-format=sha1', '@object-format=sha256'].includes(lines[0])) fail('ERR_BACKUP_BUNDLE', 'Bundle object format is unsupported.');
|
|
197
|
+
format = lines.shift().slice('@object-format='.length);
|
|
198
|
+
} else if (signature !== '# v2 git bundle') fail('ERR_BACKUP_BUNDLE', 'Bundle version is unsupported.');
|
|
199
|
+
if (format !== data.source.objectFormat) fail('ERR_BACKUP_BUNDLE', 'Bundle object format conflicts with the manifest.');
|
|
200
|
+
const heads = new Map(data.refs.map(ref => [ref.name, ref.oid])); heads.set('HEAD', data.source.head);
|
|
201
|
+
for (const line of lines) {
|
|
202
|
+
const index = line.indexOf(' '), oid = line.slice(0, index), name = line.slice(index + 1);
|
|
203
|
+
// Reject prerequisites, filtered/unknown capabilities and extra/duplicate refs.
|
|
204
|
+
if (index < 1 || !heads.has(name) || heads.get(name) !== oid) fail('ERR_BACKUP_BUNDLE', 'Require an exact self-contained bundle without prerequisites or extra capabilities.');
|
|
205
|
+
heads.delete(name);
|
|
206
|
+
}
|
|
207
|
+
if (heads.size) fail('ERR_BACKUP_BUNDLE', 'Bundle does not advertise every recorded ref and HEAD.');
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function snapshot(run, format) {
|
|
211
|
+
// Ref listings can omit dangling symbolic refs without a diagnostic.
|
|
212
|
+
const connectivity = await run(['fsck', '--connectivity-only', '--no-reflogs', '--no-dangling']).catch(error => {
|
|
213
|
+
if (error.code !== 'ERR_GIT_COMMAND') throw error;
|
|
214
|
+
fail('ERR_BACKUP_REFS', 'Git reported broken refs or incomplete reachable history.');
|
|
215
|
+
});
|
|
216
|
+
if (connectivity.stderrBytes) fail('ERR_BACKUP_REFS', 'Git reported uncertain reachable history.');
|
|
217
|
+
const result = await run(['for-each-ref', REF_FORMAT]);
|
|
218
|
+
if (result.stderrBytes) fail('ERR_BACKUP_REFS', 'Git reported uncertain ref metadata.');
|
|
219
|
+
const refs = [];
|
|
220
|
+
let aliases = 0;
|
|
221
|
+
for (const line of result.stdout.replace(/\n$/u, '').split('\n').filter(Boolean)) {
|
|
222
|
+
const parts = line.split('\0');
|
|
223
|
+
if (parts.length !== 3) fail('ERR_GIT_PARSE', 'Git returned malformed backup refs.');
|
|
224
|
+
const [name, oid, symbolic] = parts;
|
|
225
|
+
const ref = { name: fullRef(name), oid };
|
|
226
|
+
if (symbolic) {
|
|
227
|
+
if (++aliases > 100) fail('ERR_BACKUP_LIMIT', 'Too many symbolic refs for supported recovery.');
|
|
228
|
+
ref.symbolicTarget = (await run(['symbolic-ref', '--no-recurse', name])).stdout.trim();
|
|
229
|
+
}
|
|
230
|
+
refs.push(ref);
|
|
231
|
+
}
|
|
232
|
+
return { refs: refList(refs, format), attached: (await run(['symbolic-ref', '--quiet', '--no-recurse', 'HEAD'])).stdout.trim(),
|
|
233
|
+
head: objectId((await run(['rev-parse', '--verify', 'HEAD^{commit}'])).stdout.trim(), format) };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function summary(data, directory) {
|
|
237
|
+
return { verified: true, repository: data.repository, objectFormat: data.source.objectFormat, refCount: data.refs.length,
|
|
238
|
+
bundleSha256: data.bundle.sha256, bundleBytes: data.bundle.bytes, directory, networkAccess: false, sourceRefMutations: false };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function restoreData(directory, data, options, destination) {
|
|
242
|
+
const temporary = await mkdtemp(join(tmpdir(), 'git-guardrails-restore-'));
|
|
243
|
+
try {
|
|
244
|
+
// Clone only the privately staged exact bytes that were hashed, not a path
|
|
245
|
+
// that could be exchanged between verification and Git opening it.
|
|
246
|
+
const staged = join(temporary, 'repository.bundle'), input = await regular(join(directory, 'repository.bundle'));
|
|
247
|
+
let output;
|
|
248
|
+
try {
|
|
249
|
+
output = await open(staged, 'wx', 0o600);
|
|
250
|
+
const copied = await transfer(input, options, options.maxBackupBytes, output);
|
|
251
|
+
if (copied.bytes !== data.bundle.bytes || copied.sha256 !== data.bundle.sha256) fail('ERR_BACKUP_INTEGRITY', 'Backup bundle size or digest does not match the manifest.');
|
|
252
|
+
validateHeader(copied, data); await output.sync();
|
|
253
|
+
} finally { await input.close(); await output?.close(); }
|
|
254
|
+
check(options);
|
|
255
|
+
const target = destination ?? join(temporary, 'proof.git');
|
|
256
|
+
await exclusiveDirectory(target);
|
|
257
|
+
const run = gitReader({ ...options, cwd: temporary, isolatedConfig: true });
|
|
258
|
+
await run(['-c', 'protocol.file.allow=always', 'clone', '--quiet', '--mirror', '--no-hardlinks', '--template=', '--', staged, target]);
|
|
259
|
+
const recovered = gitReader({ ...options, cwd: target, isolatedConfig: true });
|
|
260
|
+
// Remove clone transport configuration without deleting any recovered refs.
|
|
261
|
+
await recovered(['config', '--local', '--remove-section', 'remote.origin']);
|
|
262
|
+
for (const ref of data.refs) if (ref.symbolicTarget) await recovered(['symbolic-ref', ref.name, ref.symbolicTarget]);
|
|
263
|
+
await recovered(['symbolic-ref', 'HEAD', `refs/heads/${data.source.branch}`]);
|
|
264
|
+
const format = (await recovered(['rev-parse', '--show-object-format'])).stdout.trim();
|
|
265
|
+
const actual = await snapshot(recovered, data.source.objectFormat);
|
|
266
|
+
if (format !== data.source.objectFormat || actual.attached !== `refs/heads/${data.source.branch}`
|
|
267
|
+
|| actual.head !== data.source.head || JSON.stringify(actual.refs) !== JSON.stringify(data.refs)) fail('ERR_BACKUP_RESTORE', 'Recovered refs or object format do not match the backup.');
|
|
268
|
+
await recovered(['fsck', '--full', '--strict']);
|
|
269
|
+
if ((await recovered(['rev-parse', '--is-bare-repository'])).stdout.trim() !== 'true'
|
|
270
|
+
|| (await recovered(['rev-parse', '--is-shallow-repository'])).stdout.trim() !== 'false') fail('ERR_BACKUP_RESTORE', 'Require a full bare recovery repository.');
|
|
271
|
+
check(options);
|
|
272
|
+
return { ...summary(data, directory), ...(destination ? { destination: target } : {}) };
|
|
273
|
+
} finally { await rm(temporary, { recursive: true, force: true }); }
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async function guarded(action) {
|
|
277
|
+
try { return await action(); }
|
|
278
|
+
catch (error) {
|
|
279
|
+
if (error.code?.startsWith('ERR_')) throw error;
|
|
280
|
+
fail('ERR_BACKUP_IO', 'Backup operation failed; preserve any partial new directory for inspection.');
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Backup inspected, committed/ref-reachable Git history; never original refs/config/files. */
|
|
285
|
+
export async function createRetirementBackup(input) {
|
|
286
|
+
return guarded(async () => {
|
|
287
|
+
const { data, directory: requested, options } = operation(input, ['inspection']);
|
|
288
|
+
const source = fields(data.inspection, ['cwd', 'repository', 'expectedRemoteUrls', 'remote', 'integrationBranch', 'permanent',
|
|
289
|
+
'reviewedHeads', 'temporaryPrefixes', 'timeoutMs', 'maxOutputBytes'], 'Backup inspection');
|
|
290
|
+
for (const name of ['permanent', 'expectedRemoteUrls', 'temporaryPrefixes']) if (source[name] !== undefined) source[name] = list(source[name], name, 10000);
|
|
291
|
+
if (source.reviewedHeads !== undefined) source.reviewedHeads = list(source.reviewedHeads, 'Reviewed heads', 10000)
|
|
292
|
+
.map(item => fields(item, ['repository', 'branch', 'head', 'target', 'evidence'], 'Reviewed head'));
|
|
293
|
+
const inspection = await inspectRetirements({ ...source, signal: options.signal });
|
|
294
|
+
source.cwd = inspection.source.root;
|
|
295
|
+
const run = gitReader({ ...options, cwd: inspection.source.root });
|
|
296
|
+
const common = await realpath(resolve(inspection.source.root, (await run(['rev-parse', '--git-common-dir'])).stdout.trim()));
|
|
297
|
+
const directory = await newPath(requested);
|
|
298
|
+
if (inside(directory, inspection.source.root) || inside(directory, common)) fail('ERR_BACKUP_DESTINATION', 'Store backup outside the source working tree and Git directory.');
|
|
299
|
+
const before = await snapshot(run, inspection.source.objectFormat);
|
|
300
|
+
if (before.attached !== `refs/heads/${inspection.source.branch}` || before.head !== inspection.source.head) fail('ERR_BACKUP_CHANGED', 'Source changed before backup.');
|
|
301
|
+
check(options); await exclusiveDirectory(directory);
|
|
302
|
+
const handle = await open(join(directory, 'repository.bundle'), 'wx', 0o600);
|
|
303
|
+
try { await writeBundle(handle, { ...options, cwd: inspection.source.root }); }
|
|
304
|
+
finally { await handle.close(); }
|
|
305
|
+
const reader = await regular(join(directory, 'repository.bundle'));
|
|
306
|
+
let identity;
|
|
307
|
+
try { identity = await transfer(reader, options, options.maxBackupBytes); }
|
|
308
|
+
finally { await reader.close(); }
|
|
309
|
+
const value = manifest({ schemaVersion: 1, kind: 'git-release-guardrails-backup', createdAt: new Date().toISOString(),
|
|
310
|
+
repository: inspection.plan.repository, source: { branch: inspection.source.branch, head: inspection.source.head, objectFormat: inspection.source.objectFormat },
|
|
311
|
+
bundle: { file: 'repository.bundle', bytes: identity.bytes, sha256: identity.sha256 }, refs: before.refs });
|
|
312
|
+
validateHeader(identity, value);
|
|
313
|
+
await restoreData(directory, value, options);
|
|
314
|
+
const reinspection = await inspectRetirements({ ...source, signal: options.signal });
|
|
315
|
+
const after = await snapshot(run, inspection.source.objectFormat);
|
|
316
|
+
if (JSON.stringify(before) !== JSON.stringify(after) || JSON.stringify(inspection) !== JSON.stringify(reinspection)) fail('ERR_BACKUP_CHANGED', 'Source changed during backup; no completed manifest was written.');
|
|
317
|
+
check(options);
|
|
318
|
+
const encoded = JSON.stringify(value, null, 2) + '\n';
|
|
319
|
+
if (Buffer.byteLength(encoded) > MAX_MANIFEST) fail('ERR_BACKUP_LIMIT', 'Backup manifest exceeds the supported limit.');
|
|
320
|
+
const pending = join(directory, '.manifest.pending');
|
|
321
|
+
const completed = await open(pending, 'wx', 0o600);
|
|
322
|
+
try { await completed.writeFile(encoded); await completed.sync(); }
|
|
323
|
+
finally { await completed.close(); }
|
|
324
|
+
check(options);
|
|
325
|
+
// Publish only the complete fsynced manifest, without replacing any path.
|
|
326
|
+
await link(pending, join(directory, 'manifest.json')); await unlink(pending);
|
|
327
|
+
const folder = await open(directory, constants.O_RDONLY);
|
|
328
|
+
try { await folder.sync(); } finally { await folder.close(); }
|
|
329
|
+
check(options);
|
|
330
|
+
return summary(value, directory);
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Hash/header checks plus an actual isolated restoration and full Git fsck. */
|
|
335
|
+
export async function verifyRetirementBackup(input) {
|
|
336
|
+
return guarded(async () => {
|
|
337
|
+
const { directory: requested, options } = operation(input);
|
|
338
|
+
const directory = await existingDirectory(requested), data = await readManifest(directory, options);
|
|
339
|
+
return restoreData(directory, data, options);
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// Internal binding between the approved heads and the verified Git bundle.
|
|
344
|
+
export async function assertBackupCoversRetirement(directory, state, checksum, signal) {
|
|
345
|
+
const options = { signal };
|
|
346
|
+
const data = await readManifest(await existingDirectory(directory), options);
|
|
347
|
+
const byName = new Map(data.refs.map(ref => [ref.name, ref]));
|
|
348
|
+
const source = state.source;
|
|
349
|
+
const expected = [
|
|
350
|
+
...state.refs.local.map(([name, id]) => [`refs/heads/${name}`, id]),
|
|
351
|
+
...state.refs.tracking.map(([name, id]) => [`refs/remotes/${source.remote}/${name}`, id]),
|
|
352
|
+
];
|
|
353
|
+
if (data.repository !== state.plan.repository || data.source.branch !== source.branch ||
|
|
354
|
+
data.source.head !== source.head || data.source.objectFormat !== source.objectFormat || data.bundle.sha256 !== checksum ||
|
|
355
|
+
expected.some(([name, id]) => byName.get(name)?.oid !== id || byName.get(name)?.symbolicTarget)) {
|
|
356
|
+
fail('ERR_RETIREMENT_BACKUP', 'The verified backup does not cover the approved direct branch refs.');
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Restore only into a newly created bare repository, never an existing live repo. */
|
|
361
|
+
export async function restoreRetirementBackup(input) {
|
|
362
|
+
return guarded(async () => {
|
|
363
|
+
const { data: request, directory: requested, options } = operation(input, ['destination']);
|
|
364
|
+
const destination = await newPath(resolve(text(request.destination, 'Recovery destination', 4096)));
|
|
365
|
+
const directory = await existingDirectory(requested), data = await readManifest(directory, options);
|
|
366
|
+
if (inside(destination, directory)) fail('ERR_BACKUP_DESTINATION', 'Recover outside the backup directory.');
|
|
367
|
+
await protectExistingRepositories(destination);
|
|
368
|
+
return restoreData(directory, data, options, destination);
|
|
369
|
+
});
|
|
370
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { GitReleaseGuardError, fail } from '../errors.mjs';
|
|
3
|
+
import { GIT_LOCAL_ARGS, inspectionEnvironment } from './process.mjs';
|
|
4
|
+
|
|
5
|
+
/** Binary streaming: backpressure to the exclusive file, never a whole-pack buffer. */
|
|
6
|
+
export async function writeBundle(handle, { cwd, timeoutMs, maxBackupBytes, signal }) {
|
|
7
|
+
if (signal.aborted) fail('ERR_ABORTED', 'Backup was cancelled.');
|
|
8
|
+
const child = spawn('git', [...GIT_LOCAL_ARGS, 'bundle', 'create', '--quiet', '-', '--all'], {
|
|
9
|
+
cwd, env: inspectionEnvironment(), detached: true, stdio: ['ignore', 'pipe', 'pipe'],
|
|
10
|
+
});
|
|
11
|
+
let failure, bytes = 0, diagnostics = 0;
|
|
12
|
+
const stop = (code, message) => {
|
|
13
|
+
failure ??= new GitReleaseGuardError(code, message);
|
|
14
|
+
if (child.pid) { try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); } }
|
|
15
|
+
};
|
|
16
|
+
const closed = new Promise(resolve => {
|
|
17
|
+
child.once('error', () => stop('ERR_GIT_START', 'Git could not be started.'));
|
|
18
|
+
child.once('close', (status, by) => resolve({ status, by }));
|
|
19
|
+
});
|
|
20
|
+
child.stderr.on('data', data => {
|
|
21
|
+
diagnostics += data.length;
|
|
22
|
+
if (diagnostics > 1024 * 1024) stop('ERR_GIT_OUTPUT_LIMIT', 'Backup diagnostics exceeded the supported limit.');
|
|
23
|
+
});
|
|
24
|
+
const timer = setTimeout(() => stop('ERR_GIT_TIMEOUT', 'Backup exceeded its command deadline.'), timeoutMs);
|
|
25
|
+
const aborted = () => stop(signal.reason?.name === 'TimeoutError' ? 'ERR_GIT_TIMEOUT' : 'ERR_ABORTED', 'Backup was cancelled or exceeded its deadline.');
|
|
26
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
27
|
+
if (signal.aborted) aborted();
|
|
28
|
+
try {
|
|
29
|
+
try {
|
|
30
|
+
for await (const chunk of child.stdout) {
|
|
31
|
+
if (failure) break;
|
|
32
|
+
bytes += chunk.length;
|
|
33
|
+
if (bytes > maxBackupBytes) { stop('ERR_BACKUP_LIMIT', 'Backup exceeds the supported byte limit.'); break; }
|
|
34
|
+
let offset = 0;
|
|
35
|
+
while (offset < chunk.length) {
|
|
36
|
+
if (signal.aborted) { aborted(); break; }
|
|
37
|
+
const { bytesWritten } = await handle.write(chunk, offset, chunk.length - offset, null);
|
|
38
|
+
if (!bytesWritten) throw new Error();
|
|
39
|
+
offset += bytesWritten;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
} catch { stop('ERR_BACKUP_IO', 'Backup data could not be written.'); }
|
|
43
|
+
const { status, by } = await closed;
|
|
44
|
+
if (failure) throw failure;
|
|
45
|
+
if (status !== 0 || by || diagnostics) fail('ERR_GIT_COMMAND', 'Git could not create a complete warning-free backup.');
|
|
46
|
+
await handle.sync();
|
|
47
|
+
return bytes;
|
|
48
|
+
} finally {
|
|
49
|
+
clearTimeout(timer); signal.removeEventListener('abort', aborted);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { open, constants } from 'node:fs/promises';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { fields, text, list, branch, branchList, objectId } from '../validation.mjs';
|
|
4
|
+
import { assertRemoteDestinations } from '../remote.mjs';
|
|
5
|
+
import { DEFAULT_TEMPORARY_PREFIXES } from '../plan.mjs';
|
|
6
|
+
import { fail } from '../errors.mjs';
|
|
7
|
+
|
|
8
|
+
const MAX_BYTES = 1024 * 1024;
|
|
9
|
+
|
|
10
|
+
function cancelled(signal) {
|
|
11
|
+
if (signal?.aborted) fail('ERR_ABORTED', 'Configuration loading was cancelled.');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// JSON.parse establishes grammar first. This second pass rejects duplicate keys
|
|
15
|
+
// (including escaped aliases) and bounds nesting without executing any input.
|
|
16
|
+
export function unambiguousJson(source) {
|
|
17
|
+
let value;
|
|
18
|
+
try { value = JSON.parse(source); }
|
|
19
|
+
catch { fail('ERR_CONFIG_JSON', 'Configuration must contain valid UTF-8 JSON.'); }
|
|
20
|
+
const stack = [];
|
|
21
|
+
for (const match of source.matchAll(/"(?:[^"\\]|\\[\s\S])*"|[{}\[\],:]|[^\s{}\[\],:"]+/gu)) {
|
|
22
|
+
const token = match[0], current = stack.at(-1);
|
|
23
|
+
if (token === '{' || token === '[') {
|
|
24
|
+
stack.push({ keys: token === '{' ? new Set() : null, key: true });
|
|
25
|
+
if (stack.length > 32) fail('ERR_CONFIG_JSON', 'Configuration nesting exceeds the supported limit.');
|
|
26
|
+
} else if (token === '}' || token === ']') stack.pop();
|
|
27
|
+
else if (token === ',') { if (current?.keys) current.key = true; }
|
|
28
|
+
else if (token.startsWith('"') && current?.keys && current.key) {
|
|
29
|
+
const key = JSON.parse(token);
|
|
30
|
+
if (current.keys.has(key)) fail('ERR_CONFIG_JSON', 'Configuration contains duplicate object keys.');
|
|
31
|
+
current.keys.add(key); current.key = false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** JSON data only: no imports, environment interpolation or executable hooks. */
|
|
38
|
+
function configuration(value) {
|
|
39
|
+
const data = fields(value, ['schemaVersion', 'repository', 'expectedRemoteUrls', 'remote', 'integrationBranch',
|
|
40
|
+
'permanent', 'reviewedHeads', 'temporaryPrefixes', 'timeoutMs', 'maxOutputBytes'], 'Configuration');
|
|
41
|
+
if (data.schemaVersion !== 1) fail('ERR_CONFIG_SCHEMA', 'Use configuration schemaVersion 1.');
|
|
42
|
+
const repository = text(data.repository, 'Repository identity');
|
|
43
|
+
const expectedRemoteUrls = list(data.expectedRemoteUrls, 'Expected remote URLs', 8);
|
|
44
|
+
assertRemoteDestinations({ expectedRemoteUrls, fetchUrls: expectedRemoteUrls.slice(0, 1), pushUrls: expectedRemoteUrls.slice(0, 1) });
|
|
45
|
+
const remote = data.remote === undefined ? 'origin' : text(data.remote, 'Remote name', 64);
|
|
46
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/u.test(remote) || remote.includes('..')) fail('ERR_INPUT', 'Use a supported simple remote name.');
|
|
47
|
+
const integrationBranch = branch(data.integrationBranch, 'Integration branch');
|
|
48
|
+
const permanent = branchList(data.permanent, 'Permanent branches');
|
|
49
|
+
if (!permanent.includes(integrationBranch)) fail('ERR_INPUT', 'The integration branch must be permanent.');
|
|
50
|
+
const temporaryPrefixes = list(data.temporaryPrefixes === undefined ? DEFAULT_TEMPORARY_PREFIXES : data.temporaryPrefixes, 'Temporary prefixes').map(prefix => {
|
|
51
|
+
text(prefix, 'Temporary prefix');
|
|
52
|
+
if (!prefix.endsWith('/')) fail('ERR_INPUT', 'Each temporary prefix must end with a slash.');
|
|
53
|
+
branch(prefix.slice(0, -1), 'Temporary prefix'); return prefix;
|
|
54
|
+
});
|
|
55
|
+
if (!temporaryPrefixes.length || new Set(temporaryPrefixes).size !== temporaryPrefixes.length) fail('ERR_INPUT', 'Supply distinct temporary prefixes.');
|
|
56
|
+
const reviewedHeads = list(data.reviewedHeads === undefined ? [] : data.reviewedHeads, 'Reviewed heads', 10000).map(item => {
|
|
57
|
+
const review = fields(item, ['repository', 'branch', 'head', 'target', 'evidence'], 'Reviewed head');
|
|
58
|
+
const format = typeof review.head === 'string' && review.head.length === 64 ? 'sha256' : 'sha1';
|
|
59
|
+
return { repository: text(review.repository, 'Reviewed repository'), branch: branch(review.branch, 'Reviewed branch'),
|
|
60
|
+
head: objectId(review.head, format, 'Reviewed head'), target: objectId(review.target, format, 'Reviewed target'),
|
|
61
|
+
evidence: text(review.evidence, 'Review evidence reference', 2048) };
|
|
62
|
+
});
|
|
63
|
+
const identities = reviewedHeads.map(({ repository, branch, head, target }) => JSON.stringify([repository, branch, head, target]));
|
|
64
|
+
if (new Set(identities).size !== identities.length) fail('ERR_INPUT', 'Duplicate reviewed-head identities are ambiguous.');
|
|
65
|
+
const timeoutMs = data.timeoutMs === undefined ? 10000 : data.timeoutMs;
|
|
66
|
+
const maxOutputBytes = data.maxOutputBytes === undefined ? 4 * 1024 * 1024 : data.maxOutputBytes;
|
|
67
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30000
|
|
68
|
+
|| !Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1024 || maxOutputBytes > 16 * 1024 * 1024) fail('ERR_INPUT', 'Supply supported inspection limits.');
|
|
69
|
+
return { repository, expectedRemoteUrls, remote, integrationBranch, permanent, temporaryPrefixes, reviewedHeads, timeoutMs, maxOutputBytes };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Read a bounded regular file, refusing a symlink as the final path component. */
|
|
73
|
+
export async function readRetirementConfig(file, input = {}) {
|
|
74
|
+
text(file, 'Configuration file', 4096);
|
|
75
|
+
const { signal } = fields(input, ['signal'], 'Configuration read options');
|
|
76
|
+
if (signal !== undefined && !(signal instanceof AbortSignal)) fail('ERR_INPUT', 'Supply a valid AbortSignal.');
|
|
77
|
+
cancelled(signal);
|
|
78
|
+
// Fail closed on platforms without these POSIX regular-file protections.
|
|
79
|
+
if (!Number.isInteger(constants.O_NOFOLLOW) || constants.O_NOFOLLOW <= 0
|
|
80
|
+
|| !Number.isInteger(constants.O_NONBLOCK) || constants.O_NONBLOCK <= 0) fail('ERR_CONFIG_FILE', 'This platform lacks the required configuration-file protections.');
|
|
81
|
+
let handle;
|
|
82
|
+
try {
|
|
83
|
+
handle = await open(resolve(file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
84
|
+
const before = await handle.stat({ bigint: true });
|
|
85
|
+
if (!before.isFile()) fail('ERR_CONFIG_FILE', 'Configuration must be a regular file.');
|
|
86
|
+
if (before.size > BigInt(MAX_BYTES)) fail('ERR_CONFIG_LIMIT', 'Configuration exceeds the 1 MiB limit.');
|
|
87
|
+
const chunks = []; let bytes = 0;
|
|
88
|
+
while (true) {
|
|
89
|
+
cancelled(signal);
|
|
90
|
+
const buffer = Buffer.alloc(Math.min(65536, MAX_BYTES + 1 - bytes));
|
|
91
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
|
|
92
|
+
if (bytesRead === 0) break;
|
|
93
|
+
chunks.push(buffer.subarray(0, bytesRead)); bytes += bytesRead;
|
|
94
|
+
if (bytes > MAX_BYTES) fail('ERR_CONFIG_LIMIT', 'Configuration exceeds the 1 MiB limit.');
|
|
95
|
+
}
|
|
96
|
+
const after = await handle.stat({ bigint: true });
|
|
97
|
+
if (['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].some(key => before[key] !== after[key]) || after.size !== BigInt(bytes)) fail('ERR_CONFIG_CHANGED', 'Configuration changed while being read; retry from stable data.');
|
|
98
|
+
cancelled(signal);
|
|
99
|
+
let source;
|
|
100
|
+
try { source = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(Buffer.concat(chunks)); }
|
|
101
|
+
catch { fail('ERR_CONFIG_JSON', 'Configuration must contain valid UTF-8 JSON.'); }
|
|
102
|
+
return configuration(unambiguousJson(source));
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (error.code?.startsWith('ERR_')) throw error;
|
|
105
|
+
fail('ERR_CONFIG_FILE', 'Configuration could not be read as a regular file.');
|
|
106
|
+
} finally {
|
|
107
|
+
try { await handle?.close(); }
|
|
108
|
+
catch { fail('ERR_CONFIG_FILE', 'Configuration file could not be closed.'); }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { ReviewedHead, RetirementPlan, ObjectFormat } from '../index.mjs';
|
|
2
|
+
|
|
3
|
+
export interface InspectionOptions {
|
|
4
|
+
readonly cwd: string;
|
|
5
|
+
readonly repository: string;
|
|
6
|
+
readonly expectedRemoteUrls: readonly string[];
|
|
7
|
+
readonly remote?: string;
|
|
8
|
+
readonly integrationBranch: string;
|
|
9
|
+
readonly permanent: readonly string[];
|
|
10
|
+
readonly reviewedHeads?: readonly ReviewedHead[];
|
|
11
|
+
readonly temporaryPrefixes?: readonly string[];
|
|
12
|
+
/** Git inspection deadline in milliseconds; 1..30000, default 10000. */
|
|
13
|
+
readonly timeoutMs?: number;
|
|
14
|
+
/** Combined stdout/stderr bytes per command; 1024..16777216, default 4194304. */
|
|
15
|
+
readonly maxOutputBytes?: number;
|
|
16
|
+
readonly signal?: AbortSignal;
|
|
17
|
+
}
|
|
18
|
+
export interface InspectionResult {
|
|
19
|
+
inspectionOnly: true;
|
|
20
|
+
remoteFreshness: 'unverified-local-cache';
|
|
21
|
+
networkAccess: false;
|
|
22
|
+
refMutations: false;
|
|
23
|
+
source: { root: string; branch: string; head: string; objectFormat: ObjectFormat; remote: string };
|
|
24
|
+
transport: { fetchUrl: string; pushUrl: string; fetchRefspec: string };
|
|
25
|
+
worktrees: { path: string; branch: string; head: string }[];
|
|
26
|
+
plan: RetirementPlan;
|
|
27
|
+
}
|
|
28
|
+
export function inspectRetirements(options: InspectionOptions): Promise<InspectionResult>;
|
|
29
|
+
|
|
30
|
+
export interface LiveInspectionOptions extends InspectionOptions {
|
|
31
|
+
/** Optional Basic or Bearer header value sent only to this exact approved HTTPS endpoint. */
|
|
32
|
+
readonly httpsAuthorization?: { readonly endpoint: string; readonly value: string };
|
|
33
|
+
}
|
|
34
|
+
export interface LiveInspectionResult extends Omit<InspectionResult, 'remoteFreshness' | 'networkAccess'> {
|
|
35
|
+
remoteFreshness: 'matched-live-advertisement';
|
|
36
|
+
networkAccess: true;
|
|
37
|
+
/** Exact reviewed plan identity to supply to apply or recovery. */
|
|
38
|
+
planId: string;
|
|
39
|
+
observation: { checkedAt: string; fetchBranchCount: number; pushBranchCount: number; distinctEndpointsChecked: number };
|
|
40
|
+
}
|
|
41
|
+
export function validateLiveRetirement(options: LiveInspectionOptions): Promise<LiveInspectionResult>;
|
|
42
|
+
|
|
43
|
+
/** Declarative schemaVersion 1 data; paths/AbortSignal are supplied by the caller. */
|
|
44
|
+
export type RetirementConfig = Omit<InspectionOptions, 'cwd' | 'signal'>;
|
|
45
|
+
/** A regular, nonsymlink UTF-8 JSON file, at most 1 MiB; no executable config. */
|
|
46
|
+
export function readRetirementConfig(file: string, options?: { readonly signal?: AbortSignal }): Promise<RetirementConfig>;
|
|
47
|
+
|
|
48
|
+
export interface BackupOptions {
|
|
49
|
+
readonly directory: string;
|
|
50
|
+
/** Whole Git-operation deadline; 1..30000 milliseconds, default 30000. Native FS calls are not preempted. */
|
|
51
|
+
readonly timeoutMs?: number;
|
|
52
|
+
/** Bundle byte limit; 1024..1073741824, default 268435456. */
|
|
53
|
+
readonly maxBackupBytes?: number;
|
|
54
|
+
readonly signal?: AbortSignal;
|
|
55
|
+
}
|
|
56
|
+
export interface BackupResult {
|
|
57
|
+
verified: true;
|
|
58
|
+
repository: string;
|
|
59
|
+
objectFormat: ObjectFormat;
|
|
60
|
+
refCount: number;
|
|
61
|
+
bundleSha256: string;
|
|
62
|
+
bundleBytes: number;
|
|
63
|
+
directory: string;
|
|
64
|
+
networkAccess: false;
|
|
65
|
+
sourceRefMutations: false;
|
|
66
|
+
}
|
|
67
|
+
export interface RestorationResult extends BackupResult { destination: string; }
|
|
68
|
+
export function createRetirementBackup(options: BackupOptions & { readonly inspection: Omit<InspectionOptions, 'signal'> }): Promise<BackupResult>;
|
|
69
|
+
export function verifyRetirementBackup(options: BackupOptions): Promise<BackupResult>;
|
|
70
|
+
export function restoreRetirementBackup(options: BackupOptions & { readonly destination: string }): Promise<RestorationResult>;
|
|
71
|
+
|
|
72
|
+
export interface RetirementExecutionOptions extends BackupOptions {
|
|
73
|
+
readonly inspection: Omit<LiveInspectionOptions, 'signal'>;
|
|
74
|
+
readonly expectedPlanId: string;
|
|
75
|
+
}
|
|
76
|
+
export interface RetirementExecutionResult {
|
|
77
|
+
completed: true;
|
|
78
|
+
recovered: boolean;
|
|
79
|
+
planId: string;
|
|
80
|
+
directory: string | null;
|
|
81
|
+
remoteRetired: number;
|
|
82
|
+
localRetired: number;
|
|
83
|
+
localAligned: number;
|
|
84
|
+
}
|
|
85
|
+
export function applyRetirement(options: RetirementExecutionOptions): Promise<RetirementExecutionResult>;
|
|
86
|
+
export function recoverRetirement(options: RetirementExecutionOptions): Promise<RetirementExecutionResult>;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { inspectRetirements, validateLiveRetirement } from './inspect.mjs';
|
|
2
|
+
export { applyRetirement, recoverRetirement } from './retire.mjs';
|
|
3
|
+
export { readRetirementConfig } from './config.mjs';
|
|
4
|
+
export { createRetirementBackup, verifyRetirementBackup, restoreRetirementBackup } from './backup.mjs';
|