@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,175 @@
1
+ /**
2
+ * A git config file per (user, project), for the one surface that outlives a
3
+ * single command: the terminal.
4
+ *
5
+ * ── The problem this solves ──
6
+ * `GIT_CONFIG_*` is read from the environment, and a process's environment is
7
+ * fixed when it is spawned. That is fine for the Git panel (one process per
8
+ * command) and for an engine turn, but a shell lives for hours. PtyKit's
9
+ * `createSession` is idempotent and Clopen's session ids are deterministic
10
+ * (`<project>-terminal-1`), so a tab opened before an account was chosen — or
11
+ * before it was changed — keeps the environment it started with, silently, for
12
+ * as long as it stays open. A user who switches accounts, sees the Git panel
13
+ * update, and then commits from the terminal gets the OLD identity with nothing
14
+ * to indicate it.
15
+ *
16
+ * A file is re-read by git on every single invocation, so pointing
17
+ * `GIT_CONFIG_GLOBAL` at one makes a change take effect in tabs that are already
18
+ * open. The file is rewritten whenever the resolution could have changed.
19
+ *
20
+ * ── Why the user's own global config is not lost ──
21
+ * `GIT_CONFIG_GLOBAL` REPLACES `~/.gitconfig` rather than adding to it, which
22
+ * would take the user's aliases, diff tools and everything else with it. So the
23
+ * generated file `[include]`s the real ones FIRST, then sets the identity — git
24
+ * applies later values last, so ours win while everything else survives.
25
+ *
26
+ * ── Precedence, stated plainly ──
27
+ * A global file ranks BELOW a repository's own `.git/config`. So in a terminal, a
28
+ * repo that hardcodes `user.email` keeps winning, where the Git panel's
29
+ * `GIT_CONFIG_*` would override it. That is a real difference and it is the
30
+ * deliberate trade: a stale identity is silent and wrong, while a repo-local
31
+ * override is something the user wrote on purpose.
32
+ */
33
+
34
+ import { mkdir, rm, writeFile } from 'node:fs/promises';
35
+ import { existsSync } from 'node:fs';
36
+ import { homedir } from 'node:os';
37
+ import { join } from 'node:path';
38
+ import { getClopenDir } from '$backend/utils/paths';
39
+ import { debug } from '$shared/utils/logger';
40
+ import { buildGitConfigPairs } from './env';
41
+ import { helperCommand, pickCredentialIdentity, resolveIdentity, toEnvIdentity } from './resolve';
42
+
43
+ /** Where the generated per-scope config files live. */
44
+ function scopeConfigDir(): string {
45
+ return join(getClopenDir(), 'git-identities', 'scopes');
46
+ }
47
+
48
+ /**
49
+ * Path of the config file for one (user, project).
50
+ *
51
+ * Both ids are in the name because the identity is chosen per pair — two people
52
+ * in one project must not share a file.
53
+ */
54
+ export function scopeConfigPath(userId: string, projectId: string): string {
55
+ return join(scopeConfigDir(), `${userId}__${projectId}.gitconfig`);
56
+ }
57
+
58
+ /** The config files git would normally read as "global", in the order it does. */
59
+ function realGlobalConfigPaths(): string[] {
60
+ const home = homedir();
61
+ const xdg = process.env.XDG_CONFIG_HOME?.trim() || join(home, '.config');
62
+ // Git reads the XDG path first and `~/.gitconfig` second, so a value in the
63
+ // latter wins. Preserving that order keeps the user's own precedence intact.
64
+ return [join(xdg, 'git', 'config'), join(home, '.gitconfig')].filter((p) => existsSync(p));
65
+ }
66
+
67
+ /** Escape a value for a git config file's `key = value` form. */
68
+ function configValue(value: string): string {
69
+ // Quoted, with backslashes and quotes escaped: git's own parser rule. Without
70
+ // it an ssh command containing a quoted path would truncate the value.
71
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
72
+ }
73
+
74
+ /**
75
+ * Render the file contents for a set of config pairs.
76
+ *
77
+ * Written as flat `section.key` lines under a single `[include]` plus one
78
+ * section per key rather than grouping, because the pairs arrive as dotted keys
79
+ * and splitting them into sections by hand is where a subkey like
80
+ * `credential.https://host.username` gets mangled.
81
+ */
82
+ export function renderScopeConfig(pairs: Array<[string, string]>): string {
83
+ const lines = [
84
+ '# Generated by Clopen — do not edit.',
85
+ '# Identity for one (user, project); regenerated whenever it changes.',
86
+ ''
87
+ ];
88
+
89
+ const includes = realGlobalConfigPaths();
90
+ if (includes.length > 0) {
91
+ // First, so the user's own settings are the base and ours override them.
92
+ lines.push('[include]');
93
+ for (const path of includes) lines.push(`\tpath = ${configValue(path)}`);
94
+ lines.push('');
95
+ }
96
+
97
+ for (const [key, value] of pairs) {
98
+ // `section.subsection.key` — the subsection is everything between, and it
99
+ // is the part that must stay verbatim (it can contain dots and slashes).
100
+ const first = key.indexOf('.');
101
+ const last = key.lastIndexOf('.');
102
+ if (first <= 0) continue;
103
+ const section = key.slice(0, first);
104
+ const leaf = key.slice(last + 1);
105
+ const subsection = last > first ? key.slice(first + 1, last) : null;
106
+
107
+ lines.push(subsection ? `[${section} ${configValue(subsection)}]` : `[${section}]`);
108
+ lines.push(`\t${leaf} = ${configValue(value)}`);
109
+ }
110
+
111
+ return `${lines.join('\n')}\n`;
112
+ }
113
+
114
+ /**
115
+ * Write (or remove) the config file for one (user, project).
116
+ *
117
+ * Returns the path when a file now exists, and `null` when there is nothing to
118
+ * write. The caller must only set `GIT_CONFIG_GLOBAL` on a non-null result:
119
+ * pointing it at a missing file would make git ignore the user's real global
120
+ * config entirely, which is a far worse outcome than having no identity.
121
+ */
122
+ export async function writeScopeConfig(
123
+ userId: string,
124
+ projectId: string
125
+ ): Promise<string | null> {
126
+ try {
127
+ const { row } = resolveIdentity(projectId, userId);
128
+ const path = scopeConfigPath(userId, projectId);
129
+
130
+ if (!row) {
131
+ // No identity — remove any file from a previous one, so a cleared
132
+ // binding does not keep applying.
133
+ await rm(path, { force: true });
134
+ return null;
135
+ }
136
+
137
+ // No remote URL here: a terminal is not one command against one remote, so
138
+ // the credential comes from the identity's own host claims.
139
+ const credential = pickCredentialIdentity(userId, null, row);
140
+ const pairs = buildGitConfigPairs(toEnvIdentity(row, credential), helperCommand());
141
+
142
+ await mkdir(scopeConfigDir(), { recursive: true, mode: 0o700 });
143
+ await writeFile(path, renderScopeConfig(pairs), { mode: 0o600 });
144
+ debug.log('git', `Wrote git scope config for ${userId} in project ${projectId}`);
145
+ return path;
146
+ } catch (error) {
147
+ // A terminal with the machine's identity is a working terminal; failing to
148
+ // open one because a config file could not be written would not be.
149
+ debug.warn('git', 'Could not write the git scope config:', error);
150
+ return null;
151
+ }
152
+ }
153
+
154
+ /** Drop the file for one (user, project). */
155
+ export async function removeScopeConfig(userId: string, projectId: string): Promise<void> {
156
+ await rm(scopeConfigPath(userId, projectId), { force: true }).catch(() => {});
157
+ }
158
+
159
+ /**
160
+ * Refresh every file that could be affected by a change to `identityId`.
161
+ *
162
+ * Called after a create/update/delete/default change, so a shell that is already
163
+ * open picks the new identity up on its next git command. Bindings naming the
164
+ * identity are refreshed, and so is every project the user's default reaches —
165
+ * which is why the project list is consulted rather than only the bindings.
166
+ */
167
+ export async function refreshScopeConfigsForUser(userId: string): Promise<void> {
168
+ try {
169
+ const { projectQueries } = await import('$backend/database/queries');
170
+ const projects = projectQueries.getAllForUser(userId);
171
+ await Promise.all(projects.map((project) => writeScopeConfig(userId, project.id)));
172
+ } catch (error) {
173
+ debug.warn('git', 'Could not refresh git scope configs:', error);
174
+ }
175
+ }
@@ -0,0 +1,297 @@
1
+ /**
2
+ * The git identity service — CRUD, key materialisation, and the DTO boundary.
3
+ *
4
+ * One rule governs this module: A SECRET NEVER LEAVES IT. `toDTO` reduces the
5
+ * private key, its passphrase, and the HTTPS token to booleans, so no code path
6
+ * above this file can accidentally serialise one to a browser. The public key
7
+ * is the deliberate exception — it is public, and the user needs to copy it.
8
+ *
9
+ * Key material on disk is kept in step with the row here rather than in the
10
+ * query layer: writing a file is not part of storing a row, and a failed write
11
+ * must not leave a saved identity whose key silently does not exist.
12
+ */
13
+
14
+ import { randomUUID } from 'node:crypto';
15
+ import {
16
+ gitIdentityQueries,
17
+ gitIdentityBindingQueries,
18
+ parseHosts,
19
+ type GitIdentityRow
20
+ } from '$backend/database/queries';
21
+ import { debug } from '$shared/utils/logger';
22
+ import type {
23
+ GeneratedSshKey,
24
+ GitIdentityDTO,
25
+ GitIdentityInput
26
+ } from '$shared/types/git-identity';
27
+ import { derivePublicKey, generateKeyPair, identityKeyPath, removeKeyFiles, writeKeyFile } from './keys';
28
+ import { syncLocalMachineIdentity } from './import-local';
29
+ import { refreshScopeConfigsForUser, writeScopeConfig } from './scope-config';
30
+
31
+ /** Strip a row down to what a client may see. */
32
+ export function toDTO(row: GitIdentityRow): GitIdentityDTO {
33
+ return {
34
+ id: row.id,
35
+ label: row.label,
36
+ name: row.name,
37
+ email: row.email,
38
+ authMethod: row.auth_method,
39
+ hosts: parseHosts(row.hosts),
40
+ sshPublicKey: row.ssh_public_key,
41
+ hasSshKey: !!row.ssh_private_key,
42
+ hasSshPassphrase: !!row.ssh_passphrase,
43
+ hasHttpsToken: !!row.https_token,
44
+ httpsUsername: row.https_username,
45
+ integrationAccountId: row.integration_account_id,
46
+ isDefault: row.is_default === 1,
47
+ source: row.source,
48
+ // Mirrored rows are not deletable: the machine's config still exists, so a
49
+ // delete would only be undone by the next list read.
50
+ canDelete: row.source !== 'local-machine',
51
+ createdAt: row.created_at,
52
+ updatedAt: row.updated_at
53
+ };
54
+ }
55
+
56
+ function assertValid(input: GitIdentityInput): void {
57
+ if (!input.label.trim()) throw new Error('An identity needs a label');
58
+ if (!input.name.trim()) throw new Error('An identity needs a name');
59
+ const email = input.email.trim();
60
+ // Deliberately loose. Git accepts anything without whitespace or angle
61
+ // brackets as an email, and rejecting an address a host does accept would be
62
+ // the more annoying failure.
63
+ if (!email || /[\s<>]/.test(email)) throw new Error('That email is not usable in a git commit');
64
+ }
65
+
66
+ /**
67
+ * Keep the key file in step with the row.
68
+ *
69
+ * Called after every write. Reads the stored (already unsealed) key rather than
70
+ * the input, so an edit that leaves the key untouched still guarantees the file
71
+ * exists — which matters after a restore onto a machine that has the database
72
+ * but not the key files.
73
+ */
74
+ async function syncKeyFile(row: GitIdentityRow): Promise<GitIdentityRow> {
75
+ if (row.auth_method !== 'ssh-key' || !row.ssh_private_key) {
76
+ await removeKeyFiles(row.id);
77
+ return row;
78
+ }
79
+
80
+ const { strictPermissions } = await writeKeyFile(row.id, row.ssh_private_key);
81
+ if (!strictPermissions) {
82
+ // Said once, loudly, rather than left for the user to decode out of an
83
+ // ssh error at push time.
84
+ debug.warn(
85
+ 'git',
86
+ `Key for identity ${row.id} could not be given strict permissions; ssh may refuse it`
87
+ );
88
+ }
89
+
90
+ // A user who pasted only a private key still gets something to copy into
91
+ // GitHub. Skipped for passphrased keys, which cannot be read unattended.
92
+ if (!row.ssh_public_key && !row.ssh_passphrase) {
93
+ const derived = await derivePublicKey(identityKeyPath(row.id));
94
+ if (derived) {
95
+ const updated = gitIdentityQueries.update(row.id, {
96
+ label: row.label,
97
+ name: row.name,
98
+ email: row.email,
99
+ authMethod: row.auth_method,
100
+ hosts: parseHosts(row.hosts),
101
+ sshPublicKey: derived,
102
+ httpsUsername: row.https_username,
103
+ integrationAccountId: row.integration_account_id
104
+ });
105
+ if (updated) return updated;
106
+ }
107
+ }
108
+
109
+ return row;
110
+ }
111
+
112
+ export const gitIdentityService = {
113
+ /**
114
+ * Every identity this user owns, mirroring the machine's git config first.
115
+ *
116
+ * Done on the read rather than at startup so it also covers a user who joins
117
+ * later, and because it is the moment the result is actually about to be
118
+ * shown. It is idempotent and only writes on the first call per user.
119
+ */
120
+ async list(userId: string): Promise<GitIdentityDTO[]> {
121
+ await syncLocalMachineIdentity(userId);
122
+ return gitIdentityQueries.listByUser(userId).map(toDTO);
123
+ },
124
+
125
+ get(userId: string, id: string): GitIdentityDTO | null {
126
+ const row = gitIdentityQueries.getById(id);
127
+ if (!row || row.owner_user_id !== userId) return null;
128
+ return toDTO(row);
129
+ },
130
+
131
+ async create(userId: string, input: GitIdentityInput): Promise<GitIdentityDTO> {
132
+ assertValid(input);
133
+ if (gitIdentityQueries.labelTaken(userId, input.label.trim())) {
134
+ throw new Error(`You already have an identity called "${input.label.trim()}"`);
135
+ }
136
+
137
+ const id = randomUUID();
138
+ let row = gitIdentityQueries.create(id, userId, {
139
+ label: input.label.trim(),
140
+ name: input.name.trim(),
141
+ email: input.email.trim(),
142
+ authMethod: input.authMethod,
143
+ hosts: input.hosts,
144
+ sshPrivateKey: input.sshPrivateKey ?? null,
145
+ sshPublicKey: input.sshPublicKey ?? null,
146
+ sshPassphrase: input.sshPassphrase ?? null,
147
+ httpsUsername: input.httpsUsername ?? null,
148
+ httpsToken: input.httpsToken ?? null,
149
+ integrationAccountId: input.integrationAccountId ?? null
150
+ });
151
+
152
+ row = await syncKeyFile(row);
153
+
154
+ // The first identity a user creates becomes their default — otherwise it
155
+ // would sit there doing nothing until they found the toggle, which reads
156
+ // as the feature being broken.
157
+ if (input.isDefault || gitIdentityQueries.listByUser(userId).length === 1) {
158
+ gitIdentityQueries.setDefault(userId, id);
159
+ row = gitIdentityQueries.getById(id)!;
160
+ }
161
+
162
+ // Terminals that are already open read their identity from a file, so it is
163
+ // rewritten here — otherwise the new account would only reach tabs opened
164
+ // after this point.
165
+ await refreshScopeConfigsForUser(userId);
166
+
167
+ debug.log('git', `Created git identity "${row.label}" for user ${userId}`);
168
+ return toDTO(row);
169
+ },
170
+
171
+ async update(userId: string, id: string, input: GitIdentityInput): Promise<GitIdentityDTO> {
172
+ assertValid(input);
173
+ const existing = gitIdentityQueries.getById(id);
174
+ if (!existing || existing.owner_user_id !== userId) throw new Error('Identity not found');
175
+ if (gitIdentityQueries.labelTaken(userId, input.label.trim(), id)) {
176
+ throw new Error(`You already have an identity called "${input.label.trim()}"`);
177
+ }
178
+
179
+ let row = gitIdentityQueries.update(id, {
180
+ label: input.label.trim(),
181
+ name: input.name.trim(),
182
+ email: input.email.trim(),
183
+ authMethod: input.authMethod,
184
+ hosts: input.hosts,
185
+ // `undefined` keeps the stored secret, `null` clears it — the
186
+ // distinction the query layer depends on.
187
+ sshPrivateKey: input.sshPrivateKey,
188
+ sshPublicKey: input.sshPublicKey ?? existing.ssh_public_key,
189
+ sshPassphrase: input.sshPassphrase,
190
+ httpsUsername: input.httpsUsername ?? null,
191
+ httpsToken: input.httpsToken,
192
+ integrationAccountId: input.integrationAccountId ?? null
193
+ // `source` is deliberately absent: the update statement does not touch
194
+ // that column, so an edited mirror stays a mirror — and stays
195
+ // undeletable, because the machine config it reflects is still there.
196
+ });
197
+ if (!row) throw new Error('Identity not found');
198
+
199
+ row = await syncKeyFile(row);
200
+
201
+ if (input.isDefault && row.is_default !== 1) {
202
+ gitIdentityQueries.setDefault(userId, id);
203
+ row = gitIdentityQueries.getById(id)!;
204
+ }
205
+
206
+ await refreshScopeConfigsForUser(userId);
207
+
208
+ debug.log('git', `Updated git identity "${row.label}"`);
209
+ return toDTO(row);
210
+ },
211
+
212
+ async remove(userId: string, id: string): Promise<void> {
213
+ const row = gitIdentityQueries.getById(id);
214
+ if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
215
+ if (row.source === 'local-machine') {
216
+ throw new Error(
217
+ "This account mirrors the machine's own git config, so it cannot be deleted. Edit it instead."
218
+ );
219
+ }
220
+
221
+ gitIdentityQueries.remove(id);
222
+ await removeKeyFiles(id);
223
+
224
+ // Deleting the default leaves the user with none, so the next one in the
225
+ // list takes over rather than every project silently losing its identity.
226
+ if (row.is_default === 1) {
227
+ const remaining = gitIdentityQueries.listByUser(userId);
228
+ if (remaining.length > 0) gitIdentityQueries.setDefault(userId, remaining[0]!.id);
229
+ }
230
+
231
+ await refreshScopeConfigsForUser(userId);
232
+
233
+ debug.log('git', `Removed git identity "${row.label}"`);
234
+ },
235
+
236
+ async setDefault(userId: string, id: string): Promise<GitIdentityDTO> {
237
+ const row = gitIdentityQueries.getById(id);
238
+ if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
239
+ gitIdentityQueries.setDefault(userId, id);
240
+ // Every project that inherits the default is affected, not just one.
241
+ await refreshScopeConfigsForUser(userId);
242
+ return toDTO(gitIdentityQueries.getById(id)!);
243
+ },
244
+
245
+ /**
246
+ * Generate a keypair for an identity and store the private half.
247
+ *
248
+ * Returns only the public key and its fingerprint; the private key goes
249
+ * straight into the sealed column and the 0600 file.
250
+ */
251
+ async generateKey(userId: string, id: string): Promise<GeneratedSshKey> {
252
+ const row = gitIdentityQueries.getById(id);
253
+ if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
254
+
255
+ const { privateKey, publicKey, fingerprint } = await generateKeyPair(
256
+ id,
257
+ `${row.email} (clopen)`
258
+ );
259
+
260
+ gitIdentityQueries.update(id, {
261
+ label: row.label,
262
+ name: row.name,
263
+ email: row.email,
264
+ authMethod: 'ssh-key',
265
+ hosts: parseHosts(row.hosts),
266
+ sshPrivateKey: privateKey,
267
+ sshPublicKey: publicKey,
268
+ // A generated key has no passphrase, so any stored one is now wrong.
269
+ sshPassphrase: null,
270
+ httpsUsername: row.https_username,
271
+ integrationAccountId: row.integration_account_id
272
+ });
273
+
274
+ await refreshScopeConfigsForUser(userId);
275
+
276
+ debug.log('git', `Generated SSH key for identity "${row.label}"`);
277
+ return { publicKey, fingerprint };
278
+ },
279
+
280
+ /** Bind a project to an identity, for this user. */
281
+ async bind(userId: string, projectId: string, identityId: string | null): Promise<void> {
282
+ if (identityId === null) {
283
+ gitIdentityBindingQueries.clear(projectId, userId);
284
+ } else {
285
+ const row = gitIdentityQueries.getById(identityId);
286
+ if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
287
+ gitIdentityBindingQueries.set(projectId, userId, identityId);
288
+ }
289
+ // Only this project's file can have changed, so only it is rewritten.
290
+ await writeScopeConfig(userId, projectId);
291
+ },
292
+
293
+ /** How many projects would lose their binding if this identity went away. */
294
+ bindingCount(identityId: string): number {
295
+ return gitIdentityBindingQueries.countForIdentity(identityId);
296
+ }
297
+ };
package/backend/index.ts CHANGED
@@ -16,6 +16,22 @@ if (typeof globalThis.Bun === 'undefined') {
16
16
  // MUST be first import — cleans process.env before any other module reads it.
17
17
  import { SERVER_ENV } from './utils/env';
18
18
 
19
+ // Git's credential/askpass helpers re-invoke Clopen through whatever entry point
20
+ // is running, which is `Bun.main` — and that is this file under `bun --watch
21
+ // backend/index.ts`, and `scripts/start.ts` (which imports this one) under `bun
22
+ // run start`. `bin/clopen.ts` has the same guard for a global install. All three
23
+ // need it: without one, git would spawn an entry that does not know the
24
+ // subcommand, and an HTTPS push would fail asking for a password nobody typed.
25
+ //
26
+ // Placed here, above every side-effecting import, so a helper invocation exits
27
+ // before anything opens a port or starts a watcher.
28
+ import { runGitHelper } from './git/identity/cli';
29
+
30
+ {
31
+ const helperExit = await runGitHelper(process.argv.slice(2));
32
+ if (helperExit !== null) process.exit(helperExit);
33
+ }
34
+
19
35
  import { Elysia } from 'elysia';
20
36
  import { corsMiddleware } from './middleware/cors';
21
37
  import { errorHandlerMiddleware } from './middleware/error-handler';