dsh-git-branch-manage 1.0.6 → 1.0.8

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/lib/git.js CHANGED
@@ -521,9 +521,11 @@ export function accelArgs(prefix) {
521
521
  * @param repoRoot - main worktree directory (fetch is repository-wide).
522
522
  * @param accelPrefix - optional cn-accelerate mirror prefix (see
523
523
  * {@link accelArgs}); only the READ half of the network commands gets it.
524
+ * @param authArgs - optional per-host credential `-c` pairs (see
525
+ * `credentials.ts`); prepended before the subcommand like the accel rewrite.
524
526
  */
525
- export async function fetchAll(exec, repoRoot, accelPrefix) {
526
- await git(exec, repoRoot, [...accelArgs(accelPrefix), 'fetch', '--all', '--prune'], NETWORK_TIMEOUT_MS);
527
+ export async function fetchAll(exec, repoRoot, accelPrefix, authArgs = []) {
528
+ await git(exec, repoRoot, [...accelArgs(accelPrefix), ...authArgs, 'fetch', '--all', '--prune'], NETWORK_TIMEOUT_MS);
527
529
  }
528
530
  /**
529
531
  * Update the CURRENT checkout: fetch every remote, then fast-forward the
@@ -541,8 +543,8 @@ export async function fetchAll(exec, repoRoot, accelPrefix) {
541
543
  * @returns the branch name and whether HEAD actually moved (false = the
542
544
  * upstream already contained it).
543
545
  */
544
- export async function updateBranch(exec, cwd, accelPrefix) {
545
- await fetchAll(exec, cwd, accelPrefix);
546
+ export async function updateBranch(exec, cwd, accelPrefix, authArgs = []) {
547
+ await fetchAll(exec, cwd, accelPrefix, authArgs);
546
548
  const before = (await git(exec, cwd, ['rev-parse', 'HEAD'])).trim();
547
549
  await git(exec, cwd, ['merge', '--ff-only', '@{u}']);
548
550
  const after = (await git(exec, cwd, ['rev-parse', 'HEAD'])).trim();
@@ -567,17 +569,156 @@ export async function updateBranch(exec, cwd, accelPrefix) {
567
569
  * without an upstream can still be handed to `git push`, so Git's own
568
570
  * push-specific diagnostic is preserved; in that case `pushed` is false.
569
571
  */
570
- export async function pushBranch(exec, cwd) {
572
+ export async function pushBranch(exec, cwd, authArgs = []) {
571
573
  const before = await gitMaybe(exec, cwd, ['rev-parse', '@{u}']);
572
- await git(exec, cwd, ['push'], NETWORK_TIMEOUT_MS);
574
+ await git(exec, cwd, [...authArgs, 'push'], NETWORK_TIMEOUT_MS);
573
575
  const after = await gitMaybe(exec, cwd, ['rev-parse', '@{u}']);
574
576
  const branch = (await gitMaybe(exec, cwd, ['branch', '--show-current']))?.trim() ?? '';
575
577
  return { branch, pushed: before !== undefined && after !== undefined && before.trim() !== after.trim() };
576
578
  }
579
+ /** Every LOCAL tag name of the repository, in git's own sort order. */
580
+ export async function listTagNames(exec, cwd) {
581
+ const text = await git(exec, cwd, ['for-each-ref', 'refs/tags', '--format=%(refname:short)']);
582
+ return text.split('\n').map(line => line.trim()).filter(line => line !== '');
583
+ }
584
+ /**
585
+ * Pick the remote ONE tag push goes to, in fallback order: the checked-out
586
+ * branch's upstream remote, `remote.pushDefault`, then the only remote there
587
+ * is. Ambiguity is reported instead of guessed — a tag pushed to the wrong
588
+ * remote is a published mistake, not an inconvenience.
589
+ * @param exec - executor seam.
590
+ * @param cwd - directory whose checked-out branch supplies the upstream.
591
+ * @returns the remote name, or the caller-side reason none could be chosen.
592
+ */
593
+ export async function resolvePushRemote(exec, cwd) {
594
+ const upstream = (await gitMaybe(exec, cwd, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']))?.trim() ?? '';
595
+ const slash = upstream.indexOf('/');
596
+ if (slash > 0)
597
+ return { ok: true, remote: upstream.slice(0, slash) };
598
+ const pushDefault = (await gitMaybe(exec, cwd, ['config', '--get', 'remote.pushDefault']))?.trim() ?? '';
599
+ if (pushDefault !== '')
600
+ return { ok: true, remote: pushDefault };
601
+ const remotes = ((await gitMaybe(exec, cwd, ['remote'])) ?? '')
602
+ .split('\n').map(line => line.trim()).filter(line => line !== '');
603
+ const only = remotes.length === 1 ? remotes[0] : undefined;
604
+ if (only !== undefined)
605
+ return { ok: true, remote: only };
606
+ return { ok: false, message: remotes.length === 0
607
+ ? 'no remote to push the tag to: the current branch has no upstream and the repository has none either'
608
+ : `multiple remotes (${remotes.join(', ')}) and the current branch has no upstream: set one, or git config remote.pushDefault <name>` };
609
+ }
610
+ /**
611
+ * Push ONE existing local tag to `remote` (`git push <remote>
612
+ * refs/tags/<name>:refs/tags/<name>`) — the publish step a tag needs and a
613
+ * branch push never performs: `git push` sends the current branch alone, so a
614
+ * tag made on an already-pushed commit is invisible to the remote.
615
+ *
616
+ * The tag must already exist locally (the route verifies it against
617
+ * {@link listTagNames}); a remote that already carries the SAME tag object is
618
+ * reported as `pushed: false` without running the push at all. The refspec
619
+ * always names both sides explicitly, so no configured push refspec (a mirror,
620
+ * a `push.default=upstream` branch) can widen what a menu click publishes, and
621
+ * tags are never deleted or overwritten: `--force` is deliberately absent, and
622
+ * a remote tag pointing somewhere else makes git refuse (mapped to 400).
623
+ *
624
+ * The cn-accelerate rewrite is never injected here (no {@link accelArgs}
625
+ * parameter exists, like {@link pushBranch}): a mirror has no `receive-pack` —
626
+ * and the pre-push probe must see the very remote the push targets, or the
627
+ * `pushed` flag would compare two different servers.
628
+ * @param exec - executor seam.
629
+ * @param cwd - any directory inside the repository (tag refs are shared).
630
+ * @param name - an existing local tag name.
631
+ * @param remote - the remote to publish to (see {@link resolvePushRemote}).
632
+ * @returns the tag, the remote, and whether the push had to run.
633
+ */
634
+ export async function pushTag(exec, cwd, name, remote, authArgs = []) {
635
+ const ref = `refs/tags/${name}`;
636
+ const local = (await git(exec, cwd, ['rev-parse', '--verify', ref])).trim();
637
+ const listed = await gitMaybe(exec, cwd, [...authArgs, 'ls-remote', '--refs', remote, ref], NETWORK_TIMEOUT_MS);
638
+ const present = (listed ?? '').split('\n')
639
+ .map(line => line.trim().split(/\s+/)[0] ?? '')
640
+ .includes(local);
641
+ if (present)
642
+ return { tag: name, remote, pushed: false };
643
+ await git(exec, cwd, [...authArgs, 'push', remote, `${ref}:${ref}`], NETWORK_TIMEOUT_MS);
644
+ return { tag: name, remote, pushed: true };
645
+ }
577
646
  /** Guard for route inputs: a non-empty absolute directory path. */
578
647
  export function isAbsoluteDir(value) {
579
648
  return value.trim() !== '' && isAbsolute(value);
580
649
  }
650
+ /**
651
+ * Every configured remote of the repository (`git remote -v`), with the fetch
652
+ * and push URLs git would actually use. A remote with only one side set
653
+ * mirrors that URL into both fields — git falls back to it the same way.
654
+ * @param exec - executor seam.
655
+ * @param cwd - any directory inside the repository.
656
+ */
657
+ export async function listRemotes(exec, cwd) {
658
+ const text = await git(exec, cwd, ['remote', '-v']);
659
+ const byName = new Map();
660
+ for (const line of text.split('\n')) {
661
+ // `git remote -v` separates the name from `<url> (fetch|push)` with a tab;
662
+ // splitting there keeps a local-path URL with spaces intact.
663
+ const tab = line.indexOf('\t');
664
+ if (tab <= 0)
665
+ continue;
666
+ const name = line.slice(0, tab).trim();
667
+ const rest = line.slice(tab + 1).trim();
668
+ const match = /^(.*)\s+\((fetch|push)\)$/.exec(rest);
669
+ if (name === '' || match === null)
670
+ continue;
671
+ const url = (match[1] ?? '').trim();
672
+ const entry = byName.get(name) ?? {};
673
+ if (match[2] === 'fetch')
674
+ entry.fetchUrl = url;
675
+ else
676
+ entry.pushUrl = url;
677
+ byName.set(name, entry);
678
+ }
679
+ return [...byName.entries()]
680
+ .map(([name, urls]) => ({
681
+ name,
682
+ fetchUrl: urls.fetchUrl ?? urls.pushUrl ?? '',
683
+ pushUrl: urls.pushUrl ?? urls.fetchUrl ?? '',
684
+ }))
685
+ .sort((left, right) => left.name.localeCompare(right.name));
686
+ }
687
+ /**
688
+ * Register a new remote (`git remote add`). The name/URL were validated by
689
+ * the route; git still refuses a duplicate name — its stderr rides the
690
+ * GitError, mapped to 400 for the caller.
691
+ * @param exec - executor seam.
692
+ * @param cwd - any directory inside the repository.
693
+ * @param name - the new remote name.
694
+ * @param url - its URL (fetch and push; a push URL is not set apart).
695
+ */
696
+ export async function addRemote(exec, cwd, name, url) {
697
+ await git(exec, cwd, ['remote', 'add', name, url]);
698
+ }
699
+ /**
700
+ * Re-point an existing remote's fetch AND push URL (`git remote set-url`).
701
+ * Deliberately both: a separate push URL would survive as a stale target the
702
+ * UI cannot show, so the panel keeps one address per remote.
703
+ * @param exec - executor seam.
704
+ * @param cwd - any directory inside the repository.
705
+ * @param name - an existing remote name.
706
+ * @param url - the new URL.
707
+ */
708
+ export async function setRemoteUrl(exec, cwd, name, url) {
709
+ await git(exec, cwd, ['remote', 'set-url', name, url]);
710
+ await git(exec, cwd, ['remote', 'set-url', '--push', name, url]);
711
+ }
712
+ /**
713
+ * Forget one remote (`git remote remove`): deletes its remote-tracking refs
714
+ * and its config section, never the objects the local branches share.
715
+ * @param exec - executor seam.
716
+ * @param cwd - any directory inside the repository.
717
+ * @param name - an existing remote name.
718
+ */
719
+ export async function removeRemote(exec, cwd, name) {
720
+ await git(exec, cwd, ['remote', 'remove', name]);
721
+ }
581
722
  /**
582
723
  * Inspect one worktree directory for removal: how many files carry
583
724
  * uncommitted changes (those ARE lost with the folder), and how many commits
package/lib/index.js CHANGED
@@ -9,9 +9,10 @@ import { homedir } from 'node:os';
9
9
  import z from '@deepseek-ai/schemastery';
10
10
  import { childProcessExec } from './git.js';
11
11
  import { ACCEL_DEFAULT_URL, accelerateUrlError } from './normalize.js';
12
- import { handleAiCommitMessage, handleChanges, handleCommit, handleCommitFiles, handleCreateBranch, handleCreateTag, handleCreateWorktree, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleInspectWorktree, handleLog, handlePathExists, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleStage, handleStatus, handleSwitch, handleUpdate, handlePush, handleWorktreesAll, } from './routes.js';
12
+ import { handleCredentials, handleCredentialsDelete, handleCredentialsOAuthPoll, handleCredentialsOAuthStart, handleCredentialsSave, handleRemote, handleRemotes, handleAiCommitMessage, handleChanges, handleCommit, handleCommitFiles, handleCreateBranch, handleCreateTag, handleCreateWorktree, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleInspectWorktree, handleLog, handlePathExists, handlePurgeDirectory, handlePushTag, handleRemoveWorktree, handleRenameBranch, handleStage, handleStatus, handleSwitch, handleUpdate, handlePush, handleWorktreesAll, } from './routes.js';
13
13
  import { validateRootDir } from './settings.js';
14
- import { ROUTE_AI_COMMIT_MESSAGE, ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_CHANGES, ROUTE_COMMIT, ROUTE_COMMIT_FILES, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_INSPECT, ROUTE_LOG, ROUTE_PUSH, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_STAGE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_TAG, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
14
+ import { gitCredentialsTool } from './tool.js';
15
+ import { ROUTE_AI_COMMIT_MESSAGE, ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_CHANGES, ROUTE_COMMIT, ROUTE_COMMIT_FILES, ROUTE_CREDENTIALS, ROUTE_CREDENTIALS_DELETE, ROUTE_CREDENTIALS_OAUTH_POLL, ROUTE_CREDENTIALS_OAUTH_START, ROUTE_CREDENTIALS_SAVE, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_INSPECT, ROUTE_LOG, ROUTE_PUSH, ROUTE_PURGE, ROUTE_REMOTE, ROUTE_REMOTES, ROUTE_REMOVE, ROUTE_STAGE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_TAG, ROUTE_TAG_PUSH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
15
16
  export const name = 'dsh-git-branch';
16
17
  export const inject = [];
17
18
  /** Largest accepted request body (bytes) — these payloads are a few strings. */
@@ -155,6 +156,14 @@ export function apply(ctx, config = {}) {
155
156
  ctx.inject(['settings'], (settingsCtx) => {
156
157
  settingsCtx.effect(() => settingsCtx.settings.configure({ auto: false }, ctx.fiber), 'git-worktree: settings presentation policy');
157
158
  });
159
+ // Model-facing, read-only view of the same global credential store the
160
+ // routes use. A session asked to push can check which hosts already have a
161
+ // key instead of guessing; the tool never writes and masks the secret
162
+ // unless the user explicitly asked to see it.
163
+ ctx.inject(['tools'], (toolsCtx) => {
164
+ const tools = toolsCtx.tools;
165
+ toolsCtx.effect(() => tools.register(gitCredentialsTool({ home: () => homedir(), envHome: () => process.env.DSH_HOME })), 'git-worktree: git_credentials tool');
166
+ });
158
167
  ctx.inject(['webServer'], (webCtx) => {
159
168
  /** Send one outcome as JSON; no-store because repo facts are point-in-time. */
160
169
  const send = (res, outcome) => {
@@ -228,6 +237,18 @@ export function apply(ctx, config = {}) {
228
237
  postRoute(ROUTE_LOG, 'log', handleLog);
229
238
  postRoute(ROUTE_COMMIT_FILES, 'commit-files', handleCommitFiles);
230
239
  postRoute(ROUTE_TAG, 'tag', handleCreateTag);
240
+ postRoute(ROUTE_TAG_PUSH, 'tag-push', handlePushTag);
241
+ // Credentials are GLOBAL (one row per host, keyed by the remote host),
242
+ // not per repository: the same github.com token serves every checkout.
243
+ postRoute(ROUTE_CREDENTIALS, 'credentials', handleCredentials);
244
+ postRoute(ROUTE_CREDENTIALS_SAVE, 'credentials-save', handleCredentialsSave);
245
+ postRoute(ROUTE_CREDENTIALS_DELETE, 'credentials-delete', handleCredentialsDelete);
246
+ // Browser sign-in (GitHub device flow): start returns the one-time code,
247
+ // poll stores the token and answers the fresh masked list.
248
+ postRoute(ROUTE_CREDENTIALS_OAUTH_START, 'credentials-oauth-start', handleCredentialsOAuthStart);
249
+ postRoute(ROUTE_CREDENTIALS_OAUTH_POLL, 'credentials-oauth-poll', handleCredentialsOAuthPoll);
250
+ postRoute(ROUTE_REMOTES, 'remotes', handleRemotes);
251
+ postRoute(ROUTE_REMOTE, 'remote', handleRemote);
231
252
  // The AI commit-message route exists only where the host tree provides
232
253
  // the dsh-llm service: the injection resolves once the service is up and
233
254
  // never fires without it, so an llm-less deployment answers 404 and the
@@ -81,3 +81,27 @@ export declare function accelerateUrlError(value: string): AccelerateUrlIssue |
81
81
  * @returns the prefix ending in `/`.
82
82
  */
83
83
  export declare function normalizeAccelerateUrl(value: string): string;
84
+ /** Why a user-typed REMOTE name is not acceptable yet (null = fine). */
85
+ export type RemoteNameIssue = 'empty' | 'leadingDash' | 'illegal';
86
+ /**
87
+ * Pre-flight check of a remote name: non-empty; no leading `-` (git would
88
+ * parse it as a flag); letters, digits, `.`, `_` and `-` only (`/`, space and
89
+ * `~^:?*[\` are outside what a remote name can be typed as here); the lone
90
+ * `.`/`..` are rejected. Git stays the authority — a miss surfaces through
91
+ * the error envelope — this only feeds immediate form feedback.
92
+ * @param name - raw draft text.
93
+ * @returns the issue kind, or null when acceptable.
94
+ */
95
+ export declare function remoteNameIssue(name: string): RemoteNameIssue | null;
96
+ /** Why a user-typed REMOTE URL is not acceptable yet (undefined = fine). */
97
+ export type RemoteUrlIssue = 'empty' | 'whitespace' | 'invalid';
98
+ /**
99
+ * Pre-flight check of a remote URL. Accepted shapes: any `scheme://…` URL
100
+ * (`https://`, `ssh://`, `git://`, `file://`), an scp-like
101
+ * `user@host:path`, and an absolute local path (a legitimate `file` remote).
102
+ * Everything else — a bare word, a URL with stray whitespace, a value git
103
+ * would read as a flag — is rejected. Git validates the remote once added.
104
+ * @param url - raw draft text.
105
+ * @returns the issue kind, or undefined when acceptable.
106
+ */
107
+ export declare function remoteUrlIssue(url: string): RemoteUrlIssue | undefined;
package/lib/normalize.js CHANGED
@@ -126,3 +126,50 @@ export function normalizeAccelerateUrl(value) {
126
126
  const trimmed = value.trim();
127
127
  return trimmed.endsWith('/') ? trimmed : `${trimmed}/`;
128
128
  }
129
+ /**
130
+ * Pre-flight check of a remote name: non-empty; no leading `-` (git would
131
+ * parse it as a flag); letters, digits, `.`, `_` and `-` only (`/`, space and
132
+ * `~^:?*[\` are outside what a remote name can be typed as here); the lone
133
+ * `.`/`..` are rejected. Git stays the authority — a miss surfaces through
134
+ * the error envelope — this only feeds immediate form feedback.
135
+ * @param name - raw draft text.
136
+ * @returns the issue kind, or null when acceptable.
137
+ */
138
+ export function remoteNameIssue(name) {
139
+ if (name.trim() === '')
140
+ return 'empty';
141
+ if (name.startsWith('-'))
142
+ return 'leadingDash';
143
+ if (!/^[A-Za-z0-9._-]+$/.test(name))
144
+ return 'illegal';
145
+ if (name === '.' || name === '..')
146
+ return 'illegal';
147
+ return null;
148
+ }
149
+ /**
150
+ * Pre-flight check of a remote URL. Accepted shapes: any `scheme://…` URL
151
+ * (`https://`, `ssh://`, `git://`, `file://`), an scp-like
152
+ * `user@host:path`, and an absolute local path (a legitimate `file` remote).
153
+ * Everything else — a bare word, a URL with stray whitespace, a value git
154
+ * would read as a flag — is rejected. Git validates the remote once added.
155
+ * @param url - raw draft text.
156
+ * @returns the issue kind, or undefined when acceptable.
157
+ */
158
+ export function remoteUrlIssue(url) {
159
+ const trimmed = url.trim();
160
+ if (trimmed === '')
161
+ return 'empty';
162
+ if (trimmed.startsWith('-'))
163
+ return 'invalid';
164
+ // Local-path remotes may contain spaces (`C:\my repo`), so the path shape
165
+ // is classified before the whitespace rule.
166
+ if (isAbsoluteConfigPath(trimmed))
167
+ return undefined;
168
+ if (/\s/.test(trimmed))
169
+ return 'whitespace';
170
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(trimmed))
171
+ return undefined;
172
+ if (/^[^\s@/]+@[^\s:/]+:\S+$/.test(trimmed))
173
+ return undefined;
174
+ return 'invalid';
175
+ }
package/lib/oauth.d.ts ADDED
@@ -0,0 +1,109 @@
1
+ /**
2
+ * GitHub OAuth device flow behind the credential dialog's site sign-in.
3
+ *
4
+ * A browser sign-in must never need a client SECRET (that would have to ship
5
+ * in the bundle) and must work from a machine that cannot accept inbound
6
+ * connections, so the plugin uses the OAuth 2.0 device authorization grant:
7
+ * the host asks GitHub for a one-time user code, the dialog opens the browser
8
+ * and shows that code, and the plugin polls the token endpoint until the user
9
+ * approves. The token that comes back is stored like a pasted personal access
10
+ * token (method `token`) and the user never sees a raw PAT workflow.
11
+ *
12
+ * Only hosts whose device flow this module knows are accepted; the caller
13
+ * decides which of them to offer in the UI.
14
+ *
15
+ * @module git-worktree/oauth
16
+ */
17
+ /** The hosts whose device flow this module implements. The dialog imports the
18
+ * same list, so the offered buttons cannot drift from what the host supports. */
19
+ export declare const DEVICE_FLOW_HOSTS: readonly string[];
20
+ /**
21
+ * Fallback OAuth App client id. GitHub's device flow requires a client id but
22
+ * never a client secret; the shipped value is the public GitHub CLI app,
23
+ * which lets a stock `gh` install and this plugin sign in with the same app.
24
+ * Point `DSH_GITHUB_OAUTH_CLIENT_ID` at a dedicated OAuth App to use one.
25
+ */
26
+ export declare const DEFAULT_OAUTH_CLIENT_ID = "178c6fc778ccc68e1d6a";
27
+ /** Scopes one push needs: `repo` covers private repositories and write access. */
28
+ export declare const OAUTH_SCOPE = "repo";
29
+ /** One device-code grant, reduced to what the browser needs to show/open. */
30
+ export interface DeviceCodeGrant {
31
+ /** Polling credential; never rendered. */
32
+ deviceCode: string;
33
+ /** The short code the user types on the verification page. */
34
+ userCode: string;
35
+ /** Verification page (without the code). */
36
+ verificationUri: string;
37
+ /** Verification page with the code pre-filled, when GitHub returns one. */
38
+ verificationUriComplete?: string;
39
+ /** Minimum seconds between polls. */
40
+ intervalSeconds: number;
41
+ /** Seconds until the grant expires. */
42
+ expiresInSeconds: number;
43
+ }
44
+ /** One poll answer: the finished token, or why there is no token yet. */
45
+ export type DeviceFlowPoll = {
46
+ status: 'token';
47
+ token: string;
48
+ } | {
49
+ status: 'pending';
50
+ } | {
51
+ status: 'slow_down';
52
+ }
53
+ /** The transport broke (DNS, TLS, reset keep-alive connection): the grant is
54
+ * untouched, so a poll loop should retry instead of ending the sign-in. */
55
+ | {
56
+ status: 'network';
57
+ message: string;
58
+ } | {
59
+ status: 'denied';
60
+ message: string;
61
+ } | {
62
+ status: 'expired';
63
+ message: string;
64
+ } | {
65
+ status: 'failed';
66
+ message: string;
67
+ };
68
+ /**
69
+ * The OAuth App client id to use: the environment override when set, else the
70
+ * shipped default.
71
+ * @param env - environment seam (`process.env` in production).
72
+ */
73
+ export declare function deviceFlowClientId(env?: Readonly<Record<string, string | undefined>>): string;
74
+ /** Whether browser sign-in is implemented for this (normalized) host. */
75
+ export declare function isDeviceFlowHost(host: string): boolean;
76
+ /**
77
+ * A request that never reached the host: DNS failure, TLS interference, or a
78
+ * reset pooled connection. Unlike an OAuth error answer this says nothing
79
+ * about the grant, so the poll loop may retry it.
80
+ */
81
+ export declare class DeviceFlowTransportError extends Error {
82
+ /** The endpoint that could not be reached. */
83
+ readonly url: string;
84
+ /**
85
+ * @param url - the endpoint that could not be reached.
86
+ * @param cause - the underlying fetch failure.
87
+ */
88
+ constructor(url: string, cause: unknown);
89
+ }
90
+ /**
91
+ * Ask GitHub for a device code. The caller opens `verificationUriComplete`
92
+ * (or `verificationUri` plus the shown `userCode`) and then polls.
93
+ * @param fetchImpl - fetch seam (global fetch in production, a fake in tests).
94
+ * @param host - normalized host; must be a {@link DEVICE_FLOW_HOSTS} member.
95
+ * @param clientId - OAuth App client id, see {@link deviceFlowClientId}.
96
+ * @param timeoutMs - per-request budget for the device-code request.
97
+ */
98
+ export declare function startDeviceFlow(fetchImpl: typeof fetch, host: string, clientId: string, timeoutMs?: number): Promise<DeviceCodeGrant>;
99
+ /**
100
+ * Poll the token endpoint once for one grant. GitHub answers `400` with an
101
+ * `error` code until the user acts, so a pending grant is a normal answer,
102
+ * not a thrown failure; only transport problems throw.
103
+ * @param fetchImpl - fetch seam.
104
+ * @param host - normalized host.
105
+ * @param clientId - the same client id the grant was started with.
106
+ * @param deviceCode - the grant's `deviceCode`.
107
+ * @param timeoutMs - per-request budget for this poll.
108
+ */
109
+ export declare function pollDeviceFlow(fetchImpl: typeof fetch, host: string, clientId: string, deviceCode: string, timeoutMs?: number): Promise<DeviceFlowPoll>;
package/lib/oauth.js ADDED
@@ -0,0 +1,182 @@
1
+ /**
2
+ * GitHub OAuth device flow behind the credential dialog's site sign-in.
3
+ *
4
+ * A browser sign-in must never need a client SECRET (that would have to ship
5
+ * in the bundle) and must work from a machine that cannot accept inbound
6
+ * connections, so the plugin uses the OAuth 2.0 device authorization grant:
7
+ * the host asks GitHub for a one-time user code, the dialog opens the browser
8
+ * and shows that code, and the plugin polls the token endpoint until the user
9
+ * approves. The token that comes back is stored like a pasted personal access
10
+ * token (method `token`) and the user never sees a raw PAT workflow.
11
+ *
12
+ * Only hosts whose device flow this module knows are accepted; the caller
13
+ * decides which of them to offer in the UI.
14
+ *
15
+ * @module git-worktree/oauth
16
+ */
17
+ import { BROWSER_SIGN_IN_HOSTS } from './wire.js';
18
+ /** The hosts whose device flow this module implements. The dialog imports the
19
+ * same list, so the offered buttons cannot drift from what the host supports. */
20
+ export const DEVICE_FLOW_HOSTS = BROWSER_SIGN_IN_HOSTS;
21
+ /**
22
+ * Fallback OAuth App client id. GitHub's device flow requires a client id but
23
+ * never a client secret; the shipped value is the public GitHub CLI app,
24
+ * which lets a stock `gh` install and this plugin sign in with the same app.
25
+ * Point `DSH_GITHUB_OAUTH_CLIENT_ID` at a dedicated OAuth App to use one.
26
+ */
27
+ export const DEFAULT_OAUTH_CLIENT_ID = '178c6fc778ccc68e1d6a';
28
+ /** Scopes one push needs: `repo` covers private repositories and write access. */
29
+ export const OAUTH_SCOPE = 'repo';
30
+ /**
31
+ * The OAuth App client id to use: the environment override when set, else the
32
+ * shipped default.
33
+ * @param env - environment seam (`process.env` in production).
34
+ */
35
+ export function deviceFlowClientId(env = process.env) {
36
+ const configured = env.DSH_GITHUB_OAUTH_CLIENT_ID?.trim();
37
+ return configured === undefined || configured === '' ? DEFAULT_OAUTH_CLIENT_ID : configured;
38
+ }
39
+ /** Whether browser sign-in is implemented for this (normalized) host. */
40
+ export function isDeviceFlowHost(host) {
41
+ return DEVICE_FLOW_HOSTS.includes(host);
42
+ }
43
+ /** Read one non-empty string field from a parsed JSON object. */
44
+ function readString(payload, key) {
45
+ const value = payload[key];
46
+ return typeof value === 'string' && value !== '' ? value : undefined;
47
+ }
48
+ /**
49
+ * A request that never reached the host: DNS failure, TLS interference, or a
50
+ * reset pooled connection. Unlike an OAuth error answer this says nothing
51
+ * about the grant, so the poll loop may retry it.
52
+ */
53
+ export class DeviceFlowTransportError extends Error {
54
+ /** The endpoint that could not be reached. */
55
+ url;
56
+ /**
57
+ * @param url - the endpoint that could not be reached.
58
+ * @param cause - the underlying fetch failure.
59
+ */
60
+ constructor(url, cause) {
61
+ super(`${url} could not be reached (${cause instanceof Error ? cause.message : String(cause)})`);
62
+ this.name = 'DeviceFlowTransportError';
63
+ this.url = url;
64
+ }
65
+ }
66
+ /**
67
+ * POST one form-encoded body and parse the JSON answer. Network failures and
68
+ * unexpected non-2xx answers become one thrown Error; callers map it to a
69
+ * route failure. `allowErrorStatus` keeps the body of a documented OAuth
70
+ * error answer (the token endpoint reports a pending grant as `400`), which
71
+ * is an answer, not a transport failure.
72
+ */
73
+ async function postForm(fetchImpl, url, fields, timeoutMs, allowErrorStatus = false) {
74
+ let response;
75
+ try {
76
+ response = await fetchImpl(url, {
77
+ method: 'POST',
78
+ headers: {
79
+ 'content-type': 'application/x-www-form-urlencoded',
80
+ accept: 'application/json',
81
+ },
82
+ body: new URLSearchParams(fields).toString(),
83
+ signal: AbortSignal.timeout(timeoutMs),
84
+ });
85
+ }
86
+ catch (error) {
87
+ throw new DeviceFlowTransportError(url, error);
88
+ }
89
+ let payload;
90
+ let parsed = false;
91
+ try {
92
+ payload = await response.json();
93
+ parsed = true;
94
+ }
95
+ catch {
96
+ parsed = false;
97
+ }
98
+ if (!parsed)
99
+ throw new Error(`${url} answered a non-JSON body`);
100
+ if (!response.ok && !allowErrorStatus)
101
+ throw new Error(`${url} answered HTTP ${String(response.status)}`);
102
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
103
+ throw new Error(`${url} answered an unexpected body`);
104
+ }
105
+ return payload;
106
+ }
107
+ /**
108
+ * Ask GitHub for a device code. The caller opens `verificationUriComplete`
109
+ * (or `verificationUri` plus the shown `userCode`) and then polls.
110
+ * @param fetchImpl - fetch seam (global fetch in production, a fake in tests).
111
+ * @param host - normalized host; must be a {@link DEVICE_FLOW_HOSTS} member.
112
+ * @param clientId - OAuth App client id, see {@link deviceFlowClientId}.
113
+ * @param timeoutMs - per-request budget for the device-code request.
114
+ */
115
+ export async function startDeviceFlow(fetchImpl, host, clientId, timeoutMs = 15_000) {
116
+ const payload = await postForm(fetchImpl, `https://${host}/login/device/code`, { client_id: clientId, scope: OAUTH_SCOPE }, timeoutMs);
117
+ const deviceCode = readString(payload, 'device_code');
118
+ const userCode = readString(payload, 'user_code');
119
+ const verificationUri = readString(payload, 'verification_uri');
120
+ if (deviceCode === undefined || userCode === undefined || verificationUri === undefined) {
121
+ throw new Error(`${host} did not return a device code (is device flow enabled for the OAuth app?)`);
122
+ }
123
+ const interval = typeof payload.interval === 'number' && payload.interval > 0 ? payload.interval : 5;
124
+ const expiresIn = typeof payload.expires_in === 'number' && payload.expires_in > 0 ? payload.expires_in : 900;
125
+ const verificationUriComplete = readString(payload, 'verification_uri_complete');
126
+ return {
127
+ deviceCode,
128
+ userCode,
129
+ verificationUri,
130
+ ...(verificationUriComplete === undefined ? {} : { verificationUriComplete }),
131
+ intervalSeconds: interval,
132
+ expiresInSeconds: expiresIn,
133
+ };
134
+ }
135
+ /**
136
+ * Poll the token endpoint once for one grant. GitHub answers `400` with an
137
+ * `error` code until the user acts, so a pending grant is a normal answer,
138
+ * not a thrown failure; only transport problems throw.
139
+ * @param fetchImpl - fetch seam.
140
+ * @param host - normalized host.
141
+ * @param clientId - the same client id the grant was started with.
142
+ * @param deviceCode - the grant's `deviceCode`.
143
+ * @param timeoutMs - per-request budget for this poll.
144
+ */
145
+ export async function pollDeviceFlow(fetchImpl, host, clientId, deviceCode, timeoutMs = 15_000) {
146
+ let payload;
147
+ try {
148
+ payload = await postForm(fetchImpl, `https://${host}/login/oauth/access_token`, {
149
+ client_id: clientId,
150
+ device_code: deviceCode,
151
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
152
+ }, timeoutMs,
153
+ // A pending grant is a 400 with an OAuth error body, not a failure.
154
+ true);
155
+ }
156
+ catch (error) {
157
+ // A dropped connection says nothing about the grant: report it as a
158
+ // retryable answer so one blip cannot end a sign-in the user already
159
+ // approved in the browser. Any other failure (malformed body, HTTP 5xx)
160
+ // still throws and surfaces as a route error.
161
+ if (error instanceof DeviceFlowTransportError)
162
+ return { status: 'network', message: error.message };
163
+ throw error;
164
+ }
165
+ const token = readString(payload, 'access_token');
166
+ if (token !== undefined)
167
+ return { status: 'token', token };
168
+ const code = readString(payload, 'error') ?? 'unknown_error';
169
+ const description = readString(payload, 'error_description') ?? code;
170
+ switch (code) {
171
+ case 'authorization_pending':
172
+ return { status: 'pending' };
173
+ case 'slow_down':
174
+ return { status: 'slow_down' };
175
+ case 'expired_token':
176
+ return { status: 'expired', message: description };
177
+ case 'access_denied':
178
+ return { status: 'denied', message: description };
179
+ default:
180
+ return { status: 'failed', message: description };
181
+ }
182
+ }