@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,148 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { resolve } from 'node:path';
4
+ import metadata from '../package.json' with { type: 'json' };
5
+ import { inspectRetirements, validateLiveRetirement, readRetirementConfig, createRetirementBackup, verifyRetirementBackup, restoreRetirementBackup, applyRetirement, recoverRetirement } from '../src/node/index.mjs';
6
+ import { GitReleaseGuardError } from '../src/errors.mjs';
7
+
8
+ const commands = ['preview', 'backup', 'verify-backup', 'restore-backup', 'apply', 'recover'];
9
+ const help = `Usage: ehven-git-release-guardrails preview --config FILE [--cwd ROOT] [--live] [--json]
10
+ ehven-git-release-guardrails backup --config FILE --directory NEW [--cwd ROOT] [--json]
11
+ ehven-git-release-guardrails verify-backup --directory DIR [--json]
12
+ ehven-git-release-guardrails restore-backup --directory DIR --destination NEW [--json]
13
+ ehven-git-release-guardrails apply --config FILE --expect-plan ID --directory NEW [--cwd ROOT] [--json]
14
+ ehven-git-release-guardrails recover --config FILE --expect-plan ID --directory DIR [--cwd ROOT] [--json]
15
+ ehven-git-release-guardrails --help
16
+ ehven-git-release-guardrails --version
17
+
18
+ Preview integrated temporary branches using local Git and cached remote refs.
19
+ Backup creates a new private directory outside source; it verifies isolated bare
20
+ restoration before writing its completion manifest. Verify-backup repeats that
21
+ proof. Restore-backup creates a fresh bare repository, never an existing target.
22
+ Preview uses the local cache by default. --live compares that cache with the
23
+ branches advertised by the approved endpoints and prints a point-in-time plan ID.
24
+ Apply requires that reviewed ID and writes a verified backup and journal before
25
+ changing refs. Recover continues the exact recorded plan after an interruption.
26
+
27
+ --config FILE SchemaVersion 1 regular JSON file (at most 1 MiB).
28
+ --cwd ROOT Source root for preview/backup; default invocation directory.
29
+ --live Request read-only live remote validation.
30
+ --https-auth-endpoint URL Exact approved HTTPS endpoint for authorization.
31
+ --https-auth-env NAME Environment variable containing Basic or Bearer value.
32
+ --expect-plan ID Full plan ID from the reviewed live preview.
33
+ --directory DIR New backup output or existing backup input, by command.
34
+ --destination NEW New bare recovery directory for restore-backup.
35
+ --timeout-ms N Backup stage deadline, 1..30000; default 30000.
36
+ --max-backup-bytes N Bundle limit, 1024..1073741824; default 268435456.
37
+ --json JSON success on stdout; JSON refusals on stderr.
38
+
39
+ Paths resolve from the invocation directory. Configuration is data only. Backup
40
+ preserves ref-reachable Git history, not working files, configuration, reflogs or
41
+ unreachable objects. Keep backup history private. Parent filesystems/writers are
42
+ trusted; native filesystem calls are not preempted by the Git-process deadline.
43
+ The apply/recover commands can delete committed branches. See the README for
44
+ the separate remote and local transaction guarantees and recovery procedure.
45
+ `;
46
+
47
+ const args = process.argv.slice(2);
48
+ let json = args.includes('--json');
49
+ const controller = new AbortController();
50
+ let interrupted;
51
+ const onInterrupt = signal => { interrupted = signal; controller.abort(); };
52
+ const onSigint = () => onInterrupt('SIGINT'), onSigterm = () => onInterrupt('SIGTERM');
53
+ process.on('SIGINT', onSigint); process.on('SIGTERM', onSigterm);
54
+ const usage = () => { throw new GitReleaseGuardError('ERR_CLI_USAGE', 'Select a supported command with its required arguments, or use --help.'); };
55
+ try {
56
+ let parsed;
57
+ try {
58
+ parsed = parseArgs({ args, strict: true, allowPositionals: true, tokens: true, options: {
59
+ config: { type: 'string' }, cwd: { type: 'string' }, json: { type: 'boolean' },
60
+ help: { type: 'boolean' }, version: { type: 'boolean' }, directory: { type: 'string' },
61
+ destination: { type: 'string' }, 'timeout-ms': { type: 'string' }, 'max-backup-bytes': { type: 'string' },
62
+ live: { type: 'boolean' }, 'https-auth-endpoint': { type: 'string' }, 'https-auth-env': { type: 'string' },
63
+ 'expect-plan': { type: 'string' },
64
+ } });
65
+ const names = parsed.tokens.filter(token => token.kind === 'option').map(token => token.name);
66
+ if (new Set(names).size !== names.length) throw new Error();
67
+ } catch { throw new GitReleaseGuardError('ERR_CLI_USAGE', 'Unsupported or repeated command-line arguments. Use --help.'); }
68
+ const { values, positionals } = parsed;
69
+ json = values.json === true;
70
+ if (values.help && Object.keys(values).length === 1 && positionals.length <= 1
71
+ && (!positionals.length || commands.includes(positionals[0]))) {
72
+ process.stdout.write(help);
73
+ } else if (values.version && Object.keys(values).length === 1 && positionals.length === 0) {
74
+ process.stdout.write(`${metadata.name}@${metadata.version}\n`);
75
+ } else {
76
+ const command = positionals[0];
77
+ if (positionals.length !== 1 || !commands.includes(command)) usage();
78
+ const execution = command === 'apply' || command === 'recover';
79
+ const hasSource = ['preview', 'backup', 'apply', 'recover'].includes(command);
80
+ const allowed = command === 'preview' ? ['config', 'cwd', 'json', 'live', 'https-auth-endpoint', 'https-auth-env']
81
+ : command === 'backup' ? ['config', 'cwd', 'directory', 'json', 'timeout-ms', 'max-backup-bytes']
82
+ : command === 'verify-backup' ? ['directory', 'json', 'timeout-ms', 'max-backup-bytes']
83
+ : execution ? ['config', 'cwd', 'directory', 'json', 'timeout-ms', 'max-backup-bytes', 'expect-plan', 'https-auth-endpoint', 'https-auth-env']
84
+ : ['directory', 'destination', 'json', 'timeout-ms', 'max-backup-bytes'];
85
+ if (Object.keys(values).some(name => !allowed.includes(name))) usage();
86
+ if ((hasSource && !values.config) || (execution && !values['expect-plan'])
87
+ || (command !== 'preview' && !values.directory) || (command === 'restore-backup' && !values.destination)) usage();
88
+ const authEndpoint = values['https-auth-endpoint'], authEnv = values['https-auth-env'];
89
+ let httpsAuthorization;
90
+ if (authEndpoint !== undefined || authEnv !== undefined) {
91
+ if ((!values.live && !execution) || !authEndpoint || !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(authEnv ?? '')) usage();
92
+ httpsAuthorization = { endpoint: authEndpoint, value: process.env[authEnv] };
93
+ }
94
+ const options = { signal: controller.signal };
95
+ if (values.directory) options.directory = values.directory;
96
+ for (const [flag, name] of [['timeout-ms', 'timeoutMs'], ['max-backup-bytes', 'maxBackupBytes']]) {
97
+ if (values[flag] !== undefined) {
98
+ if (!/^[1-9][0-9]*$/u.test(values[flag]) || !Number.isSafeInteger(Number(values[flag]))) usage();
99
+ options[name] = Number(values[flag]);
100
+ }
101
+ }
102
+ let result;
103
+ if (hasSource) {
104
+ const config = await readRetirementConfig(values.config, { signal: controller.signal });
105
+ const inspection = { ...config, cwd: resolve(values.cwd ?? process.cwd()) };
106
+ if (command === 'backup') result = await createRetirementBackup({ ...options, inspection });
107
+ else if (execution) {
108
+ const execute = command === 'apply' ? applyRetirement : recoverRetirement;
109
+ result = await execute({ ...options, inspection: { ...inspection, httpsAuthorization },
110
+ expectedPlanId: values['expect-plan'] });
111
+ }
112
+ else if (values.live) result = await validateLiveRetirement({ ...inspection, signal: controller.signal, httpsAuthorization });
113
+ else result = await inspectRetirements({ ...inspection, signal: controller.signal });
114
+ } else if (command === 'verify-backup') result = await verifyRetirementBackup(options);
115
+ else result = await restoreRetirementBackup({ ...options, destination: values.destination });
116
+ if (json) process.stdout.write(JSON.stringify({ schemaVersion: 1, ok: true, command, result }) + '\n');
117
+ else if (command === 'preview') {
118
+ if (result.networkAccess) {
119
+ process.stdout.write(`Preview only. Live advertisements matched at ${result.observation.checkedAt}. No ref changes.\n`);
120
+ process.stdout.write(`Plan ID: ${result.planId}\n`);
121
+ } else {
122
+ process.stdout.write('Preview only. Remote freshness: unverified local cache. No network or ref changes.\n');
123
+ }
124
+ process.stdout.write(`Target: ${result.plan.target}\n`);
125
+ for (const scope of ['remote', 'local']) {
126
+ process.stdout.write(`${scope} temporary branches: ${result.plan[scope].length}\n`);
127
+ for (const entry of result.plan[scope]) process.stdout.write(` ${entry.branch} ${entry.sha} (${entry.basis})\n`);
128
+ }
129
+ process.stdout.write(`Local permanent branches needing alignment: ${result.plan.align.length}\n`);
130
+ for (const name of result.plan.align) process.stdout.write(` ${name}\n`);
131
+ } else if (execution) {
132
+ process.stdout.write(`Retirement verified. Remote retired: ${result.remoteRetired}; local retired: ${result.localRetired}; aligned: ${result.localAligned}.\n`);
133
+ if (result.directory) process.stdout.write(`Backup and recovery journal: ${result.directory}\n`);
134
+ } else {
135
+ process.stdout.write(`Verified ${command}: ${result.refCount} refs, ${result.bundleBytes} bundle bytes.\n`);
136
+ process.stdout.write(`Backup: ${result.directory}\nSHA256: ${result.bundleSha256}\n`);
137
+ if (result.destination) process.stdout.write(`Fresh bare recovery: ${result.destination}\n`);
138
+ process.stdout.write('No network access or original source ref changes.\n');
139
+ }
140
+ }
141
+ } catch (cause) {
142
+ const error = cause instanceof GitReleaseGuardError ? cause : new GitReleaseGuardError('ERR_CLI_FAILURE', 'The command failed; inspect and preserve repository state before retrying.');
143
+ if (json) process.stderr.write(JSON.stringify({ schemaVersion: 1, ok: false, error: { code: error.code, message: error.message } }) + '\n');
144
+ else process.stderr.write(`${error.code}: ${error.message}\n`);
145
+ process.exitCode = interrupted === 'SIGINT' ? 130 : interrupted === 'SIGTERM' ? 143 : error.code === 'ERR_CLI_USAGE' ? 2 : 1;
146
+ } finally {
147
+ process.removeListener('SIGINT', onSigint); process.removeListener('SIGTERM', onSigterm);
148
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@ehven/git-release-guardrails",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "description": "Portable Git release guards with verified backups, guarded retirement and recovery.",
7
+ "author": "Ehventerprise LLC",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/ehven-consultants-npm-products/ehven-git-release-guardrails.git"
11
+ },
12
+ "homepage": "https://github.com/ehven-consultants-npm-products/ehven-git-release-guardrails#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/ehven-consultants-npm-products/ehven-git-release-guardrails/issues"
15
+ },
16
+ "keywords": ["git", "branch-retirement", "release", "backup", "recovery", "cli"],
17
+ "publishConfig": {
18
+ "access": "public",
19
+ "registry": "https://registry.npmjs.org/"
20
+ },
21
+ "engines": {
22
+ "node": ">=24.19.0 <25"
23
+ },
24
+ "exports": {
25
+ ".": {
26
+ "types": "./src/index.d.mts",
27
+ "import": "./src/index.mjs"
28
+ },
29
+ "./node": {
30
+ "types": "./src/node/index.d.mts",
31
+ "import": "./src/node/index.mjs"
32
+ }
33
+ },
34
+ "files": [
35
+ "src",
36
+ "bin",
37
+ "CHANGELOG.md",
38
+ "SECURITY.md"
39
+ ],
40
+ "scripts": {
41
+ "test": "node --test test/*.test.mjs"
42
+ },
43
+ "bin": {
44
+ "ehven-git-release-guardrails": "bin/git-release-guardrails.mjs"
45
+ }
46
+ }
@@ -0,0 +1,26 @@
1
+ import { fail } from './errors.mjs';
2
+ import { fields, branch, branchList, objectFormat, objectId } from './validation.mjs';
3
+
4
+ /** Validate source metadata only; no provider, credentials, deployment or CI query. */
5
+ export function assertDeploymentSource(input) {
6
+ const options = fields(input, ['target', 'targets', 'sha', 'localBranch', 'status', 'ci', 'objectFormat'], 'Deployment options');
7
+ const format = objectFormat(options.objectFormat);
8
+ const target = branch(options.target, 'Deployment target');
9
+ const targets = branchList(options.targets, 'Allowed deployment targets');
10
+ const sha = objectId(options.sha, format);
11
+ if (!targets.includes(target)) fail('ERR_DEPLOYMENT_TARGET', 'Choose an explicitly allowed deployment target.');
12
+ if (options.status !== '') {
13
+ fail('ERR_DIRTY_SOURCE', 'Deployment requires clean committed source.');
14
+ }
15
+ if (typeof options.localBranch !== 'string') fail('ERR_INPUT', 'Supply the local branch, or an empty string for detached CI.');
16
+ if (options.localBranch !== '') branch(options.localBranch, 'Local branch');
17
+ let sourceBranch = options.localBranch;
18
+ if (options.ci !== undefined) {
19
+ const ci = fields(options.ci, ['branch', 'sha'], 'CI identity');
20
+ sourceBranch = branch(ci.branch, 'CI branch');
21
+ if (objectId(ci.sha, format, 'CI commit ID') !== sha) fail('ERR_CI_IDENTITY', 'CI source must match the checkout commit.');
22
+ if (options.localBranch && options.localBranch !== sourceBranch) fail('ERR_CI_IDENTITY', 'Attached local and CI branch identities must agree.');
23
+ }
24
+ if (sourceBranch !== target) fail('ERR_DEPLOYMENT_SOURCE', 'Deployment requires the selected target branch or matching detached CI identity.');
25
+ return { target, sha };
26
+ }
package/src/errors.mjs ADDED
@@ -0,0 +1,12 @@
1
+ /** A public, stable failure code. Input values are deliberately omitted. */
2
+ export class GitReleaseGuardError extends Error {
3
+ constructor(code, message, options) {
4
+ super(message, options);
5
+ this.name = 'GitReleaseGuardError';
6
+ this.code = code;
7
+ }
8
+ }
9
+
10
+ export function fail(code, message) {
11
+ throw new GitReleaseGuardError(code, message);
12
+ }
@@ -0,0 +1,55 @@
1
+ export type ObjectFormat = 'sha1' | 'sha256';
2
+ export interface ReviewedHead {
3
+ readonly repository: string;
4
+ readonly branch: string;
5
+ readonly head: string;
6
+ readonly target: string;
7
+ /** Consumer-owned record/reference identifying an actual completed review. */
8
+ readonly evidence: string;
9
+ }
10
+ export interface RetirementOptions {
11
+ readonly repository: string;
12
+ readonly permanent: readonly string[];
13
+ readonly remote: Readonly<Record<string, string>>;
14
+ readonly local: Readonly<Record<string, string>>;
15
+ readonly reviewedHeads?: readonly ReviewedHead[];
16
+ readonly temporaryPrefixes?: readonly string[];
17
+ readonly objectFormat?: ObjectFormat;
18
+ readonly isAncestor: (head: string, target: string) => boolean | Promise<boolean>;
19
+ }
20
+ export type RetirementEntry = { branch: string; sha: string } & (
21
+ { basis: 'ancestry' } | { basis: 'reviewed-head'; evidence: string }
22
+ );
23
+ export interface RetirementPlan {
24
+ repository: string;
25
+ objectFormat: ObjectFormat;
26
+ target: string;
27
+ remote: RetirementEntry[];
28
+ local: RetirementEntry[];
29
+ align: string[];
30
+ }
31
+ export interface DeploymentSourceOptions {
32
+ readonly target: string;
33
+ readonly targets: readonly string[];
34
+ readonly sha: string;
35
+ /** An empty string indicates a detached checkout. */
36
+ readonly localBranch: string;
37
+ /** Exact clean porcelain output: an empty string. */
38
+ readonly status: string;
39
+ readonly ci?: { readonly branch: string; readonly sha: string };
40
+ readonly objectFormat?: ObjectFormat;
41
+ }
42
+ export class GitReleaseGuardError extends Error {
43
+ readonly code: string;
44
+ constructor(code: string, message: string, options?: ErrorOptions);
45
+ }
46
+ export const DEFAULT_TEMPORARY_PREFIXES: readonly string[];
47
+ export function planRetirements(options: RetirementOptions): Promise<RetirementPlan>;
48
+ export function assertDeploymentSource(options: DeploymentSourceOptions): { target: string; sha: string };
49
+ export interface RemoteDestinationOptions {
50
+ readonly expectedRemoteUrls: readonly string[];
51
+ readonly fetchUrls: readonly string[];
52
+ readonly pushUrls: readonly string[];
53
+ }
54
+ export function normalizeRemoteUrl(url: string): string;
55
+ export function assertRemoteDestinations(options: RemoteDestinationOptions): { fetchUrl: string; pushUrl: string };
package/src/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ export { planRetirements, DEFAULT_TEMPORARY_PREFIXES } from './plan.mjs';
2
+ export { assertDeploymentSource } from './deployment.mjs';
3
+ export { GitReleaseGuardError } from './errors.mjs';
4
+ export { normalizeRemoteUrl, assertRemoteDestinations } from './remote.mjs';