ccdeck 3.53.2 → 3.80.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.
Files changed (62) hide show
  1. package/README.md +56 -4
  2. package/THIRD_PARTY_NOTICES.md +31 -1
  3. package/dist/web/assets/{BrowserWatchModal-DedhCY8E.js → BrowserWatchModal-Bfvo_8H6.js} +1 -1
  4. package/dist/web/assets/{IntegrationModal-1m1mQQhW.js → IntegrationModal-GS5jIQ_J.js} +1 -1
  5. package/dist/web/assets/{RadioPanel-Sgo5WNTi.js → RadioPanel-Bxd2ElWb.js} +1 -1
  6. package/dist/web/assets/{TrafficRadar-BqjzLlO_.js → TrafficRadar-FgHBI2Oh.js} +1 -1
  7. package/dist/web/assets/{UsageHistoryModal-2pcftBwX.js → UsageHistoryModal-APwKtE2J.js} +1 -1
  8. package/dist/web/assets/{app-BZaB84m4.js → app-BzHVsgB2.js} +90 -90
  9. package/dist/web/assets/{index-D1WZBFCw.js → index-7whwMaPX.js} +1 -1
  10. package/dist/web/index.html +2 -2
  11. package/node_modules/ws/LICENSE +20 -0
  12. package/node_modules/ws/README.md +540 -0
  13. package/node_modules/ws/browser.js +8 -0
  14. package/node_modules/ws/index.js +22 -0
  15. package/node_modules/ws/lib/buffer-util.js +142 -0
  16. package/node_modules/ws/lib/constants.js +19 -0
  17. package/node_modules/ws/lib/event-target.js +292 -0
  18. package/node_modules/ws/lib/extension.js +203 -0
  19. package/node_modules/ws/lib/limiter.js +55 -0
  20. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  21. package/node_modules/ws/lib/receiver.js +743 -0
  22. package/node_modules/ws/lib/sender.js +610 -0
  23. package/node_modules/ws/lib/stream.js +161 -0
  24. package/node_modules/ws/lib/subprotocol.js +62 -0
  25. package/node_modules/ws/lib/validation.js +152 -0
  26. package/node_modules/ws/lib/websocket-server.js +562 -0
  27. package/node_modules/ws/lib/websocket.js +1426 -0
  28. package/node_modules/ws/package.json +74 -0
  29. package/node_modules/ws/wrapper.mjs +21 -0
  30. package/package.json +5 -3
  31. package/release-notes.json +39 -1
  32. package/src/server/account-engine.mjs +87 -0
  33. package/src/server/account-routes.mjs +31 -3
  34. package/src/server/codex-auto.mjs +7 -18
  35. package/src/server/codex-engine-adapter.mjs +272 -0
  36. package/src/server/codex-engine-bridge.mjs +47 -0
  37. package/src/server/codex-engine-config.mjs +42 -0
  38. package/src/server/codex-engine-rpc.mjs +88 -0
  39. package/src/server/codex-handoff.mjs +20 -0
  40. package/src/server/codex-interactive-engine.mjs +335 -0
  41. package/src/server/codex-live-checkpoint.mjs +55 -0
  42. package/src/server/codex-live-credentials.mjs +214 -0
  43. package/src/server/codex-live-engine.mjs +577 -0
  44. package/src/server/codex-live-handoff.mjs +300 -0
  45. package/src/server/codex-live-lease.mjs +64 -0
  46. package/src/server/codex-live-rpc.mjs +155 -0
  47. package/src/server/codex-quota.mjs +36 -2
  48. package/src/server/codex-selection.mjs +62 -8
  49. package/src/server/codex-share.mjs +193 -0
  50. package/src/server/codex-terminal-runner.mjs +38 -1
  51. package/src/server/codex-terminal.mjs +15 -3
  52. package/src/server/codex-watch.mjs +3 -1
  53. package/src/server/codex-windows-private.mjs +96 -0
  54. package/src/server/codex-windows-private.ps1 +140 -0
  55. package/src/server/codex-windows-proxy.mjs +53 -0
  56. package/src/server/deck-prefs.mjs +6 -1
  57. package/src/server/index.mjs +9 -2
  58. package/src/server/login-service.mjs +2 -0
  59. package/src/server/pinned-build.mjs +2 -0
  60. package/src/server/reports-routes.mjs +10 -0
  61. package/src/server/reports.mjs +46 -5
  62. package/src/server/ui-language.mjs +17 -0
@@ -27,7 +27,7 @@ export function codexSelectionError(code) {
27
27
  const fail = code => { throw codexSelectionError(code); };
28
28
  const idPattern = /^[a-f0-9]{20}$/;
29
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']);
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', 'import_write_failed', 'windows_permissions_failed']);
31
31
  const storeDir = options => resolve(options.store ?? deckDataDir(options.platform, options.env, options.home));
32
32
  export const codexSelectionPath = (options = {}) => join(storeDir(options), 'codex-accounts.json');
33
33
 
@@ -48,6 +48,7 @@ async function validate(state, options) {
48
48
  const ids = new Set();
49
49
  for (const p of state.profiles) {
50
50
  if (!p || typeof p.id !== 'string' || !idPattern.test(p.id) || ids.has(p.id) || typeof p.home !== 'string' || !path.isAbsolute(p.home)
51
+ || (p.importFingerprint !== undefined && (!p.managed || !/^[a-f0-9]{64}$/.test(p.importFingerprint)))
51
52
  || typeof p.managed !== 'boolean' || !(p.label === null || validLabel(p.label))) fail('registry_corrupt');
52
53
  ids.add(p.id);
53
54
  if (p.managed) {
@@ -62,11 +63,14 @@ async function validate(state, options) {
62
63
  if (await directoryExists(p.home) && await codexProfileId(p.home) !== p.id) fail('profile_unavailable');
63
64
  }
64
65
  if (!state.profiles.some(p => p.home === state.originalHome) || !ids.has(state.selectedProfileId)) fail('registry_corrupt');
66
+ if (state.runningSelection != null && (!ids.has(state.runningSelection.id) || !Number.isSafeInteger(state.runningSelection.revision)
67
+ || state.runningSelection.revision < 1 || state.runningSelection.revision > state.revision)) fail('registry_corrupt');
65
68
  const operations = new Set();
66
69
  for (const op of state.operations) {
67
70
  if (!op || typeof op.operationId !== 'string' || !operationPattern.test(op.operationId) || operations.has(op.operationId)
68
71
  || !['add', 'select'].includes(op.kind) || !ids.has(op.id) || !Number.isSafeInteger(op.revision)
69
72
  || op.revision < 1 || op.revision > state.revision
73
+ || (op.switchRunning !== undefined && typeof op.switchRunning !== 'boolean')
70
74
  || (op.kind === 'select' && (!Number.isSafeInteger(op.expectedRevision) || op.expectedRevision < 0))
71
75
  || (op.kind === 'add' && !(op.label === null || validLabel(op.label)))) fail('registry_corrupt');
72
76
  operations.add(op.operationId);
@@ -104,9 +108,9 @@ async function snapshot(state, options) {
104
108
  })));
105
109
  // Absence is a recoverable state, not permission to choose another account.
106
110
  return {
107
- home, profileId: state?.selectedProfileId ?? await codexProfileId(home),
111
+ home, originalHome: state?.originalHome ?? homes[0], profileId: state?.selectedProfileId ?? await codexProfileId(home),
108
112
  revision: state?.revision ?? 0, selectionEnabled: state !== null,
109
- available: await directoryExists(home), homes, profiles,
113
+ available: await directoryExists(home), homes, profiles, runningSelection: state?.runningSelection ?? null,
110
114
  managedProfiles: (state?.profiles ?? []).filter(p => p.managed).map(({ id, label }) => ({ id, label })),
111
115
  /** The name somebody gave each account, the deck's own or not. */
112
116
  profileLabels: (state?.profiles ?? []).filter(p => p.label).map(({ id, label }) => ({ id, label })),
@@ -218,14 +222,15 @@ function replay(state, operationId, kind, matches) {
218
222
  if (op && (op.kind !== kind || !matches(op))) fail('operation_conflict');
219
223
  return op;
220
224
  }
221
- export async function selectCodexProfile({ id, expectedRevision, operationId: operation } = {}, options = {}) {
225
+ export async function selectCodexProfile({ id, expectedRevision, operationId: operation, switchRunning = false } = {}, options = {}) {
222
226
  operationId(operation);
227
+ if (typeof switchRunning !== 'boolean') fail('invalid_operation');
223
228
  if (typeof id !== 'string' || !idPattern.test(id)) fail('unknown_profile');
224
229
  if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) fail('invalid_revision');
225
230
  return locked(options, async () => {
226
231
  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' };
232
+ if (replay(state, operation, 'select', o => o.id === id && o.expectedRevision === expectedRevision && !!o.switchRunning === switchRunning)) {
233
+ return { ...await snapshot(state, options), status: switchRunning ? 'requested_for_managed_sessions' : 'applied_for_new_sessions' };
229
234
  }
230
235
  if (state.revision !== expectedRevision) fail('selection_conflict');
231
236
  const homes = await homesFor(state, options);
@@ -236,10 +241,11 @@ export async function selectCodexProfile({ id, expectedRevision, operationId: op
236
241
  if (!state.profiles.some(p => p.id === id)) state.profiles.push({ id, home, label: null, managed: false });
237
242
  state.selectedProfileId = id;
238
243
  state.revision++;
239
- state.operations.push({ operationId: operation, kind: 'select', id, expectedRevision, revision: state.revision });
244
+ state.operations.push({ operationId: operation, kind: 'select', id, expectedRevision, revision: state.revision, ...(switchRunning ? { switchRunning } : {}) });
245
+ if (switchRunning) state.runningSelection = { id, revision: state.revision };
240
246
  const result = await snapshot(state, options);
241
247
  await persist(state, options);
242
- return { ...result, status: 'applied_for_new_sessions' };
248
+ return { ...result, status: switchRunning ? 'requested_for_managed_sessions' : 'applied_for_new_sessions' };
243
249
  });
244
250
  }
245
251
  /** Add an account this deck keeps the home of. The name is optional: without
@@ -318,6 +324,7 @@ export async function removeCodexProfile({ id, expectedRevision } = {}, options
318
324
  async function dropProfile(state, profile, options) {
319
325
  const { id } = profile;
320
326
  state.profiles = state.profiles.filter(p => p.id !== id);
327
+ if (state.runningSelection?.id === id) delete state.runningSelection;
321
328
  // What this profile's add and select left behind would name a profile that
322
329
  // is gone, which the registry's own check refuses.
323
330
  state.operations = state.operations.filter(op => op.id !== id);
@@ -369,3 +376,50 @@ export async function moveCodexLogin({ id, into, expectedRevision } = {}, option
369
376
  return { ...await dropProfile(state, profile, options), status: 'replaced' };
370
377
  });
371
378
  }
379
+
380
+ /** Register a prepared batch under the same lock as account selection. The
381
+ * callback creates and writes only fresh, empty managed homes. No existing home is
382
+ * passed to it, including on retries. Only credential fingerprints persist in
383
+ * metadata; the registry never receives auth contents. */
384
+ export async function importCodexProfiles({ entries, expectedRevision }, prepareHome, options = {}) {
385
+ if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) fail('invalid_revision');
386
+ if (!Array.isArray(entries) || entries.length < 1 || entries.length > 20
387
+ || entries.some(e => !e || !/^[a-f0-9]{64}$/.test(e.fingerprint) || !(e.label === null || validLabel(e.label)))) fail('invalid_operation');
388
+ return locked(options, async () => {
389
+ const state = await initial(options);
390
+ const existing = fingerprint => state.profiles.find(p => p.importFingerprint === fingerprint);
391
+ // A fully repeated import is safe even if the caller lost the reply or
392
+ // another operation has since changed the selection revision.
393
+ if (entries.some(e => !existing(e.fingerprint)) && state.revision !== expectedRevision) fail('selection_conflict');
394
+ const made = [], results = [], guards = [];
395
+ try {
396
+ for (let index = 0; index < entries.length; index++) {
397
+ const entry = entries[index], previous = existing(entry.fingerprint);
398
+ if (previous) {
399
+ if (!await directoryExists(previous.home)) fail('profile_unavailable');
400
+ results.push({ id: previous.id, status: 'already_imported' }); continue;
401
+ }
402
+ const root = join(storeDir(options), 'codex-profiles');
403
+ await mkdir(root, { recursive: true, mode: 0o700 });
404
+ if (!(await lstat(root)).isDirectory()) fail('registry_corrupt');
405
+ const home = join(root, randomBytes(16).toString('hex'));
406
+ // The preparer creates the home: on Windows it needs an atomic
407
+ // protected DACL at creation, which mkdir(mode) cannot provide.
408
+ made.push(home);
409
+ const guard = await prepareHome(home, index);
410
+ if (guard) guards.push(guard);
411
+ const id = await codexProfileId(home);
412
+ state.profiles.push({ id, home, label: entry.label, managed: true, importFingerprint: entry.fingerprint });
413
+ results.push({ id, status: 'imported' });
414
+ }
415
+ if (guards.some(guard => !guard.valid())) fail('windows_permissions_failed');
416
+ if (made.length) { state.revision++; await persist(state, options); }
417
+ return { revision: state.revision, results };
418
+ } catch (error) {
419
+ for (const guard of guards) await guard.release();
420
+ // None of these homes was registered if preparation or commit failed.
421
+ await Promise.all(made.map(home => rm(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })));
422
+ throw error;
423
+ } finally { for (const guard of guards) await guard.release(); }
424
+ });
425
+ }
@@ -0,0 +1,193 @@
1
+ // Explicit, portable file-auth transfer. This is encoding, not encryption:
2
+ // possession of the code grants the same login as possession of auth.json.
3
+ // No expiry, revocation, JWT verification, refresh, native login or network I/O.
4
+ import { createHash } from 'node:crypto';
5
+ import { constants } from 'node:fs';
6
+ import { chmod, lstat, mkdir, open, readFile, unlink } from 'node:fs/promises';
7
+ import { join } from 'node:path';
8
+ import { createTemp, renameWithRetry } from './atomic-write.mjs';
9
+ import { readCodexSelection, importCodexProfiles } from './codex-selection.mjs';
10
+ import { ensureWindowsPrivateDirectory, holdWindowsPrivatePath } from './codex-windows-private.mjs';
11
+
12
+ export const CODEX_SHARE_PREFIX = 'ccdeck-codex-v1.';
13
+ export const CODEX_SHARE_MAX_LENGTH = 512_000;
14
+ export const CODEX_SHARE_MAX_ACCOUNTS = 20;
15
+ const AUTH_MAX_BYTES = 32_000;
16
+ const fail = code => { throw Object.assign(new Error(code), { code }); };
17
+ const object = value => value && typeof value === 'object' && !Array.isArray(value);
18
+ const keys = (value, allowed) => object(value) && Object.keys(value).every(key => allowed.includes(key));
19
+ const token = value => typeof value === 'string' && value.length > 0 && value.length <= 16_000 && /^[\x21-\x7e]+$/.test(value);
20
+ const safeLabel = value => value === null || (typeof value === 'string' && value.length > 0 && value.length <= 80 && value === value.trim() && !/[\x00-\x1f\x7f/\\]/.test(value));
21
+
22
+ function oauthProvenance(value) {
23
+ if (value === undefined || value === null) return true;
24
+ if (!keys(value, ['issuer', 'client_id']) || !token(value.issuer) || value.issuer.length > 2048
25
+ || !token(value.client_id) || value.client_id.length > 512) return false;
26
+ // Codex uses this issuer as the refresh destination, not just display data.
27
+ // Transfer only HTTPS OpenAI authorities; never infer one from JWT claims.
28
+ try {
29
+ const issuer = new URL(value.issuer);
30
+ return issuer.protocol === 'https:' && !issuer.username && !issuer.password && !issuer.port
31
+ && !/[?#\\]/.test(value.issuer)
32
+ && ['openai.com', 'chatgpt.com'].some(host => issuer.hostname === host || issuer.hostname.endsWith(`.${host}`));
33
+ } catch { return false; }
34
+ }
35
+
36
+ /** Whitelist the on-disk ChatGPT schema, never source paths/config/extra keys.
37
+ * Token strings stay opaque; a decoded JWT is never proof of identity. */
38
+ function chatgptAuth(raw) {
39
+ if (!keys(raw, ['auth_mode', 'OPENAI_API_KEY', 'tokens', 'last_refresh'])
40
+ || (raw.auth_mode !== undefined && raw.auth_mode !== 'chatgpt')
41
+ || (raw.OPENAI_API_KEY !== undefined && raw.OPENAI_API_KEY !== null)
42
+ || !keys(raw.tokens, ['access_token', 'refresh_token', 'id_token', 'account_id', 'oauth_provenance', 'login_owner_id'])
43
+ || !['access_token', 'refresh_token', 'id_token'].every(key => token(raw.tokens[key]))
44
+ || !oauthProvenance(raw.tokens.oauth_provenance)
45
+ || (raw.tokens.login_owner_id != null && (typeof raw.tokens.login_owner_id !== 'string' || !/^[A-Za-z0-9_-]{1,512}$/.test(raw.tokens.login_owner_id)))
46
+ || (raw.tokens.account_id !== undefined && (!token(raw.tokens.account_id) || raw.tokens.account_id.length > 512))
47
+ || (raw.last_refresh !== undefined && (typeof raw.last_refresh !== 'string' || raw.last_refresh.length > 40 || !Number.isFinite(Date.parse(raw.last_refresh))))) fail('unsupported_auth');
48
+ // Codex 0.166 TokenData preserves these optional fields across refreshes.
49
+ // login_owner_id identifies a completed login, not a machine: preserve it
50
+ // with its grant rather than generating a new login or dropping provenance.
51
+ // Schema/semantics: openai/codex rust-v0.166.0 (6ff1e1ca), login/src/token_data.rs,
52
+ // server.rs and auth/{account_grant,manager}.rs. Legacy fields stay absent.
53
+ const auth = { auth_mode: 'chatgpt', OPENAI_API_KEY: null, tokens: { ...raw.tokens }, ...(raw.last_refresh !== undefined ? { last_refresh: raw.last_refresh } : {}) };
54
+ if (Buffer.byteLength(JSON.stringify(auth)) > AUTH_MAX_BYTES) fail('unsupported_auth');
55
+ return auth;
56
+ }
57
+
58
+ function privateAuthFile(info, platform) {
59
+ if (!info.isFile() || info.size > AUTH_MAX_BYTES || info.nlink !== 1
60
+ || (platform !== 'win32' && (typeof process.getuid !== 'function' || info.uid !== process.getuid() || (info.mode & 0o7777 & ~0o600) !== 0))) fail('file_auth_required');
61
+ }
62
+ const unchangedFile = (a, b) => a.ino === b.ino && a.dev === b.dev && a.size === b.size
63
+ && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs && a.mode === b.mode && a.uid === b.uid && a.nlink === b.nlink;
64
+
65
+ /** Conservative store detection, NOT a TOML parser. Profiles/dotted keys,
66
+ * duplicates, multiline strings and escaped key spellings are ambiguous.
67
+ * Only absent/default or one literal root-level file setting is exportable. */
68
+ function requireFileStore(config) {
69
+ if (/'''|"""/.test(config)) fail('file_auth_required');
70
+ let section = false, seen = false;
71
+ for (const line of config.split('\n')) {
72
+ const trimmed = line.trim();
73
+ if (!trimmed || trimmed.startsWith('#')) continue;
74
+ if (trimmed.startsWith('[')) { section = true; continue; }
75
+ const key = line.split('=')[0];
76
+ if (key.includes('\\')) fail('file_auth_required');
77
+ if (!key.includes('cli_auth_credentials_store')) continue;
78
+ if (section || seen || !/^\s*(?:cli_auth_credentials_store|["']cli_auth_credentials_store["'])\s*=\s*["']file["']\s*(?:#.*)?$/.test(line)) fail('file_auth_required');
79
+ seen = true;
80
+ }
81
+ }
82
+
83
+ async function readFileAuth(home, options) {
84
+ const platform = options.platform ?? process.platform;
85
+ let handle, guard;
86
+ try {
87
+ // A non-file store can leave a stale auth.json behind. Never export that
88
+ // stale copy as if it were the actual native login. Unknown TOML is refused.
89
+ let config = '';
90
+ try {
91
+ const file = join(home, 'config.toml');
92
+ if ((await lstat(file)).size > 128_000) fail('unsupported_auth');
93
+ config = await readFile(file, 'utf8');
94
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
95
+ requireFileStore(config);
96
+ const file = join(home, 'auth.json');
97
+ if (platform === 'win32') guard = await holdWindowsPrivatePath(file, { ...options, kind: 'file' });
98
+ const before = await lstat(file);
99
+ privateAuthFile(before, platform);
100
+ handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
101
+ const opened = await handle.stat();
102
+ privateAuthFile(opened, platform);
103
+ if (!unchangedFile(opened, before)) fail('file_auth_required');
104
+ // Bounded even if the file grows after stat.
105
+ const bytes = Buffer.alloc(AUTH_MAX_BYTES + 1);
106
+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
107
+ const after = await handle.stat(), pathAfter = await lstat(file);
108
+ privateAuthFile(after, platform);
109
+ if (bytesRead > AUTH_MAX_BYTES || bytesRead !== opened.size || !unchangedFile(opened, after) || !unchangedFile(opened, pathAfter)) fail('file_auth_required');
110
+ if (guard && !guard.valid()) fail('file_auth_required');
111
+ return chatgptAuth(JSON.parse(bytes.subarray(0, bytesRead).toString('utf8')));
112
+ } catch (error) {
113
+ if (['file_auth_required', 'unsupported_auth'].includes(error.code)) throw error;
114
+ fail('file_auth_required');
115
+ } finally { try { await handle?.close(); } finally { await guard?.release(); } }
116
+ }
117
+
118
+ /** Called only by explicit POST export, against opaque registered profile IDs. */
119
+ export async function createCodexShare({ ids } = {}, options = {}) {
120
+ if (!Array.isArray(ids) || ids.length < 1 || ids.length > CODEX_SHARE_MAX_ACCOUNTS
121
+ || new Set(ids).size !== ids.length || ids.some(id => typeof id !== 'string' || !/^[a-f0-9]{20}$/.test(id))) fail('invalid_profiles');
122
+ const selection = await readCodexSelection(options);
123
+ const profiles = ids.map(id => selection.profiles.find(profile => profile.id === id));
124
+ if (profiles.some(profile => !profile)) fail('unknown_profile');
125
+ const accounts = [];
126
+ for (const profile of profiles) {
127
+ const label = selection.profileLabels.find(entry => entry.id === profile.id)?.label ?? null;
128
+ accounts.push({ label, auth: await readFileAuth(profile.home, options) });
129
+ }
130
+ const blob = CODEX_SHARE_PREFIX + Buffer.from(JSON.stringify({ version: 1, provider: 'codex', accounts })).toString('base64url');
131
+ if (blob.length > CODEX_SHARE_MAX_LENGTH) fail('share_too_large');
132
+ return { ok: true, blob, count: accounts.length };
133
+ }
134
+
135
+ function parseShare(blob) {
136
+ if (typeof blob !== 'string' || blob.length > CODEX_SHARE_MAX_LENGTH) fail('invalid_share');
137
+ const code = blob.trim();
138
+ if (!code.startsWith(CODEX_SHARE_PREFIX)) fail('invalid_share');
139
+ const encoded = code.slice(CODEX_SHARE_PREFIX.length);
140
+ if (!/^[A-Za-z0-9_-]+$/.test(encoded)) fail('invalid_share');
141
+ let payload;
142
+ try {
143
+ const decoded = Buffer.from(encoded, 'base64url');
144
+ if (decoded.toString('base64url') !== encoded) fail('invalid_share');
145
+ payload = JSON.parse(decoded.toString('utf8'));
146
+ } catch { fail('invalid_share'); }
147
+ if (!keys(payload, ['version', 'provider', 'accounts']) || payload.version !== 1 || payload.provider !== 'codex'
148
+ || !Array.isArray(payload.accounts) || payload.accounts.length < 1 || payload.accounts.length > CODEX_SHARE_MAX_ACCOUNTS) fail('invalid_share');
149
+ return payload.accounts.map(entry => {
150
+ if (!keys(entry, ['label', 'auth']) || !safeLabel(entry.label)) fail('invalid_share');
151
+ const auth = chatgptAuth(entry.auth);
152
+ // Exact credential dedup only. No unsigned JWT claim is used as authority
153
+ // to replace another account's login or suppress a different credential.
154
+ const fingerprint = createHash('sha256').update(auth.tokens.refresh_token).digest('hex');
155
+ return { label: entry.label, auth, fingerprint };
156
+ });
157
+ }
158
+
159
+ /** The common Windows helper creates the directory with its protected DACL
160
+ * atomically. Never stage a secret into a directory created by plain mkdir on
161
+ * Windows; chmod there controls read-only, not confidentiality. */
162
+ export async function secureCodexImportHome(home, options = {}) {
163
+ if ((options.platform ?? process.platform) !== 'win32') { await mkdir(home, { mode: 0o700 }); return; }
164
+ try { await ensureWindowsPrivateDirectory(home, options); }
165
+ catch { fail('windows_permissions_failed'); }
166
+ }
167
+
168
+ export async function importCodexShare({ blob, expectedRevision } = {}, options = {}) {
169
+ const entries = parseShare(blob); // validate the entire batch before touching disk
170
+ const metadata = entries.map(({ label, fingerprint }) => ({ label, fingerprint }));
171
+ const result = await importCodexProfiles({ entries: metadata, expectedRevision }, async (home, index) => {
172
+ let tmp, guard;
173
+ try {
174
+ await secureCodexImportHome(home, options);
175
+ if ((options.platform ?? process.platform) === 'win32') guard = await holdWindowsPrivatePath(home, { ...options, kind: 'directory' });
176
+ const target = join(home, 'auth.json');
177
+ const staged = await createTemp(target, { mode: 0o600 });
178
+ tmp = staged.tmp;
179
+ try { await staged.handle.writeFile(JSON.stringify(entries[index].auth) + '\n'); await staged.handle.sync(); }
180
+ finally { await staged.handle.close(); }
181
+ await chmod(tmp, 0o600);
182
+ await renameWithRetry(tmp, target);
183
+ // Keep the Windows directory pinned until the registry commit completes.
184
+ return guard;
185
+ } catch (error) {
186
+ await guard?.release();
187
+ if (tmp) await unlink(tmp).catch(() => {});
188
+ if (error.code === 'windows_permissions_failed' || error.code === 'windows_private_path_unsafe') fail('windows_permissions_failed');
189
+ fail('import_write_failed');
190
+ }
191
+ }, options);
192
+ return { ok: true, ...result };
193
+ }
@@ -1,4 +1,4 @@
1
- // Copied with exec-spec.mjs into the durable terminal integration directory.
1
+ // Copied with its engine dependencies into the durable terminal integration directory.
2
2
  // No dependency on an npx cache, running server, or OAuth credential store.
3
3
  import { readFile, realpath, stat } from 'node:fs/promises';
4
4
  import { createHash } from 'node:crypto';
@@ -39,6 +39,43 @@ export async function terminalCodexHome(file, env = process.env) {
39
39
 
40
40
  export async function runSelectedCodex(file, executable, args, { env = process.env } = {}) {
41
41
  const home = await terminalCodexHome(file, env);
42
+ // Explicit account pins and ordinary interactive/utility commands retain the
43
+ // existing path. Only supervised exec JSON sessions opt into continuation.
44
+ if (home && !env.CODEX_HOME?.trim()) {
45
+ const { createCodexEngineAdapter } = await import('./codex-engine-adapter.mjs');
46
+ if (process.stdin.isTTY && process.stdout.isTTY) {
47
+ const { codexInteractiveInvocation, supportsCodexInteractiveEngine, runInteractiveCodex } = await import('./codex-interactive-engine.mjs');
48
+ const policy = createCodexEngineAdapter(file, executable, ['exec', '--json'], home, { env });
49
+ if (codexInteractiveInvocation(args) && !(await policy.settings()).custom && await supportsCodexInteractiveEngine(executable, env)) {
50
+ return runInteractiveCodex(file, executable, args, home, { env });
51
+ }
52
+ }
53
+ const adapter = createCodexEngineAdapter(file, executable, args, home, { env });
54
+ if (adapter && (await adapter.settings()).enabled) {
55
+ const { runAccountEngine } = await import('./account-engine.mjs');
56
+ const controller = new AbortController();
57
+ const cancel = () => controller.abort();
58
+ process.on('SIGINT', cancel);
59
+ process.on('SIGTERM', cancel);
60
+ process.on('SIGHUP', cancel);
61
+ try {
62
+ const id = createHash('sha256').update(await realpath(home)).digest('hex').slice(0, 20);
63
+ const result = await runAccountEngine(adapter, { id, home, args, threadId: adapter.invocation.threadId }, {
64
+ signal: controller.signal,
65
+ onSwitch: () => process.stderr.write('ccdeck: continuing this Codex conversation on another account.\n'),
66
+ });
67
+ if (result.code !== 0 && ['handoff_failed', 'no_account_with_room', 'thread_changed', 'attempt_limit'].includes(result.reason)) {
68
+ process.stderr.write(`ccdeck: automatic continuation stopped (${result.reason}); reopen this conversation manually.\n`);
69
+ }
70
+ return result;
71
+ } finally {
72
+ await adapter.close();
73
+ process.removeListener('SIGINT', cancel);
74
+ process.removeListener('SIGTERM', cancel);
75
+ process.removeListener('SIGHUP', cancel);
76
+ }
77
+ }
78
+ }
42
79
  const spec = spawnSpec(executable, args);
43
80
  const child = spawn(spec.file, spec.args, { ...spec.opts, stdio: 'inherit', env: home ? { ...env, CODEX_HOME: home } : env });
44
81
  // Terminal Ctrl+C already reaches both processes. Keep the wrapper alive
@@ -1,6 +1,7 @@
1
- import { readFile, mkdir, chmod, access, stat } from 'node:fs/promises';
1
+ import { createRequire } from 'node:module';
2
+ import { readFile, mkdir, chmod, access, stat, cp } from 'node:fs/promises';
2
3
  import { constants } from 'node:fs';
3
- import { basename, join, isAbsolute } from 'node:path';
4
+ import { basename, dirname, join, isAbsolute } from 'node:path';
4
5
  import { homedir } from 'node:os';
5
6
  import { execFile } from 'node:child_process';
6
7
  import { promisify } from 'node:util';
@@ -85,10 +86,21 @@ export async function configureCodexTerminal(action, options = {}) {
85
86
  const data = options.store ?? deckDataDir(undefined, env, home);
86
87
  const directory = join(data, 'codex-terminal');
87
88
  await mkdir(directory, { recursive: true, mode: 0o700 });
88
- for (const name of ['codex-terminal-runner.mjs', 'exec-spec.mjs']) {
89
+ // Keep Node's package lookup inside the durable helper. An unrelated
90
+ // package.json above the data directory must not prevent startup.
91
+ const manifest = join(directory, 'package.json');
92
+ await writeFileAtomic(manifest, JSON.stringify({ private: true, type: 'module' }) + '\n');
93
+ await chmod(manifest, 0o600);
94
+ for (const name of ['codex-terminal-runner.mjs', 'exec-spec.mjs', 'account-engine.mjs', 'codex-engine-adapter.mjs', 'codex-handoff.mjs',
95
+ 'codex-interactive-engine.mjs', 'codex-engine-config.mjs', 'codex-engine-rpc.mjs', 'codex-engine-bridge.mjs',
96
+ 'codex-auto.mjs', 'codex-selection.mjs', 'codex-profiles.mjs', 'codex-native-account.mjs',
97
+ 'codex-auth.mjs', 'codex-dir.mjs', 'deck-home.mjs', 'claude-dir.mjs', 'atomic-write.mjs', 'brand.mjs', 'exec-children.mjs']) {
89
98
  await writeFileAtomic(join(directory, name), await readFile(new URL(`./${name}`, import.meta.url), 'utf8'));
90
99
  await chmod(join(directory, name), 0o600);
91
100
  }
101
+ // Keep the RFC6455 implementation and its MIT notice with the durable helper.
102
+ const wsPackage = dirname(createRequire(import.meta.url).resolve('ws/package.json'));
103
+ await cp(wsPackage, join(directory, 'node_modules', 'ws'), { recursive: true, force: true });
92
104
  const runner = join(directory, 'codex-terminal-runner.mjs');
93
105
  const file = codexSelectionPath({ store: data });
94
106
  const node = options.node ?? hookRuntime(env);
@@ -8,6 +8,7 @@
8
8
  // cwd and the chunked reader from the modules that own them — nothing here
9
9
  // reads the ring or the SSE clients. index.mjs starts the watcher. The bodies
10
10
  // are unchanged.
11
+ import { codexHandoffOffset } from './codex-handoff.mjs';
11
12
  import { stat, readdir } from "node:fs/promises";
12
13
  import { basename, dirname, join } from "node:path";
13
14
  import { PRODUCT } from "./brand.mjs";
@@ -361,7 +362,8 @@ async function openCodexCursor(path, st, now, firstRun, recover = false) {
361
362
  // UsageObserved in the file to every tab, and re-appending the lot to
362
363
  // the shared events.jsonl if this deck is the elected writer (#981).
363
364
  const fresh = !codexSeenEver.has(path);
364
- const state = { offset: fresh ? 0 : st.size, sid: header.sid, cwd: header.cwd, link: header.link, skip: false, sawBeginning: fresh, rootOpened: false, seenAt: now, path };
365
+ const copiedPrefix = fresh ? await codexHandoffOffset(path, header.sid, st.size) : 0;
366
+ const state = { offset: fresh ? copiedPrefix : st.size, sid: header.sid, cwd: header.cwd, link: header.link, skip: false, sawBeginning: fresh && copiedPrefix === 0, rootOpened: false, seenAt: now, path };
365
367
  codexFileState.set(path, state);
366
368
  rememberCodexPath(path);
367
369
  if (firstRun) {
@@ -0,0 +1,96 @@
1
+ // Windows has no POSIX UID/O_NOFOLLOW contract. The fixed PowerShell helper
2
+ // checks the current token SID and a handle's DACL, never path-supplied code.
3
+ import { execFile, spawn } from 'node:child_process';
4
+ import { promisify } from 'node:util';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { win32 } from 'node:path';
7
+
8
+ const runFile = promisify(execFile);
9
+ const helper = fileURLToPath(new URL('./codex-windows-private.ps1', import.meta.url));
10
+ const unsafe = () => Object.assign(new Error('windows_private_path_unsafe'), { code: 'windows_private_path_unsafe' });
11
+ // The first Windows PowerShell invocation compiles the fixed Win32 helper.
12
+ // Compilation on a contended Windows host can exceed ten seconds. This only
13
+ // bounds helper startup; the ACL/reparse checks and native RPC limits stay intact.
14
+ const deadline = options => Math.max(1, Math.min(30000, options.timeoutMs ?? 30000));
15
+ function command(path, operation, options) {
16
+ if ((options.platform ?? process.platform) !== 'win32' || typeof path !== 'string'
17
+ || !/^(?:[a-z]:\\|\\\\\?\\[a-z]:\\)/i.test(path) || /[\x00-\x1f"<>|]/.test(path)
18
+ || path.replace(/^\\\\\?\\/, '').slice(2).includes(':')) throw unsafe();
19
+ const kind = options.kind ?? 'directory';
20
+ if (!['directory', 'file', 'socket'].includes(kind)) throw unsafe();
21
+ // Use the OS copy, not a powershell.exe supplied by PATH or the profile cwd.
22
+ const root = process.env.SystemRoot ?? 'C:\\Windows';
23
+ return { file: win32.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
24
+ args: ['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', helper,
25
+ '-Operation', operation, '-TargetPath', path, '-Kind', kind] };
26
+ }
27
+ function result(stdout) {
28
+ const value = JSON.parse(stdout.replace(/^\uFEFF/, '').trim());
29
+ if (typeof value.path !== 'string' || !value.path || value.path.includes('\0')) throw unsafe();
30
+ return value;
31
+ }
32
+ async function check(path, operation, options) {
33
+ try {
34
+ const spec = command(path, operation, options);
35
+ const output = await (options.execFile ?? runFile)(spec.file, spec.args,
36
+ { timeout: deadline(options), maxBuffer: 16 * 1024, windowsHide: true, shell: false });
37
+ return result(output.stdout);
38
+ } catch { throw unsafe(); }
39
+ }
40
+ /** Create with a protected inheritable current-user DACL atomically. Existing
41
+ * directories must already be private; their permissions are never repaired.
42
+ * execFile is an async (file, args, options) => { stdout } test seam.
43
+ */
44
+ export const ensureWindowsPrivateDirectory = async (path, options = {}) => (await check(path, 'ensure', { ...options, kind: 'directory' })).path;
45
+ export const assertWindowsPrivatePath = async (path, options = {}) => (await check(path, 'check', options)).path;
46
+ export async function inspectWindowsPrivateSocket(path, options = {}) {
47
+ const value = await check(path, 'check', { ...options, kind: 'socket' });
48
+ if (typeof value.generation !== 'string' || !/^\d+(?::\d+){4}$/.test(value.generation)) throw unsafe();
49
+ return value;
50
+ }
51
+
52
+ /** Pin the checked directory (and a regular file, when requested) until release.
53
+ * The helper holds handles without FILE_SHARE_DELETE; file guards also exclude
54
+ * writers. A bounded startup and lifetime prevent abandoned helpers lingering.
55
+ */
56
+ export async function holdWindowsPrivatePath(path, options = {}) {
57
+ let child;
58
+ try {
59
+ const spec = command(path, 'hold', options);
60
+ child = (options.spawnChild ?? spawn)(spec.file, spec.args, { windowsHide: true, shell: false, stdio: ['pipe', 'pipe', 'ignore'] });
61
+ let alive = true;
62
+ child.on('exit', () => { alive = false; });
63
+ child.on('error', () => { alive = false; });
64
+ child.stdin.on('error', () => {});
65
+ const captured = await new Promise((ready, reject) => {
66
+ let output = '';
67
+ const timer = setTimeout(() => reject(unsafe()), deadline(options));
68
+ const finish = fn => value => { clearTimeout(timer); fn(value); };
69
+ child.once('error', finish(() => reject(unsafe())));
70
+ child.once('exit', finish(() => reject(unsafe())));
71
+ child.stdout.on('data', data => {
72
+ output += data.toString('utf8');
73
+ if (output.length > 16 * 1024) { clearTimeout(timer); reject(unsafe()); }
74
+ else if (output.includes('\n')) {
75
+ try { finish(ready)(result(output)); } catch { finish(reject)(unsafe()); }
76
+ }
77
+ });
78
+ });
79
+ let released = false, expired = false, releasing;
80
+ const release = () => {
81
+ if (released) return releasing;
82
+ released = true; clearTimeout(lifetime);
83
+ releasing = new Promise(resolve => {
84
+ if (child.exitCode !== null || child.signalCode !== null) { resolve(); return; }
85
+ const timer = setTimeout(resolve, 2000);
86
+ child.once('exit', () => { clearTimeout(timer); resolve(); });
87
+ child.stdin.destroy(); child.kill();
88
+ });
89
+ return releasing;
90
+ };
91
+ // Covers cold native startup and the subsequent bounded ACL rechecks.
92
+ const lifetime = setTimeout(() => { expired = true; release(); }, 120000); lifetime.unref();
93
+ return { path: captured.path, generation: captured.generation, valid: () => alive && !released && !expired && child.exitCode === null && child.signalCode === null,
94
+ release };
95
+ } catch { child?.stdin?.destroy(); child?.kill(); throw unsafe(); }
96
+ }