@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.
- package/backend/chat/stream-manager.ts +8 -0
- package/backend/database/crypto/secret-columns.ts +5 -1
- package/backend/database/index.ts +18 -0
- package/backend/database/migrations/082_create_git_identities.test.ts +186 -0
- package/backend/database/migrations/082_create_git_identities.ts +122 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/git-identity-queries.ts +290 -0
- package/backend/database/queries/index.ts +2 -0
- package/backend/engine/adapters/claude/environment.ts +11 -1
- package/backend/engine/adapters/claude/stream.ts +1 -1
- package/backend/engine/adapters/codex/stream.ts +35 -3
- package/backend/engine/adapters/opencode/server.ts +26 -2
- package/backend/engine/adapters/opencode/stream.ts +4 -1
- package/backend/engine/adapters/qwen/stream.ts +3 -1
- package/backend/engine/types.ts +10 -0
- package/backend/git/git-executor.ts +28 -2
- package/backend/git/git-service.ts +59 -40
- package/backend/git/identity/cli.test.ts +58 -0
- package/backend/git/identity/cli.ts +201 -0
- package/backend/git/identity/credential-helper.test.ts +242 -0
- package/backend/git/identity/env.test.ts +214 -0
- package/backend/git/identity/env.ts +193 -0
- package/backend/git/identity/import-local.test.ts +199 -0
- package/backend/git/identity/import-local.ts +141 -0
- package/backend/git/identity/index.ts +78 -0
- package/backend/git/identity/keys.ts +183 -0
- package/backend/git/identity/resolve.ts +140 -0
- package/backend/git/identity/scope-config.test.ts +145 -0
- package/backend/git/identity/scope-config.ts +175 -0
- package/backend/git/identity/service.ts +297 -0
- package/backend/index.ts +16 -0
- package/backend/preview/browser/browser-console-manager.ts +214 -34
- package/backend/preview/browser/browser-pool.ts +526 -123
- package/backend/preview/browser/browser-preview-service.ts +192 -8
- package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
- package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
- package/backend/preview/browser/browser-tab-manager.ts +291 -65
- package/backend/preview/browser/capture-profile.ts +15 -1
- package/backend/preview/browser/types.ts +26 -1
- package/backend/terminal/ptykit.ts +24 -0
- package/backend/ws/git/branch.ts +17 -6
- package/backend/ws/git/commit.ts +6 -5
- package/backend/ws/git/conflict.ts +3 -2
- package/backend/ws/git/identity-context.ts +91 -0
- package/backend/ws/git/identity.ts +200 -0
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/git/remote.ts +57 -11
- package/backend/ws/preview/browser/data.ts +60 -0
- package/backend/ws/preview/browser/interact.ts +6 -0
- package/backend/ws/preview/browser/tab-info.ts +9 -1
- package/backend/ws/preview/browser/tab.ts +64 -8
- package/backend/ws/preview/index.ts +21 -0
- package/bin/clopen.ts +9 -0
- package/dist/assets/{index-CeNKKSDR.js → index-BynqyvF4.js} +1 -1
- package/dist/assets/{index-DW89566K.js → index-DLoJsmNQ.js} +1 -1
- package/dist/assets/{main-Cy5DXWPT.js → main-CUyZAmqt.js} +591 -584
- package/dist/assets/main-DVCW3cfr.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +2 -2
- package/shared/types/git-identity.ts +112 -0
- package/dist/assets/main-DJKj_4By.css +0 -1
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mirroring the machine's git identity, against a real `git config --global`.
|
|
3
|
+
*
|
|
4
|
+
* Runs in a subprocess with `HOME` pointed at a temporary directory, so the
|
|
5
|
+
* developer's own `~/.gitconfig` is neither read nor written and the result does
|
|
6
|
+
* not depend on how this machine happens to be configured.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { afterEach, describe, expect, test } from 'bun:test';
|
|
10
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
11
|
+
import { tmpdir } from 'node:os';
|
|
12
|
+
import { join, resolve } from 'node:path';
|
|
13
|
+
|
|
14
|
+
const REPO_ROOT = resolve(import.meta.dir, '../../..');
|
|
15
|
+
const dirs: string[] = [];
|
|
16
|
+
|
|
17
|
+
afterEach(async () => {
|
|
18
|
+
let dir: string | undefined;
|
|
19
|
+
while ((dir = dirs.pop())) await rm(dir, { recursive: true, force: true });
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
async function tempDir(prefix: string): Promise<string> {
|
|
23
|
+
const dir = await mkdtemp(join(tmpdir(), prefix));
|
|
24
|
+
dirs.push(dir);
|
|
25
|
+
return dir;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Run `script` inside the repo with an isolated HOME and data directory.
|
|
30
|
+
*
|
|
31
|
+
* The script writes its result to stdout as JSON on the last line; everything
|
|
32
|
+
* else there is Clopen's own startup logging.
|
|
33
|
+
*/
|
|
34
|
+
async function runInSandbox(
|
|
35
|
+
script: string,
|
|
36
|
+
env: { home: string; dataDir: string }
|
|
37
|
+
): Promise<any> {
|
|
38
|
+
const file = join(REPO_ROOT, `.import-local-test-${process.pid}-${dirs.length}.ts`);
|
|
39
|
+
await writeFile(file, script);
|
|
40
|
+
try {
|
|
41
|
+
const proc = Bun.spawn([process.execPath, 'run', file], {
|
|
42
|
+
cwd: REPO_ROOT,
|
|
43
|
+
env: {
|
|
44
|
+
...process.env,
|
|
45
|
+
HOME: env.home,
|
|
46
|
+
// Git also reads the XDG path; pin it inside the sandbox too.
|
|
47
|
+
XDG_CONFIG_HOME: join(env.home, '.config'),
|
|
48
|
+
CLOPEN_DATA_DIR: env.dataDir
|
|
49
|
+
} as Record<string, string>,
|
|
50
|
+
stdout: 'pipe',
|
|
51
|
+
stderr: 'pipe'
|
|
52
|
+
});
|
|
53
|
+
const [out, err] = await Promise.all([
|
|
54
|
+
new Response(proc.stdout).text(),
|
|
55
|
+
new Response(proc.stderr).text()
|
|
56
|
+
]);
|
|
57
|
+
const code = await proc.exited;
|
|
58
|
+
const line = out.trim().split('\n').pop() ?? '';
|
|
59
|
+
if (code !== 0) throw new Error(`sandbox failed (${code}): ${err}\n${out}`);
|
|
60
|
+
return JSON.parse(line);
|
|
61
|
+
} finally {
|
|
62
|
+
await rm(file, { force: true });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const PRELUDE = `
|
|
67
|
+
import { initializeDatabase, getDatabase } from '$backend/database';
|
|
68
|
+
import { gitIdentityService } from '$backend/git/identity';
|
|
69
|
+
await initializeDatabase();
|
|
70
|
+
const now = new Date().toISOString();
|
|
71
|
+
getDatabase().prepare(
|
|
72
|
+
\`INSERT INTO users (id, name, color, avatar, role, created_at, updated_at)
|
|
73
|
+
VALUES ('u1', 'User', '#fff', 'a', 'admin', ?, ?)\`
|
|
74
|
+
).run(now, now);
|
|
75
|
+
`;
|
|
76
|
+
|
|
77
|
+
describe('mirroring the machine git identity', () => {
|
|
78
|
+
test('a configured machine shows up in the list, as the default', async () => {
|
|
79
|
+
const home = await tempDir('clopen-home-');
|
|
80
|
+
const dataDir = await tempDir('clopen-data-');
|
|
81
|
+
await writeFile(
|
|
82
|
+
join(home, '.gitconfig'),
|
|
83
|
+
'[user]\n\tname = Machine User\n\temail = machine@example.com\n'
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
const result = await runInSandbox(
|
|
87
|
+
`${PRELUDE}
|
|
88
|
+
const list = await gitIdentityService.list('u1');
|
|
89
|
+
console.log(JSON.stringify(list.map((i) => ({
|
|
90
|
+
label: i.label, name: i.name, email: i.email,
|
|
91
|
+
isDefault: i.isDefault, source: i.source, canDelete: i.canDelete
|
|
92
|
+
}))));`,
|
|
93
|
+
{ home, dataDir }
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
expect(result).toEqual([
|
|
97
|
+
{
|
|
98
|
+
label: 'This machine',
|
|
99
|
+
name: 'Machine User',
|
|
100
|
+
email: 'machine@example.com',
|
|
101
|
+
isDefault: true,
|
|
102
|
+
source: 'local-machine',
|
|
103
|
+
canDelete: false
|
|
104
|
+
}
|
|
105
|
+
]);
|
|
106
|
+
}, 120_000);
|
|
107
|
+
|
|
108
|
+
test('reading the list twice does not create a second copy', async () => {
|
|
109
|
+
// The import runs on every read, so it has to be idempotent — otherwise
|
|
110
|
+
// the list grows by one every time Settings is opened.
|
|
111
|
+
const home = await tempDir('clopen-home-');
|
|
112
|
+
const dataDir = await tempDir('clopen-data-');
|
|
113
|
+
await writeFile(
|
|
114
|
+
join(home, '.gitconfig'),
|
|
115
|
+
'[user]\n\tname = Machine User\n\temail = machine@example.com\n'
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
const result = await runInSandbox(
|
|
119
|
+
`${PRELUDE}
|
|
120
|
+
await gitIdentityService.list('u1');
|
|
121
|
+
await gitIdentityService.list('u1');
|
|
122
|
+
const list = await gitIdentityService.list('u1');
|
|
123
|
+
console.log(JSON.stringify({ count: list.length }));`,
|
|
124
|
+
{ home, dataDir }
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
expect(result).toEqual({ count: 1 });
|
|
128
|
+
}, 120_000);
|
|
129
|
+
|
|
130
|
+
test('the mirrored account refuses to be deleted', async () => {
|
|
131
|
+
const home = await tempDir('clopen-home-');
|
|
132
|
+
const dataDir = await tempDir('clopen-data-');
|
|
133
|
+
await writeFile(
|
|
134
|
+
join(home, '.gitconfig'),
|
|
135
|
+
'[user]\n\tname = Machine User\n\temail = machine@example.com\n'
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
const result = await runInSandbox(
|
|
139
|
+
`${PRELUDE}
|
|
140
|
+
const [mirrored] = await gitIdentityService.list('u1');
|
|
141
|
+
let error = null;
|
|
142
|
+
try { await gitIdentityService.remove('u1', mirrored.id); }
|
|
143
|
+
catch (e) { error = e instanceof Error ? e.message : String(e); }
|
|
144
|
+
const after = await gitIdentityService.list('u1');
|
|
145
|
+
console.log(JSON.stringify({ error, stillThere: after.length }));`,
|
|
146
|
+
{ home, dataDir }
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
expect(result.error).toContain('cannot be deleted');
|
|
150
|
+
expect(result.stillThere).toBe(1);
|
|
151
|
+
}, 120_000);
|
|
152
|
+
|
|
153
|
+
test('editing it keeps it mirrored, and still undeletable', async () => {
|
|
154
|
+
// An edit is a preference, not a conversion to a manual account — the
|
|
155
|
+
// machine config it reflects has not gone anywhere.
|
|
156
|
+
const home = await tempDir('clopen-home-');
|
|
157
|
+
const dataDir = await tempDir('clopen-data-');
|
|
158
|
+
await writeFile(
|
|
159
|
+
join(home, '.gitconfig'),
|
|
160
|
+
'[user]\n\tname = Machine User\n\temail = machine@example.com\n'
|
|
161
|
+
);
|
|
162
|
+
|
|
163
|
+
const result = await runInSandbox(
|
|
164
|
+
`${PRELUDE}
|
|
165
|
+
const [mirrored] = await gitIdentityService.list('u1');
|
|
166
|
+
const updated = await gitIdentityService.update('u1', mirrored.id, {
|
|
167
|
+
label: 'Renamed', name: 'Edited Name', email: 'edited@example.com',
|
|
168
|
+
authMethod: 'none', hosts: []
|
|
169
|
+
});
|
|
170
|
+
console.log(JSON.stringify({
|
|
171
|
+
name: updated.name, source: updated.source, canDelete: updated.canDelete
|
|
172
|
+
}));`,
|
|
173
|
+
{ home, dataDir }
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
expect(result).toEqual({
|
|
177
|
+
name: 'Edited Name',
|
|
178
|
+
source: 'local-machine',
|
|
179
|
+
canDelete: false
|
|
180
|
+
});
|
|
181
|
+
}, 120_000);
|
|
182
|
+
|
|
183
|
+
test('a machine with no global identity contributes nothing', async () => {
|
|
184
|
+
// Half-configured counts as nothing: git itself refuses to commit with
|
|
185
|
+
// only a name, so mirroring one would create an unusable account.
|
|
186
|
+
const home = await tempDir('clopen-home-');
|
|
187
|
+
const dataDir = await tempDir('clopen-data-');
|
|
188
|
+
await writeFile(join(home, '.gitconfig'), '[user]\n\tname = Only A Name\n');
|
|
189
|
+
|
|
190
|
+
const result = await runInSandbox(
|
|
191
|
+
`${PRELUDE}
|
|
192
|
+
const list = await gitIdentityService.list('u1');
|
|
193
|
+
console.log(JSON.stringify({ count: list.length }));`,
|
|
194
|
+
{ home, dataDir }
|
|
195
|
+
);
|
|
196
|
+
|
|
197
|
+
expect(result).toEqual({ count: 0 });
|
|
198
|
+
}, 120_000);
|
|
199
|
+
});
|