repown 0.5.4 → 0.6.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 CHANGED
@@ -7,6 +7,26 @@ commands. How a release is cut: [docs/RELEASING.md](docs/RELEASING.md).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.6.0] - 2026-11-27
11
+
12
+ ### Added
13
+ - `repown doctor --online` checks the sign-in itself. It runs one dry-run push to origin
14
+ as the clone's account, which sends nothing and skips the pre-push hook. Then it says what
15
+ the host answered, and the fix: a token that was rejected (expired, revoked or wrong) gets the
16
+ Git Credential Manager command to sign in again; an organisation that enforces SAML SSO gets
17
+ the approval link GitHub sent; a sign-in as the wrong account, or an account that can't see
18
+ the repository, is named. Without the flag, doctor stays offline.
19
+
20
+ ## [0.5.5] - 2026-11-27
21
+
22
+ ### Fixed
23
+ - `repown fix` said "nothing to undo -- gh is not installed as a credential helper" while
24
+ `repown doctor` reported gh as the helper, when `gh auth setup-git`'s entries sat in a
25
+ file your git config includes (`include.path`, for example `~/.gitconfig.local`). `fix`
26
+ now finds them there, removes them from that file, and its preview names the file.
27
+ - A `user.name` or `user.email` kept in a file your global config includes is now shown as
28
+ the machine default by setup and `repown status`.
29
+
10
30
  ## [0.5.4] - 2026-10-12
11
31
 
12
32
  ### Changed
@@ -334,7 +354,9 @@ and cmd. `status`, `doctor` and the pre-push guard are faster on Windows.
334
354
  contract for scripts.
335
355
  - Runs on Node 20+ on Windows, macOS and Linux, with zero runtime dependencies.
336
356
 
337
- [Unreleased]: https://github.com/makubexD/repown/compare/v0.5.4...HEAD
357
+ [Unreleased]: https://github.com/makubexD/repown/compare/v0.6.0...HEAD
358
+ [0.6.0]: https://github.com/makubexD/repown/compare/v0.5.5...v0.6.0
359
+ [0.5.5]: https://github.com/makubexD/repown/compare/v0.5.4...v0.5.5
338
360
  [0.5.4]: https://github.com/makubexD/repown/compare/v0.5.3...v0.5.4
339
361
  [0.5.3]: https://github.com/makubexD/repown/compare/v0.5.2...v0.5.3
340
362
  [0.5.2]: https://github.com/makubexD/repown/compare/v0.5.1...v0.5.2
package/README.md CHANGED
@@ -213,7 +213,7 @@ then commit and push.
213
213
 
214
214
  | When | Command | What it does |
215
215
  | --- | --- | --- |
216
- | Once per machine | `repown doctor` | what serves credentials on this machine, and whether each account is signed in to git and gh |
216
+ | Once per machine | `repown doctor [--online]` | what serves credentials on this machine, and whether each account is signed in to git and gh. 🌐 `--online` also asks origin, with a dry-run push that sends nothing, whether it accepts this clone's sign-in, and prints the fix when it doesn't |
217
217
  | | `repown fix [--dry-run] [--yes]` | undo `gh auth setup-git`, so each clone's pinned account is used; shows what it removes, and the undo, first |
218
218
  | Once per clone | `repown setup [<account>]` | guided setup of this clone. Questions, flags and the review: [Quick start](#quick-start). A clone that is already set up opens on that screen |
219
219
  | | `repown use <account> [--gh]` | what setup runs: pin this clone to an account. `--gh` switches gh's active account, or signs the account in to gh when needed (in a terminal). `--name` with `--email` skips the registry, the file where repown remembers accounts |
@@ -296,6 +296,7 @@ Every `setup` case: [Scripts and CI](docs/CONFIGURATION.md#scripts-and-ci).
296
296
  | `repown doctor` shows `helper` … `none configured` | `git credential-manager configure`, then `repown doctor` again |
297
297
  | A push asked for a password | `repown status` (this clone) or `repown doctor` (this machine): each names the cause (gh as the helper, or no helper) and the fix |
298
298
  | A push failed right after signing in (SSO) | [card 6](docs/HOW-IT-WORKS.md#6-commit-and-first-push) |
299
+ | A pinned clone still can't push or pull ("Invalid username or token", "SAML SSO", 403, 404) | `repown doctor --online`: it says whether the token was rejected, needs SSO approval, or belongs to the wrong account, and prints the command or link that fixes it |
299
300
  | The guard refused a push | it says which commit and the fix. Most often a commit made before pinning: `git commit --amend --reset-author --no-edit` fixes the last one ([card 8](docs/HOW-IT-WORKS.md#8-push-refused-and-the-fix) for older ones, and every other refusal) |
300
301
  | `gh pr create` acts as the wrong account | `gh auth switch -u <account>` when gh lists it, otherwise `repown use <account> --gh` |
301
302
  | `git push` says the branch has no upstream | `repown setup --auto-upstream`, or once `git push -u origin <branch>` |
@@ -0,0 +1,66 @@
1
+ // `repown doctor --online`: ask origin, once, whether it accepts this clone's sign-in for a
2
+ // push (ADR-031). Opt-in, never in the push path (ADR-004): without the flag doctor stays
3
+ // offline.
4
+ import { pinsCredential } from '../core/inspect.js';
5
+ import { isGcm } from '../core/credential/gcm.js';
6
+ import { classifySignIn, describeSignIn } from '../core/signin-check.js';
7
+ import { parseGitUrl } from '../core/url.js';
8
+ import * as out from '../ui/format.js';
9
+ /** Prints the verdict and returns its level; nothing to ask with is a warning, never a pass. */
10
+ export async function checkOnline(repo, pinned) {
11
+ out.heading('This clone, asked online');
12
+ const blocked = await nothingToAsk(repo);
13
+ if (blocked) {
14
+ out.warn('sign-in', blocked);
15
+ return 'warn';
16
+ }
17
+ const verdict = ownLink(classifySignIn(await repo.git.signInProbe('origin')), httpsUrl(repo));
18
+ return printed(describeSignIn(verdict, { account: sentAccount(repo), pinned, gcm: isGcm(repo.helper), github: onGithubCom(repo) }));
19
+ }
20
+ /** The username git sends: the pinned credential username, only where repown pins one over HTTPS. */
21
+ function sentAccount(repo) {
22
+ return pinsCredential(repo) && httpsUrl(repo) ? repo.identity.account : null;
23
+ }
24
+ function httpsUrl(repo) {
25
+ const url = repo.credentialUrl ? parseGitUrl(repo.credentialUrl) : null;
26
+ return url?.scheme === 'https' ? url : null;
27
+ }
28
+ /** The SSO link comes from the remote: shown only when it points at origin's own host. */
29
+ function ownLink(verdict, origin) {
30
+ if (verdict.kind !== 'sso' || !verdict.link)
31
+ return verdict;
32
+ const host = URL.canParse(verdict.link) ? new URL(verdict.link).hostname.toLowerCase() : null;
33
+ return host !== null && host === origin?.host.toLowerCase() ? verdict : { kind: 'sso', link: null };
34
+ }
35
+ /** Why there is no push to try, or null when there is one. */
36
+ async function nothingToAsk(repo) {
37
+ if (!repo.isRepo || repo.originUrl === null)
38
+ return 'not checked: --online asks origin, and there is no clone with an origin here.';
39
+ if (await repo.git.revParse('HEAD') === null)
40
+ return 'not checked: there is no commit to try a push with yet. Commit once, then: repown doctor --online';
41
+ return null;
42
+ }
43
+ /** GCM's `github login` was measured on github.com only (ADR-009). */
44
+ function onGithubCom(repo) {
45
+ return httpsUrl(repo)?.host.toLowerCase() === 'github.com';
46
+ }
47
+ function printed(report) {
48
+ const message = out.printable(report.message);
49
+ if (report.level === 'pass')
50
+ out.pass('sign-in', message);
51
+ else if (report.level === 'fail')
52
+ out.fail('sign-in', message);
53
+ else
54
+ out.warn('sign-in', message);
55
+ for (const line of report.fix)
56
+ out.detail(out.printable(line));
57
+ return report.level;
58
+ }
59
+ /** The closing line, with what the online check found added to the offline verdict. */
60
+ export function closingWithOnline(verdict, code, level) {
61
+ if (level === 'fail')
62
+ return code === 0 ? '1 problem: origin refused the sign-in (above)' : verdict + ' · and origin refused the sign-in';
63
+ if (level === 'warn')
64
+ return verdict + ' · sign-in not checked online';
65
+ return verdict + ' · origin accepts the sign-in';
66
+ }
@@ -15,7 +15,8 @@
15
15
  // accountRows decides the cells. A failed lookup stays `unknown`.
16
16
  import { inspectRepo, inspectAuth, activeAccountLabel, pinsCredential } from '../core/inspect.js';
17
17
  import { loadRegistry } from '../core/registry.js';
18
- import { gitFor } from '../ui/args.js';
18
+ import { flagBool, gitFor } from '../ui/args.js';
19
+ import { checkOnline, closingWithOnline } from './doctor-online.js';
19
20
  import { snapshotOf } from '../core/config-snapshot.js';
20
21
  import { parseGitUrl } from '../core/url.js';
21
22
  import * as out from '../ui/format.js';
@@ -31,7 +32,10 @@ const MACHINE = 'This machine';
31
32
  const MACHINE_FOR_GITHUB = 'This machine, for github.com';
32
33
  export default {
33
34
  summary: 'what serves credentials on this machine, and to whom',
34
- examples: ['repown doctor'],
35
+ options: [
36
+ { name: 'online', kind: 'boolean', help: 'also ask origin, with a dry-run push that sends nothing, whether it accepts this clone\'s sign-in (uses the network)' },
37
+ ],
38
+ examples: ['repown doctor', 'repown doctor --online'],
35
39
  async run(args) {
36
40
  // Read-only: config reads come from one list per scope (ADR-029).
37
41
  const git = snapshotOf(gitFor(args));
@@ -39,8 +43,13 @@ export default {
39
43
  const auth = await inspectAuth(git, probeUrl(repo));
40
44
  const warned = printReport(repo, auth, await loadRegistry());
41
45
  const found = diagnose(auth, ssoHost(repo));
42
- closeDoctor(scoped(repo, found) + warningTally(warned));
43
- return found.code;
46
+ if (!flagBool(args, 'online')) {
47
+ closeDoctor(scoped(repo, found) + warningTally(warned));
48
+ return found.code;
49
+ }
50
+ const level = await checkOnline(repo, pinnedOf(repo));
51
+ closeDoctor(closingWithOnline(scoped(repo, found), found.code, level) + warningTally(warned));
52
+ return level === 'fail' ? 1 : found.code;
44
53
  },
45
54
  };
46
55
  export function accountRows(registry, auth, pinned) {
@@ -54,8 +54,10 @@ function preview(planned) {
54
54
  }
55
55
  /** What `fix` would remove, and the undo. `repown setup` shows the same lines in its review. */
56
56
  export function previewLines(planned) {
57
+ // The file is named: it may be one the scope includes, not the file the user expects (ADR-030).
57
58
  const entries = planned.flatMap((entry) => [
58
59
  ' ' + entry.scope + ': ' + entry.key,
60
+ ' in ' + entry.file,
59
61
  ...entry.values.map((value) => ' = ' + describeValue(value)),
60
62
  ]);
61
63
  return [
@@ -85,6 +87,7 @@ function reportRemovals(results) {
85
87
  continue;
86
88
  }
87
89
  out.warn('fix', 'could NOT remove ' + entry.scope + ': ' + entry.key);
90
+ out.detail('in ' + entry.file);
88
91
  if (entry.scope === 'system')
89
92
  out.detail('the system scope is machine-wide; re-run this in an ELEVATED shell.');
90
93
  }
@@ -1,9 +1,9 @@
1
- // Config reads answered from one `git config [--scope] --list -z` per scope, read on first
2
- // use, for code that only reads (ADR-029). A plain `--get` or `--get-all` is answered with
1
+ // Config reads answered from one `git config [--scope [--includes]] --list -z` per scope, read on
2
+ // first use, for code that only reads (ADR-029, ADR-030). A plain `--get` or `--get-all` is answered with
3
3
  // the output git itself would print for it, so Git's parsing of that output is unchanged.
4
4
  // Other config queries (`--type=bool`, `--get-urlmatch`, `--show-origin --get-regexp`) and
5
5
  // every non-config call go to git. A config write refuses.
6
- import { Git } from './git.js';
6
+ import { Git, followsIncludes } from './git.js';
7
7
  import { succeeded } from './exec.js';
8
8
  const SCOPE_FLAGS = new Map([['--local', 'local'], ['--global', 'global'], ['--system', 'system']]);
9
9
  /** The first argument after `config` and its scope: the query git is asked, never a value. */
@@ -13,10 +13,11 @@ export class ConfigSnapshot extends Git {
13
13
  exec(args, input) {
14
14
  if (args[0] !== 'config')
15
15
  return this.spawnGit(args, input);
16
- const read = configRead(args);
16
+ const query = withoutIncludes(args);
17
+ const read = configRead(query);
17
18
  if (read)
18
19
  return this.answer(read);
19
- if (PASSED_THROUGH.has(actionOf(args) ?? ''))
20
+ if (PASSED_THROUGH.has(actionOf(query) ?? ''))
20
21
  return this.spawnGit(args, input);
21
22
  return Promise.reject(new Error('a config snapshot only reads: git ' + args.join(' ')));
22
23
  }
@@ -60,8 +61,18 @@ export function snapshotOf(git) {
60
61
  throw new Error('snapshotOf takes a plain Git, not ' + git.constructor.name);
61
62
  return new ConfigSnapshot(git.cwd);
62
63
  }
64
+ /** A global or system list follows includes, as those reads from Git do; local does not (ADR-030). */
63
65
  function listArgs(scope) {
64
- return scope ? ['config', '--' + scope, '--list', '-z'] : ['config', '--list', '-z'];
66
+ if (!scope)
67
+ return ['config', '--list', '-z'];
68
+ return ['config', '--' + scope, ...(followsIncludes(scope) ? ['--includes'] : []), '--list', '-z'];
69
+ }
70
+ /**
71
+ * The query without the `--includes` a scoped read carries: a snapshot's lists already follow
72
+ * includes. Only the flag right after the scope is dropped, so a value is never touched.
73
+ */
74
+ function withoutIncludes(args) {
75
+ return SCOPE_FLAGS.has(args[1] ?? '') && args[2] === '--includes' ? [...args.slice(0, 2), ...args.slice(3)] : args;
65
76
  }
66
77
  function missingFileIsEmpty(listed) {
67
78
  return !succeeded(listed) && /unable to read config file/.test(listed.stderr) ? answered(0, '') : listed;
@@ -27,25 +27,31 @@
27
27
  // machine-wide and needs an elevated shell.
28
28
  import { isGh } from './gh.js';
29
29
  const SCOPES = ['local', 'global', 'system'];
30
- const HOSTS = ['https://github.com', 'https://gist.github.com'];
30
+ /** The helper key of github.com and gist.github.com, the two hosts gh writes. */
31
+ const HELPER_KEYS = '^credential\\.https://(gist\\.)?github\\.com\\.helper$';
31
32
  /**
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,
33
+ * What `repair` would remove, without removing it: on each key in each file, gh's
34
+ * values and the empty reset gh writes with them. A key holding no gh value is not
35
+ * listed, and any other helper on a listed key stays -- `gh auth setup-git`, the undo,
35
36
  * would never bring it back.
36
37
  */
37
38
  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
- }
39
+ const read = await Promise.all(SCOPES.map((scope) => git.configOrigins(HELPER_KEYS, scope)));
40
+ return SCOPES.flatMap((scope, index) => plannedIn(scope, read[index]));
41
+ }
42
+ /** One outcome per (file, key) holding gh's value: gh writes its reset and value together. */
43
+ function plannedIn(scope, entries) {
44
+ const byFileAndKey = new Map();
45
+ for (const entry of entries) {
46
+ const id = entry.file + '\0' + entry.key;
47
+ byFileAndKey.set(id, [...(byFileAndKey.get(id) ?? []), entry]);
47
48
  }
48
- return found;
49
+ return [...byFileAndKey.values()].flatMap((group) => {
50
+ const values = group.map((entry) => entry.value);
51
+ if (!values.some(isGh))
52
+ return [];
53
+ return [{ scope, file: group[0].file, key: group[0].key, values: ghEntries(values), removed: false }];
54
+ });
49
55
  }
50
56
  /** gh's value, or an empty reset sitting directly before one -- the pair gh writes. */
51
57
  function isGhEntry(values, index) {
@@ -57,21 +63,30 @@ function ghEntries(values) {
57
63
  }
58
64
  /**
59
65
  * 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.
66
+ * the same pattern, only one of them gh's. So the key is rewritten in its file:
67
+ * unset, then every value that is not gh's added back, in its original order.
62
68
  */
63
69
  export async function repair(git) {
64
70
  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
- }
71
+ for (const entry of await planRepair(git))
72
+ results.push({ ...entry, removed: await rewrite(git, entry) });
73
73
  return results;
74
74
  }
75
+ /**
76
+ * That file's own values of the key, gh's left out. A local entry goes through `--local`:
77
+ * git prints its origin relative to the worktree (`.git/config`), which `--file=` would
78
+ * resolve against the cwd, and local reads don't follow includes. A global or system origin
79
+ * is absolute, and named outright, so its own includes are not read.
80
+ */
81
+ async function rewrite(git, entry) {
82
+ const target = entry.scope === 'local' ? 'local' : { file: entry.file };
83
+ const all = await git.getAllConfigRaw(entry.key, target);
84
+ const kept = all.filter((_, index) => !isGhEntry(all, index));
85
+ let removed = await git.unsetConfig(entry.key, target);
86
+ for (const value of kept)
87
+ removed = await git.addConfig(entry.key, value, target) && removed;
88
+ return removed;
89
+ }
75
90
  /**
76
91
  * An empty value is the list reset, and saying so is the whole point of showing
77
92
  * the values at all -- on its own the blank line reads like a formatting bug
package/dist/core/git.js CHANGED
@@ -19,6 +19,7 @@ import { tmpdir } from 'node:os';
19
19
  import { randomUUID } from 'node:crypto';
20
20
  import { run, succeeded, output, lines } from './exec.js';
21
21
  import { ok, err } from './result.js';
22
+ import { positional } from './shell.js';
22
23
  export class Git {
23
24
  cwd;
24
25
  constructor(cwd = process.cwd()) {
@@ -154,20 +155,34 @@ export class Git {
154
155
  return output(await this.exec(['rev-parse', '--git-path', 'hooks']));
155
156
  }
156
157
  // ---- config -------------------------------------------------------------
157
- scoped(scope, args) {
158
- return scope ? ['config', `--${scope}`, ...args] : ['config', ...args];
158
+ /** argv addressed to a scope's own file, or to one file named outright: every write. */
159
+ scoped(target, args) {
160
+ if (target === undefined)
161
+ return ['config', ...args];
162
+ return ['config', typeof target === 'string' ? `--${target}` : `--file=${target.file}`, ...args];
163
+ }
164
+ /**
165
+ * A read's argv. git follows include.path only when no scope is named, unless told to:
166
+ * without --includes a global or system read misses a value kept in a file it includes,
167
+ * which git itself applies (ADR-030). A local read stays bare: a clone's include can name a
168
+ * file the repository tracks, and committed content must not set the guard's own keys.
169
+ * A file named outright is read on its own.
170
+ */
171
+ reading(target, args) {
172
+ const scoped = this.scoped(target, args);
173
+ return followsIncludes(target) ? [...scoped.slice(0, 2), '--includes', ...scoped.slice(2)] : scoped;
159
174
  }
160
175
  /** The value, or null when unset. Omit `scope` to read what git would EFFECTIVELY use. */
161
176
  async getConfig(key, scope) {
162
- return output(await this.exec(this.scoped(scope, ['--get', key])));
177
+ return output(await this.exec(this.reading(scope, ['--get', key])));
163
178
  }
164
179
  /** Effective boolean, or null when unset or not a bool. Omit `scope` for any-scope. */
165
180
  async getBoolConfig(key, scope) {
166
- const value = output(await this.exec(this.scoped(scope, ['--type=bool', '--get', key])));
181
+ const value = output(await this.exec(this.reading(scope, ['--type=bool', '--get', key])));
167
182
  return value === 'true' ? true : value === 'false' ? false : null;
168
183
  }
169
184
  async getAllConfig(key, scope) {
170
- return lines(await this.exec(this.scoped(scope, ['--get-all', key])));
185
+ return lines(await this.exec(this.reading(scope, ['--get-all', key])));
171
186
  }
172
187
  /**
173
188
  * Every value of a multi-valued key, INCLUDING empty ones.
@@ -179,8 +194,8 @@ export class Git {
179
194
  * stopped working. Filtering it out made `repown fix` preview two values while
180
195
  * removing four, and hid the one the explanation is actually about.
181
196
  */
182
- async getAllConfigRaw(key, scope) {
183
- const result = await this.exec(this.scoped(scope, ['--get-all', key]));
197
+ async getAllConfigRaw(key, target) {
198
+ const result = await this.exec(this.reading(target, ['--get-all', key]));
184
199
  if (!succeeded(result))
185
200
  return [];
186
201
  // git ends every value with LF on every platform, so a CR is part of a value: kept.
@@ -195,12 +210,12 @@ export class Git {
195
210
  return succeeded(await this.exec(this.scoped(scope, [key, value])));
196
211
  }
197
212
  /** Appends one more value to a multi-valued key. */
198
- async addConfig(key, value, scope) {
199
- return succeeded(await this.exec(this.scoped(scope, ['--add', key, value])));
213
+ async addConfig(key, value, target) {
214
+ return succeeded(await this.exec(this.scoped(target, ['--add', key, value])));
200
215
  }
201
216
  /** True when the key is gone afterwards -- including when it was never set. */
202
- async unsetConfig(key, scope = 'local') {
203
- const result = await this.exec(this.scoped(scope, ['--unset-all', key]));
217
+ async unsetConfig(key, target = 'local') {
218
+ const result = await this.exec(this.scoped(target, ['--unset-all', key]));
204
219
  return succeeded(result) || result.code === 5; // 5 = the key did not exist
205
220
  }
206
221
  /**
@@ -215,10 +230,13 @@ export class Git {
215
230
  async getUrlMatch(key, url) {
216
231
  return output(await this.exec(['config', '--get-urlmatch', key, url]));
217
232
  }
218
- /** Which FILE each matching key lives in, so a repair edits the scope that holds it. */
233
+ /**
234
+ * Which FILE each matching value lives in, so a repair edits the file that holds it: with a
235
+ * scope, an included file too, under the scope that includes it (ADR-030).
236
+ */
219
237
  async configOrigins(pattern, scope) {
220
- const args = this.scoped(scope, ['--show-origin', '--get-regexp', pattern]);
221
- return lines(await this.exec(args)).flatMap(parseOriginLine);
238
+ const result = await this.exec(this.reading(scope, ['--show-origin', '-z', '--get-regexp', pattern]));
239
+ return succeeded(result) ? parseOrigins(result.stdout) : [];
222
240
  }
223
241
  // ---- history ------------------------------------------------------------
224
242
  /**
@@ -279,6 +297,16 @@ export class Git {
279
297
  const fetched = await this.execLong([...QUIET, 'fetch', '--quiet', '--no-recurse-submodules', '--', remote], await this.quietEnvHere(), NETWORK_MS);
280
298
  return succeeded(fetched) ? ok(undefined) : err(networkReason(fetched));
281
299
  }
300
+ /**
301
+ * A dry-run push of HEAD to a branch nobody has (network, prompts off, no pre-push hook): it
302
+ * signs in as a push would and sends nothing. git's raw answer, for classifySignIn (ADR-031).
303
+ * `--no-recurse-submodules` overrides push.recurseSubmodules: on-demand would run each
304
+ * submodule's own push, and its hook, which --no-verify doesn't reach.
305
+ */
306
+ async signInProbe(remote) {
307
+ const push = ['push', '--dry-run', '--no-verify', '--no-recurse-submodules', '--porcelain', ...positional(remote), 'HEAD:refs/heads/repown-sign-in-check'];
308
+ return this.execLong([...QUIET, ...push], await this.quietEnvHere(), NETWORK_MS);
309
+ }
282
310
  /** How many branches the remote lists (network, prompts off). */
283
311
  async remoteHeadCount(remote) {
284
312
  const listed = await this.execLong([...QUIET, 'ls-remote', '--heads', '--', remote], await this.quietEnvHere(), NETWORK_MS);
@@ -426,16 +454,28 @@ export class Git {
426
454
  return ok(counts);
427
455
  }
428
456
  }
457
+ /** The machine's own scopes, whose includes are the user's files (ADR-030). */
458
+ export function followsIncludes(target) {
459
+ return target === 'global' || target === 'system';
460
+ }
429
461
  /**
430
- * `file:<path>\t<key> <value>`. The path is printed UNQUOTED and may hold
431
- * spaces (`C:/Program Files/Git/etc/gitconfig`), so it ends at the TAB, not at
432
- * the first space.
462
+ * `--show-origin -z --get-regexp`: `<origin>\0<key>\n<value>\0` per value, a key with no
463
+ * `=` written without the newline. NUL can't occur in a path, key or value, so a path with
464
+ * spaces or a value with a tab or newline comes back whole. Only a `file:` origin can be
465
+ * edited; a command-line or blob one is left out.
433
466
  */
434
- function parseOriginLine(line) {
435
- const match = /^file:([^\t]+)\t(\S+)(?: (.*))?$/.exec(line);
436
- if (!match)
437
- return [];
438
- return [{ file: match[1], key: match[2], value: match[3] ?? '' }];
467
+ function parseOrigins(stdout) {
468
+ const fields = stdout.split('\0');
469
+ const entries = [];
470
+ for (let index = 0; index + 1 < fields.length; index += 2) {
471
+ const origin = fields[index];
472
+ const pair = fields[index + 1];
473
+ if (!origin.startsWith('file:'))
474
+ continue;
475
+ const newline = pair.indexOf('\n');
476
+ entries.push({ file: origin.slice('file:'.length), key: newline < 0 ? pair : pair.slice(0, newline), value: newline < 0 ? '' : pair.slice(newline + 1) });
477
+ }
478
+ return entries;
439
479
  }
440
480
  /**
441
481
  * NUL-terminated fields, subject LAST. git refuses NUL in a name or an address,
@@ -0,0 +1,59 @@
1
+ // What origin says to a dry-run push, as the clone's pinned account (ADR-031).
2
+ //
3
+ // A read is no check: github.com answers `ls-remote` of a public repository without asking for
4
+ // the credential at all, so a revoked token reads as fine (measured). The push endpoint always
5
+ // asks. `git push --dry-run` stops after the ref advertisement and sends nothing.
6
+ //
7
+ // The WHOLE stderr is read: the SSO refusal's fix is the `visit <url>` line git prints before
8
+ // its last one.
9
+ import { succeeded } from './exec.js';
10
+ import { networkReason } from './git.js';
11
+ import { copyableCommand } from './shell.js';
12
+ /** First match wins: SSO's 403 also reads as "unable to access", so it goes first. */
13
+ const PATTERNS = [
14
+ [/SAML SSO/, (stderr) => ({ kind: 'sso', link: /visit (https:\/\/\S+)/.exec(stderr)?.[1] ?? null })],
15
+ [/Permission to \S+ denied to /, (stderr) => ({ kind: 'denied', as: /denied to ([^\s.]+)/.exec(stderr)?.[1] ?? '' })],
16
+ [/Invalid username or token|Authentication failed/, () => ({ kind: 'rejected' })],
17
+ [/Repository not found/, () => ({ kind: 'not-found' })],
18
+ [/unable to get password|Cannot prompt because user interactivity has been disabled|could not read Username|terminal prompts disabled/, () => ({ kind: 'no-sign-in' })],
19
+ ];
20
+ export function classifySignIn(result) {
21
+ if (succeeded(result))
22
+ return { kind: 'ok' };
23
+ if (result.timedOut)
24
+ return { kind: 'unchecked', reason: 'timed out' };
25
+ const found = PATTERNS.find(([pattern]) => pattern.test(result.stderr));
26
+ return found ? found[1](result.stderr) : { kind: 'unchecked', reason: networkReason(result) };
27
+ }
28
+ export function describeSignIn(verdict, ctx) {
29
+ const whose = ctx.account ? ctx.account + '\'s sign-in' : 'this clone\'s sign-in';
30
+ switch (verdict.kind) {
31
+ case 'ok': return { level: 'pass', message: (ctx.account ? 'origin accepts ' + whose + ' for a push' : 'origin accepts a push from this clone') + ' (a dry run: nothing was sent)', fix: [] };
32
+ case 'sso': return { level: 'fail', message: 'origin refused ' + whose + ': the organisation enforces SAML SSO, and this sign-in isn\'t authorised for it.', fix: ssoFix(verdict.link) };
33
+ case 'rejected': return { level: 'fail', message: 'the host rejected ' + whose + ': the token or password git holds was expired, revoked or wrong.', fix: loginFix(ctx) };
34
+ case 'denied': return denied(verdict.as, ctx);
35
+ case 'not-found': return { level: 'fail', message: 'origin was not found with ' + whose + ': that account can\'t see it (the wrong account, or no access).', fix: ['check the account (repown status), or ask for access'] };
36
+ case 'no-sign-in': return { level: 'fail', message: 'no sign-in is stored' + (ctx.account ? ' for ' + ctx.account : '') + ', so a push would ask for one.', fix: loginFix(ctx) };
37
+ case 'unchecked': return { level: 'warn', message: 'couldn\'t check the sign-in: ' + verdict.reason, fix: [] };
38
+ }
39
+ }
40
+ function ssoFix(link) {
41
+ const then = 'then: repown doctor --online';
42
+ return link ? ['authorise it: ' + link, then] : ['authorise this sign-in in the organisation\'s SSO settings', then];
43
+ }
44
+ /** GCM's own sign-in, only where it was measured, and only when the account quotes safely. */
45
+ function loginFix(ctx) {
46
+ if (!ctx.gcm || !ctx.github || !ctx.account)
47
+ return [];
48
+ const command = copyableCommand(['git', 'credential-manager', 'github', 'login', '--username', ctx.account, '--browser', '--force']);
49
+ return command ? ['sign in again: ' + command] : [];
50
+ }
51
+ /** Signed in as someone who can't push: the pinned account when it differs, else write access. */
52
+ function denied(as, ctx) {
53
+ const pinned = ctx.pinned;
54
+ if (!pinned || !as || as.toLowerCase() === pinned.toLowerCase()) {
55
+ return { level: 'fail', message: 'origin refused the push: ' + (as || 'this sign-in') + ' can\'t push here; ask for write access.', fix: [] };
56
+ }
57
+ const command = copyableCommand(['repown', 'use', pinned]);
58
+ return { level: 'fail', message: 'origin refused the push: git signed in as ' + as + ', not ' + pinned + ', and ' + as + ' can\'t push here.', fix: command ? ['use the pinned account: ' + command] : [] };
59
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "repown",
3
- "version": "0.5.4",
3
+ "version": "0.6.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "repown",
9
- "version": "0.5.4",
9
+ "version": "0.6.0",
10
10
  "license": "MIT",
11
11
  "bin": {
12
12
  "repown": "dist/cli.js"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "repown",
3
- "version": "0.5.4",
3
+ "version": "0.6.0",
4
4
  "description": "Use several git accounts on one machine: each repo owns its identity, so you move between repos with no switch command and never push the wrong one.",
5
5
  "repository": {
6
6
  "type": "git",