@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,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
+ });
@@ -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
+ }