@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,141 @@
1
+ /**
2
+ * Mirroring the machine's own git identity into the list.
3
+ *
4
+ * Someone who already has `git config --global user.email` set has an account —
5
+ * they just have not told Clopen about it. Showing them an empty Git Accounts
6
+ * page and asking them to retype what git already knows is the kind of setup
7
+ * step that makes a feature feel like paperwork, so the machine's identity is
8
+ * imported on first read and becomes the default when nothing else is.
9
+ *
10
+ * ── Mirrored once, then owned by the user ──
11
+ * The import writes only when the row does not exist. It never overwrites it
12
+ * afterwards, deliberately: telling an edit apart from machine drift would need
13
+ * a record of what was last mirrored, and guessing wrong means silently
14
+ * replacing a value the user chose. Importing once and leaving it alone is the
15
+ * behaviour that is easy to explain and impossible to get wrong — a machine
16
+ * config change is picked up by editing the row.
17
+ *
18
+ * ── Not deletable ──
19
+ * Deleting it would accomplish nothing — the machine's config is still there and
20
+ * the next read would recreate it. So the row is marked `local-machine` and the
21
+ * delete path refuses it. Editing is how a user changes it.
22
+ */
23
+
24
+ import { gitIdentityQueries, type GitIdentityRow } from '$backend/database/queries';
25
+ import { getCleanSpawnEnv } from '$backend/utils/env';
26
+ import { resolveBinary } from '$backend/utils/cli';
27
+ import { debug } from '$shared/utils/logger';
28
+ import { randomUUID } from 'node:crypto';
29
+
30
+ /** What the machine's global git config says about who the user is. */
31
+ export interface MachineIdentity {
32
+ name: string;
33
+ email: string;
34
+ }
35
+
36
+ /**
37
+ * Read one value from the machine's GLOBAL git config.
38
+ *
39
+ * `--global` explicitly, not the default lookup: a repository-local value
40
+ * describes one project, while this is meant to be the person's own account. No
41
+ * cwd is given for the same reason.
42
+ */
43
+ async function readGlobalConfig(key: string): Promise<string | null> {
44
+ const gitPath = resolveBinary('git');
45
+ if (!gitPath) return null;
46
+
47
+ try {
48
+ const proc = Bun.spawn([gitPath, 'config', '--global', '--get', key], {
49
+ env: getCleanSpawnEnv(),
50
+ stdin: 'ignore',
51
+ stdout: 'pipe',
52
+ stderr: 'pipe'
53
+ });
54
+ const out = await new Response(proc.stdout).text();
55
+ const code = await proc.exited;
56
+ // Exit 1 simply means "not set", which is not a failure.
57
+ if (code !== 0) return null;
58
+ return out.trim() || null;
59
+ } catch (error) {
60
+ debug.warn('git', `Could not read global git config ${key}:`, error);
61
+ return null;
62
+ }
63
+ }
64
+
65
+ /** The machine's identity, or null when git has no global name/email. */
66
+ export async function readMachineIdentity(): Promise<MachineIdentity | null> {
67
+ const [name, email] = await Promise.all([
68
+ readGlobalConfig('user.name'),
69
+ readGlobalConfig('user.email')
70
+ ]);
71
+ // Both halves are needed. Git itself refuses to commit with only one, so a
72
+ // half-configured machine has nothing worth mirroring.
73
+ if (!name || !email) return null;
74
+ return { name, email };
75
+ }
76
+
77
+ /**
78
+ * A label that says where the row came from without pretending to be a choice.
79
+ *
80
+ * Unique per user is enforced by the schema, so a collision with a manual
81
+ * identity called "This machine" has to be resolved rather than thrown.
82
+ */
83
+ function machineLabel(userId: string, taken: (label: string) => boolean): string {
84
+ const base = 'This machine';
85
+ if (!taken(base)) return base;
86
+ for (let i = 2; i < 50; i++) {
87
+ const candidate = `${base} (${i})`;
88
+ if (!taken(candidate)) return candidate;
89
+ }
90
+ // Practically unreachable; a unique suffix beats failing the whole list read.
91
+ return `${base} ${userId.slice(0, 6)}`;
92
+ }
93
+
94
+ /**
95
+ * Ensure the user's list reflects the machine's git config.
96
+ *
97
+ * Returns the mirrored row, or null when the machine has nothing to mirror.
98
+ * Never throws: this runs on the read path for Settings, and a failure to mirror
99
+ * must not take the whole list with it.
100
+ */
101
+ export async function syncLocalMachineIdentity(userId: string): Promise<GitIdentityRow | null> {
102
+ try {
103
+ const machine = await readMachineIdentity();
104
+ const existing = gitIdentityQueries.getLocalMachine(userId);
105
+
106
+ if (!machine) {
107
+ // Nothing to mirror. An existing row is left alone rather than deleted —
108
+ // the user may have edited it into a real account, and a machine that
109
+ // temporarily has no global config should not erase it.
110
+ return existing;
111
+ }
112
+
113
+ if (!existing) {
114
+ const label = machineLabel(userId, (l) => gitIdentityQueries.labelTaken(userId, l));
115
+ const row = gitIdentityQueries.create(randomUUID(), userId, {
116
+ label,
117
+ name: machine.name,
118
+ email: machine.email,
119
+ // Attribution only. Whatever already authenticates this machine's
120
+ // pushes keeps doing so, because no credential is claimed here.
121
+ authMethod: 'none',
122
+ hosts: [],
123
+ source: 'local-machine'
124
+ });
125
+ // Becoming the default is the point: a fresh install then commits as the
126
+ // person the machine already says it is, with nothing to configure.
127
+ if (!gitIdentityQueries.getDefaultForUser(userId)) {
128
+ gitIdentityQueries.setDefault(userId, row.id);
129
+ }
130
+ debug.log('git', `Imported the machine's git identity for user ${userId}`);
131
+ return gitIdentityQueries.getById(row.id);
132
+ }
133
+
134
+ // Already mirrored. Left exactly as it is, whether or not the machine has
135
+ // changed since — see the header.
136
+ return existing;
137
+ } catch (error) {
138
+ debug.warn('git', 'Could not mirror the machine git identity:', error);
139
+ return null;
140
+ }
141
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Git identities — public facade.
3
+ *
4
+ * Three seams the rest of Clopen uses:
5
+ * - `gitIdentityService` — CRUD for the Settings surface.
6
+ * - `resolveGitEnv` — the one call every git-running surface makes to get the
7
+ * environment fragment for a (project, user). Panel, engine, and terminal all
8
+ * go through it so they cannot drift apart.
9
+ * - `buildGitIdentityEnv` / `remoteHost` — the primitives, for tests and the
10
+ * credential helper.
11
+ */
12
+
13
+ import { gitIdentityQueries } from '$backend/database/queries';
14
+ import { buildGitIdentityEnv, remoteHost } from './env';
15
+ import { helperCommand, pickCredentialIdentity, resolveIdentity, toEnvIdentity } from './resolve';
16
+ import { toDTO } from './service';
17
+ import type { ResolvedGitIdentity } from '$shared/types/git-identity';
18
+
19
+ export { gitIdentityService, toDTO } from './service';
20
+ export { buildGitIdentityEnv, buildGitConfigPairs, remoteHost } from './env';
21
+ export type { GitEnvIdentity, HelperCommand } from './env';
22
+ export { resolveIdentity, pickCredentialIdentity, toEnvIdentity, helperCommand } from './resolve';
23
+ export { identityKeyPath, removeKeyFiles, writeKeyFile } from './keys';
24
+ export { writeScopeConfig, removeScopeConfig, refreshScopeConfigsForUser, scopeConfigPath } from './scope-config';
25
+ export { readMachineIdentity, syncLocalMachineIdentity } from './import-local';
26
+
27
+ /**
28
+ * The environment fragment for a (project, user), optionally scoped to a remote.
29
+ *
30
+ * `remoteUrl` is what lets a fork workflow work: the host it points at decides
31
+ * which identity's credential answers, while attribution always comes from the
32
+ * project's own identity. Callers that are not talking to a remote (a commit, a
33
+ * rebase) leave it out and get attribution only.
34
+ *
35
+ * Returns `{}` when the user has no identity, so every call site can merge the
36
+ * result unconditionally.
37
+ */
38
+ export function resolveGitEnv(
39
+ projectId: string,
40
+ userId: string,
41
+ remoteUrl?: string | null
42
+ ): Record<string, string> {
43
+ const { row } = resolveIdentity(projectId, userId);
44
+ if (!row) return {};
45
+
46
+ const host = remoteUrl ? remoteHost(remoteUrl) : null;
47
+ const credential = pickCredentialIdentity(userId, host, row);
48
+ return buildGitIdentityEnv(toEnvIdentity(row, credential), helperCommand());
49
+ }
50
+
51
+ /**
52
+ * What the UI shows above the commit box: who this will be committed as, and
53
+ * whether that was chosen for this project or inherited.
54
+ */
55
+ export function describeIdentity(
56
+ projectId: string,
57
+ userId: string,
58
+ remoteUrl?: string | null
59
+ ): ResolvedGitIdentity {
60
+ const { row, source } = resolveIdentity(projectId, userId);
61
+ if (!row) return { identity: null, source: 'none', credentialIdentity: null };
62
+
63
+ const host = remoteUrl ? remoteHost(remoteUrl) : null;
64
+ const credential = pickCredentialIdentity(userId, host, row);
65
+
66
+ return {
67
+ identity: toDTO(row),
68
+ source,
69
+ // Only reported when it differs, so the UI can stay quiet in the common
70
+ // case and speak up exactly when a second account is in play.
71
+ credentialIdentity: credential && credential.id !== row.id ? toDTO(credential) : null
72
+ };
73
+ }
74
+
75
+ /** Every identity a user owns, as rows — for the credential helper. */
76
+ export function identitiesOf(userId: string) {
77
+ return gitIdentityQueries.listByUser(userId);
78
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * SSH keys on disk, because `ssh` cannot read one from memory.
3
+ *
4
+ * The key is stored sealed in `git_identities`, which is where it belongs: it
5
+ * survives a reinstall, it is included in a backup of the database, and a VPS
6
+ * or container gets it without anyone copying files around. But `ssh -i` takes
7
+ * a PATH, and OpenSSH has no way to accept a key over a pipe — so the stored
8
+ * key has to exist as a file whenever git runs.
9
+ *
10
+ * ── Written on save, not per command ──
11
+ * Materialising inside every git invocation would mean several processes
12
+ * writing and deleting the same path concurrently — a push and a fetch racing
13
+ * would hand one of them a half-written key, and the failure would look like a
14
+ * corrupt key rather than a race. Instead the file is written once when the
15
+ * identity is saved, lives for as long as the identity does, and is removed
16
+ * when it is deleted.
17
+ *
18
+ * ── Permissions ──
19
+ * OpenSSH refuses a private key whose mode is loose, and on Windows it checks
20
+ * an ACL that `chmod` does not touch. `writeKeyFile` sets 0600 and reports what
21
+ * it could not guarantee, so the caller can tell the user why ssh will refuse
22
+ * rather than letting them discover it at push time.
23
+ */
24
+
25
+ import { chmod, mkdir, rm, writeFile } from 'node:fs/promises';
26
+ import { join } from 'node:path';
27
+ import { getClopenDir } from '$backend/utils/paths';
28
+ import { getCleanSpawnEnv } from '$backend/utils/env';
29
+ import { debug } from '$shared/utils/logger';
30
+ import type { GeneratedSshKey } from '$shared/types/git-identity';
31
+
32
+ /** Where an identity's key material lives. */
33
+ export function identityKeyDir(identityId: string): string {
34
+ return join(getClopenDir(), 'git-identities', identityId);
35
+ }
36
+
37
+ /** Absolute path of the private key file for an identity. */
38
+ export function identityKeyPath(identityId: string): string {
39
+ return join(identityKeyDir(identityId), 'id_key');
40
+ }
41
+
42
+ /**
43
+ * Write the private key to disk with 0600.
44
+ *
45
+ * On Windows the mode is advisory — ssh reads the ACL instead — so this returns
46
+ * whether strict permissions could actually be applied rather than pretending
47
+ * they were.
48
+ */
49
+ export async function writeKeyFile(
50
+ identityId: string,
51
+ privateKey: string
52
+ ): Promise<{ path: string; strictPermissions: boolean }> {
53
+ const dir = identityKeyDir(identityId);
54
+ await mkdir(dir, { recursive: true, mode: 0o700 });
55
+
56
+ const path = identityKeyPath(identityId);
57
+ // A private key without its trailing newline is rejected by some OpenSSH
58
+ // builds as malformed, and a pasted key routinely arrives without one.
59
+ const normalized = privateKey.endsWith('\n') ? privateKey : `${privateKey}\n`;
60
+ await writeFile(path, normalized, { mode: 0o600 });
61
+
62
+ let strictPermissions = true;
63
+ try {
64
+ await chmod(path, 0o600);
65
+ if (process.platform === 'win32') strictPermissions = false;
66
+ } catch (error) {
67
+ strictPermissions = false;
68
+ debug.warn('git', `Could not tighten permissions on ${path}:`, error);
69
+ }
70
+
71
+ debug.log('git', `Materialised SSH key for identity ${identityId}`);
72
+ return { path, strictPermissions };
73
+ }
74
+
75
+ /** Remove an identity's key material. Safe to call when nothing was written. */
76
+ export async function removeKeyFiles(identityId: string): Promise<void> {
77
+ try {
78
+ await rm(identityKeyDir(identityId), { recursive: true, force: true });
79
+ debug.log('git', `Removed SSH key material for identity ${identityId}`);
80
+ } catch (error) {
81
+ debug.warn('git', `Could not remove key material for ${identityId}:`, error);
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Generate an ed25519 keypair through `ssh-keygen`.
87
+ *
88
+ * The CLI rather than node:crypto: Node can produce an ed25519 keypair, but not
89
+ * in OpenSSH's own private-key container, and hand-rolling that encoding to
90
+ * save one subprocess would be a serious amount of custom crypto plumbing for
91
+ * no gain. `ssh-keygen` ships with git on every platform Clopen supports.
92
+ *
93
+ * Generated keys carry NO passphrase. A passphrase on a key Clopen stores and
94
+ * uses unattended protects nothing — the passphrase would sit sealed in the
95
+ * same database as the key it unlocks. Users who want one bring their own key.
96
+ */
97
+ export async function generateKeyPair(
98
+ identityId: string,
99
+ comment: string
100
+ ): Promise<GeneratedSshKey & { privateKey: string }> {
101
+ const dir = identityKeyDir(identityId);
102
+ await mkdir(dir, { recursive: true, mode: 0o700 });
103
+ const path = identityKeyPath(identityId);
104
+
105
+ // ssh-keygen refuses to overwrite, and prompting for confirmation would hang
106
+ // with no terminal attached.
107
+ await rm(path, { force: true });
108
+ await rm(`${path}.pub`, { force: true });
109
+
110
+ const proc = Bun.spawn(
111
+ ['ssh-keygen', '-t', 'ed25519', '-f', path, '-N', '', '-C', comment, '-q'],
112
+ {
113
+ env: getCleanSpawnEnv(),
114
+ stdin: 'ignore',
115
+ stdout: 'pipe',
116
+ stderr: 'pipe'
117
+ }
118
+ );
119
+ const stderr = await new Response(proc.stderr).text();
120
+ const code = await proc.exited;
121
+ if (code !== 0) {
122
+ throw new Error(`ssh-keygen failed: ${stderr.trim() || `exit ${code}`}`);
123
+ }
124
+
125
+ const privateKey = await Bun.file(path).text();
126
+ const publicKey = (await Bun.file(`${path}.pub`).text()).trim();
127
+
128
+ // The public file is regenerated from the stored key whenever it is needed,
129
+ // so leaving it here would be a second copy to keep in sync.
130
+ await rm(`${path}.pub`, { force: true });
131
+
132
+ debug.log('git', `Generated ed25519 keypair for identity ${identityId}`);
133
+ return { privateKey, publicKey, fingerprint: await fingerprintOf(publicKey) };
134
+ }
135
+
136
+ /**
137
+ * SHA256 fingerprint of a public key, for display.
138
+ *
139
+ * Returns an empty string when `ssh-keygen` cannot read the key: a fingerprint
140
+ * is a display detail, and failing the whole save because it could not be
141
+ * computed would be the wrong trade.
142
+ */
143
+ export async function fingerprintOf(publicKey: string): Promise<string> {
144
+ try {
145
+ const proc = Bun.spawn(['ssh-keygen', '-lf', '-'], {
146
+ env: getCleanSpawnEnv(),
147
+ stdin: new TextEncoder().encode(`${publicKey.trim()}\n`),
148
+ stdout: 'pipe',
149
+ stderr: 'pipe'
150
+ });
151
+ const out = await new Response(proc.stdout).text();
152
+ const code = await proc.exited;
153
+ if (code !== 0) return '';
154
+ // "256 SHA256:abc… comment (ED25519)" — the fingerprint is the second field.
155
+ return out.trim().split(/\s+/)[1] ?? '';
156
+ } catch {
157
+ return '';
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Derive the public key from a stored private key.
163
+ *
164
+ * Lets a user paste only their private key and still get something to copy into
165
+ * GitHub. Returns null for a key that needs a passphrase, since deriving it
166
+ * would require prompting.
167
+ */
168
+ export async function derivePublicKey(privateKeyPath: string): Promise<string | null> {
169
+ try {
170
+ const proc = Bun.spawn(['ssh-keygen', '-y', '-P', '', '-f', privateKeyPath], {
171
+ env: getCleanSpawnEnv(),
172
+ stdin: 'ignore',
173
+ stdout: 'pipe',
174
+ stderr: 'pipe'
175
+ });
176
+ const out = await new Response(proc.stdout).text();
177
+ const code = await proc.exited;
178
+ if (code !== 0) return null;
179
+ return out.trim() || null;
180
+ } catch {
181
+ return null;
182
+ }
183
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Which identity a git command runs as.
3
+ *
4
+ * ── The chain ──
5
+ * binding (project, user) → the user's default → nothing
6
+ * "Nothing" is a real answer, not a failure: Clopen then runs git exactly as it
7
+ * did before this feature existed, deferring to `.git/config` and the machine.
8
+ * That is what keeps the feature opt-in for people who already have git set up.
9
+ *
10
+ * ── Why the credential can come from a different identity ──
11
+ * Attribution is a property of the person; a credential is a property of the
12
+ * host. A fork workflow has `origin` on a personal account and `upstream` on a
13
+ * work one, and the commits belong to the same human either way. So the
14
+ * project's identity always decides `user.name`/`user.email`, while the
15
+ * credential is chosen by matching the remote's host against each identity's
16
+ * claimed hosts — falling back to the project identity when it claims the host
17
+ * itself, and to nothing when no identity does.
18
+ */
19
+
20
+ import {
21
+ gitIdentityQueries,
22
+ gitIdentityBindingQueries,
23
+ parseHosts,
24
+ type GitIdentityRow
25
+ } from '$backend/database/queries';
26
+ import { debug } from '$shared/utils/logger';
27
+ import type { GitEnvIdentity, HelperCommand } from './env';
28
+ import { identityKeyPath } from './keys';
29
+
30
+ /** Where the identity came from, for the "committing as…" line in the UI. */
31
+ export type IdentitySource = 'project' | 'user-default' | 'none';
32
+
33
+ export interface IdentityResolution {
34
+ row: GitIdentityRow | null;
35
+ source: IdentitySource;
36
+ }
37
+
38
+ /**
39
+ * The identity for a project, for one user.
40
+ *
41
+ * A binding pointing at a deleted identity resolves to the user's default
42
+ * rather than to nothing — `ON DELETE CASCADE` removes such bindings, so this
43
+ * only guards against a row that outlived its target.
44
+ */
45
+ export function resolveIdentity(projectId: string, userId: string): IdentityResolution {
46
+ const binding = gitIdentityBindingQueries.get(projectId, userId);
47
+ if (binding) {
48
+ const row = gitIdentityQueries.getById(binding.identity_id);
49
+ if (row && row.owner_user_id === userId) return { row, source: 'project' };
50
+ debug.warn('git', `Identity binding for project ${projectId} points at a missing identity`);
51
+ }
52
+
53
+ const fallback = gitIdentityQueries.getDefaultForUser(userId);
54
+ return fallback ? { row: fallback, source: 'user-default' } : { row: null, source: 'none' };
55
+ }
56
+
57
+ /** True when this identity can authenticate to `host`. */
58
+ function claimsHost(row: GitIdentityRow, host: string): boolean {
59
+ if (row.auth_method === 'none') return false;
60
+ return parseHosts(row.hosts).includes(host);
61
+ }
62
+
63
+ /**
64
+ * The identity whose credential should answer for `host`.
65
+ *
66
+ * Prefers the one already chosen for the project, so the common case never
67
+ * looks past it. Otherwise the user's other identities are searched, and a
68
+ * single match wins. AMBIGUITY IS RESOLVED AS "NO CREDENTIAL": if two
69
+ * identities claim the same host, picking one arbitrarily would authenticate
70
+ * as an account the user did not choose, and a push that fails asking for a
71
+ * credential is far easier to understand than a push that lands under the
72
+ * wrong name.
73
+ */
74
+ export function pickCredentialIdentity(
75
+ userId: string,
76
+ host: string | null,
77
+ primary: GitIdentityRow | null
78
+ ): GitIdentityRow | null {
79
+ if (!host) return null;
80
+ if (primary && claimsHost(primary, host)) return primary;
81
+
82
+ const candidates = gitIdentityQueries
83
+ .listByUser(userId)
84
+ .filter((row) => claimsHost(row, host));
85
+
86
+ if (candidates.length === 1) return candidates[0]!;
87
+ if (candidates.length > 1) {
88
+ debug.warn(
89
+ 'git',
90
+ `${candidates.length} identities claim ${host}; refusing to guess which credential to use`
91
+ );
92
+ }
93
+ return null;
94
+ }
95
+
96
+ /**
97
+ * Flatten a row (plus an optional credential row) into what the env builder needs.
98
+ *
99
+ * The two halves can come from different identities, which is the whole point
100
+ * of `pickCredentialIdentity` — attribution from one, credential from another.
101
+ */
102
+ export function toEnvIdentity(
103
+ row: GitIdentityRow,
104
+ credential: GitIdentityRow | null
105
+ ): GitEnvIdentity {
106
+ const credentialRow = credential ?? null;
107
+ const usesSsh = credentialRow?.auth_method === 'ssh-key' && !!credentialRow.ssh_private_key;
108
+ const usesHttps =
109
+ credentialRow?.auth_method === 'https-token' || credentialRow?.auth_method === 'https-account';
110
+
111
+ return {
112
+ // The helper is invoked with the CREDENTIAL identity's id when one exists,
113
+ // because that is the row holding the token it must read back.
114
+ id: credentialRow?.id ?? row.id,
115
+ name: row.name,
116
+ email: row.email,
117
+ sshKeyPath: usesSsh ? identityKeyPath(credentialRow!.id) : null,
118
+ needsPassphrase: usesSsh ? !!credentialRow!.ssh_passphrase : false,
119
+ httpsUsername: usesHttps ? credentialRow!.https_username : null,
120
+ credentialHosts: usesHttps ? parseHosts(credentialRow!.hosts) : []
121
+ };
122
+ }
123
+
124
+ /**
125
+ * How to re-invoke this Clopen for the credential/askpass helpers.
126
+ *
127
+ * Taken from the running process rather than from a configured path: whichever
128
+ * runtime and entry script are executing right now are, by definition, the ones
129
+ * that work. A hardcoded `clopen` on PATH would break for a source checkout, and
130
+ * a packaged path would break for a global install.
131
+ */
132
+ export function helperCommand(): HelperCommand | undefined {
133
+ const runtime = process.execPath;
134
+ const script = Bun.main;
135
+ if (!runtime || !script) {
136
+ debug.warn('git', 'Cannot locate the Clopen entry point; git credential helpers disabled');
137
+ return undefined;
138
+ }
139
+ return { runtime, script };
140
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * The terminal's config file, checked against real git.
3
+ *
4
+ * This file exists because the mechanism has one dangerous failure mode:
5
+ * `GIT_CONFIG_GLOBAL` REPLACES `~/.gitconfig`. Get the `[include]` wrong and
6
+ * every terminal silently loses the user's aliases, diff tool and everything
7
+ * else they have configured — while the identity part still looks correct.
8
+ */
9
+
10
+ import { afterEach, describe, expect, test } from 'bun:test';
11
+ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import { renderScopeConfig } from './scope-config';
15
+
16
+ const dirs: string[] = [];
17
+ const originalXdg = process.env.XDG_CONFIG_HOME;
18
+
19
+ afterEach(async () => {
20
+ let dir: string | undefined;
21
+ while ((dir = dirs.pop())) await rm(dir, { recursive: true, force: true });
22
+ if (originalXdg === undefined) delete process.env.XDG_CONFIG_HOME;
23
+ else process.env.XDG_CONFIG_HOME = originalXdg;
24
+ });
25
+
26
+ /** A fake XDG git config the generated file should include. */
27
+ async function withUserConfig(contents: string): Promise<string> {
28
+ const dir = await mkdtemp(join(tmpdir(), 'clopen-xdg-'));
29
+ dirs.push(dir);
30
+ await mkdir(join(dir, 'git'), { recursive: true });
31
+ await writeFile(join(dir, 'git', 'config'), contents);
32
+ process.env.XDG_CONFIG_HOME = dir;
33
+ return dir;
34
+ }
35
+
36
+ async function writeGenerated(pairs: Array<[string, string]>): Promise<string> {
37
+ const dir = await mkdtemp(join(tmpdir(), 'clopen-scope-'));
38
+ dirs.push(dir);
39
+ const path = join(dir, 'generated.gitconfig');
40
+ await writeFile(path, renderScopeConfig(pairs));
41
+ return path;
42
+ }
43
+
44
+ async function gitConfig(key: string, configPath: string, cwd: string): Promise<string> {
45
+ const proc = Bun.spawn(['git', 'config', '--get', key], {
46
+ cwd,
47
+ env: { ...process.env, GIT_CONFIG_GLOBAL: configPath, GIT_CONFIG_SYSTEM: '/dev/null' } as Record<
48
+ string,
49
+ string
50
+ >,
51
+ stdout: 'pipe',
52
+ stderr: 'pipe'
53
+ });
54
+ const out = await new Response(proc.stdout).text();
55
+ await proc.exited;
56
+ return out.trim();
57
+ }
58
+
59
+ async function tempRepo(): Promise<string> {
60
+ const dir = await mkdtemp(join(tmpdir(), 'clopen-scope-repo-'));
61
+ dirs.push(dir);
62
+ const proc = Bun.spawn(['git', 'init', '-q', '.'], { cwd: dir, stdout: 'pipe', stderr: 'pipe' });
63
+ await proc.exited;
64
+ return dir;
65
+ }
66
+
67
+ describe('renderScopeConfig', () => {
68
+ test('git reads the identity out of it', async () => {
69
+ await withUserConfig('[alias]\n\tlg = log --oneline\n');
70
+ const path = await writeGenerated([
71
+ ['user.name', 'Ada Lovelace'],
72
+ ['user.email', 'ada@example.com']
73
+ ]);
74
+ const repo = await tempRepo();
75
+
76
+ expect(await gitConfig('user.name', path, repo)).toBe('Ada Lovelace');
77
+ expect(await gitConfig('user.email', path, repo)).toBe('ada@example.com');
78
+ }, 60_000);
79
+
80
+ test("the user's own global config survives", async () => {
81
+ // The dangerous failure: GIT_CONFIG_GLOBAL replaces ~/.gitconfig, so
82
+ // without the include the alias below would simply vanish in terminals.
83
+ await withUserConfig('[alias]\n\tlg = log --oneline\n[core]\n\tpager = delta\n');
84
+ const path = await writeGenerated([['user.email', 'ada@example.com']]);
85
+ const repo = await tempRepo();
86
+
87
+ expect(await gitConfig('alias.lg', path, repo)).toBe('log --oneline');
88
+ expect(await gitConfig('core.pager', path, repo)).toBe('delta');
89
+ }, 60_000);
90
+
91
+ test('our value wins over the same key in the user config', async () => {
92
+ // The include comes first precisely so this ordering holds.
93
+ await withUserConfig('[user]\n\temail = machine@example.com\n');
94
+ const path = await writeGenerated([['user.email', 'chosen@example.com']]);
95
+ const repo = await tempRepo();
96
+
97
+ expect(await gitConfig('user.email', path, repo)).toBe('chosen@example.com');
98
+ }, 60_000);
99
+
100
+ test('a URL subsection key survives verbatim', async () => {
101
+ // `credential.https://host.username` has dots and slashes inside the
102
+ // subsection; splitting it wrong is how the credential silently stops
103
+ // matching the host.
104
+ const path = await writeGenerated([
105
+ ['credential.https://github.com.username', 'ada'],
106
+ ['user.email', 'ada@example.com']
107
+ ]);
108
+ const repo = await tempRepo();
109
+
110
+ expect(await gitConfig('credential.https://github.com.username', path, repo)).toBe('ada');
111
+ }, 60_000);
112
+
113
+ test('a value with quotes and backslashes round-trips', async () => {
114
+ const weird = `ssh -i "/keys/it's odd\\path" -o IdentitiesOnly=yes`;
115
+ const path = await writeGenerated([['core.sshCommand', weird]]);
116
+ const repo = await tempRepo();
117
+
118
+ expect(await gitConfig('core.sshCommand', path, repo)).toBe(weird);
119
+ }, 60_000);
120
+
121
+ test('a multi-valued key keeps both entries in order', async () => {
122
+ // The empty-then-helper pair that stops the machine's keychain answering.
123
+ const path = await writeGenerated([
124
+ ['credential.helper', ''],
125
+ ['credential.helper', '!clopen-helper']
126
+ ]);
127
+ const repo = await tempRepo();
128
+
129
+ const proc = Bun.spawn(['git', 'config', '--get-all', 'credential.helper'], {
130
+ cwd: repo,
131
+ env: { ...process.env, GIT_CONFIG_GLOBAL: path, GIT_CONFIG_SYSTEM: '/dev/null' } as Record<
132
+ string,
133
+ string
134
+ >,
135
+ stdout: 'pipe',
136
+ stderr: 'pipe'
137
+ });
138
+ const out = await new Response(proc.stdout).text();
139
+ await proc.exited;
140
+ expect(out.split('\n').filter((l) => l !== '' || true).slice(0, 2)).toEqual([
141
+ '',
142
+ '!clopen-helper'
143
+ ]);
144
+ }, 60_000);
145
+ });