ccdeck 3.81.3 → 3.81.4

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.
@@ -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-0jqgYDft.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-K55Tw-ZZ.js"></script>
81
+ <link rel="modulepreload" crossorigin href="/assets/app-0jqgYDft.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.81.4",
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,7 @@
84
84
  "without one."
85
85
  ],
86
86
  "//summaries": {
87
+ "3.81.4": "Codex account switching works with Windows sandbox logins",
87
88
  "3.81.3": "More reliable Codex switching and quieter account rows",
88
89
  "3.81.2": "Codex account switches wait through activity changes",
89
90
  "3.81.1": "Codex reconnection and Windows fixes",
@@ -139,25 +140,41 @@
139
140
  "3.53.1",
140
141
  "3.53.3"
141
142
  ],
143
+ "3.81.4": [
144
+ {
145
+ "title": "🔄 Switch Codex accounts without another sign-in",
146
+ "body": "On Windows, Switch can use your existing native Codex login while keeping its sandbox permissions unchanged.",
147
+ "priority": "highlight",
148
+ "icon": "accounts"
149
+ },
150
+ {
151
+ "title": "🔐 New Windows accounts are ready for switching",
152
+ "body": "Accounts added through + now get private folders from the start, and older native login files are recognized."
153
+ },
154
+ {
155
+ "title": "💬 Clearer account-switching errors",
156
+ "body": "If a login cannot be used safely, ccdeck explains the folder-permission problem and how to continue."
157
+ }
158
+ ],
142
159
  "3.81.3": [
143
160
  {
144
- "title": "More reliable Codex account switching",
161
+ "title": "🔄 More reliable Codex account switching",
145
162
  "body": "ccdeck retries temporary connection failures before switching the open Codex app.",
146
163
  "priority": "highlight",
147
164
  "icon": "accounts"
148
165
  },
149
166
  {
150
- "title": "Quieter account switching",
167
+ "title": "✨ Quieter account switching",
151
168
  "body": "Successful switches no longer leave an extra message under the account row."
152
169
  },
153
170
  {
154
- "title": "Arrow-key navigation in ccdeck tui",
171
+ "title": "⌨️ Arrow-key navigation in ccdeck tui",
155
172
  "body": "The footer and help now show the left and right arrow keys for moving between tabs."
156
173
  }
157
174
  ],
158
175
  "3.81.2": [
159
176
  {
160
- "title": "Codex account switches wait through activity changes",
177
+ "title": "🔄 Codex account switches wait through activity changes",
161
178
  "body": "If new work starts while a switch is being prepared, ccdeck now waits and retries safely instead of leaving the switch failed.",
162
179
  "priority": "highlight",
163
180
  "icon": "accounts"
@@ -165,7 +182,7 @@
165
182
  ],
166
183
  "3.81.1": [
167
184
  {
168
- "title": "Fix Codex sharing on Windows",
185
+ "title": "🔐 Fix Codex sharing on Windows",
169
186
  "body": "Codex logins blocked by Windows folder permissions can now be prepared for sharing from the Share dialog.",
170
187
  "priority": "highlight",
171
188
  "icon": "accounts",
@@ -173,20 +190,20 @@
173
190
  "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
191
  },
175
192
  {
176
- "title": "Windows updates reach the copy you use",
193
+ "title": "🪟 Windows updates reach the copy you use",
177
194
  "body": "Global npm updates now target the active installation and confirm that newer files arrived before showing installed.",
178
195
  "priority": "highlight",
179
196
  "noticeLabel": "Already stuck?",
180
197
  "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
198
  },
182
199
  {
183
- "title": "Reconnect Codex without a false login-change warning",
200
+ "title": "🔄 Reconnect Codex without a false login-change warning",
184
201
  "body": "Connecting to an unchanged Codex account no longer pauses control because of its initial account update.",
185
202
  "priority": "highlight",
186
203
  "icon": "accounts"
187
204
  },
188
205
  {
189
- "title": "See why a shared login did not arrive",
206
+ "title": "📡 See why a shared login did not arrive",
190
207
  "body": "The network map now shows a failed transfer instead of promising that the login will arrive next round."
191
208
  }
192
209
  ],
@@ -9,7 +9,7 @@ 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
15
  // A loaded Windows host can exceed twelve seconds starting a cold CLI while
@@ -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');
@@ -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 });
@@ -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
  /**
@@ -6,6 +6,10 @@
6
6
  // The server names what a request did: the routes below are actions somebody
7
7
  // takes on purpose, never something a page polls, so the request is the use.
8
8
  // Either way only a name off FEATURES is kept, and only as "used today".
9
+ //
10
+ // And where the deck was looked at from: a page connected to /events is the
11
+ // desktop app's window or a browser tab for as long as it stays (event-routes.mjs),
12
+ // and `ccdeck tui` says so on the requests it makes (deck-client.mjs).
9
13
  import { readBody, send } from "./http-io.mjs";
10
14
  import { usageDay } from "./usage-day.mjs";
11
15
 
@@ -50,3 +54,44 @@ export async function handleFeature(req, res) {
50
54
  if (!usageDay.noteFeature(name)) return send(res, 400, { ok: false, reason: "unknown_feature" });
51
55
  return send(res, 200, { ok: true });
52
56
  }
57
+
58
+ /** The desktop app's window says so in its User-Agent, `ccdeck-desktop/<version>`
59
+ * after the browser's own (desktop/main.mjs), and the page reads it the same way
60
+ * (src/web/in-app.ts). */
61
+ const IN_APP = /\bccdeck-desktop\/\d/;
62
+
63
+ /** Which surface a page is: "desktop-window" for the app's window, else
64
+ * "browser-tab" — any browser, on this machine or through a tunnel. */
65
+ export function pageSurface(headers = {}) {
66
+ const ua = headers?.["user-agent"];
67
+ return typeof ua === "string" && IN_APP.test(ua) ? "desktop-window" : "browser-tab";
68
+ }
69
+
70
+ /** A page connected to /events: its surface is used today, and on every day it
71
+ * is still connected when the day turns, until the connection closes. Never
72
+ * for the app's tray connection, which is a reader and not somebody looking
73
+ * (sse-clients.mjs): the caller leaves it out. Never throws. */
74
+ export function holdPageSurface(req, usage = usageDay) {
75
+ try {
76
+ const release = usage.holdFeature(pageSurface(req?.headers));
77
+ req.once("close", release);
78
+ } catch {
79
+ // A page this could not count still gets its stream.
80
+ }
81
+ }
82
+
83
+ /** What a terminal client may say it is, in `x-ccdeck-client`, and the feature
84
+ * each is. Anything else — another value, another command — is nothing. */
85
+ const CLIENT_FEATURES = new Map([["tui", "tui"]]);
86
+
87
+ /** Note the client a request says it came from, if it is one off the list and
88
+ * the request carries the deck's own token (`authenticated`, request-gates.mjs
89
+ * presentsDeckToken), which only this user's own commands read off the deck's
90
+ * record: nothing else can pass for a terminal by setting the header. */
91
+ export function noteClientFeature(headers = {}, authenticated = false, usage = usageDay) {
92
+ if (!authenticated) return;
93
+ const raw = headers?.["x-ccdeck-client"];
94
+ if (typeof raw !== "string") return;
95
+ const name = CLIENT_FEATURES.get(raw.trim().toLowerCase());
96
+ if (name) usage.noteFeature(name);
97
+ }
@@ -19,7 +19,9 @@ import { challengeDeck, challengeProof, isProcessAlive } from "./deck-probe.mjs"
19
19
  export { challengeDeck, challengeProof, isProcessAlive };
20
20
  // The gates in front of the route table — see src/server/request-gates.mjs,
21
21
  // which also holds the per-process token the strictest of them checks.
22
- import { OPEN_MUTATIONS, isAuthorizedDataRead, isAuthorizedMutation, isGuardedRead, isTrustedMutation, isTrustedRead } from "./request-gates.mjs";
22
+ import {
23
+ OPEN_MUTATIONS, isAuthorizedDataRead, isAuthorizedMutation, isGuardedRead, isTrustedMutation, isTrustedRead, presentsDeckToken,
24
+ } from "./request-gates.mjs";
23
25
  import { trafficCapture } from "./traffic-radar-capture.mjs";
24
26
  import { trafficRadar } from "./traffic-radar.mjs";
25
27
  import { handleTrafficCapture, isAuthorizedTrafficIngest } from "./traffic-radar-routes.mjs";
@@ -71,7 +73,7 @@ import { serveStatic } from "./static-serve.mjs";
71
73
  // session-tracking.mjs.
72
74
  import { handleForget, startOutputWatch } from "./session-tracking.mjs";
73
75
  // Which features were used today, for the usage reports — see feature-use.mjs.
74
- import { handleFeature, noteRouteFeature } from "./feature-use.mjs";
76
+ import { handleFeature, noteClientFeature, noteRouteFeature } from "./feature-use.mjs";
75
77
  // Exported from this file before it moved, and still.
76
78
  export { HARD_TRACKED_SESSIONS } from "./session-tracking.mjs";
77
79
  // The desktop app's update as its window sees it — the state the app reports
@@ -316,6 +318,9 @@ export async function startServer({ port = 4317, host = "127.0.0.1", persist = n
316
318
  // account, pairing a deck — counts as that feature used today. Past the
317
319
  // gates above, so only the deck's own callers count. See feature-use.mjs.
318
320
  noteRouteFeature(req.method, url.pathname);
321
+ // And `ccdeck tui` saying it is the one asking, on a request with the
322
+ // deck's own token — which only this user's own commands hold.
323
+ noteClientFeature(req.headers, presentsDeckToken(req.headers));
319
324
 
320
325
  // `?persist=0` — another deck was elected to write this event to the log
321
326
  // the two of them share. Absent, this deck writes it.
@@ -23,6 +23,7 @@
23
23
  import { readFileSync } from "node:fs";
24
24
  import { release as osRelease } from "node:os";
25
25
  import { open, seal } from "./lan-sync.mjs";
26
+ import { osVersionOf } from "./os-version.mjs";
26
27
 
27
28
  /**
28
29
  * The operating system, in the words its owner would use.
@@ -30,26 +31,17 @@ import { open, seal } from "./lan-sync.mjs";
30
31
  * Node reports the KERNEL — `darwin 25.5.0`, `win32 10.0.26100` — and nobody
31
32
  * calls their laptop Darwin 25. So the numbers are translated on the machine
32
33
  * they describe, where the translation is certain, rather than on the one
33
- * reading them. Every input is a parameter, so all three platforms are tested
34
- * on any one of them.
34
+ * reading them (os-version.mjs, which the usage reports share). Every input is
35
+ * a parameter, so all three platforms are tested on any one of them.
35
36
  */
36
37
  export function osLabel({ platform, release = "", prettyName = "" } = {}) {
37
- const [major, minor, build] = String(release).split(".").map(n => Number.parseInt(n, 10));
38
- const dot = Number.isInteger(minor) ? `.${minor}` : "";
39
38
  if (platform === "darwin") {
40
- if (!Number.isInteger(major)) return "macOS";
41
- // Darwin 20 was macOS 11 and every major after it was one more — until 25,
42
- // which Apple shipped as macOS 26 to match the year.
43
- if (major >= 25) return `macOS ${major + 1}${dot}`;
44
- if (major >= 20) return `macOS ${major - 9}${dot}`;
45
- // The 10.x years, where the kernel's major minus four is the second number.
46
- return major >= 5 ? `macOS 10.${major - 4}` : "macOS";
39
+ const v = osVersionOf({ platform, release });
40
+ return v ? `macOS ${v.major}${v.minor === null ? "" : `.${v.minor}`}` : "macOS";
47
41
  }
48
42
  if (platform === "win32") {
49
- // Windows 11 kept the version 10.0 and moved only the build, and 22000 is
50
- // the first one. From here it is the only way to tell the two apart.
51
- if (major === 10 && Number.isInteger(build)) return build >= 22_000 ? "Windows 11" : "Windows 10";
52
- return "Windows";
43
+ const v = osVersionOf({ platform, release });
44
+ return v ? `Windows ${v.major}` : "Windows";
53
45
  }
54
46
  if (platform === "linux") return prettyName || "Linux";
55
47
  return typeof platform === "string" && platform ? platform : "unknown";
@@ -0,0 +1,57 @@
1
+ // Which release of its operating system a machine runs, read off the kernel
2
+ // version Node reports.
3
+ //
4
+ // Node says `darwin 25.5.0` and `win32 10.0.26100`, and nobody calls their
5
+ // laptop Darwin 25. The translation is shared by the two places that say it:
6
+ // a paired deck's card (lan-about.mjs), which words it for a person ("macOS
7
+ // 26.5", "Windows 11"), and the usage reports (reports.mjs), which send it as a
8
+ // short token ("macos-26", "windows-11"). Pure: every input is a parameter, so
9
+ // all three platforms are tested on any one of them, and nothing here reads the
10
+ // machine or throws.
11
+
12
+ /**
13
+ * The OS release a kernel version stands for, as `{ family, major, minor }`, or
14
+ * null when it cannot be told: `{ family: "macos", major: 26, minor: 5 }` for
15
+ * darwin 25.5.0, `{ family: "windows", major: 11, minor: null }` for win32
16
+ * 10.0.26100. `minor` is null when the release does not say one. Only macOS and
17
+ * Windows: a Linux kernel's version says nothing about the distribution on it.
18
+ */
19
+ export function osVersionOf({ platform, release = "" } = {}) {
20
+ const [major, minor, build] = String(release).split(".").map(n => Number.parseInt(n, 10));
21
+ if (platform === "darwin") {
22
+ if (!Number.isInteger(major)) return null;
23
+ const dot = Number.isInteger(minor) ? minor : null;
24
+ // Darwin 20 was macOS 11 and every major after it was one more — until 25,
25
+ // which Apple shipped as macOS 26 to match the year.
26
+ if (major >= 25) return { family: "macos", major: major + 1, minor: dot };
27
+ if (major >= 20) return { family: "macos", major: major - 9, minor: dot };
28
+ // The 10.x years, where the kernel's major minus four is the second number.
29
+ return major >= 5 ? { family: "macos", major: 10, minor: major - 4 } : null;
30
+ }
31
+ if (platform === "win32") {
32
+ // Windows 11 kept the version 10.0 and moved only the build, and 22000 is
33
+ // the first one. From here it is the only way to tell the two apart.
34
+ if (major === 10 && Number.isInteger(build)) return { family: "windows", major: build >= 22_000 ? 11 : 10, minor: null };
35
+ return null;
36
+ }
37
+ return null;
38
+ }
39
+
40
+ /**
41
+ * The fields of an os-release file (os-release(5)): `KEY=value` lines, the
42
+ * value bare or in single or double quotes, a double-quoted one with its
43
+ * backslash escapes undone. Comments, blank lines and anything else are
44
+ * skipped. Never throws.
45
+ */
46
+ export function osReleaseFields(text) {
47
+ const out = {};
48
+ for (const line of String(text ?? "").split(/\r?\n/)) {
49
+ const m = /^\s*([A-Za-z0-9_]+)=(.*)$/.exec(line);
50
+ if (!m) continue;
51
+ let value = m[2].trim();
52
+ const quoted = /^(["'])(.*)\1$/.exec(value);
53
+ if (quoted) value = quoted[1] === '"' ? quoted[2].replace(/\\([\\"$`])/g, "$1") : quoted[2];
54
+ out[m[1]] = value;
55
+ }
56
+ return out;
57
+ }