ccdeck 3.51.0 → 3.53.0
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 +13 -4
- package/bin/cli/help.js +1 -1
- package/bin/cli/one-shot.js +3 -2
- package/bin/cli/second-start.js +2 -2
- package/bin/cli/uninstall.js +1 -1
- package/bin/codex-profile.js +21 -0
- package/bin/deck.js +4 -3
- package/dist/web/assets/BrowserWatchModal-CKN9jBCT.js +1 -0
- package/dist/web/assets/IntegrationModal-Cb9MgsP1.js +7 -0
- package/dist/web/assets/RadioPanel-D8h6qba-.js +1 -0
- package/dist/web/assets/TrafficRadar-3_aX8BI6.js +8 -0
- package/dist/web/assets/UsageHistoryModal-DgMXDORj.js +1 -0
- package/dist/web/assets/app-BwJGP2ic.js +358 -0
- package/dist/web/assets/app-xTrs4aEH.css +1 -0
- package/dist/web/assets/{index-CWUj8Kqh.js → index-C8fQC4Vq.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +2 -1
- package/release-notes.json +36 -0
- package/src/server/account-routes.mjs +99 -0
- package/src/server/account-watch.mjs +1 -1
- package/src/server/cli-versions.mjs +3 -3
- package/src/server/codex-auth.mjs +51 -9
- package/src/server/codex-auto.mjs +196 -0
- package/src/server/codex-login.mjs +117 -0
- package/src/server/codex-native-account.mjs +288 -0
- package/src/server/codex-profiles.mjs +243 -0
- package/src/server/codex-quota.mjs +370 -251
- package/src/server/codex-selection.mjs +371 -0
- package/src/server/codex-terminal-runner.mjs +78 -0
- package/src/server/codex-terminal.mjs +109 -0
- package/src/server/codex-watch.mjs +38 -22
- package/src/server/depth-facts.mjs +1 -1
- package/src/server/discovery.mjs +13 -0
- package/src/server/index.mjs +19 -1
- package/src/server/installer.mjs +11 -5
- package/src/server/log-election.mjs +32 -3
- package/src/server/login-service.mjs +1 -1
- package/src/server/memory-files.mjs +2 -2
- package/src/server/pinned-build.mjs +3 -0
- package/src/server/request-gates.mjs +9 -0
- package/src/server/running-deck.mjs +12 -1
- package/src/server/session-enrichment.mjs +2 -2
- package/src/server/tool-audit.mjs +15 -1
- package/src/server/usage-routes.mjs +1 -1
- package/dist/web/assets/BrowserWatchModal-CDpunrq9.js +0 -1
- package/dist/web/assets/IntegrationModal-BctMcNU8.js +0 -7
- package/dist/web/assets/RadioPanel-DQNFtYOx.js +0 -1
- package/dist/web/assets/TrafficRadar-DRt3Al7E.js +0 -8
- package/dist/web/assets/UsageHistoryModal-DlgPufgs.js +0 -1
- package/dist/web/assets/app-4x4wTE-L.js +0 -321
- package/dist/web/assets/app-o4kL0FgZ.css +0 -1
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
// Machine-local metadata only. This module never opens or copies credentials.
|
|
2
|
+
import { access, link, lstat, mkdir, open, readFile, realpath, rename, rm, stat, unlink } from 'node:fs/promises';
|
|
3
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { createServer } from 'node:net';
|
|
6
|
+
import { basename, join, posix, win32, resolve } from 'node:path';
|
|
7
|
+
import { codexHome } from './codex-dir.mjs';
|
|
8
|
+
import { deckDataDir } from './deck-home.mjs';
|
|
9
|
+
import { createTemp, renameWithRetry } from './atomic-write.mjs';
|
|
10
|
+
|
|
11
|
+
export function configuredCodexHomes(env = process.env, home = homedir(), platform = process.platform) {
|
|
12
|
+
const path = platform === 'win32' ? win32 : posix;
|
|
13
|
+
const result = [codexHome(env, home, platform)];
|
|
14
|
+
let extras = [];
|
|
15
|
+
try { const value = JSON.parse(env.CCDECK_CODEX_HOMES ?? '[]'); if (Array.isArray(value)) extras = value; } catch { /* optional configuration */ }
|
|
16
|
+
for (const entry of extras) {
|
|
17
|
+
if (typeof entry !== 'string' || !entry.trim() || !path.isAbsolute(entry.trim())) continue;
|
|
18
|
+
const candidate = path.resolve(entry.trim());
|
|
19
|
+
if (!result.includes(candidate)) result.push(candidate);
|
|
20
|
+
}
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function codexSelectionError(code) {
|
|
25
|
+
return Object.assign(new Error(code), { code });
|
|
26
|
+
}
|
|
27
|
+
const fail = code => { throw codexSelectionError(code); };
|
|
28
|
+
const idPattern = /^[a-f0-9]{20}$/;
|
|
29
|
+
const operationPattern = /^[A-Za-z0-9_-]{1,128}$/;
|
|
30
|
+
const safeCodes = new Set(['not_removable', 'login_not_movable', 'selection_conflict', 'operation_conflict', 'selection_busy', 'unknown_profile', 'profile_unavailable', 'registry_corrupt', 'registry_write_failed', 'invalid_operation', 'invalid_revision', 'invalid_label']);
|
|
31
|
+
const storeDir = options => resolve(options.store ?? deckDataDir(options.platform, options.env, options.home));
|
|
32
|
+
export const codexSelectionPath = (options = {}) => join(storeDir(options), 'codex-accounts.json');
|
|
33
|
+
|
|
34
|
+
export async function codexProfileId(home) {
|
|
35
|
+
let canonical;
|
|
36
|
+
try { canonical = await realpath(home); } catch { canonical = home; }
|
|
37
|
+
return createHash('sha256').update(canonical).digest('hex').slice(0, 20);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function directoryExists(home) {
|
|
41
|
+
try { return (await stat(home)).isDirectory(); } catch { return false; }
|
|
42
|
+
}
|
|
43
|
+
async function validate(state, options) {
|
|
44
|
+
const path = (options.platform ?? process.platform) === 'win32' ? win32 : posix;
|
|
45
|
+
if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0
|
|
46
|
+
|| typeof state.originalHome !== 'string' || !path.isAbsolute(state.originalHome)
|
|
47
|
+
|| typeof state.selectedProfileId !== 'string' || !idPattern.test(state.selectedProfileId) || !Array.isArray(state.profiles) || !Array.isArray(state.operations)) fail('registry_corrupt');
|
|
48
|
+
const ids = new Set();
|
|
49
|
+
for (const p of state.profiles) {
|
|
50
|
+
if (!p || typeof p.id !== 'string' || !idPattern.test(p.id) || ids.has(p.id) || typeof p.home !== 'string' || !path.isAbsolute(p.home)
|
|
51
|
+
|| typeof p.managed !== 'boolean' || !(p.label === null || validLabel(p.label))) fail('registry_corrupt');
|
|
52
|
+
ids.add(p.id);
|
|
53
|
+
if (p.managed) {
|
|
54
|
+
const root = join(storeDir(options), 'codex-profiles');
|
|
55
|
+
const leaf = path.basename(p.home);
|
|
56
|
+
if (!/^[a-f0-9]{32}$/.test(leaf) || p.home !== join(root, leaf)) fail('registry_corrupt');
|
|
57
|
+
// Never follow an externally substituted managed directory.
|
|
58
|
+
try { if (!(await lstat(root)).isDirectory() || !(await lstat(p.home)).isDirectory() || await realpath(p.home) !== join(await realpath(root), leaf)) fail('registry_corrupt'); }
|
|
59
|
+
catch (e) { if (e.code === 'registry_corrupt') throw e; if (e.code !== 'ENOENT') fail('profile_unavailable'); }
|
|
60
|
+
}
|
|
61
|
+
// Missing homes remain inspectable, with their persisted IDs.
|
|
62
|
+
if (await directoryExists(p.home) && await codexProfileId(p.home) !== p.id) fail('profile_unavailable');
|
|
63
|
+
}
|
|
64
|
+
if (!state.profiles.some(p => p.home === state.originalHome) || !ids.has(state.selectedProfileId)) fail('registry_corrupt');
|
|
65
|
+
const operations = new Set();
|
|
66
|
+
for (const op of state.operations) {
|
|
67
|
+
if (!op || typeof op.operationId !== 'string' || !operationPattern.test(op.operationId) || operations.has(op.operationId)
|
|
68
|
+
|| !['add', 'select'].includes(op.kind) || !ids.has(op.id) || !Number.isSafeInteger(op.revision)
|
|
69
|
+
|| op.revision < 1 || op.revision > state.revision
|
|
70
|
+
|| (op.kind === 'select' && (!Number.isSafeInteger(op.expectedRevision) || op.expectedRevision < 0))
|
|
71
|
+
|| (op.kind === 'add' && !(op.label === null || validLabel(op.label)))) fail('registry_corrupt');
|
|
72
|
+
operations.add(op.operationId);
|
|
73
|
+
}
|
|
74
|
+
return state;
|
|
75
|
+
}
|
|
76
|
+
async function load(options) {
|
|
77
|
+
try {
|
|
78
|
+
const file = codexSelectionPath(options);
|
|
79
|
+
if ((await lstat(file)).isSymbolicLink()) fail('registry_corrupt');
|
|
80
|
+
return await validate(JSON.parse(await readFile(file, 'utf8')), options);
|
|
81
|
+
} catch (e) {
|
|
82
|
+
if (e.code === 'ENOENT') return null;
|
|
83
|
+
if (['registry_corrupt', 'profile_unavailable'].includes(e.code)) throw e;
|
|
84
|
+
fail('registry_corrupt');
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async function homesFor(state, options) {
|
|
88
|
+
const candidates = [...configuredCodexHomes(options.env, options.home, options.platform), ...(state?.profiles.map(p => p.home) ?? [])];
|
|
89
|
+
const ids = new Set(), homes = [];
|
|
90
|
+
for (const home of candidates) {
|
|
91
|
+
const id = state?.profiles.find(p => p.home === home)?.id ?? await codexProfileId(home);
|
|
92
|
+
if (!ids.has(id)) { ids.add(id); homes.push(home); }
|
|
93
|
+
}
|
|
94
|
+
return homes;
|
|
95
|
+
}
|
|
96
|
+
async function snapshot(state, options) {
|
|
97
|
+
const homes = await homesFor(state, options);
|
|
98
|
+
const selected = state?.profiles.find(p => p.id === state.selectedProfileId);
|
|
99
|
+
const home = selected?.home ?? homes[0];
|
|
100
|
+
const profiles = await Promise.all(homes.map(async directory => ({
|
|
101
|
+
id: state?.profiles.find(p => p.home === directory)?.id ?? await codexProfileId(directory),
|
|
102
|
+
home: directory,
|
|
103
|
+
available: await directoryExists(directory),
|
|
104
|
+
})));
|
|
105
|
+
// Absence is a recoverable state, not permission to choose another account.
|
|
106
|
+
return {
|
|
107
|
+
home, profileId: state?.selectedProfileId ?? await codexProfileId(home),
|
|
108
|
+
revision: state?.revision ?? 0, selectionEnabled: state !== null,
|
|
109
|
+
available: await directoryExists(home), homes, profiles,
|
|
110
|
+
managedProfiles: (state?.profiles ?? []).filter(p => p.managed).map(({ id, label }) => ({ id, label })),
|
|
111
|
+
/** The name somebody gave each account, the deck's own or not. */
|
|
112
|
+
profileLabels: (state?.profiles ?? []).filter(p => p.label).map(({ id, label }) => ({ id, label })),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
export async function readCodexSelection(options = {}) { return snapshot(await load(options), options); }
|
|
116
|
+
|
|
117
|
+
// Immutable file locks serialize independent processes. A recovery-only OS
|
|
118
|
+
// mutex prevents two reclaimers from unlinking a fresh owner's replacement.
|
|
119
|
+
// Its kernel ownership disappears on crash, unlike a second recovery file.
|
|
120
|
+
async function locked(options, fn) {
|
|
121
|
+
try { return await acquireAndRun(options, fn); }
|
|
122
|
+
catch (e) { if (safeCodes.has(e.code)) throw e; fail('registry_write_failed'); }
|
|
123
|
+
}
|
|
124
|
+
function ownerAlive(pid) {
|
|
125
|
+
try { process.kill(pid, 0); return true; }
|
|
126
|
+
catch (e) { return e.code !== 'ESRCH'; }
|
|
127
|
+
}
|
|
128
|
+
async function lockRecord(file) {
|
|
129
|
+
let handle;
|
|
130
|
+
try {
|
|
131
|
+
handle = await open(file, 'r');
|
|
132
|
+
const info = await handle.stat();
|
|
133
|
+
const owner = JSON.parse(await handle.readFile('utf8'));
|
|
134
|
+
if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0 || !/^[a-f0-9]{32}$/.test(owner.nonce ?? '')) return null;
|
|
135
|
+
return { ...owner, ino: info.ino, dev: info.dev };
|
|
136
|
+
} catch { return null; }
|
|
137
|
+
finally { await handle?.close(); }
|
|
138
|
+
}
|
|
139
|
+
const sameLock = (a, b) => a && b && a.pid === b.pid && a.nonce === b.nonce && a.ino === b.ino && a.dev === b.dev;
|
|
140
|
+
async function reclaimDeadLock(file, dir) {
|
|
141
|
+
const observed = await lockRecord(file);
|
|
142
|
+
if (!observed || ownerAlive(observed.pid)) return;
|
|
143
|
+
const canonical = await realpath(dir);
|
|
144
|
+
const port = 32768 + createHash('sha256').update(canonical).digest().readUInt16BE(0) % 16384;
|
|
145
|
+
const mutex = createServer(socket => socket.destroy());
|
|
146
|
+
const held = await new Promise(resolve => {
|
|
147
|
+
mutex.once('error', () => resolve(false));
|
|
148
|
+
mutex.listen({ host: '127.0.0.1', port, exclusive: true }, () => resolve(true));
|
|
149
|
+
});
|
|
150
|
+
if (!held) return; // occupied port: never reclaim without exclusive ownership
|
|
151
|
+
try {
|
|
152
|
+
const current = await lockRecord(file);
|
|
153
|
+
if (!sameLock(observed, current) || ownerAlive(current.pid)) return;
|
|
154
|
+
// No competing reclaimer can act between this check and unlink. A new
|
|
155
|
+
// owner cannot link its lock while this dead owner's file still exists.
|
|
156
|
+
const checked = await lockRecord(file);
|
|
157
|
+
if (sameLock(current, checked) && !ownerAlive(checked.pid)) await unlink(file);
|
|
158
|
+
} finally { await new Promise(resolve => mutex.close(resolve)); }
|
|
159
|
+
}
|
|
160
|
+
async function acquireAndRun(options, fn) {
|
|
161
|
+
const dir = storeDir(options), file = join(dir, 'codex-accounts.lock');
|
|
162
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
163
|
+
const nonce = randomBytes(16).toString('hex');
|
|
164
|
+
const staged = join(dir, `.codex-accounts-lock-${process.pid}-${nonce}.tmp`);
|
|
165
|
+
const handle = await open(staged, 'wx', 0o600);
|
|
166
|
+
try {
|
|
167
|
+
try { await handle.writeFile(JSON.stringify({ pid: process.pid, nonce })); await handle.sync(); }
|
|
168
|
+
finally { await handle.close(); }
|
|
169
|
+
} catch (e) { await unlink(staged).catch(() => {}); throw e; }
|
|
170
|
+
const deadline = Date.now() + (options.lockTimeoutMs ?? 5000);
|
|
171
|
+
let held = false;
|
|
172
|
+
try {
|
|
173
|
+
while (!held) {
|
|
174
|
+
try { await link(staged, file); held = true; }
|
|
175
|
+
catch (e) {
|
|
176
|
+
if (e.code !== 'EEXIST') fail('registry_write_failed');
|
|
177
|
+
await reclaimDeadLock(file, dir);
|
|
178
|
+
if (Date.now() >= deadline) fail('selection_busy');
|
|
179
|
+
await new Promise(r => setTimeout(r, 25));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return await fn();
|
|
183
|
+
} finally {
|
|
184
|
+
if (held) {
|
|
185
|
+
const record = await lockRecord(file);
|
|
186
|
+
if (record?.pid === process.pid && record.nonce === nonce) await unlink(file);
|
|
187
|
+
}
|
|
188
|
+
await unlink(staged).catch(() => {});
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
async function initial(options) {
|
|
192
|
+
const state = await load(options);
|
|
193
|
+
if (state) return state;
|
|
194
|
+
const home = configuredCodexHomes(options.env, options.home, options.platform)[0];
|
|
195
|
+
const id = await codexProfileId(home);
|
|
196
|
+
return { version: 1, revision: 0, originalHome: home, selectedProfileId: id,
|
|
197
|
+
profiles: [{ id, home, label: null, managed: false }], operations: [] };
|
|
198
|
+
}
|
|
199
|
+
function validLabel(label) {
|
|
200
|
+
return typeof label === 'string' && label.trim() === label && label.length > 0 && label.length <= 80 && !/[\x00-\x1f\x7f/\\]/.test(label);
|
|
201
|
+
}
|
|
202
|
+
function operationId(value) { if (typeof value !== 'string' || !operationPattern.test(value)) fail('invalid_operation'); }
|
|
203
|
+
// Restrictive mode from creation, including the staged metadata file.
|
|
204
|
+
async function writeRegistryAtomic(target, text) {
|
|
205
|
+
const { tmp, handle } = await createTemp(target, { mode: 0o600 });
|
|
206
|
+
try {
|
|
207
|
+
try { await handle.writeFile(text, 'utf8'); await handle.sync(); }
|
|
208
|
+
finally { await handle.close(); }
|
|
209
|
+
await renameWithRetry(tmp, target);
|
|
210
|
+
} catch (e) { await unlink(tmp).catch(() => {}); throw e; }
|
|
211
|
+
}
|
|
212
|
+
async function persist(state, options) {
|
|
213
|
+
try { await (options.writeFileAtomic ?? writeRegistryAtomic)(codexSelectionPath(options), JSON.stringify(state) + '\n'); }
|
|
214
|
+
catch { fail('registry_write_failed'); }
|
|
215
|
+
}
|
|
216
|
+
function replay(state, operationId, kind, matches) {
|
|
217
|
+
const op = state.operations.find(o => o.operationId === operationId);
|
|
218
|
+
if (op && (op.kind !== kind || !matches(op))) fail('operation_conflict');
|
|
219
|
+
return op;
|
|
220
|
+
}
|
|
221
|
+
export async function selectCodexProfile({ id, expectedRevision, operationId: operation } = {}, options = {}) {
|
|
222
|
+
operationId(operation);
|
|
223
|
+
if (typeof id !== 'string' || !idPattern.test(id)) fail('unknown_profile');
|
|
224
|
+
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) fail('invalid_revision');
|
|
225
|
+
return locked(options, async () => {
|
|
226
|
+
const state = await initial(options);
|
|
227
|
+
if (replay(state, operation, 'select', o => o.id === id && o.expectedRevision === expectedRevision)) {
|
|
228
|
+
return { ...await snapshot(state, options), status: 'applied_for_new_sessions' };
|
|
229
|
+
}
|
|
230
|
+
if (state.revision !== expectedRevision) fail('selection_conflict');
|
|
231
|
+
const homes = await homesFor(state, options);
|
|
232
|
+
let home;
|
|
233
|
+
for (const candidate of homes) if ((state.profiles.find(p => p.home === candidate)?.id ?? await codexProfileId(candidate)) === id) { home = candidate; break; }
|
|
234
|
+
if (!home) fail('unknown_profile');
|
|
235
|
+
if (!await directoryExists(home)) fail('profile_unavailable');
|
|
236
|
+
if (!state.profiles.some(p => p.id === id)) state.profiles.push({ id, home, label: null, managed: false });
|
|
237
|
+
state.selectedProfileId = id;
|
|
238
|
+
state.revision++;
|
|
239
|
+
state.operations.push({ operationId: operation, kind: 'select', id, expectedRevision, revision: state.revision });
|
|
240
|
+
const result = await snapshot(state, options);
|
|
241
|
+
await persist(state, options);
|
|
242
|
+
return { ...result, status: 'applied_for_new_sessions' };
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
/** Add an account this deck keeps the home of. The name is optional: without
|
|
246
|
+
* one it is called by its email once it is signed in, the way Claude's are. */
|
|
247
|
+
export async function addCodexProfile({ label = null, operationId: operation } = {}, options = {}) {
|
|
248
|
+
operationId(operation);
|
|
249
|
+
if (label !== null && !validLabel(label)) fail('invalid_label');
|
|
250
|
+
return locked(options, async () => {
|
|
251
|
+
const state = await initial(options);
|
|
252
|
+
const previous = replay(state, operation, 'add', o => o.label === label);
|
|
253
|
+
if (previous) return { ...await snapshot(state, options), id: previous.id, profile: { id: previous.id, label, managed: true } };
|
|
254
|
+
const root = join(storeDir(options), 'codex-profiles');
|
|
255
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
256
|
+
if (!(await lstat(root)).isDirectory()) fail('registry_corrupt');
|
|
257
|
+
const home = join(root, randomBytes(16).toString('hex'));
|
|
258
|
+
await mkdir(home, { mode: 0o700 });
|
|
259
|
+
try {
|
|
260
|
+
const id = await codexProfileId(home);
|
|
261
|
+
state.profiles.push({ id, home, label, managed: true });
|
|
262
|
+
state.revision++;
|
|
263
|
+
state.operations.push({ operationId: operation, kind: 'add', id, label, revision: state.revision });
|
|
264
|
+
const result = await snapshot(state, options);
|
|
265
|
+
await persist(state, options);
|
|
266
|
+
return { ...result, id, profile: { id, label, managed: true } };
|
|
267
|
+
} catch (e) { await rm(home, { recursive: true, force: true }); throw e; }
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
/** Give an account a short name, or take it away with an empty one, as Claude's
|
|
273
|
+
* Rename does. Any account can have one: it is the deck's note about a home, so
|
|
274
|
+
* the user's own home is named here and nothing in it is touched. */
|
|
275
|
+
export async function renameCodexProfile({ id, label, expectedRevision } = {}, options = {}) {
|
|
276
|
+
if (typeof id !== 'string' || !idPattern.test(id)) fail('unknown_profile');
|
|
277
|
+
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) fail('invalid_revision');
|
|
278
|
+
const name = label === null || label === undefined || label === '' ? null : label;
|
|
279
|
+
if (name !== null && !validLabel(name)) fail('invalid_label');
|
|
280
|
+
return locked(options, async () => {
|
|
281
|
+
const state = await initial(options);
|
|
282
|
+
if (state.revision !== expectedRevision) fail('selection_conflict');
|
|
283
|
+
let profile = state.profiles.find(p => p.id === id);
|
|
284
|
+
if (!profile) {
|
|
285
|
+
// A home named only in the environment has no entry until it is needed.
|
|
286
|
+
for (const home of await homesFor(state, options)) {
|
|
287
|
+
if (await codexProfileId(home) === id) { profile = { id, home, label: null, managed: false }; state.profiles.push(profile); break; }
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (!profile) fail('unknown_profile');
|
|
291
|
+
profile.label = name;
|
|
292
|
+
state.revision++;
|
|
293
|
+
const result = await snapshot(state, options);
|
|
294
|
+
await persist(state, options);
|
|
295
|
+
return { ...result, id, status: 'renamed' };
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Take a managed profile out of the registry. Its folder is not deleted: it is
|
|
300
|
+
* moved to `codex-profiles-removed/` beside the live ones, with its sign-in and
|
|
301
|
+
* Codex history, so nothing is lost and nothing signed in stays listed. Only a
|
|
302
|
+
* profile this deck made can go; the original home and any home named in
|
|
303
|
+
* CCDECK_CODEX_HOMES are the user's own and stay. */
|
|
304
|
+
export async function removeCodexProfile({ id, expectedRevision } = {}, options = {}) {
|
|
305
|
+
if (typeof id !== 'string' || !idPattern.test(id)) fail('unknown_profile');
|
|
306
|
+
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) fail('invalid_revision');
|
|
307
|
+
return locked(options, async () => {
|
|
308
|
+
const state = await initial(options);
|
|
309
|
+
if (state.revision !== expectedRevision) fail('selection_conflict');
|
|
310
|
+
const profile = state.profiles.find(p => p.id === id);
|
|
311
|
+
if (!profile) fail('unknown_profile');
|
|
312
|
+
if (!profile.managed) fail('not_removable');
|
|
313
|
+
return { ...await dropProfile(state, profile, options), status: 'removed' };
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Take a profile off the registry, and its folder out of the way. */
|
|
318
|
+
async function dropProfile(state, profile, options) {
|
|
319
|
+
const { id } = profile;
|
|
320
|
+
state.profiles = state.profiles.filter(p => p.id !== id);
|
|
321
|
+
// What this profile's add and select left behind would name a profile that
|
|
322
|
+
// is gone, which the registry's own check refuses.
|
|
323
|
+
state.operations = state.operations.filter(op => op.id !== id);
|
|
324
|
+
if (state.selectedProfileId === id) {
|
|
325
|
+
// The default falls back to the home that was the default before any
|
|
326
|
+
// account was added.
|
|
327
|
+
state.selectedProfileId = state.profiles.find(p => p.home === state.originalHome).id;
|
|
328
|
+
}
|
|
329
|
+
state.revision++;
|
|
330
|
+
const result = await snapshot(state, options);
|
|
331
|
+
await persist(state, options);
|
|
332
|
+
const trash = join(storeDir(options), 'codex-profiles-removed');
|
|
333
|
+
try {
|
|
334
|
+
await mkdir(trash, { recursive: true, mode: 0o700 });
|
|
335
|
+
await rename(profile.home, join(trash, `${basename(profile.home)}-${Date.now()}`));
|
|
336
|
+
} catch { /* The folder stays where it was, unlisted: nothing is lost. */ }
|
|
337
|
+
return result;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** Give an account the login of a sign-in that landed on it, as Claude's replaces
|
|
341
|
+
* a stored login in place: the row keeps its place, its name and its history.
|
|
342
|
+
* A sign-in needs a home of its own, because nobody can say who it lands on until
|
|
343
|
+
* it has; when that is an account already here, the login crosses over and the
|
|
344
|
+
* home made for it goes.
|
|
345
|
+
*
|
|
346
|
+
* The file is renamed, never opened or copied, so no two homes hold one login.
|
|
347
|
+
* Another disk, or a login kept in the OS keyring, cannot move that way and is
|
|
348
|
+
* refused, leaving the account the login it had. That both rows are one account
|
|
349
|
+
* is for the caller to prove: see replaceCodexLogin. */
|
|
350
|
+
export async function moveCodexLogin({ id, into, expectedRevision } = {}, options = {}) {
|
|
351
|
+
if (typeof id !== 'string' || !idPattern.test(id) || typeof into !== 'string' || !idPattern.test(into) || id === into) fail('unknown_profile');
|
|
352
|
+
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) fail('invalid_revision');
|
|
353
|
+
return locked(options, async () => {
|
|
354
|
+
const state = await initial(options);
|
|
355
|
+
if (state.revision !== expectedRevision) fail('selection_conflict');
|
|
356
|
+
const profile = state.profiles.find(p => p.id === id);
|
|
357
|
+
const target = state.profiles.find(p => p.id === into);
|
|
358
|
+
if (!profile || !target) fail('unknown_profile');
|
|
359
|
+
if (!profile.managed) fail('not_removable');
|
|
360
|
+
try {
|
|
361
|
+
await access(join(target.home, 'auth.json'));
|
|
362
|
+
await renameWithRetry(join(profile.home, 'auth.json'), join(target.home, 'auth.json'));
|
|
363
|
+
} catch { fail('login_not_movable'); }
|
|
364
|
+
const { settleMovedLogin } = await import('./codex-native-account.mjs');
|
|
365
|
+
// The login has already crossed over. Settling its readings only spares one
|
|
366
|
+
// stale poll, so a failure here must not leave the empty row listed with a
|
|
367
|
+
// login that is no longer there to move again.
|
|
368
|
+
try { await settleMovedLogin(target.home); } catch { /* the next read settles it */ }
|
|
369
|
+
return { ...await dropProfile(state, profile, options), status: 'replaced' };
|
|
370
|
+
});
|
|
371
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Copied with exec-spec.mjs into the durable terminal integration directory.
|
|
2
|
+
// No dependency on an npx cache, running server, or OAuth credential store.
|
|
3
|
+
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { spawnSpec } from './exec-spec.mjs';
|
|
9
|
+
|
|
10
|
+
export async function terminalCodexHome(file, env = process.env) {
|
|
11
|
+
if (env.CODEX_HOME?.trim()) return env.CODEX_HOME;
|
|
12
|
+
let state;
|
|
13
|
+
try { state = JSON.parse(await readFile(file, 'utf8')); }
|
|
14
|
+
catch (error) {
|
|
15
|
+
if (error.code === 'ENOENT') return null;
|
|
16
|
+
throw new Error('Codex account selection cannot be read. Repair it in ccdeck before launching.');
|
|
17
|
+
}
|
|
18
|
+
const selected = state?.profiles?.find(p => p.id === state.selectedProfileId);
|
|
19
|
+
if (state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 1
|
|
20
|
+
|| !selected || typeof selected.home !== 'string' || !isAbsolute(selected.home)) {
|
|
21
|
+
throw new Error('Codex account selection is invalid. Repair it in ccdeck before launching.');
|
|
22
|
+
}
|
|
23
|
+
let canonical;
|
|
24
|
+
try {
|
|
25
|
+
canonical = await realpath(selected.home);
|
|
26
|
+
if (!(await stat(canonical)).isDirectory()) throw new Error();
|
|
27
|
+
} catch { throw new Error('The selected Codex profile is unavailable. Restore it or select another in ccdeck.'); }
|
|
28
|
+
if (createHash('sha256').update(canonical).digest('hex').slice(0, 20) !== selected.id) {
|
|
29
|
+
throw new Error('The selected Codex profile changed location. Select it again in ccdeck.');
|
|
30
|
+
}
|
|
31
|
+
if (selected.managed) {
|
|
32
|
+
const root = await realpath(join(dirname(file), 'codex-profiles'));
|
|
33
|
+
if (dirname(canonical) !== root || !/^[a-f0-9]{32}$/.test(canonical.slice(root.length + 1))) {
|
|
34
|
+
throw new Error('The selected Codex profile is invalid. Repair it in ccdeck before launching.');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return selected.home;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function runSelectedCodex(file, executable, args, { env = process.env } = {}) {
|
|
41
|
+
const home = await terminalCodexHome(file, env);
|
|
42
|
+
const spec = spawnSpec(executable, args);
|
|
43
|
+
const child = spawn(spec.file, spec.args, { ...spec.opts, stdio: 'inherit', env: home ? { ...env, CODEX_HOME: home } : env });
|
|
44
|
+
// Terminal Ctrl+C already reaches both processes. Keep the wrapper alive
|
|
45
|
+
// until the child exits; forwarding would deliver the signal twice.
|
|
46
|
+
const hold = () => {};
|
|
47
|
+
process.on('SIGINT', hold);
|
|
48
|
+
const stop = () => child.kill('SIGTERM');
|
|
49
|
+
process.on('SIGTERM', stop);
|
|
50
|
+
process.on('SIGHUP', stop);
|
|
51
|
+
try {
|
|
52
|
+
return await new Promise((resolve, reject) => {
|
|
53
|
+
child.once('error', reject);
|
|
54
|
+
child.once('exit', (code, signal) => resolve({ code: code ?? (signal === 'SIGINT' ? 130 : 143), signal }));
|
|
55
|
+
});
|
|
56
|
+
} finally {
|
|
57
|
+
process.removeListener('SIGINT', hold);
|
|
58
|
+
process.removeListener('SIGTERM', stop);
|
|
59
|
+
process.removeListener('SIGHUP', stop);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (process.argv[1] && await realpath(fileURLToPath(import.meta.url)) === await realpath(process.argv[1]).catch(() => null)) {
|
|
64
|
+
const [file, executable, ...args] = process.argv.slice(2);
|
|
65
|
+
if (!file || !executable) { console.error('Codex terminal integration is incomplete. Reinstall it from ccdeck.'); process.exitCode = 1; }
|
|
66
|
+
else {
|
|
67
|
+
try {
|
|
68
|
+
let forwarded = args;
|
|
69
|
+
if (args[0] === '--ccdeck-args-base64') {
|
|
70
|
+
if (args.length !== 2) throw new Error('Invalid terminal argument envelope');
|
|
71
|
+
forwarded = JSON.parse(Buffer.from(args[1], 'base64').toString('utf8'));
|
|
72
|
+
if (!Array.isArray(forwarded) || forwarded.some(arg => typeof arg !== 'string')) throw new Error('Invalid terminal argument envelope');
|
|
73
|
+
}
|
|
74
|
+
process.exitCode = (await runSelectedCodex(file, executable, forwarded)).code;
|
|
75
|
+
}
|
|
76
|
+
catch { console.error('Could not start the selected Codex account. Check the selection in ccdeck or reinstall terminal integration.'); process.exitCode = 1; }
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { readFile, mkdir, chmod, access, stat } from 'node:fs/promises';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { basename, join, isAbsolute } from 'node:path';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { deckDataDir } from './deck-home.mjs';
|
|
9
|
+
import { codexSelectionPath } from './codex-selection.mjs';
|
|
10
|
+
import { resolveWriteTarget, writeFileAtomic } from './atomic-write.mjs';
|
|
11
|
+
import { pathLookup } from './exec-spec.mjs';
|
|
12
|
+
import { hookRuntime } from './app-host.mjs';
|
|
13
|
+
|
|
14
|
+
const BEGIN = '# >>> ccdeck Codex accounts >>>';
|
|
15
|
+
const END = '# <<< ccdeck Codex accounts <<<';
|
|
16
|
+
const quote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
17
|
+
const psQuote = value => `'${String(value).replaceAll("'", "''")}'`;
|
|
18
|
+
const psNodeMode = command => `$ccdeckPreviousNodeMode = $env:ELECTRON_RUN_AS_NODE; try { $env:ELECTRON_RUN_AS_NODE = '1'; ${command} } finally { $env:ELECTRON_RUN_AS_NODE = $ccdeckPreviousNodeMode }`;
|
|
19
|
+
const supported = new Set(['zsh', 'bash', 'powershell', 'powershell5']);
|
|
20
|
+
export const defaultCodexShell = (env = process.env, platform = process.platform) =>
|
|
21
|
+
platform === 'win32' ? 'powershell' : basename(env.SHELL ?? (platform === 'darwin' ? '/bin/zsh' : '/bin/bash'));
|
|
22
|
+
|
|
23
|
+
export function codexLoginCommand(home, platform = process.platform) {
|
|
24
|
+
if (platform === 'win32') return `$previousCodexHome = $env:CODEX_HOME; try { $env:CODEX_HOME = ${psQuote(home)}; codex login } finally { $env:CODEX_HOME = $previousCodexHome }`;
|
|
25
|
+
return `CODEX_HOME=${quote(home)} codex login`;
|
|
26
|
+
}
|
|
27
|
+
export function codexTerminalCommand(action = 'install', shell = null, platform = process.platform) {
|
|
28
|
+
shell ||= defaultCodexShell(process.env, platform);
|
|
29
|
+
if (!supported.has(shell) || !['install', 'uninstall'].includes(action)) return null;
|
|
30
|
+
const script = fileURLToPath(new URL('../../bin/codex-profile.js', import.meta.url));
|
|
31
|
+
const q = platform === 'win32' ? psQuote : quote;
|
|
32
|
+
const store = deckDataDir();
|
|
33
|
+
const rc = platform === 'win32' && shell.startsWith('powershell') ? ' --rc $PROFILE.CurrentUserAllHosts' : '';
|
|
34
|
+
const command = `${platform === 'win32' ? '& ' : ''}${q(hookRuntime())} ${q(script)} ${action} --shell ${shell} --store ${q(store)}${rc}`;
|
|
35
|
+
return platform === 'win32' ? `& { ${psNodeMode(command)} }` : `ELECTRON_RUN_AS_NODE=1 ${command}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function rcFor(shell, home, env, platform) {
|
|
39
|
+
if (shell === 'zsh') return join(env.ZDOTDIR?.trim() || home, '.zshrc');
|
|
40
|
+
if (shell === 'bash') {
|
|
41
|
+
if (platform === 'darwin') {
|
|
42
|
+
for (const file of ['.bash_profile', '.bash_login', '.profile']) {
|
|
43
|
+
const path = join(home, file);
|
|
44
|
+
try { await stat(path); return path; } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
45
|
+
}
|
|
46
|
+
return join(home, '.bash_profile');
|
|
47
|
+
}
|
|
48
|
+
return join(home, '.bashrc');
|
|
49
|
+
}
|
|
50
|
+
const executable = shell === 'powershell5' ? 'powershell.exe' : 'pwsh.exe';
|
|
51
|
+
const { stdout } = await promisify(execFile)(executable, ['-NoProfile', '-Command', '$PROFILE.CurrentUserAllHosts'], { encoding: 'utf8', timeout: 5000, maxBuffer: 4096 });
|
|
52
|
+
const rc = stdout.trim();
|
|
53
|
+
if (!isAbsolute(rc)) throw new Error('Could not locate the PowerShell profile. Supply --rc $PROFILE.CurrentUserAllHosts.');
|
|
54
|
+
return rc;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function stripIntegration(text) {
|
|
58
|
+
const start = text.indexOf(BEGIN), end = text.indexOf(END);
|
|
59
|
+
if (start < 0 && end < 0) return text;
|
|
60
|
+
if (start < 0 || end < start || text.indexOf(BEGIN, start + BEGIN.length) >= 0 || text.indexOf(END, end + END.length) >= 0) {
|
|
61
|
+
throw new Error('Terminal integration markers are incomplete. Repair the shell configuration first.');
|
|
62
|
+
}
|
|
63
|
+
return text.slice(0, start) + text.slice(end + END.length).replace(/^\r?\n/, '');
|
|
64
|
+
}
|
|
65
|
+
export async function configureCodexTerminal(action, options = {}) {
|
|
66
|
+
const env = options.env ?? process.env;
|
|
67
|
+
const platform = options.platform ?? process.platform;
|
|
68
|
+
const shell = options.shell ?? defaultCodexShell(env, platform);
|
|
69
|
+
if (!supported.has(shell) || !['install', 'uninstall'].includes(action)) throw new Error('Unsupported terminal integration');
|
|
70
|
+
const home = options.home ?? homedir();
|
|
71
|
+
const rc = options.rc ?? await rcFor(shell, home, env, platform);
|
|
72
|
+
let previous = '';
|
|
73
|
+
try { previous = await readFile(rc, 'utf8'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
74
|
+
let next = stripIntegration(previous);
|
|
75
|
+
if (action === 'install') {
|
|
76
|
+
let executable = options.executable;
|
|
77
|
+
if (!executable) {
|
|
78
|
+
for (const name of process.platform === 'win32' ? ['codex.exe', 'codex.cmd', 'codex'] : ['codex']) {
|
|
79
|
+
executable = pathLookup(name, process.platform);
|
|
80
|
+
if (executable) break;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (!executable) throw new Error('Install Codex before enabling terminal selection.');
|
|
84
|
+
await access(executable, process.platform === 'win32' ? constants.F_OK : constants.X_OK);
|
|
85
|
+
const data = options.store ?? deckDataDir(undefined, env, home);
|
|
86
|
+
const directory = join(data, 'codex-terminal');
|
|
87
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
88
|
+
for (const name of ['codex-terminal-runner.mjs', 'exec-spec.mjs']) {
|
|
89
|
+
await writeFileAtomic(join(directory, name), await readFile(new URL(`./${name}`, import.meta.url), 'utf8'));
|
|
90
|
+
await chmod(join(directory, name), 0o600);
|
|
91
|
+
}
|
|
92
|
+
const runner = join(directory, 'codex-terminal-runner.mjs');
|
|
93
|
+
const file = codexSelectionPath({ store: data });
|
|
94
|
+
const node = options.node ?? hookRuntime(env);
|
|
95
|
+
const line = shell.startsWith('powershell')
|
|
96
|
+
// Windows PowerShell's native argv conversion strips embedded quotes and
|
|
97
|
+
// empty arguments. Transport strings as JSON/base64, then spawn normally.
|
|
98
|
+
? `function global:codex { $ccdeckCodexArgs = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject ([string[]]@($args)) -Compress))); ${psNodeMode(`& ${psQuote(node)} ${psQuote(runner)} ${psQuote(file)} ${psQuote(executable)} --ccdeck-args-base64 $ccdeckCodexArgs`)} }`
|
|
99
|
+
: `codex() { ELECTRON_RUN_AS_NODE=1 command ${quote(node)} ${quote(runner)} ${quote(file)} ${quote(executable)} "$@"; }`;
|
|
100
|
+
next += `${next.endsWith('\n') || next === '' ? '' : '\n'}${BEGIN}\n${line}\n${END}\n`;
|
|
101
|
+
}
|
|
102
|
+
await mkdir(join(rc, '..'), { recursive: true });
|
|
103
|
+
const target = await resolveWriteTarget(rc);
|
|
104
|
+
await writeFileAtomic(target, next);
|
|
105
|
+
// Only the new integration files are private. Preserve the user's shell-file
|
|
106
|
+
// permissions and unrelated settings; authentication files are never opened.
|
|
107
|
+
if (action === 'install') await chmod(join(options.store ?? deckDataDir(undefined, env, home), 'codex-terminal'), 0o700);
|
|
108
|
+
return { shell, rc, action };
|
|
109
|
+
}
|