@myrialabs/clopen 0.4.41 → 0.4.42

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.
Files changed (61) hide show
  1. package/backend/chat/stream-manager.ts +8 -0
  2. package/backend/database/crypto/secret-columns.ts +5 -1
  3. package/backend/database/index.ts +18 -0
  4. package/backend/database/migrations/082_create_git_identities.test.ts +186 -0
  5. package/backend/database/migrations/082_create_git_identities.ts +122 -0
  6. package/backend/database/migrations/index.ts +7 -0
  7. package/backend/database/queries/git-identity-queries.ts +290 -0
  8. package/backend/database/queries/index.ts +2 -0
  9. package/backend/engine/adapters/claude/environment.ts +11 -1
  10. package/backend/engine/adapters/claude/stream.ts +1 -1
  11. package/backend/engine/adapters/codex/stream.ts +35 -3
  12. package/backend/engine/adapters/opencode/server.ts +26 -2
  13. package/backend/engine/adapters/opencode/stream.ts +4 -1
  14. package/backend/engine/adapters/qwen/stream.ts +3 -1
  15. package/backend/engine/types.ts +10 -0
  16. package/backend/git/git-executor.ts +28 -2
  17. package/backend/git/git-service.ts +59 -40
  18. package/backend/git/identity/cli.test.ts +58 -0
  19. package/backend/git/identity/cli.ts +201 -0
  20. package/backend/git/identity/credential-helper.test.ts +242 -0
  21. package/backend/git/identity/env.test.ts +214 -0
  22. package/backend/git/identity/env.ts +193 -0
  23. package/backend/git/identity/import-local.test.ts +199 -0
  24. package/backend/git/identity/import-local.ts +141 -0
  25. package/backend/git/identity/index.ts +78 -0
  26. package/backend/git/identity/keys.ts +183 -0
  27. package/backend/git/identity/resolve.ts +140 -0
  28. package/backend/git/identity/scope-config.test.ts +145 -0
  29. package/backend/git/identity/scope-config.ts +175 -0
  30. package/backend/git/identity/service.ts +297 -0
  31. package/backend/index.ts +16 -0
  32. package/backend/preview/browser/browser-console-manager.ts +214 -34
  33. package/backend/preview/browser/browser-pool.ts +526 -123
  34. package/backend/preview/browser/browser-preview-service.ts +192 -8
  35. package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
  36. package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
  37. package/backend/preview/browser/browser-tab-manager.ts +291 -65
  38. package/backend/preview/browser/capture-profile.ts +15 -1
  39. package/backend/preview/browser/types.ts +26 -1
  40. package/backend/terminal/ptykit.ts +24 -0
  41. package/backend/ws/git/branch.ts +17 -6
  42. package/backend/ws/git/commit.ts +6 -5
  43. package/backend/ws/git/conflict.ts +3 -2
  44. package/backend/ws/git/identity-context.ts +91 -0
  45. package/backend/ws/git/identity.ts +200 -0
  46. package/backend/ws/git/index.ts +3 -1
  47. package/backend/ws/git/remote.ts +57 -11
  48. package/backend/ws/preview/browser/data.ts +60 -0
  49. package/backend/ws/preview/browser/interact.ts +6 -0
  50. package/backend/ws/preview/browser/tab-info.ts +9 -1
  51. package/backend/ws/preview/browser/tab.ts +64 -8
  52. package/backend/ws/preview/index.ts +21 -0
  53. package/bin/clopen.ts +9 -0
  54. package/dist/assets/{index-CeNKKSDR.js → index-BynqyvF4.js} +1 -1
  55. package/dist/assets/{index-DW89566K.js → index-DLoJsmNQ.js} +1 -1
  56. package/dist/assets/{main-Cy5DXWPT.js → main-CUyZAmqt.js} +591 -584
  57. package/dist/assets/main-DVCW3cfr.css +1 -0
  58. package/dist/index.html +2 -2
  59. package/package.json +2 -2
  60. package/shared/types/git-identity.ts +112 -0
  61. package/dist/assets/main-DJKj_4By.css +0 -1
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The helper's input parsing, which authentication depends on.
3
+ *
4
+ * Git speaks a line protocol on stdin and reads the answer on stdout, so a
5
+ * mis-parse does not fail loudly — it produces a helper that silently answers
6
+ * nothing, and a push that asks for a password nobody typed.
7
+ */
8
+
9
+ import { describe, expect, test } from 'bun:test';
10
+ import { identityIdFrom, parseCredentialRequest } from './cli';
11
+
12
+ describe('parseCredentialRequest', () => {
13
+ test('reads the key=value lines git sends', () => {
14
+ expect(
15
+ parseCredentialRequest('protocol=https\nhost=github.com\npath=owner/repo.git\n\n')
16
+ ).toEqual({
17
+ protocol: 'https',
18
+ host: 'github.com',
19
+ path: 'owner/repo.git'
20
+ });
21
+ });
22
+
23
+ test('keeps a value containing "=" intact', () => {
24
+ // Only the FIRST `=` separates; a token or query string would otherwise
25
+ // arrive truncated at its first equals sign.
26
+ expect(parseCredentialRequest('password=abc=def=ghi\n')).toEqual({
27
+ password: 'abc=def=ghi'
28
+ });
29
+ });
30
+
31
+ test('ignores blank lines and malformed rows rather than failing', () => {
32
+ expect(parseCredentialRequest('\nhost=github.com\n\n=novalue\ngarbage\n')).toEqual({
33
+ host: 'github.com'
34
+ });
35
+ });
36
+
37
+ test('an empty value is a value, not a missing key', () => {
38
+ expect(parseCredentialRequest('username=\n')).toEqual({ username: '' });
39
+ });
40
+
41
+ test('empty input yields no fields', () => {
42
+ expect(parseCredentialRequest('')).toEqual({});
43
+ });
44
+ });
45
+
46
+ describe('identityIdFrom', () => {
47
+ test('finds the flag among git-appended arguments', () => {
48
+ // Git appends the operation after our own arguments.
49
+ expect(identityIdFrom(['--identity=abc-123', 'get'])).toBe('abc-123');
50
+ expect(identityIdFrom(['get', '--identity=abc-123'])).toBe('abc-123');
51
+ });
52
+
53
+ test('a missing or empty flag yields null, so the helper declines', () => {
54
+ expect(identityIdFrom(['get'])).toBeNull();
55
+ expect(identityIdFrom(['--identity=', 'get'])).toBeNull();
56
+ expect(identityIdFrom([])).toBeNull();
57
+ });
58
+ });
@@ -0,0 +1,201 @@
1
+ /**
2
+ * The two helper subcommands git invokes: `git-credential` and `git-askpass`.
3
+ *
4
+ * Both exist for one reason: A SECRET MUST NOT TRAVEL THROUGH ARGV OR THE
5
+ * ENVIRONMENT. `ps` shows another user on the same machine every argument of
6
+ * every running process, and the alternatives git offers all leak:
7
+ * `http.extraheader` puts the token in the command line, `credential.helper
8
+ * store` writes it to a plaintext file, and a token embedded in a remote URL
9
+ * persists in `.git/config`. A helper receives its question on stdin and
10
+ * answers on stdout, which no other process can read.
11
+ *
12
+ * ── STDOUT IS THE PROTOCOL ──
13
+ * Git parses this process's stdout. Anything else written there — a debug line,
14
+ * a warning, a stray `console.log` from a module loaded on the way in — is read
15
+ * as part of the answer and corrupts it. So the first thing either entry point
16
+ * does is move `console.log` to stderr. That is not tidiness; it is what keeps
17
+ * an unrelated log statement from breaking authentication.
18
+ *
19
+ * These run in a SHORT-LIVED SEPARATE PROCESS. Git spawns them, they answer,
20
+ * they exit. They open the database directly and start no server.
21
+ */
22
+
23
+ /**
24
+ * Silence routine logging for the rest of this process.
25
+ *
26
+ * `debug.log` writes through `console.log`, which is stdout — the protocol
27
+ * channel. Redirecting it to stderr protects the protocol but then prints
28
+ * "Connected to database" into the middle of the user's `git push` output,
29
+ * which is noise they can neither act on nor turn off. So routine logs are
30
+ * dropped entirely; a genuine helper failure still goes to stderr through
31
+ * `console.error`, which git shows and which is worth showing.
32
+ */
33
+ function protectStdout(): void {
34
+ const drop = () => {};
35
+ console.log = drop;
36
+ console.info = drop;
37
+ console.debug = drop;
38
+ }
39
+
40
+ /** `--identity=<id>` out of the helper's own arguments. */
41
+ export function identityIdFrom(argv: string[]): string | null {
42
+ for (const arg of argv) {
43
+ if (arg.startsWith('--identity=')) {
44
+ const value = arg.slice('--identity='.length).trim();
45
+ if (value) return value;
46
+ }
47
+ }
48
+ return null;
49
+ }
50
+
51
+ /**
52
+ * Open the existing database, without migrating or seeding it.
53
+ *
54
+ * `initializeDatabase()` would run migrations and seeders — the right thing for
55
+ * a server starting up, the wrong thing for a helper git spawned mid-push. It
56
+ * would race the running server's schema and could apply a migration from a
57
+ * process nobody is watching. A helper only ever reads one row.
58
+ */
59
+ async function connectReadOnly(): Promise<void> {
60
+ const { connectExistingDatabase } = await import('$backend/database');
61
+ await connectExistingDatabase();
62
+ }
63
+
64
+ /** Read stdin to the end. Empty string when nothing is piped. */
65
+ async function readStdin(): Promise<string> {
66
+ try {
67
+ return await new Response(Bun.stdin.stream()).text();
68
+ } catch {
69
+ return '';
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Parse git's credential description: `key=value` lines, blank line terminated.
75
+ *
76
+ * Unknown keys are kept — git adds fields over time, and one we do not
77
+ * recognise is not a reason to fail an authentication.
78
+ */
79
+ export function parseCredentialRequest(input: string): Record<string, string> {
80
+ const fields: Record<string, string> = {};
81
+ for (const line of input.split('\n')) {
82
+ const trimmed = line.trim();
83
+ if (!trimmed) continue;
84
+ const eq = trimmed.indexOf('=');
85
+ if (eq <= 0) continue;
86
+ fields[trimmed.slice(0, eq)] = trimmed.slice(eq + 1);
87
+ }
88
+ return fields;
89
+ }
90
+
91
+ /**
92
+ * Answer a `git credential` request.
93
+ *
94
+ * Only `get` produces output. `store` and `erase` are accepted and ignored on
95
+ * purpose: the credential lives in Clopen's database, and letting git overwrite
96
+ * or delete it would put git's cache in charge of a user's stored account.
97
+ * Exiting 0 without output tells git "no opinion", which is the correct answer
98
+ * for a read-only helper.
99
+ */
100
+ async function runCredentialHelper(argv: string[]): Promise<number> {
101
+ const operation = argv.find((a) => !a.startsWith('--')) ?? 'get';
102
+ if (operation !== 'get') return 0;
103
+
104
+ const identityId = identityIdFrom(argv);
105
+ if (!identityId) return 0;
106
+
107
+ const request = parseCredentialRequest(await readStdin());
108
+
109
+ // Imported here, after stdout is protected, and lazily so `store`/`erase`
110
+ // never pay for opening the database.
111
+ await connectReadOnly();
112
+ const { gitIdentityQueries, integrationAccountQueries, parseHosts } = await import(
113
+ '$backend/database/queries'
114
+ );
115
+
116
+ const row = gitIdentityQueries.getById(identityId);
117
+ if (!row) return 0;
118
+
119
+ // The host git is asking about must be one this identity claims. Without the
120
+ // check, a repository whose remote was changed to another host would be
121
+ // handed this account's token.
122
+ const host = (request.host ?? '').toLowerCase().split(':')[0] ?? '';
123
+ if (host && !parseHosts(row.hosts).includes(host)) return 0;
124
+
125
+ let token: string | null = null;
126
+ if (row.auth_method === 'https-token') {
127
+ token = row.https_token;
128
+ } else if (row.auth_method === 'https-account' && row.integration_account_id) {
129
+ // Borrowed from a connected integration account, so rotating the token in
130
+ // one place is enough.
131
+ const account = integrationAccountQueries.getById(row.integration_account_id);
132
+ if (account) {
133
+ const credentials = integrationAccountQueries.credentialsOf(account);
134
+ token = credentials.token ?? credentials.apiKey ?? null;
135
+ }
136
+ }
137
+ if (!token) return 0;
138
+
139
+ // GitHub and friends accept any non-empty username alongside a token, but it
140
+ // must not be blank, so fall back to the conventional placeholder.
141
+ const username = row.https_username || request.username || 'x-access-token';
142
+ process.stdout.write(`username=${username}\npassword=${token}\n`);
143
+ return 0;
144
+ }
145
+
146
+ /**
147
+ * Answer `ssh`'s passphrase prompt.
148
+ *
149
+ * `ssh` calls SSH_ASKPASS with the prompt text as an argument and reads the
150
+ * answer from stdout. Only passphrase prompts are answered: a host-key
151
+ * confirmation ("Are you sure you want to continue connecting?") reaching this
152
+ * helper must not be auto-accepted, because that is the check that detects a
153
+ * man-in-the-middle.
154
+ */
155
+ async function runAskpass(argv: string[]): Promise<number> {
156
+ const identityId = identityIdFrom(argv);
157
+ if (!identityId) return 1;
158
+
159
+ const prompt = argv.filter((a) => !a.startsWith('--') && a !== 'git-askpass').join(' ');
160
+ if (prompt && !/passphrase|password/i.test(prompt)) {
161
+ // Declining leaves ssh to fail the way it would without us, which is the
162
+ // safe outcome for anything that is not a passphrase question.
163
+ return 1;
164
+ }
165
+
166
+ await connectReadOnly();
167
+ const { gitIdentityQueries } = await import('$backend/database/queries');
168
+
169
+ const row = gitIdentityQueries.getById(identityId);
170
+ if (!row?.ssh_passphrase) return 1;
171
+
172
+ process.stdout.write(`${row.ssh_passphrase}\n`);
173
+ return 0;
174
+ }
175
+
176
+ /** The subcommands this module owns. */
177
+ export const GIT_HELPER_COMMANDS = ['git-credential', 'git-askpass'] as const;
178
+
179
+ /**
180
+ * Handle a helper subcommand if this invocation is one.
181
+ *
182
+ * Returns the exit code to use, or `null` when the arguments are not a helper
183
+ * call and the CLI should carry on to its normal startup.
184
+ */
185
+ export async function runGitHelper(argv: string[]): Promise<number | null> {
186
+ const command = argv[0];
187
+ if (command !== 'git-credential' && command !== 'git-askpass') return null;
188
+
189
+ protectStdout();
190
+
191
+ try {
192
+ return command === 'git-credential'
193
+ ? await runCredentialHelper(argv.slice(1))
194
+ : await runAskpass(argv.slice(1));
195
+ } catch (error) {
196
+ // Never print the failure to stdout, and never expose the reason to git —
197
+ // an empty answer means "no credential", which is what a failure is.
198
+ console.error('[clopen] git helper failed:', error);
199
+ return command === 'git-credential' ? 0 : 1;
200
+ }
201
+ }
@@ -0,0 +1,242 @@
1
+ /**
2
+ * The credential path, end to end, against real git.
3
+ *
4
+ * Unit tests cover the shape of the environment; they cannot catch what this
5
+ * file exists for. Two bugs got through them and were only found by running
6
+ * git:
7
+ *
8
+ * 1. `credential.helper` is a MULTI-VALUE key. The user's global config
9
+ * normally names one (osxkeychain, libsecret, manager), it is consulted
10
+ * before ours, and first answer wins — so choosing the "Work" account and
11
+ * pushing authenticated with whatever the system keychain volunteered. It
12
+ * failed silently: the push succeeded, under the wrong account.
13
+ * 2. Connecting the database manager is not the same as registering it, so the
14
+ * helper threw `Database not initialized` and answered nothing, which git
15
+ * reports as "could not read Password".
16
+ *
17
+ * Everything runs in its own data directory and its own repository, so the
18
+ * developer's real `~/.clopen` and git config are never touched. A system
19
+ * credential helper being configured on the machine is not a problem for this
20
+ * test — it is the thing being tested against.
21
+ */
22
+
23
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
24
+ import { mkdtemp, rm } from 'node:fs/promises';
25
+ import { tmpdir } from 'node:os';
26
+ import { join, resolve } from 'node:path';
27
+ import { buildGitIdentityEnv } from './env';
28
+
29
+ const REPO_ROOT = resolve(import.meta.dir, '../../..');
30
+ const CLI_ENTRY = join(REPO_ROOT, 'bin/clopen.ts');
31
+
32
+ let dataDir = '';
33
+ let repoDir = '';
34
+
35
+ /** Identity env as the real builder produces it, pointed at the real CLI. */
36
+ function identityEnv(): Record<string, string> {
37
+ return buildGitIdentityEnv(
38
+ {
39
+ id: 'id-test',
40
+ name: 'Ada Lovelace',
41
+ email: 'ada@example.com',
42
+ httpsUsername: 'ada',
43
+ credentialHosts: ['github.com']
44
+ },
45
+ { runtime: process.execPath, script: CLI_ENTRY }
46
+ );
47
+ }
48
+
49
+ async function run(
50
+ cmd: string[],
51
+ options: { cwd?: string; env?: Record<string, string>; stdin?: string } = {}
52
+ ): Promise<{ stdout: string; stderr: string; code: number }> {
53
+ const proc = Bun.spawn(cmd, {
54
+ cwd: options.cwd ?? repoDir,
55
+ env: { ...process.env, ...(options.env ?? {}) } as Record<string, string>,
56
+ stdin: options.stdin === undefined ? 'ignore' : new TextEncoder().encode(options.stdin),
57
+ stdout: 'pipe',
58
+ stderr: 'pipe'
59
+ });
60
+ const [stdout, stderr] = await Promise.all([
61
+ new Response(proc.stdout).text(),
62
+ new Response(proc.stderr).text()
63
+ ]);
64
+ return { stdout, stderr, code: await proc.exited };
65
+ }
66
+
67
+ beforeAll(async () => {
68
+ dataDir = await mkdtemp(join(tmpdir(), 'clopen-cred-data-'));
69
+ repoDir = await mkdtemp(join(tmpdir(), 'clopen-cred-repo-'));
70
+ await run(['git', 'init', '-q', '.']);
71
+
72
+ // Seed an identity in the isolated data directory, through the real query
73
+ // layer so the token is sealed exactly as it is in production.
74
+ const seed = `
75
+ import { initializeDatabase, getDatabase } from '$backend/database';
76
+ import { gitIdentityQueries } from '$backend/database/queries';
77
+ await initializeDatabase();
78
+ const now = new Date().toISOString();
79
+ getDatabase().prepare(
80
+ \`INSERT INTO users (id, name, color, avatar, role, created_at, updated_at)
81
+ VALUES ('u-test', 'Ada', '#fff', 'a', 'admin', ?, ?)\`
82
+ ).run(now, now);
83
+ gitIdentityQueries.create('id-test', 'u-test', {
84
+ label: 'Work',
85
+ name: 'Ada Lovelace',
86
+ email: 'ada@example.com',
87
+ authMethod: 'https-token',
88
+ hosts: ['github.com'],
89
+ httpsUsername: 'ada',
90
+ httpsToken: 'test-token-value'
91
+ });
92
+ `;
93
+ const seedFile = join(REPO_ROOT, `.seed-identity-${process.pid}.ts`);
94
+ await Bun.write(seedFile, seed);
95
+ try {
96
+ const result = await run([process.execPath, 'run', seedFile], {
97
+ cwd: REPO_ROOT,
98
+ env: { CLOPEN_DATA_DIR: dataDir }
99
+ });
100
+ if (result.code !== 0) throw new Error(`seeding failed: ${result.stderr}`);
101
+ } finally {
102
+ await rm(seedFile, { force: true });
103
+ }
104
+ }, 120_000);
105
+
106
+ afterAll(async () => {
107
+ await rm(dataDir, { recursive: true, force: true });
108
+ await rm(repoDir, { recursive: true, force: true });
109
+ });
110
+
111
+ describe('the git credential helper', () => {
112
+ test('answers with the identity\'s credential for a claimed host', async () => {
113
+ const result = await run([process.execPath, CLI_ENTRY, 'git-credential', '--identity=id-test', 'get'], {
114
+ env: { CLOPEN_DATA_DIR: dataDir },
115
+ stdin: 'protocol=https\nhost=github.com\npath=owner/repo.git\n\n'
116
+ });
117
+ expect(result.stdout).toContain('username=ada');
118
+ expect(result.stdout).toContain('password=test-token-value');
119
+ }, 60_000);
120
+
121
+ test('declines for a host the identity does not claim', async () => {
122
+ // Otherwise a repository whose remote moved to another host would be
123
+ // handed this account's token.
124
+ const result = await run([process.execPath, CLI_ENTRY, 'git-credential', '--identity=id-test', 'get'], {
125
+ env: { CLOPEN_DATA_DIR: dataDir },
126
+ stdin: 'protocol=https\nhost=gitlab.com\n\n'
127
+ });
128
+ expect(result.stdout.trim()).toBe('');
129
+ }, 60_000);
130
+
131
+ test('writes nothing but the protocol to stdout', async () => {
132
+ // Git parses stdout. A stray log line there corrupts the answer, which is
133
+ // why the helper silences routine logging.
134
+ const result = await run([process.execPath, CLI_ENTRY, 'git-credential', '--identity=id-test', 'get'], {
135
+ env: { CLOPEN_DATA_DIR: dataDir },
136
+ stdin: 'protocol=https\nhost=github.com\n\n'
137
+ });
138
+ const lines = result.stdout.trim().split('\n');
139
+ expect(lines).toEqual(['username=ada', 'password=test-token-value']);
140
+ }, 60_000);
141
+
142
+ test('ignores store and erase, leaving Clopen the owner of the credential', async () => {
143
+ for (const operation of ['store', 'erase']) {
144
+ const result = await run([process.execPath, CLI_ENTRY, 'git-credential', '--identity=id-test', operation], {
145
+ env: { CLOPEN_DATA_DIR: dataDir },
146
+ stdin: 'protocol=https\nhost=github.com\nusername=x\npassword=y\n\n'
147
+ });
148
+ expect(result.code).toBe(0);
149
+ expect(result.stdout.trim()).toBe('');
150
+ }
151
+ // The stored token is untouched by either.
152
+ const after = await run([process.execPath, CLI_ENTRY, 'git-credential', '--identity=id-test', 'get'], {
153
+ env: { CLOPEN_DATA_DIR: dataDir },
154
+ stdin: 'protocol=https\nhost=github.com\n\n'
155
+ });
156
+ expect(after.stdout).toContain('password=test-token-value');
157
+ }, 120_000);
158
+ });
159
+
160
+ describe('git consuming the identity environment', () => {
161
+ test('uses our helper rather than the machine\'s configured one', async () => {
162
+ const result = await run(['git', 'credential', 'fill'], {
163
+ env: { ...identityEnv(), CLOPEN_DATA_DIR: dataDir },
164
+ stdin: 'protocol=https\nhost=github.com\n\n'
165
+ });
166
+ expect(result.stdout).toContain('username=ada');
167
+ expect(result.stdout).toContain('password=test-token-value');
168
+ }, 60_000);
169
+
170
+ test('a helper already configured on the machine cannot answer first', async () => {
171
+ // The regression guard for bug (1), made deterministic: rather than relying
172
+ // on whatever credential helper this machine happens to have, the test
173
+ // repository configures one of its own. Local config is read before the
174
+ // environment's, so without the empty-value reset this intruder answers
175
+ // first and the push authenticates as the wrong account — silently, since
176
+ // the push still succeeds.
177
+ //
178
+ // The identity here has NO username, which is the vulnerable shape: a
179
+ // `credential.<url>.username` narrows the lookup enough that a real
180
+ // keychain often misses and hides the bug.
181
+ const repoWithHelper = await mkdtemp(join(tmpdir(), 'clopen-cred-intruder-'));
182
+ try {
183
+ await run(['git', 'init', '-q', '.'], { cwd: repoWithHelper });
184
+ await run(
185
+ [
186
+ 'git',
187
+ 'config',
188
+ '--local',
189
+ 'credential.helper',
190
+ '!f() { echo username=intruder; echo password=wrong-token; }; f'
191
+ ],
192
+ { cwd: repoWithHelper }
193
+ );
194
+
195
+ // The developer's own global config is pinned out of the way, so the
196
+ // test asserts against a known helper instead of whatever this machine
197
+ // happens to have installed. (Which, notably, wins over local config —
198
+ // that is how the original bug reached a real push.)
199
+ const isolate = { GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' };
200
+
201
+ // Sanity check: the intruder does answer when we are not involved.
202
+ const withoutUs = await run(['git', 'credential', 'fill'], {
203
+ cwd: repoWithHelper,
204
+ env: isolate,
205
+ stdin: 'protocol=https\nhost=github.com\n\n'
206
+ });
207
+ expect(withoutUs.stdout).toContain('password=wrong-token');
208
+
209
+ const env = buildGitIdentityEnv(
210
+ {
211
+ id: 'id-test',
212
+ name: 'Ada Lovelace',
213
+ email: 'ada@example.com',
214
+ credentialHosts: ['github.com']
215
+ },
216
+ { runtime: process.execPath, script: CLI_ENTRY }
217
+ );
218
+
219
+ const withUs = await run(['git', 'credential', 'fill'], {
220
+ cwd: repoWithHelper,
221
+ env: { ...env, ...isolate, CLOPEN_DATA_DIR: dataDir },
222
+ stdin: 'protocol=https\nhost=github.com\n\n'
223
+ });
224
+ expect(withUs.stdout).not.toContain('wrong-token');
225
+ expect(withUs.stdout).not.toContain('intruder');
226
+ expect(withUs.stdout).toContain('password=test-token-value');
227
+ } finally {
228
+ await rm(repoWithHelper, { recursive: true, force: true });
229
+ }
230
+ }, 120_000);
231
+
232
+ test('leaves a host the identity does not claim to the machine', async () => {
233
+ // The reset is scoped by the helper itself declining, not by removing the
234
+ // user's helpers for every host — so an unclaimed host still has no
235
+ // Clopen-supplied credential.
236
+ const result = await run(['git', 'credential', 'fill'], {
237
+ env: { ...identityEnv(), CLOPEN_DATA_DIR: dataDir, GIT_TERMINAL_PROMPT: '0' },
238
+ stdin: 'protocol=https\nhost=gitlab.com\n\n'
239
+ });
240
+ expect(result.stdout).not.toContain('test-token-value');
241
+ }, 60_000);
242
+ });