dsh-git-branch-manage 1.0.10 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # 变更日志
2
+
3
+ 本文件记录 `dsh-git-branch-manage` 的重要变更。版本号遵循语义化版本。
4
+
5
+ ## [1.1.0] - 2026-11-02
6
+
7
+ ### 修复
8
+
9
+ - **宿主里的 `git` 命令全部 `fatal`**(`fatal: unable to parse command-line config`):0032 的 `GIT_CONFIG_KEY/VALUE_*` 环境注入被 DeepSeek Harness 的子进程环境清洗(按 `/KEY|PASSWORD|SECRET|TOKEN/i` 过滤变量名、并剥掉 `DSH_*` 前缀)半剥离——`KEY_n` 被删、`COUNT/VALUE_n` 幸存。改用 `GIT_CONFIG_GLOBAL` 指向一份会话临时 gitconfig 注入凭据(决策 0034)。
10
+ - **shell 里的 `git` 走本机 gh 账号而非面板令牌**:会话配置用 URL 作用域的空 `helper` 重置,清掉 `~/.gitconfig` 里 `[credential "https://github.com"]` 的 gh helper,让已配置域名命中面板令牌。
11
+ - **未配置域名弹 GCM 凭据对话框 / 挂死**:全局空 `helper` 清空机器 helper 链,未配置域名 `exit 128` 快速失败,不再弹窗。
12
+ - **含空格的 node/helper 路径调用失败**(`sh: C:/Program: No such file or directory`):`gitconfigEscape` / `shellQuote` 正确转义引号与反斜杠。
13
+
14
+ ### 变更
15
+
16
+ - 新增 `createCredentialService`,把凭据入口收敛为单一服务(`store` / `authConfigArgs` / `refreshShellEnv` / `dispose`);routes、`git_network`、密钥工具统一经它取 store 与注入通道(决策 0034)。
17
+ - 桥 helper 环境变量改 `DGB_*` 命名(`DGB_BRIDGE_HELPER` 等),避开 DSH 环境清洗。
18
+ - 新增真实 `git` 端到端回归测试(`shell-bridge-e2e`):验证已配置域名命中桥令牌、空格路径正确调用、未配置域名快速失败。
19
+
20
+ ## [1.0.10] - 2026-10-30
21
+
22
+ - shell 里的 `git push` 也走插件密钥(环境变量桥,决策 0032)。注:该注入通道在 DeepSeek Harness 宿主中失效,已由 1.1.0 修正(决策 0034)。
23
+
24
+ 更早版本见 [GitHub Releases](https://github.com/GaoHu1997/dsh-git-branch/releases)。
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The one entry point every credential channel goes through (decision 0034).
3
+ *
4
+ * Before this module the store, the `-c http.<url>.extraHeader` injection
5
+ * (`authConfigArgs`, 0021/0029) and the shell environment bridge
6
+ * (`shell-bridge.ts`, 0032/0034) were assembled in three places — the routes,
7
+ * the two model-facing tools and the plugin entry — each resolving the store
8
+ * path itself. Every future plugin that needs git credentials would have
9
+ * repeated that wiring and drifted from it.
10
+ *
11
+ * `createCredentialService` owns the store instance and both injection
12
+ * channels, so callers share one contract:
13
+ *
14
+ * - {@link CredentialService.authConfigArgs} — the `-c extraHeader` pairs for
15
+ * git commands the plugin itself runs (panel routes, `git_network`). The
16
+ * token rides the argv of that one command and never an environment.
17
+ * - {@link CredentialService.refreshShellEnv} — re-derive the session
18
+ * gitconfig + `GIT_CONFIG_GLOBAL` environment so a plain shell `git push`
19
+ * authenticates as configured. Call it after every store change.
20
+ * - {@link CredentialService.dispose} — undo the environment injection and
21
+ * delete the session config file (plugin teardown).
22
+ *
23
+ * A store that cannot be read degrades to "no credentials" on every channel
24
+ * (an unauthenticated command runs as it always did; the credentials route is
25
+ * where the file problem surfaces) — a broken file must never break git.
26
+ */
27
+ import { type CredentialStore } from './credentials.js';
28
+ /** Host-side seams the service reads through (tests substitute all of them). */
29
+ export interface CredentialServiceDeps {
30
+ /** User home directory seam. */
31
+ readonly home: () => string;
32
+ /** `$DSH_HOME` seam (blank/undefined = unset). */
33
+ readonly envHome: () => string | undefined;
34
+ /** Store seam; the fs-backed store at the resolved path when absent. */
35
+ readonly store?: CredentialStore;
36
+ /** The environment object to mutate; `process.env` when absent. */
37
+ readonly env?: Record<string, string | undefined>;
38
+ /** Absolute helper script path; the compiled sibling under `helpers/` when absent. */
39
+ readonly helperPath?: string;
40
+ /** Node executable that runs the helper; `process.execPath` when absent. */
41
+ readonly nodePath?: string;
42
+ /** Directory for the session config; the OS temp dir when absent. */
43
+ readonly configDir?: () => string;
44
+ /** Exact session config path (tests); derived from the pid when absent. */
45
+ readonly configPath?: string;
46
+ /** User global config the session file includes; `<home>/.gitconfig` when absent. */
47
+ readonly userGitconfig?: string;
48
+ }
49
+ /** The single credential entry point. */
50
+ export interface CredentialService {
51
+ /** The shared global store (one row per remote host). */
52
+ readonly store: CredentialStore;
53
+ /**
54
+ * `-c http.<url>.extraHeader` pairs for every stored credential, ready to
55
+ * prepend to a git network command the plugin runs itself. A broken store
56
+ * degrades to "no credentials" rather than throwing.
57
+ */
58
+ readonly authConfigArgs: () => Promise<readonly string[]>;
59
+ /**
60
+ * Re-derive the shell credential environment after a credential changed, so
61
+ * a message sent in the same session can `git push` with the token the user
62
+ * just saved. Never throws: the worst case is a stale environment until the
63
+ * next refresh.
64
+ */
65
+ readonly refreshShellEnv: () => Promise<void>;
66
+ /** Remove the environment injection and delete the session config file. */
67
+ readonly dispose: () => Promise<void>;
68
+ }
69
+ /**
70
+ * Build the credential service for one host process: one store instance, one
71
+ * session-gitconfig bridge, shared by the routes and every tool.
72
+ * @param deps - host seams (see {@link CredentialServiceDeps}).
73
+ */
74
+ export declare function createCredentialService(deps: CredentialServiceDeps): CredentialService;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The one entry point every credential channel goes through (decision 0034).
3
+ *
4
+ * Before this module the store, the `-c http.<url>.extraHeader` injection
5
+ * (`authConfigArgs`, 0021/0029) and the shell environment bridge
6
+ * (`shell-bridge.ts`, 0032/0034) were assembled in three places — the routes,
7
+ * the two model-facing tools and the plugin entry — each resolving the store
8
+ * path itself. Every future plugin that needs git credentials would have
9
+ * repeated that wiring and drifted from it.
10
+ *
11
+ * `createCredentialService` owns the store instance and both injection
12
+ * channels, so callers share one contract:
13
+ *
14
+ * - {@link CredentialService.authConfigArgs} — the `-c extraHeader` pairs for
15
+ * git commands the plugin itself runs (panel routes, `git_network`). The
16
+ * token rides the argv of that one command and never an environment.
17
+ * - {@link CredentialService.refreshShellEnv} — re-derive the session
18
+ * gitconfig + `GIT_CONFIG_GLOBAL` environment so a plain shell `git push`
19
+ * authenticates as configured. Call it after every store change.
20
+ * - {@link CredentialService.dispose} — undo the environment injection and
21
+ * delete the session config file (plugin teardown).
22
+ *
23
+ * A store that cannot be read degrades to "no credentials" on every channel
24
+ * (an unauthenticated command runs as it always did; the credentials route is
25
+ * where the file problem surfaces) — a broken file must never break git.
26
+ */
27
+ import { authConfigArgs, createCredentialStore, credentialFilePath, } from './credentials.js';
28
+ import { createShellBridge } from './shell-bridge.js';
29
+ /**
30
+ * Build the credential service for one host process: one store instance, one
31
+ * session-gitconfig bridge, shared by the routes and every tool.
32
+ * @param deps - host seams (see {@link CredentialServiceDeps}).
33
+ */
34
+ export function createCredentialService(deps) {
35
+ const store = deps.store
36
+ ?? createCredentialStore(credentialFilePath(deps.home(), deps.envHome()));
37
+ const bridgeDeps = { ...deps, store };
38
+ const shellBridge = createShellBridge(bridgeDeps);
39
+ return {
40
+ store,
41
+ async authConfigArgs() {
42
+ try {
43
+ return authConfigArgs(await store.load());
44
+ }
45
+ catch {
46
+ return [];
47
+ }
48
+ },
49
+ refreshShellEnv() {
50
+ return shellBridge.apply();
51
+ },
52
+ dispose() {
53
+ return shellBridge.dispose();
54
+ },
55
+ };
56
+ }
@@ -4,28 +4,33 @@
4
4
  * The panel's credential file (`~/.dsh/git-credentials.json`) normally rides
5
5
  * `-c http.<url>.extraHeader` config on the routes and the `git_network` tool.
6
6
  * This helper extends that coverage to a plain shell `git push`: the plugin's
7
- * host process exports `GIT_CONFIG_COUNT/KEY/VALUE` entries that install this
8
- * script as a URL-scoped credential helper for every stored host, so commands
9
- * the model runs in the shell authenticate as the configured account too.
7
+ * host process writes a session gitconfig (see `src/shell-bridge.ts`) that
8
+ * installs this script as a URL-scoped credential helper for every stored
9
+ * host, so commands the model runs in the shell authenticate as the
10
+ * configured account too.
10
11
  *
11
- * Design constraints (see docs/decisions/0029 and 0032):
12
+ * Design constraints (see docs/decisions/0029, 0032 and 0034):
12
13
  * - The user's global git config and credential helpers are never written;
13
- * the injection lives in the process environment only.
14
+ * the injection lives in one generated session config plus the process
15
+ * environment only.
14
16
  * - The token never enters the conversation: this script reads the
15
17
  * credential file directly on the host and answers git on stdout.
16
- * - URL scope (`credential.https://<host>/.helper`) confines the helper to
17
- * hosts with a stored credential. The host half also clears the machine
18
- * helper list, so a host this script cannot answer fails fast instead of
19
- * opening an interactive credential dialog.
18
+ * - URL scope (`credential.https://<host>/`) confines the helper to hosts
19
+ * with a stored credential. The host half also clears the machine helper
20
+ * list, so a host this script cannot answer fails fast instead of opening
21
+ * an interactive credential dialog.
20
22
  * - `get` is silent on a miss (git falls through to the next helper);
21
23
  * `store`/`erase` are pass-through by decision — writing back would race
22
24
  * the panel's atomic save and leak the file shape.
23
25
  *
24
- * Environment contract (set by src/shell-bridge.ts):
25
- * - `DSH_GIT_BRIDGE_HELPER` — credential file path (required).
26
- * - `DSH_GIT_BRIDGE_HOME` — user home directory (fallback resolution).
27
- * - `DSH_GIT_BRIDGE_DSH_HOME` — `$DSH_HOME` override (optional).
28
- * - `DSH_GIT_BRIDGE_DEBUG` — when non-blank, a debug log path (optional).
26
+ * Environment contract (set by src/shell-bridge.ts). The names carry no
27
+ * KEY/PASSWORD/SECRET/TOKEN substring and no `DSH_` prefix, because the DSH
28
+ * subprocess scrubber strips exactly those from inherited environments
29
+ * (decision 0034; a stripped path made this helper read the wrong file):
30
+ * - `DGB_BRIDGE_HELPER` — credential file path (required).
31
+ * - `DGB_BRIDGE_HOME` — user home directory (fallback resolution).
32
+ * - `DGB_BRIDGE_DSH_HOME` — `$DSH_HOME` override (optional).
33
+ * - `DGB_BRIDGE_DEBUG` — when non-blank, a debug log path (optional).
29
34
  *
30
35
  * @module dsh-git-branch/git-credential-bridge
31
36
  */
@@ -4,28 +4,33 @@
4
4
  * The panel's credential file (`~/.dsh/git-credentials.json`) normally rides
5
5
  * `-c http.<url>.extraHeader` config on the routes and the `git_network` tool.
6
6
  * This helper extends that coverage to a plain shell `git push`: the plugin's
7
- * host process exports `GIT_CONFIG_COUNT/KEY/VALUE` entries that install this
8
- * script as a URL-scoped credential helper for every stored host, so commands
9
- * the model runs in the shell authenticate as the configured account too.
7
+ * host process writes a session gitconfig (see `src/shell-bridge.ts`) that
8
+ * installs this script as a URL-scoped credential helper for every stored
9
+ * host, so commands the model runs in the shell authenticate as the
10
+ * configured account too.
10
11
  *
11
- * Design constraints (see docs/decisions/0029 and 0032):
12
+ * Design constraints (see docs/decisions/0029, 0032 and 0034):
12
13
  * - The user's global git config and credential helpers are never written;
13
- * the injection lives in the process environment only.
14
+ * the injection lives in one generated session config plus the process
15
+ * environment only.
14
16
  * - The token never enters the conversation: this script reads the
15
17
  * credential file directly on the host and answers git on stdout.
16
- * - URL scope (`credential.https://<host>/.helper`) confines the helper to
17
- * hosts with a stored credential. The host half also clears the machine
18
- * helper list, so a host this script cannot answer fails fast instead of
19
- * opening an interactive credential dialog.
18
+ * - URL scope (`credential.https://<host>/`) confines the helper to hosts
19
+ * with a stored credential. The host half also clears the machine helper
20
+ * list, so a host this script cannot answer fails fast instead of opening
21
+ * an interactive credential dialog.
20
22
  * - `get` is silent on a miss (git falls through to the next helper);
21
23
  * `store`/`erase` are pass-through by decision — writing back would race
22
24
  * the panel's atomic save and leak the file shape.
23
25
  *
24
- * Environment contract (set by src/shell-bridge.ts):
25
- * - `DSH_GIT_BRIDGE_HELPER` — credential file path (required).
26
- * - `DSH_GIT_BRIDGE_HOME` — user home directory (fallback resolution).
27
- * - `DSH_GIT_BRIDGE_DSH_HOME` — `$DSH_HOME` override (optional).
28
- * - `DSH_GIT_BRIDGE_DEBUG` — when non-blank, a debug log path (optional).
26
+ * Environment contract (set by src/shell-bridge.ts). The names carry no
27
+ * KEY/PASSWORD/SECRET/TOKEN substring and no `DSH_` prefix, because the DSH
28
+ * subprocess scrubber strips exactly those from inherited environments
29
+ * (decision 0034; a stripped path made this helper read the wrong file):
30
+ * - `DGB_BRIDGE_HELPER` — credential file path (required).
31
+ * - `DGB_BRIDGE_HOME` — user home directory (fallback resolution).
32
+ * - `DGB_BRIDGE_DSH_HOME` — `$DSH_HOME` override (optional).
33
+ * - `DGB_BRIDGE_DEBUG` — when non-blank, a debug log path (optional).
29
34
  *
30
35
  * @module dsh-git-branch/git-credential-bridge
31
36
  */
@@ -34,7 +39,7 @@ import { homedir } from 'node:os';
34
39
  import { join } from 'node:path';
35
40
  /** git helpers receive exactly one argument: the operation. */
36
41
  const OPERATION = process.argv[2] ?? 'get';
37
- /** The credential file this helper reads (`DSH_GIT_BRIDGE_HELPER` wins). */
42
+ /** The credential file this helper reads (`DGB_BRIDGE_HELPER` wins). */
38
43
  const DEFAULT_CREDENTIAL_FILE = 'git-credentials.json';
39
44
  /** The dsh home directory below the user profile when `$DSH_HOME` is unset. */
40
45
  const PACKAGE_HOME = '.dsh';
@@ -45,7 +50,7 @@ const TOKEN_USERNAME = 'oauth2';
45
50
  * break the credential lookup.
46
51
  */
47
52
  function debug(line) {
48
- const path = process.env.DSH_GIT_BRIDGE_DEBUG;
53
+ const path = process.env.DGB_BRIDGE_DEBUG;
49
54
  if (path === undefined || path.trim() === '')
50
55
  return;
51
56
  try {
@@ -55,16 +60,16 @@ function debug(line) {
55
60
  // Deliberately swallowed: debugging is best-effort.
56
61
  }
57
62
  }
58
- /** The credential file this helper reads (`DSH_GIT_BRIDGE_HELPER` wins). */
63
+ /** The credential file this helper reads (`DGB_BRIDGE_HELPER` wins). */
59
64
  function credentialFile() {
60
- const helper = process.env.DSH_GIT_BRIDGE_HELPER;
65
+ const helper = process.env.DGB_BRIDGE_HELPER;
61
66
  if (helper !== undefined && helper.trim() !== '')
62
67
  return helper;
63
- const dshHome = process.env.DSH_GIT_BRIDGE_DSH_HOME;
68
+ const dshHome = process.env.DGB_BRIDGE_DSH_HOME;
64
69
  const home = dshHome !== undefined && dshHome.trim() !== ''
65
70
  ? dshHome
66
- : process.env.DSH_GIT_BRIDGE_HOME ?? homedir();
67
- return join(home, DEFAULT_CREDENTIAL_FILE);
71
+ : process.env.DGB_BRIDGE_HOME ?? homedir();
72
+ return join(home, PACKAGE_HOME, DEFAULT_CREDENTIAL_FILE);
68
73
  }
69
74
  /** One `key=value` request from git on stdin. */
70
75
  function readRequest() {
package/lib/index.js CHANGED
@@ -13,7 +13,7 @@ import { handleCredentials, handleCredentialsDelete, handleCredentialsOAuthPoll,
13
13
  import { validateRootDir } from './settings.js';
14
14
  import { gitNetworkTool } from './network-tool.js';
15
15
  import { gitCredentialsTool } from './tool.js';
16
- import { createShellBridge } from './shell-bridge.js';
16
+ import { createCredentialService } from './credential-service.js';
17
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';
18
18
  export const name = 'dsh-git-branch';
19
19
  export const inject = [];
@@ -142,14 +142,19 @@ export function sectionOf(config) {
142
142
  export function apply(ctx, config = {}) {
143
143
  validateConfig(config);
144
144
  const currentConfig = () => ctx.fiber?.config ?? config;
145
- // Host half of the shell credential bridge: derive the environment that
146
- // lets a plain `git push` in a spawned shell authenticate with the panel's
147
- // stored token instead of the machine helper's account. It also clears the
148
- // machine helper chain, so a host without a stored token fails fast rather
149
- // than opening a credential dialog no agent shell can answer. Applied at
150
- // activate and re-derived after every credential save / delete / sign-in.
151
- const shellBridge = createShellBridge({ home: () => homedir(), envHome: () => process.env.DSH_HOME });
152
- void shellBridge.apply();
145
+ // Host half of the credential channels: one service owns the store, the
146
+ // `-c extraHeader` injection for plugin-run commands and the shell bridge
147
+ // (decision 0034). The bridge lets a plain `git push` in a spawned shell
148
+ // authenticate with the panel's stored token instead of the machine helper's
149
+ // account. It also clears the machine helper chain, so a host without a
150
+ // stored token fails fast rather than opening a credential dialog no agent
151
+ // shell can answer. Applied at activate and re-derived after every
152
+ // credential save / delete / sign-in.
153
+ const credentials = createCredentialService({ home: () => homedir(), envHome: () => process.env.DSH_HOME });
154
+ void credentials.refreshShellEnv();
155
+ ctx.effect(() => () => {
156
+ void credentials.dispose();
157
+ }, 'git-worktree: credential service dispose');
153
158
  const deps = () => ({
154
159
  exec: childProcessExec,
155
160
  sectionRootDir: () => readVolatile(currentConfig().rootDir),
@@ -159,7 +164,8 @@ export function apply(ctx, config = {}) {
159
164
  sectionCnAccelerateUrl: () => readVolatile(currentConfig().cnAccelerateUrl),
160
165
  home: () => homedir(),
161
166
  envHome: () => process.env.DSH_HOME,
162
- refreshShellBridge: () => shellBridge.apply(),
167
+ credentialsService: credentials,
168
+ refreshShellBridge: () => credentials.refreshShellEnv(),
163
169
  });
164
170
  // In dsh 0.1.7+, the settings service projects volatile Config fields into forms.
165
171
  // We configure auto: false to inform the host that this plugin provides its own
@@ -173,7 +179,7 @@ export function apply(ctx, config = {}) {
173
179
  // unless the user explicitly asked to see it.
174
180
  ctx.inject(['tools'], (toolsCtx) => {
175
181
  const tools = toolsCtx.tools;
176
- toolsCtx.effect(() => tools.register(gitCredentialsTool({ home: () => homedir(), envHome: () => process.env.DSH_HOME })), 'git-worktree: git_credentials tool');
182
+ toolsCtx.effect(() => tools.register(gitCredentialsTool({ home: () => homedir(), envHome: () => process.env.DSH_HOME, credentialsService: credentials })), 'git-worktree: git_credentials tool');
177
183
  // The panel routes inject the stored credentials into the requests the
178
184
  // browser half makes; a shell command is served by the environment bridge
179
185
  // (see `shell-bridge.ts`) instead. This tool is the deterministic path for
@@ -181,7 +187,7 @@ export function apply(ctx, config = {}) {
181
187
  // http.<url>.extraHeader` prefix, so the command authenticates as the
182
188
  // configured account and the secret never enters the conversation — even
183
189
  // when the bridge is missing (an older host, a shell outside the plugin).
184
- toolsCtx.effect(() => tools.register(gitNetworkTool({ home: () => homedir(), envHome: () => process.env.DSH_HOME })), 'git-worktree: git_network tool');
190
+ toolsCtx.effect(() => tools.register(gitNetworkTool({ home: () => homedir(), envHome: () => process.env.DSH_HOME, credentialsService: credentials })), 'git-worktree: git_network tool');
185
191
  });
186
192
  ctx.inject(['webServer'], (webCtx) => {
187
193
  /** Send one outcome as JSON; no-store because repo facts are point-in-time. */
@@ -20,6 +20,7 @@
20
20
  * @module dsh-git-branch/network-tool
21
21
  */
22
22
  import { type CredentialStore, type GitCredential } from './credentials.js';
23
+ import type { CredentialService } from './credential-service.js';
23
24
  import { type Exec } from './git.js';
24
25
  /** Model-facing tool name. */
25
26
  export declare const GIT_NETWORK_TOOL_NAME = "git_network";
@@ -66,6 +67,9 @@ export interface GitNetworkToolDeps {
66
67
  readonly envHome: () => string | undefined;
67
68
  /** Store seam; the fs-backed store at the resolved path when absent. */
68
69
  readonly store?: CredentialStore;
70
+ /** The single credential entry point (decision 0034); when wired its store
71
+ * is shared with the routes and the shell bridge. */
72
+ readonly credentialsService?: CredentialService;
69
73
  /** Process seam; the real `git` over node:child_process when absent. */
70
74
  readonly exec?: Exec;
71
75
  }
@@ -162,7 +162,7 @@ export function renderGitNetwork(value) {
162
162
  * @returns a definition ready for `ctx.tools.register`.
163
163
  */
164
164
  export function gitNetworkTool(deps) {
165
- const storeOf = () => deps.store ?? createCredentialStore(credentialFilePath(deps.home(), deps.envHome()));
165
+ const storeOf = () => deps.credentialsService?.store ?? deps.store ?? createCredentialStore(credentialFilePath(deps.home(), deps.envHome()));
166
166
  const exec = deps.exec ?? childProcessExec;
167
167
  return {
168
168
  name: GIT_NETWORK_TOOL_NAME,
package/lib/routes.d.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { type CopyFilesSeams } from './copy-files.js';
6
6
  import { type CredentialStore } from './credentials.js';
7
+ import type { CredentialService } from './credential-service.js';
7
8
  import { type DirExists, type ExcludeSeams, type Exec } from './git.js';
8
9
  import type { AiCommitMessageResult, ChangesResult, CommitFilesResult, CommitResult, CreateBranchResult, CreateTagResult, CreateWorktreeResult, CredentialOAuthPollResult, CredentialOAuthStartResult, CredentialsResult, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, InspectWorktreeResult, LogResult, PathExistsResult, PurgeDirectoryResult, PushTagResult, RemoveWorktreeResult, RemotesResult, RepoStatus, RouteError, StageResult, SwitchResult, UpdateResult, WorktreesAllResult } from './wire.js';
9
10
  /** Everything the handlers need from the host half. */
@@ -44,6 +45,9 @@ export interface RouteDeps {
44
45
  /** Global per-host credential store. Absent = the fs-backed store at the
45
46
  * resolved dsh home; tests substitute an in-memory one. */
46
47
  credentialsStore?: CredentialStore;
48
+ /** The single credential entry point (decision 0034): when wired, it owns
49
+ * the store and both injection channels, and the seams below are ignored. */
50
+ credentialsService?: CredentialService;
47
51
  /** Re-derive the shell credential bridge after the store changed (absent =
48
52
  * a host that does not provide the bridge; tests omit it). */
49
53
  refreshShellBridge?: () => Promise<void>;
package/lib/routes.js CHANGED
@@ -53,10 +53,11 @@ function accelPrefix(deps) {
53
53
  const url = deps.sectionCnAccelerateUrl?.() ?? ACCEL_DEFAULT_URL;
54
54
  return accelerateUrlError(url) === undefined ? normalizeAccelerateUrl(url) : undefined;
55
55
  }
56
- /** The global credential store: the wired one, else the fs-backed file at the
57
- * resolved dsh home (`<dshHome>/git-credentials.json`). */
56
+ /** The global credential store: the service's shared instance (decision 0034),
57
+ * else the wired store, else the fs-backed file at the resolved dsh home
58
+ * (`<dshHome>/git-credentials.json`). */
58
59
  function credentialStore(deps) {
59
- return deps.credentialsStore ?? createCredentialStore(credentialFilePath(deps.home(), deps.envHome()));
60
+ return deps.credentialsService?.store ?? deps.credentialsStore ?? createCredentialStore(credentialFilePath(deps.home(), deps.envHome()));
60
61
  }
61
62
  /**
62
63
  * `-c http.<url>.extraHeader` pairs for every stored credential, ready to
@@ -66,6 +67,8 @@ function credentialStore(deps) {
66
67
  * route is where the file problem surfaces.
67
68
  */
68
69
  async function authArgsFor(deps) {
70
+ if (deps.credentialsService !== undefined)
71
+ return deps.credentialsService.authConfigArgs();
69
72
  try {
70
73
  return authConfigArgs(await credentialStore(deps).load());
71
74
  }
@@ -81,10 +84,11 @@ async function authArgsFor(deps) {
81
84
  * save (an added host is not reachable, a deleted one may still be).
82
85
  */
83
86
  async function refreshBridge(deps) {
84
- if (deps.refreshShellBridge === undefined)
87
+ const refresh = deps.credentialsService?.refreshShellEnv ?? deps.refreshShellBridge;
88
+ if (refresh === undefined)
85
89
  return;
86
90
  try {
87
- await deps.refreshShellBridge();
91
+ await refresh();
88
92
  }
89
93
  catch {
90
94
  // Deliberately swallowed; see the contract above.
@@ -1,35 +1,53 @@
1
1
  /**
2
- * Shell credential bridge (host half). The credential panel stores one token
3
- * per remote host, but 0029 could only inject it into the panel's own routes
4
- * and the `git_network` tool; a plain `git push` run in a shell authenticated
5
- * as whatever the machine's credential helper held — often a different
6
- * account — or hung on an interactive prompt nobody could answer.
2
+ * Shell credential bridge (host half) — session gitconfig channel. The
3
+ * credential panel stores one token per remote host, but 0029 could only
4
+ * inject it into the panel's own routes and the `git_network` tool; a plain
5
+ * `git push` run in a shell authenticated as whatever the machine's
6
+ * credential helper held — often a different account — or hung on an
7
+ * interactive prompt nobody could answer.
7
8
  *
8
- * This module closes that gap without touching the user's git configuration
9
- * FILES (0021's constraint): it exports `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_n`/
10
- * `GIT_CONFIG_VALUE_n` entries that install the bundled credential helper
11
- * (`helpers/git-credential-bridge.js`) as a URL-scoped helper for every stored
12
- * host. git reads that environment as configuration, every child process the
13
- * host spawns inherits it, and a non-empty value list is always preceded by the
14
- * same key with an empty value — git resets the accumulated helper list
15
- * there, so the machine chain (`helper-selector` → GCM) can neither answer
16
- * with a different account nor open a blocking dialog for those hosts.
17
- * The list is reset globally as well: a host with no stored credential then
18
- * fails at once ("terminal prompts disabled") instead of reaching the machine
19
- * chain, whose interactive GUI dialog nobody in an agent shell can answer.
9
+ * 0032 closed that gap with `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_n`/
10
+ * `GIT_CONFIG_VALUE_n` environment entries. That channel is dead on a DSH
11
+ * host: the subprocess environment scrubber
12
+ * (`@deepseek-ai/dsh-subprocess`, `SENSITIVE_ENV_PATTERN = /KEY|PASSWORD|SECRET|TOKEN/i`
13
+ * plus every `DSH_*` name) strips the `GIT_CONFIG_KEY_*` names and keeps
14
+ * `GIT_CONFIG_COUNT`/`VALUE_*`, so git starts with a half-parsed config and
15
+ * dies with `fatal: unable to parse command-line config` — every git command
16
+ * in the shell, not only the networked ones (0034).
20
17
  *
21
- * `GIT_TERMINAL_PROMPT=0` and `GCM_INTERACTIVE=never` ride along so a host
22
- * with no usable credential fails fast instead of parking a shell on a prompt
23
- * (the failure mode that started this: a 3m38s silent hang).
18
+ * The replacement writes ONE generated gitconfig per host process and points
19
+ * git at it with `GIT_CONFIG_GLOBAL` — a name the scrubber keeps. The file:
24
20
  *
25
- * The assignments are re-derived whenever the credential store changes
21
+ * 1. `[include]`s the user's own `~/.gitconfig` (read-only; 0021's "never
22
+ * write the user's git config files" stands) so identity, proxies and
23
+ * `http.sslBackend` keep working;
24
+ * 2. resets the whole `credential.helper` list to empty, cutting the machine
25
+ * chain (`helper-selector` → GCM) and any helper the included user config
26
+ * carries (the local `gh` helper being the motivating case);
27
+ * 3. per stored host, resets that URL scope and then installs the bundled
28
+ * helper (`helpers/git-credential-bridge.js`) as a `!`-shell command.
29
+ *
30
+ * A host with no stored credential then fails at once ("terminal prompts
31
+ * disabled") instead of reaching the machine chain, whose interactive GUI
32
+ * dialog nobody in an agent shell can answer. `GIT_TERMINAL_PROMPT=0` and
33
+ * `GCM_INTERACTIVE=never` ride along as the last line of defence.
34
+ *
35
+ * Environment contract (all names survive the scrubber — no KEY/PASSWORD/
36
+ * SECRET/TOKEN substring, no `DSH_` prefix):
37
+ * - `GIT_CONFIG_GLOBAL` — the generated session config (0034).
38
+ * - `DGB_BRIDGE_HELPER` — credential file path for the helper script.
39
+ * - `GIT_TERMINAL_PROMPT` / `GCM_INTERACTIVE` — fail fast, never prompt.
40
+ *
41
+ * The file is re-derived whenever the credential store changes
26
42
  * (`src/routes.ts` calls the bridge after every save / delete / sign-in).
27
43
  */
28
44
  import { type CredentialStore } from './credentials.js';
29
45
  /** Env var carrying the credential file path to the helper script. */
30
- export declare const BRIDGE_HELPER_ENV = "DSH_GIT_BRIDGE_HELPER";
46
+ export declare const BRIDGE_HELPER_ENV = "DGB_BRIDGE_HELPER";
31
47
  /** Env var carrying a debug log path to the helper script (unset by default). */
32
- export declare const BRIDGE_DEBUG_ENV = "DSH_GIT_BRIDGE_DEBUG";
48
+ export declare const BRIDGE_DEBUG_ENV = "DGB_BRIDGE_DEBUG";
49
+ /** Env var pointing git at the generated session configuration file. */
50
+ export declare const SESSION_GITCONFIG_ENV = "GIT_CONFIG_GLOBAL";
33
51
  /** Host-side seams the bridge reads through (tests substitute all of them). */
34
52
  export interface ShellBridgeDeps {
35
53
  /** User home directory seam. */
@@ -45,21 +63,31 @@ export interface ShellBridgeDeps {
45
63
  readonly helperPath?: string;
46
64
  /** Node executable that runs the helper; `process.execPath` when absent. */
47
65
  readonly nodePath?: string;
66
+ /** Directory for the session config; the OS temp dir when absent. */
67
+ readonly configDir?: () => string;
68
+ /** Exact session config path (tests); `<configDir>/dsh-git-branch-<pid>.gitconfig` when absent. */
69
+ readonly configPath?: string;
70
+ /** User global config the session file includes; `<home>/.gitconfig` when absent. */
71
+ readonly userGitconfig?: string;
48
72
  }
49
- /** The bridge's one operation: re-derive the environment from the store. */
73
+ /** The bridge's operations: re-derive the environment, and undo it. */
50
74
  export interface ShellBridge {
51
75
  /** Read the credential store and rewrite the injected environment.
52
76
  * A store that cannot be read drops every URL-scoped helper (no host can be
53
77
  * bridged), but keeps the global reset, so shell git still fails fast
54
78
  * instead of opening an interactive credential dialog. */
55
79
  readonly apply: () => Promise<void>;
80
+ /** Remove the injected environment and delete the session config file. */
81
+ readonly dispose: () => Promise<void>;
82
+ /** The session config path this bridge writes. */
83
+ readonly configPath: () => string;
56
84
  }
57
85
  /** One ordered environment assignment. */
58
86
  export type BridgeAssignment = readonly [key: string, value: string];
59
87
  /**
60
88
  * Quote one executable or path for git's `!` shell command. Backslashes are
61
89
  * normalized to forward slashes first: git runs `!` helpers through `sh`,
62
- * where `C:\…` would be read as escape sequences.
90
+ * where `C:\\…` would be read as escape sequences.
63
91
  * @param value - an absolute path.
64
92
  */
65
93
  export declare function shellQuote(value: string): string;
@@ -72,22 +100,44 @@ export declare function shellQuote(value: string): string;
72
100
  */
73
101
  export declare function bridgeCommand(nodePath: string, helperPath: string): string;
74
102
  /**
75
- * The ordered environment assignments for the given hosts: per host an empty
76
- * helper value (git resets the accumulated list for that URL scope) and then
77
- * the bridge command, plus the credential-file variable the helper reads and
78
- * the two fail-fast switches.
103
+ * Escape one value for a gitconfig line: a literal `"` becomes `\"`, which is
104
+ * how a quoted path survives git's config parser and still reaches `sh`
105
+ * intact. Without this the quotes are eaten and `sh` splits
106
+ * `C:/Program Files/…` on the space.
107
+ * @param value - the raw helper command.
108
+ */
109
+ export declare function gitconfigEscape(value: string): string;
110
+ /**
111
+ * The session gitconfig body for the given hosts: the user's own config
112
+ * included (read-only), the whole machine helper list reset to empty, and per
113
+ * host a URL-scoped reset followed by the bridge command. The empty value
114
+ * before each command is what cuts the included `gh` helper (and any other
115
+ * helper the user configures for that URL) out of that scope.
79
116
  * @param hosts - normalized hosts with a stored credential.
80
- * @param options - process paths and the credential file.
117
+ * @param options - the node/helper pair and the user config to include.
81
118
  */
82
- export declare function shellBridgeEnv(hosts: readonly string[], options: {
119
+ export declare function sessionGitconfigBody(hosts: readonly string[], options: {
83
120
  readonly nodePath: string;
84
121
  readonly helperPath: string;
122
+ readonly userGitconfig?: string;
123
+ }): string;
124
+ /**
125
+ * The environment assignments pointing git at the session config: the config
126
+ * path itself, the credential file the helper reads, and the two fail-fast
127
+ * switches. `hosts` live in the file now, not in the environment.
128
+ * @param options - the session config path and the credential file.
129
+ */
130
+ export declare function shellBridgeEnv(options: {
131
+ readonly configPath: string;
85
132
  readonly credentialFile: string;
86
133
  }): readonly BridgeAssignment[];
87
134
  /**
88
135
  * Build the bridge over one host process. Every {@link ShellBridge.apply}
89
- * first removes the assignments it made last time, so a deleted host loses
90
- * its helper scope just like a freshly added one gains it.
136
+ * rewrites the session config for the current store and re-points the
137
+ * environment at it, so a deleted host loses its helper scope just like a
138
+ * freshly added one gains it. A config file that cannot be written leaves
139
+ * `GIT_CONFIG_GLOBAL` untouched (git then runs with the machine config —
140
+ * unauthenticated at worst) while the fail-fast switches still go out.
91
141
  * @param deps - host seams.
92
142
  */
93
143
  export declare function createShellBridge(deps: ShellBridgeDeps): ShellBridge;
@@ -1,40 +1,61 @@
1
1
  /**
2
- * Shell credential bridge (host half). The credential panel stores one token
3
- * per remote host, but 0029 could only inject it into the panel's own routes
4
- * and the `git_network` tool; a plain `git push` run in a shell authenticated
5
- * as whatever the machine's credential helper held — often a different
6
- * account — or hung on an interactive prompt nobody could answer.
2
+ * Shell credential bridge (host half) — session gitconfig channel. The
3
+ * credential panel stores one token per remote host, but 0029 could only
4
+ * inject it into the panel's own routes and the `git_network` tool; a plain
5
+ * `git push` run in a shell authenticated as whatever the machine's
6
+ * credential helper held — often a different account — or hung on an
7
+ * interactive prompt nobody could answer.
7
8
  *
8
- * This module closes that gap without touching the user's git configuration
9
- * FILES (0021's constraint): it exports `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_n`/
10
- * `GIT_CONFIG_VALUE_n` entries that install the bundled credential helper
11
- * (`helpers/git-credential-bridge.js`) as a URL-scoped helper for every stored
12
- * host. git reads that environment as configuration, every child process the
13
- * host spawns inherits it, and a non-empty value list is always preceded by the
14
- * same key with an empty value — git resets the accumulated helper list
15
- * there, so the machine chain (`helper-selector` → GCM) can neither answer
16
- * with a different account nor open a blocking dialog for those hosts.
17
- * The list is reset globally as well: a host with no stored credential then
18
- * fails at once ("terminal prompts disabled") instead of reaching the machine
19
- * chain, whose interactive GUI dialog nobody in an agent shell can answer.
9
+ * 0032 closed that gap with `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_n`/
10
+ * `GIT_CONFIG_VALUE_n` environment entries. That channel is dead on a DSH
11
+ * host: the subprocess environment scrubber
12
+ * (`@deepseek-ai/dsh-subprocess`, `SENSITIVE_ENV_PATTERN = /KEY|PASSWORD|SECRET|TOKEN/i`
13
+ * plus every `DSH_*` name) strips the `GIT_CONFIG_KEY_*` names and keeps
14
+ * `GIT_CONFIG_COUNT`/`VALUE_*`, so git starts with a half-parsed config and
15
+ * dies with `fatal: unable to parse command-line config` — every git command
16
+ * in the shell, not only the networked ones (0034).
20
17
  *
21
- * `GIT_TERMINAL_PROMPT=0` and `GCM_INTERACTIVE=never` ride along so a host
22
- * with no usable credential fails fast instead of parking a shell on a prompt
23
- * (the failure mode that started this: a 3m38s silent hang).
18
+ * The replacement writes ONE generated gitconfig per host process and points
19
+ * git at it with `GIT_CONFIG_GLOBAL` — a name the scrubber keeps. The file:
24
20
  *
25
- * The assignments are re-derived whenever the credential store changes
21
+ * 1. `[include]`s the user's own `~/.gitconfig` (read-only; 0021's "never
22
+ * write the user's git config files" stands) so identity, proxies and
23
+ * `http.sslBackend` keep working;
24
+ * 2. resets the whole `credential.helper` list to empty, cutting the machine
25
+ * chain (`helper-selector` → GCM) and any helper the included user config
26
+ * carries (the local `gh` helper being the motivating case);
27
+ * 3. per stored host, resets that URL scope and then installs the bundled
28
+ * helper (`helpers/git-credential-bridge.js`) as a `!`-shell command.
29
+ *
30
+ * A host with no stored credential then fails at once ("terminal prompts
31
+ * disabled") instead of reaching the machine chain, whose interactive GUI
32
+ * dialog nobody in an agent shell can answer. `GIT_TERMINAL_PROMPT=0` and
33
+ * `GCM_INTERACTIVE=never` ride along as the last line of defence.
34
+ *
35
+ * Environment contract (all names survive the scrubber — no KEY/PASSWORD/
36
+ * SECRET/TOKEN substring, no `DSH_` prefix):
37
+ * - `GIT_CONFIG_GLOBAL` — the generated session config (0034).
38
+ * - `DGB_BRIDGE_HELPER` — credential file path for the helper script.
39
+ * - `GIT_TERMINAL_PROMPT` / `GCM_INTERACTIVE` — fail fast, never prompt.
40
+ *
41
+ * The file is re-derived whenever the credential store changes
26
42
  * (`src/routes.ts` calls the bridge after every save / delete / sign-in).
27
43
  */
44
+ import { chmodSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
45
+ import { tmpdir } from 'node:os';
46
+ import { dirname, join } from 'node:path';
28
47
  import { fileURLToPath } from 'node:url';
29
48
  import { credentialFilePath, createCredentialStore, } from './credentials.js';
30
49
  /** Env var carrying the credential file path to the helper script. */
31
- export const BRIDGE_HELPER_ENV = 'DSH_GIT_BRIDGE_HELPER';
50
+ export const BRIDGE_HELPER_ENV = 'DGB_BRIDGE_HELPER';
32
51
  /** Env var carrying a debug log path to the helper script (unset by default). */
33
- export const BRIDGE_DEBUG_ENV = 'DSH_GIT_BRIDGE_DEBUG';
52
+ export const BRIDGE_DEBUG_ENV = 'DGB_BRIDGE_DEBUG';
53
+ /** Env var pointing git at the generated session configuration file. */
54
+ export const SESSION_GITCONFIG_ENV = 'GIT_CONFIG_GLOBAL';
34
55
  /**
35
56
  * Quote one executable or path for git's `!` shell command. Backslashes are
36
57
  * normalized to forward slashes first: git runs `!` helpers through `sh`,
37
- * where `C:\…` would be read as escape sequences.
58
+ * where `C:\\…` would be read as escape sequences.
38
59
  * @param value - an absolute path.
39
60
  */
40
61
  export function shellQuote(value) {
@@ -51,50 +72,101 @@ export function bridgeCommand(nodePath, helperPath) {
51
72
  return `!${shellQuote(nodePath)} ${shellQuote(helperPath)}`;
52
73
  }
53
74
  /**
54
- * The ordered environment assignments for the given hosts: per host an empty
55
- * helper value (git resets the accumulated list for that URL scope) and then
56
- * the bridge command, plus the credential-file variable the helper reads and
57
- * the two fail-fast switches.
75
+ * Escape one value for a gitconfig line: a literal `"` becomes `\"`, which is
76
+ * how a quoted path survives git's config parser and still reaches `sh`
77
+ * intact. Without this the quotes are eaten and `sh` splits
78
+ * `C:/Program Files/…` on the space.
79
+ * @param value - the raw helper command.
80
+ */
81
+ export function gitconfigEscape(value) {
82
+ return value.replace(/"/g, '\\"');
83
+ }
84
+ /**
85
+ * The session gitconfig body for the given hosts: the user's own config
86
+ * included (read-only), the whole machine helper list reset to empty, and per
87
+ * host a URL-scoped reset followed by the bridge command. The empty value
88
+ * before each command is what cuts the included `gh` helper (and any other
89
+ * helper the user configures for that URL) out of that scope.
58
90
  * @param hosts - normalized hosts with a stored credential.
59
- * @param options - process paths and the credential file.
91
+ * @param options - the node/helper pair and the user config to include.
60
92
  */
61
- export function shellBridgeEnv(hosts, options) {
93
+ export function sessionGitconfigBody(hosts, options) {
62
94
  const unique = [...new Set(hosts)];
63
- const assignments = [];
64
- // Reset the WHOLE helper list first, even when no host is stored. Without it,
65
- // any host without a stored credential still reaches the machine chain
95
+ const lines = [
96
+ '# Generated by dsh-git-branch-manage (shell credential bridge, decision 0034). Do not edit.',
97
+ '# Regenerated whenever the credential store changes; safe to delete.',
98
+ ];
99
+ if (options.userGitconfig !== undefined) {
100
+ // Read-only include: the user\'s identity, proxies and TLS settings keep
101
+ // working, and nothing is ever written back to this file.
102
+ lines.push('[include]', `\tpath = ${options.userGitconfig.replace(/\\/g, '/')}`);
103
+ }
104
+ // Reset the WHOLE helper list first, even when no host is stored. Without
105
+ // it, any host without a stored credential still reaches the machine chain
66
106
  // (`helper-selector` → GCM), which raises a GUI prompt no agent shell can
67
- // answer — the dialog that kept popping up. With it, such a host fails at
68
- // once with "terminal prompts disabled", and the URL-scoped pairs below are
69
- // the only way credentials get back into a shell.
70
- assignments.push(['GIT_CONFIG_COUNT', String(unique.length * 2 + 1)]);
71
- assignments.push(['GIT_CONFIG_KEY_0', 'credential.helper'], ['GIT_CONFIG_VALUE_0', '']);
72
- unique.forEach((host, index) => {
73
- const key = `credential.https://${host}/.helper`;
74
- const empty = String(index * 2 + 1);
75
- const command = String(index * 2 + 2);
76
- assignments.push([`GIT_CONFIG_KEY_${empty}`, key], [`GIT_CONFIG_VALUE_${empty}`, '']);
77
- assignments.push([`GIT_CONFIG_KEY_${command}`, key], [`GIT_CONFIG_VALUE_${command}`, bridgeCommand(options.nodePath, options.helperPath)]);
78
- });
79
- assignments.push([BRIDGE_HELPER_ENV, options.credentialFile]);
80
- // Fail fast instead of parking a shell on a prompt or a GUI dialog.
81
- assignments.push(['GIT_TERMINAL_PROMPT', '0'], ['GCM_INTERACTIVE', 'never']);
82
- return assignments;
107
+ // answer. With it, such a host fails at once with "terminal prompts
108
+ // disabled", and the URL-scoped pairs below are the only way credentials
109
+ // get back into a shell.
110
+ lines.push('[credential]', '\thelper =');
111
+ const command = gitconfigEscape(bridgeCommand(options.nodePath, options.helperPath));
112
+ for (const host of unique) {
113
+ lines.push(`[credential "https://${host}/"]`,
114
+ // Empty first: it resets whatever helper list the included user config
115
+ // accumulated for this URL (the local `gh` helper), or git would answer
116
+ // with that account before the bridge is ever consulted.
117
+ '\thelper =', `\thelper = ${command}`);
118
+ }
119
+ return `${lines.join('\n')}\n`;
120
+ }
121
+ /**
122
+ * The environment assignments pointing git at the session config: the config
123
+ * path itself, the credential file the helper reads, and the two fail-fast
124
+ * switches. `hosts` live in the file now, not in the environment.
125
+ * @param options - the session config path and the credential file.
126
+ */
127
+ export function shellBridgeEnv(options) {
128
+ return [
129
+ [SESSION_GITCONFIG_ENV, options.configPath],
130
+ [BRIDGE_HELPER_ENV, options.credentialFile],
131
+ // Fail fast instead of parking a shell on a prompt or a GUI dialog.
132
+ ['GIT_TERMINAL_PROMPT', '0'],
133
+ ['GCM_INTERACTIVE', 'never'],
134
+ ];
83
135
  }
84
136
  /**
85
137
  * Build the bridge over one host process. Every {@link ShellBridge.apply}
86
- * first removes the assignments it made last time, so a deleted host loses
87
- * its helper scope just like a freshly added one gains it.
138
+ * rewrites the session config for the current store and re-points the
139
+ * environment at it, so a deleted host loses its helper scope just like a
140
+ * freshly added one gains it. A config file that cannot be written leaves
141
+ * `GIT_CONFIG_GLOBAL` untouched (git then runs with the machine config —
142
+ * unauthenticated at worst) while the fail-fast switches still go out.
88
143
  * @param deps - host seams.
89
144
  */
90
145
  export function createShellBridge(deps) {
91
146
  const env = deps.env ?? process.env;
147
+ const configPath = deps.configPath
148
+ ?? join((deps.configDir ?? tmpdir)(), `dsh-git-branch-${String(process.pid)}.gitconfig`);
92
149
  let applied = [];
150
+ const credentialFile = () => credentialFilePath(deps.home(), deps.envHome());
151
+ /** Write the session config atomically with owner-only permissions. */
152
+ const writeConfig = (body) => {
153
+ mkdirSync(dirname(configPath), { recursive: true });
154
+ const partial = `${configPath}.tmp`;
155
+ writeFileSync(partial, body, { encoding: 'utf8', mode: 0o600 });
156
+ renameSync(partial, configPath);
157
+ try {
158
+ chmodSync(configPath, 0o600);
159
+ }
160
+ catch {
161
+ // Best effort: Windows ignores the mode, the file holds no secret.
162
+ }
163
+ };
93
164
  return {
165
+ configPath: () => configPath,
94
166
  async apply() {
95
167
  let hosts = [];
96
168
  try {
97
- hosts = (await (deps.store ?? createCredentialStore(credentialFilePath(deps.home(), deps.envHome()))).load()).map(entry => entry.host);
169
+ hosts = (await (deps.store ?? createCredentialStore(credentialFile())).load()).map(entry => entry.host);
98
170
  }
99
171
  catch {
100
172
  // An unreadable store means no host can be bridged. The global helper
@@ -104,11 +176,25 @@ export function createShellBridge(deps) {
104
176
  }
105
177
  const helperPath = deps.helperPath
106
178
  ?? fileURLToPath(new URL('./helpers/git-credential-bridge.js', import.meta.url));
107
- const assignments = shellBridgeEnv(hosts, {
179
+ const body = sessionGitconfigBody(hosts, {
108
180
  nodePath: deps.nodePath ?? process.execPath,
109
181
  helperPath,
110
- credentialFile: credentialFilePath(deps.home(), deps.envHome()),
182
+ userGitconfig: deps.userGitconfig ?? join(deps.home(), '.gitconfig'),
111
183
  });
184
+ let assignments = [
185
+ ['GIT_TERMINAL_PROMPT', '0'],
186
+ ['GCM_INTERACTIVE', 'never'],
187
+ ];
188
+ try {
189
+ writeConfig(body);
190
+ assignments = shellBridgeEnv({ configPath, credentialFile: credentialFile() });
191
+ }
192
+ catch {
193
+ // The session config could not be written. Do not point
194
+ // GIT_CONFIG_GLOBAL at a missing file (that would drop the reset and
195
+ // let the machine chain pop a dialog); only the fail-fast switches
196
+ // remain, so a shell git runs unauthenticated but never hangs.
197
+ }
112
198
  for (const key of applied)
113
199
  delete env[key];
114
200
  applied = [];
@@ -117,5 +203,16 @@ export function createShellBridge(deps) {
117
203
  applied.push(key);
118
204
  }
119
205
  },
206
+ async dispose() {
207
+ for (const key of applied)
208
+ delete env[key];
209
+ applied = [];
210
+ try {
211
+ rmSync(configPath, { force: true });
212
+ }
213
+ catch {
214
+ // Best effort: a leftover file holds no secret and apply rewrites it.
215
+ }
216
+ },
120
217
  };
121
218
  }
package/lib/tool.d.ts CHANGED
@@ -15,6 +15,7 @@
15
15
  * @module dsh-git-branch/tool
16
16
  */
17
17
  import { type CredentialStore } from './credentials.js';
18
+ import type { CredentialService } from './credential-service.js';
18
19
  /** Model-facing tool name. */
19
20
  export declare const GIT_CREDENTIALS_TOOL_NAME = "git_credentials";
20
21
  /** One text block in a tool result. */
@@ -58,6 +59,9 @@ export interface GitCredentialsToolDeps {
58
59
  readonly envHome: () => string | undefined;
59
60
  /** Store seam; the fs-backed store at the resolved path when absent. */
60
61
  readonly store?: CredentialStore;
62
+ /** The single credential entry point (decision 0034); when wired its store
63
+ * is shared with the routes and the shell bridge. */
64
+ readonly credentialsService?: CredentialService;
61
65
  }
62
66
  /** A tool definition as `ctx.tools.register` accepts it. */
63
67
  export interface GitCredentialsTool {
package/lib/tool.js CHANGED
@@ -48,7 +48,7 @@ export function renderGitCredentials(value) {
48
48
  * @returns a definition ready for `ctx.tools.register`.
49
49
  */
50
50
  export function gitCredentialsTool(deps) {
51
- const storeOf = () => deps.store ?? createCredentialStore(credentialFilePath(deps.home(), deps.envHome()));
51
+ const storeOf = () => deps.credentialsService?.store ?? deps.store ?? createCredentialStore(credentialFilePath(deps.home(), deps.envHome()));
52
52
  /** Read the store, folding a read failure into the result value. */
53
53
  const read = async (args) => {
54
54
  const store = storeOf();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-git-branch-manage",
3
- "version": "1.0.10",
3
+ "version": "1.1.0",
4
4
  "description": "提供 git 分支与 worktree 管理:输入框工具栏显示当前分支、可原地切换;支持 IDEA 风格分支选择器、远程分支检出、右键操作菜单(新建/重命名/删除/复制)、推送与更新当前分支,以及把分支隔离到独立 worktree 工作区,并管理其创建与删除。",
5
5
  "keywords": [
6
6
  "dsh",
@@ -45,6 +45,7 @@
45
45
  "!lib/**/*.map",
46
46
  "cordis.patch.yml",
47
47
  "README.md",
48
+ "CHANGELOG.md",
48
49
  "locale/*.json",
49
50
  "icon.svg"
50
51
  ],