repown 0.5.5 → 0.7.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,45 @@ commands. How a release is cut: [docs/RELEASING.md](docs/RELEASING.md).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.7.0] - 2026-11-28
11
+
12
+ ### Added
13
+ - repown now guides the sign-in until the remote accepts it. In a terminal, when
14
+ `repown doctor --online` finds a refusal, it offers the matching fix, runs it on a yes,
15
+ and checks again: Git Credential Manager's github.com sign-in (your browser opens),
16
+ `repown fix` when gh is the helper (it shows what it removes and asks first), pinning the
17
+ account again, or, for SAML SSO, waiting while you approve the page. Without a terminal it
18
+ prints the verdict and the fix, as before.
19
+ - `repown setup` ends by asking to check the sign-in online (one dry-run push, nothing sent),
20
+ with the same guided repair. Its closing line says `done` with `· origin accepts the
21
+ sign-in` only on a pass, and says what is left otherwise. Never asked under `--no-input`.
22
+ - `doctor --online` names an SSH key the host refused, a host key ssh doesn't trust yet, and
23
+ a deploy key without write access, each with its fix.
24
+
25
+ ### Changed
26
+ - `repown doctor --online` exits 3 when the check couldn't run (offline, no commit, no
27
+ remote), so a script never reads a skipped check as a pass.
28
+ - `doctor --online` asks the remote a plain `git push` uses, and describes that remote's
29
+ push URL: its account, helper and SSO link.
30
+ - A failed check always names a next step, by credential helper.
31
+
32
+ ### Fixed
33
+ - A username in the push URL (`https://octo-work@github.com/…`) other than the pinned
34
+ account was reported as ready, though git signs in as that user. `repown status` and setup
35
+ now report it as blocking the next push, with the `git remote set-url` command that
36
+ removes it.
37
+ - A remote that refused only the pushed ref, after signing in, read as a failed sign-in.
38
+
39
+ ## [0.6.0] - 2026-11-27
40
+
41
+ ### Added
42
+ - `repown doctor --online` checks the sign-in itself. It runs one dry-run push to origin
43
+ as the clone's account, which sends nothing and skips the pre-push hook. Then it says what
44
+ the host answered, and the fix: a token that was rejected (expired, revoked or wrong) gets the
45
+ Git Credential Manager command to sign in again; an organisation that enforces SAML SSO gets
46
+ the approval link GitHub sent; a sign-in as the wrong account, or an account that can't see
47
+ the repository, is named. Without the flag, doctor stays offline.
48
+
10
49
  ## [0.5.5] - 2026-11-27
11
50
 
12
51
  ### Fixed
@@ -344,7 +383,9 @@ and cmd. `status`, `doctor` and the pre-push guard are faster on Windows.
344
383
  contract for scripts.
345
384
  - Runs on Node 20+ on Windows, macOS and Linux, with zero runtime dependencies.
346
385
 
347
- [Unreleased]: https://github.com/makubexD/repown/compare/v0.5.5...HEAD
386
+ [Unreleased]: https://github.com/makubexD/repown/compare/v0.7.0...HEAD
387
+ [0.7.0]: https://github.com/makubexD/repown/compare/v0.6.0...v0.7.0
388
+ [0.6.0]: https://github.com/makubexD/repown/compare/v0.5.5...v0.6.0
348
389
  [0.5.5]: https://github.com/makubexD/repown/compare/v0.5.4...v0.5.5
349
390
  [0.5.4]: https://github.com/makubexD/repown/compare/v0.5.3...v0.5.4
350
391
  [0.5.3]: https://github.com/makubexD/repown/compare/v0.5.2...v0.5.3
package/README.md CHANGED
@@ -158,6 +158,14 @@ repown # in a terminal: starts the guided setup of this clone
158
158
  └
159
159
  ```
160
160
 
161
+ 🌐 Once the steps have run and nothing blocks the next push, setup asks one more
162
+ question: **Check the sign-in with the remote now?** Yes (the default) runs one dry-run
163
+ push that sends nothing. If the remote refuses, setup says why and offers the fix: sign in
164
+ again through Git Credential Manager, undo gh's helper, approve the SSO page in your
165
+ browser (setup waits), or pin the account again. Then it checks again. Setup says
166
+ `done … · origin accepts the sign-in` only when it passes
167
+ ([card 13](docs/HOW-IT-WORKS.md#13-guided-setup)).
168
+
161
169
  4. **Push.** The first push from each account signs in once: GCM opens a browser, and you
162
170
  sign in as *that* clone's account, not whichever you used last. After that, pushes from
163
171
  that clone use it without asking. When setup set `push.autoSetupRemote`, the first
@@ -213,7 +221,7 @@ then commit and push.
213
221
 
214
222
  | When | Command | What it does |
215
223
  | --- | --- | --- |
216
- | Once per machine | `repown doctor` | what serves credentials on this machine, and whether each account is signed in to git and gh |
224
+ | 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. When it doesn't, it says why and the fix; in a terminal it offers to run that fix (waiting while you approve an SSO page), then checks again |
217
225
  | | `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
226
  | 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
227
  | | `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 |
@@ -284,6 +292,7 @@ note, not a warning. Every warning it can print:
284
292
  | `repown scan` | Whatever it finds (read its output or JSON) | | A missing folder or a bad `--depth` | |
285
293
  | `repown setup` | Done, or already set up | Decline, or it can't start | Flags that don't fit, or no terminal without `--no-input` | 130 when cancelled or interrupted; a failing step's own code |
286
294
  | `repown status` | Success. Warnings alone exit 0 | A problem | | |
295
+ | `repown doctor --online` | Ready, and the remote accepts the sign-in | A problem, or the remote refused the sign-in | | 3 when the sign-in couldn't be checked (no network, no commit, no remote) |
287
296
 
288
297
  Every `setup` case: [Scripts and CI](docs/CONFIGURATION.md#scripts-and-ci).
289
298
 
@@ -296,6 +305,7 @@ Every `setup` case: [Scripts and CI](docs/CONFIGURATION.md#scripts-and-ci).
296
305
  | `repown doctor` shows `helper` … `none configured` | `git credential-manager configure`, then `repown doctor` again |
297
306
  | 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
307
  | A push failed right after signing in (SSO) | [card 6](docs/HOW-IT-WORKS.md#6-commit-and-first-push) |
308
+ | 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 the command or link that fixes it. In a terminal it offers to run the fix, then checks again |
299
309
  | 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
310
  | `gh pr create` acts as the wrong account | `gh auth switch -u <account>` when gh lists it, otherwise `repown use <account> --gh` |
301
311
  | `git push` says the branch has no upstream | `repown setup --auto-upstream`, or once `git push -u origin <branch>` |
@@ -0,0 +1,108 @@
1
+ // `repown doctor --online`: ask the remote a plain `git push` uses, once, whether it accepts
2
+ // this clone's sign-in for a push (ADR-031). Opt-in, never in the push path (ADR-004):
3
+ // without the flag doctor stays offline.
4
+ //
5
+ // Everything said about the sign-in (account, helper, host, SSO link) describes the URL the
6
+ // probe really pushes to (`remote get-url --push`, after insteadOf and pushInsteadOf), never
7
+ // the fetch URL: an HTTPS fetch with an SSH push signs in with a key, not a token.
8
+ import { inspectRepo, keysOf } from '../core/inspect.js';
9
+ import { carriesSecret } from '../core/push-state.js';
10
+ import { pushTarget } from '../core/push-destination.js';
11
+ import { classifySignIn, describeSignIn } from '../core/signin-check.js';
12
+ import { parseGitUrl } from '../core/url.js';
13
+ import * as out from '../ui/format.js';
14
+ import { gitFor } from '../ui/args.js';
15
+ import { interactive } from '../ui/prompt.js';
16
+ import { repairFor } from '../core/signin-repair.js';
17
+ import { guideSignIn } from './signin-guide.js';
18
+ import { terminalIo } from './signin-terminal.js';
19
+ /**
20
+ * Asks once; in a terminal, offers each repair and asks again after it. Each round reads the
21
+ * clone afresh, since a repair (fix, use) changes the config the next check depends on.
22
+ */
23
+ export async function askOnline(args, repo, pinnedOf) {
24
+ if (!interactive())
25
+ return checkOnline(repo, pinnedOf(repo));
26
+ let round = 0;
27
+ const check = async () => {
28
+ const fresh = round === 0 ? repo : await inspectRepo(gitFor(args));
29
+ return checkOnline(fresh, pinnedOf(fresh), round++ === 0);
30
+ };
31
+ return guideSignIn(check, terminalIo(args));
32
+ }
33
+ /** Prints the verdict and returns it with its repair; nothing to ask with is a warning, never a pass. */
34
+ export async function checkOnline(repo, pinned, heading = true) {
35
+ if (heading)
36
+ out.heading('This clone, asked online');
37
+ const target = repo.isRepo ? await targetOf(repo) : null;
38
+ const blocked = await nothingToAsk(repo, target);
39
+ if (blocked || !target) {
40
+ out.warn('sign-in', blocked ?? 'not checked');
41
+ return { level: 'warn', remote: target?.remote ?? 'origin', repair: null };
42
+ }
43
+ out.detail('asking ' + target.remote + ' with a dry-run push…');
44
+ const verdict = ownLink(classifySignIn(await repo.git.signInProbe(target.remote)), target.https);
45
+ const ctx = { ...target, pinned, github: target.https?.host.toLowerCase() === 'github.com' };
46
+ const level = printed(describeSignIn(verdict, ctx));
47
+ return { level, remote: target.remote, repair: level === 'fail' ? repairFor(verdict, ctx) : null };
48
+ }
49
+ async function targetOf(repo) {
50
+ const remote = await pushRemote(repo);
51
+ const raw = await repo.git.remotePushUrl(remote);
52
+ const parsed = raw ? parseGitUrl(raw) : null;
53
+ const https = parsed?.scheme === 'https' ? parsed : null;
54
+ const host = parsed?.host || null;
55
+ if (!raw || !https)
56
+ return { remote, raw, https, host, account: null, fromUrl: false, helper: null };
57
+ const [account, helper] = await Promise.all([sentUser(repo.git, raw, https), repo.git.getUrlMatch('credential.helper', raw)]);
58
+ return { remote, raw, https, host, account, fromUrl: !!https.user && account !== null, helper };
59
+ }
60
+ /** The remote a plain push sends HEAD's branch to; origin when that is a URL or can't be read. */
61
+ async function pushRemote(repo) {
62
+ if (repo.branch?.kind !== 'branch')
63
+ return 'origin';
64
+ const target = await pushTarget(repo.git, repo.branch.name);
65
+ return target?.isRemote ? target.name : 'origin';
66
+ }
67
+ /** The username git sends: the URL's own (never a secret), else the pin where repown pins one. */
68
+ async function sentUser(git, raw, url) {
69
+ if (url.user)
70
+ return carriesSecret(raw) ? null : url.user;
71
+ return keysOf(raw).length > 0 ? git.getUrlMatch('credential.username', raw) : null;
72
+ }
73
+ /** The SSO link comes from the remote: shown only when it points at the push URL's own host. */
74
+ function ownLink(verdict, url) {
75
+ if (verdict.kind !== 'sso' || !verdict.link)
76
+ return verdict;
77
+ const host = URL.canParse(verdict.link) ? new URL(verdict.link).hostname.toLowerCase() : null;
78
+ return host !== null && host === url?.host.toLowerCase() ? verdict : { kind: 'sso', link: null };
79
+ }
80
+ /** Why there is no push to try, or null when there is one. */
81
+ async function nothingToAsk(repo, target) {
82
+ if (!target || target.raw === null)
83
+ return 'not checked: --online asks the remote a push goes to, and there is no clone with one here.';
84
+ if (await repo.git.revParse('HEAD') === null)
85
+ return 'not checked: there is no commit to try a push with yet. Commit once, then: repown doctor --online';
86
+ return null;
87
+ }
88
+ function printed(report) {
89
+ const message = out.printable(report.message);
90
+ if (report.level === 'pass')
91
+ out.pass('sign-in', message);
92
+ else if (report.level === 'fail')
93
+ out.fail('sign-in', message);
94
+ else
95
+ out.warn('sign-in', message);
96
+ for (const line of report.fix)
97
+ out.detail(out.printable(line));
98
+ return report.level;
99
+ }
100
+ /** The closing line, with what the online check found added to the offline verdict. */
101
+ export function closingWithOnline(verdict, code, level, named = 'origin') {
102
+ const remote = out.printable(named);
103
+ if (level === 'fail')
104
+ return code === 0 ? '1 problem: ' + remote + ' refused the sign-in (above)' : verdict + ' · and ' + remote + ' refused the sign-in';
105
+ if (level === 'warn')
106
+ return verdict + ' · sign-in not checked online';
107
+ return verdict + ' · ' + remote + ' accepts the sign-in';
108
+ }
@@ -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 { askOnline, 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,10 +43,31 @@ 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 online = await askOnline(args, repo, pinnedOf);
51
+ // A repair changed the machine after the offline report: say so rather than repeat it.
52
+ if (online.repaired) {
53
+ closeDoctor(closingWithOnline(REPAIRED, online.level === 'fail' ? 1 : 0, online.level, online.remote) + warningTally(warned));
54
+ return onlineCode(online.level, 0);
55
+ }
56
+ closeDoctor(closingWithOnline(scoped(repo, found), found.code, online.level, online.remote) + warningTally(warned));
57
+ return onlineCode(online.level, found.code);
44
58
  },
45
59
  };
60
+ /** The closing line's start once a repair ran: the report above it was read before. */
61
+ export const REPAIRED = 'a repair ran (the report above was read before it; repown doctor shows the state now)';
62
+ /** Exit code: a refusal is 1; a check that couldn't run is 3, never a pass's 0 (ADR-032). */
63
+ export const NOT_CHECKED = 3;
64
+ function onlineCode(level, offline) {
65
+ if (level === 'fail')
66
+ return 1;
67
+ if (offline !== 0)
68
+ return offline;
69
+ return level === 'warn' ? NOT_CHECKED : 0;
70
+ }
46
71
  export function accountRows(registry, auth, pinned) {
47
72
  const rows = mergeNames(registry, auth).map((item) => toRow(item, auth, pinned));
48
73
  return reportOf(rows, registry, auth);
@@ -0,0 +1,43 @@
1
+ // The guided repair after a failed sign-in check (ADR-032): offer the repair, run it on a yes,
2
+ // check again; an SSO approval waits for Enter instead. Terminal only: the callers decide that,
3
+ // and without one doctor --online prints its advice and stops.
4
+ //
5
+ // The loop can't run forever: every repair but the SSO wait is tried once, a no or a q stops
6
+ // it, and a repair that didn't run stops it without another check.
7
+ import { repairQuestion, triedOnce, SSO_WAIT } from '../core/signin-repair.js';
8
+ export async function guideSignIn(check, io) {
9
+ const tried = new Set();
10
+ let repaired = false;
11
+ let result = await check();
12
+ while (result.level === 'fail' && result.repair) {
13
+ if (!offerable(result.repair, tried)) {
14
+ io.say(UNHELPED);
15
+ break;
16
+ }
17
+ if (!await attempt(result.repair, io))
18
+ break;
19
+ repaired ||= result.repair.kind !== 'sso';
20
+ result = await check();
21
+ }
22
+ return repaired ? { ...result, repaired } : result;
23
+ }
24
+ /** Said when the same repair comes back after it ran: it is not offered again. */
25
+ export const UNHELPED = 'that repair ran, and the remote still refuses the sign-in; repown won\'t offer it again. The advice above is what is left.';
26
+ /** Records the repair as tried; false when it already was. */
27
+ function offerable(repair, tried) {
28
+ const key = triedOnce(repair);
29
+ if (key === null)
30
+ return true;
31
+ if (tried.has(key))
32
+ return false;
33
+ tried.add(key);
34
+ return true;
35
+ }
36
+ async function attempt(repair, io) {
37
+ if (repair.kind === 'sso')
38
+ return io.waitEnter(SSO_WAIT);
39
+ const question = repairQuestion(repair);
40
+ if (question !== null && !await io.confirm(question))
41
+ return false;
42
+ return io.run(repair);
43
+ }
@@ -0,0 +1,25 @@
1
+ // The guided repair in a plain terminal, for `repown doctor --online` (ADR-032): questions
2
+ // through `confirm`, the SSO wait through `waitForEnter`, and each repair through the
3
+ // command that owns it (`repown fix`, `repown use`) or GCM's own sign-in. Never a copy.
4
+ import { flagString } from '../ui/args.js';
5
+ import { confirm, waitForEnter } from '../ui/prompt.js';
6
+ import * as out from '../ui/format.js';
7
+ import { printable } from '../ui/format.js';
8
+ import { gcmGithubLogin } from '../core/credential/gcm.js';
9
+ import fixCommand from './fix.js';
10
+ import useCommand from './use.js';
11
+ export function terminalIo(args) {
12
+ // The user asked for the check, so each repair defaults to Yes; Enter runs it.
13
+ return { confirm: (question) => confirm(printable(question), true), waitEnter: waitForEnter, say: (line) => out.warn('sign-in', line), run: (repair) => runRepair(repair, args) };
14
+ }
15
+ /** Runs a repair as its own command would, in the same directory doctor was asked about. */
16
+ export async function runRepair(repair, args) {
17
+ const cwd = flagString(args, 'cwd');
18
+ const flags = (extra) => new Map([...(cwd ? [['cwd', cwd]] : []), ...extra]);
19
+ // fix previews what it removes, and where, then asks its own question (default No).
20
+ if (repair.kind === 'fix')
21
+ return await fixCommand.run({ positional: [], flags: flags([]) }) === 0;
22
+ if (repair.kind === 'use')
23
+ return await useCommand.run({ positional: [repair.account], flags: flags([]) }) === 0;
24
+ return gcmGithubLogin(repair.account);
25
+ }
@@ -16,6 +16,7 @@ export function blockers(facts, choice) {
16
16
  ...unpushedBlocker(facts.unpushed, choice),
17
17
  ...elsewhereBlocker(facts.elsewhere, facts.destination, branch, choice),
18
18
  ...signinBlocker(facts, branch, choice.account),
19
+ ...urlUserBlocker(facts.urlUser, branch, choice.account),
19
20
  ...facts.env.map((name) => envBlocker(name, choice)),
20
21
  ...facts.configOverrides.map((key) => configBlocker(key, choice.email)),
21
22
  ...ownerBlocker(facts.destination, branch, choice),
@@ -56,6 +57,27 @@ function signinBlocker(facts, branch, account) {
56
57
  blocks: true,
57
58
  }];
58
59
  }
60
+ /** A username in the push URL outranks the pinned credential username: git signs in as it. */
61
+ function urlUserBlocker(found, branch, account) {
62
+ if (!found || found.user.toLowerCase() === account.toLowerCase())
63
+ return [];
64
+ const holder = found.key ? printable(found.key) : printable(found.remote) + "'s push URL, as git resolves it,";
65
+ const user = printable(found.user);
66
+ return [{
67
+ kind: 'urluser',
68
+ summary: 'the push URL signs in as ' + user,
69
+ lines: [holder + ' names the user ' + user + ', so git signs in as ' + user + ' for pushes from ' + branch + ', not ' + account, urlUserFix(found)],
70
+ blocks: true,
71
+ }];
72
+ }
73
+ function urlUserFix(found) {
74
+ const rule = 'remove the user from the url.<base>.insteadOf or pushInsteadOf rule that adds it (' + (copyableCommand(['git', 'config', '--get-regexp', '^url[.]']) ?? 'git config --list') + ' lists them)';
75
+ if (!found.key || !found.clean)
76
+ return found.key ? 'remove ' + printable(found.user) + '@ from ' + printable(found.key) : rule;
77
+ const push = found.key.endsWith('.pushurl') ? ['--push'] : [];
78
+ const command = copyableCommand(['git', 'remote', 'set-url', ...push, ...positional(found.remote), found.clean]);
79
+ return command ? 'remove it: ' + command : 'remove ' + printable(found.user) + '@ from ' + printable(found.key);
80
+ }
59
81
  /** Counted with the guard's own exclusion, so a fork's upstream commits are not missed. */
60
82
  function elsewhereBlocker(elsewhere, destination, branch, choice) {
61
83
  if (!elsewhere.ok) {
@@ -13,7 +13,7 @@
13
13
  // deliberately rather than rediscovered.
14
14
  import { join, dirname } from 'node:path';
15
15
  import { existsSync } from 'node:fs';
16
- import { run, succeeded, lines, notInstalled } from '../exec.js';
16
+ import { run, inherit, succeeded, lines, notInstalled } from '../exec.js';
17
17
  import { ok, err } from '../result.js';
18
18
  const NAMES = ['git-credential-manager', 'git-credential-manager-core'];
19
19
  /** Directories that hold GCM but are not necessarily on PATH. */
@@ -81,3 +81,13 @@ export async function listAccounts(gcmPath, namespace) {
81
81
  }
82
82
  return ok(lines(result));
83
83
  }
84
+ /**
85
+ * GCM's own github.com sign-in, with the terminal handed to it (ADR-032): the browser opens,
86
+ * the user signs in, and GCM stores the token. repown sees nothing GCM prints. The command is
87
+ * GCM 2.6.1's; `--force` over an account GCM already holds is not yet measured (ADR-032).
88
+ * Offered only for github.com with GCM as the helper.
89
+ */
90
+ export async function gcmGithubLogin(account, runner = inherit) {
91
+ const result = await runner('git', ['credential-manager', 'github', 'login', '--username', account, '--browser', '--force']);
92
+ return result.code === 0 && !result.spawnError;
93
+ }
package/dist/core/exec.js CHANGED
@@ -111,8 +111,9 @@ function once(act) {
111
111
  };
112
112
  }
113
113
  /**
114
- * The terminal belongs to the child. Only `gh auth login` uses this, and only
115
- * from a terminal: repown cannot see what the child prints.
114
+ * The terminal belongs to the child. Only `gh auth login` and Git Credential
115
+ * Manager's `github login` use this, and only from a terminal: repown cannot
116
+ * see what the child prints.
116
117
  */
117
118
  export function inherit(file, args, options = {}) {
118
119
  return new Promise((resolve) => {
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()) {
@@ -296,6 +297,16 @@ export class Git {
296
297
  const fetched = await this.execLong([...QUIET, 'fetch', '--quiet', '--no-recurse-submodules', '--', remote], await this.quietEnvHere(), NETWORK_MS);
297
298
  return succeeded(fetched) ? ok(undefined) : err(networkReason(fetched));
298
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
+ }
299
310
  /** How many branches the remote lists (network, prompts off). */
300
311
  async remoteHeadCount(remote) {
301
312
  const listed = await this.execLong([...QUIET, 'ls-remote', '--heads', '--', remote], await this.quietEnvHere(), NETWORK_MS);
@@ -18,16 +18,17 @@ export async function readPushFacts(git, unpushed, env = process.env) {
18
18
  const rewritable = await rewritableOf(git, target);
19
19
  // A remote target's push URLs, read once for the sign-in and later-URL checks.
20
20
  const pushed = target?.isRemote ? git.remoteUrls(target.name, true) : null;
21
- const [configOverrides, signin, repoint, destination, laterUrls, divergence, elsewhere, upstream] = await Promise.all([
21
+ const [configOverrides, signin, urlUser, repoint, destination, laterUrls, divergence, elsewhere, upstream] = await Promise.all([
22
22
  overridesIn(git),
23
23
  signinOf(git, target, { rewritable: rewritable !== null, pushed }),
24
+ urlUserOf(git, target, pushed),
24
25
  repointOf(git, branch),
25
26
  rewritable ? null : destinationOf(git, target),
26
27
  laterUrlsOf(git, target, pushed),
27
28
  divergenceOf(git, target), elsewhereOf(git, target), upstreamOf(git, branch, target),
28
29
  ]);
29
30
  return {
30
- unpushed, env: hostileSet(env), configOverrides, elsewhere, signin, repoint, destination, laterUrls, rewritable, divergence,
31
+ unpushed, env: hostileSet(env), configOverrides, elsewhere, signin, urlUser, repoint, destination, laterUrls, rewritable, divergence,
31
32
  detached: head?.kind === 'detached', upstream,
32
33
  };
33
34
  }
@@ -35,10 +36,16 @@ async function overridesIn(git) {
35
36
  const values = await Promise.all(OVERRIDES.map((key) => git.getConfig(key)));
36
37
  return OVERRIDES.filter((_, index) => values[index]);
37
38
  }
39
+ /**
40
+ * A bare username shaped like an account name: a login's characters, at most 39 of them
41
+ * (GitHub's limit), and not a legacy 40-hex token. Anything else in the userinfo may be a
42
+ * token used as the username, so it is never printed or passed on (ADR-032).
43
+ */
44
+ const ACCOUNT_LIKE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,38}$/;
38
45
  /** A password or a token in the userinfo. A bare username (GCM's own advice) is not a secret. */
39
- function carriesSecret(raw) {
46
+ export function carriesSecret(raw) {
40
47
  const user = raw ? parseGitUrl(raw)?.user : null;
41
- return !!user && (user.includes(':') || /^(gh[pousr]_|github_pat_)/i.test(user));
48
+ return !!user && (user.includes(':') || /^(gh[pousr]_|github_pat_)/i.test(user) || !ACCOUNT_LIKE.test(user));
42
49
  }
43
50
  async function signinOf(git, target, { rewritable, pushed }) {
44
51
  const found = pushed && target ? await remoteSignin(git, target.name, await pushed)
@@ -84,6 +91,27 @@ async function configuredSignin(git, remote) {
84
91
  const [key, values] = pushurls.length > 0 ? [pushurl, pushurls] : ['remote.' + remote + '.url', await git.getAllConfig('remote.' + remote + '.url')];
85
92
  return values.some(carriesSecret) ? { key } : null;
86
93
  }
94
+ async function urlUserOf(git, target, pushed) {
95
+ const urls = pushed && target ? await pushed : null;
96
+ const found = urls?.ok ? urls.value.find(namesUser) : undefined;
97
+ if (!found || !target)
98
+ return null;
99
+ const user = parseGitUrl(found).user;
100
+ for (const key of ['remote.' + target.name + '.pushurl', 'remote.' + target.name + '.url']) {
101
+ const values = await git.getAllConfig(key);
102
+ if (values.includes(found))
103
+ return { remote: target.name, user, key, clean: values.length === 1 ? withoutUser(found, user) : null };
104
+ }
105
+ return { remote: target.name, user, key: null, clean: null };
106
+ }
107
+ /** An HTTPS URL with a bare username: never one that carries a secret (that is `signin`). */
108
+ function namesUser(raw) {
109
+ const url = parseGitUrl(raw);
110
+ return url?.scheme === 'https' && !!url.user && !carriesSecret(raw);
111
+ }
112
+ function withoutUser(raw, user) {
113
+ return raw.replace('//' + user + '@', '//');
114
+ }
87
115
  async function repointOf(git, branch) {
88
116
  const unknown = branch ? await unknownDestination(git, branch) : null;
89
117
  if (unknown?.kind !== 'url' || !unknown.remote)
@@ -0,0 +1,95 @@
1
+ // What the push remote 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, and an SSH refusal's cause is its first line (ADR-032).
9
+ import { succeeded } from './exec.js';
10
+ import { networkReason } from './git.js';
11
+ import { copyableCommand } from './shell.js';
12
+ import { isGcm } from './credential/gcm.js';
13
+ import { isGh } from './credential/gh.js';
14
+ /** First match wins: SSO's 403 also reads as "unable to access", so it goes first. */
15
+ const PATTERNS = [
16
+ [/SAML SSO/, (stderr) => ({ kind: 'sso', link: /visit (https:\/\/\S+)/.exec(stderr)?.[1] ?? null })],
17
+ [/Permission to \S+ denied to deploy key/, () => ({ kind: 'deploy-key' })],
18
+ [/Permission to \S+ denied to /, (stderr) => ({ kind: 'denied', as: /denied to ([^\s.]+)/.exec(stderr)?.[1] ?? '' })],
19
+ [/Invalid username or token|Authentication failed/, () => ({ kind: 'rejected' })],
20
+ [/Repository not found/, () => ({ kind: 'not-found' })],
21
+ [/unable to get password|Cannot prompt because user interactivity has been disabled|could not read Username|terminal prompts disabled/, () => ({ kind: 'no-sign-in' })],
22
+ [/Host key verification failed/, () => ({ kind: 'host-key' })],
23
+ [/Permission denied \(publickey/, () => ({ kind: 'ssh-key' })],
24
+ ];
25
+ /** A porcelain `!` line: the remote refused the ref itself, so the sign-in had already passed. */
26
+ const REF_REJECTED = /^!\t/m;
27
+ export function classifySignIn(result) {
28
+ if (succeeded(result))
29
+ return { kind: 'ok' };
30
+ if (result.timedOut)
31
+ return { kind: 'unchecked', reason: 'timed out' };
32
+ const found = PATTERNS.find(([pattern]) => pattern.test(result.stderr));
33
+ if (found)
34
+ return found[1](result.stderr);
35
+ return REF_REJECTED.test(result.stdout) ? { kind: 'ok' } : { kind: 'unchecked', reason: networkReason(result) };
36
+ }
37
+ export function describeSignIn(verdict, ctx) {
38
+ const whose = ctx.account ? ctx.account + '\'s sign-in' : 'this clone\'s sign-in';
39
+ const fail = (message, fix) => ({ level: 'fail', message: ctx.remote + message, fix });
40
+ switch (verdict.kind) {
41
+ case 'ok': return { level: 'pass', message: ctx.remote + (ctx.account ? ' accepts ' + whose + ' for a push' : ' accepts a push from this clone') + ' (a dry run: nothing was sent)', fix: [] };
42
+ case 'sso': return fail(' refused ' + whose + ': the organisation enforces SAML SSO, and this sign-in isn\'t authorised for it.', ssoFix(verdict.link));
43
+ case 'rejected': return fail(' rejected ' + whose + ': the token or password git held was expired, revoked or wrong, and git has asked the helper to forget it.', signInFix(ctx));
44
+ case 'denied': return denied(verdict.as, ctx);
45
+ case 'not-found': return fail(' was not found with ' + whose + ': that account can\'t see it (the wrong account, or no access).', ['check the account (repown status), or ask for access']);
46
+ case 'no-sign-in': return fail(': no sign-in is stored' + (ctx.account ? ' for ' + ctx.account : '') + ', so a push would ask for one.', signInFix(ctx));
47
+ case 'deploy-key': return fail(' refused the push: the SSH key is a deploy key without write access here.', ['give that deploy key write access, or sign in with an account\'s own key']);
48
+ case 'ssh-key': return fail(' refused this machine\'s SSH key: it isn\'t added to an account that can push here.', sshFix('see which account the key signs in as: ', ctx));
49
+ case 'host-key': return fail(': ssh doesn\'t trust ' + (ctx.host ?? 'the host') + '\'s host key yet, so it stopped before signing in.', sshFix('check and trust it once: ', ctx));
50
+ case 'unchecked': return { level: 'warn', message: 'couldn\'t check the sign-in: ' + verdict.reason, fix: [] };
51
+ }
52
+ }
53
+ function ssoFix(link) {
54
+ const then = 'then: repown doctor --online';
55
+ return link ? ['authorise it: ' + link, then] : ['authorise this sign-in in the organisation\'s SSO settings', then];
56
+ }
57
+ /** How to sign in again, by helper; GCM's own command only where it was measured. */
58
+ function signInFix(ctx) {
59
+ if (isGh(ctx.helper))
60
+ return ['gh signs in as its active account; undo it: repown fix'];
61
+ if (!ctx.helper)
62
+ return ['no credential helper serves this URL; install Git Credential Manager, then: repown doctor --online'];
63
+ if (!isGcm(ctx.helper))
64
+ return ['sign in again through the credential helper (' + ctx.helper + '); a push in a terminal asks'];
65
+ const command = ctx.github && ctx.account ? gcmLogin(ctx.account) : null;
66
+ return [command ? 'sign in again: ' + command : 'sign in again through Git Credential Manager; a push in a terminal asks'];
67
+ }
68
+ /** GCM's sign-in for github.com (measured, GCM 2.6.1); null when no shell quotes the account. */
69
+ export function gcmLogin(account) {
70
+ return copyableCommand(['git', 'credential-manager', 'github', 'login', '--username', account, '--browser', '--force']);
71
+ }
72
+ /** git sent the pinned username, but the helper answered with another account's token. */
73
+ function storedFor(ctx) {
74
+ return ['the stored sign-in for ' + ctx.account + ' is another account\'s', ...signInFix(ctx)];
75
+ }
76
+ function sshFix(label, ctx) {
77
+ const command = ctx.host ? copyableCommand(['ssh', '-T', 'git@' + ctx.host]) : null;
78
+ return [command ? label + command : 'check this machine\'s SSH key and known_hosts for the remote'];
79
+ }
80
+ /** Signed in as someone who can't push: the pinned account when it differs, else write access. */
81
+ function denied(as, ctx) {
82
+ const pinned = ctx.pinned;
83
+ if (!pinned || !as || as.toLowerCase() === pinned.toLowerCase()) {
84
+ return { level: 'fail', message: ctx.remote + ' refused the push: ' + (as || 'this sign-in') + ' can\'t push here.', fix: ['ask the owner for write access'] };
85
+ }
86
+ const message = ctx.remote + ' refused the push: git signed in as ' + as + ', not ' + pinned + ', and ' + as + ' can\'t push here.';
87
+ if (!ctx.account)
88
+ return { level: 'fail', message, fix: sshFix('the SSH key signs in as ' + as + '; see which key: ', ctx) };
89
+ if (ctx.account.toLowerCase() === pinned.toLowerCase())
90
+ return { level: 'fail', message, fix: storedFor(ctx) };
91
+ if (ctx.fromUrl)
92
+ return { level: 'fail', message, fix: ['the push URL names ' + as + '; remove it (repown status prints the command)'] };
93
+ const command = copyableCommand(['repown', 'use', pinned]);
94
+ return { level: 'fail', message, fix: [command ? 'use the pinned account: ' + command : 'pin ' + pinned + ' again with repown use'] };
95
+ }
@@ -0,0 +1,52 @@
1
+ // Which repair a failed sign-in check can offer to run, and what to ask first (ADR-032). Pure:
2
+ // doctor --online and setup's last step share it, and each draws the question its own way.
3
+ //
4
+ // An offer is made only where the fix is measured and local or the user's own sign-in:
5
+ // `repown fix` (a config edit), GCM's github.com login (the user signs in, repown sees
6
+ // nothing), the SSO page (the user approves it; repown only waits), `repown use` (a config
7
+ // edit). Everything else stays printed advice.
8
+ import { isGcm } from './credential/gcm.js';
9
+ import { isGh } from './credential/gh.js';
10
+ /** Null when there is nothing repown can run for this verdict. */
11
+ export function repairFor(verdict, ctx) {
12
+ if (verdict.kind === 'sso')
13
+ return { kind: 'sso', link: verdict.link };
14
+ if (verdict.kind === 'rejected' || verdict.kind === 'no-sign-in')
15
+ return signInRepair(ctx);
16
+ return verdict.kind === 'denied' ? deniedRepair(verdict.as, ctx) : null;
17
+ }
18
+ /**
19
+ * Signed in as another account: `repown use` helps only where it changes the username git
20
+ * sends (HTTPS, not the URL's own); when git already sends the pinned one, the stored token is
21
+ * someone else's, so sign in again. Over SSH the key decides, and nothing here changes it.
22
+ */
23
+ function deniedRepair(as, ctx) {
24
+ const same = (a, b) => a.toLowerCase() === b.toLowerCase();
25
+ if (ctx.fromUrl || !ctx.pinned || !as || same(as, ctx.pinned) || !ctx.account)
26
+ return null;
27
+ return same(ctx.account, ctx.pinned) ? signInRepair(ctx) : { kind: 'use', account: ctx.pinned };
28
+ }
29
+ function signInRepair(ctx) {
30
+ if (isGh(ctx.helper))
31
+ return { kind: 'fix' };
32
+ // A username in the URL is the blocker to remove, never an account to sign in as.
33
+ return isGcm(ctx.helper) && ctx.github && ctx.account && !ctx.fromUrl ? { kind: 'login', account: ctx.account } : null;
34
+ }
35
+ /**
36
+ * The question before running it, or null when the repair asks its own: `repown fix` shows
37
+ * which entries it removes, in which file, before its own question (default No). The SSO
38
+ * repair asks nothing and waits instead.
39
+ */
40
+ export function repairQuestion(repair) {
41
+ switch (repair.kind) {
42
+ case 'fix': return null;
43
+ case 'login': return 'Sign in to GitHub as ' + repair.account + ' now? (Git Credential Manager opens your browser)';
44
+ case 'use': return 'Pin ' + repair.account + ' to this clone again now?';
45
+ }
46
+ }
47
+ /** What the SSO wait says: the link is printed with the verdict above it. */
48
+ export const SSO_WAIT = 'Authorise the sign-in in your browser (the link above), then press Enter to check again; type q to stop.';
49
+ /** An SSO wait may repeat (the user decides when it's done); any other repair is tried once. */
50
+ export function triedOnce(repair) {
51
+ return repair.kind === 'sso' ? null : repair.kind + ':' + ('account' in repair ? repair.account : '');
52
+ }
package/dist/ui/help.js CHANGED
@@ -13,7 +13,7 @@ export function renderTopHelp(entries) {
13
13
  ...globalOptionsHelp(),
14
14
  ...environmentHelp(),
15
15
  ' Exit codes: 0 success, 1 failure or refusal, 2 usage error,',
16
- ' 130 cancelled (setup, the start screen).',
16
+ ' 3 not checked (doctor --online), 130 cancelled (setup, the start screen).',
17
17
  '',
18
18
  ];
19
19
  }
package/dist/ui/prompt.js CHANGED
@@ -29,15 +29,35 @@ export async function ask(label, suggestion) {
29
29
  rl.close();
30
30
  }
31
31
  }
32
- export async function confirm(question) {
33
- if (!interactive())
34
- return false;
32
+ /** One question; null when the user pressed Ctrl-C or the input ended, which every caller takes as a stop. */
33
+ async function answerOf(question) {
35
34
  const rl = createInterface({ input: process.stdin, output: process.stderr });
35
+ const ended = new Promise((resolve) => rl.once('close', () => resolve(null)));
36
36
  try {
37
- const answer = (await rl.question(' ' + question + ' [y/N] ')).trim().toLowerCase();
38
- return answer === 'y' || answer === 'yes';
37
+ return await Promise.race([rl.question(question), ended]);
38
+ }
39
+ catch (error) {
40
+ if (error.name === 'AbortError')
41
+ return null;
42
+ throw new Error('the question could not be asked', { cause: error });
39
43
  }
40
44
  finally {
41
45
  rl.close();
42
46
  }
43
47
  }
48
+ /** y or n; an empty answer is `fallback` (No unless the caller says the step is recommended). */
49
+ export async function confirm(question, fallback = false) {
50
+ if (!interactive())
51
+ return false;
52
+ const answer = (await answerOf(' ' + question + (fallback ? ' [Y/n] ' : ' [y/N] ')))?.trim().toLowerCase();
53
+ if (answer === undefined)
54
+ return false;
55
+ return answer === '' ? fallback : answer === 'y' || answer === 'yes';
56
+ }
57
+ /** Waits for Enter; false when the user types q or Ctrl-C (or there is no terminal to wait in). */
58
+ export async function waitForEnter(message) {
59
+ if (!interactive())
60
+ return false;
61
+ const answer = await answerOf(' ' + message + ' ');
62
+ return answer !== null && answer.trim().toLowerCase() !== 'q';
63
+ }
@@ -27,6 +27,8 @@ import { blockers } from '../core/blockers.js';
27
27
  import { readPushFacts } from '../core/push-state.js';
28
28
  import { guardStateAt, hookLocation } from '../core/guard/hook.js';
29
29
  import { readUnpushed } from '../core/unpushed.js';
30
+ import { interactive } from '../ui/prompt.js';
31
+ import { signInAfterSetup, signInRefused, signInSuffix, terminalSignIn } from './setup-signin.js';
30
32
  const CANCELLED = 130;
31
33
  export async function runSetup(args, deps) {
32
34
  const registry = await readRegistry();
@@ -49,6 +51,7 @@ export async function runSetup(args, deps) {
49
51
  args, git, given: given.value, prompter, accountKind: deps.accountKind, readAuth: deps.auth ?? inspectAuth,
50
52
  ...(deps.preview ? { preview: deps.preview } : {}),
51
53
  ...(deps.lead === undefined ? {} : { lead: deps.lead }),
54
+ signIn: unattended ? null : deps.signIn !== undefined ? deps.signIn : interactive() ? terminalSignIn(args) : null,
52
55
  });
53
56
  }
54
57
  finally {
@@ -60,7 +63,7 @@ function notARepo(git) {
60
63
  out.detail('run it inside a clone: cd path/to/repo, then repown setup');
61
64
  return 1;
62
65
  }
63
- async function continueSetup({ args, git, given, prompter, accountKind, readAuth, preview, lead }) {
66
+ async function continueSetup({ args, git, given, prompter, accountKind, readAuth, preview, lead, signIn }) {
64
67
  prompter?.intro?.('repown setup');
65
68
  drawLead(prompter, lead);
66
69
  prompter?.busy?.('Reading this clone and this machine');
@@ -74,7 +77,7 @@ async function continueSetup({ args, git, given, prompter, accountKind, readAuth
74
77
  return answers.error;
75
78
  if (!prompter)
76
79
  return runUnattended(answers.value, ctx.value, git, readAuth);
77
- return runGuided(answers.value, ctx.value, { git, prompter, readAuth });
80
+ return runGuided(answers.value, ctx.value, { git, prompter, readAuth, signIn });
78
81
  }
79
82
  /** The bare-repown sentence, inside the frame when the prompter can draw it. */
80
83
  function drawLead(prompter, lead) {
@@ -189,21 +192,34 @@ async function runUnattended(answers, ctx, git, readAuth) {
189
192
  }
190
193
  async function runGuided(given, ctx, guided) {
191
194
  const outcome = await wizard(setupFlow(ctx), ctx, given, guided.prompter);
192
- if (outcome.status === 'done') {
193
- guided.prompter.outro?.('Nothing changed: this clone was already set up');
194
- return 0;
195
- }
195
+ if (outcome.status === 'done')
196
+ return settled(guided);
196
197
  if (outcome.status !== 'run')
197
198
  return stoppedBefore(outcome.status, guided.prompter);
198
199
  return runAccepted(outcome.answers, ctx, guided);
199
200
  }
200
- async function runAccepted(answers, ctx, { git, prompter, readAuth }) {
201
+ /** Already set up: nothing to run, and the sign-in check is still offered (ADR-032). */
202
+ async function settled({ git, prompter, signIn }) {
203
+ prompter.outro?.('Nothing changed: this clone was already set up');
204
+ if (!signIn)
205
+ return 0;
206
+ prompter.close();
207
+ const online = await signInAfterSetup(signIn, git);
208
+ if (online)
209
+ out.detail(signInLine(online));
210
+ return 0;
211
+ }
212
+ function signInLine(online) {
213
+ const refused = signInRefused(online);
214
+ return refused ? out.marked('warn', process.stderr, refused) : out.marked('ok', process.stderr, 'set up' + signInSuffix(online));
215
+ }
216
+ async function runAccepted(answers, ctx, { git, prompter, readAuth, signIn }) {
201
217
  prompter.outro?.('Running the commands');
202
218
  const confirm = gateFor(prompter, answers, ctx);
203
219
  // Recommended hands the terminal over now. Step by step keeps it for each question.
204
220
  if (!confirm)
205
221
  prompter.close();
206
- const state = { ...runState(git, readAuth, ctx), ...reported(answers, ctx, !ghNoted(answers, ctx)) };
222
+ const state = { ...runState(git, readAuth, ctx), ...reported(answers, ctx, !ghNoted(answers, ctx)), signIn, release: () => prompter.close() };
207
223
  const code = await execute(planCommands(answers, ctx), confirm ? { ...state, confirm } : state);
208
224
  if (confirm)
209
225
  prompter.close();
@@ -264,7 +280,9 @@ function reported(answers, ctx, repeatGh) {
264
280
  async function execute(plan, state) {
265
281
  const before = await readCloneSnapshot(state.git, state.watchedKeys);
266
282
  const ran = await walk(plan, state.git, state.confirm);
267
- await reportRun(before, ran, state);
283
+ const end = ran.code === null ? await endOf(ran.done, state) : null;
284
+ const online = end && !end.found.some((blocker) => blocker.blocks) ? await onlineAfter(state) : null;
285
+ await reportRun(before, ran, state, { end, online });
268
286
  return ran.code ?? 0;
269
287
  }
270
288
  async function walk(plan, git, confirm) {
@@ -328,22 +346,32 @@ function halt(remaining, code, why) {
328
346
  out.detail(' ' + out.accent(process.stderr, formatCommand(planned.argv)));
329
347
  return code;
330
348
  }
349
+ async function endOf(done, state) {
350
+ const pinned = done.find((planned) => planned.argv[0] === 'use')?.argv.at(-1);
351
+ const account = pinned ?? (state.pinnedAlready ? state.account : null);
352
+ return account ? { account, found: await blockersNow(state.git, account) } : null;
353
+ }
354
+ /** The last step: the prompter gives the terminal back first, since the check may hand it on. */
355
+ async function onlineAfter(state) {
356
+ if (!state.signIn)
357
+ return null;
358
+ state.release?.();
359
+ return signInAfterSetup(state.signIn, state.git);
360
+ }
331
361
  /** On stderr, like the step lines: stdout carries only what the commands themselves print. */
332
- async function reportRun(before, ran, state) {
362
+ async function reportRun(before, ran, state, end) {
333
363
  if (ran.code === null)
334
- await announce(ran.done, ran.skipped, state);
364
+ announce(ran.skipped, end);
335
365
  await printClone(before, state);
336
366
  const auth = wantsAuth(ran, state) ? await state.readAuth(state.git) : null;
337
367
  printMachine(ran.done, auth);
338
368
  if (ran.code === null)
339
369
  closeRun(auth, state);
340
370
  }
341
- async function announce(done, skipped, state) {
371
+ function announce(skipped, { end, online }) {
342
372
  process.stderr.write('\n');
343
- const pinned = done.find((planned) => planned.argv[0] === 'use')?.argv.at(-1);
344
- const account = pinned ?? (state.pinnedAlready ? state.account : null);
345
- if (account)
346
- closing(account, await blockersNow(state.git, account));
373
+ if (end)
374
+ closing(end, online);
347
375
  for (const planned of skipped)
348
376
  out.detail('skipped: ' + printable(planned.what));
349
377
  }
@@ -351,12 +379,17 @@ async function announce(done, skipped, state) {
351
379
  * `done` only with nothing left in the way of the next push; otherwise the first, then each one
352
380
  * (ADR-026). What blocks nothing (the guard is off) still gets its lines, under `done`.
353
381
  */
354
- function closing(account, found) {
382
+ function closing({ account, found }, online) {
355
383
  const blocking = found.filter((blocker) => blocker.blocks);
356
384
  const more = blocking.length > 1 ? ' (and ' + (blocking.length - 1) + ' more below)' : '';
357
385
  const [first] = blocking;
358
- out.detail(first ? out.marked('warn', process.stderr, 'set up for ' + printable(account) + '; the next push will fail: ' + printable(first.summary) + more)
359
- : out.marked('ok', process.stderr, 'done: this clone is set up for ' + printable(account)));
386
+ const refused = signInRefused(online);
387
+ if (first)
388
+ out.detail(out.marked('warn', process.stderr, 'set up for ' + printable(account) + '; the next push will fail: ' + printable(first.summary) + more));
389
+ else if (refused)
390
+ out.detail(out.marked('warn', process.stderr, 'set up for ' + printable(account) + '; ' + printable(refused)));
391
+ else
392
+ out.detail(out.marked('ok', process.stderr, 'done: this clone is set up for ' + printable(account) + signInSuffix(online)));
360
393
  // A mark pushes the closing words two columns right; the blockers stay two deeper still.
361
394
  const indent = useColour(process.stderr) ? ' ' : ' ';
362
395
  for (const line of found.flatMap((blocker) => blocker.lines))
@@ -0,0 +1,55 @@
1
+ // Setup's last step (ADR-032): once the clone is set up with nothing in the way of the next
2
+ // push, ask whether to check the sign-in with the remote, and run doctor --online's check and
3
+ // guided repair if so. Terminal only, never under --no-input. The answer joins setup's closing
4
+ // line, so setup says "done" with the sign-in checked, or says what is left.
5
+ import { inspectRepo } from '../core/inspect.js';
6
+ import { gitFor } from '../ui/args.js';
7
+ import { confirm } from '../ui/prompt.js';
8
+ import { printable } from '../ui/format.js';
9
+ import { checkOnline } from '../commands/doctor-online.js';
10
+ import { guideSignIn } from '../commands/signin-guide.js';
11
+ import { terminalIo } from '../commands/signin-terminal.js';
12
+ /** Why there is no push to try yet: the closing line says it, so a skip never reads as a pass. */
13
+ export const NO_COMMIT = 'no commit to try a push with yet';
14
+ export const NO_REMOTE = 'no remote to ask yet';
15
+ export const SIGNIN_QUESTION = 'Check the sign-in with the remote now? (one dry-run push: nothing is sent)';
16
+ export function terminalSignIn(args) {
17
+ return {
18
+ offer: () => confirm(SIGNIN_QUESTION, true),
19
+ check: () => {
20
+ let first = true;
21
+ const once = async () => {
22
+ const repo = await inspectRepo(gitFor(args));
23
+ const pinned = repo.identity.owner ?? repo.identity.account;
24
+ const result = await checkOnline(repo, pinned, first);
25
+ first = false;
26
+ return result;
27
+ };
28
+ return guideSignIn(once, terminalIo(args));
29
+ },
30
+ };
31
+ }
32
+ /** Skipped, with the reason, when there is nothing to ask with: no commit, or no remote. */
33
+ export async function signInAfterSetup(step, git) {
34
+ if (await git.revParse('HEAD') === null)
35
+ return { kind: 'skipped', why: NO_COMMIT };
36
+ const remotes = await git.readRemotes();
37
+ if (!remotes.ok || remotes.value.length === 0)
38
+ return { kind: 'skipped', why: NO_REMOTE };
39
+ if (!await step.offer())
40
+ return { kind: 'declined' };
41
+ return { kind: 'checked', check: await step.check() };
42
+ }
43
+ /** What the closing line adds; a refusal is said instead of "done" (closingWords). */
44
+ export function signInSuffix(outcome) {
45
+ if (!outcome)
46
+ return '';
47
+ if (outcome.kind === 'skipped')
48
+ return ' · sign-in not checked online (' + outcome.why + ')';
49
+ if (outcome.kind === 'declined' || outcome.check.level === 'warn')
50
+ return ' · sign-in not checked online';
51
+ return outcome.check.level === 'pass' ? ' · ' + printable(outcome.check.remote) + ' accepts the sign-in' : '';
52
+ }
53
+ export function signInRefused(outcome) {
54
+ return outcome?.kind === 'checked' && outcome.check.level === 'fail' ? printable(outcome.check.remote) + ' refused the sign-in (above)' : null;
55
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "repown",
3
- "version": "0.5.5",
3
+ "version": "0.7.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "repown",
9
- "version": "0.5.5",
9
+ "version": "0.7.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.5",
3
+ "version": "0.7.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",