dsh-git-branch-manage 1.1.0 → 1.3.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 +34 -0
- package/lib/client.js +271 -29
- package/lib/credential-service.d.ts +32 -38
- package/lib/credential-service.js +56 -27
- package/lib/credentials.d.ts +145 -40
- package/lib/credentials.js +398 -70
- package/lib/git.d.ts +82 -9
- package/lib/git.js +260 -24
- package/lib/index.d.ts +11 -0
- package/lib/index.js +56 -19
- package/lib/local-import.d.ts +68 -0
- package/lib/local-import.js +151 -0
- package/lib/network-ip.d.ts +99 -0
- package/lib/network-ip.js +206 -0
- package/lib/network-probe.d.ts +28 -0
- package/lib/network-probe.js +47 -0
- package/lib/network-proxy.d.ts +35 -0
- package/lib/network-proxy.js +55 -0
- package/lib/network-tool.d.ts +5 -8
- package/lib/network-tool.js +17 -20
- package/lib/network.d.ts +58 -0
- package/lib/network.js +128 -0
- package/lib/normalize.d.ts +14 -2
- package/lib/normalize.js +38 -2
- package/lib/routes.d.ts +41 -3
- package/lib/routes.js +159 -27
- package/lib/shell-bridge.d.ts +57 -115
- package/lib/shell-bridge.js +96 -170
- package/lib/tool.js +2 -2
- package/lib/wire.d.ts +64 -0
- package/lib/wire.js +5 -0
- package/package.json +1 -1
- package/lib/helpers/git-credential-bridge.d.ts +0 -37
- package/lib/helpers/git-credential-bridge.js +0 -119
package/lib/index.js
CHANGED
|
@@ -8,13 +8,15 @@
|
|
|
8
8
|
import { homedir } from 'node:os';
|
|
9
9
|
import z from '@deepseek-ai/schemastery';
|
|
10
10
|
import { childProcessExec } from './git.js';
|
|
11
|
+
import { pinnedChannelFor, pinnedProbe } from './network-ip.js';
|
|
12
|
+
import { proxyArgs, proxyUrlError, systemProxyUrl } from './network-proxy.js';
|
|
11
13
|
import { ACCEL_DEFAULT_URL, accelerateUrlError } from './normalize.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';
|
|
14
|
+
import { handleCredentials, handleCredentialsDelete, handleCredentialsImport, 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, handleNetworkProbe, handleWorktreesAll, } from './routes.js';
|
|
13
15
|
import { validateRootDir } from './settings.js';
|
|
14
16
|
import { gitNetworkTool } from './network-tool.js';
|
|
15
17
|
import { gitCredentialsTool } from './tool.js';
|
|
16
18
|
import { createCredentialService } from './credential-service.js';
|
|
17
|
-
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';
|
|
19
|
+
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_IMPORT, 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_NETWORK_PROBE, 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';
|
|
18
20
|
export const name = 'dsh-git-branch';
|
|
19
21
|
export const inject = [];
|
|
20
22
|
/** Largest accepted request body (bytes) — these payloads are a few strings. */
|
|
@@ -43,10 +45,11 @@ export const Config = z.object({
|
|
|
43
45
|
postCreateCopyFiles: z.array(z.string()).default([]).volatile(),
|
|
44
46
|
cnAccelerate: z.boolean().default(false).volatile(),
|
|
45
47
|
cnAccelerateUrl: z.string().default(ACCEL_DEFAULT_URL).volatile(),
|
|
48
|
+
networkProxy: z.string().default('').volatile(),
|
|
46
49
|
});
|
|
47
50
|
/** Reject stale or misspelled config keys before defaults can hide them. */
|
|
48
51
|
export function validateConfig(config) {
|
|
49
|
-
const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar' && key !== 'fetchBeforeCreate' && key !== 'autoPruneWorktrees' && key !== 'keepWorktrees' && key !== 'postCreateCopyFiles' && key !== 'cnAccelerate' && key !== 'cnAccelerateUrl');
|
|
52
|
+
const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar' && key !== 'fetchBeforeCreate' && key !== 'autoPruneWorktrees' && key !== 'keepWorktrees' && key !== 'postCreateCopyFiles' && key !== 'cnAccelerate' && key !== 'cnAccelerateUrl' && key !== 'networkProxy');
|
|
50
53
|
if (unknown !== undefined) {
|
|
51
54
|
throw new Error(`GitWorktreeConfig: unknown key "${unknown}"`);
|
|
52
55
|
}
|
|
@@ -77,6 +80,7 @@ export function validateConfig(config) {
|
|
|
77
80
|
throw new Error('GitWorktreeConfig: "cnAccelerate" must be a boolean');
|
|
78
81
|
}
|
|
79
82
|
validateCnAccelerateUrl(readVolatile(config.cnAccelerateUrl));
|
|
83
|
+
validateNetworkProxy(readVolatile(config.networkProxy));
|
|
80
84
|
validateKeepWorktrees(readVolatile(config.keepWorktrees));
|
|
81
85
|
validateRootDir(root);
|
|
82
86
|
}
|
|
@@ -93,6 +97,18 @@ export function validateCnAccelerateUrl(value) {
|
|
|
93
97
|
throw new Error('GitWorktreeConfig: "cnAccelerateUrl" must be an http(s) URL without whitespace');
|
|
94
98
|
}
|
|
95
99
|
}
|
|
100
|
+
/**
|
|
101
|
+
* An explicit proxy must be a URL git can hand to libcurl: no credentials
|
|
102
|
+
* (they would be stored and displayed in clear text), no path. Empty means
|
|
103
|
+
* "no proxy channel", which is the default and always valid.
|
|
104
|
+
*/
|
|
105
|
+
export function validateNetworkProxy(value) {
|
|
106
|
+
if (value === undefined || value === '')
|
|
107
|
+
return;
|
|
108
|
+
if (typeof value !== 'string' || proxyUrlError(value) !== undefined) {
|
|
109
|
+
throw new Error('GitWorktreeConfig: "networkProxy" must be an http(s)/socks5 proxy URL without credentials');
|
|
110
|
+
}
|
|
111
|
+
}
|
|
96
112
|
/**
|
|
97
113
|
* The prune cap must be an integer >= 1: 0 would read as "create then
|
|
98
114
|
* immediately self-delete" (the fresh worktree is excluded, but every other
|
|
@@ -120,10 +136,12 @@ export function sectionOf(config) {
|
|
|
120
136
|
const keepWorktrees = readVolatile(config.keepWorktrees);
|
|
121
137
|
const cnAccelerate = readVolatile(config.cnAccelerate);
|
|
122
138
|
const cnAccelerateUrl = readVolatile(config.cnAccelerateUrl);
|
|
139
|
+
const networkProxy = readVolatile(config.networkProxy);
|
|
123
140
|
return {
|
|
124
141
|
...(rootDir === undefined ? {} : { rootDir }),
|
|
125
142
|
...(postCreateCopyFiles === undefined ? {} : { postCreateCopyFiles }),
|
|
126
143
|
...(cnAccelerateUrl === undefined ? {} : { cnAccelerateUrl }),
|
|
144
|
+
...(networkProxy === undefined || networkProxy === '' ? {} : { networkProxy }),
|
|
127
145
|
// The composition layer spells the shipped defaults so a user-layer
|
|
128
146
|
// unset can always fall back to them.
|
|
129
147
|
groupSidebar: groupSidebar ?? true,
|
|
@@ -142,26 +160,44 @@ export function sectionOf(config) {
|
|
|
142
160
|
export function apply(ctx, config = {}) {
|
|
143
161
|
validateConfig(config);
|
|
144
162
|
const currentConfig = () => ctx.fiber?.config ?? config;
|
|
145
|
-
// Host half of the credential
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
//
|
|
150
|
-
//
|
|
151
|
-
//
|
|
152
|
-
// credential save / delete /
|
|
163
|
+
// Host half of the credential channel (decision 0037): one service owns the
|
|
164
|
+
// store — the machine's own `~/.git-credentials`, i.e. git's
|
|
165
|
+
// `credential-store` file — and installs a URL-scoped `helper = store`
|
|
166
|
+
// include into `~/.gitconfig`. Because that is git's standard channel, a
|
|
167
|
+
// plain `git push` in a spawned shell authenticates with the panel's token,
|
|
168
|
+
// and a host without a stored token fails fast (`GIT_TERMINAL_PROMPT=0`)
|
|
169
|
+
// rather than opening a credential dialog no agent shell can answer.
|
|
170
|
+
// Applied at activate and re-derived after every credential save / delete /
|
|
171
|
+
// sign-in.
|
|
153
172
|
const credentials = createCredentialService({ home: () => homedir(), envHome: () => process.env.DSH_HOME });
|
|
154
|
-
|
|
173
|
+
// Import first, then derive the include: a machine already signed in through
|
|
174
|
+
// gh / GCM / Keychain keeps working without the user re-entering a token
|
|
175
|
+
// (decision 0038). Both steps are opportunistic and never throw.
|
|
176
|
+
void credentials.refreshShellEnv()
|
|
177
|
+
.then(() => credentials.autoImport())
|
|
178
|
+
.catch(() => { });
|
|
155
179
|
ctx.effect(() => () => {
|
|
156
180
|
void credentials.dispose();
|
|
157
181
|
}, 'git-worktree: credential service dispose');
|
|
158
182
|
const deps = () => ({
|
|
159
183
|
exec: childProcessExec,
|
|
184
|
+
networkChannels: (exec, cwd, authArgs) => {
|
|
185
|
+
const providers = [];
|
|
186
|
+
// An explicit proxy outranks the IP heuristic: the user configured it
|
|
187
|
+
// because it is the path they trust. Absent/blank = no proxy channel.
|
|
188
|
+
const proxy = readVolatile(currentConfig().networkProxy);
|
|
189
|
+
if (proxy !== undefined && proxy !== '')
|
|
190
|
+
providers.push(async () => proxyArgs(proxy));
|
|
191
|
+
providers.push(endpoint => pinnedChannelFor({ endpoint, probe: pinnedProbe(exec, cwd, endpoint, authArgs) }));
|
|
192
|
+
return providers;
|
|
193
|
+
},
|
|
160
194
|
sectionRootDir: () => readVolatile(currentConfig().rootDir),
|
|
161
195
|
sectionFetchBeforeCreate: () => readVolatile(currentConfig().fetchBeforeCreate),
|
|
162
196
|
sectionPostCreateCopyFiles: () => readVolatile(currentConfig().postCreateCopyFiles),
|
|
163
197
|
sectionCnAccelerate: () => readVolatile(currentConfig().cnAccelerate),
|
|
164
198
|
sectionCnAccelerateUrl: () => readVolatile(currentConfig().cnAccelerateUrl),
|
|
199
|
+
sectionNetworkProxy: () => readVolatile(currentConfig().networkProxy),
|
|
200
|
+
sectionSystemProxy: () => systemProxyUrl(childProcessExec, homedir()),
|
|
165
201
|
home: () => homedir(),
|
|
166
202
|
envHome: () => process.env.DSH_HOME,
|
|
167
203
|
credentialsService: credentials,
|
|
@@ -180,13 +216,10 @@ export function apply(ctx, config = {}) {
|
|
|
180
216
|
ctx.inject(['tools'], (toolsCtx) => {
|
|
181
217
|
const tools = toolsCtx.tools;
|
|
182
218
|
toolsCtx.effect(() => tools.register(gitCredentialsTool({ home: () => homedir(), envHome: () => process.env.DSH_HOME, credentialsService: credentials })), 'git-worktree: git_credentials tool');
|
|
183
|
-
// The panel routes
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
//
|
|
187
|
-
// http.<url>.extraHeader` prefix, so the command authenticates as the
|
|
188
|
-
// configured account and the secret never enters the conversation — even
|
|
189
|
-
// when the bridge is missing (an older host, a shell outside the plugin).
|
|
219
|
+
// The panel routes authenticate through the same local git credential
|
|
220
|
+
// store (0037). This tool is the deterministic path for a session: it
|
|
221
|
+
// runs one network subcommand, git resolves the host through the include
|
|
222
|
+
// the service installs, and the secret never enters the conversation.
|
|
190
223
|
toolsCtx.effect(() => tools.register(gitNetworkTool({ home: () => homedir(), envHome: () => process.env.DSH_HOME, credentialsService: credentials })), 'git-worktree: git_network tool');
|
|
191
224
|
});
|
|
192
225
|
ctx.inject(['webServer'], (webCtx) => {
|
|
@@ -250,6 +283,7 @@ export function apply(ctx, config = {}) {
|
|
|
250
283
|
postRoute(ROUTE_GROUP, 'group', handleGroupWorktrees);
|
|
251
284
|
postRoute(ROUTE_UPDATE, 'update', handleUpdate);
|
|
252
285
|
postRoute(ROUTE_PUSH, 'push', handlePush);
|
|
286
|
+
postRoute(ROUTE_NETWORK_PROBE, 'network-probe', handleNetworkProbe);
|
|
253
287
|
postRoute(ROUTE_INSPECT, 'inspect', handleInspectWorktree);
|
|
254
288
|
postRoute(ROUTE_REMOVE, 'remove', handleRemoveWorktree);
|
|
255
289
|
postRoute(ROUTE_EXISTS, 'exists', handlePathExists);
|
|
@@ -272,6 +306,9 @@ export function apply(ctx, config = {}) {
|
|
|
272
306
|
// poll stores the token and answers the fresh masked list.
|
|
273
307
|
postRoute(ROUTE_CREDENTIALS_OAUTH_START, 'credentials-oauth-start', handleCredentialsOAuthStart);
|
|
274
308
|
postRoute(ROUTE_CREDENTIALS_OAUTH_POLL, 'credentials-oauth-poll', handleCredentialsOAuthPoll);
|
|
309
|
+
// One-click adoption of what the machine's own helpers already know:
|
|
310
|
+
// the modal calls it, startup calls it once automatically.
|
|
311
|
+
postRoute(ROUTE_CREDENTIALS_IMPORT, 'credentials-import', handleCredentialsImport);
|
|
275
312
|
postRoute(ROUTE_REMOTES, 'remotes', handleRemotes);
|
|
276
313
|
postRoute(ROUTE_REMOTE, 'remote', handleRemote);
|
|
277
314
|
// The AI commit-message route exists only where the host tree provides
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Import the machine's OWN credentials into the managed store (decision 0038).
|
|
3
|
+
*
|
|
4
|
+
* The store itself only knows the lines of `~/.git-credentials`. Everything
|
|
5
|
+
* the user already signed in through — Windows Credential Manager, macOS
|
|
6
|
+
* keychain, `gh auth git-credential` — lives outside that file and cannot be
|
|
7
|
+
* enumerated. What CAN be enumerated is the set of hosts git is configured to
|
|
8
|
+
* talk to (`[credential "https://host"]` sections in the user's gitconfig), so
|
|
9
|
+
* the import probes each of those with `git credential fill` and copies the
|
|
10
|
+
* secret the helper is willing to hand over. A host that answers nothing is
|
|
11
|
+
* reported as failed and left alone: importing never clears, only adds.
|
|
12
|
+
*/
|
|
13
|
+
import { type CredentialStore } from './credentials.js';
|
|
14
|
+
/** One host the import copied out of the machine's own helper. */
|
|
15
|
+
export interface ImportedCredential {
|
|
16
|
+
host: string;
|
|
17
|
+
username: string;
|
|
18
|
+
method: 'token' | 'password';
|
|
19
|
+
}
|
|
20
|
+
/** One host whose helper refused (or could not be asked) — the store is untouched. */
|
|
21
|
+
export interface LocalImportFailure {
|
|
22
|
+
host: string;
|
|
23
|
+
error: string;
|
|
24
|
+
}
|
|
25
|
+
/** Outcome of one import run. */
|
|
26
|
+
export interface LocalImportReport {
|
|
27
|
+
imported: ImportedCredential[];
|
|
28
|
+
skipped: string[];
|
|
29
|
+
failed: LocalImportFailure[];
|
|
30
|
+
}
|
|
31
|
+
/** One finished git invocation (local import never throws on a non-zero exit). */
|
|
32
|
+
export interface LocalGitResult {
|
|
33
|
+
code: number;
|
|
34
|
+
stdout: string;
|
|
35
|
+
stderr: string;
|
|
36
|
+
}
|
|
37
|
+
/** Runs one git command with `input` on stdin; tests substitute a fake. */
|
|
38
|
+
export type LocalGit = (args: readonly string[], input: string, env: NodeJS.ProcessEnv, timeoutMs: number) => Promise<LocalGitResult>;
|
|
39
|
+
/** Seams for the import: the environment, the git runner, the per-host timeout. */
|
|
40
|
+
export interface LocalImportDeps {
|
|
41
|
+
env?: NodeJS.ProcessEnv;
|
|
42
|
+
runGit?: LocalGit;
|
|
43
|
+
timeoutMs?: number;
|
|
44
|
+
}
|
|
45
|
+
/** The production git runner: spawn, feed stdin, collect both streams, kill on
|
|
46
|
+
* the deadline. `GIT_TERMINAL_PROMPT=0` / `GCM_INTERACTIVE=never` are applied
|
|
47
|
+
* by the caller, so a missing credential fails instead of opening a dialog. */
|
|
48
|
+
export declare const runGitLocal: LocalGit;
|
|
49
|
+
/**
|
|
50
|
+
* Hosts git is configured to ask for credentials: the URL-scoped
|
|
51
|
+
* `[credential "https://host"]` sections of the user's gitconfig, plus any
|
|
52
|
+
* that the global `credential.<url>.helper` keys spell out. Read-only.
|
|
53
|
+
* @param deps - environment and git seams.
|
|
54
|
+
*/
|
|
55
|
+
export declare function localCredentialHosts(deps?: LocalImportDeps): Promise<string[]>;
|
|
56
|
+
/**
|
|
57
|
+
* Copy every host the machine already answers for into the managed store.
|
|
58
|
+
*
|
|
59
|
+
* Candidates come from the caller (`hosts`) or from the user's gitconfig. A
|
|
60
|
+
* host already managed is skipped (the panel is the source of truth for it),
|
|
61
|
+
* a host whose helper answers nothing is reported and left untouched, and the
|
|
62
|
+
* store is written once at the end — a partial import is still a valid import.
|
|
63
|
+
*
|
|
64
|
+
* @param store - the managed credential store.
|
|
65
|
+
* @param deps - environment and git seams.
|
|
66
|
+
* @param hosts - explicit candidates; omitted, the gitconfig's hosts are used.
|
|
67
|
+
*/
|
|
68
|
+
export declare function importLocalCredentials(store: CredentialStore, deps?: LocalImportDeps, hosts?: readonly string[]): Promise<LocalImportReport>;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Import the machine's OWN credentials into the managed store (decision 0038).
|
|
3
|
+
*
|
|
4
|
+
* The store itself only knows the lines of `~/.git-credentials`. Everything
|
|
5
|
+
* the user already signed in through — Windows Credential Manager, macOS
|
|
6
|
+
* keychain, `gh auth git-credential` — lives outside that file and cannot be
|
|
7
|
+
* enumerated. What CAN be enumerated is the set of hosts git is configured to
|
|
8
|
+
* talk to (`[credential "https://host"]` sections in the user's gitconfig), so
|
|
9
|
+
* the import probes each of those with `git credential fill` and copies the
|
|
10
|
+
* secret the helper is willing to hand over. A host that answers nothing is
|
|
11
|
+
* reported as failed and left alone: importing never clears, only adds.
|
|
12
|
+
*/
|
|
13
|
+
import { spawn } from 'node:child_process';
|
|
14
|
+
import { TOKEN_USERNAME, normalizeCredentialHost, upsertCredential } from './credentials.js';
|
|
15
|
+
/** A helper may take a while (keychain prompts, network providers); 20s is
|
|
16
|
+
* long enough for a cold GCM start and short enough not to hang a modal. */
|
|
17
|
+
const DEFAULT_TIMEOUT_MS = 20_000;
|
|
18
|
+
/** The production git runner: spawn, feed stdin, collect both streams, kill on
|
|
19
|
+
* the deadline. `GIT_TERMINAL_PROMPT=0` / `GCM_INTERACTIVE=never` are applied
|
|
20
|
+
* by the caller, so a missing credential fails instead of opening a dialog. */
|
|
21
|
+
export const runGitLocal = (args, input, env, timeoutMs) => new Promise(resolve => {
|
|
22
|
+
const child = spawn('git', [...args], { env, windowsHide: true });
|
|
23
|
+
let stdout = '';
|
|
24
|
+
let stderr = '';
|
|
25
|
+
let settled = false;
|
|
26
|
+
const finish = (result) => {
|
|
27
|
+
if (settled)
|
|
28
|
+
return;
|
|
29
|
+
settled = true;
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
resolve(result);
|
|
32
|
+
};
|
|
33
|
+
const timer = setTimeout(() => {
|
|
34
|
+
child.kill();
|
|
35
|
+
finish({ code: -1, stdout, stderr: stderr === '' ? 'git timed out' : stderr });
|
|
36
|
+
}, timeoutMs);
|
|
37
|
+
child.stdout.setEncoding('utf8');
|
|
38
|
+
child.stderr.setEncoding('utf8');
|
|
39
|
+
child.stdout.on('data', (chunk) => { stdout += chunk; });
|
|
40
|
+
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
41
|
+
child.on('error', error => finish({ code: -1, stdout, stderr: error.message }));
|
|
42
|
+
child.on('close', code => finish({ code: code ?? -1, stdout, stderr }));
|
|
43
|
+
child.stdin.on('error', () => { });
|
|
44
|
+
child.stdin.end(input);
|
|
45
|
+
});
|
|
46
|
+
/** The local channel: fail fast instead of prompting, and drop any half
|
|
47
|
+
* injected `GIT_CONFIG_COUNT` channel (decision 0036) that would make every
|
|
48
|
+
* git command fail to parse. */
|
|
49
|
+
function localEnv(env) {
|
|
50
|
+
const next = { ...env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never' };
|
|
51
|
+
for (const key of Object.keys(next)) {
|
|
52
|
+
if (key === 'GIT_CONFIG_COUNT' || key.startsWith('GIT_CONFIG_KEY_') || key.startsWith('GIT_CONFIG_VALUE_'))
|
|
53
|
+
delete next[key];
|
|
54
|
+
}
|
|
55
|
+
return next;
|
|
56
|
+
}
|
|
57
|
+
/** First non-empty line of a helper's complaint, for the panel. */
|
|
58
|
+
function firstLine(text) {
|
|
59
|
+
const line = text.split(/\r?\n/).map(part => part.trim()).find(part => part !== '');
|
|
60
|
+
return line ?? '';
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Hosts git is configured to ask for credentials: the URL-scoped
|
|
64
|
+
* `[credential "https://host"]` sections of the user's gitconfig, plus any
|
|
65
|
+
* that the global `credential.<url>.helper` keys spell out. Read-only.
|
|
66
|
+
* @param deps - environment and git seams.
|
|
67
|
+
*/
|
|
68
|
+
export async function localCredentialHosts(deps = {}) {
|
|
69
|
+
const run = deps.runGit ?? runGitLocal;
|
|
70
|
+
const result = await run(['config', '--get-regexp', '^credential\\.https?://'], '', localEnv(deps.env ?? process.env), deps.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
71
|
+
// `git config --get-regexp` exits 1 when nothing matches: that is "no
|
|
72
|
+
// candidates", never an error worth surfacing.
|
|
73
|
+
if (result.code !== 0)
|
|
74
|
+
return [];
|
|
75
|
+
const hosts = [];
|
|
76
|
+
for (const line of result.stdout.split(/\r?\n/)) {
|
|
77
|
+
const match = /^credential\.https?:\/\/(\S+?)\.[A-Za-z0-9_-]+(?:\s|$)/i.exec(line);
|
|
78
|
+
if (match === null)
|
|
79
|
+
continue;
|
|
80
|
+
const host = normalizeCredentialHost(match[1] ?? '');
|
|
81
|
+
if (host !== undefined && !hosts.includes(host))
|
|
82
|
+
hosts.push(host);
|
|
83
|
+
}
|
|
84
|
+
return hosts;
|
|
85
|
+
}
|
|
86
|
+
/** Ask the machine's own helper for one host's credential. */
|
|
87
|
+
async function probe(host, deps) {
|
|
88
|
+
const run = deps.runGit ?? runGitLocal;
|
|
89
|
+
const result = await run(['credential', 'fill'], `protocol=https\nhost=${host}\n\n`, localEnv(deps.env ?? process.env), deps.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
90
|
+
if (result.code !== 0) {
|
|
91
|
+
return { error: firstLine(result.stderr) === '' ? `git exited ${String(result.code)}` : firstLine(result.stderr) };
|
|
92
|
+
}
|
|
93
|
+
const field = (name) => result.stdout.split(/\r?\n/)
|
|
94
|
+
.find(line => line.startsWith(`${name}=`))
|
|
95
|
+
?.slice(name.length + 1) ?? '';
|
|
96
|
+
const secret = field('password');
|
|
97
|
+
if (secret === '')
|
|
98
|
+
return { error: 'the credential helper returned no secret' };
|
|
99
|
+
return { username: field('username').trim(), secret };
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Copy every host the machine already answers for into the managed store.
|
|
103
|
+
*
|
|
104
|
+
* Candidates come from the caller (`hosts`) or from the user's gitconfig. A
|
|
105
|
+
* host already managed is skipped (the panel is the source of truth for it),
|
|
106
|
+
* a host whose helper answers nothing is reported and left untouched, and the
|
|
107
|
+
* store is written once at the end — a partial import is still a valid import.
|
|
108
|
+
*
|
|
109
|
+
* @param store - the managed credential store.
|
|
110
|
+
* @param deps - environment and git seams.
|
|
111
|
+
* @param hosts - explicit candidates; omitted, the gitconfig's hosts are used.
|
|
112
|
+
*/
|
|
113
|
+
export async function importLocalCredentials(store, deps = {}, hosts) {
|
|
114
|
+
const report = { imported: [], skipped: [], failed: [] };
|
|
115
|
+
const entries = await store.load();
|
|
116
|
+
const managed = new Set(entries.map(entry => entry.host));
|
|
117
|
+
const candidates = [];
|
|
118
|
+
const seen = new Set();
|
|
119
|
+
for (const value of hosts ?? await localCredentialHosts(deps)) {
|
|
120
|
+
const host = normalizeCredentialHost(value);
|
|
121
|
+
if (host === undefined || seen.has(host))
|
|
122
|
+
continue;
|
|
123
|
+
seen.add(host);
|
|
124
|
+
if (managed.has(host)) {
|
|
125
|
+
report.skipped.push(host);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
candidates.push(host);
|
|
129
|
+
}
|
|
130
|
+
let next = entries;
|
|
131
|
+
for (const host of candidates) {
|
|
132
|
+
const probed = await probe(host, deps);
|
|
133
|
+
if ('error' in probed) {
|
|
134
|
+
report.failed.push({ host, error: probed.error });
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
const token = probed.username === '' || probed.username === TOKEN_USERNAME;
|
|
138
|
+
const entry = {
|
|
139
|
+
host,
|
|
140
|
+
username: token ? '' : probed.username,
|
|
141
|
+
secret: probed.secret,
|
|
142
|
+
method: token ? 'token' : 'password',
|
|
143
|
+
updatedAt: Date.now(),
|
|
144
|
+
};
|
|
145
|
+
next = upsertCredential(next, entry);
|
|
146
|
+
report.imported.push({ host, username: token ? TOKEN_USERNAME : probed.username, method: token ? 'token' : 'password' });
|
|
147
|
+
}
|
|
148
|
+
if (report.imported.length > 0)
|
|
149
|
+
await store.save(next);
|
|
150
|
+
return report;
|
|
151
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The second network channel: resolve the host yourself, then race a few
|
|
3
|
+
* edge IPs with a real `ls-remote` and pin the winner with
|
|
4
|
+
* `http.curloptResolve`.
|
|
5
|
+
*
|
|
6
|
+
* Why a runtime lookup and not a built-in table: measured on 2026-11-03, a
|
|
7
|
+
* static list of eight GitHub edge IPs had seven TCP-reachable but only four
|
|
8
|
+
* that could answer `ls-remote`, two of them taking 88s and 211s. Edge
|
|
9
|
+
* assignment moves; a table baked into a release rots. So the table is
|
|
10
|
+
* fetched from DNS-over-HTTPS at the moment of need, and every candidate is
|
|
11
|
+
* validated by the same command the push will run.
|
|
12
|
+
*
|
|
13
|
+
* TCP reachability is deliberately NOT the judge: `connect()` succeeding
|
|
14
|
+
* says nothing about TLS termination or the git endpoint behind it.
|
|
15
|
+
*/
|
|
16
|
+
import type { Exec } from './git.js';
|
|
17
|
+
/** Budget for ONE pinned probe; candidates run in parallel, so the race is bounded by this. */
|
|
18
|
+
export declare const IP_PROBE_TIMEOUT_MS = 5000;
|
|
19
|
+
/** How long a winning channel is reused before the IPs are re-resolved. */
|
|
20
|
+
export declare const IP_CACHE_TTL_MS = 600000;
|
|
21
|
+
/**
|
|
22
|
+
* Concurrent candidates. Probes run in parallel, so the wall clock is one
|
|
23
|
+
* timeout no matter how many run; this only bounds process count.
|
|
24
|
+
*/
|
|
25
|
+
export declare const MAX_IP_CANDIDATES = 6;
|
|
26
|
+
/** Drop every cached channel (tests, and a user-triggered re-probe). */
|
|
27
|
+
export declare function resetIpChannelCache(): void;
|
|
28
|
+
/**
|
|
29
|
+
* Pull the IPv4 answers out of one DoH JSON body. Anything malformed answers
|
|
30
|
+
* `[]` rather than throwing: a resolver hiccup must degrade to the direct
|
|
31
|
+
* channel, not fail the push before it starts.
|
|
32
|
+
*/
|
|
33
|
+
export declare function parseDohIps(payload: unknown): string[];
|
|
34
|
+
/** Budget for one DoH query. Three resolvers are asked in parallel, so this bounds resolution. */
|
|
35
|
+
export declare const DOH_TIMEOUT_MS = 3000;
|
|
36
|
+
/**
|
|
37
|
+
* Ask every resolver about one host, in parallel, and union the answers.
|
|
38
|
+
*
|
|
39
|
+
* Sequential fallback was measured to be the wrong shape: the resolvers that
|
|
40
|
+
* are blocked here are blocked for the full timeout each, so a "fallback
|
|
41
|
+
* chain" spends three timeouts to learn what one parallel round trip tells.
|
|
42
|
+
* @param host - hostname to resolve.
|
|
43
|
+
* @param fetchImpl - fetch seam (tests inject a stub).
|
|
44
|
+
*/
|
|
45
|
+
export declare function resolveHostIps(host: string, fetchImpl?: typeof fetch): Promise<string[]>;
|
|
46
|
+
/**
|
|
47
|
+
* Candidates to race for one endpoint: the endpoint's own answers first, then
|
|
48
|
+
* the sibling services' answers (only for `github.com`), deduplicated and
|
|
49
|
+
* capped at {@link MAX_IP_CANDIDATES}. Everything runs in parallel, so the
|
|
50
|
+
* whole lookup is bounded by {@link DOH_TIMEOUT_MS}.
|
|
51
|
+
* @param host - endpoint hostname.
|
|
52
|
+
* @param fetchImpl - fetch seam.
|
|
53
|
+
*/
|
|
54
|
+
export declare function candidateIpsFor(host: string, fetchImpl?: typeof fetch): Promise<string[]>;
|
|
55
|
+
/** Whether this endpoint is one the pinned-IP channel may rewrite. */
|
|
56
|
+
export declare function isOptimizableEndpoint(endpoint: string): boolean;
|
|
57
|
+
/**
|
|
58
|
+
* The argv that pins `host:443` to one IP for a single command. `-c` goes
|
|
59
|
+
* before the subcommand, per git's global-option rule.
|
|
60
|
+
*/
|
|
61
|
+
export declare function pinArgs(host: string, ip: string): readonly string[];
|
|
62
|
+
/** Seam for the race: resolves when the candidate answered `ls-remote`. */
|
|
63
|
+
export type Probe = (args: readonly string[]) => Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Race up to {@link MAX_IP_CANDIDATES} pinned channels and answer the argv of
|
|
66
|
+
* the first that actually answers `ls-remote`. "First" means first to
|
|
67
|
+
* SUCCEED: all candidates start together and a slow-but-working IP can beat
|
|
68
|
+
* one that fails later.
|
|
69
|
+
* @param ips - candidates in resolver order.
|
|
70
|
+
* @param host - hostname being pinned.
|
|
71
|
+
* @param probe - one pinned probe (the caller supplies the budget + argv).
|
|
72
|
+
* @returns the winning `-c` argv, or undefined when every candidate failed.
|
|
73
|
+
*/
|
|
74
|
+
export declare function racePinnedChannels(ips: readonly string[], host: string, probe: Probe): Promise<readonly string[] | undefined>;
|
|
75
|
+
/**
|
|
76
|
+
* The channel a read/write may fall back to when the direct one fails in a
|
|
77
|
+
* retryable way. Wraps resolution + race + caching; answers undefined for
|
|
78
|
+
* endpoints outside {@link OPTIMIZABLE_HOSTS} or when nothing works.
|
|
79
|
+
* @param options.endpoint - the URL the command would use.
|
|
80
|
+
* @param options.probe - one pinned probe, built by {@link pinnedProbe}.
|
|
81
|
+
* @param options.now - clock seam for the cache.
|
|
82
|
+
* @param options.fetchImpl - DoH fetch seam.
|
|
83
|
+
*/
|
|
84
|
+
export declare function pinnedChannelFor(options: {
|
|
85
|
+
endpoint: string;
|
|
86
|
+
probe: Probe;
|
|
87
|
+
now?: () => number;
|
|
88
|
+
fetchImpl?: typeof fetch;
|
|
89
|
+
}): Promise<readonly string[] | undefined>;
|
|
90
|
+
/**
|
|
91
|
+
* Build the probe the race runs: one pinned `ls-remote` at the probe budget,
|
|
92
|
+
* with terminal prompts disabled so a credentialed endpoint fails instead of
|
|
93
|
+
* hanging on an invisible dialog.
|
|
94
|
+
* @param exec - executor seam.
|
|
95
|
+
* @param cwd - any directory inside the repository.
|
|
96
|
+
* @param endpoint - URL being probed.
|
|
97
|
+
* @param authArgs - per-host credential argv.
|
|
98
|
+
*/
|
|
99
|
+
export declare function pinnedProbe(exec: Exec, cwd: string, endpoint: string, authArgs?: readonly string[]): Probe;
|