@myrialabs/clopen 0.4.41 → 0.4.43

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 (72) 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/db-client/env/detect.ts +2 -1
  10. package/backend/engine/adapters/claude/environment.ts +11 -1
  11. package/backend/engine/adapters/claude/models.ts +147 -18
  12. package/backend/engine/adapters/claude/stream.ts +1 -1
  13. package/backend/engine/adapters/codex/models.ts +13 -9
  14. package/backend/engine/adapters/codex/stream.ts +35 -3
  15. package/backend/engine/adapters/opencode/server.ts +26 -2
  16. package/backend/engine/adapters/opencode/stream.ts +4 -1
  17. package/backend/engine/adapters/qwen/stream.ts +3 -1
  18. package/backend/engine/types.ts +10 -0
  19. package/backend/env-files/discovery.ts +2 -1
  20. package/backend/files/file-reading.ts +4 -3
  21. package/backend/files/path-browsing.ts +2 -1
  22. package/backend/git/git-executor.ts +28 -2
  23. package/backend/git/git-service.ts +61 -41
  24. package/backend/git/identity/cli.test.ts +58 -0
  25. package/backend/git/identity/cli.ts +201 -0
  26. package/backend/git/identity/credential-helper.test.ts +242 -0
  27. package/backend/git/identity/env.test.ts +214 -0
  28. package/backend/git/identity/env.ts +193 -0
  29. package/backend/git/identity/import-local.test.ts +199 -0
  30. package/backend/git/identity/import-local.ts +141 -0
  31. package/backend/git/identity/index.ts +78 -0
  32. package/backend/git/identity/keys.ts +183 -0
  33. package/backend/git/identity/resolve.ts +140 -0
  34. package/backend/git/identity/scope-config.test.ts +145 -0
  35. package/backend/git/identity/scope-config.ts +175 -0
  36. package/backend/git/identity/service.ts +297 -0
  37. package/backend/index.ts +16 -0
  38. package/backend/preview/browser/browser-console-manager.ts +214 -34
  39. package/backend/preview/browser/browser-pool.ts +526 -123
  40. package/backend/preview/browser/browser-preview-service.ts +192 -8
  41. package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
  42. package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
  43. package/backend/preview/browser/browser-tab-manager.ts +291 -65
  44. package/backend/preview/browser/capture-profile.ts +15 -1
  45. package/backend/preview/browser/types.ts +26 -1
  46. package/backend/snapshot/turn-changes.ts +3 -2
  47. package/backend/ssh/sftp.ts +2 -1
  48. package/backend/terminal/ptykit.ts +24 -0
  49. package/backend/worktrees/merge.ts +2 -1
  50. package/backend/ws/git/branch.ts +17 -6
  51. package/backend/ws/git/commit.ts +6 -5
  52. package/backend/ws/git/conflict.ts +3 -2
  53. package/backend/ws/git/identity-context.ts +91 -0
  54. package/backend/ws/git/identity.ts +200 -0
  55. package/backend/ws/git/index.ts +3 -1
  56. package/backend/ws/git/remote.ts +57 -11
  57. package/backend/ws/preview/browser/data.ts +60 -0
  58. package/backend/ws/preview/browser/interact.ts +6 -0
  59. package/backend/ws/preview/browser/tab-info.ts +9 -1
  60. package/backend/ws/preview/browser/tab.ts +64 -8
  61. package/backend/ws/preview/index.ts +21 -0
  62. package/bin/clopen.ts +9 -0
  63. package/dist/assets/{index-CeNKKSDR.js → index-B6u8cait.js} +1 -1
  64. package/dist/assets/{index-DW89566K.js → index-BeUKiRiY.js} +1 -1
  65. package/dist/assets/{main-Cy5DXWPT.js → main-CMRXlv2f.js} +604 -596
  66. package/dist/assets/main-DzCY0n-j.css +1 -0
  67. package/dist/index.html +2 -2
  68. package/package.json +2 -2
  69. package/shared/types/git-identity.ts +112 -0
  70. package/shared/utils/compare.test.ts +46 -0
  71. package/shared/utils/compare.ts +21 -0
  72. package/dist/assets/main-DJKj_4By.css +0 -1
@@ -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
+ });
@@ -0,0 +1,214 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { mkdtemp, rm } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { buildGitConfigPairs, buildGitIdentityEnv, remoteHost } from './env';
6
+
7
+ const helper = { runtime: '/usr/local/bin/bun', script: '/opt/clopen/index.js' };
8
+
9
+ function pairsOf(env: Record<string, string>): Array<[string, string]> {
10
+ const count = Number(env.GIT_CONFIG_COUNT ?? 0);
11
+ return Array.from({ length: count }, (_, i) => [
12
+ env[`GIT_CONFIG_KEY_${i}`]!,
13
+ env[`GIT_CONFIG_VALUE_${i}`]!
14
+ ]);
15
+ }
16
+
17
+ describe('buildGitIdentityEnv', () => {
18
+ test('no identity yields no variables, so callers can merge unconditionally', () => {
19
+ expect(buildGitIdentityEnv(null)).toEqual({});
20
+ });
21
+
22
+ test('emits a well-formed GIT_CONFIG_* block', () => {
23
+ const env = buildGitIdentityEnv({ id: 'i1', name: 'Ada', email: 'ada@example.com' });
24
+ expect(env.GIT_CONFIG_COUNT).toBe('2');
25
+ expect(pairsOf(env)).toEqual([
26
+ ['user.name', 'Ada'],
27
+ ['user.email', 'ada@example.com']
28
+ ]);
29
+ });
30
+
31
+ test('the index is contiguous from zero — git stops reading at the first gap', () => {
32
+ const env = buildGitIdentityEnv(
33
+ {
34
+ id: 'i1',
35
+ name: 'Ada',
36
+ email: 'ada@example.com',
37
+ sshKeyPath: '/keys/id_ed25519',
38
+ credentialHosts: ['github.com'],
39
+ httpsUsername: 'ada'
40
+ },
41
+ helper
42
+ );
43
+ const count = Number(env.GIT_CONFIG_COUNT);
44
+ for (let i = 0; i < count; i++) {
45
+ expect(env[`GIT_CONFIG_KEY_${i}`]).toBeString();
46
+ expect(env[`GIT_CONFIG_VALUE_${i}`]).toBeString();
47
+ }
48
+ expect(env[`GIT_CONFIG_KEY_${count}`]).toBeUndefined();
49
+ });
50
+
51
+ test('ssh keys are pinned with IdentitiesOnly', () => {
52
+ // Without this the agent still offers every other key and the push can
53
+ // silently authenticate as the wrong account.
54
+ const pairs = buildGitConfigPairs({
55
+ id: 'i1',
56
+ name: 'Ada',
57
+ email: 'ada@example.com',
58
+ sshKeyPath: '/keys/id_ed25519'
59
+ });
60
+ const ssh = pairs.find(([k]) => k === 'core.sshCommand')?.[1];
61
+ expect(ssh).toContain('-o IdentitiesOnly=yes');
62
+ expect(ssh).toContain(`-i '/keys/id_ed25519'`);
63
+ });
64
+
65
+ test('a key path with shell metacharacters cannot break out', () => {
66
+ const pairs = buildGitConfigPairs({
67
+ id: 'i1',
68
+ name: 'Ada',
69
+ email: 'ada@example.com',
70
+ sshKeyPath: "/keys/'; rm -rf /; echo '"
71
+ });
72
+ const ssh = pairs.find(([k]) => k === 'core.sshCommand')?.[1] ?? '';
73
+ // Every embedded quote is escaped, so the payload stays one argument.
74
+ expect(ssh).toContain(`'\\''`);
75
+ expect(ssh.startsWith('ssh -i ')).toBe(true);
76
+ });
77
+
78
+ test('the credential helper is only wired when a host is claimed', () => {
79
+ const withoutHosts = buildGitConfigPairs(
80
+ { id: 'i1', name: 'Ada', email: 'ada@example.com', credentialHosts: [] },
81
+ helper
82
+ );
83
+ expect(withoutHosts.some(([k]) => k === 'credential.helper')).toBe(false);
84
+
85
+ const withHosts = buildGitConfigPairs(
86
+ { id: 'i1', name: 'Ada', email: 'ada@example.com', credentialHosts: ['github.com'] },
87
+ helper
88
+ );
89
+ const cred = withHosts.filter(([k]) => k === 'credential.helper').map(([, v]) => v);
90
+
91
+ // Two entries, in this order, and the order is the whole point: the empty
92
+ // value clears the helpers the machine already configured, so ours is the
93
+ // only one git asks. Reversed or missing, a system keychain answers first
94
+ // and the push authenticates as the wrong account.
95
+ expect(cred.length).toBe(2);
96
+ expect(cred[0]).toBe('');
97
+ expect(cred[1]!.startsWith('!')).toBe(true);
98
+ expect(cred[1]).toContain('git-credential');
99
+ expect(cred[1]).toContain('--identity=i1');
100
+ });
101
+
102
+ test('no secret is ever placed in the environment', () => {
103
+ const env = buildGitIdentityEnv(
104
+ {
105
+ id: 'i1',
106
+ name: 'Ada',
107
+ email: 'ada@example.com',
108
+ sshKeyPath: '/keys/id_ed25519',
109
+ needsPassphrase: true,
110
+ httpsUsername: 'ada',
111
+ credentialHosts: ['github.com']
112
+ },
113
+ helper
114
+ );
115
+ // argv and the environment are readable; the helpers exist so secrets
116
+ // travel over stdout instead.
117
+ const blob = JSON.stringify(env);
118
+ expect(blob).not.toContain('PRIVATE KEY');
119
+ expect(blob).not.toContain('passphrase');
120
+ expect(blob).not.toContain('token');
121
+ });
122
+
123
+ test('a passphrased key forces askpass so a PTY shell cannot hang on the prompt', () => {
124
+ const env = buildGitIdentityEnv(
125
+ {
126
+ id: 'i1',
127
+ name: 'Ada',
128
+ email: 'ada@example.com',
129
+ sshKeyPath: '/keys/id_ed25519',
130
+ needsPassphrase: true
131
+ },
132
+ helper
133
+ );
134
+ expect(env.SSH_ASKPASS).toContain('git-askpass');
135
+ expect(env.SSH_ASKPASS_REQUIRE).toBe('force');
136
+ expect(env.DISPLAY).toBeTruthy();
137
+ });
138
+
139
+ test('a key without a passphrase does not drag askpass in', () => {
140
+ const env = buildGitIdentityEnv(
141
+ { id: 'i1', name: 'Ada', email: 'ada@example.com', sshKeyPath: '/keys/id_ed25519' },
142
+ helper
143
+ );
144
+ expect(env.SSH_ASKPASS).toBeUndefined();
145
+ });
146
+ });
147
+
148
+ describe('remoteHost', () => {
149
+ test('reads scp-like remotes, where the colon is a path and not a port', () => {
150
+ expect(remoteHost('git@github.com:owner/repo.git')).toBe('github.com');
151
+ expect(remoteHost('github.com:owner/repo.git')).toBe('github.com');
152
+ });
153
+
154
+ test('reads URL remotes', () => {
155
+ expect(remoteHost('https://github.com/owner/repo.git')).toBe('github.com');
156
+ expect(remoteHost('ssh://git@git.example.com:2222/owner/repo.git')).toBe('git.example.com');
157
+ expect(remoteHost('https://GitHub.com/owner/repo')).toBe('github.com');
158
+ });
159
+
160
+ test('local paths have no host', () => {
161
+ expect(remoteHost('/srv/repos/thing.git')).toBeNull();
162
+ expect(remoteHost('file:///srv/repos/thing.git')).toBeNull();
163
+ expect(remoteHost('')).toBeNull();
164
+ });
165
+ });
166
+
167
+ describe('the env block against real git', () => {
168
+ test('a commit made with it carries the identity, and the repo stays clean', async () => {
169
+ const dir = await mkdtemp(join(tmpdir(), 'clopen-git-identity-'));
170
+ try {
171
+ const git = async (args: string[], env: Record<string, string> = {}) => {
172
+ const proc = Bun.spawn(['git', ...args], {
173
+ cwd: dir,
174
+ env: { ...process.env, ...env } as Record<string, string>,
175
+ stdout: 'pipe',
176
+ stderr: 'pipe'
177
+ });
178
+ const [out, err] = await Promise.all([
179
+ new Response(proc.stdout).text(),
180
+ new Response(proc.stderr).text()
181
+ ]);
182
+ const code = await proc.exited;
183
+ if (code !== 0) throw new Error(`git ${args.join(' ')} failed: ${err}`);
184
+ return out.trim();
185
+ };
186
+
187
+ await git(['init', '-q', '.']);
188
+ await Bun.write(join(dir, 'a.txt'), 'hello');
189
+ await git(['add', 'a.txt']);
190
+
191
+ const env = buildGitIdentityEnv({
192
+ id: 'i1',
193
+ name: 'Grace Hopper',
194
+ email: 'grace@example.com'
195
+ });
196
+ await git(['commit', '-m', 'test'], env);
197
+
198
+ // Both halves: git records the identity as author AND committer.
199
+ expect(await git(['log', '-1', '--format=%an <%ae>'])).toBe(
200
+ 'Grace Hopper <grace@example.com>'
201
+ );
202
+ expect(await git(['log', '-1', '--format=%cn <%ce>'])).toBe(
203
+ 'Grace Hopper <grace@example.com>'
204
+ );
205
+
206
+ // The whole point of the env route: the user's repository is untouched,
207
+ // so their own CLI outside Clopen sees no Clopen-written identity.
208
+ const config = await Bun.file(join(dir, '.git', 'config')).text();
209
+ expect(config).not.toContain('grace@example.com');
210
+ } finally {
211
+ await rm(dir, { recursive: true, force: true });
212
+ }
213
+ });
214
+ });
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Turning an identity into environment variables git obeys.
3
+ *
4
+ * Git reads `GIT_CONFIG_COUNT` plus `GIT_CONFIG_KEY_<n>` / `GIT_CONFIG_VALUE_<n>`
5
+ * as if each pair had been passed as `-c key=value` (git 2.31+). That is the
6
+ * whole mechanism, and it was chosen over the two alternatives for reasons that
7
+ * are worth keeping written down:
8
+ *
9
+ * - Writing `user.name` into the repository's `.git/config` would cover every
10
+ * git invocation, including ones Clopen never sees — but it MODIFIES THE
11
+ * USER'S REPOSITORY, is visible to their own CLI outside Clopen, and two
12
+ * Clopen users sharing a checkout would overwrite each other.
13
+ * - Passing `-c` on the command line only reaches commands Clopen spawns
14
+ * itself, so an agent running `git commit` through its shell tool would
15
+ * still use the machine's identity.
16
+ *
17
+ * Environment variables are inherited, so one builder covers all three
18
+ * surfaces: Clopen's own git calls, the engine process, and the terminal PTY.
19
+ * The repository is never touched.
20
+ *
21
+ * ── What is deliberately NOT here ──
22
+ * No secret is ever placed in a variable or an argument. The HTTPS token is
23
+ * fetched by a credential helper over its own stdin/stdout protocol, and the
24
+ * SSH passphrase by an askpass helper, precisely because argv is world-readable
25
+ * through `ps` and the environment of a process is readable by its owner.
26
+ */
27
+
28
+ import { debug } from '$shared/utils/logger';
29
+
30
+ /** An identity reduced to what the env builder needs. */
31
+ export interface GitEnvIdentity {
32
+ id: string;
33
+ name: string;
34
+ email: string;
35
+ /** Absolute path to the materialised private key, when one is stored. */
36
+ sshKeyPath?: string | null;
37
+ /** True when that key needs a passphrase — turns on the askpass helper. */
38
+ needsPassphrase?: boolean;
39
+ /** Host → username for the credential protocol, when HTTPS auth is used. */
40
+ httpsUsername?: string | null;
41
+ /** Hosts the credential helper should answer for. */
42
+ credentialHosts?: string[];
43
+ }
44
+
45
+ /** How to re-invoke Clopen for the credential/askpass helpers. */
46
+ export interface HelperCommand {
47
+ /** The runtime executable (`process.execPath`). */
48
+ runtime: string;
49
+ /** The entry script (`Bun.main`). */
50
+ script: string;
51
+ }
52
+
53
+ /**
54
+ * Quote one argument for the shell git runs a `!`-prefixed helper through.
55
+ *
56
+ * Single quotes with the standard `'\''` escape: inside single quotes a POSIX
57
+ * shell expands nothing, so a data directory containing a space, a `$`, or a
58
+ * backtick cannot turn into a command. This runs on every git invocation, so
59
+ * getting it wrong would be a command injection through a file path.
60
+ */
61
+ function shellQuote(value: string): string {
62
+ return `'${value.replace(/'/g, `'\\''`)}'`;
63
+ }
64
+
65
+ /** Config pairs for an identity, as `[key, value]` tuples. */
66
+ export function buildGitConfigPairs(
67
+ identity: GitEnvIdentity,
68
+ helper?: HelperCommand
69
+ ): Array<[string, string]> {
70
+ const pairs: Array<[string, string]> = [
71
+ ['user.name', identity.name],
72
+ ['user.email', identity.email]
73
+ ];
74
+
75
+ if (identity.sshKeyPath) {
76
+ // `IdentitiesOnly=yes` is not optional. Without it ssh still offers every
77
+ // key the agent holds, in the agent's order, and a server that accepts one
78
+ // of those authenticates as the WRONG ACCOUNT — with no error to notice,
79
+ // because the push succeeds.
80
+ const sshArgs = [
81
+ 'ssh',
82
+ '-i',
83
+ shellQuote(identity.sshKeyPath),
84
+ '-o',
85
+ 'IdentitiesOnly=yes'
86
+ ];
87
+ pairs.push(['core.sshCommand', sshArgs.join(' ')]);
88
+ }
89
+
90
+ if (helper && identity.credentialHosts?.length) {
91
+ // `credential.helper` is a MULTI-VALUE key: git collects every configured
92
+ // helper and asks them in order, first answer wins. The user's global
93
+ // config almost always names one already (osxkeychain, libsecret,
94
+ // manager), and it is consulted BEFORE a command-line value — so without
95
+ // this reset, choosing the "Work" account and pushing would authenticate
96
+ // with whatever token the system keychain volunteered. That is the exact
97
+ // failure this feature exists to prevent, and it fails silently: the push
98
+ // succeeds, under the wrong account.
99
+ //
100
+ // An empty value clears the accumulated list, so the next entry is the
101
+ // only helper git will ask. Only done when this identity actually carries
102
+ // an HTTPS credential — an attribution-only identity leaves the machine's
103
+ // helpers exactly as they were.
104
+ pairs.push(['credential.helper', '']);
105
+
106
+ // The helper is asked for a credential, it is never handed one. Git runs
107
+ // this through a shell (the `!` prefix), passes the request on stdin, and
108
+ // reads the answer from stdout.
109
+ const command = [
110
+ shellQuote(helper.runtime),
111
+ shellQuote(helper.script),
112
+ 'git-credential',
113
+ shellQuote(`--identity=${identity.id}`)
114
+ ].join(' ');
115
+ pairs.push(['credential.helper', `!${command}`]);
116
+
117
+ for (const host of identity.credentialHosts) {
118
+ // Scoping by host means a repo whose `origin` and `upstream` live on
119
+ // different accounts asks the right helper for each.
120
+ if (identity.httpsUsername) {
121
+ pairs.push([`credential.https://${host}.username`, identity.httpsUsername]);
122
+ }
123
+ }
124
+ }
125
+
126
+ return pairs;
127
+ }
128
+
129
+ /**
130
+ * The environment fragment for an identity.
131
+ *
132
+ * Returns `{}` for no identity so every caller can merge unconditionally and a
133
+ * project without one behaves exactly as Clopen did before this feature.
134
+ */
135
+ export function buildGitIdentityEnv(
136
+ identity: GitEnvIdentity | null,
137
+ helper?: HelperCommand
138
+ ): Record<string, string> {
139
+ if (!identity) return {};
140
+
141
+ const pairs = buildGitConfigPairs(identity, helper);
142
+ const env: Record<string, string> = { GIT_CONFIG_COUNT: String(pairs.length) };
143
+
144
+ pairs.forEach(([key, value], index) => {
145
+ env[`GIT_CONFIG_KEY_${index}`] = key;
146
+ env[`GIT_CONFIG_VALUE_${index}`] = value;
147
+ });
148
+
149
+ if (identity.sshKeyPath && identity.needsPassphrase && helper) {
150
+ // `ssh` only consults SSH_ASKPASS when it has no terminal to prompt on.
151
+ // A PTY-backed shell HAS one, so without REQUIRE=force a passphrased key
152
+ // would hang the terminal waiting for input git can never deliver.
153
+ const askpass = [
154
+ shellQuote(helper.runtime),
155
+ shellQuote(helper.script),
156
+ 'git-askpass',
157
+ shellQuote(`--identity=${identity.id}`)
158
+ ].join(' ');
159
+ env.SSH_ASKPASS = askpass;
160
+ env.SSH_ASKPASS_REQUIRE = 'force';
161
+ // Older OpenSSH consults DISPLAY before SSH_ASKPASS. The value is never
162
+ // connected to, it only has to be non-empty.
163
+ env.DISPLAY = env.DISPLAY || ':0';
164
+ }
165
+
166
+ debug.log('git', `Git identity env built for ${identity.email} (${pairs.length} config pairs)`);
167
+ return env;
168
+ }
169
+
170
+ /**
171
+ * The hostname a git remote URL points at, lowercased.
172
+ *
173
+ * Handles the three shapes git accepts: scp-like (`git@github.com:owner/repo`),
174
+ * a real URL (`https://github.com/owner/repo`, `ssh://git@host:22/repo`), and a
175
+ * local path — which has no host and yields null.
176
+ */
177
+ export function remoteHost(url: string): string | null {
178
+ const trimmed = url.trim();
179
+ if (!trimmed) return null;
180
+
181
+ // scp-like syntax is not a URL and `new URL()` would misread it: the part
182
+ // after the colon is a path, not a port.
183
+ const scpLike = /^(?:[^@/]+@)?([^/:]+):(?!\/\/)/.exec(trimmed);
184
+ if (scpLike) return scpLike[1]!.toLowerCase();
185
+
186
+ try {
187
+ const parsed = new URL(trimmed);
188
+ if (parsed.protocol === 'file:') return null;
189
+ return parsed.hostname.toLowerCase() || null;
190
+ } catch {
191
+ return null;
192
+ }
193
+ }