@myrialabs/clopen 0.4.40 → 0.4.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +1 -1
- package/backend/artifacts/detect.ts +15 -3
- package/backend/artifacts/generate.ts +2 -2
- package/backend/artifacts/index.ts +12 -4
- package/backend/artifacts/markers.ts +24 -1
- package/backend/artifacts/matrix.ts +47 -3
- package/backend/artifacts/sync.test.ts +3 -3
- package/backend/artifacts/sync.ts +8 -20
- package/backend/artifacts/types.ts +9 -3
- package/backend/auth/permissions.ts +6 -11
- package/backend/auth/session-cleanup.ts +10 -1
- package/backend/auth/tokens.ts +9 -1
- package/backend/chat/stream-manager.ts +50 -0
- package/backend/database/crypto/secret-columns.ts +5 -1
- package/backend/database/index.ts +18 -0
- package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
- package/backend/database/migrations/080_create_file_shares.ts +111 -0
- package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
- package/backend/database/migrations/082_create_git_identities.test.ts +186 -0
- package/backend/database/migrations/082_create_git_identities.ts +122 -0
- package/backend/database/migrations/index.ts +28 -0
- package/backend/database/queries/file-share-queries.ts +163 -0
- package/backend/database/queries/git-identity-queries.ts +290 -0
- package/backend/database/queries/index.ts +8 -4
- package/backend/database/queries/profile-queries.ts +5 -3
- package/backend/database/queries/push-subscription-queries.test.ts +90 -0
- package/backend/database/queries/push-subscription-queries.ts +99 -0
- package/backend/database/queries/skill-queries.ts +96 -18
- package/backend/engine/adapters/claude/environment.ts +11 -1
- package/backend/engine/adapters/claude/stream.ts +3 -2
- package/backend/engine/adapters/cline/stream.ts +3 -3
- package/backend/engine/adapters/codex/stream.ts +38 -6
- package/backend/engine/adapters/copilot/stream.ts +3 -3
- package/backend/engine/adapters/cursor/stream.ts +25 -3
- package/backend/engine/adapters/opencode/server.ts +26 -2
- package/backend/engine/adapters/opencode/stream.ts +8 -7
- package/backend/engine/adapters/pi/stream.ts +2 -2
- package/backend/engine/adapters/qwen/stream.ts +5 -3
- package/backend/engine/artifact-sync.ts +26 -20
- package/backend/engine/docs/artifacts.md +81 -22
- package/backend/engine/docs/quick-reference.md +2 -1
- package/backend/engine/resolve-model.test.ts +108 -0
- package/backend/engine/resolve-model.ts +53 -10
- package/backend/engine/structured-helpers.ts +22 -0
- package/backend/engine/types.ts +10 -0
- package/backend/files/file-shares.ts +369 -0
- package/backend/files/path-browsing.ts +27 -21
- package/backend/git/git-executor.ts +28 -2
- package/backend/git/git-service.ts +59 -40
- package/backend/git/identity/cli.test.ts +58 -0
- package/backend/git/identity/cli.ts +201 -0
- package/backend/git/identity/credential-helper.test.ts +242 -0
- package/backend/git/identity/env.test.ts +214 -0
- package/backend/git/identity/env.ts +193 -0
- package/backend/git/identity/import-local.test.ts +199 -0
- package/backend/git/identity/import-local.ts +141 -0
- package/backend/git/identity/index.ts +78 -0
- package/backend/git/identity/keys.ts +183 -0
- package/backend/git/identity/resolve.ts +140 -0
- package/backend/git/identity/scope-config.test.ts +145 -0
- package/backend/git/identity/scope-config.ts +175 -0
- package/backend/git/identity/service.ts +297 -0
- package/backend/http/files-shared.test.ts +505 -0
- package/backend/http/files-shared.ts +351 -0
- package/backend/http/push.ts +150 -0
- package/backend/index.ts +24 -0
- package/backend/instructions/index.ts +1 -1
- package/backend/instructions/sync.ts +30 -6
- package/backend/memory/compose.ts +2 -2
- package/backend/memory/consolidate.ts +2 -2
- package/backend/memory/extract/episodic.ts +2 -2
- package/backend/memory/judge.ts +2 -2
- package/backend/preview/browser/browser-console-manager.ts +214 -34
- package/backend/preview/browser/browser-pool.ts +526 -123
- package/backend/preview/browser/browser-preview-service.ts +192 -8
- package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
- package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
- package/backend/preview/browser/browser-tab-manager.ts +291 -65
- package/backend/preview/browser/capture-profile.ts +15 -1
- package/backend/preview/browser/types.ts +26 -1
- package/backend/profiles/service.ts +7 -6
- package/backend/push/sender.ts +172 -0
- package/backend/push/tags.ts +25 -0
- package/backend/push/vapid-keys.ts +77 -0
- package/backend/push/webpush-crypto.test.ts +200 -0
- package/backend/push/webpush-crypto.ts +231 -0
- package/backend/skills/detect.ts +28 -0
- package/backend/skills/index.ts +22 -4
- package/backend/skills/invoke.test.ts +114 -0
- package/backend/skills/invoke.ts +222 -0
- package/backend/skills/service.ts +194 -44
- package/backend/skills/spec.ts +35 -0
- package/backend/skills/sync.ts +85 -55
- package/backend/subagents/detect.ts +2 -3
- package/backend/subagents/sync.ts +15 -8
- package/backend/terminal/ptykit.ts +24 -0
- package/backend/work/pull-requests.ts +2 -2
- package/backend/ws/chat/stream.ts +100 -8
- package/backend/ws/files/index.ts +4 -0
- package/backend/ws/files/share.ts +95 -0
- package/backend/ws/git/branch-name.ts +2 -2
- package/backend/ws/git/branch.ts +17 -6
- package/backend/ws/git/commit-message.ts +2 -2
- package/backend/ws/git/commit.ts +6 -5
- package/backend/ws/git/conflict.ts +3 -2
- package/backend/ws/git/identity-context.ts +91 -0
- package/backend/ws/git/identity.ts +200 -0
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/git/remote.ts +57 -11
- package/backend/ws/index.ts +3 -4
- package/backend/ws/preview/browser/data.ts +60 -0
- package/backend/ws/preview/browser/interact.ts +6 -0
- package/backend/ws/preview/browser/tab-info.ts +9 -1
- package/backend/ws/preview/browser/tab.ts +64 -8
- package/backend/ws/preview/index.ts +21 -0
- package/backend/ws/profiles/crud.ts +2 -3
- package/backend/ws/skills/catalog.ts +5 -1
- package/backend/ws/skills/crud.ts +128 -22
- package/backend/ws/skills/index.ts +4 -1
- package/backend/ws/user/crud.ts +12 -3
- package/bin/clopen.ts +9 -0
- package/dist/assets/{index-D4igjF6e.js → index-BynqyvF4.js} +1 -1
- package/dist/assets/{index-DONNwiXm.js → index-DLoJsmNQ.js} +1 -1
- package/dist/assets/{main-BrfXH1bL.js → main-CUyZAmqt.js} +601 -592
- package/dist/assets/main-DVCW3cfr.css +1 -0
- package/dist/index.html +7 -2
- package/dist/sw.js +112 -0
- package/package.json +2 -2
- package/shared/constants/engine-tools.ts +31 -6
- package/shared/constants/notification-messages.ts +142 -0
- package/shared/types/git-identity.ts +112 -0
- package/shared/types/unified/stream.ts +7 -0
- package/backend/commands/detect.ts +0 -25
- package/backend/commands/index.ts +0 -9
- package/backend/commands/service.ts +0 -178
- package/backend/commands/store.ts +0 -45
- package/backend/commands/sync.ts +0 -94
- package/backend/database/queries/command-queries.ts +0 -82
- package/backend/ws/commands/crud.ts +0 -157
- package/backend/ws/commands/index.ts +0 -8
- package/dist/assets/main-CT1PygsW.css +0 -1
|
@@ -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
|
+
});
|
|
@@ -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
|
+
}
|