repown 0.1.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,226 @@
1
+ // Everything this tool asks of git, in one place.
2
+ //
3
+ // Bound to a working directory rather than reading a global: every command runs
4
+ // against an explicit clone, `repown scan` walks seventeen of them in one process,
5
+ // and the pre-push hook runs inside whichever worktree git invoked it from.
6
+ //
7
+ // STRIP-ONLY TYPESCRIPT throughout this project: no parameter properties, no
8
+ // enums, no namespaces -- nothing that needs code GENERATED rather than types
9
+ // removed. That keeps every source file runnable by bare `node`, which is what
10
+ // lets the pre-push hook and the tests run without a build step standing
11
+ // between a change and its verification.
12
+ //
13
+ // `git config --get` EXITS 1 WHEN A KEY IS NOT SET. That is an answer, not a
14
+ // failure, and it is why nothing here treats a non-zero code as an error by
15
+ // itself. See the note in exec.ts.
16
+ import { run, succeeded, output, lines } from "./exec.js";
17
+ import { ok, err } from "./result.js";
18
+ export class Git {
19
+ cwd;
20
+ constructor(cwd = process.cwd()) {
21
+ this.cwd = cwd;
22
+ }
23
+ /**
24
+ * --no-replace-objects on every call: `git replace` changes what git SHOWS for
25
+ * an object, never what a push SENDS, so a replaced foreign commit read as the
26
+ * clean replacement while the original was published.
27
+ */
28
+ exec(args, input) {
29
+ const full = ['--no-replace-objects', ...args];
30
+ return input === undefined
31
+ ? run('git', full, { cwd: this.cwd })
32
+ : run('git', full, { cwd: this.cwd, input });
33
+ }
34
+ // ---- location -----------------------------------------------------------
35
+ async isRepo() {
36
+ return succeeded(await this.exec(['rev-parse', '--git-dir']));
37
+ }
38
+ /** The working tree root. Asked of git so a linked worktree resolves to itself. */
39
+ async root() {
40
+ return output(await this.exec(['rev-parse', '--show-toplevel']));
41
+ }
42
+ /**
43
+ * The directory every worktree shares -- where hooks and config actually live.
44
+ * In a linked worktree `.git` is a FILE, so joining '.git' to the root gives a
45
+ * path that cannot be written to. `--git-common-dir` is the only right answer.
46
+ */
47
+ async commonDir() {
48
+ return output(await this.exec(['rev-parse', '--git-common-dir']));
49
+ }
50
+ /**
51
+ * The directory git will actually run hooks from: `core.hooksPath` when it is
52
+ * set (husky and friends set it), otherwise the common dir's `hooks`. May be
53
+ * relative to `cwd`, like commonDir(). NOT `--path-format=absolute`: that needs
54
+ * git 2.31, and older git echoes the unknown flag back and exits 0, which
55
+ * would turn the answer into a path nobody runs hooks from.
56
+ */
57
+ async hooksDir() {
58
+ return output(await this.exec(['rev-parse', '--git-path', 'hooks']));
59
+ }
60
+ // ---- config -------------------------------------------------------------
61
+ scoped(scope, args) {
62
+ return scope ? ['config', `--${scope}`, ...args] : ['config', ...args];
63
+ }
64
+ /** The value, or null when unset. Omit `scope` to read what git would EFFECTIVELY use. */
65
+ async getConfig(key, scope) {
66
+ return output(await this.exec(this.scoped(scope, ['--get', key])));
67
+ }
68
+ async getAllConfig(key, scope) {
69
+ return lines(await this.exec(this.scoped(scope, ['--get-all', key])));
70
+ }
71
+ /**
72
+ * Every value of a multi-valued key, INCLUDING empty ones.
73
+ *
74
+ * `getAllConfig` drops blanks, which is right for a list of owners or branches
75
+ * and wrong here. An empty `credential.<url>.helper` is not noise: it is the
76
+ * list reset that discards every helper configured before it, and so it is the
77
+ * single most important line to show someone asking why their credentials
78
+ * stopped working. Filtering it out made `repown fix` preview two values while
79
+ * removing four, and hid the one the explanation is actually about.
80
+ */
81
+ async getAllConfigRaw(key, scope) {
82
+ const result = await this.exec(this.scoped(scope, ['--get-all', key]));
83
+ if (!succeeded(result))
84
+ return [];
85
+ const split = result.stdout.split(/\r?\n/);
86
+ // git terminates the last value with a newline, so a trailing empty element
87
+ // is an artefact of splitting -- unlike any earlier one, which is a value.
88
+ if (split[split.length - 1] === '')
89
+ split.pop();
90
+ return split;
91
+ }
92
+ async setConfig(key, value, scope = 'local') {
93
+ return succeeded(await this.exec(this.scoped(scope, [key, value])));
94
+ }
95
+ /** True when the key is gone afterwards -- including when it was never set. */
96
+ /** Appends one more value to a multi-valued key. */
97
+ async addConfig(key, value, scope) {
98
+ return succeeded(await this.exec(this.scoped(scope, ['--add', key, value])));
99
+ }
100
+ async unsetConfig(key, scope = 'local') {
101
+ const result = await this.exec(this.scoped(scope, ['--unset-all', key]));
102
+ return succeeded(result) || result.code === 5; // 5 = the key did not exist
103
+ }
104
+ /**
105
+ * What git would really use for `url`, honouring the credential.<pattern> rules.
106
+ *
107
+ * THIS IS THE ONLY CORRECT WAY TO READ A CREDENTIAL HELPER. An empty
108
+ * `credential.<url>.helper` value is defined by gitcredentials(7) as RESETTING
109
+ * the list, discarding every helper configured before it. Collecting entries by
110
+ * hand and taking the last -- or worse, the first -- gets the wrong answer on
111
+ * exactly the machine this tool exists to diagnose.
112
+ */
113
+ async getUrlMatch(key, url) {
114
+ return output(await this.exec(['config', '--get-urlmatch', key, url]));
115
+ }
116
+ /** Which FILE each matching key lives in, so a repair edits the scope that holds it. */
117
+ async configOrigins(pattern, scope) {
118
+ const args = this.scoped(scope, ['--show-origin', '--get-regexp', pattern]);
119
+ return lines(await this.exec(args)).flatMap(parseOriginLine);
120
+ }
121
+ // ---- history ------------------------------------------------------------
122
+ /**
123
+ * Author and committer of every commit in `range`, which is passed to git as
124
+ * separate arguments so a caller can use `<sha> --not --remotes=origin`.
125
+ */
126
+ async identitiesIn(range) {
127
+ const [log, count] = await Promise.all([
128
+ this.exec(['log', '--no-show-signature', `--format=${IDENTITY_FORMAT}`, ...range]),
129
+ this.exec(['rev-list', '--count', ...range]),
130
+ ]);
131
+ // An empty list would read as "no foreign commits": a failure must stay one.
132
+ if (!succeeded(log))
133
+ return err(log.timedOut ? 'git log timed out reading the range' : log.stderr.trim() || 'git log failed');
134
+ const commits = parseIdentities(log.stdout);
135
+ // The author writes the subject and the name. Whatever they contain, every
136
+ // commit in the range must come back parsed, or the answer is not trusted.
137
+ if (!commits.ok)
138
+ return commits;
139
+ if (!succeeded(count) || Number(count.stdout.trim()) !== commits.value.length) {
140
+ return err('could not account for every commit in the range');
141
+ }
142
+ return commits;
143
+ }
144
+ /**
145
+ * The tagger address of every annotated tag in the chain starting at `sha`
146
+ * (a tag may point at a tag). Empty when `sha` is not a tag at all. `git log`
147
+ * peels tags to their commit, so this is the only place a tagger is seen.
148
+ */
149
+ async taggersOf(sha) {
150
+ const taggers = [];
151
+ for (let object = sha, depth = 0; depth < MAX_TAG_CHAIN; depth++) {
152
+ const type = await this.exec(['cat-file', '-t', object]);
153
+ // A missing starting object is the range check's to refuse; only a broken chain is ours.
154
+ if (!succeeded(type))
155
+ return depth === 0 ? ok(taggers) : err('could not read object ' + object);
156
+ if (type.stdout.trim() !== 'tag')
157
+ return ok(taggers);
158
+ const body = await this.exec(['cat-file', 'tag', object]);
159
+ const next = /^object ([0-9a-f]+)$/m.exec(body.stdout)?.[1];
160
+ if (!succeeded(body) || !next)
161
+ return err('could not read tag ' + object);
162
+ const tagger = /^tagger [^<\n]*<([^>\n]*)>/m.exec(body.stdout)?.[1];
163
+ taggers.push(tagger ?? ''); // no tagger line: '' never matches
164
+ object = next;
165
+ }
166
+ return err('tag chain longer than ' + MAX_TAG_CHAIN + ' starting at ' + sha);
167
+ }
168
+ /** Whether this clone has the commit at all -- a remote tip it never fetched is absent. */
169
+ async hasCommit(sha) {
170
+ return succeeded(await this.exec(['cat-file', '-e', sha + '^{commit}']));
171
+ }
172
+ /**
173
+ * Author/committer addresses across every ref, with a count each.
174
+ *
175
+ * `exclude` drops commits reachable from another ref, which is how a fork gets
176
+ * a useful answer: counting every address in a mirror of someone else's
177
+ * project reports that project's contributors and says nothing about this
178
+ * clone. Excluding the mirror branch leaves the commits written HERE.
179
+ */
180
+ async emailCounts(exclude) {
181
+ const range = exclude ? ['--all', '--not', exclude] : ['--all'];
182
+ // --no-show-signature: a scanned repository's own log.showSignature + gpg.program
183
+ // would otherwise run a program of its choosing.
184
+ const result = await this.exec(['log', '--no-show-signature', ...range, '--format=%ae%n%ce']);
185
+ // An empty map would read as "no identities in history": a failure stays one.
186
+ if (!succeeded(result))
187
+ return err(result.stderr.trim() || 'git log failed');
188
+ const counts = new Map();
189
+ for (const address of lines(result)) {
190
+ counts.set(address, (counts.get(address) ?? 0) + 1);
191
+ }
192
+ return ok(counts);
193
+ }
194
+ }
195
+ /**
196
+ * `file:<path>\t<key> <value>`. The path is printed UNQUOTED and may hold
197
+ * spaces (`C:/Program Files/Git/etc/gitconfig`), so it ends at the TAB, not at
198
+ * the first space.
199
+ */
200
+ function parseOriginLine(line) {
201
+ const match = /^file:([^\t]+)\t(\S+)(?: (.*))?$/.exec(line);
202
+ if (!match)
203
+ return [];
204
+ return [{ file: match[1], key: match[2], value: match[3] ?? '' }];
205
+ }
206
+ /**
207
+ * NUL-terminated fields, subject LAST. git refuses NUL in a name or an address,
208
+ * so nothing an author writes can shift them; the subject cannot reach past its
209
+ * own terminator either. Records are a fixed IDENTITY_FIELDS long.
210
+ */
211
+ const IDENTITY_FORMAT = '%H%x00%ae%x00%ce%x00%an%x00%cn%x00%s%x00';
212
+ const IDENTITY_FIELDS = 6;
213
+ const MAX_TAG_CHAIN = 16;
214
+ const SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
215
+ function parseIdentities(stdout) {
216
+ const fields = stdout.split('\0');
217
+ const commits = [];
218
+ for (let at = 0; at + IDENTITY_FIELDS <= fields.length; at += IDENTITY_FIELDS) {
219
+ const [sha, authorEmail, committerEmail, authorName, committerName, subject] = fields.slice(at, at + IDENTITY_FIELDS).map((field, index) => index === 0 ? field.trim() : field);
220
+ if (!SHA.test(sha))
221
+ return err('unreadable commit record from git log');
222
+ commits.push({ sha: sha, subject: subject, authorName: authorName, authorEmail: authorEmail,
223
+ committerName: committerName, committerEmail: committerEmail });
224
+ }
225
+ return ok(commits);
226
+ }
@@ -0,0 +1,245 @@
1
+ // The check the pre-push hook runs.
2
+ //
3
+ // IT VERIFIES THE COMMITS BEING PUSHED, not the configuration as it stands now.
4
+ // That distinction is the whole reason this exists. A config check answers "is
5
+ // the identity right at this moment", which a commit authored in the window
6
+ // before setup -- or on a branch, or introduced by a merge, rebase, cherry-pick
7
+ // or an IDE -- passes cleanly as soon as the config is put right afterwards. The
8
+ // push is recoverable; the commit object is not. `user.email` is baked into its
9
+ // author and committer fields, and on a public repository that is permanent.
10
+ //
11
+ // The hook receives, on stdin:
12
+ //
13
+ // <local ref> <local sha> <remote ref> <remote sha>
14
+ //
15
+ // which is exactly the set of commits about to be published. The previous design
16
+ // read that and threw it away.
17
+ import { parseGitUrl } from "../url.js";
18
+ import { providerFor } from "../hosts/index.js";
19
+ import { readIdentity, legacyAccountKey } from "../identity.js";
20
+ /** The null object id: 40 zeros, or 64 in a SHA-256 repository. */
21
+ const isZero = (sha) => /^0+$/.test(sha);
22
+ const MIRROR_KEY = 'repown.mirrorBranch';
23
+ const ALLOW_OWNER_KEY = 'repown.allowOwner';
24
+ const ALLOW_TAGGER_KEY = 'repown.allowTagger';
25
+ /** Variables that override the identity the guard just validated, or bypass the check gh performs. */
26
+ const HOSTILE = [
27
+ ['GIT_AUTHOR_EMAIL', 'silently overrides the author address of every commit made'],
28
+ ['GIT_COMMITTER_EMAIL', 'silently overrides the committer address of every commit made'],
29
+ ['GH_TOKEN', 'makes gh serve this token whatever account git asked for, skipping its own username check'],
30
+ ['GITHUB_TOKEN', 'makes gh serve this token whatever account git asked for, skipping its own username check'],
31
+ ];
32
+ export function parsePushRefs(stdin) {
33
+ return stdin.split(/\r?\n/).flatMap((raw) => {
34
+ const parts = raw.trim().split(/\s+/);
35
+ if (parts.length < 4)
36
+ return [];
37
+ return [{ localRef: parts[0], localSha: parts[1], remoteRef: parts[2], remoteSha: parts[3] }];
38
+ });
39
+ }
40
+ export async function check(input) {
41
+ const hostile = checkEnvironment();
42
+ if (hostile.length > 0)
43
+ return hostile;
44
+ const url = parseGitUrl(input.url);
45
+ const provider = providerFor(url);
46
+ const credentialKey = url ? provider.credentialKeys(url)[0] ?? null : null;
47
+ const identity = await readIdentity(input.git, credentialKey);
48
+ if (!identity.email) {
49
+ return [{
50
+ reason: 'This clone sets no identity of its own, so the guard cannot tell ' +
51
+ 'your commits from anyone else’s.',
52
+ detail: ['fix: repown use <account>'],
53
+ }];
54
+ }
55
+ const owner = url ? provider.ownerOf(url) : null;
56
+ const legacy = !identity.owner && url ? await input.git.getConfig(legacyAccountKey(url), 'local') : null;
57
+ const allowed = await allowedOwners(input.git, identity.owner ?? identity.account ?? legacy);
58
+ const destination = checkDestination({ url, owner, allowed }, input.onNote);
59
+ return [...destination, ...await checkCommits(input, identity.email)];
60
+ }
61
+ function checkEnvironment() {
62
+ return HOSTILE.flatMap(([name, why]) => {
63
+ if (!process.env[name])
64
+ return [];
65
+ return [{
66
+ reason: name + ' is set, and it ' + why + '.',
67
+ detail: ['unset it and push again, or push with --no-verify if you meant it'],
68
+ }];
69
+ });
70
+ }
71
+ /**
72
+ * Owners this clone may legitimately push to: the pinned account, plus anything
73
+ * listed in repown.allowOwner.
74
+ *
75
+ * THE LIST EXISTS BECAUSE ORGANISATIONS ARE NOT ACCOUNTS. A repository owned by
76
+ * an organisation you belong to has an owner that is not, and never will be,
77
+ * your account name -- so comparing the two refuses every push to every org
78
+ * repository, which is most working repositories in most jobs.
79
+ *
80
+ * Organisation membership could be resolved from the host API instead. It is
81
+ * not, deliberately: that would put a network call and an auth dependency in the
82
+ * pre-push path, where a rate limit or an offline laptop would turn into a
83
+ * failed push. An explicit local list is offline, instant, and readable.
84
+ */
85
+ export async function allowedOwners(git, account) {
86
+ // LOCAL only: "per repository, explicitly". A global entry would widen every clone.
87
+ const extra = await git.getAllConfig(ALLOW_OWNER_KEY, 'local');
88
+ return [...(account ? [account] : []), ...extra].map((owner) => owner.toLowerCase());
89
+ }
90
+ function checkDestination({ url, owner, allowed }, onNote) {
91
+ const skipped = !url ? 'the remote is not a URL (a local path?)'
92
+ : !owner ? 'no owner can be read from ' + url.host + ' URLs'
93
+ : allowed.length === 0 ? 'no account is recorded for this clone -- run: repown use <account>'
94
+ : null;
95
+ if (skipped) {
96
+ onNote?.('destination not checked: ' + skipped);
97
+ return [];
98
+ }
99
+ if (allowed.includes(owner.toLowerCase()))
100
+ return [];
101
+ return [{
102
+ reason: 'This push goes to "' + printable(owner) + '", which this clone is not pinned to.',
103
+ detail: [
104
+ 'destination: ' + printable(redacted(url.raw)),
105
+ 'allowed here: ' + allowed.join(', '),
106
+ 'if that owner is legitimate -- an organisation you belong to, say:',
107
+ ' git config --local --add ' + ALLOW_OWNER_KEY + ' ' + shellWord(printable(owner)),
108
+ ],
109
+ }];
110
+ }
111
+ async function checkCommits(input, expected) {
112
+ const mirror = await input.git.getConfig(MIRROR_KEY, 'local');
113
+ const refusals = [];
114
+ for (const ref of parsePushRefs(input.stdin)) {
115
+ if (isZero(ref.localSha))
116
+ continue; // a deletion publishes nothing
117
+ const upstreamShaped = ref.remoteRef === 'refs/heads/' + mirror || ref.remoteRef.startsWith('refs/tags/');
118
+ const exclude = mirror && upstreamShaped
119
+ ? ['--not', '--remotes'] // fork: on any remote, upstream included
120
+ : ['--not', '--remotes=' + input.remote];
121
+ refusals.push(...await checkTaggers(input.git, ref, expected));
122
+ refusals.push(...await checkRange(input, { ref, exclude }, expected));
123
+ }
124
+ return refusals;
125
+ }
126
+ /**
127
+ * An annotated tag's tagger is published with it, as permanently as an author.
128
+ * Whether a tag OBJECT is already public cannot be told offline -- its commit
129
+ * being on a remote proves nothing, since a tag made here under the wrong
130
+ * identity can sit on an upstream commit too. So a fork pushing upstream's tags
131
+ * names upstream's taggers explicitly, repo-locally: repown.allowTagger.
132
+ */
133
+ async function checkTaggers(git, ref, expected) {
134
+ const taggers = await git.taggersOf(ref.localSha);
135
+ if (!taggers.ok) {
136
+ return [{
137
+ reason: 'The guard could not read the tag bound for ' + ref.remoteRef + '. Refusing rather than passing unchecked.',
138
+ detail: ['git said: ' + taggers.error],
139
+ }];
140
+ }
141
+ const allowed = [expected, ...await git.getAllConfig(ALLOW_TAGGER_KEY, 'local')];
142
+ const foreign = taggers.value.filter((tagger) => !allowed.some((address) => matches(tagger, address)));
143
+ if (foreign.length === 0)
144
+ return [];
145
+ return [{
146
+ reason: 'The tag bound for ' + ref.remoteRef + ' was not tagged as ' + expected + '.',
147
+ detail: [...foreign.map((tagger) => ' tagger ' + (printable(tagger) || '(none)')), '',
148
+ 'The tagger address becomes permanent once pushed.',
149
+ 'an upstream tag on a fork? allow its tagger: git config --local --add ' + ALLOW_TAGGER_KEY + ' <address>'],
150
+ }];
151
+ }
152
+ /**
153
+ * The mirror exemption is OPT-IN, per repository, via repown.mirrorBranch. A branch
154
+ * that only ever fast-forwards to upstream commits nobody here authored would
155
+ * otherwise be refused for carrying their addresses -- but defaulting to an
156
+ * exemption is how the previous design silently exempted every feature branch, so
157
+ * an unset key means no exemption at all.
158
+ *
159
+ * EVEN THEN THE MIRROR IS CHECKED, just against a wider exclusion: a commit on
160
+ * ANY remote-tracking ref (upstream's included) is public already and does not
161
+ * count, but one on no remote was made here. Skipping the ref outright let
162
+ * `git push origin feature:master` publish anything at all.
163
+ *
164
+ * BOTH RANGES EXCLUDE WHAT THE REMOTE ALREADY HAS. The question this guard asks
165
+ * is which addresses THIS push makes permanent -- and a commit already on a
166
+ * remote-tracking ref made its own permanent when it was first published.
167
+ * Pushing it onto a second branch publishes nothing new. Without the exclusion
168
+ * a fork that merges upstream into its release branch is refused for every
169
+ * upstream commit in the merge, one step after pushing those very commits to
170
+ * its own mirror branch: a false positive on its most routine operation.
171
+ *
172
+ * The cost is bounded, and worth naming rather than hiding. A STALE
173
+ * remote-tracking ref -- a branch deleted or force-pushed on the server -- can
174
+ * exclude a commit that is no longer really published. `git fetch --prune`
175
+ * corrects it, and the new-branch path has always carried the same exposure.
176
+ * The mirror's wider exclusion adds one more: a commit that only a PRIVATE
177
+ * remote carries (a work remote, say) is not public, yet does not count there.
178
+ */
179
+ async function checkRange(input, { ref, exclude }, expected) {
180
+ const range = await rangeFor(input.git, ref, exclude);
181
+ const commits = await input.git.identitiesIn(range);
182
+ if (!commits.ok) {
183
+ return [{
184
+ reason: 'The guard could not read the commits bound for ' + ref.remoteRef +
185
+ ', so it cannot tell whether they are yours. Refusing rather than passing unchecked.',
186
+ detail: ['reason: ' + commits.error, unreadableHint(commits.error)],
187
+ }];
188
+ }
189
+ const foreign = commits.value.filter((commit) => !matches(commit.authorEmail, expected) || !matches(commit.committerEmail, expected));
190
+ if (foreign.length === 0)
191
+ return [];
192
+ const refusal = foreignRefusal(ref, foreign, expected);
193
+ // The remote's tip was not here, so every commit it lacks locally was checked;
194
+ // some of those may well be on the remote already.
195
+ const widened = !isZero(ref.remoteSha) && range[0] === ref.localSha;
196
+ return [widened ? { ...refusal, detail: [...refusal.detail, 'if they are already on the remote: git fetch, then push again'] } : refusal];
197
+ }
198
+ /**
199
+ * `remoteSha..localSha` needs remoteSha to exist HERE. A tip someone else pushed,
200
+ * never fetched, does not -- a force-push over it is the routine case -- so the
201
+ * push is checked as if the branch were new: everything the remote's
202
+ * tracking refs do not already carry.
203
+ */
204
+ async function rangeFor(git, ref, exclude) {
205
+ const known = !isZero(ref.remoteSha) && await git.hasCommit(ref.remoteSha);
206
+ return known ? [ref.remoteSha + '..' + ref.localSha, ...exclude] : [ref.localSha, ...exclude];
207
+ }
208
+ /** Each commit shows the address that is WRONG -- the committer's, when the author is right. */
209
+ function foreignRefusal(ref, foreign, expected) {
210
+ const shown = foreign.slice(0, 10).map((commit) => {
211
+ const wrong = [...new Set([commit.authorEmail, commit.committerEmail])]
212
+ .filter((address) => !matches(address, expected));
213
+ return ' ' + commit.sha.slice(0, 9) + ' ' + printable(wrong.join(', ')) + ' ' + printable(commit.subject);
214
+ });
215
+ const more = foreign.length > shown.length ? [' ... and ' + (foreign.length - shown.length) + ' more'] : [];
216
+ return {
217
+ reason: foreign.length + ' commit(s) bound for ' + ref.remoteRef +
218
+ ' were not authored as ' + expected + ', or were committed by someone else.',
219
+ detail: [...shown, ...more, '', 'These addresses become permanent once pushed.'],
220
+ };
221
+ }
222
+ /** A fetch cures a missing object; it does nothing for history git printed in a shape repown cannot parse. */
223
+ function unreadableHint(error) {
224
+ return /account for every commit|unreadable commit record/.test(error)
225
+ ? 'the history could not be parsed reliably; inspect it yourself before any --no-verify'
226
+ : 'try: git fetch, then push again';
227
+ }
228
+ function matches(actual, expected) {
229
+ return actual.toLowerCase() === expected.toLowerCase();
230
+ }
231
+ /** Text a commit's author chose: control characters could rewrite the terminal around the refusal. */
232
+ function printable(text) {
233
+ return text.replace(/[\x00-\x1f\x7f-\x9f]/g, '?');
234
+ }
235
+ /**
236
+ * A URL as it may be shown: the WHOLE userinfo is replaced. A token is often the
237
+ * username itself (`https://ghp_...@github.com/`), not only a password.
238
+ */
239
+ function redacted(raw) {
240
+ return raw.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i, '$1***@');
241
+ }
242
+ /** An owner comes from the URL, so a suggested command must quote it for the shell. */
243
+ export function shellWord(value) {
244
+ return /^[\w.@-]+$/.test(value) ? value : "'" + value.replace(/'/g, "'\\''") + "'";
245
+ }
@@ -0,0 +1,184 @@
1
+ // The pre-push hook: writing it, recognising it, removing it.
2
+ //
3
+ // WHY THE HOOK CALLS AN INSTALLED CLI RATHER THAN A COPY OF ITSELF. A copy of
4
+ // the checker inside .git/ adds two states -- `stale` (a copy is missing, so the
5
+ // check cannot load) and `drifted` (the copy is older than the tool). Calling the
6
+ // installed entry point removes both: there is only ever one implementation, and
7
+ // it is current by construction (ADR-003).
8
+ //
9
+ // The absolute path is baked in at install time AND a PATH lookup is kept as a
10
+ // fallback, so neither a PATH change nor a reinstall elsewhere can quietly
11
+ // disable the guard. If both fail it REFUSES. A hook that cannot run its check is
12
+ // not a check, and exiting 0 there is how the previous design let five of six
13
+ // branches push unguarded.
14
+ //
15
+ // Written LF-only, always: `sh` rejects a CRLF script with "bad interpreter", and
16
+ // on Windows the line endings of anything templated here depend on how the file
17
+ // was checked out.
18
+ import { readFile, writeFile, mkdir, rm, chmod } from 'node:fs/promises';
19
+ import { existsSync, realpathSync } from 'node:fs';
20
+ import { join, dirname, resolve } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { ok, err } from "../result.js";
23
+ export const MARKER = 'repown-identity-guard';
24
+ /**
25
+ * A marker counts only where this tool writes it: line 2 (right after the shebang)
26
+ * starts with `# <marker>:`. A hook that merely MENTIONS it, or that has this
27
+ * tool's body pasted below lines of its own, is someone else's -- and a hook classified
28
+ * as ours gets overwritten by `guard on` and deleted by `guard off`.
29
+ */
30
+ function classify(body) {
31
+ const header = body.split('\n')[1] ?? '';
32
+ return header.startsWith('# ' + MARKER + ':') ? 'on' : 'foreign';
33
+ }
34
+ /** This CLI's own entry point, as the hook will invoke it. */
35
+ export function entryPoint() {
36
+ const here = fileURLToPath(import.meta.url);
37
+ return join(dirname(here), '..', '..', 'cli' + here.slice(here.lastIndexOf('.')));
38
+ }
39
+ /** git may answer relative to the directory it ran in; both are made absolute against it. */
40
+ async function hookDirs(git) {
41
+ const [common, hooks] = await Promise.all([git.commonDir(), git.hooksDir()]);
42
+ if (!common || !hooks)
43
+ return null;
44
+ return { own: join(resolve(git.cwd, common), 'hooks'), effective: resolve(git.cwd, hooks) };
45
+ }
46
+ /** The pre-push hook git will actually RUN -- through core.hooksPath if that is set. */
47
+ export async function hookPath(git) {
48
+ return (await hookLocation(git))?.path ?? null;
49
+ }
50
+ export async function hookLocation(git) {
51
+ const dirs = await hookDirs(git);
52
+ return dirs ? { path: join(dirs.effective, 'pre-push'), redirected: isRedirected(dirs) } : null;
53
+ }
54
+ /**
55
+ * core.hooksPath pointing anywhere but this clone's own hooks directory: a
56
+ * directory another tool manages, or one shared by every repository on the
57
+ * machine. repown never writes or deletes there -- a hook in a shared directory
58
+ * would run, and refuse, in clones that were never pinned.
59
+ */
60
+ function isRedirected(dirs) {
61
+ return !samePath(dirs.own, dirs.effective);
62
+ }
63
+ /** Compared as real paths, so a symlinked .git/hooks and Windows 8.3 names match. */
64
+ function samePath(a, b) {
65
+ const real = (path) => {
66
+ try {
67
+ return realpathSync.native(path);
68
+ }
69
+ catch {
70
+ return resolve(path);
71
+ }
72
+ };
73
+ const [x, y] = [real(a), real(b)];
74
+ const folded = process.platform === 'win32' || process.platform === 'darwin';
75
+ return folded ? x.toLowerCase() === y.toLowerCase() : x === y;
76
+ }
77
+ function redirectMessage(dirs) {
78
+ return 'core.hooksPath makes git run hooks from ' + dirs.effective + ', a directory repown ' +
79
+ 'does not own -- leaving it alone. Unset core.hooksPath, or have that tool\'s ' +
80
+ 'pre-push hook run: repown guard check --remote="$1" --url="$2"';
81
+ }
82
+ export async function guardState(git) {
83
+ const path = await hookPath(git);
84
+ return path ? stateOf(path) : 'off';
85
+ }
86
+ /**
87
+ * The PATH fallback trusts a `repown` only if it SAYS it is repown. Without this, any
88
+ * program of that name that exits 0 passes every push unchecked.
89
+ */
90
+ const PATH_FALLBACK_CHECK = [
91
+ 'repown_on_path() {',
92
+ ' command -v repown >/dev/null 2>&1 || return 1',
93
+ ' case "$(repown --version 2>/dev/null)" in "repown "*) return 0 ;; *) return 1 ;; esac',
94
+ '}',
95
+ '',
96
+ ];
97
+ export function hookBody(entry, nodePath) {
98
+ const q = (value) => "'" + value.replace(/'/g, "'\\''") + "'";
99
+ return [
100
+ '#!/bin/sh',
101
+ '# ' + MARKER + ': installed by `repown guard on`, removed by `repown guard off`.',
102
+ '# Bypass one push (recorded in the reflog either way): git push --no-verify',
103
+ '#',
104
+ '# stdin -- the <local ref> <local sha> <remote ref> <remote sha> lines -- is',
105
+ '# inherited by the child, and is what says WHICH COMMITS are about to be',
106
+ '# published. That is the thing being checked, not the config as it stands now.',
107
+ '',
108
+ 'repown_entry=' + q(entry),
109
+ 'repown_node=' + q(nodePath),
110
+ '',
111
+ ...PATH_FALLBACK_CHECK,
112
+ 'if [ -f "$repown_entry" ] && [ -x "$repown_node" ]; then',
113
+ ' "$repown_node" "$repown_entry" guard check --remote="$1" --url="$2"',
114
+ 'elif repown_on_path; then',
115
+ ' repown guard check --remote="$1" --url="$2"',
116
+ 'else',
117
+ ' echo "" >&2',
118
+ ' echo "repown: the identity guard is installed but repown cannot be found," >&2',
119
+ ' echo "so this push CANNOT be checked. Refusing rather than passing silently." >&2',
120
+ ' echo " expected: $repown_entry" >&2',
121
+ ' echo " fix: reinstall repown, then run: repown guard on" >&2',
122
+ ' echo " or, to stop using repown in this clone, delete $0" >&2',
123
+ ' echo " or, for this one push only: git push --no-verify" >&2',
124
+ ' exit 1',
125
+ 'fi',
126
+ '',
127
+ 'status=$?',
128
+ 'if [ $status -ne 0 ]; then',
129
+ ' echo "" >&2',
130
+ ' echo "Push stopped by the repown identity guard (above)." >&2',
131
+ ' echo "Override this one push with: git push --no-verify" >&2',
132
+ 'fi',
133
+ 'exit $status',
134
+ '',
135
+ ].join('\n');
136
+ }
137
+ const NO_GIT_DIR = 'could not locate the git directory for this repository';
138
+ async function stateOf(path) {
139
+ if (!existsSync(path))
140
+ return 'off';
141
+ return classify(await readFile(path, 'utf8').catch(() => ''));
142
+ }
143
+ export async function installGuard(git) {
144
+ const dirs = await hookDirs(git);
145
+ if (!dirs)
146
+ return err(NO_GIT_DIR);
147
+ if (isRedirected(dirs))
148
+ return err(redirectMessage(dirs));
149
+ const path = join(dirs.effective, 'pre-push');
150
+ if (await stateOf(path) === 'foreign') {
151
+ return err('a pre-push hook this tool did not write already exists at ' + path + ' -- leaving it alone');
152
+ }
153
+ await mkdir(dirname(path), { recursive: true });
154
+ await writeFile(path, hookBody(entryPoint(), process.execPath), 'utf8');
155
+ await chmod(path, 0o755).catch(() => { });
156
+ return ok({ path });
157
+ }
158
+ /**
159
+ * Deletes only a hook repown can prove it wrote, and only from this clone's own
160
+ * hooks directory. With core.hooksPath set, a repown hook left in .git/hooks is
161
+ * still removed -- it would come back to life the moment the key is unset.
162
+ */
163
+ export async function uninstallGuard(git) {
164
+ const dirs = await hookDirs(git);
165
+ if (!dirs)
166
+ return err(NO_GIT_DIR);
167
+ const removed = await removeIfOurs(join(dirs.own, 'pre-push'));
168
+ if (!removed.ok || !isRedirected(dirs))
169
+ return removed;
170
+ // A repown hook in the redirected directory is ours to report but not to delete,
171
+ // and it still runs -- so "off" would be false even after removing the leftover.
172
+ // Anything else there is simply someone else's, and there is nothing to turn off.
173
+ return await stateOf(join(dirs.effective, 'pre-push')) === 'on' ? err(redirectMessage(dirs)) : removed;
174
+ }
175
+ async function removeIfOurs(path) {
176
+ const state = await stateOf(path);
177
+ if (state === 'off')
178
+ return ok(false);
179
+ if (state === 'foreign') {
180
+ return err('the pre-push hook at ' + path + ' was not written by this tool -- leaving it alone');
181
+ }
182
+ await rm(path, { force: true });
183
+ return ok(true);
184
+ }