@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
@@ -3,7 +3,7 @@
3
3
  * High-level git operations built on top of executor and parser
4
4
  */
5
5
 
6
- import { execGit, isGitRepo, getGitRoot, type GitExecResult } from './git-executor';
6
+ import { execGit, isGitRepo, getGitRoot, type GitExecResult, type GitIdentityEnv } from './git-executor';
7
7
  import { resolveBinary } from '../utils/cli';
8
8
  import { getCleanSpawnEnv } from '../utils/env';
9
9
  import {
@@ -35,6 +35,7 @@ import type {
35
35
  GitOperationState,
36
36
  GitReflogEntry
37
37
  } from '$shared/types/git';
38
+ import { naturalCompare } from '$shared/utils/compare';
38
39
  import { debug } from '$shared/utils/logger';
39
40
  import {
40
41
  assertSafeGitCommitMessage,
@@ -241,9 +242,18 @@ export class GitService {
241
242
  // Commit
242
243
  // ============================================
243
244
 
244
- async commit(cwd: string, message: string): Promise<string> {
245
+ /**
246
+ * Create a commit.
247
+ *
248
+ * `identityEnv` carries who is committing (see `backend/git/identity`). It is
249
+ * threaded explicitly through the operations that create a git object or talk
250
+ * to a remote, rather than resolved inside `execGit`, because resolving it
251
+ * reads the database and the read-only commands run constantly. Anything
252
+ * added here that writes an object or authenticates needs the same parameter.
253
+ */
254
+ async commit(cwd: string, message: string, identityEnv: GitIdentityEnv = {}): Promise<string> {
245
255
  assertSafeGitCommitMessage(message);
246
- const result = await execGit(['commit', '-m', message], cwd);
256
+ const result = await execGit(['commit', '-m', message], cwd, { env: identityEnv });
247
257
  if (result.exitCode !== 0) {
248
258
  throw new Error(`git commit failed: ${result.stderr}`);
249
259
  }
@@ -252,7 +262,7 @@ export class GitService {
252
262
  return hashResult.stdout.trim();
253
263
  }
254
264
 
255
- async amendCommit(cwd: string, message?: string): Promise<string> {
265
+ async amendCommit(cwd: string, message?: string, identityEnv: GitIdentityEnv = {}): Promise<string> {
256
266
  const args = ['commit', '--amend'];
257
267
  if (message) {
258
268
  assertSafeGitCommitMessage(message);
@@ -260,7 +270,7 @@ export class GitService {
260
270
  } else {
261
271
  args.push('--no-edit');
262
272
  }
263
- const result = await execGit(args, cwd);
273
+ const result = await execGit(args, cwd, { env: identityEnv });
264
274
  if (result.exitCode !== 0) {
265
275
  // Unborn HEAD — git says "You have nothing to amend", which reads like a
266
276
  // failure rather than "commit normally instead".
@@ -478,7 +488,7 @@ export class GitService {
478
488
  })
479
489
  );
480
490
  // Stable order for the UI (sorted by relPath).
481
- nestedResults.sort((a, b) => a.relPath.localeCompare(b.relPath));
491
+ nestedResults.sort((a, b) => naturalCompare(a.relPath, b.relPath));
482
492
  branchInfo.nested = nestedResults;
483
493
  }
484
494
  } catch (err) {
@@ -535,10 +545,10 @@ export class GitService {
535
545
  }
536
546
  }
537
547
 
538
- async deleteRemoteBranch(cwd: string, remote: string, branch: string): Promise<void> {
548
+ async deleteRemoteBranch(cwd: string, remote: string, branch: string, identityEnv: GitIdentityEnv = {}): Promise<void> {
539
549
  assertSafeGitRevish(remote, 'remote name');
540
550
  assertSafeGitRevish(branch, 'branch name');
541
- const result = await execGit(['push', remote, '--delete', branch], cwd);
551
+ const result = await execGit(['push', remote, '--delete', branch], cwd, { env: identityEnv });
542
552
  if (result.exitCode !== 0) {
543
553
  throw new Error(`git push --delete failed: ${result.stderr}`);
544
554
  }
@@ -555,7 +565,8 @@ export class GitService {
555
565
  async mergeBranch(
556
566
  cwd: string,
557
567
  branchName: string,
558
- options: { noFastForward?: boolean; squash?: boolean; ffOnly?: boolean } | boolean = false
568
+ options: { noFastForward?: boolean; squash?: boolean; ffOnly?: boolean } | boolean = false,
569
+ identityEnv: GitIdentityEnv = {}
559
570
  ): Promise<{ success: boolean; message: string }> {
560
571
  assertSafeGitRevish(branchName, 'merge branch');
561
572
  const opts = typeof options === 'boolean' ? { noFastForward: options } : options;
@@ -564,7 +575,7 @@ export class GitService {
564
575
  else if (opts.ffOnly) args.push('--ff-only');
565
576
  else if (opts.noFastForward) args.push('--no-ff');
566
577
  args.push(branchName);
567
- const result = await execGit(args, cwd, 120000);
578
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
568
579
  return {
569
580
  success: result.exitCode === 0,
570
581
  message: result.exitCode === 0 ? result.stdout : result.stderr
@@ -627,10 +638,10 @@ export class GitService {
627
638
  return parseRemotes(result.stdout);
628
639
  }
629
640
 
630
- async fetch(cwd: string, remote = 'origin'): Promise<string> {
641
+ async fetch(cwd: string, remote = 'origin', identityEnv: GitIdentityEnv = {}): Promise<string> {
631
642
  assertSafeGitRemoteName(remote);
632
643
  // Use explicit refspec to ensure all branches are fetched regardless of clone config
633
- const result = await execGit(['fetch', remote, `+refs/heads/*:refs/remotes/${remote}/*`, '--prune'], cwd, 60000);
644
+ const result = await execGit(['fetch', remote, `+refs/heads/*:refs/remotes/${remote}/*`, '--prune'], cwd, { timeout: 60000, env: identityEnv });
634
645
  if (result.exitCode !== 0) {
635
646
  throw new Error(`git fetch failed: ${result.stderr}`);
636
647
  }
@@ -645,7 +656,7 @@ export class GitService {
645
656
  * differently-named branch, which is the normal state of a fork PR under
646
657
  * review. A tracked branch pulls from its own upstream.
647
658
  */
648
- async pull(cwd: string, remote = 'origin', branch?: string, rebase = false): Promise<{ success: boolean; message: string }> {
659
+ async pull(cwd: string, remote = 'origin', branch?: string, rebase = false, identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
649
660
  const args = ['pull'];
650
661
  if (rebase) args.push('--rebase');
651
662
 
@@ -659,7 +670,9 @@ export class GitService {
659
670
  }
660
671
  }
661
672
 
662
- const result = await execGit(args, cwd, 60000);
673
+ // A pull can create a merge commit, so it needs both halves of the
674
+ // identity: the credential to fetch, the name to author the merge.
675
+ const result = await execGit(args, cwd, { timeout: 60000, env: identityEnv });
663
676
  return {
664
677
  success: result.exitCode === 0,
665
678
  message: result.exitCode === 0 ? result.stdout : result.stderr
@@ -794,7 +807,8 @@ export class GitService {
794
807
  remote = 'origin',
795
808
  branch?: string,
796
809
  force = false,
797
- options: { useUpstream?: boolean } = {}
810
+ options: { useUpstream?: boolean } = {},
811
+ identityEnv: GitIdentityEnv = {}
798
812
  ): Promise<{ success: boolean; message: string }> {
799
813
  const { useUpstream = true } = options;
800
814
  const target = await this.getPushTarget(cwd, branch);
@@ -802,7 +816,7 @@ export class GitService {
802
816
  if (useUpstream && target.hasUpstream) {
803
817
  const args = ['push'];
804
818
  if (force) args.push('--force-with-lease');
805
- return this.describePushResult(cwd, await execGit(args, cwd, 60000));
819
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
806
820
  }
807
821
 
808
822
  assertSafeGitRemoteName(remote);
@@ -815,7 +829,7 @@ export class GitService {
815
829
  // Only safe here: the branch tracks nothing, so there is no upstream to
816
830
  // overwrite and recording one is the point of a first push.
817
831
  args.push('-u');
818
- return this.describePushResult(cwd, await execGit(args, cwd, 60000));
832
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
819
833
  }
820
834
 
821
835
  /** Point a branch at a different upstream — the way back from a wrong push. */
@@ -857,7 +871,8 @@ export class GitService {
857
871
  cwd: string,
858
872
  mode: 'with-tags' | 'all-tags' | 'force-lease' | 'force',
859
873
  remote = 'origin',
860
- branch?: string
874
+ branch?: string,
875
+ identityEnv: GitIdentityEnv = {}
861
876
  ): Promise<{ success: boolean; message: string }> {
862
877
  // `--tags` is about the tag namespace, not this branch, so it always needs
863
878
  // an explicit remote.
@@ -865,7 +880,7 @@ export class GitService {
865
880
  assertSafeGitRemoteName(remote);
866
881
  return this.describePushResult(
867
882
  cwd,
868
- await execGit(['push', remote, '--tags'], cwd, 60000)
883
+ await execGit(['push', remote, '--tags'], cwd, { timeout: 60000, env: identityEnv })
869
884
  );
870
885
  }
871
886
 
@@ -879,7 +894,7 @@ export class GitService {
879
894
  // Same rule as `push`: a tracked branch goes where git says it goes.
880
895
  const target = await this.getPushTarget(cwd, branch);
881
896
  if (target.hasUpstream) {
882
- return this.describePushResult(cwd, await execGit(['push', flag], cwd, 60000));
897
+ return this.describePushResult(cwd, await execGit(['push', flag], cwd, { timeout: 60000, env: identityEnv }));
883
898
  }
884
899
 
885
900
  assertSafeGitRemoteName(remote);
@@ -889,12 +904,12 @@ export class GitService {
889
904
  args.push(branch);
890
905
  }
891
906
  args.push(flag, '-u');
892
- return this.describePushResult(cwd, await execGit(args, cwd, 60000));
907
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
893
908
  }
894
909
 
895
910
  /** Fetch every configured remote and prune deleted remote-tracking refs. */
896
- async fetchAll(cwd: string): Promise<string> {
897
- const result = await execGit(['fetch', '--all', '--prune', '--tags'], cwd, 60000);
911
+ async fetchAll(cwd: string, identityEnv: GitIdentityEnv = {}): Promise<string> {
912
+ const result = await execGit(['fetch', '--all', '--prune', '--tags'], cwd, { timeout: 60000, env: identityEnv });
898
913
  if (result.exitCode !== 0) {
899
914
  throw new Error(`git fetch --all failed: ${result.stderr}`);
900
915
  }
@@ -950,7 +965,7 @@ export class GitService {
950
965
  return parseStashList(result.stdout);
951
966
  }
952
967
 
953
- async stashSave(cwd: string, message?: string, stagedOnly = false): Promise<void> {
968
+ async stashSave(cwd: string, message?: string, stagedOnly = false, identityEnv: GitIdentityEnv = {}): Promise<void> {
954
969
  const args = ['stash', 'push'];
955
970
  // `--staged` stashes exactly the index (works at hunk level, so partially
956
971
  // staged files are handled precisely). Requires Git >= 2.35.
@@ -959,7 +974,7 @@ export class GitService {
959
974
  assertSafeGitCommitMessage(message);
960
975
  args.push('-m', message);
961
976
  }
962
- const result = await execGit(args, cwd);
977
+ const result = await execGit(args, cwd, { env: identityEnv });
963
978
  if (result.exitCode !== 0) {
964
979
  // Git < 2.35 doesn't know `--staged`; surface an actionable message
965
980
  // instead of the raw "unknown option" / "usage:" noise.
@@ -1073,7 +1088,7 @@ export class GitService {
1073
1088
  return tags;
1074
1089
  }
1075
1090
 
1076
- async createTag(cwd: string, name: string, message?: string, commitHash?: string): Promise<void> {
1091
+ async createTag(cwd: string, name: string, message?: string, commitHash?: string, identityEnv: GitIdentityEnv = {}): Promise<void> {
1077
1092
  assertSafeGitRevish(name, 'tag name');
1078
1093
  const args = ['tag'];
1079
1094
  if (message) {
@@ -1086,7 +1101,7 @@ export class GitService {
1086
1101
  assertSafeGitRevish(commitHash, 'tag target');
1087
1102
  args.push(commitHash);
1088
1103
  }
1089
- const result = await execGit(args, cwd);
1104
+ const result = await execGit(args, cwd, { env: identityEnv });
1090
1105
  if (result.exitCode !== 0) {
1091
1106
  throw new Error(`git tag failed: ${result.stderr}`);
1092
1107
  }
@@ -1100,10 +1115,10 @@ export class GitService {
1100
1115
  }
1101
1116
  }
1102
1117
 
1103
- async pushTag(cwd: string, name: string, remote = 'origin'): Promise<{ success: boolean; message: string }> {
1118
+ async pushTag(cwd: string, name: string, remote = 'origin', identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1104
1119
  assertSafeGitRemoteName(remote);
1105
1120
  assertSafeGitRevish(name, 'tag name');
1106
- const result = await execGit(['push', remote, name], cwd, 60000);
1121
+ const result = await execGit(['push', remote, name], cwd, { timeout: 60000, env: identityEnv });
1107
1122
  return {
1108
1123
  success: result.exitCode === 0,
1109
1124
  message: result.exitCode === 0 ? (result.stderr || result.stdout) : result.stderr
@@ -1422,7 +1437,7 @@ export class GitService {
1422
1437
  * on failure, because the common failures here are instructions rather than
1423
1438
  * errors — "nothing to commit, use --skip" is something the user must read.
1424
1439
  */
1425
- async continueOperation(cwd: string): Promise<{ success: boolean; message: string }> {
1440
+ async continueOperation(cwd: string, identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1426
1441
  const operation = await this.detectGitOperation(cwd);
1427
1442
  const unmerged = await this.getUnmergedPaths(cwd);
1428
1443
  if (unmerged.length > 0) {
@@ -1449,7 +1464,7 @@ export class GitService {
1449
1464
  throw new Error('There is no operation to continue.');
1450
1465
  }
1451
1466
 
1452
- const result = await execGit(args, cwd, 120000);
1467
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
1453
1468
  return {
1454
1469
  success: result.exitCode === 0,
1455
1470
  message: (result.exitCode === 0 ? result.stdout : result.stderr).trim()
@@ -1457,7 +1472,7 @@ export class GitService {
1457
1472
  }
1458
1473
 
1459
1474
  /** Drop the commit git is currently stuck on and move to the next one. */
1460
- async skipOperation(cwd: string): Promise<{ success: boolean; message: string }> {
1475
+ async skipOperation(cwd: string, identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1461
1476
  const operation = await this.detectGitOperation(cwd);
1462
1477
  let args: string[];
1463
1478
  switch (operation) {
@@ -1474,7 +1489,7 @@ export class GitService {
1474
1489
  throw new Error('This operation cannot be skipped.');
1475
1490
  }
1476
1491
 
1477
- const result = await execGit(args, cwd, 120000);
1492
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
1478
1493
  return {
1479
1494
  success: result.exitCode === 0,
1480
1495
  message: (result.exitCode === 0 ? result.stdout : result.stderr).trim()
@@ -1531,14 +1546,15 @@ export class GitService {
1531
1546
  async rebaseOnto(
1532
1547
  cwd: string,
1533
1548
  upstream: string,
1534
- autostash = true
1549
+ autostash = true,
1550
+ identityEnv: GitIdentityEnv = {}
1535
1551
  ): Promise<{ success: boolean; hasConflicts: boolean; message: string }> {
1536
1552
  assertSafeGitRevish(upstream, 'rebase upstream');
1537
1553
  const args = ['rebase'];
1538
1554
  if (autostash) args.push('--autostash');
1539
1555
  args.push(upstream);
1540
1556
 
1541
- const result = await execGit(args, cwd, 120000);
1557
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
1542
1558
  const combined = `${result.stdout}\n${result.stderr}`;
1543
1559
  const hasConflicts = /CONFLICT \(/.test(combined) || /could not apply/i.test(combined);
1544
1560
  if (result.exitCode !== 0 && !hasConflicts) {
@@ -1644,9 +1660,9 @@ export class GitService {
1644
1660
  }
1645
1661
 
1646
1662
  /** Create a new commit that reverses a previous one (default: HEAD). */
1647
- async revertCommit(cwd: string, ref = 'HEAD'): Promise<{ success: boolean; message: string }> {
1663
+ async revertCommit(cwd: string, ref = 'HEAD', identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1648
1664
  assertSafeGitRevish(ref, 'revert ref');
1649
- const result = await execGit(['revert', '--no-edit', ref], cwd);
1665
+ const result = await execGit(['revert', '--no-edit', ref], cwd, { env: identityEnv });
1650
1666
  if (result.exitCode !== 0 && !(await this.hasCommits(cwd))) {
1651
1667
  // Unborn HEAD — git only reports `bad revision 'HEAD'`.
1652
1668
  return { success: false, message: 'This repository has no commits yet, so there is nothing to revert.' };
@@ -1658,14 +1674,14 @@ export class GitService {
1658
1674
  }
1659
1675
 
1660
1676
  /** Cherry-pick one or more commits onto the current branch (`git cherry-pick <hash>...`). */
1661
- async cherryPick(cwd: string, refs: string[]): Promise<{ success: boolean; message: string }> {
1677
+ async cherryPick(cwd: string, refs: string[], identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1662
1678
  if (refs.length === 0) {
1663
1679
  return { success: false, message: 'No commits provided' };
1664
1680
  }
1665
1681
  for (const ref of refs) {
1666
1682
  assertSafeGitRevish(ref, 'cherry-pick ref');
1667
1683
  }
1668
- const result = await execGit(['cherry-pick', ...refs], cwd);
1684
+ const result = await execGit(['cherry-pick', ...refs], cwd, { env: identityEnv });
1669
1685
  return {
1670
1686
  success: result.exitCode === 0,
1671
1687
  message: result.exitCode === 0 ? (result.stdout || result.stderr || 'Cherry-pick succeeded') : result.stderr
@@ -1705,17 +1721,21 @@ export class GitService {
1705
1721
  */
1706
1722
  async npmVersion(
1707
1723
  cwd: string,
1708
- bump: 'patch' | 'minor' | 'major'
1724
+ bump: 'patch' | 'minor' | 'major',
1725
+ identityEnv: GitIdentityEnv = {}
1709
1726
  ): Promise<{ success: boolean; version: string; message: string }> {
1710
1727
  const npmPath = resolveBinary('npm');
1711
1728
  if (!npmPath) {
1712
1729
  throw new Error('npm binary not found on PATH');
1713
1730
  }
1731
+ // npm runs git itself for the bump commit and tag, so the identity has to
1732
+ // travel in the environment — there is no `execGit` call here to attach it
1733
+ // to, and this is precisely why the mechanism is environment-based.
1714
1734
  const proc = Bun.spawn([npmPath, 'version', bump], {
1715
1735
  cwd,
1716
1736
  stdout: 'pipe',
1717
1737
  stderr: 'pipe',
1718
- env: { ...getCleanSpawnEnv() }
1738
+ env: { ...getCleanSpawnEnv(), ...identityEnv }
1719
1739
  });
1720
1740
  const [stdout, stderr] = await Promise.all([
1721
1741
  new Response(proc.stdout).text(),
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The helper's input parsing, which authentication depends on.
3
+ *
4
+ * Git speaks a line protocol on stdin and reads the answer on stdout, so a
5
+ * mis-parse does not fail loudly — it produces a helper that silently answers
6
+ * nothing, and a push that asks for a password nobody typed.
7
+ */
8
+
9
+ import { describe, expect, test } from 'bun:test';
10
+ import { identityIdFrom, parseCredentialRequest } from './cli';
11
+
12
+ describe('parseCredentialRequest', () => {
13
+ test('reads the key=value lines git sends', () => {
14
+ expect(
15
+ parseCredentialRequest('protocol=https\nhost=github.com\npath=owner/repo.git\n\n')
16
+ ).toEqual({
17
+ protocol: 'https',
18
+ host: 'github.com',
19
+ path: 'owner/repo.git'
20
+ });
21
+ });
22
+
23
+ test('keeps a value containing "=" intact', () => {
24
+ // Only the FIRST `=` separates; a token or query string would otherwise
25
+ // arrive truncated at its first equals sign.
26
+ expect(parseCredentialRequest('password=abc=def=ghi\n')).toEqual({
27
+ password: 'abc=def=ghi'
28
+ });
29
+ });
30
+
31
+ test('ignores blank lines and malformed rows rather than failing', () => {
32
+ expect(parseCredentialRequest('\nhost=github.com\n\n=novalue\ngarbage\n')).toEqual({
33
+ host: 'github.com'
34
+ });
35
+ });
36
+
37
+ test('an empty value is a value, not a missing key', () => {
38
+ expect(parseCredentialRequest('username=\n')).toEqual({ username: '' });
39
+ });
40
+
41
+ test('empty input yields no fields', () => {
42
+ expect(parseCredentialRequest('')).toEqual({});
43
+ });
44
+ });
45
+
46
+ describe('identityIdFrom', () => {
47
+ test('finds the flag among git-appended arguments', () => {
48
+ // Git appends the operation after our own arguments.
49
+ expect(identityIdFrom(['--identity=abc-123', 'get'])).toBe('abc-123');
50
+ expect(identityIdFrom(['get', '--identity=abc-123'])).toBe('abc-123');
51
+ });
52
+
53
+ test('a missing or empty flag yields null, so the helper declines', () => {
54
+ expect(identityIdFrom(['get'])).toBeNull();
55
+ expect(identityIdFrom(['--identity=', 'get'])).toBeNull();
56
+ expect(identityIdFrom([])).toBeNull();
57
+ });
58
+ });
@@ -0,0 +1,201 @@
1
+ /**
2
+ * The two helper subcommands git invokes: `git-credential` and `git-askpass`.
3
+ *
4
+ * Both exist for one reason: A SECRET MUST NOT TRAVEL THROUGH ARGV OR THE
5
+ * ENVIRONMENT. `ps` shows another user on the same machine every argument of
6
+ * every running process, and the alternatives git offers all leak:
7
+ * `http.extraheader` puts the token in the command line, `credential.helper
8
+ * store` writes it to a plaintext file, and a token embedded in a remote URL
9
+ * persists in `.git/config`. A helper receives its question on stdin and
10
+ * answers on stdout, which no other process can read.
11
+ *
12
+ * ── STDOUT IS THE PROTOCOL ──
13
+ * Git parses this process's stdout. Anything else written there — a debug line,
14
+ * a warning, a stray `console.log` from a module loaded on the way in — is read
15
+ * as part of the answer and corrupts it. So the first thing either entry point
16
+ * does is move `console.log` to stderr. That is not tidiness; it is what keeps
17
+ * an unrelated log statement from breaking authentication.
18
+ *
19
+ * These run in a SHORT-LIVED SEPARATE PROCESS. Git spawns them, they answer,
20
+ * they exit. They open the database directly and start no server.
21
+ */
22
+
23
+ /**
24
+ * Silence routine logging for the rest of this process.
25
+ *
26
+ * `debug.log` writes through `console.log`, which is stdout — the protocol
27
+ * channel. Redirecting it to stderr protects the protocol but then prints
28
+ * "Connected to database" into the middle of the user's `git push` output,
29
+ * which is noise they can neither act on nor turn off. So routine logs are
30
+ * dropped entirely; a genuine helper failure still goes to stderr through
31
+ * `console.error`, which git shows and which is worth showing.
32
+ */
33
+ function protectStdout(): void {
34
+ const drop = () => {};
35
+ console.log = drop;
36
+ console.info = drop;
37
+ console.debug = drop;
38
+ }
39
+
40
+ /** `--identity=<id>` out of the helper's own arguments. */
41
+ export function identityIdFrom(argv: string[]): string | null {
42
+ for (const arg of argv) {
43
+ if (arg.startsWith('--identity=')) {
44
+ const value = arg.slice('--identity='.length).trim();
45
+ if (value) return value;
46
+ }
47
+ }
48
+ return null;
49
+ }
50
+
51
+ /**
52
+ * Open the existing database, without migrating or seeding it.
53
+ *
54
+ * `initializeDatabase()` would run migrations and seeders — the right thing for
55
+ * a server starting up, the wrong thing for a helper git spawned mid-push. It
56
+ * would race the running server's schema and could apply a migration from a
57
+ * process nobody is watching. A helper only ever reads one row.
58
+ */
59
+ async function connectReadOnly(): Promise<void> {
60
+ const { connectExistingDatabase } = await import('$backend/database');
61
+ await connectExistingDatabase();
62
+ }
63
+
64
+ /** Read stdin to the end. Empty string when nothing is piped. */
65
+ async function readStdin(): Promise<string> {
66
+ try {
67
+ return await new Response(Bun.stdin.stream()).text();
68
+ } catch {
69
+ return '';
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Parse git's credential description: `key=value` lines, blank line terminated.
75
+ *
76
+ * Unknown keys are kept — git adds fields over time, and one we do not
77
+ * recognise is not a reason to fail an authentication.
78
+ */
79
+ export function parseCredentialRequest(input: string): Record<string, string> {
80
+ const fields: Record<string, string> = {};
81
+ for (const line of input.split('\n')) {
82
+ const trimmed = line.trim();
83
+ if (!trimmed) continue;
84
+ const eq = trimmed.indexOf('=');
85
+ if (eq <= 0) continue;
86
+ fields[trimmed.slice(0, eq)] = trimmed.slice(eq + 1);
87
+ }
88
+ return fields;
89
+ }
90
+
91
+ /**
92
+ * Answer a `git credential` request.
93
+ *
94
+ * Only `get` produces output. `store` and `erase` are accepted and ignored on
95
+ * purpose: the credential lives in Clopen's database, and letting git overwrite
96
+ * or delete it would put git's cache in charge of a user's stored account.
97
+ * Exiting 0 without output tells git "no opinion", which is the correct answer
98
+ * for a read-only helper.
99
+ */
100
+ async function runCredentialHelper(argv: string[]): Promise<number> {
101
+ const operation = argv.find((a) => !a.startsWith('--')) ?? 'get';
102
+ if (operation !== 'get') return 0;
103
+
104
+ const identityId = identityIdFrom(argv);
105
+ if (!identityId) return 0;
106
+
107
+ const request = parseCredentialRequest(await readStdin());
108
+
109
+ // Imported here, after stdout is protected, and lazily so `store`/`erase`
110
+ // never pay for opening the database.
111
+ await connectReadOnly();
112
+ const { gitIdentityQueries, integrationAccountQueries, parseHosts } = await import(
113
+ '$backend/database/queries'
114
+ );
115
+
116
+ const row = gitIdentityQueries.getById(identityId);
117
+ if (!row) return 0;
118
+
119
+ // The host git is asking about must be one this identity claims. Without the
120
+ // check, a repository whose remote was changed to another host would be
121
+ // handed this account's token.
122
+ const host = (request.host ?? '').toLowerCase().split(':')[0] ?? '';
123
+ if (host && !parseHosts(row.hosts).includes(host)) return 0;
124
+
125
+ let token: string | null = null;
126
+ if (row.auth_method === 'https-token') {
127
+ token = row.https_token;
128
+ } else if (row.auth_method === 'https-account' && row.integration_account_id) {
129
+ // Borrowed from a connected integration account, so rotating the token in
130
+ // one place is enough.
131
+ const account = integrationAccountQueries.getById(row.integration_account_id);
132
+ if (account) {
133
+ const credentials = integrationAccountQueries.credentialsOf(account);
134
+ token = credentials.token ?? credentials.apiKey ?? null;
135
+ }
136
+ }
137
+ if (!token) return 0;
138
+
139
+ // GitHub and friends accept any non-empty username alongside a token, but it
140
+ // must not be blank, so fall back to the conventional placeholder.
141
+ const username = row.https_username || request.username || 'x-access-token';
142
+ process.stdout.write(`username=${username}\npassword=${token}\n`);
143
+ return 0;
144
+ }
145
+
146
+ /**
147
+ * Answer `ssh`'s passphrase prompt.
148
+ *
149
+ * `ssh` calls SSH_ASKPASS with the prompt text as an argument and reads the
150
+ * answer from stdout. Only passphrase prompts are answered: a host-key
151
+ * confirmation ("Are you sure you want to continue connecting?") reaching this
152
+ * helper must not be auto-accepted, because that is the check that detects a
153
+ * man-in-the-middle.
154
+ */
155
+ async function runAskpass(argv: string[]): Promise<number> {
156
+ const identityId = identityIdFrom(argv);
157
+ if (!identityId) return 1;
158
+
159
+ const prompt = argv.filter((a) => !a.startsWith('--') && a !== 'git-askpass').join(' ');
160
+ if (prompt && !/passphrase|password/i.test(prompt)) {
161
+ // Declining leaves ssh to fail the way it would without us, which is the
162
+ // safe outcome for anything that is not a passphrase question.
163
+ return 1;
164
+ }
165
+
166
+ await connectReadOnly();
167
+ const { gitIdentityQueries } = await import('$backend/database/queries');
168
+
169
+ const row = gitIdentityQueries.getById(identityId);
170
+ if (!row?.ssh_passphrase) return 1;
171
+
172
+ process.stdout.write(`${row.ssh_passphrase}\n`);
173
+ return 0;
174
+ }
175
+
176
+ /** The subcommands this module owns. */
177
+ export const GIT_HELPER_COMMANDS = ['git-credential', 'git-askpass'] as const;
178
+
179
+ /**
180
+ * Handle a helper subcommand if this invocation is one.
181
+ *
182
+ * Returns the exit code to use, or `null` when the arguments are not a helper
183
+ * call and the CLI should carry on to its normal startup.
184
+ */
185
+ export async function runGitHelper(argv: string[]): Promise<number | null> {
186
+ const command = argv[0];
187
+ if (command !== 'git-credential' && command !== 'git-askpass') return null;
188
+
189
+ protectStdout();
190
+
191
+ try {
192
+ return command === 'git-credential'
193
+ ? await runCredentialHelper(argv.slice(1))
194
+ : await runAskpass(argv.slice(1));
195
+ } catch (error) {
196
+ // Never print the failure to stdout, and never expose the reason to git —
197
+ // an empty answer means "no credential", which is what a failure is.
198
+ console.error('[clopen] git helper failed:', error);
199
+ return command === 'git-credential' ? 0 : 1;
200
+ }
201
+ }