ccdeck 3.53.2 → 3.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +56 -4
  2. package/THIRD_PARTY_NOTICES.md +31 -1
  3. package/dist/web/assets/{BrowserWatchModal-DedhCY8E.js → BrowserWatchModal-Bfvo_8H6.js} +1 -1
  4. package/dist/web/assets/{IntegrationModal-1m1mQQhW.js → IntegrationModal-GS5jIQ_J.js} +1 -1
  5. package/dist/web/assets/{RadioPanel-Sgo5WNTi.js → RadioPanel-Bxd2ElWb.js} +1 -1
  6. package/dist/web/assets/{TrafficRadar-BqjzLlO_.js → TrafficRadar-FgHBI2Oh.js} +1 -1
  7. package/dist/web/assets/{UsageHistoryModal-2pcftBwX.js → UsageHistoryModal-APwKtE2J.js} +1 -1
  8. package/dist/web/assets/{app-BZaB84m4.js → app-BzHVsgB2.js} +90 -90
  9. package/dist/web/assets/{index-D1WZBFCw.js → index-7whwMaPX.js} +1 -1
  10. package/dist/web/index.html +2 -2
  11. package/node_modules/ws/LICENSE +20 -0
  12. package/node_modules/ws/README.md +540 -0
  13. package/node_modules/ws/browser.js +8 -0
  14. package/node_modules/ws/index.js +22 -0
  15. package/node_modules/ws/lib/buffer-util.js +142 -0
  16. package/node_modules/ws/lib/constants.js +19 -0
  17. package/node_modules/ws/lib/event-target.js +292 -0
  18. package/node_modules/ws/lib/extension.js +203 -0
  19. package/node_modules/ws/lib/limiter.js +55 -0
  20. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  21. package/node_modules/ws/lib/receiver.js +743 -0
  22. package/node_modules/ws/lib/sender.js +610 -0
  23. package/node_modules/ws/lib/stream.js +161 -0
  24. package/node_modules/ws/lib/subprotocol.js +62 -0
  25. package/node_modules/ws/lib/validation.js +152 -0
  26. package/node_modules/ws/lib/websocket-server.js +562 -0
  27. package/node_modules/ws/lib/websocket.js +1426 -0
  28. package/node_modules/ws/package.json +74 -0
  29. package/node_modules/ws/wrapper.mjs +21 -0
  30. package/package.json +5 -3
  31. package/release-notes.json +39 -1
  32. package/src/server/account-engine.mjs +87 -0
  33. package/src/server/account-routes.mjs +31 -3
  34. package/src/server/codex-auto.mjs +7 -18
  35. package/src/server/codex-engine-adapter.mjs +272 -0
  36. package/src/server/codex-engine-bridge.mjs +47 -0
  37. package/src/server/codex-engine-config.mjs +42 -0
  38. package/src/server/codex-engine-rpc.mjs +88 -0
  39. package/src/server/codex-handoff.mjs +20 -0
  40. package/src/server/codex-interactive-engine.mjs +335 -0
  41. package/src/server/codex-live-checkpoint.mjs +55 -0
  42. package/src/server/codex-live-credentials.mjs +214 -0
  43. package/src/server/codex-live-engine.mjs +577 -0
  44. package/src/server/codex-live-handoff.mjs +300 -0
  45. package/src/server/codex-live-lease.mjs +64 -0
  46. package/src/server/codex-live-rpc.mjs +155 -0
  47. package/src/server/codex-quota.mjs +36 -2
  48. package/src/server/codex-selection.mjs +62 -8
  49. package/src/server/codex-share.mjs +193 -0
  50. package/src/server/codex-terminal-runner.mjs +38 -1
  51. package/src/server/codex-terminal.mjs +15 -3
  52. package/src/server/codex-watch.mjs +3 -1
  53. package/src/server/codex-windows-private.mjs +96 -0
  54. package/src/server/codex-windows-private.ps1 +140 -0
  55. package/src/server/codex-windows-proxy.mjs +53 -0
  56. package/src/server/deck-prefs.mjs +6 -1
  57. package/src/server/index.mjs +9 -2
  58. package/src/server/login-service.mjs +2 -0
  59. package/src/server/pinned-build.mjs +2 -0
  60. package/src/server/reports-routes.mjs +10 -0
  61. package/src/server/reports.mjs +46 -5
  62. package/src/server/ui-language.mjs +17 -0
@@ -0,0 +1,214 @@
1
+ // Read only the credential owned/refreshed by the selected native Codex home.
2
+ // Never log RPC payloads, expose refresh tokens, or write auth/config files.
3
+ import { constants } from 'node:fs';
4
+ import { lstat, open, realpath } from 'node:fs/promises';
5
+ import { createHash } from 'node:crypto';
6
+ import { spawn } from 'node:child_process';
7
+ import { join, resolve } from 'node:path';
8
+ import { performance } from 'node:perf_hooks';
9
+ import { readCodexSelection } from './codex-selection.mjs';
10
+ import { startEngineRpc } from './codex-engine-rpc.mjs';
11
+ import { pathLookup } from './exec-spec.mjs';
12
+ import { holdWindowsPrivatePath } from './codex-windows-private.mjs';
13
+
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,
17
+ // plus the owned process's four-second shutdown; never retry a native request.
18
+ const NATIVE_DEADLINE_MS = process.platform === 'win32' ? 34000 : 7000;
19
+ // startEngineRpc.stop() closes stdin, then escalates at 2s and 4s. Reserve its
20
+ // full shutdown window rather than giving each request another seven seconds.
21
+ const STOP_RESERVE_MS = 4000;
22
+ class CredentialError extends Error {
23
+ constructor(code) {
24
+ super(code);
25
+ this.code = code;
26
+ this.stack = `Error: ${code}`;
27
+ }
28
+ }
29
+ const fail = code => { throw new CredentialError(code); };
30
+ const sanitized = (error, code) => error instanceof CredentialError ? error : new CredentialError(code);
31
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
32
+ const sameNode = (a, b) => a.dev === b.dev && a.ino === b.ino && a.mode === b.mode;
33
+ const sameFile = (a, b) => sameNode(a, b) && a.uid === b.uid && a.size === b.size
34
+ && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs && a.nlink === b.nlink;
35
+
36
+ async function beforeDeadline(action, deadline) {
37
+ const remaining = deadline - performance.now();
38
+ if (remaining <= 0) fail('native_timeout');
39
+ let timer;
40
+ try {
41
+ const value = await Promise.race([
42
+ Promise.resolve().then(action),
43
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new CredentialError('native_timeout')), remaining); }),
44
+ ]);
45
+ if (performance.now() >= deadline) fail('native_timeout');
46
+ return value;
47
+ } finally { clearTimeout(timer); }
48
+ }
49
+
50
+ function profileFrom(selection, profileId) {
51
+ const profile = selection.profiles.find(p => p.id === profileId);
52
+ if (!profile) fail('unknown_profile');
53
+ if (!profile.available) fail('profile_unavailable');
54
+ return profile;
55
+ }
56
+ async function captureProfile(profile) {
57
+ const canonical = await realpath(profile.home);
58
+ if (createHash('sha256').update(canonical).digest('hex').slice(0, 20) !== profile.id) fail('profile_changed');
59
+ const literal = await lstat(profile.home, { bigint: true });
60
+ const directory = await lstat(canonical, { bigint: true });
61
+ if (!directory.isDirectory()) fail('profile_unavailable');
62
+ return { canonical, literal, directory };
63
+ }
64
+ async function revalidateProfile(profile, captured, revision, options) {
65
+ try {
66
+ const selection = await readCodexSelection(options);
67
+ const current = profileFrom(selection, profile.id);
68
+ if (selection.revision !== revision || current.home !== profile.home || await realpath(current.home) !== captured.canonical
69
+ || !sameNode(await lstat(current.home, { bigint: true }), captured.literal)
70
+ || !sameNode(await lstat(captured.canonical, { bigint: true }), captured.directory)) fail('profile_changed');
71
+ } catch { fail('profile_changed'); }
72
+ }
73
+
74
+ async function nativeAccount(home, env, executable, startRpc, refresh) {
75
+ const deadline = performance.now() + NATIVE_DEADLINE_MS;
76
+ const requestDeadline = deadline - STOP_RESERVE_MS;
77
+ let rpc, account, failure;
78
+ try {
79
+ rpc = startRpc(executable, ['app-server', '--listen', 'stdio://'], home, {
80
+ env, deadlineMs: Math.max(1, requestDeadline - performance.now()),
81
+ spawnChild: (file, args, settings) => spawn(file, args, { ...settings, cwd: home }),
82
+ });
83
+ await beforeDeadline(() => rpc.request('initialize', {
84
+ clientInfo: { name: 'ccdeck', title: 'ccdeck', version: '1' },
85
+ capabilities: { experimentalApi: true },
86
+ }), requestDeadline);
87
+ await beforeDeadline(() => rpc.send({ method: 'initialized', params: {} }), requestDeadline);
88
+ const result = await beforeDeadline(() => rpc.request('config/read', { includeLayers: false, cwd: home }), requestDeadline);
89
+ if (!record(result?.config)) fail('unsupported_credentials_store');
90
+ const store = result.config.cli_auth_credentials_store;
91
+ if (store != null && store !== 'file') fail('unsupported_credentials_store');
92
+ account = await beforeDeadline(() => rpc.request('account/read', { refreshToken: refresh }), requestDeadline);
93
+ if (account?.account?.type !== 'chatgpt') fail('unsupported_auth');
94
+ } catch (error) { failure = sanitized(error, 'native_error'); }
95
+ finally {
96
+ if (rpc) {
97
+ // This handle is created for this read alone; never stop a shared engine.
98
+ try {
99
+ const stopping = Promise.resolve(rpc.stop());
100
+ // Always initiate shutdown, even if an event-loop stall used the budget.
101
+ stopping.catch(() => {});
102
+ if (await beforeDeadline(() => stopping, deadline) === false) fail('native_error');
103
+ } catch (error) { failure ??= sanitized(error, 'native_error'); }
104
+ }
105
+ }
106
+ if (failure) throw failure;
107
+ return account;
108
+ }
109
+
110
+ function privateFile(info, windows) {
111
+ if (!info.isFile() || info.size > BigInt(MAX_AUTH_BYTES)
112
+ || !windows && (typeof process.getuid !== 'function' || info.uid !== BigInt(process.getuid())
113
+ || (info.mode & 0o7777n & ~0o600n) !== 0n)) fail('credential_file_unsafe');
114
+ }
115
+ function jwtClaims(token) {
116
+ if (typeof token !== 'string' || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token)) fail('invalid_credentials');
117
+ let claims;
118
+ try { claims = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8')); }
119
+ catch { fail('invalid_credentials'); }
120
+ if (!record(claims)) fail('invalid_credentials');
121
+ return claims;
122
+ }
123
+ const validEmail = value => typeof value === 'string' && value.length <= 254 && /^[^\s@/\\\x00-\x1f\x7f]+@[^\s@/\\\x00-\x1f\x7f]+$/.test(value);
124
+ const validAccountId = value => typeof value === 'string' && value.length > 0 && value.length <= 256 && !/[\s/\\\x00-\x1f\x7f]/.test(value);
125
+ const plan = value => typeof value === 'string' && /^[a-z0-9_-]{1,40}$/.test(value) ? value : null;
126
+ function credentialFrom(auth, snapshot, profileId) {
127
+ const account = snapshot.account;
128
+ if (auth?.auth_mode !== 'chatgpt' || auth.OPENAI_API_KEY != null) fail('unsupported_auth');
129
+ const tokens = auth.tokens;
130
+ if (!record(tokens) || !validAccountId(tokens.account_id)) fail('invalid_credentials');
131
+ // Deliberately never access tokens.refresh_token, even when native refreshed.
132
+ const identity = jwtClaims(tokens.id_token);
133
+ const access = jwtClaims(tokens.access_token);
134
+ const email = identity.email ?? identity['https://api.openai.com/profile']?.email;
135
+ const claims = identity['https://api.openai.com/auth'];
136
+ if (!validEmail(email) || !validEmail(account.email) || email.toLowerCase() !== account.email.toLowerCase()
137
+ || (claims?.chatgpt_account_id != null && claims.chatgpt_account_id !== tokens.account_id)
138
+ || (account.accountId != null && account.accountId !== tokens.account_id)
139
+ || (account.id != null && account.id !== tokens.account_id)
140
+ || (snapshot.workspaceRouting?.chatgptAccountId != null && snapshot.workspaceRouting.chatgptAccountId !== tokens.account_id)) fail('identity_mismatch');
141
+ if (!Number.isSafeInteger(access.exp) || access.exp <= 0 || access.exp > 8_640_000_000_000) fail('invalid_credentials');
142
+ const expiresAt = access.exp * 1000;
143
+ if (expiresAt <= Date.now()) fail('credential_expired');
144
+ return { profileId, accessToken: tokens.access_token, accountId: tokens.account_id, email,
145
+ planType: plan(account.planType) ?? plan(claims?.chatgpt_plan_type), expiresAt };
146
+ }
147
+
148
+ /** Server-owned options only. profileId is a roster ID, never a home/path.
149
+ * expiresAt is Unix milliseconds. Native Codex owns any requested refresh.
150
+ * POSIX uses UID/private modes and O_NOFOLLOW; Windows uses pinned private
151
+ * DACL-validated directory/file handles as its no-follow substitute.
152
+ */
153
+ export async function readLiveCodexCredential(profileId, options = {}) {
154
+ let phase = 'profile_unavailable', profileGuard;
155
+ try {
156
+ const platform = options.platform ?? process.platform, windows = platform === 'win32';
157
+ if (typeof profileId !== 'string' || !/^[a-f0-9]{20}$/.test(profileId)) fail('unknown_profile');
158
+ const env = { ...(options.env ?? process.env) };
159
+ const selectionOptions = { store: options.store, env };
160
+ const selection = await readCodexSelection(selectionOptions);
161
+ const profile = profileFrom(selection, profileId);
162
+ if (windows) {
163
+ try { profileGuard = await holdWindowsPrivatePath(profile.home, { ...options.windowsPrivate, kind: 'directory' }); }
164
+ catch { fail('credential_file_unsafe'); }
165
+ }
166
+ const captured = await captureProfile(profile);
167
+ const childEnv = { ...env, CODEX_HOME: captured.canonical };
168
+ for (const key of Object.keys(childEnv)) if (/^(OPENAI_API_KEY|CODEX_API_KEY)$/i.test(key)) delete childEnv[key];
169
+ phase = 'native_unavailable';
170
+ const executable = options.executable ?? pathLookup('codex', platform, { pathEnv: childEnv.PATH ?? childEnv.Path ?? '' });
171
+ if (typeof executable !== 'string' || !executable || executable.includes('\0')) fail('native_unavailable');
172
+ phase = 'native_error';
173
+ // Resolve before entering the profile directory so a relative PATH entry
174
+ // cannot select an executable from that profile instead of the server cwd.
175
+ const account = await nativeAccount(captured.canonical, childEnv, resolve(executable), options.startRpc ?? startEngineRpc, options.refresh === true);
176
+ // Native has finished refreshing and its owned process has stopped. No
177
+ // pre-refresh file version is compared with the legitimately renewed file.
178
+ await revalidateProfile(profile, captured, selection.revision, selectionOptions);
179
+ phase = 'credential_unavailable';
180
+ const file = join(captured.canonical, 'auth.json');
181
+ let handle, fileGuard;
182
+ try {
183
+ if (windows) {
184
+ try { fileGuard = await holdWindowsPrivatePath(file, { ...options.windowsPrivate, kind: 'file' }); }
185
+ catch { fail('credential_file_unsafe'); }
186
+ }
187
+ const initial = await lstat(file, { bigint: true });
188
+ privateFile(initial, windows);
189
+ if (!windows && typeof constants.O_NOFOLLOW !== 'number') fail('credential_file_unsafe');
190
+ handle = await open(file, constants.O_RDONLY | (windows ? 0 : constants.O_NOFOLLOW | constants.O_NONBLOCK));
191
+ const opened = await handle.stat({ bigint: true });
192
+ privateFile(opened, windows);
193
+ if (!sameFile(initial, opened)) fail('credential_file_changed');
194
+ const bytes = Buffer.alloc(MAX_AUTH_BYTES + 1);
195
+ let length = 0;
196
+ while (length < bytes.length) {
197
+ const { bytesRead } = await handle.read(bytes, length, bytes.length - length, null);
198
+ if (!bytesRead) break;
199
+ length += bytesRead;
200
+ }
201
+ if (length > MAX_AUTH_BYTES || BigInt(length) !== opened.size) fail('credential_file_changed');
202
+ let auth;
203
+ try { auth = JSON.parse(bytes.subarray(0, length).toString('utf8')); }
204
+ catch { fail('invalid_credentials'); }
205
+ const credential = credentialFrom(auth, account, profileId);
206
+ await revalidateProfile(profile, captured, selection.revision, selectionOptions);
207
+ if (!sameFile(opened, await handle.stat({ bigint: true })) || !sameFile(opened, await lstat(file, { bigint: true }))) fail('credential_file_changed');
208
+ if (windows && (!profileGuard.valid() || !fileGuard.valid())) fail('credential_file_changed');
209
+ if (credential.expiresAt <= Date.now()) fail('credential_expired');
210
+ return credential;
211
+ } finally { await handle?.close(); await fileGuard?.release(); }
212
+ } catch (error) { throw sanitized(error, phase); }
213
+ finally { await profileGuard?.release(); }
214
+ }