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,164 @@
1
+ // Pin this clone to one account.
2
+ //
3
+ // A clone belongs to ONE account, permanently. This writes repo-local git config
4
+ // and is not run again:
5
+ //
6
+ // user.name
7
+ // user.email
8
+ // user.useConfigOnly git refuses to invent an identity from the hostname
9
+ // repown.account whose clone this is -- the guard's destination check
10
+ // credential.<host>.username which stored credential serves this remote (GitHub over https)
11
+ //
12
+ // NOTHING IS WRITTEN TO THE REPOSITORY. All of it lands in .git/config, which git
13
+ // never tracks -- which is what keeps a name or address out of a public repo, and
14
+ // also why this is per clone: a second machine, or a re-clone, runs it again.
15
+ //
16
+ // You do not switch this afterwards, and you do not need to. Changing which
17
+ // account the GitHub CLI acts as is `gh auth switch`, which after `repown fix` has
18
+ // no effect on git at all -- `--gh` does both at once for when you want them to
19
+ // agree.
20
+ import { inspectRepo, inspectAuth } from "../core/inspect.js";
21
+ import { pinIdentity } from "../core/identity.js";
22
+ import { lookupAccount, saveAccount } from "../core/registry.js";
23
+ import { ghSwitch } from "../core/credential/gh.js";
24
+ import { allowedOwners, shellWord } from "../core/guard/check.js";
25
+ import { ask, interactive } from "../ui/prompt.js";
26
+ import { flagString, flagBool, gitFor } from "../ui/args.js";
27
+ import * as out from "../ui/format.js";
28
+ export default {
29
+ summary: 'pin this clone to an account (repown use <account>)',
30
+ positionals: { min: 1, max: 1, label: '<account>' },
31
+ options: [
32
+ { name: 'gh', kind: 'boolean', help: "also switch the GitHub CLI's active account to match" },
33
+ { name: 'name', kind: 'string', help: 'the commit author name (given with --email, skips the registry and the prompt)' },
34
+ { name: 'email', kind: 'string', help: 'the commit author email (given with --name, skips the registry and the prompt)' },
35
+ ],
36
+ examples: ['repown use octocat', 'repown use octocat --gh'],
37
+ async run(args) {
38
+ const account = args.positional[0];
39
+ const git = gitFor(args);
40
+ const repo = await inspectRepo(git);
41
+ if (!repo.isRepo) {
42
+ out.fail('use', 'Not a git repository: ' + git.cwd);
43
+ return 1;
44
+ }
45
+ const values = await resolveAccount(account, repo, args);
46
+ if (!values)
47
+ return 1;
48
+ if (!reportPinned(await pinIdentity(git, { ...values, account }, repo.credentialKeys)))
49
+ return 1;
50
+ out.pass('identity', values.name + ' <' + values.email + '> push-as:' + account);
51
+ if (flagBool(args, 'gh'))
52
+ await switchCli(account);
53
+ await reportConcerns(account, repo);
54
+ return 0;
55
+ },
56
+ };
57
+ /** False, naming every key, when any write failed: nothing reports success it did not have. */
58
+ function reportPinned(outcomes) {
59
+ const failed = outcomes.filter((outcome) => !outcome.written);
60
+ if (failed.length === 0)
61
+ return true;
62
+ out.fail('use', 'could not write ' + failed.length + ' of ' + outcomes.length + ' keys.');
63
+ for (const outcome of failed)
64
+ out.detail(outcome.key);
65
+ out.detail('this clone is NOT pinned -- nothing here reports success it did not have.');
66
+ return false;
67
+ }
68
+ /**
69
+ * Flags first, then the registry, then ask -- with the host only suggesting the
70
+ * prompt's defaults. The registry is why this is usually instant.
71
+ */
72
+ async function resolveAccount(account, repo, args) {
73
+ const flagged = { name: flagString(args, 'name'), email: flagString(args, 'email') };
74
+ if (flagged.name && flagged.email)
75
+ return { name: flagged.name, email: flagged.email };
76
+ const lookup = await lookupAccount(account);
77
+ if (!lookup.ok) {
78
+ out.fail('use', lookup.error);
79
+ return null;
80
+ }
81
+ const recorded = lookup.value;
82
+ const name = flagged.name ?? recorded?.name;
83
+ const email = flagged.email ?? recorded?.email;
84
+ if (name && email)
85
+ return { name, email };
86
+ return askAndRecord(account, repo, { name, email });
87
+ }
88
+ async function askAndRecord(account, repo, known) {
89
+ // Checked BEFORE asking the host for a suggestion: with no terminal there is
90
+ // nobody to suggest to, and the lookup is a network call.
91
+ if (!interactive()) {
92
+ out.fail('use', 'no record of "' + account + '" and no terminal to ask.');
93
+ out.detail('record it once: repown accounts add ' + account + ' --name "..." --email "..."');
94
+ return null;
95
+ }
96
+ const suggested = (await repo.provider.resolveProfile?.(account)) ?? {};
97
+ out.line();
98
+ out.line(' No record of "' + account + '" yet. Asking once, then never again.');
99
+ const entry = await askProfile({
100
+ name: known.name ?? suggested.name ?? account, email: known.email ?? suggested.email,
101
+ }, repo.provider.id);
102
+ if (!entry)
103
+ return null;
104
+ const saved = await saveAccount(account, entry);
105
+ if (!saved.ok)
106
+ out.warn('accounts', 'pinned, but not recorded: ' + saved.error);
107
+ out.line();
108
+ return entry;
109
+ }
110
+ async function askProfile(defaults, host) {
111
+ const name = await ask('Commit name', defaults.name);
112
+ if (!name.ok) {
113
+ out.fail('use', name.error);
114
+ return null;
115
+ }
116
+ const email = await ask('Commit email', defaults.email);
117
+ if (!email.ok) {
118
+ out.fail('use', email.error);
119
+ return null;
120
+ }
121
+ return { name: name.value, email: email.value, host };
122
+ }
123
+ async function switchCli(account) {
124
+ const switched = await ghSwitch(account);
125
+ if (switched.ok)
126
+ out.pass('gh', 'active account switched to ' + account);
127
+ else
128
+ out.warn('gh', 'could not switch: ' + switched.error);
129
+ }
130
+ /** Everything that is now true but not yet right. Warnings, never refusals. */
131
+ async function reportConcerns(account, repo) {
132
+ if (repo.credentialKeys.length === 0 && repo.url) {
133
+ out.warn('host', repo.provider.label + ' credentials are not pinned by repown.');
134
+ out.detail('commits are pinned and the guard still runs; only credential');
135
+ out.detail('selection is left to whatever already serves this host.');
136
+ }
137
+ await ownerConcern(account, repo);
138
+ await credentialConcern(account, repo);
139
+ if (repo.guard === 'off' && !repo.hook?.redirected) {
140
+ out.line();
141
+ out.line(' Next: repown guard on (check every push before it leaves)');
142
+ }
143
+ }
144
+ async function ownerConcern(account, repo) {
145
+ if (!repo.owner || repo.owner.toLowerCase() === account.toLowerCase())
146
+ return;
147
+ if ((await allowedOwners(repo.git, account)).includes(repo.owner.toLowerCase()))
148
+ return;
149
+ out.warn('origin', 'origin belongs to "' + repo.owner + '", not "' + account + '".');
150
+ out.detail('normal for an organisation repository. To stop the guard refusing it:');
151
+ out.detail(' git config --local --add repown.allowOwner ' + shellWord(repo.owner));
152
+ }
153
+ async function credentialConcern(account, repo) {
154
+ const auth = await inspectAuth(repo.git, repo.originUrl ?? undefined);
155
+ if (auth.ghIsHelper) {
156
+ out.warn('helper', 'gh is still the git credential helper, so this pin is not honoured.');
157
+ out.detail('fix: repown fix');
158
+ }
159
+ else if (auth.gcmPresent && auth.stored.ok && !auth.stored.value.includes(account)) {
160
+ out.line();
161
+ out.line(' No stored credential for "' + account + '" yet -- the first push signs in');
162
+ out.line(' once, then never again. Verify it afterwards: repown doctor');
163
+ }
164
+ }
@@ -0,0 +1,83 @@
1
+ // Finding Git Credential Manager, and asking it which accounts it holds.
2
+ //
3
+ // RESOLVED BY LOCATION, NOT BY BARE NAME, AND THAT IS LOAD-BEARING.
4
+ //
5
+ // On Windows GCM ships INSIDE Git's own directory -- Git Bash puts that on PATH
6
+ // and nothing else does. Verified again on this machine today:
7
+ // `git-credential-manager` does not resolve on the PowerShell or cmd PATH, while
8
+ // GCM is installed and is holding credentials for two accounts.
9
+ //
10
+ // A tool that decides "GCM is not installed" from a PATH lookup therefore refuses
11
+ // to run its own repair on exactly the machine that needs it. That false negative
12
+ // cost a debugging session in the implementation this replaces; it is ported
13
+ // deliberately rather than rediscovered.
14
+ import { join, dirname } from 'node:path';
15
+ import { existsSync } from 'node:fs';
16
+ import { run, succeeded, lines, notInstalled } from "../exec.js";
17
+ import { ok, err } from "../result.js";
18
+ const NAMES = ['git-credential-manager', 'git-credential-manager-core'];
19
+ /** Directories that hold GCM but are not necessarily on PATH. */
20
+ async function searchDirectories() {
21
+ const directories = [];
22
+ // Git for Windows bundles GCM as a sibling of git's own exec-path:
23
+ // <root>/mingw64/libexec/git-core -> <root>/mingw64/bin
24
+ const execPath = await run('git', ['--exec-path']);
25
+ if (succeeded(execPath)) {
26
+ const mingw = dirname(dirname(execPath.stdout.trim()));
27
+ if (mingw)
28
+ directories.push(join(mingw, 'bin'));
29
+ }
30
+ // Where the standalone GCM installer puts it.
31
+ const localAppData = process.env['LOCALAPPDATA'];
32
+ if (localAppData) {
33
+ directories.push(join(localAppData, 'Programs', 'Git Credential Manager'));
34
+ }
35
+ return directories;
36
+ }
37
+ /**
38
+ * Whether a credential.helper value is GCM. Git for Windows writes `manager`
39
+ * (once `manager-core`); the macOS and Linux installers write the executable's
40
+ * path. Matched on the last path component, so a path form is not reported as
41
+ * "a helper repown has no opinion about".
42
+ */
43
+ export function isGcm(helper) {
44
+ if (helper === null)
45
+ return false;
46
+ const base = helper.trim().split(/[\\/]/).pop() ?? '';
47
+ return /^(git-credential-)?manager(-core)?(\.exe)?$/i.test(base);
48
+ }
49
+ /** The GCM executable, or null. Checks PATH first, then the known locations. */
50
+ export async function findGcm() {
51
+ for (const name of NAMES) {
52
+ const probe = await run(name, ['--version']);
53
+ if (!notInstalled(probe))
54
+ return name;
55
+ }
56
+ const suffixes = process.platform === 'win32' ? ['.exe'] : [''];
57
+ for (const directory of await searchDirectories()) {
58
+ for (const name of NAMES) {
59
+ for (const suffix of suffixes) {
60
+ const candidate = join(directory, name + suffix);
61
+ if (existsSync(candidate))
62
+ return candidate;
63
+ }
64
+ }
65
+ }
66
+ return null;
67
+ }
68
+ /**
69
+ * The accounts GCM stores for `namespace` ('github', 'azure-repos', ...).
70
+ *
71
+ * An error result means GCM could not be ASKED, which is not the same as it
72
+ * holding nothing -- callers must keep the two apart or a failed lookup reads as
73
+ * a clean machine.
74
+ */
75
+ export async function listAccounts(gcmPath, namespace) {
76
+ if (!gcmPath)
77
+ return err('Git Credential Manager is not installed');
78
+ const result = await run(gcmPath, [namespace, 'list']);
79
+ if (!succeeded(result)) {
80
+ return err(`\`${namespace} list\` failed: ${result.stderr.trim() || `exit ${result.code}`}`);
81
+ }
82
+ return ok(lines(result));
83
+ }
@@ -0,0 +1,78 @@
1
+ // The GitHub CLI, asked only about ITSELF.
2
+ //
3
+ // After `repown fix` gh has nothing to do with git authentication. It remains the
4
+ // account store and the thing `gh pr create` acts as, and that is worth
5
+ // reporting -- a pull request opened from the wrong account on a public repo is
6
+ // as permanent as a commit.
7
+ //
8
+ // NOT `gh api user`. That spent an API round trip to learn one login and, the
9
+ // reason it had to go, returned nothing on failure. Callers guarded their
10
+ // warnings on the value being truthy, so an offline machine or an expired token
11
+ // made those warnings SILENTLY VANISH and the output looked clean rather than
12
+ // uncertain. `gh auth status --json hosts` reports every account and the active
13
+ // one in a single local call, and exits 0 even when one account has a token
14
+ // problem -- so one bad account no longer erases the whole picture.
15
+ //
16
+ // "Could not be queried" is a THIRD STATE, distinct both from "gh is not
17
+ // installed" and from "gh is active as nobody". Collapsing it into either is the
18
+ // bug this shape exists to prevent.
19
+ import { run, succeeded, notInstalled, output } from "../exec.js";
20
+ import { ok, err } from "../result.js";
21
+ /**
22
+ * A credential-helper value that `gh auth setup-git` wrote -- `!gh auth
23
+ * git-credential`, or with gh's path, quoted on Windows -- and nothing more. A
24
+ * composite (`... | manager`) or another CLI's helper (`glab auth git-credential`)
25
+ * is not gh's, and `repown fix` must not remove it.
26
+ */
27
+ export function isGh(helper) {
28
+ return helper !== null && /^!(?:.*[\\/'\s])?gh(?:\.exe)?'?\s+auth\s+git-credential\s*$/.test(helper.trim());
29
+ }
30
+ export async function ghInstalled() {
31
+ return !notInstalled(await run('gh', ['--version']));
32
+ }
33
+ export async function ghState(host = 'github.com') {
34
+ const result = await run('gh', ['auth', 'status', '--json', 'hosts']);
35
+ if (notInstalled(result))
36
+ return err('gh is not installed');
37
+ if (!succeeded(result))
38
+ return err('gh auth status failed');
39
+ const parsed = parseHosts(result.stdout, host);
40
+ if (!parsed)
41
+ return err('gh auth status returned nothing usable');
42
+ return ok(parsed);
43
+ }
44
+ function parseHosts(raw, host) {
45
+ let hosts;
46
+ try {
47
+ hosts = JSON.parse(raw).hosts ?? {};
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ const entries = hosts[host];
53
+ if (!Array.isArray(entries))
54
+ return null;
55
+ const accounts = entries.flatMap(toAccount);
56
+ const active = accounts.find((account) => account.active)?.login ?? null;
57
+ return { accounts, active };
58
+ }
59
+ function toAccount(raw) {
60
+ const entry = raw;
61
+ if (typeof entry?.login !== 'string' || !entry.login)
62
+ return [];
63
+ return [{ login: entry.login, active: entry.active === true }];
64
+ }
65
+ /** A profile field from the public API, or null. Absence here is unremarkable. */
66
+ export async function ghProfileField(login, field) {
67
+ const result = await run('gh', ['api', `users/${login}`, '--jq', `.${field}`]);
68
+ const value = output(result);
69
+ return value && value !== 'null' ? value : null;
70
+ }
71
+ export async function ghSwitch(login) {
72
+ const result = await run('gh', ['auth', 'switch', '-u', login]);
73
+ if (notInstalled(result))
74
+ return err('gh is not installed');
75
+ if (!succeeded(result))
76
+ return err(result.stderr.trim() || `gh auth switch exited ${result.code}`);
77
+ return ok(undefined);
78
+ }
@@ -0,0 +1,84 @@
1
+ // Undoing `gh auth setup-git`, and nothing else.
2
+ //
3
+ // WHAT IT DID. `gh auth setup-git` writes two entries per host:
4
+ //
5
+ // [credential "https://github.com"]
6
+ // helper = <- EMPTY
7
+ // helper = !'.../gh.exe' auth git-credential
8
+ //
9
+ // gitcredentials(7) defines the empty value as RESETTING the helper list, so a
10
+ // perfectly good `credential.helper = manager` sitting underneath is discarded
11
+ // and gh becomes the only helper for that host.
12
+ //
13
+ // WHY THAT BREAKS. `gh auth git-credential` resolves the token by HOST and serves
14
+ // only the ACTIVE account: asked for any other account it returns nothing and
15
+ // exits 1, even when that account's token is in the same keyring. So while gh is
16
+ // the helper, every `gh auth switch` guarantees a password prompt for every
17
+ // repository pinned to a different account.
18
+ //
19
+ // Removing those entries hands the host back to whatever was configured
20
+ // underneath. It is reversible in one command -- `gh auth setup-git` puts them
21
+ // back exactly as they were.
22
+ //
23
+ // REPORTS AN OUTCOME PER ENTRY, not a list of successes. An earlier version
24
+ // appended only on exit 0 and discarded stderr, so a write it could not perform
25
+ // vanished from the report and a partial repair read as a smaller successful one.
26
+ // The system scope is the realistic case: reading it needs nothing, editing it is
27
+ // machine-wide and needs an elevated shell.
28
+ import { isGh } from "./gh.js";
29
+ const SCOPES = ['local', 'global', 'system'];
30
+ const HOSTS = ['https://github.com', 'https://gist.github.com'];
31
+ /**
32
+ * What `repair` would remove, without removing it: on each key, gh's values and
33
+ * the empty reset gh writes with them. A key holding no gh value is not listed,
34
+ * and any other helper on a listed key stays -- `gh auth setup-git`, the undo,
35
+ * would never bring it back.
36
+ */
37
+ export async function planRepair(git) {
38
+ const found = [];
39
+ for (const scope of SCOPES) {
40
+ for (const host of HOSTS) {
41
+ const key = 'credential.' + host + '.helper';
42
+ const values = await git.getAllConfigRaw(key, scope);
43
+ if (!values.some(isGh))
44
+ continue;
45
+ found.push({ scope, key, values: ghEntries(values), removed: false });
46
+ }
47
+ }
48
+ return found;
49
+ }
50
+ /** gh's value, or an empty reset sitting directly before one -- the pair gh writes. */
51
+ function isGhEntry(values, index) {
52
+ const value = values[index];
53
+ return isGh(value) || (value.trim().length === 0 && isGh(values[index + 1] ?? null));
54
+ }
55
+ function ghEntries(values) {
56
+ return values.filter((_, index) => isGhEntry(values, index));
57
+ }
58
+ /**
59
+ * git can remove a value by PATTERN, not by position -- and two empty resets are
60
+ * the same pattern, only one of them gh's. So the key is rewritten: unset, then
61
+ * every value that is not gh's added back, in its original order.
62
+ */
63
+ export async function repair(git) {
64
+ const results = [];
65
+ for (const entry of await planRepair(git)) {
66
+ const all = await git.getAllConfigRaw(entry.key, entry.scope);
67
+ const kept = all.filter((_, index) => !isGhEntry(all, index));
68
+ let removed = await git.unsetConfig(entry.key, entry.scope);
69
+ for (const value of kept)
70
+ removed = await git.addConfig(entry.key, value, entry.scope) && removed;
71
+ results.push({ ...entry, removed });
72
+ }
73
+ return results;
74
+ }
75
+ /**
76
+ * An empty value is the list reset, and saying so is the whole point of showing
77
+ * the values at all -- on its own the blank line reads like a formatting bug
78
+ * rather than the thing that discarded the real helper.
79
+ */
80
+ export function describeValue(value) {
81
+ return value.trim().length === 0
82
+ ? '(empty -- resets the helper list, discarding what was configured before)'
83
+ : value;
84
+ }
@@ -0,0 +1,82 @@
1
+ // The single choke point for every subprocess this tool runs.
2
+ //
3
+ // TWO INVARIANTS, BOTH LOAD-BEARING.
4
+ //
5
+ // 1. NOTHING HERE WRITES TO A CONSOLE, EVER. Credential helpers and git can
6
+ // print live secrets on stdout. Whatever a child prints is RETURNED to the
7
+ // caller, never shown, so this layer is never the thing that leaks it.
8
+ // There is no debug flag and no logging hook by design -- the absence is
9
+ // the control. test/exec.test.ts asserts it.
10
+ //
11
+ // 2. A NON-ZERO EXIT IS NOT AN ERROR. git answers questions with exit codes:
12
+ // `git config --get missing.key` exits 1, and that is the answer "not set",
13
+ // not a failure. So this resolves rather than rejects, and callers read
14
+ // `code` themselves. (PowerShell 7.4 turning native exit codes into
15
+ // terminating errors is what forced `Use-NativeExitCodes` in the version
16
+ // this replaces; Node has no such behaviour, but the discipline is the same.)
17
+ //
18
+ // `shell: false` throughout: no argument ever reaches a shell parser, so a
19
+ // branch name or URL containing shell metacharacters cannot be interpreted.
20
+ import { spawn } from 'node:child_process';
21
+ const DEFAULT_TIMEOUT_MS = 30_000;
22
+ /**
23
+ * The timeout is our own timer, NOT spawn's `timeout` option. Node clears that
24
+ * one only on 'exit', which a spawn that fails (ENOENT) never emits -- so every
25
+ * probe for a binary that is not on PATH held the process open for the full
26
+ * 30 s after the command had already printed its answer.
27
+ */
28
+ export function run(file, args, options = {}) {
29
+ return new Promise((resolve) => {
30
+ const child = spawn(file, [...args], {
31
+ cwd: options.cwd,
32
+ env: options.env ?? process.env,
33
+ shell: false,
34
+ windowsHide: true,
35
+ });
36
+ const output = collect(child);
37
+ let timedOut = false;
38
+ const timer = setTimeout(() => { timedOut = true; child.kill(); }, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
39
+ const settle = (result) => {
40
+ clearTimeout(timer);
41
+ resolve({ ...output(), ...result, ...(timedOut ? { timedOut } : {}) });
42
+ };
43
+ child.on('error', (error) => settle({ code: -1, spawnError: error }));
44
+ child.on('close', (code) => settle({ code: code ?? -1 }));
45
+ child.stdin.on('error', () => { });
46
+ child.stdin.end(options.input ?? '');
47
+ });
48
+ }
49
+ /** Accumulates the child's stdout and stderr; call the result for what has arrived so far. */
50
+ function collect(child) {
51
+ let stdout = '';
52
+ let stderr = '';
53
+ child.stdout.setEncoding('utf8');
54
+ child.stderr.setEncoding('utf8');
55
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
56
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
57
+ return () => ({ stdout, stderr });
58
+ }
59
+ /** Ran, and exited 0. */
60
+ export function succeeded(result) {
61
+ return result.code === 0 && result.spawnError === undefined;
62
+ }
63
+ /** The binary itself is missing -- distinct from it running and refusing. */
64
+ export function notInstalled(result) {
65
+ return result.spawnError?.code === 'ENOENT';
66
+ }
67
+ /** stdout with trailing newlines removed, or null when the command did not succeed. */
68
+ export function output(result) {
69
+ if (!succeeded(result))
70
+ return null;
71
+ const text = result.stdout.replace(/\r?\n$/, '');
72
+ return text.length > 0 ? text : null;
73
+ }
74
+ /** stdout split into non-empty trimmed lines. Empty when the command failed. */
75
+ export function lines(result) {
76
+ if (!succeeded(result))
77
+ return [];
78
+ return result.stdout
79
+ .split(/\r?\n/)
80
+ .map((line) => line.trim())
81
+ .filter((line) => line.length > 0);
82
+ }