ccdeck 3.80.0 → 3.81.1

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 (48) hide show
  1. package/README.md +23 -4
  2. package/bin/cli/tui.js +433 -11
  3. package/dist/web/assets/{BrowserWatchModal-Bfvo_8H6.js → BrowserWatchModal-BcvsD8Np.js} +1 -1
  4. package/dist/web/assets/{IntegrationModal-GS5jIQ_J.js → IntegrationModal-BMtv2XWR.js} +1 -1
  5. package/dist/web/assets/{RadioPanel-Bxd2ElWb.js → RadioPanel-k65VVqTb.js} +1 -1
  6. package/dist/web/assets/{TrafficRadar-FgHBI2Oh.js → TrafficRadar-BNw0skS3.js} +1 -1
  7. package/dist/web/assets/{UsageHistoryModal-APwKtE2J.js → UsageHistoryModal-CYxrrwCl.js} +1 -1
  8. package/dist/web/assets/{app-xTrs4aEH.css → app-BIrh5Q0W.css} +1 -1
  9. package/dist/web/assets/{app-BzHVsgB2.js → app-DCoamBD4.js} +93 -93
  10. package/dist/web/assets/{index-7whwMaPX.js → index-BMX8nr4f.js} +1 -1
  11. package/dist/web/index.html +3 -3
  12. package/package.json +1 -1
  13. package/release-notes.json +62 -0
  14. package/src/server/account-notify.mjs +81 -16
  15. package/src/server/account-routes.mjs +20 -2
  16. package/src/server/account-watch.mjs +21 -0
  17. package/src/server/codex-auto.mjs +157 -37
  18. package/src/server/codex-lan-identity.mjs +61 -0
  19. package/src/server/codex-live-engine.mjs +28 -2
  20. package/src/server/codex-live-rpc.mjs +4 -1
  21. package/src/server/codex-profiles.mjs +34 -4
  22. package/src/server/codex-projects.mjs +308 -0
  23. package/src/server/codex-selection.mjs +17 -2
  24. package/src/server/codex-share.mjs +74 -12
  25. package/src/server/codex-terminal.mjs +1 -1
  26. package/src/server/codex-usage.mjs +69 -0
  27. package/src/server/codex-windows-private.mjs +2 -0
  28. package/src/server/codex-windows-private.ps1 +48 -1
  29. package/src/server/index.mjs +6 -4
  30. package/src/server/lan-codex-store.mjs +173 -0
  31. package/src/server/lan-codex.mjs +103 -0
  32. package/src/server/lan-copies.mjs +1 -1
  33. package/src/server/lan-deck.mjs +5 -0
  34. package/src/server/lan-engine.mjs +34 -6
  35. package/src/server/lan-manifest.mjs +16 -2
  36. package/src/server/lan-serve.mjs +21 -6
  37. package/src/server/lifecycle.mjs +2 -2
  38. package/src/server/npm-upgrade.mjs +17 -6
  39. package/src/server/pinned-build.mjs +3 -0
  40. package/src/server/request-gates.mjs +3 -0
  41. package/src/server/self-update.mjs +2 -72
  42. package/src/server/terminal-cli.mjs +8 -2
  43. package/src/server/tui-codex.mjs +229 -0
  44. package/src/server/tui-lan.mjs +684 -0
  45. package/src/server/tui-machine.mjs +492 -0
  46. package/src/server/tui-network.mjs +730 -0
  47. package/src/server/tui-view.mjs +735 -60
  48. package/src/server/version-order.mjs +74 -0
@@ -6,8 +6,8 @@ import { constants } from 'node:fs';
6
6
  import { chmod, lstat, mkdir, open, readFile, unlink } from 'node:fs/promises';
7
7
  import { join } from 'node:path';
8
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';
9
+ import { readCodexSelection, importCodexProfiles, withCodexProfileLocked } from './codex-selection.mjs';
10
+ import { ensureWindowsPrivateDirectory, holdWindowsPrivatePath, protectWindowsCodexLogin } from './codex-windows-private.mjs';
11
11
 
12
12
  export const CODEX_SHARE_PREFIX = 'ccdeck-codex-v1.';
13
13
  export const CODEX_SHARE_MAX_LENGTH = 512_000;
@@ -80,23 +80,30 @@ function requireFileStore(config) {
80
80
  }
81
81
  }
82
82
 
83
+ async function requireFileStoreAt(home) {
84
+ let config = '';
85
+ try {
86
+ const file = join(home, 'config.toml');
87
+ if ((await lstat(file)).size > 128_000) fail('unsupported_auth');
88
+ config = await readFile(file, 'utf8');
89
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
90
+ requireFileStore(config);
91
+ }
92
+
83
93
  async function readFileAuth(home, options) {
84
94
  const platform = options.platform ?? process.platform;
85
95
  let handle, guard;
86
96
  try {
87
97
  // A non-file store can leave a stale auth.json behind. Never export that
88
98
  // 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);
99
+ await requireFileStoreAt(home);
96
100
  const file = join(home, 'auth.json');
97
- if (platform === 'win32') guard = await holdWindowsPrivatePath(file, { ...options, kind: 'file' });
98
101
  const before = await lstat(file);
99
102
  privateAuthFile(before, platform);
103
+ if (platform === 'win32') {
104
+ try { guard = await holdWindowsPrivatePath(file, { ...options, kind: 'file' }); }
105
+ catch { fail('windows_permissions_required'); }
106
+ }
100
107
  handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
101
108
  const opened = await handle.stat();
102
109
  privateAuthFile(opened, platform);
@@ -110,18 +117,28 @@ async function readFileAuth(home, options) {
110
117
  if (guard && !guard.valid()) fail('file_auth_required');
111
118
  return chatgptAuth(JSON.parse(bytes.subarray(0, bytesRead).toString('utf8')));
112
119
  } catch (error) {
113
- if (['file_auth_required', 'unsupported_auth'].includes(error.code)) throw error;
120
+ if (['file_auth_required', 'unsupported_auth', 'windows_permissions_required'].includes(error.code)) throw error;
114
121
  fail('file_auth_required');
115
122
  } finally { try { await handle?.close(); } finally { await guard?.release(); } }
116
123
  }
117
124
 
118
125
  /** Called only by explicit POST export, against opaque registered profile IDs. */
119
- export async function createCodexShare({ ids } = {}, options = {}) {
126
+ export async function createCodexShare({ ids, preparePermissions = false } = {}, options = {}) {
120
127
  if (!Array.isArray(ids) || ids.length < 1 || ids.length > CODEX_SHARE_MAX_ACCOUNTS
121
128
  || new Set(ids).size !== ids.length || ids.some(id => typeof id !== 'string' || !/^[a-f0-9]{20}$/.test(id))) fail('invalid_profiles');
129
+ if (typeof preparePermissions !== 'boolean' || (preparePermissions && (options.platform ?? process.platform) !== 'win32')) fail('invalid_profiles');
122
130
  const selection = await readCodexSelection(options);
123
131
  const profiles = ids.map(id => selection.profiles.find(profile => profile.id === id));
124
132
  if (profiles.some(profile => !profile)) fail('unknown_profile');
133
+ if (preparePermissions) {
134
+ // The export and LAN paths never repair permissions implicitly. Check the
135
+ // credential store for the entire selection before this explicit action.
136
+ for (const profile of profiles) await requireFileStoreAt(profile.home);
137
+ for (const profile of profiles) {
138
+ try { await protectWindowsCodexLogin(profile.home, options); }
139
+ catch { fail('windows_share_protection_failed'); }
140
+ }
141
+ }
125
142
  const accounts = [];
126
143
  for (const profile of profiles) {
127
144
  const label = selection.profileLabels.find(entry => entry.id === profile.id)?.label ?? null;
@@ -156,6 +173,51 @@ function parseShare(blob) {
156
173
  });
157
174
  }
158
175
 
176
+ /** The logins a share carries, validated as an import validates them, without
177
+ * touching disk: Local network reads who a login is before it lands. */
178
+ export function readCodexShare(blob) { return parseShare(blob); }
179
+
180
+ /** Put the one login a share carries into a registered profile's home in place
181
+ * of the login there — only while `stillDead(auth)` says that login is still
182
+ * the one the caller proved superseded. The check and the write happen under
183
+ * the registry lock every sign-in and move of this deck takes, so a sign-in
184
+ * that lands meanwhile is never overwritten. Local network's heal, and only
185
+ * that: an import never replaces anything (see importCodexShare). */
186
+ export async function replaceCodexLoginFromShare({ blob, id, stillDead } = {}, options = {}) {
187
+ const entries = parseShare(blob);
188
+ if (entries.length !== 1 || typeof stillDead !== 'function') fail('invalid_share');
189
+ return withCodexProfileLocked({ id }, async home => {
190
+ const target = join(home, 'auth.json');
191
+ let current = null;
192
+ try {
193
+ const info = await lstat(target);
194
+ if (info.isFile() && info.size <= AUTH_MAX_BYTES) current = JSON.parse(await readFile(target, 'utf8'));
195
+ } catch { /* no login there to replace */ }
196
+ if (!current || !stillDead(current)) fail('login_changed');
197
+ let tmp, guard;
198
+ try {
199
+ // ON WINDOWS ONLY INTO A PRIVATE FOLDER, by the rule secureCodexImportHome
200
+ // states: a profile that arrived over the network has one, while a folder
201
+ // made by a plain mkdir (a sign-in profile, or ~/.codex) does not and is
202
+ // refused here rather than repaired — its permissions are never changed.
203
+ if ((options.platform ?? process.platform) === 'win32') guard = await holdWindowsPrivatePath(home, { ...options, kind: 'directory' });
204
+ const staged = await createTemp(target, { mode: 0o600 });
205
+ tmp = staged.tmp;
206
+ try { await staged.handle.writeFile(JSON.stringify(entries[0].auth) + '\n'); await staged.handle.sync(); }
207
+ finally { await staged.handle.close(); }
208
+ await chmod(tmp, 0o600);
209
+ if (guard && !guard.valid()) fail('windows_permissions_failed');
210
+ await renameWithRetry(tmp, target);
211
+ tmp = null;
212
+ } catch (error) {
213
+ if (tmp) await unlink(tmp).catch(() => {});
214
+ if (error.code === 'windows_permissions_failed' || error.code === 'windows_private_path_unsafe') fail('windows_permissions_failed');
215
+ fail('import_write_failed');
216
+ } finally { await guard?.release(); }
217
+ return { ok: true, home };
218
+ }, options);
219
+ }
220
+
159
221
  /** The common Windows helper creates the directory with its protected DACL
160
222
  * atomically. Never stage a secret into a directory created by plain mkdir on
161
223
  * Windows; chmod there controls read-only, not confidentiality. */
@@ -93,7 +93,7 @@ export async function configureCodexTerminal(action, options = {}) {
93
93
  await chmod(manifest, 0o600);
94
94
  for (const name of ['codex-terminal-runner.mjs', 'exec-spec.mjs', 'account-engine.mjs', 'codex-engine-adapter.mjs', 'codex-handoff.mjs',
95
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',
96
+ 'codex-auto.mjs', 'codex-selection.mjs', 'codex-profiles.mjs', 'codex-lan-identity.mjs', 'codex-native-account.mjs',
97
97
  'codex-auth.mjs', 'codex-dir.mjs', 'deck-home.mjs', 'claude-dir.mjs', 'atomic-write.mjs', 'brand.mjs', 'exec-children.mjs']) {
98
98
  await writeFileAtomic(join(directory, name), await readFile(new URL(`./${name}`, import.meta.url), 'utf8'));
99
99
  await chmod(join(directory, name), 0o600);
@@ -251,6 +251,75 @@ async function readCompressedTokenSeries(filePath) {
251
251
  finally { source?.destroy(); }
252
252
  }
253
253
 
254
+ /**
255
+ * Hand every line of a rollout to `onLine`, plain or compressed, a chunk at a
256
+ * time — the line reader codex-projects.mjs folds a whole rollout with.
257
+ *
258
+ * It is the same read the two series readers above do (a bounded chunk, a
259
+ * StringDecoder for a UTF-8 sequence that straddles a boundary, a final line with
260
+ * no newline, the compressed source held and destroyed), kept apart from them
261
+ * because they build a token series out of each line and this one builds
262
+ * whatever its caller asks. Resolves true when the file was read to its end and
263
+ * false when it could not be (missing, unreadable, a torn archive, or a Node
264
+ * that cannot decompress), so a caller never memoises half a file.
265
+ */
266
+ export async function forEachRolloutLine(filePath, onLine) {
267
+ if (filePath.endsWith(COMPRESSED)) {
268
+ if (!createZstdDecompress) {
269
+ if (!warnedNoZstd) {
270
+ warnedNoZstd = true;
271
+ console.error(
272
+ `${PRODUCT} codex-usage: this Node (${process.version}) cannot read Codex's compressed `
273
+ + "rollouts; sessions older than about a week are being left out. Node 22.15 or newer reads them.",
274
+ );
275
+ }
276
+ return false;
277
+ }
278
+ let source = null;
279
+ try {
280
+ const decoder = new StringDecoder("utf8");
281
+ let pending = "";
282
+ source = createReadStream(filePath);
283
+ const stream = source.pipe(createZstdDecompress());
284
+ source.on("error", err => { stream.destroy(err); });
285
+ for await (const chunk of stream) {
286
+ pending += decoder.write(chunk);
287
+ let from = 0;
288
+ let nl;
289
+ while ((nl = pending.indexOf("\n", from)) >= 0) { onLine(pending.slice(from, nl)); from = nl + 1; }
290
+ if (from > 0) pending = pending.slice(from);
291
+ }
292
+ pending += decoder.end();
293
+ if (pending) onLine(pending);
294
+ return true;
295
+ } catch { return false; }
296
+ finally { source?.destroy(); }
297
+ }
298
+ let fd;
299
+ try {
300
+ fd = await open(filePath, "r");
301
+ const { size } = await fd.stat();
302
+ const buf = Buffer.allocUnsafe(READ_CHUNK_BYTES);
303
+ const decoder = new StringDecoder("utf8");
304
+ let pending = "";
305
+ let pos = 0;
306
+ while (pos < size) {
307
+ const { bytesRead } = await fd.read(buf, 0, READ_CHUNK_BYTES, pos);
308
+ if (bytesRead <= 0) break;
309
+ pos += bytesRead;
310
+ pending += decoder.write(buf.subarray(0, bytesRead));
311
+ let from = 0;
312
+ let nl;
313
+ while ((nl = pending.indexOf("\n", from)) >= 0) { onLine(pending.slice(from, nl)); from = nl + 1; }
314
+ if (from > 0) pending = pending.slice(from);
315
+ }
316
+ pending += decoder.end();
317
+ if (pending) onLine(pending);
318
+ return true;
319
+ } catch { return false; }
320
+ finally { await fd?.close().catch(() => {}); }
321
+ }
322
+
254
323
  /** The reader, exported under a test-only name. The compressed path cannot be
255
324
  * reached through `fetchCodexUsage` without a Codex home full of week-old
256
325
  * sessions, and the thing worth checking is that both spellings produce the
@@ -42,6 +42,8 @@ async function check(path, operation, options) {
42
42
  * execFile is an async (file, args, options) => { stdout } test seam.
43
43
  */
44
44
  export const ensureWindowsPrivateDirectory = async (path, options = {}) => (await check(path, 'ensure', { ...options, kind: 'directory' })).path;
45
+ // Only the explicit Share repair may tighten an existing profile.
46
+ export const protectWindowsCodexLogin = async (path, options = {}) => (await check(path, 'protect-login', { ...options, kind: 'directory' })).path;
45
47
  export const assertWindowsPrivatePath = async (path, options = {}) => (await check(path, 'check', options)).path;
46
48
  export async function inspectWindowsPrivateSocket(path, options = {}) {
47
49
  const value = await check(path, 'check', { ...options, kind: 'socket' });
@@ -1,5 +1,5 @@
1
1
  param(
2
- [ValidateSet('ensure','check','hold')][string]$Operation,
2
+ [ValidateSet('ensure','check','hold','protect-login')][string]$Operation,
3
3
  [Parameter(Mandatory=$true)][string]$TargetPath,
4
4
  [ValidateSet('directory','file','socket')][string]$Kind = 'directory'
5
5
  )
@@ -83,6 +83,49 @@ public static class CodexPrivatePath {
83
83
  Require(userAccess);
84
84
  } finally { if (descriptor != IntPtr.Zero) LocalFree(descriptor); }
85
85
  }
86
+ // Explicit preparation only. Open both objects without following final
87
+ // reparse points or sharing deletion; modify security through those handles,
88
+ // never by looking up an unchecked path a second time. No credential bytes
89
+ // are read, copied or replaced here.
90
+ [DllImport("advapi32.dll", SetLastError=true)]
91
+ static extern uint SetSecurityInfo(SafeFileHandle h, uint type, uint what, IntPtr owner, IntPtr group, IntPtr dacl, IntPtr sacl);
92
+ static SafeFileHandle OpenForProtection(string path, bool directory) {
93
+ var h = CreateFileW(path, 0xe0081u, directory ? 3u : 1u,
94
+ IntPtr.Zero, 3, 0x02000000u | 0x00200000u, IntPtr.Zero);
95
+ if (h.IsInvalid) { h.Dispose(); throw new IOException("unsafe"); }
96
+ try {
97
+ FileInfo info; Require(GetFileInformationByHandle(h, out info));
98
+ Require((info.Attributes & 0x400u) == 0 && ((info.Attributes & 0x10u) != 0) == directory);
99
+ if (!directory) Require(info.Links == 1);
100
+ return h;
101
+ } catch { h.Dispose(); throw; }
102
+ }
103
+ static void Protect(SafeFileHandle h, bool directory) {
104
+ var user = WindowsIdentity.GetCurrent().User;
105
+ var sid = new byte[user.BinaryLength]; user.GetBinaryForm(sid, 0);
106
+ var acl = new RawAcl(2, 1);
107
+ acl.InsertAce(0, new CommonAce(directory ? AceFlags.ContainerInherit | AceFlags.ObjectInherit : AceFlags.None,
108
+ AceQualifier.AccessAllowed, 0x1f01ff, user, false, null));
109
+ var bytes = new byte[acl.BinaryLength]; acl.GetBinaryForm(bytes, 0);
110
+ var owner = GCHandle.Alloc(sid, GCHandleType.Pinned);
111
+ var dacl = GCHandle.Alloc(bytes, GCHandleType.Pinned);
112
+ try {
113
+ Require(SetSecurityInfo(h, 1, 0x80000005u, owner.AddrOfPinnedObject(), IntPtr.Zero, dacl.AddrOfPinnedObject(), IntPtr.Zero) == 0);
114
+ ValidateAcl(h, directory);
115
+ } finally { dacl.Free(); owner.Free(); }
116
+ }
117
+ public static string ProtectLogin(string path) {
118
+ Require(!String.Equals(Path.GetPathRoot(path).TrimEnd('\\'), path.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase));
119
+ using (var directory = OpenForProtection(path, true)) {
120
+ string canonical = Canonical(directory);
121
+ using (var file = OpenForProtection(Path.Combine(canonical, "auth.json"), false)) {
122
+ Protect(file, false);
123
+ Protect(directory, true);
124
+ ValidateAcl(file, false);
125
+ }
126
+ return canonical;
127
+ }
128
+ }
86
129
  public static string SocketGeneration(string path) {
87
130
  // Node/libuv lstat returns EACCES on Windows AF_UNIX entries. Open only
88
131
  // reparse metadata, never follow a symlink/junction or read socket bytes.
@@ -111,6 +154,10 @@ public static class CodexPrivatePath {
111
154
  $guards = [System.Collections.Generic.List[System.IDisposable]]::new()
112
155
  try {
113
156
  $path = [IO.Path]::GetFullPath($TargetPath)
157
+ if ($Operation -eq 'protect-login') {
158
+ if ($Kind -ne 'directory') { throw 'unsafe' }
159
+ $null = [CodexPrivatePath]::ProtectLogin($path)
160
+ }
114
161
  if ($Operation -eq 'ensure') {
115
162
  if ($Kind -ne 'directory') { throw 'unsafe' }
116
163
  [CodexPrivatePath]::Ensure($path)
@@ -139,7 +139,7 @@ export { markDeckReady, releaseRestart } from "./lifecycle.mjs";
139
139
  import { prefsRead } from "./prefs-state.mjs";
140
140
  // Quota read for the account notifications while no page reads it — only while
141
141
  // one of their quota switches is on (account-watch.mjs).
142
- import { startAccountWatch } from "./account-watch.mjs";
142
+ import { startAccountWatch, noteCodexAutoTick } from "./account-watch.mjs";
143
143
  // This deck's LAN engine, what the settings may tell it, and the probe that
144
144
  // asks whether other decks can reach it — see lan-deck.mjs. startServer hands
145
145
  // it the prefs at boot; the settings route does after every write.
@@ -164,7 +164,7 @@ export { sendInternalError };
164
164
  // The accounts surface's routes — see account-routes.mjs. The boot wires the
165
165
  // stale-copy repair and starts auto-switch through the same module.
166
166
  import { handleStopContinue, handleStopContinueRead } from "./stop-continue.mjs";
167
- import { cswapAutoModule, getProjectRollup, handleAccountLoginState, handleAccountProjects, handleClaudeAccountAdmin, handleClaudeAccountSwitch, handleClaudeAccounts, handleCodexProfiles, handleCodexAccountShare, handleCodexProfileQuota, handleCodexProfileLaunch, handleCodexProfileMutation, handleCodexProfileLogin, handleCodexProfileLoginFlow, handleCodexTerminalCommand, handleCodexAuto, handleCodexAutoAction, handleCswapAuto, handleCswapAutoAction, wireAccountOrigins, wireStaleCopyRepair } from "./account-routes.mjs";
167
+ import { cswapAutoModule, getProjectRollup, handleAccountLoginState, handleAccountProjects, handleClaudeAccountAdmin, handleClaudeAccountSwitch, handleClaudeAccounts, handleCodexProfiles, handleCodexAccountShare, handleCodexProfileQuota, handleCodexProfileProjects, handleCodexProfileLaunch, handleCodexProfileMutation, handleCodexProfileLogin, handleCodexProfileLoginFlow, handleCodexTerminalCommand, handleCodexAuto, handleCodexAutoAction, handleCswapAuto, handleCswapAutoAction, wireAccountOrigins, wireStaleCopyRepair } from "./account-routes.mjs";
168
168
  // Browser Watch's three routes — see browser-watch-routes.mjs.
169
169
  import { handleBrowserWatch, handleBrowserWatchDismiss, handleBrowserWatchSettings } from "./browser-watch-routes.mjs";
170
170
  // The music routes, every one behind AGENTS_DECK_NO_MUSIC — see music-routes.mjs.
@@ -404,6 +404,7 @@ export async function startServer({ port = 4317, host = "127.0.0.1", persist = n
404
404
  if (req.method === "GET" && url.pathname === "/api/claude-accounts") return guard(handleClaudeAccounts(req, res), res);
405
405
  if (req.method === "GET" && url.pathname === "/api/codex-profiles") return guard(handleCodexProfiles(req, res), res);
406
406
  if (req.method === "GET" && url.pathname === "/api/codex-profile-quota") return guard(handleCodexProfileQuota(req, res), res);
407
+ if (req.method === "GET" && url.pathname === "/api/codex-profile-projects") return guard(handleCodexProfileProjects(req, res), res);
407
408
  if (req.method === "GET" && url.pathname === "/api/codex-profile-launch") return guard(handleCodexProfileLaunch(req, res), res);
408
409
  if (req.method === "GET" && url.pathname === "/api/codex-auto") return guard(handleCodexAuto(req, res), res);
409
410
  if (req.method === "POST" && url.pathname === "/api/codex-auto") return guard(handleCodexAutoAction(req, res), res);
@@ -602,8 +603,9 @@ export async function startServer({ port = 4317, host = "127.0.0.1", persist = n
602
603
  // caller with nothing to wait for.
603
604
  cswapAutoModule().then(m => m.initCswapAuto({ after: cswapQuiet })).catch(() => {});
604
605
  // Codex's Auto-switch, on the deck's own loop. A settings read a minute
605
- // unless somebody turned it on (codex-auto.mjs).
606
- import("./codex-auto.mjs").then(m => m.startCodexAutoLoop()).catch(() => {});
606
+ // unless somebody turned it on (codex-auto.mjs). Each tick tells the
607
+ // account notifications what it did, for the swap notice.
608
+ import("./codex-auto.mjs").then(m => m.startCodexAutoLoop({ onTick: noteCodexAutoTick })).catch(() => {});
607
609
  // The account notifications' own quota reads, for the providers this deck
608
610
  // watches. Idle — a check of two switches every couple of minutes — unless
609
611
  // the threshold or the reset notification is on.
@@ -0,0 +1,173 @@
1
+ // This deck's Codex accounts as Local network reads, gives and takes them — the
2
+ // store half of lan-codex.mjs's rules, as the claude-swap adapters in
3
+ // lan-deck.mjs are Claude's. The engine never opens a credential: it asks this
4
+ // for rows, for one login sealed as a share, and to place one that arrived.
5
+ //
6
+ // WHAT IS READ is each registered home's auth.json, for three things: who it is
7
+ // signed in as (the id_token's email), which workspace (the account id, hashed
8
+ // into the key), and a hash of the refresh token it holds now. No token leaves
9
+ // this file except inside the share `exportAccount` builds for a `want` the
10
+ // engine has already proved and checked, and nothing is ever refreshed here.
11
+ //
12
+ // WHAT IS KEPT is each profile's token history, as hashes, in
13
+ // codex-lan-lineage.json beside the Codex registry: the token it holds now and
14
+ // the ones it held before. That history is how a paired deck proves its copy
15
+ // of a login is dead (see codexSyncAction), and it outlives a restart because a
16
+ // renewal can happen while the deck is not running.
17
+ import { lstat, mkdir, readFile, unlink } from "node:fs/promises";
18
+ import { dirname, join } from "node:path";
19
+ import { createTemp, renameWithRetry } from "./atomic-write.mjs";
20
+ import { nextLineage } from "./lan-codex.mjs";
21
+ import { codexLoginOf } from "./codex-lan-identity.mjs";
22
+
23
+ export { codexLoginOf };
24
+
25
+ const AUTH_MAX_BYTES = 32_000;
26
+ const LINEAGE_MAX_BYTES = 256_000;
27
+
28
+ /** The login on file in one home, or null: no file, a file that is not a
29
+ * plain bounded one, or one that is not a ChatGPT login. */
30
+ export async function codexLoginOnFile(home) {
31
+ try {
32
+ const file = join(home, "auth.json");
33
+ const info = await lstat(file);
34
+ if (!info.isFile() || info.size > AUTH_MAX_BYTES) return null;
35
+ return codexLoginOf(JSON.parse(await readFile(file, "utf8")));
36
+ } catch { return null; }
37
+ }
38
+
39
+ /**
40
+ * The adapter the LAN engine takes as `codex`. `options` reaches the Codex
41
+ * registry and share modules (a store directory in the suite); `readSelection`,
42
+ * `share` and `settle` may replace those modules' functions there too.
43
+ */
44
+ export function createCodexLan(options = {}) {
45
+ const selectionModule = () => import("./codex-selection.mjs");
46
+ const shareModule = () => import("./codex-share.mjs");
47
+ const readSelection = async () => (options.readSelection ?? (await selectionModule()).readCodexSelection)(options);
48
+
49
+ let lineage = null;
50
+ let writing = Promise.resolve();
51
+ const lineageFile = async () => join(dirname((await selectionModule()).codexSelectionPath(options)), "codex-lan-lineage.json");
52
+ const loadLineage = async () => {
53
+ if (lineage) return lineage;
54
+ let kept = {};
55
+ try {
56
+ const file = await lineageFile();
57
+ if ((await lstat(file)).size <= LINEAGE_MAX_BYTES) {
58
+ const raw = JSON.parse(await readFile(file, "utf8"));
59
+ if (raw && typeof raw.profiles === "object" && raw.profiles && !Array.isArray(raw.profiles)) kept = raw.profiles;
60
+ }
61
+ } catch { /* none yet: every profile starts with no history */ }
62
+ lineage = lineage ?? { profiles: { ...kept } };
63
+ return lineage;
64
+ };
65
+ const saveLineage = () => {
66
+ const text = JSON.stringify(lineage) + "\n";
67
+ writing = writing.then(async () => {
68
+ const target = await lineageFile();
69
+ // The deck's data folder, which nothing may have made yet on a deck that
70
+ // never took a Codex lock.
71
+ await mkdir(dirname(target), { recursive: true, mode: 0o700 });
72
+ const { tmp, handle } = await createTemp(target, { mode: 0o600 });
73
+ try {
74
+ try { await handle.writeFile(text, "utf8"); await handle.sync(); }
75
+ finally { await handle.close(); }
76
+ await renameWithRetry(tmp, target);
77
+ } catch (err) { await unlink(tmp).catch(() => {}); throw err; }
78
+ }).catch(() => { /* kept in memory; the next change writes it again */ });
79
+ return writing;
80
+ };
81
+
82
+ return {
83
+ /** Every registered home signed in to a ChatGPT account, in the rules' shape:
84
+ * `num` is the profile id, `active` the one Codex runs on here. */
85
+ async readAccounts() {
86
+ const selection = await readSelection();
87
+ const kept = await loadLineage();
88
+ let changed = false;
89
+ const rows = [];
90
+ const seen = new Set();
91
+ for (const profile of selection.profiles ?? []) {
92
+ seen.add(profile.id);
93
+ if (!profile.available) continue;
94
+ const login = await codexLoginOnFile(profile.home);
95
+ const next = nextLineage(kept.profiles[profile.id], login?.rt ?? null);
96
+ if (next.changed) { kept.profiles[profile.id] = next.entry; changed = true; }
97
+ if (!login) continue;
98
+ rows.push({
99
+ key: login.key, email: login.email, alive: true, readable: true, unreadableWhy: "export failed",
100
+ num: profile.id, active: profile.id === selection.profileId, rt: login.rt, was: next.entry.was,
101
+ });
102
+ }
103
+ // A profile removed here takes its history with it.
104
+ for (const id of Object.keys(kept.profiles)) {
105
+ if (!seen.has(id)) { delete kept.profiles[id]; changed = true; }
106
+ }
107
+ if (changed) await saveLineage();
108
+ return rows;
109
+ },
110
+
111
+ /** One profile's login as a share holding exactly that login, or null. The
112
+ * share is read back before it goes, so a profile that changed accounts
113
+ * since the manifest never answers a `want` for the old one. */
114
+ async exportAccount(id, expectedKey) {
115
+ try {
116
+ const { createCodexShare, readCodexShare } = await shareModule();
117
+ const out = await (options.share ?? createCodexShare)({ ids: [id] }, options);
118
+ const entries = readCodexShare(out?.blob);
119
+ return entries.length === 1 && codexLoginOf(entries[0].auth)?.key === expectedKey ? out.blob : null;
120
+ } catch (err) {
121
+ if (err?.code === 'windows_permissions_required') throw Object.assign(new Error('windows_permissions_required'), { code: 'windows_permissions_required' });
122
+ return null;
123
+ }
124
+ },
125
+
126
+ /**
127
+ * Place one login that arrived. An add registers a new profile, as Import
128
+ * does; a heal puts it in place of the dead copy `mine` names, and only
129
+ * while that copy is still the token the other deck renewed past.
130
+ *
131
+ * NARROWED TO THE ONE ACCOUNT ASKED FOR. The seal binds the envelope to the
132
+ * key that was requested, not its contents, and a share can carry twenty
133
+ * logins: one that is not exactly the asked-for account is refused whole.
134
+ */
135
+ async importAccount(blob, step, mine) {
136
+ const { importCodexShare, readCodexShare, replaceCodexLoginFromShare } = await shareModule();
137
+ let entries;
138
+ try { entries = readCodexShare(blob); } catch { return { ok: false, why: "import refused" }; }
139
+ if (entries.length !== 1 || codexLoginOf(entries[0].auth)?.key !== step?.key) return { ok: false, why: "import refused" };
140
+ if (step.action === "heal") {
141
+ if (!mine?.num || !mine.rt) return { ok: false, why: "import refused" };
142
+ try {
143
+ const { home } = await replaceCodexLoginFromShare({
144
+ blob, id: mine.num,
145
+ stillDead: auth => {
146
+ const here = codexLoginOf(auth);
147
+ return here?.key === step.key && here.rt === mine.rt;
148
+ },
149
+ }, options);
150
+ // The account did not change, its login did: keep a good reading's
151
+ // floor and drop a failed one, as a sign-in moved in place does.
152
+ try { await (options.settle ?? (await import("./codex-native-account.mjs")).settleMovedLogin)(home); }
153
+ catch { /* the next read settles it */ }
154
+ return { ok: true };
155
+ } catch (err) {
156
+ return { ok: false, why: err?.code === "login_changed" ? "import refused" : "import failed" };
157
+ }
158
+ }
159
+ // A conflict is somebody else changing the registry between the read and
160
+ // the write; one fresh read is enough to tell that from a real failure.
161
+ for (let attempt = 0; attempt < 2; attempt++) {
162
+ try {
163
+ const { revision } = await readSelection();
164
+ const out = await importCodexShare({ blob, expectedRevision: revision }, options);
165
+ return out?.results?.[0]?.status === "imported" ? { ok: true } : { ok: false, why: "import refused" };
166
+ } catch (err) {
167
+ if (err?.code !== "selection_conflict" || attempt) return { ok: false, why: "import failed" };
168
+ }
169
+ }
170
+ return { ok: false, why: "import failed" };
171
+ },
172
+ };
173
+ }
@@ -0,0 +1,103 @@
1
+ // Codex accounts on Local network: the rules, pure, as lan-copies.mjs holds
2
+ // Claude's. No sockets, no timers, no filesystem — the store is
3
+ // lan-codex-store.mjs, and the engine carries both kinds of login over one
4
+ // pairing, one seal and one `want`.
5
+ //
6
+ // THEY TRAVEL IN THEIR OWN LIST. A manifest's `accounts` is Claude's, and every
7
+ // deck since the first one reads it as claude-swap logins: a Codex row there
8
+ // would be asked for, handed over, and refused by `cswap import` on every round
9
+ // of an older deck. So Codex rows go in a `codex` field that an older deck never
10
+ // reads — the same additive rule the card and the usage readings follow.
11
+ import { manifestFor, offered, onePerKey, slotFor } from "./lan-copies.mjs";
12
+ import { CODEX_KEY_PREFIX, codexLanKey, tokenHash } from "./codex-lan-identity.mjs";
13
+
14
+ // The name of a login is a leaf of its own — see codex-lan-identity.mjs.
15
+ export { CODEX_KEY_PREFIX, codexLanKey, tokenHash };
16
+
17
+ /** How many superseded logins a row remembers. A login is renewed about once a
18
+ * week; eight covers two months of a paired deck that was switched off. */
19
+ export const LINEAGE_MAX = 8;
20
+
21
+ const HASH = /^[a-f0-9]{32}$/;
22
+
23
+ export const isCodexKey = key => typeof key === "string" && key.startsWith(CODEX_KEY_PREFIX);
24
+
25
+ /**
26
+ * Remember the refresh token one profile holds now, and the ones it held before.
27
+ * `entry` is what was kept for that profile, or nothing. Returns the entry to
28
+ * keep and whether it changed, so the store writes only when it did.
29
+ */
30
+ export function nextLineage(entry, rt) {
31
+ const was = Array.isArray(entry?.was) ? entry.was.filter(h => HASH.test(h)) : [];
32
+ if (!HASH.test(rt ?? "")) return { entry: { rt: null, was }, changed: !!entry?.rt };
33
+ if (entry?.rt === rt) return { entry: { rt, was }, changed: false };
34
+ const older = HASH.test(entry?.rt ?? "") ? [entry.rt, ...was.filter(h => h !== entry.rt)] : was;
35
+ return { entry: { rt, was: older.filter(h => h !== rt).slice(0, LINEAGE_MAX) }, changed: true };
36
+ }
37
+
38
+ /**
39
+ * What to do about one Codex account, given my copy and a paired deck's.
40
+ *
41
+ * "add" I do not have this account at all.
42
+ * "heal" My copy's refresh token is one the other deck has already renewed
43
+ * past. A Codex refresh token works once: the deck that renews it
44
+ * keeps the account and every other copy is refused from then on. So
45
+ * when that deck says it held my token before the one it holds now,
46
+ * my copy is dead — proven, not guessed from an expiry or a failed
47
+ * read — and its copy is the same login, renewed.
48
+ * null Anything else, which is most of the time.
49
+ *
50
+ * A DIFFERENT LOGIN IS NEVER REPLACED. Somebody who signed in on each machine
51
+ * holds two token families that share no history, so neither deck can find its
52
+ * token in the other's list, and both keep their own. The same holds for a copy
53
+ * that works: it is in nobody's history until somebody renews past it.
54
+ */
55
+ export function codexSyncAction(mine, theirs) {
56
+ if (!theirs || !theirs.alive || theirs.shareable === false) return null;
57
+ if (!mine) return "add";
58
+ return HASH.test(mine.rt ?? "") && Array.isArray(theirs.was) && theirs.was.includes(mine.rt) ? "heal" : null;
59
+ }
60
+
61
+ /** Everything to do this round over one paired deck's Codex list, in key order
62
+ * like Claude's plan, so a failure halfway is the same half each time. */
63
+ export function planCodex(local, remote) {
64
+ const mine = new Map(onePerKey(local).map(a => [a.key, a]));
65
+ const out = [];
66
+ for (const theirs of remote) {
67
+ const action = codexSyncAction(mine.get(theirs.key), theirs);
68
+ if (action) out.push({ key: theirs.key, email: theirs.email, action, provider: "codex" });
69
+ }
70
+ return out.sort((a, b) => a.key.localeCompare(b.key));
71
+ }
72
+
73
+ /**
74
+ * This deck's Codex list for one paired deck: the Claude rules word for word —
75
+ * only what is ticked, the login it is on listed and not given unless its owner
76
+ * said so, nothing about it while that is hidden — plus each row's token
77
+ * history, which is what lets the other deck tell a dead copy of this login from
78
+ * a different login of the same account.
79
+ */
80
+ export function codexManifest(accounts, shared, opts = {}) {
81
+ const codex = accounts.filter(a => isCodexKey(a.key));
82
+ return manifestFor(codex, shared.filter(isCodexKey), opts).map(row => {
83
+ const held = slotFor(codex, row.key);
84
+ return HASH.test(held?.rt ?? "")
85
+ ? { ...row, rt: held.rt, was: (held.was ?? []).filter(h => HASH.test(h)).slice(0, LINEAGE_MAX) }
86
+ : row;
87
+ });
88
+ }
89
+
90
+ /**
91
+ * A paired deck's Codex list as this deck keeps it: read, not trusted. The
92
+ * Claude list's rules — strings where strings belong, fifty logins at most — and
93
+ * only keys that are Codex keys, with hashes that are hashes.
94
+ */
95
+ export function offeredCodex(list) {
96
+ const raw = (Array.isArray(list) ? list : []).filter(a => a && isCodexKey(a.key));
97
+ return offered(raw).filter(a => isCodexKey(a.key)).map(row => {
98
+ const src = raw.find(a => a.key === row.key && HASH.test(a.rt ?? ""));
99
+ if (!src) return row;
100
+ const was = Array.isArray(src.was) ? src.was.filter(h => typeof h === "string" && HASH.test(h)).slice(0, LINEAGE_MAX) : [];
101
+ return { ...row, rt: src.rt, was };
102
+ });
103
+ }
@@ -277,7 +277,7 @@ export const SENDER_UNREADABLE = "keychain_unavailable";
277
277
  * "refused". "in use" is the sending deck being on that login itself (#2192);
278
278
  * a deck older than that records it as "refused", which is all it proves. */
279
279
  export const IN_USE = "in use";
280
- const WIRE_REFUSALS = new Set(["proof", "not shared", "not mine to give", "export failed", SENDER_UNREADABLE, IN_USE, "error"]);
280
+ const WIRE_REFUSALS = new Set(["proof", "not shared", "not mine to give", "export failed", "windows_permissions_required", SENDER_UNREADABLE, IN_USE, "error"]);
281
281
 
282
282
  /**
283
283
  * A peer's refusal, as this deck records it. The panel prints these, so a peer
@@ -27,6 +27,7 @@ import { createRouteCheck } from "./route-via.mjs";
27
27
  import { DISCOVERY_PORT } from "./lan-beacon.mjs";
28
28
  import { aboutThisDeck } from "./lan-about.mjs";
29
29
  import { createUsageShare } from "./usage-share.mjs";
30
+ import { createCodexLan } from "./lan-codex-store.mjs";
30
31
  import { MAC_FW, PROBE_PS, UFW_CONF, UFW_DEFAULTS, isActive, localAliases, reachability, readMacProbe, readProbe, readUfw, silentInbound } from "./lan-reach.mjs";
31
32
  import { run } from "./exec.mjs";
32
33
  // A LAN round checks the imports it lands the way the paste box does.
@@ -131,6 +132,10 @@ export const lanEngine = createEngine({
131
132
  // moved/reused slot can never satisfy a want for another account.
132
133
  return accountKey(accounts[0]?.email, accounts[0]?.organizationUuid) === expectedKey ? out.blob : null;
133
134
  },
135
+ // This deck's Codex logins, offered and taken by the same pairing in a list
136
+ // of their own — see lan-codex.mjs for the rules and lan-codex-store.mjs for
137
+ // what is read and written.
138
+ codex: createCodexLan(),
134
139
  // The logins a round just imported, checked once after it — see checkImports.
135
140
  checkArrivals: async steps => {
136
141
  const { checkImports } = await import("./cswap-admin.mjs");