@playcraft/cli 0.1.0 → 0.1.2
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/README.md +14 -2
- package/dist/utils/agent-api-client.js +50 -7
- package/dist/utils/tool-operation-journal.js +82 -16
- package/dist/workspace-runtime/codex/app-server.js +109 -51
- package/dist/workspace-runtime/codex/launcher-client.js +155 -0
- package/dist/workspace-runtime/codex/loopback.js +32 -2
- package/dist/workspace-runtime/codex/model-broker.js +183 -0
- package/dist/workspace-runtime/codex/native-adapter.js +3 -0
- package/dist/workspace-runtime/serve.js +23 -7
- package/dist/workspace-runtime/server/dispatch.js +15 -4
- package/dist/workspace-runtime/server/http.js +67 -4
- package/dist/workspace-runtime/workspaces/git-credential-broker.js +276 -0
- package/dist/workspace-runtime/workspaces/git-credential-helper.js +66 -0
- package/dist/workspace-runtime/workspaces/git-direct-store.js +154 -0
- package/dist/workspace-runtime/workspaces/git.js +16 -3
- package/dist/workspace-runtime/workspaces/prepare.js +29 -172
- package/dist/workspace-runtime/workspaces/registry.js +12 -2
- package/package.json +4 -4
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { chmod, chown, lstat, unlink, open, mkdir, mkdtemp, writeFile, readFile, rename, rm } from 'node:fs/promises';
|
|
4
|
+
import { constants } from 'node:fs';
|
|
5
|
+
import { createServer } from 'node:http';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { promisify } from 'node:util';
|
|
9
|
+
import { isLocalWorkspaceGitAuthMode, isLocalWorkspaceGitEnvironment, matchWorkspaceGitGatewayCloneUrl, workspacePreparationSchema } from '@playcraft/common/cloud-workspace/runtime';
|
|
10
|
+
import { WorkspaceGitDirectStore } from './git-direct-store.js';
|
|
11
|
+
const exec = promisify(execFile);
|
|
12
|
+
/** Only this control process sees the callback credential. Development processes use the local socket. */
|
|
13
|
+
export class WorkspaceGitCredentialBroker {
|
|
14
|
+
state;
|
|
15
|
+
socketPath;
|
|
16
|
+
server;
|
|
17
|
+
closed = false;
|
|
18
|
+
ready = false;
|
|
19
|
+
cache = new Map();
|
|
20
|
+
pending = new Map();
|
|
21
|
+
direct;
|
|
22
|
+
constructor(state) {
|
|
23
|
+
this.state = state;
|
|
24
|
+
this.direct = new WorkspaceGitDirectStore(state);
|
|
25
|
+
const id = createHash('sha256').update(state.config.stateDir).digest('hex').slice(0, 24);
|
|
26
|
+
this.socketPath = `/tmp/playcraft-git-${id}.sock`;
|
|
27
|
+
}
|
|
28
|
+
async start() {
|
|
29
|
+
await this.direct.sweep(this.state.journal.destroyed());
|
|
30
|
+
const old = await lstat(this.socketPath).catch(error => {
|
|
31
|
+
if (error.code !== 'ENOENT')
|
|
32
|
+
throw error;
|
|
33
|
+
return undefined;
|
|
34
|
+
});
|
|
35
|
+
if (old) {
|
|
36
|
+
if (!old.isSocket() || old.uid !== process.getuid?.())
|
|
37
|
+
throw new Error('git_broker_socket_conflict');
|
|
38
|
+
await unlink(this.socketPath);
|
|
39
|
+
}
|
|
40
|
+
const server = this.server = createServer({ maxHeaderSize: 2048, requestTimeout: 10_000 }, async (request, response) => {
|
|
41
|
+
try {
|
|
42
|
+
if (request.method !== 'POST' || request.url !== '/credential')
|
|
43
|
+
throw new Error();
|
|
44
|
+
const chunks = [];
|
|
45
|
+
let size = 0;
|
|
46
|
+
for await (const chunk of request) {
|
|
47
|
+
size += chunk.length;
|
|
48
|
+
if (size > 16_384)
|
|
49
|
+
throw new Error();
|
|
50
|
+
chunks.push(Buffer.from(chunk));
|
|
51
|
+
}
|
|
52
|
+
const result = await this.credential(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
53
|
+
response.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
54
|
+
response.end(JSON.stringify(result));
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
response.writeHead(403, { 'cache-control': 'no-store', connection: 'close' });
|
|
58
|
+
response.end();
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
server.maxConnections = 32;
|
|
62
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(this.socketPath, resolve); });
|
|
63
|
+
// The workspace group is the image's development group; other system users cannot connect.
|
|
64
|
+
const directory = await lstat(this.state.config.workspaceRoot);
|
|
65
|
+
await chown(this.socketPath, process.getuid(), directory.gid);
|
|
66
|
+
await chmod(this.socketPath, 0o660);
|
|
67
|
+
this.ready = true;
|
|
68
|
+
}
|
|
69
|
+
async close() {
|
|
70
|
+
this.closed = true;
|
|
71
|
+
this.cache.clear();
|
|
72
|
+
if (this.server?.listening) {
|
|
73
|
+
this.server.closeAllConnections();
|
|
74
|
+
await new Promise(resolve => this.server.close(() => resolve()));
|
|
75
|
+
await unlink(this.socketPath).catch(() => undefined);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async configure(binding, preparation) {
|
|
79
|
+
preparation = workspacePreparationSchema.parse(preparation);
|
|
80
|
+
const transport = preparation.transport;
|
|
81
|
+
const isDirect = isLocalWorkspaceGitAuthMode(preparation.authMode);
|
|
82
|
+
if (!isDirect && transport?.kind !== 'git-gateway-v2')
|
|
83
|
+
return;
|
|
84
|
+
if (isDirect) {
|
|
85
|
+
if (!isLocalWorkspaceGitEnvironment(this.state.config.environment) || (preparation.directAccess && preparation.directAccess.repositoryUrl !== binding.repositoryUrl))
|
|
86
|
+
throw new Error('git_access_denied');
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
const matched = matchWorkspaceGitGatewayCloneUrl(transport.cloneUrl, this.state.config.gitGatewayOrigins, binding.repositoryUrl);
|
|
90
|
+
if (!matched.ok || matched.requestId !== `v2/${binding.workspaceId}`)
|
|
91
|
+
throw new Error('workspace_git_gateway_unavailable');
|
|
92
|
+
}
|
|
93
|
+
// Revocation and switching to gateway invalidate first; direct rotation keeps the old file until rename.
|
|
94
|
+
if (!isDirect)
|
|
95
|
+
await this.direct.remove(binding.workspaceId);
|
|
96
|
+
else if (preparation.directAccess === null)
|
|
97
|
+
await this.direct.put(binding, null);
|
|
98
|
+
this.cache.delete(binding.workspaceId);
|
|
99
|
+
const cloneUrl = isDirect ? binding.repositoryUrl : transport.cloneUrl;
|
|
100
|
+
const root = join(this.state.config.workspaceRoot, binding.workspaceId);
|
|
101
|
+
const helper = `!${quote(process.execPath)} ${quote(fileURLToPath(new URL('./git-credential-helper.js', import.meta.url)))} ${quote(this.socketPath)} ${quote(binding.workspaceId)}`;
|
|
102
|
+
await configureGitFile(root, this.state.config.stateDir, [
|
|
103
|
+
...(!isDirect ? [['--replace-all', `url.${cloneUrl}.insteadOf`, binding.repositoryUrl]] : []),
|
|
104
|
+
['--replace-all', `credential.${cloneUrl}.useHttpPath`, 'true'],
|
|
105
|
+
['--replace-all', `credential.${cloneUrl}.helper`, ''],
|
|
106
|
+
['--add', `credential.${cloneUrl}.helper`, helper],
|
|
107
|
+
['--replace-all', `http.${cloneUrl}.followRedirects`, 'false'],
|
|
108
|
+
['--replace-all', 'playcraft.gitAuthUrl', cloneUrl],
|
|
109
|
+
], binding.repositoryUrl);
|
|
110
|
+
if (isDirect)
|
|
111
|
+
await this.direct.put(binding, preparation.directAccess);
|
|
112
|
+
this.cache.delete(binding.workspaceId);
|
|
113
|
+
}
|
|
114
|
+
async credential(input) {
|
|
115
|
+
if (!this.ready || this.closed || this.state.journal.destroyed() || !input || !['get', 'erase'].includes(input.action)
|
|
116
|
+
|| typeof input.workspaceId !== 'string' || !/^[a-f0-9-]{36}$/.test(input.workspaceId)
|
|
117
|
+
|| !['http', 'https'].includes(input.protocol) || typeof input.host !== 'string'
|
|
118
|
+
|| typeof input.path !== 'string')
|
|
119
|
+
throw new Error('git_access_denied');
|
|
120
|
+
const binding = this.state.journal.getWorkspace(input.workspaceId);
|
|
121
|
+
if (!binding)
|
|
122
|
+
throw new Error('git_access_denied');
|
|
123
|
+
const cloneUrl = `${input.protocol}://${input.host}/${input.path}`;
|
|
124
|
+
const direct = await this.direct.get(binding);
|
|
125
|
+
if (direct) {
|
|
126
|
+
if (!direct.access || cloneUrl !== binding.repositoryUrl)
|
|
127
|
+
throw new Error('git_access_denied');
|
|
128
|
+
if (input.action === 'erase') {
|
|
129
|
+
if (input.password === direct.access.password)
|
|
130
|
+
await this.direct.put(binding, null, input.password);
|
|
131
|
+
return {};
|
|
132
|
+
}
|
|
133
|
+
return { username: direct.access.username, password: direct.access.password };
|
|
134
|
+
}
|
|
135
|
+
const matched = matchWorkspaceGitGatewayCloneUrl(cloneUrl, this.state.config.gitGatewayOrigins, binding.repositoryUrl);
|
|
136
|
+
if (!matched.ok || matched.requestId !== `v2/${binding.workspaceId}`)
|
|
137
|
+
throw new Error('git_access_denied');
|
|
138
|
+
if (input.action === 'erase') {
|
|
139
|
+
if (this.cache.get(input.workspaceId)?.preparation.gitAccess?.password === input.password)
|
|
140
|
+
this.cache.delete(input.workspaceId);
|
|
141
|
+
return {};
|
|
142
|
+
}
|
|
143
|
+
const key = JSON.stringify([binding, this.state.config.generation, this.state.runtimeEpoch]);
|
|
144
|
+
const cached = this.cache.get(input.workspaceId);
|
|
145
|
+
let preparation = cached?.key === key && Date.parse(cached.preparation.gitAccess.expiresAt) > Date.now() + 60_000
|
|
146
|
+
? cached.preparation : undefined;
|
|
147
|
+
if (!preparation) {
|
|
148
|
+
const pendingKey = `${input.workspaceId}:${key}`;
|
|
149
|
+
let pending = this.pending.get(pendingKey);
|
|
150
|
+
if (!pending) {
|
|
151
|
+
pending = this.refresh(binding, key).finally(() => this.pending.delete(pendingKey));
|
|
152
|
+
this.pending.set(pendingKey, pending);
|
|
153
|
+
}
|
|
154
|
+
preparation = await pending;
|
|
155
|
+
}
|
|
156
|
+
if (await this.direct.get(binding) || preparation.transport?.cloneUrl !== cloneUrl || !preparation.gitAccess)
|
|
157
|
+
throw new Error('git_access_denied');
|
|
158
|
+
return { username: preparation.gitAccess.username, password: preparation.gitAccess.password };
|
|
159
|
+
}
|
|
160
|
+
async destroy() {
|
|
161
|
+
await this.close();
|
|
162
|
+
await this.direct.sweep(true);
|
|
163
|
+
}
|
|
164
|
+
async refresh(binding, key) {
|
|
165
|
+
const endpoint = new URL('/runtime/internal/git-credentials', this.state.config.callbackUrl);
|
|
166
|
+
if (endpoint.protocol !== 'https:' && !(endpoint.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(endpoint.hostname)))
|
|
167
|
+
throw new Error('git_broker_unavailable');
|
|
168
|
+
const epoch = this.state.runtimeEpoch;
|
|
169
|
+
const response = await fetch(endpoint, {
|
|
170
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(10_000),
|
|
171
|
+
headers: { authorization: `Bearer ${this.state.config.controlToken}`, 'content-type': 'application/json' },
|
|
172
|
+
body: JSON.stringify({ runtimeId: this.state.config.runtimeId, generation: this.state.config.generation,
|
|
173
|
+
runtimeEpoch: epoch, workspaceId: binding.workspaceId }),
|
|
174
|
+
});
|
|
175
|
+
if (!response.ok) {
|
|
176
|
+
await response.body?.cancel();
|
|
177
|
+
throw new Error('git_broker_unavailable');
|
|
178
|
+
}
|
|
179
|
+
const preparation = workspacePreparationSchema.parse(await response.json());
|
|
180
|
+
const matched = preparation.transport && matchWorkspaceGitGatewayCloneUrl(preparation.transport.cloneUrl, this.state.config.gitGatewayOrigins, binding.repositoryUrl);
|
|
181
|
+
if (this.closed || this.state.journal.destroyed() || this.state.runtimeEpoch !== epoch
|
|
182
|
+
|| JSON.stringify(this.state.journal.getWorkspace(binding.workspaceId)) !== JSON.stringify(binding)
|
|
183
|
+
|| preparation.transport?.kind !== 'git-gateway-v2' || !matched?.ok || matched.requestId !== `v2/${binding.workspaceId}`
|
|
184
|
+
|| !preparation.gitAccess || Date.parse(preparation.gitAccess.issuedAt) > Date.now()
|
|
185
|
+
|| Date.parse(preparation.gitAccess.expiresAt) <= Date.now() + 10_000)
|
|
186
|
+
throw new Error('git_access_denied');
|
|
187
|
+
if (this.cache.size >= 128)
|
|
188
|
+
this.cache.clear();
|
|
189
|
+
this.cache.set(binding.workspaceId, { key, preparation });
|
|
190
|
+
return preparation;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function quote(value) { return `'${value.replaceAll("'", "'\\''")}'`; }
|
|
194
|
+
/** Pin directories in Linux sandboxes and replace config atomically without following user-owned symlinks. */
|
|
195
|
+
async function configureGitFile(root, stateDir, commands, repositoryUrl) {
|
|
196
|
+
const directoryFlags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
|
|
197
|
+
const directory = await open(root, directoryFlags);
|
|
198
|
+
const pinnedRoot = process.platform === 'linux' ? `/proc/self/fd/${directory.fd}` : root;
|
|
199
|
+
let gitDirectory;
|
|
200
|
+
let lock;
|
|
201
|
+
let temporary;
|
|
202
|
+
let lockPath;
|
|
203
|
+
try {
|
|
204
|
+
gitDirectory = await open(join(pinnedRoot, '.git'), directoryFlags);
|
|
205
|
+
const gitPath = process.platform === 'linux' ? `/proc/self/fd/${gitDirectory.fd}` : join(root, '.git');
|
|
206
|
+
const configPath = join(gitPath, 'config');
|
|
207
|
+
lock = await open(join(gitPath, 'config.lock'), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o640);
|
|
208
|
+
lockPath = join(gitPath, 'config.lock');
|
|
209
|
+
const source = await open(configPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
210
|
+
let content;
|
|
211
|
+
try {
|
|
212
|
+
const stat = await source.stat();
|
|
213
|
+
if (!stat.isFile() || stat.size > 1024 * 1024 || stat.nlink !== 1)
|
|
214
|
+
throw new Error('invalid_git_config');
|
|
215
|
+
content = await source.readFile('utf8');
|
|
216
|
+
await lock.chmod(stat.mode & 0o666);
|
|
217
|
+
}
|
|
218
|
+
finally {
|
|
219
|
+
await source.close();
|
|
220
|
+
}
|
|
221
|
+
await mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
222
|
+
temporary = await mkdtemp(join(stateDir, 'git-config-'));
|
|
223
|
+
const staging = join(temporary, 'config');
|
|
224
|
+
await writeFile(staging, content, { mode: 0o600 });
|
|
225
|
+
await clearManagedGitConfig(staging, repositoryUrl);
|
|
226
|
+
for (const args of commands)
|
|
227
|
+
await exec('git', ['config', '--file', staging, '--no-includes', ...args], {
|
|
228
|
+
timeout: 5000, maxBuffer: 8192, env: { PATH: process.env.PATH, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' },
|
|
229
|
+
});
|
|
230
|
+
await lock.writeFile(await readFile(staging));
|
|
231
|
+
await lock.sync();
|
|
232
|
+
await lock.close();
|
|
233
|
+
lock = undefined;
|
|
234
|
+
await rename(lockPath, configPath);
|
|
235
|
+
lockPath = undefined;
|
|
236
|
+
}
|
|
237
|
+
finally {
|
|
238
|
+
await lock?.close();
|
|
239
|
+
if (lockPath)
|
|
240
|
+
await unlink(lockPath).catch(() => undefined);
|
|
241
|
+
if (temporary)
|
|
242
|
+
await rm(temporary, { recursive: true, force: true });
|
|
243
|
+
await gitDirectory?.close();
|
|
244
|
+
await directory.close();
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/** Only remove authentication/routing for this binding and previous PlayCraft endpoints. */
|
|
248
|
+
async function clearManagedGitConfig(file, repositoryUrl) {
|
|
249
|
+
const run = (...args) => exec('git', ['config', '--file', file, '--no-includes', ...args], {
|
|
250
|
+
timeout: 5000, maxBuffer: 1024 * 1024,
|
|
251
|
+
env: { PATH: process.env.PATH, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' },
|
|
252
|
+
});
|
|
253
|
+
const entries = (await run('--null', '--list')).stdout.split('\0').filter(Boolean).map(entry => {
|
|
254
|
+
const newline = entry.indexOf('\n');
|
|
255
|
+
return [entry.slice(0, newline), entry.slice(newline + 1)];
|
|
256
|
+
});
|
|
257
|
+
const urls = new Set([repositoryUrl]);
|
|
258
|
+
const remove = new Set();
|
|
259
|
+
for (const [key, value] of entries) {
|
|
260
|
+
if (key === 'playcraft.gitauthurl')
|
|
261
|
+
urls.add(value);
|
|
262
|
+
const rewrite = /^url\.(.+)\.(?:insteadof|pushinsteadof)$/.exec(key);
|
|
263
|
+
if (rewrite && value === repositoryUrl) {
|
|
264
|
+
urls.add(rewrite[1]);
|
|
265
|
+
remove.add(key);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
for (const [key] of entries) {
|
|
269
|
+
for (const url of urls) {
|
|
270
|
+
if (key.startsWith(`credential.${url}.`) || key.startsWith(`http.${url}.`))
|
|
271
|
+
remove.add(key);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
for (const key of remove)
|
|
275
|
+
await run('--unset-all', key);
|
|
276
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { request } from 'node:http';
|
|
2
|
+
// Git invokes this executable directly. Keep standard output exclusively for the credential protocol.
|
|
3
|
+
const [socketPath, workspaceId, action] = process.argv.slice(2);
|
|
4
|
+
try {
|
|
5
|
+
if (action === 'get' || action === 'erase') {
|
|
6
|
+
const fields = {};
|
|
7
|
+
const chunks = [];
|
|
8
|
+
let size = 0;
|
|
9
|
+
for await (const chunk of process.stdin) {
|
|
10
|
+
size += chunk.length;
|
|
11
|
+
if (size > 16_384)
|
|
12
|
+
throw new Error();
|
|
13
|
+
chunks.push(Buffer.from(chunk));
|
|
14
|
+
}
|
|
15
|
+
for (const line of Buffer.concat(chunks).toString('utf8').split('\n')) {
|
|
16
|
+
if (!line)
|
|
17
|
+
break;
|
|
18
|
+
const separator = line.indexOf('=');
|
|
19
|
+
if (separator < 1)
|
|
20
|
+
throw new Error();
|
|
21
|
+
const key = line.slice(0, separator);
|
|
22
|
+
// Git may repeat extension fields such as capability[] and wwwauth[].
|
|
23
|
+
if (!['protocol', 'host', 'path', 'password'].includes(key))
|
|
24
|
+
continue;
|
|
25
|
+
if (key in fields)
|
|
26
|
+
throw new Error();
|
|
27
|
+
fields[key] = line.slice(separator + 1);
|
|
28
|
+
}
|
|
29
|
+
const credential = await new Promise((resolve, reject) => {
|
|
30
|
+
const client = request({ socketPath, path: '/credential', method: 'POST',
|
|
31
|
+
headers: { 'content-type': 'application/json' }, signal: AbortSignal.timeout(12_000) }, async (response) => {
|
|
32
|
+
try {
|
|
33
|
+
if (response.statusCode !== 200) {
|
|
34
|
+
response.resume();
|
|
35
|
+
throw new Error();
|
|
36
|
+
}
|
|
37
|
+
const parts = [];
|
|
38
|
+
let length = 0;
|
|
39
|
+
for await (const chunk of response) {
|
|
40
|
+
length += chunk.length;
|
|
41
|
+
if (length > 16_384)
|
|
42
|
+
throw new Error();
|
|
43
|
+
parts.push(Buffer.from(chunk));
|
|
44
|
+
}
|
|
45
|
+
resolve(JSON.parse(Buffer.concat(parts).toString('utf8')));
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
reject(new Error());
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
client.once('error', reject);
|
|
52
|
+
client.end(JSON.stringify({ workspaceId, action, protocol: fields.protocol, host: fields.host,
|
|
53
|
+
path: fields.path, ...(action === 'erase' ? { password: fields.password } : {}) }));
|
|
54
|
+
});
|
|
55
|
+
if (action === 'get') {
|
|
56
|
+
if (!credential.username || !credential.password || /[\r\n\0]/.test(credential.username + credential.password))
|
|
57
|
+
throw new Error();
|
|
58
|
+
process.stdout.write(`username=${credential.username}\npassword=${credential.password}\n\n`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
if (action === 'get')
|
|
64
|
+
process.stdout.write('quit=true\n\n');
|
|
65
|
+
process.exitCode = 1;
|
|
66
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { lstat, mkdir, open, realpath, readdir, rename, unlink } from 'node:fs/promises';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { join, resolve, sep } from 'node:path';
|
|
5
|
+
import { isLocalWorkspaceGitEnvironment, workspaceGitDirectAccessSchema } from '@playcraft/common/cloud-workspace/runtime';
|
|
6
|
+
/** Control-owned files only. Same-user processes are not an operating-system isolation boundary. */
|
|
7
|
+
export class WorkspaceGitDirectStore {
|
|
8
|
+
state;
|
|
9
|
+
mutation = Promise.resolve();
|
|
10
|
+
constructor(state) {
|
|
11
|
+
this.state = state;
|
|
12
|
+
}
|
|
13
|
+
exclusive(action) {
|
|
14
|
+
const result = this.mutation.then(action);
|
|
15
|
+
this.mutation = result.catch(() => undefined);
|
|
16
|
+
return result;
|
|
17
|
+
}
|
|
18
|
+
identity() {
|
|
19
|
+
const c = this.state.config;
|
|
20
|
+
return JSON.stringify([c.environment, c.userId, c.runtimeId, c.generation]);
|
|
21
|
+
}
|
|
22
|
+
name(id) {
|
|
23
|
+
if (!/^[a-f0-9-]{36}$/.test(id))
|
|
24
|
+
throw new Error('git_access_denied');
|
|
25
|
+
return `${id}.json`;
|
|
26
|
+
}
|
|
27
|
+
async directory(create, action) {
|
|
28
|
+
const stateDir = resolve(this.state.config.stateDir);
|
|
29
|
+
const directory = join(stateDir, 'direct-git');
|
|
30
|
+
if (!create && !(await lstat(directory).catch(error => {
|
|
31
|
+
if (error.code === 'ENOENT')
|
|
32
|
+
return undefined;
|
|
33
|
+
throw error;
|
|
34
|
+
})))
|
|
35
|
+
return undefined;
|
|
36
|
+
const root = await realpath(this.state.config.workspaceRoot);
|
|
37
|
+
if (this.state.config.stateDir !== stateDir || await realpath(stateDir) !== stateDir || stateDir === root || stateDir.startsWith(`${root}${sep}`)) {
|
|
38
|
+
throw new Error('git_control_directory_rejected');
|
|
39
|
+
}
|
|
40
|
+
for (const path of [stateDir, directory]) {
|
|
41
|
+
if (path === directory && create)
|
|
42
|
+
await mkdir(path, { mode: 0o700 }).catch(error => {
|
|
43
|
+
if (error.code !== 'EEXIST')
|
|
44
|
+
throw error;
|
|
45
|
+
});
|
|
46
|
+
const stat = await lstat(path);
|
|
47
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0) {
|
|
48
|
+
throw new Error('git_control_directory_rejected');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const handle = await open(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
52
|
+
try {
|
|
53
|
+
const pinned = process.platform === 'linux' ? `/proc/self/fd/${handle.fd}` : directory;
|
|
54
|
+
return await action(pinned);
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
await handle.close();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async read(path) {
|
|
61
|
+
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch(error => {
|
|
62
|
+
if (error.code === 'ENOENT')
|
|
63
|
+
return undefined;
|
|
64
|
+
throw error;
|
|
65
|
+
});
|
|
66
|
+
if (!handle)
|
|
67
|
+
return undefined;
|
|
68
|
+
try {
|
|
69
|
+
const stat = await handle.stat();
|
|
70
|
+
if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || stat.nlink !== 1 || stat.size > 16384) {
|
|
71
|
+
throw new Error('git_credential_file_rejected');
|
|
72
|
+
}
|
|
73
|
+
return JSON.parse(await handle.readFile('utf8'));
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
await handle.close();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async get(binding) {
|
|
80
|
+
return this.directory(false, async (path) => {
|
|
81
|
+
const stored = await this.read(join(path, this.name(binding.workspaceId)));
|
|
82
|
+
if (!stored)
|
|
83
|
+
return undefined;
|
|
84
|
+
if (stored.identity !== this.identity() || JSON.stringify(stored.binding) !== JSON.stringify(binding)
|
|
85
|
+
|| !isLocalWorkspaceGitEnvironment(this.state.config.environment))
|
|
86
|
+
throw new Error('git_access_denied');
|
|
87
|
+
if (stored.access !== null) {
|
|
88
|
+
const access = workspaceGitDirectAccessSchema.parse(stored.access);
|
|
89
|
+
if (access.repositoryUrl !== binding.repositoryUrl)
|
|
90
|
+
throw new Error('git_access_denied');
|
|
91
|
+
}
|
|
92
|
+
return stored;
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
async put(binding, access, rejectedPassword) {
|
|
96
|
+
if (!isLocalWorkspaceGitEnvironment(this.state.config.environment) || this.state.journal.destroyed())
|
|
97
|
+
throw new Error('git_access_denied');
|
|
98
|
+
if (access && (workspaceGitDirectAccessSchema.parse(access).repositoryUrl !== binding.repositoryUrl))
|
|
99
|
+
throw new Error('git_access_denied');
|
|
100
|
+
await this.exclusive(() => this.directory(true, async (path) => {
|
|
101
|
+
const target = join(path, this.name(binding.workspaceId));
|
|
102
|
+
// Refuse symlink/hardlink/permissive old files even though rename would replace them.
|
|
103
|
+
const old = await this.read(target);
|
|
104
|
+
if (rejectedPassword !== undefined && old?.access?.password !== rejectedPassword)
|
|
105
|
+
return;
|
|
106
|
+
const temporary = join(path, `${randomUUID()}.tmp`);
|
|
107
|
+
const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
108
|
+
try {
|
|
109
|
+
await handle.writeFile(JSON.stringify({ identity: this.identity(), binding, access }));
|
|
110
|
+
await handle.sync();
|
|
111
|
+
await handle.close();
|
|
112
|
+
if (this.state.journal.destroyed())
|
|
113
|
+
throw new Error('git_access_denied');
|
|
114
|
+
await rename(temporary, target);
|
|
115
|
+
const dir = await open(path, constants.O_RDONLY | constants.O_DIRECTORY);
|
|
116
|
+
try {
|
|
117
|
+
await dir.sync();
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
await dir.close();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
await handle.close();
|
|
125
|
+
await unlink(temporary).catch(error => { if (error.code !== 'ENOENT')
|
|
126
|
+
throw error; });
|
|
127
|
+
}
|
|
128
|
+
}));
|
|
129
|
+
}
|
|
130
|
+
async remove(workspaceId) {
|
|
131
|
+
await this.exclusive(() => this.directory(false, async (path) => {
|
|
132
|
+
const target = join(path, this.name(workspaceId));
|
|
133
|
+
await this.read(target);
|
|
134
|
+
await unlink(target).catch(error => { if (error.code !== 'ENOENT')
|
|
135
|
+
throw error; });
|
|
136
|
+
}));
|
|
137
|
+
}
|
|
138
|
+
async sweep(destroy = false) {
|
|
139
|
+
await this.exclusive(() => this.directory(false, async (path) => {
|
|
140
|
+
for (const name of await readdir(path)) {
|
|
141
|
+
if (!/^[a-f0-9-]{36}\.(json|tmp)$/.test(name))
|
|
142
|
+
throw new Error('git_credential_file_rejected');
|
|
143
|
+
const target = join(path, name);
|
|
144
|
+
if (name.endsWith('.tmp')) {
|
|
145
|
+
await unlink(target);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const stored = await this.read(target);
|
|
149
|
+
if (destroy || stored?.identity !== this.identity() || !isLocalWorkspaceGitEnvironment(this.state.config.environment))
|
|
150
|
+
await unlink(target);
|
|
151
|
+
}
|
|
152
|
+
}));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
@@ -116,10 +116,23 @@ export async function pushWorkspaceGit(root) {
|
|
|
116
116
|
if (origin.code !== 0) {
|
|
117
117
|
throw new GitWorkspaceError('remote_not_configured', 'origin');
|
|
118
118
|
}
|
|
119
|
-
const
|
|
120
|
-
if (
|
|
121
|
-
throw new GitWorkspaceError('git_command_failed',
|
|
119
|
+
const ref = (await git(rootReal, ['symbolic-ref', '--quiet', 'HEAD'])).trim();
|
|
120
|
+
if (!ref.startsWith('refs/heads/'))
|
|
121
|
+
throw new GitWorkspaceError('git_command_failed', 'git_branch_required');
|
|
122
|
+
const commit = (await git(rootReal, ['rev-parse', '--verify', 'HEAD^{commit}'])).trim();
|
|
123
|
+
try {
|
|
124
|
+
const pushed = await gitAllowFail(rootReal, ['push', '--porcelain', 'origin', `${commit}:${ref}`], 90000);
|
|
125
|
+
if (pushed.code === 0)
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
catch { /* A lost response does not prove the remote rejected the update. */ }
|
|
129
|
+
try {
|
|
130
|
+
const remote = await gitAllowFail(rootReal, ['ls-remote', '--refs', 'origin', ref], 20000);
|
|
131
|
+
if (remote.code === 0 && remote.stdout.trim() === `${commit}\t${ref}`)
|
|
132
|
+
return;
|
|
122
133
|
}
|
|
134
|
+
catch { /* Preserve uncertainty; never replay a write automatically. */ }
|
|
135
|
+
throw new GitWorkspaceError('git_push_outcome_unknown', 'git_push_outcome_unknown');
|
|
123
136
|
}
|
|
124
137
|
export async function ensureWorkspaceGit(root) {
|
|
125
138
|
const rootReal = await realpath(root);
|