ccdeck 3.81.3 → 3.82.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 (29) hide show
  1. package/README.md +32 -17
  2. package/bin/cli/help.js +3 -2
  3. package/bin/cli/tui.js +3 -1
  4. package/bin/cli/uninstall.js +19 -0
  5. package/dist/web/assets/{BrowserWatchModal-CtzXOp5j.js → BrowserWatchModal-lX2W_tSy.js} +1 -1
  6. package/dist/web/assets/{IntegrationModal-DxRO6C3V.js → IntegrationModal-oMFIAY4f.js} +1 -1
  7. package/dist/web/assets/{RadioPanel-BXXsKLiL.js → RadioPanel-DLiI3_Ok.js} +1 -1
  8. package/dist/web/assets/{TrafficRadar-CcCdZ-Tp.js → TrafficRadar-D2JAXMid.js} +1 -1
  9. package/dist/web/assets/{UsageHistoryModal-DOZTQtT2.js → UsageHistoryModal-DTJc1c1C.js} +1 -1
  10. package/dist/web/assets/{app-BWU-3pHs.js → app-BK08kq7X.js} +88 -88
  11. package/dist/web/assets/{index-A7xHctiv.js → index-B3icWRJZ.js} +1 -1
  12. package/dist/web/index.html +2 -2
  13. package/package.json +1 -1
  14. package/release-notes.json +58 -8
  15. package/src/server/codex-live-credentials.mjs +34 -6
  16. package/src/server/codex-live-engine.mjs +33 -11
  17. package/src/server/codex-live-rpc.mjs +13 -2
  18. package/src/server/codex-selection.mjs +4 -1
  19. package/src/server/codex-terminal.mjs +75 -2
  20. package/src/server/codex-windows-private.mjs +10 -0
  21. package/src/server/codex-windows-private.ps1 +53 -2
  22. package/src/server/deck-client.mjs +9 -1
  23. package/src/server/event-routes.mjs +8 -1
  24. package/src/server/feature-use.mjs +45 -0
  25. package/src/server/index.mjs +7 -2
  26. package/src/server/lan-about.mjs +7 -15
  27. package/src/server/os-version.mjs +57 -0
  28. package/src/server/reports.mjs +163 -13
  29. package/src/server/usage-day.mjs +35 -2
@@ -1 +1 @@
1
- import"./app-BWU-3pHs.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))i(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function s(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerPolicy&&(r.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?r.credentials="include":e.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(e){if(e.ep)return;e.ep=!0;const r=s(e);fetch(e.href,r)}})();
1
+ import"./app-BK08kq7X.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))i(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function s(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerPolicy&&(r.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?r.credentials="include":e.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(e){if(e.ep)return;e.ep=!0;const r=s(e);fetch(e.href,r)}})();
@@ -77,8 +77,8 @@
77
77
  document.documentElement.setAttribute("data-density", density === "tightest" || density === "tighter" || density === "compact" || density === "comfortable" ? density : "default");
78
78
  })();
79
79
  </script>
80
- <script type="module" crossorigin src="/assets/index-A7xHctiv.js"></script>
81
- <link rel="modulepreload" crossorigin href="/assets/app-BWU-3pHs.js">
80
+ <script type="module" crossorigin src="/assets/index-B3icWRJZ.js"></script>
81
+ <link rel="modulepreload" crossorigin href="/assets/app-BK08kq7X.js">
82
82
  <link rel="stylesheet" crossorigin href="/assets/app-BIrh5Q0W.css">
83
83
  </head>
84
84
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ccdeck",
3
- "version": "3.81.3",
3
+ "version": "3.82.0",
4
4
  "description": "Local dashboard for Claude Code and Codex CLI sessions: which Claude Code session needs input, every tool call and Claude Code subagent live, token cost and quota, several Claude accounts. Run npx ccdeck.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -84,6 +84,8 @@
84
84
  "without one."
85
85
  ],
86
86
  "//summaries": {
87
+ "3.82.0": "Steadier Codex switching, and uninstall cleans up Codex's terminal selection",
88
+ "3.81.4": "Codex account switching works with Windows sandbox logins",
87
89
  "3.81.3": "More reliable Codex switching and quieter account rows",
88
90
  "3.81.2": "Codex account switches wait through activity changes",
89
91
  "3.81.1": "Codex reconnection and Windows fixes",
@@ -139,25 +141,73 @@
139
141
  "3.53.1",
140
142
  "3.53.3"
141
143
  ],
144
+ "3.82.0": [
145
+ {
146
+ "title": "🔄 Codex switching recovers instead of staying stuck",
147
+ "body": "A failed reconnect or manual switch no longer leaves Codex account control disconnected, and turning Auto-switch off stops a switch it had already queued.",
148
+ "priority": "highlight",
149
+ "icon": "accounts",
150
+ "details": "On Windows, a Codex connection that never answers now fails after 30 seconds instead of waiting forever."
151
+ },
152
+ {
153
+ "title": "⏱️ Slow Codex logins get more time and a Retry button",
154
+ "body": "ccdeck now gives Codex more time to read a login during a switch, and if it still runs out, the panel says why and offers Retry selected account.",
155
+ "priority": "highlight",
156
+ "icon": "accounts"
157
+ },
158
+ {
159
+ "title": "🧹 Uninstall also removes Codex's terminal selection",
160
+ "body": "ccdeck --uninstall now takes the codex block that Enable terminal selection added out of your shell profiles, and names any file it could not clean.",
161
+ "priority": "highlight"
162
+ },
163
+ {
164
+ "title": "⌨️ A opens Codex accounts on a Codex-only deck",
165
+ "body": "With Codex alone, the Codex accounts door now shows its A key, and its name follows your interface language."
166
+ },
167
+ {
168
+ "title": "🔑 Jira token help names the permission for comments and statuses",
169
+ "body": "A scoped Jira Cloud token needs write:jira-work to add comments and change statuses, and the token help and Settings › Integrations now say so."
170
+ },
171
+ {
172
+ "title": "🌍 Codex messages read correctly in every language",
173
+ "body": "The message about a Codex login folder that is not private enough had lost its accented and non-Latin letters; it is whole again, and the new timeout message is translated."
174
+ }
175
+ ],
176
+ "3.81.4": [
177
+ {
178
+ "title": "🔄 Switch Codex accounts without another sign-in",
179
+ "body": "On Windows, Switch can use your existing native Codex login while keeping its sandbox permissions unchanged.",
180
+ "priority": "highlight",
181
+ "icon": "accounts"
182
+ },
183
+ {
184
+ "title": "🔐 New Windows accounts are ready for switching",
185
+ "body": "Accounts added through + now get private folders from the start, and older native login files are recognized."
186
+ },
187
+ {
188
+ "title": "💬 Clearer account-switching errors",
189
+ "body": "If a login cannot be used safely, ccdeck explains the folder-permission problem and how to continue."
190
+ }
191
+ ],
142
192
  "3.81.3": [
143
193
  {
144
- "title": "More reliable Codex account switching",
194
+ "title": "🔄 More reliable Codex account switching",
145
195
  "body": "ccdeck retries temporary connection failures before switching the open Codex app.",
146
196
  "priority": "highlight",
147
197
  "icon": "accounts"
148
198
  },
149
199
  {
150
- "title": "Quieter account switching",
200
+ "title": "✨ Quieter account switching",
151
201
  "body": "Successful switches no longer leave an extra message under the account row."
152
202
  },
153
203
  {
154
- "title": "Arrow-key navigation in ccdeck tui",
204
+ "title": "⌨️ Arrow-key navigation in ccdeck tui",
155
205
  "body": "The footer and help now show the left and right arrow keys for moving between tabs."
156
206
  }
157
207
  ],
158
208
  "3.81.2": [
159
209
  {
160
- "title": "Codex account switches wait through activity changes",
210
+ "title": "🔄 Codex account switches wait through activity changes",
161
211
  "body": "If new work starts while a switch is being prepared, ccdeck now waits and retries safely instead of leaving the switch failed.",
162
212
  "priority": "highlight",
163
213
  "icon": "accounts"
@@ -165,7 +215,7 @@
165
215
  ],
166
216
  "3.81.1": [
167
217
  {
168
- "title": "Fix Codex sharing on Windows",
218
+ "title": "🔐 Fix Codex sharing on Windows",
169
219
  "body": "Codex logins blocked by Windows folder permissions can now be prepared for sharing from the Share dialog.",
170
220
  "priority": "highlight",
171
221
  "icon": "accounts",
@@ -173,20 +223,20 @@
173
223
  "notice": "Secure permissions and share is optional and restricts the selected Codex folders and auth.json to your Windows user, including changes to inherited access for their contents. Your login, settings and active account stay in place. Automatic network sync never changes folder permissions."
174
224
  },
175
225
  {
176
- "title": "Windows updates reach the copy you use",
226
+ "title": "🪟 Windows updates reach the copy you use",
177
227
  "body": "Global npm updates now target the active installation and confirm that newer files arrived before showing installed.",
178
228
  "priority": "highlight",
179
229
  "noticeLabel": "Already stuck?",
180
230
  "notice": "An older Windows installation already stuck at installed may need one manual update to receive this fix. For the desktop app, run the latest Windows installer. For npm, follow the Windows recovery steps in README, then restart ccdeck. Accounts and settings are kept."
181
231
  },
182
232
  {
183
- "title": "Reconnect Codex without a false login-change warning",
233
+ "title": "🔄 Reconnect Codex without a false login-change warning",
184
234
  "body": "Connecting to an unchanged Codex account no longer pauses control because of its initial account update.",
185
235
  "priority": "highlight",
186
236
  "icon": "accounts"
187
237
  },
188
238
  {
189
- "title": "See why a shared login did not arrive",
239
+ "title": "📡 See why a shared login did not arrive",
190
240
  "body": "The network map now shows a failed transfer instead of promising that the login will arrive next round."
191
241
  }
192
242
  ],
@@ -9,13 +9,13 @@ import { performance } from 'node:perf_hooks';
9
9
  import { readCodexSelection } from './codex-selection.mjs';
10
10
  import { startEngineRpc } from './codex-engine-rpc.mjs';
11
11
  import { pathLookup } from './exec-spec.mjs';
12
- import { holdWindowsPrivatePath } from './codex-windows-private.mjs';
12
+ import { holdWindowsPrivatePath, snapshotWindowsCodexLogin } from './codex-windows-private.mjs';
13
13
 
14
14
  const MAX_AUTH_BYTES = 1024 * 1024;
15
- // A loaded Windows host can exceed twelve seconds starting a cold CLI while
16
- // native agents work. Bound initialization/reads together at thirty seconds,
15
+ // A cold CLI or workspace routing discovery can exceed three seconds on any
16
+ // platform. Bound initialization/reads together at thirty seconds,
17
17
  // plus the owned process's four-second shutdown; never retry a native request.
18
- const NATIVE_DEADLINE_MS = process.platform === 'win32' ? 34000 : 7000;
18
+ const NATIVE_DEADLINE_MS = 34000;
19
19
  // startEngineRpc.stop() closes stdin, then escalates at 2s and 4s. Reserve its
20
20
  // full shutdown window rather than giving each request another seven seconds.
21
21
  const STOP_RESERVE_MS = 4000;
@@ -159,11 +159,19 @@ export async function readLiveCodexCredential(profileId, options = {}) {
159
159
  const selectionOptions = { store: options.store, env };
160
160
  const selection = await readCodexSelection(selectionOptions);
161
161
  const profile = profileFrom(selection, profileId);
162
+ if (windows && env.CODEX_HOME && (await lstat(env.CODEX_HOME)).isSymbolicLink()) fail('credential_file_unsafe');
163
+ let nativeHomeSnapshot = false;
162
164
  if (windows) {
163
165
  try { profileGuard = await holdWindowsPrivatePath(profile.home, { ...options.windowsPrivate, kind: 'directory' }); }
164
- catch { fail('credential_file_unsafe'); }
166
+ catch {
167
+ // Only the user's original native home may carry Codex sandbox ACLs.
168
+ // Imported/managed profiles keep the existing strict private-path gate.
169
+ if (resolve(profile.home).toLowerCase() !== resolve(selection.originalHome).toLowerCase()) fail('credential_file_unsafe');
170
+ nativeHomeSnapshot = true;
171
+ }
165
172
  }
166
173
  const captured = await captureProfile(profile);
174
+ if (nativeHomeSnapshot && captured.literal.isSymbolicLink()) fail('credential_file_unsafe');
167
175
  const childEnv = { ...env, CODEX_HOME: captured.canonical };
168
176
  for (const key of Object.keys(childEnv)) if (/^(OPENAI_API_KEY|CODEX_API_KEY)$/i.test(key)) delete childEnv[key];
169
177
  phase = 'native_unavailable';
@@ -176,13 +184,31 @@ export async function readLiveCodexCredential(profileId, options = {}) {
176
184
  // Native has finished refreshing and its owned process has stopped. No
177
185
  // pre-refresh file version is compared with the legitimately renewed file.
178
186
  await revalidateProfile(profile, captured, selection.revision, selectionOptions);
187
+ const snapshotCredential = async () => {
188
+ let auth;
189
+ try { auth = await snapshotWindowsCodexLogin(captured.canonical, options.windowsPrivate); }
190
+ catch { fail('credential_file_unsafe'); }
191
+ // Older native file logins omit auth_mode; the native account/read above
192
+ // has already confirmed ChatGPT auth, not an API-key account.
193
+ if (auth?.auth_mode == null && auth?.tokens && auth.OPENAI_API_KEY == null) auth.auth_mode = 'chatgpt';
194
+ // Bind the copied access token to the selected account read by native
195
+ // Codex. No refresh token is copied, persisted, or renewed by the deck.
196
+ const credential = credentialFrom(auth, account, profileId);
197
+ await revalidateProfile(profile, captured, selection.revision, selectionOptions);
198
+ if (credential.expiresAt <= Date.now()) fail('credential_expired');
199
+ return credential;
200
+ };
201
+ if (nativeHomeSnapshot) return await snapshotCredential();
179
202
  phase = 'credential_unavailable';
180
203
  const file = join(captured.canonical, 'auth.json');
181
204
  let handle, fileGuard;
182
205
  try {
183
206
  if (windows) {
184
207
  try { fileGuard = await holdWindowsPrivatePath(file, { ...options.windowsPrivate, kind: 'file' }); }
185
- catch { fail('credential_file_unsafe'); }
208
+ catch {
209
+ if (resolve(profile.home).toLowerCase() !== resolve(selection.originalHome).toLowerCase()) fail('credential_file_unsafe');
210
+ return await snapshotCredential();
211
+ }
186
212
  }
187
213
  const initial = await lstat(file, { bigint: true });
188
214
  privateFile(initial, windows);
@@ -202,6 +228,8 @@ export async function readLiveCodexCredential(profileId, options = {}) {
202
228
  let auth;
203
229
  try { auth = JSON.parse(bytes.subarray(0, length).toString('utf8')); }
204
230
  catch { fail('invalid_credentials'); }
231
+ if (windows && resolve(profile.home).toLowerCase() === resolve(selection.originalHome).toLowerCase()
232
+ && auth?.auth_mode == null && auth?.tokens && auth.OPENAI_API_KEY == null) auth.auth_mode = 'chatgpt';
205
233
  const credential = credentialFrom(auth, account, profileId);
206
234
  await revalidateProfile(profile, captured, selection.revision, selectionOptions);
207
235
  if (!sameFile(opened, await handle.stat({ bigint: true })) || !sameFile(opened, await lstat(file, { bigint: true }))) fail('credential_file_changed');
@@ -210,8 +210,12 @@ export function createCodexLiveAccountController(input = {}) {
210
210
  } finally { clearTimeout(timeout); }
211
211
  account = await rpc.request('account/read', { refreshToken: false });
212
212
  }
213
- }
214
- finally { readingInitialAccount = false; }
213
+ } catch (error) {
214
+ // Manual switches and renewals can also create this connection while
215
+ // retaining a previous login. Never retain an unattested bootstrap.
216
+ await disconnect();
217
+ throw error;
218
+ } finally { readingInitialAccount = false; }
215
219
  if (account.account && account.account.type !== 'chatgpt') { rpc.close(); rpc = null; owned = false; throw liveError('unsupported_auth_mode'); }
216
220
  }
217
221
  async function loginCredential(id, refresh = false) {
@@ -252,6 +256,11 @@ export function createCodexLiveAccountController(input = {}) {
252
256
  journal.phase = journal.entries.every(e => ['continued', 'skipped'].includes(e.phase)) ? 'finished' : 'pending';
253
257
  await saveHandoff(journal);
254
258
  };
259
+ const assertAutoEnabled = async () => {
260
+ if (automatic && !(await (options.readAuto ?? (() => readCodexAuto({ ...options, store })))()).enabled) {
261
+ throw liveError('auto_switch_disabled');
262
+ }
263
+ };
255
264
  const authCurrent = () => !closed && !ownershipPaused && epoch === ownershipEpoch;
256
265
  const owner = () => authCurrent() && currentIntent()?.revision === intent.revision && currentIntent()?.id === intent.id;
257
266
  const verifyOwnership = async () => {
@@ -277,12 +286,15 @@ export function createCodexLiveAccountController(input = {}) {
277
286
  if (!s.profiles?.some(p => p.id === intent.id && p.available !== false)) throw liveError('profile_unavailable');
278
287
  await ensureRpc(s.originalHome);
279
288
  const next = await loginCredential(intent.id, refresh);
289
+ await assertAutoEnabled();
280
290
  if (!owner()) throw liveError('account_changed_outside_deck');
281
291
  if (!await lease.valid()) throw liveError('native_control_lost');
282
292
  const before = await rpc.request('account/read', { refreshToken: false });
283
293
  resumeIdentity = before;
284
294
  handoff = await prepareCodexLiveHandoff(rpc, { isCurrent: owner,
285
295
  beforeInterrupt: async entry => {
296
+ await assertAutoEnabled();
297
+ if (!owner()) throw liveError('account_changed_outside_deck');
286
298
  await record(entry, 'interrupt_sent');
287
299
  if (!owner()) throw liveError('account_changed_outside_deck');
288
300
  }, afterInterrupt: (entry, phase) => record(entry, phase) });
@@ -312,6 +324,8 @@ export function createCodexLiveAccountController(input = {}) {
312
324
  const current = await rpc.request('account/read', { refreshToken: false });
313
325
  if (!owner() || !sameNativeAccount(current, before)) throw liveError('account_changed_outside_deck');
314
326
  if (!await lease.valid()) throw liveError('native_control_lost');
327
+ await assertAutoEnabled();
328
+ if (!owner()) throw liveError('account_changed_outside_deck');
315
329
  // Authentication crosses only this owner-validated local socket. Codex
316
330
  // stores external tokens in memory, not either profile's credential file.
317
331
  maybeApplied = true;
@@ -365,7 +379,8 @@ export function createCodexLiveAccountController(input = {}) {
365
379
  if (journal.entries.length && journal.phase !== 'finished') update({ continuation: 'manual_required' });
366
380
  if (maybeApplied) { credential = null; owned = false; }
367
381
  const reason = publicReason(error);
368
- update({ state: ['native_not_running', 'cli_unavailable'].includes(reason) ? 'unavailable' : 'failed',
382
+ update({ state: reason === 'auto_switch_disabled' && !maybeApplied ? (owned ? 'applied' : 'idle')
383
+ : ['native_not_running', 'cli_unavailable'].includes(reason) ? 'unavailable' : 'failed',
369
384
  ...(maybeApplied ? { profileId: null } : {}), reason });
370
385
  if (!owned) await disconnect();
371
386
  } finally {
@@ -553,14 +568,21 @@ export function createCodexLiveAccountController(input = {}) {
553
568
  } catch { /* Keep the durable recovery intent until its outcome is known. */ }
554
569
  }
555
570
  async function reconnect() {
556
- const s = await selection(); await ensureRpc(s.originalHome);
557
- const actual = await rpc.request('account/read', { refreshToken: false });
558
- // Notifications were unobservable during the gap. Email/workspace labels
559
- // cannot restore authority; require a native ID or a fresh manual selection.
560
- if (!accountIds(actual).length) await externalChange('native_identity_unattested');
561
- else if (!ownershipPaused && sameAccount(actual, credential, true)) {
562
- lastCheck = Date.now(); update({ state: 'applied', profileId: credential.profileId, reason: null });
563
- } else await externalChange();
571
+ try {
572
+ const s = await selection(); await ensureRpc(s.originalHome);
573
+ const actual = await rpc.request('account/read', { refreshToken: false });
574
+ // Notifications were unobservable during the gap. Email/workspace labels
575
+ // cannot restore authority; require a native ID or a fresh manual selection.
576
+ if (!accountIds(actual).length) await externalChange('native_identity_unattested');
577
+ else if (!ownershipPaused && sameAccount(actual, credential, true)) {
578
+ lastCheck = Date.now(); update({ state: 'applied', profileId: credential.profileId, reason: null });
579
+ } else await externalChange();
580
+ } catch (error) {
581
+ // A partially initialized connection cannot attest ownership. Drop only
582
+ // our control connection so the next poll can reconnect and read IDs.
583
+ await disconnect();
584
+ throw error;
585
+ }
564
586
  }
565
587
  async function tick() {
566
588
  if (closed || ticking) return;
@@ -113,7 +113,7 @@ export async function connectCodexLiveRpc(endpoint, options = {}) {
113
113
  let ws;
114
114
  try {
115
115
  ws = new WebSocket(windows ? 'ws://localhost/' : `ws+unix://${endpoint.socketPath}:/`, {
116
- handshakeTimeout: 5000, maxPayload: 64 * 1024 * 1024, perMessageDeflate: false,
116
+ handshakeTimeout: windows ? 30000 : 5000, maxPayload: 64 * 1024 * 1024, perMessageDeflate: false,
117
117
  ...(windows ? { createConnection: () => { proxy = createCodexWindowsProxy(endpoint, options); return proxy; } } : {}),
118
118
  });
119
119
  } catch { await guard?.release(); proxy?.destroy(); throw liveError('native_connection_failed'); }
@@ -161,7 +161,18 @@ export async function connectCodexLiveRpc(endpoint, options = {}) {
161
161
  close() { closing = true; rejectPending(); ws.close(); const timer = setTimeout(() => { ws.terminate(); proxy?.destroy(); }, 500); timer.unref(); },
162
162
  };
163
163
  try {
164
- await new Promise((ready, reject) => { ws.once('open', ready); ws.once('error', () => reject(liveError('native_connection_failed'))); });
164
+ await new Promise((ready, reject) => {
165
+ // The Windows stdio Duplex does not emit a net.Socket connect event, so
166
+ // the HTTP client's socket timeout alone cannot bound its handshake.
167
+ const finish = error => {
168
+ clearTimeout(timer);
169
+ ws.off('open', opened); ws.off('error', failed); ws.off('close', failed);
170
+ if (error) reject(liveError('native_connection_failed')); else ready();
171
+ };
172
+ const opened = () => finish(false), failed = () => finish(true);
173
+ const timer = setTimeout(failed, windows ? 30000 : 5000);
174
+ ws.once('open', opened); ws.once('error', failed); ws.once('close', failed);
175
+ });
165
176
  const after = windows ? await inspectWindowsPrivateSocket(endpoint.socketPath, options.windowsPrivate) : await inspectPosixSocket(endpoint.socketPath);
166
177
  if (after.generation !== endpoint.generation) throw liveError('native_endpoint_changed');
167
178
  if (guard && !guard.valid()) throw liveError('untrusted_native_socket');
@@ -261,7 +261,10 @@ export async function addCodexProfile({ label = null, operationId: operation } =
261
261
  await mkdir(root, { recursive: true, mode: 0o700 });
262
262
  if (!(await lstat(root)).isDirectory()) fail('registry_corrupt');
263
263
  const home = join(root, randomBytes(16).toString('hex'));
264
- await mkdir(home, { mode: 0o700 });
264
+ if ((options.platform ?? process.platform) === 'win32') {
265
+ const { ensureWindowsPrivateDirectory } = await import('./codex-windows-private.mjs');
266
+ await ensureWindowsPrivateDirectory(home);
267
+ } else await mkdir(home, { mode: 0o700 });
265
268
  try {
266
269
  const id = await codexProfileId(home);
267
270
  state.profiles.push({ id, home, label, managed: true });
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'node:module';
2
- import { readFile, mkdir, chmod, access, stat, cp } from 'node:fs/promises';
2
+ import { readFile, mkdir, chmod, access, stat, cp, rm } from 'node:fs/promises';
3
3
  import { constants } from 'node:fs';
4
- import { basename, dirname, join, isAbsolute } from 'node:path';
4
+ import { basename, dirname, join, isAbsolute, relative } from 'node:path';
5
5
  import { homedir } from 'node:os';
6
6
  import { execFile } from 'node:child_process';
7
7
  import { promisify } from 'node:util';
@@ -48,6 +48,10 @@ async function rcFor(shell, home, env, platform) {
48
48
  }
49
49
  return join(home, '.bashrc');
50
50
  }
51
+ return powershellProfile(shell);
52
+ }
53
+
54
+ async function powershellProfile(shell) {
51
55
  const executable = shell === 'powershell5' ? 'powershell.exe' : 'pwsh.exe';
52
56
  const { stdout } = await promisify(execFile)(executable, ['-NoProfile', '-Command', '$PROFILE.CurrentUserAllHosts'], { encoding: 'utf8', timeout: 5000, maxBuffer: 4096 });
53
57
  const rc = stdout.trim();
@@ -119,3 +123,72 @@ export async function configureCodexTerminal(action, options = {}) {
119
123
  if (action === 'install') await chmod(join(options.store ?? deckDataDir(undefined, env, home), 'codex-terminal'), 0o700);
120
124
  return { shell, rc, action };
121
125
  }
126
+
127
+ /**
128
+ * For `--uninstall`: take the block Enable terminal selection wrote out of every
129
+ * shell profile it may be in, and the helper it calls with it.
130
+ *
131
+ * Nothing records which shell the person set it up in (they ran the command
132
+ * themselves), so every profile `rcFor` can pick is read: zsh's in ZDOTDIR and
133
+ * in the home folder, bash's on Linux and the three macOS picks the first of
134
+ * (an earlier setup may have picked another), and on Windows both PowerShells'
135
+ * CurrentUserAllHosts profile in Documents, and in OneDrive's Documents when
136
+ * OneDrive keeps that folder. Left behind, the block outlives ccdeck: `codex`
137
+ * runs through a helper that the desktop app's removal takes away, and it no
138
+ * longer starts.
139
+ *
140
+ * The PowerShell profiles are found from the home folder, not by asking
141
+ * PowerShell: `$PROFILE` follows the Documents folder Windows has on record,
142
+ * whatever HOME or USERPROFILE say, so asking would reach past an isolated
143
+ * home into the real one. A OneDrive folder outside the home is skipped for
144
+ * the same reason.
145
+ *
146
+ * A file whose markers are incomplete is not touched and is named. The helper
147
+ * goes only when no profile still holds a block, since a block left anywhere
148
+ * still calls it. Answers { removed, refused, kept, helper, directory }.
149
+ */
150
+ export async function removeCodexTerminalEverywhere(options = {}) {
151
+ const env = options.env ?? process.env;
152
+ const platform = options.platform ?? process.platform;
153
+ const home = options.home ?? homedir();
154
+ const store = options.store ?? deckDataDir(undefined, env, home);
155
+ const candidates = [];
156
+ const zdot = env.ZDOTDIR?.trim();
157
+ if (zdot) candidates.push(join(zdot, '.zshrc'));
158
+ candidates.push(...['.zshrc', '.bashrc', '.bash_profile', '.bash_login', '.profile'].map(name => join(home, name)));
159
+ if (platform === 'win32') {
160
+ const inHome = dir => { const r = relative(home, dir); return r !== '' && !r.startsWith('..') && !isAbsolute(r); };
161
+ const documents = [join(home, 'Documents'),
162
+ ...[env.OneDrive, env.OneDriveConsumer, env.OneDriveCommercial].filter(dir => dir?.trim() && inHome(dir)).map(dir => join(dir, 'Documents'))];
163
+ for (const dir of documents) candidates.push(join(dir, 'PowerShell', 'profile.ps1'), join(dir, 'WindowsPowerShell', 'profile.ps1'));
164
+ }
165
+ const removed = [], refused = [];
166
+ for (const rc of new Set(candidates)) {
167
+ let text;
168
+ try { text = await readFile(rc, 'utf8'); }
169
+ catch (error) {
170
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') refused.push({ path: rc, why: error.message });
171
+ continue;
172
+ }
173
+ if (!text.includes(BEGIN) && !text.includes(END)) continue;
174
+ try {
175
+ await writeFileAtomic(await resolveWriteTarget(rc), stripIntegration(text));
176
+ removed.push(rc);
177
+ } catch (error) {
178
+ refused.push({ path: rc, why: error.message });
179
+ }
180
+ }
181
+ const directory = join(store, 'codex-terminal');
182
+ let helper = false;
183
+ const kept = refused.length > 0;
184
+ if (!kept) {
185
+ try {
186
+ await stat(directory);
187
+ await rm(directory, { recursive: true, force: true });
188
+ helper = true;
189
+ } catch (error) {
190
+ if (error.code !== 'ENOENT') refused.push({ path: directory, why: error.message });
191
+ }
192
+ }
193
+ return { removed, refused, kept, helper, directory };
194
+ }
@@ -44,6 +44,16 @@ async function check(path, operation, options) {
44
44
  export const ensureWindowsPrivateDirectory = async (path, options = {}) => (await check(path, 'ensure', { ...options, kind: 'directory' })).path;
45
45
  // Only the explicit Share repair may tighten an existing profile.
46
46
  export const protectWindowsCodexLogin = async (path, options = {}) => (await check(path, 'protect-login', { ...options, kind: 'directory' })).path;
47
+ // The caller validates the native identity before using this local snapshot.
48
+ // Do not use check()/result(): login material must never become path metadata.
49
+ export async function snapshotWindowsCodexLogin(path, options = {}) {
50
+ try {
51
+ const spec = command(path, 'snapshot-login', { ...options, kind: 'directory' });
52
+ const output = await (options.execFile ?? runFile)(spec.file, spec.args,
53
+ { timeout: deadline(options), maxBuffer: 2 * 1024 * 1024, windowsHide: true, shell: false });
54
+ return JSON.parse(output.stdout.replace(/^\uFEFF/, ''));
55
+ } catch { throw unsafe(); }
56
+ }
47
57
  export const assertWindowsPrivatePath = async (path, options = {}) => (await check(path, 'check', options)).path;
48
58
  export async function inspectWindowsPrivateSocket(path, options = {}) {
49
59
  const value = await check(path, 'check', { ...options, kind: 'socket' });
@@ -1,5 +1,5 @@
1
1
  param(
2
- [ValidateSet('ensure','check','hold','protect-login')][string]$Operation,
2
+ [ValidateSet('ensure','check','hold','protect-login','snapshot-login')][string]$Operation,
3
3
  [Parameter(Mandatory=$true)][string]$TargetPath,
4
4
  [ValidateSet('directory','file','socket')][string]$Kind = 'directory'
5
5
  )
@@ -126,6 +126,47 @@ public static class CodexPrivatePath {
126
126
  return canonical;
127
127
  }
128
128
  }
129
+ // Explicit local import: the source may be shared with Codex's sandbox.
130
+ // Pin owner-controlled objects and read one immutable regular-file handle.
131
+ // Never alter source permissions and never export a refresh token.
132
+ public static string SnapshotLogin(string path) {
133
+ using (var directory = OpenForProtection(path, true)) {
134
+ Require(Owned(directory));
135
+ string canonical = Canonical(directory);
136
+ using (var file = OpenForProtection(Path.Combine(canonical, "auth.json"), false)) {
137
+ Require(Owned(file));
138
+ FileInfo info; Require(GetFileInformationByHandle(file, out info));
139
+ Require(info.SizeHigh == 0 && info.SizeLow <= 1048576);
140
+ using (var stream = new FileStream(file, FileAccess.Read)) {
141
+ var bytes = new byte[info.SizeLow];
142
+ int offset = 0;
143
+ while (offset < bytes.Length) { int n = stream.Read(bytes, offset, bytes.Length - offset); Require(n > 0); offset += n; }
144
+ return Encoding.UTF8.GetString(bytes);
145
+ }
146
+ }
147
+ }
148
+ }
149
+ static bool Owned(SafeFileHandle h) {
150
+ IntPtr owner, group, dacl, sacl, descriptor;
151
+ Require(GetSecurityInfo(h, 1, 5, out owner, out group, out dacl, out sacl, out descriptor) == 0);
152
+ try {
153
+ Require(owner != IntPtr.Zero && dacl != IntPtr.Zero);
154
+ var bytes = new byte[GetSecurityDescriptorLength(descriptor)];
155
+ Marshal.Copy(descriptor, bytes, 0, bytes.Length);
156
+ var sd = new RawSecurityDescriptor(bytes, 0);
157
+ Require(sd.DiscretionaryAcl != null && sd.DiscretionaryAcl.Count > 0);
158
+ foreach (GenericAce entry in sd.DiscretionaryAcl) {
159
+ var ace = entry as CommonAce;
160
+ Require(ace != null && !ace.IsCallback);
161
+ if (ace.AceQualifier == AceQualifier.AccessAllowed) {
162
+ string sid = ace.SecurityIdentifier.Value;
163
+ Require(sid != "S-1-1-0" && sid != "S-1-5-11" && sid != "S-1-5-32-545" && sid != "S-1-5-7");
164
+ }
165
+ }
166
+ return sd.Owner == WindowsIdentity.GetCurrent().User;
167
+ }
168
+ finally { if (descriptor != IntPtr.Zero) LocalFree(descriptor); }
169
+ }
129
170
  public static string SocketGeneration(string path) {
130
171
  // Node/libuv lstat returns EACCES on Windows AF_UNIX entries. Open only
131
172
  // reparse metadata, never follow a symlink/junction or read socket bytes.
@@ -154,7 +195,17 @@ public static class CodexPrivatePath {
154
195
  $guards = [System.Collections.Generic.List[System.IDisposable]]::new()
155
196
  try {
156
197
  $path = [IO.Path]::GetFullPath($TargetPath)
157
- if ($Operation -eq 'protect-login') {
198
+ if ($Operation -eq 'snapshot-login') {
199
+ $auth = [CodexPrivatePath]::SnapshotLogin($TargetPath) | Microsoft.PowerShell.Utility\ConvertFrom-Json
200
+ if ($null -ne $auth.OPENAI_API_KEY -or $null -eq $auth.tokens) { throw 'unsafe' }
201
+ # Only the access/identity material needed by the live daemon crosses this
202
+ # pipe. Native Codex remains the sole owner of refresh-token rotation.
203
+ $safe = @{ auth_mode = $auth.auth_mode; OPENAI_API_KEY = $null; tokens = @{
204
+ access_token = $auth.tokens.access_token; id_token = $auth.tokens.id_token; account_id = $auth.tokens.account_id
205
+ } }
206
+ [Console]::Out.WriteLine(($safe | Microsoft.PowerShell.Utility\ConvertTo-Json -Depth 4 -Compress))
207
+ exit 0
208
+ } elseif ($Operation -eq 'protect-login') {
158
209
  if ($Kind -ne 'directory') { throw 'unsafe' }
159
210
  $null = [CodexPrivatePath]::ProtectLogin($path)
160
211
  }
@@ -60,8 +60,15 @@ function newer(a, b) {
60
60
  * the caller has something to say about. `ok` is the HTTP status, and `body` the
61
61
  * parsed JSON or null — the deck's own `{ ok: false, reason }` arrives with a
62
62
  * 400 and is worth more to the reader than the status alone, so it is kept.
63
+ *
64
+ * `client` names the command asking, in `x-ccdeck-client`, for the deck's
65
+ * usage tally to count where it was looked at from (feature-use.mjs). Only
66
+ * `ccdeck tui` passes one, "tui"; every other command sends nothing new, and a
67
+ * name that is not a bare lowercase word is not sent.
63
68
  */
64
- export function askDeck(rec, { method = "GET", path, body = undefined, timeoutMs = ASK_MS, request = httpRequest } = {}) {
69
+ export function askDeck(rec, {
70
+ method = "GET", path, body = undefined, timeoutMs = ASK_MS, request = httpRequest, client = undefined,
71
+ } = {}) {
65
72
  return new Promise(resolve => {
66
73
  let settled = false;
67
74
  const finish = (v) => { if (!settled) { settled = true; resolve(v); } };
@@ -79,6 +86,7 @@ export function askDeck(rec, { method = "GET", path, body = undefined, timeoutMs
79
86
  // an Origin or Sec-Fetch-Site would be judged as a page's, and a page
80
87
  // is not who this is.
81
88
  "x-ccdeck-token": String(rec.token ?? ""),
89
+ ...(typeof client === "string" && /^[a-z][a-z0-9-]{0,31}$/.test(client) ? { "x-ccdeck-client": client } : {}),
82
90
  ...(payload === null
83
91
  ? { "content-length": "0" }
84
92
  : { "content-type": "application/json", "content-length": String(Buffer.byteLength(payload)) }),
@@ -18,6 +18,8 @@ import { SEQ_EPOCH, ringHoldsNewerThan, ringSnapshot } from "./event-ring.mjs";
18
18
  // The one door every event comes through — see event-pipeline.mjs.
19
19
  import { pushEvent } from "./event-pipeline.mjs";
20
20
  import { noteToolAudit } from "./tool-audit.mjs";
21
+ // Which surface a page is, counted for the usage reports — see feature-use.mjs.
22
+ import { holdPageSurface } from "./feature-use.mjs";
21
23
  import { noteLogWriter } from "./event-log.mjs";
22
24
  // Which CLIs this deck watches — see deck-scope.mjs.
23
25
  import { deckProviders } from "./deck-scope.mjs";
@@ -284,7 +286,12 @@ export function handleSse(req, res) {
284
286
  // is already committed to a 200 and its own failure path is to hang up — so
285
287
  // start it, keep the router's contract of returning nothing, and make sure a
286
288
  // rejection ends the stream rather than the process.
287
- resumeSse(req, res, lastId, { tray: isTrayRequest(req) }).catch(() => dropSse(res));
289
+ const tray = isTrayRequest(req);
290
+ // A page — the app's window or a browser tab — is that surface used, today
291
+ // and on every day it is still connected when the day turns (feature-use.mjs).
292
+ // The tray connection is a reader, not somebody looking.
293
+ if (!tray) holdPageSurface(req);
294
+ resumeSse(req, res, lastId, { tray }).catch(() => dropSse(res));
288
295
  }
289
296
 
290
297
  /**