ccdeck 3.53.3 → 3.81.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.
- package/README.md +63 -7
- package/THIRD_PARTY_NOTICES.md +31 -1
- package/bin/cli/tui.js +433 -11
- package/dist/web/assets/{BrowserWatchModal-CJ0CW4Go.js → BrowserWatchModal-DKvBSlGT.js} +1 -1
- package/dist/web/assets/{IntegrationModal-DlJzBN8b.js → IntegrationModal-D3NLczRe.js} +1 -1
- package/dist/web/assets/{RadioPanel-CHl3s3OH.js → RadioPanel-dCIMGTd9.js} +1 -1
- package/dist/web/assets/{TrafficRadar-Cw3i0Hux.js → TrafficRadar-CMbwnKe7.js} +1 -1
- package/dist/web/assets/{UsageHistoryModal-CiB5-CTH.js → UsageHistoryModal-DkGBQaM4.js} +1 -1
- package/dist/web/assets/{app-xTrs4aEH.css → app-BIrh5Q0W.css} +1 -1
- package/dist/web/assets/{app-2vj7uk2U.js → app-l0spNrc0.js} +93 -93
- package/dist/web/assets/{index-D1YZbdq3.js → index-inV7HzhI.js} +1 -1
- package/dist/web/index.html +3 -3
- package/node_modules/ws/LICENSE +20 -0
- package/node_modules/ws/README.md +540 -0
- package/node_modules/ws/browser.js +8 -0
- package/node_modules/ws/index.js +22 -0
- package/node_modules/ws/lib/buffer-util.js +142 -0
- package/node_modules/ws/lib/constants.js +19 -0
- package/node_modules/ws/lib/event-target.js +292 -0
- package/node_modules/ws/lib/extension.js +203 -0
- package/node_modules/ws/lib/limiter.js +55 -0
- package/node_modules/ws/lib/permessage-deflate.js +530 -0
- package/node_modules/ws/lib/receiver.js +743 -0
- package/node_modules/ws/lib/sender.js +610 -0
- package/node_modules/ws/lib/stream.js +161 -0
- package/node_modules/ws/lib/subprotocol.js +62 -0
- package/node_modules/ws/lib/validation.js +152 -0
- package/node_modules/ws/lib/websocket-server.js +562 -0
- package/node_modules/ws/lib/websocket.js +1426 -0
- package/node_modules/ws/package.json +74 -0
- package/node_modules/ws/wrapper.mjs +21 -0
- package/package.json +5 -3
- package/release-notes.json +71 -0
- package/src/server/account-engine.mjs +87 -0
- package/src/server/account-notify.mjs +81 -16
- package/src/server/account-routes.mjs +49 -3
- package/src/server/account-watch.mjs +21 -0
- package/src/server/codex-auto.mjs +163 -54
- package/src/server/codex-engine-adapter.mjs +272 -0
- package/src/server/codex-engine-bridge.mjs +47 -0
- package/src/server/codex-engine-config.mjs +42 -0
- package/src/server/codex-engine-rpc.mjs +88 -0
- package/src/server/codex-handoff.mjs +20 -0
- package/src/server/codex-interactive-engine.mjs +335 -0
- package/src/server/codex-lan-identity.mjs +61 -0
- package/src/server/codex-live-checkpoint.mjs +55 -0
- package/src/server/codex-live-credentials.mjs +214 -0
- package/src/server/codex-live-engine.mjs +577 -0
- package/src/server/codex-live-handoff.mjs +300 -0
- package/src/server/codex-live-lease.mjs +64 -0
- package/src/server/codex-live-rpc.mjs +158 -0
- package/src/server/codex-profiles.mjs +34 -4
- package/src/server/codex-projects.mjs +308 -0
- package/src/server/codex-quota.mjs +36 -2
- package/src/server/codex-selection.mjs +78 -9
- package/src/server/codex-share.mjs +238 -0
- package/src/server/codex-terminal-runner.mjs +38 -1
- package/src/server/codex-terminal.mjs +15 -3
- package/src/server/codex-usage.mjs +69 -0
- package/src/server/codex-watch.mjs +3 -1
- package/src/server/codex-windows-private.mjs +96 -0
- package/src/server/codex-windows-private.ps1 +140 -0
- package/src/server/codex-windows-proxy.mjs +53 -0
- package/src/server/index.mjs +12 -4
- package/src/server/lan-codex-store.mjs +170 -0
- package/src/server/lan-codex.mjs +103 -0
- package/src/server/lan-deck.mjs +5 -0
- package/src/server/lan-engine.mjs +34 -6
- package/src/server/lan-manifest.mjs +16 -2
- package/src/server/lan-serve.mjs +16 -6
- package/src/server/login-service.mjs +2 -0
- package/src/server/pinned-build.mjs +5 -0
- package/src/server/request-gates.mjs +3 -0
- package/src/server/tui-codex.mjs +229 -0
- package/src/server/tui-lan.mjs +684 -0
- package/src/server/tui-machine.mjs +492 -0
- package/src/server/tui-network.mjs +730 -0
- package/src/server/tui-view.mjs +735 -60
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
// Explicit, portable file-auth transfer. This is encoding, not encryption:
|
|
2
|
+
// possession of the code grants the same login as possession of auth.json.
|
|
3
|
+
// No expiry, revocation, JWT verification, refresh, native login or network I/O.
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { constants } from 'node:fs';
|
|
6
|
+
import { chmod, lstat, mkdir, open, readFile, unlink } from 'node:fs/promises';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { createTemp, renameWithRetry } from './atomic-write.mjs';
|
|
9
|
+
import { readCodexSelection, importCodexProfiles, withCodexProfileLocked } from './codex-selection.mjs';
|
|
10
|
+
import { ensureWindowsPrivateDirectory, holdWindowsPrivatePath } from './codex-windows-private.mjs';
|
|
11
|
+
|
|
12
|
+
export const CODEX_SHARE_PREFIX = 'ccdeck-codex-v1.';
|
|
13
|
+
export const CODEX_SHARE_MAX_LENGTH = 512_000;
|
|
14
|
+
export const CODEX_SHARE_MAX_ACCOUNTS = 20;
|
|
15
|
+
const AUTH_MAX_BYTES = 32_000;
|
|
16
|
+
const fail = code => { throw Object.assign(new Error(code), { code }); };
|
|
17
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
18
|
+
const keys = (value, allowed) => object(value) && Object.keys(value).every(key => allowed.includes(key));
|
|
19
|
+
const token = value => typeof value === 'string' && value.length > 0 && value.length <= 16_000 && /^[\x21-\x7e]+$/.test(value);
|
|
20
|
+
const safeLabel = value => value === null || (typeof value === 'string' && value.length > 0 && value.length <= 80 && value === value.trim() && !/[\x00-\x1f\x7f/\\]/.test(value));
|
|
21
|
+
|
|
22
|
+
function oauthProvenance(value) {
|
|
23
|
+
if (value === undefined || value === null) return true;
|
|
24
|
+
if (!keys(value, ['issuer', 'client_id']) || !token(value.issuer) || value.issuer.length > 2048
|
|
25
|
+
|| !token(value.client_id) || value.client_id.length > 512) return false;
|
|
26
|
+
// Codex uses this issuer as the refresh destination, not just display data.
|
|
27
|
+
// Transfer only HTTPS OpenAI authorities; never infer one from JWT claims.
|
|
28
|
+
try {
|
|
29
|
+
const issuer = new URL(value.issuer);
|
|
30
|
+
return issuer.protocol === 'https:' && !issuer.username && !issuer.password && !issuer.port
|
|
31
|
+
&& !/[?#\\]/.test(value.issuer)
|
|
32
|
+
&& ['openai.com', 'chatgpt.com'].some(host => issuer.hostname === host || issuer.hostname.endsWith(`.${host}`));
|
|
33
|
+
} catch { return false; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Whitelist the on-disk ChatGPT schema, never source paths/config/extra keys.
|
|
37
|
+
* Token strings stay opaque; a decoded JWT is never proof of identity. */
|
|
38
|
+
function chatgptAuth(raw) {
|
|
39
|
+
if (!keys(raw, ['auth_mode', 'OPENAI_API_KEY', 'tokens', 'last_refresh'])
|
|
40
|
+
|| (raw.auth_mode !== undefined && raw.auth_mode !== 'chatgpt')
|
|
41
|
+
|| (raw.OPENAI_API_KEY !== undefined && raw.OPENAI_API_KEY !== null)
|
|
42
|
+
|| !keys(raw.tokens, ['access_token', 'refresh_token', 'id_token', 'account_id', 'oauth_provenance', 'login_owner_id'])
|
|
43
|
+
|| !['access_token', 'refresh_token', 'id_token'].every(key => token(raw.tokens[key]))
|
|
44
|
+
|| !oauthProvenance(raw.tokens.oauth_provenance)
|
|
45
|
+
|| (raw.tokens.login_owner_id != null && (typeof raw.tokens.login_owner_id !== 'string' || !/^[A-Za-z0-9_-]{1,512}$/.test(raw.tokens.login_owner_id)))
|
|
46
|
+
|| (raw.tokens.account_id !== undefined && (!token(raw.tokens.account_id) || raw.tokens.account_id.length > 512))
|
|
47
|
+
|| (raw.last_refresh !== undefined && (typeof raw.last_refresh !== 'string' || raw.last_refresh.length > 40 || !Number.isFinite(Date.parse(raw.last_refresh))))) fail('unsupported_auth');
|
|
48
|
+
// Codex 0.166 TokenData preserves these optional fields across refreshes.
|
|
49
|
+
// login_owner_id identifies a completed login, not a machine: preserve it
|
|
50
|
+
// with its grant rather than generating a new login or dropping provenance.
|
|
51
|
+
// Schema/semantics: openai/codex rust-v0.166.0 (6ff1e1ca), login/src/token_data.rs,
|
|
52
|
+
// server.rs and auth/{account_grant,manager}.rs. Legacy fields stay absent.
|
|
53
|
+
const auth = { auth_mode: 'chatgpt', OPENAI_API_KEY: null, tokens: { ...raw.tokens }, ...(raw.last_refresh !== undefined ? { last_refresh: raw.last_refresh } : {}) };
|
|
54
|
+
if (Buffer.byteLength(JSON.stringify(auth)) > AUTH_MAX_BYTES) fail('unsupported_auth');
|
|
55
|
+
return auth;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function privateAuthFile(info, platform) {
|
|
59
|
+
if (!info.isFile() || info.size > AUTH_MAX_BYTES || info.nlink !== 1
|
|
60
|
+
|| (platform !== 'win32' && (typeof process.getuid !== 'function' || info.uid !== process.getuid() || (info.mode & 0o7777 & ~0o600) !== 0))) fail('file_auth_required');
|
|
61
|
+
}
|
|
62
|
+
const unchangedFile = (a, b) => a.ino === b.ino && a.dev === b.dev && a.size === b.size
|
|
63
|
+
&& a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs && a.mode === b.mode && a.uid === b.uid && a.nlink === b.nlink;
|
|
64
|
+
|
|
65
|
+
/** Conservative store detection, NOT a TOML parser. Profiles/dotted keys,
|
|
66
|
+
* duplicates, multiline strings and escaped key spellings are ambiguous.
|
|
67
|
+
* Only absent/default or one literal root-level file setting is exportable. */
|
|
68
|
+
function requireFileStore(config) {
|
|
69
|
+
if (/'''|"""/.test(config)) fail('file_auth_required');
|
|
70
|
+
let section = false, seen = false;
|
|
71
|
+
for (const line of config.split('\n')) {
|
|
72
|
+
const trimmed = line.trim();
|
|
73
|
+
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
74
|
+
if (trimmed.startsWith('[')) { section = true; continue; }
|
|
75
|
+
const key = line.split('=')[0];
|
|
76
|
+
if (key.includes('\\')) fail('file_auth_required');
|
|
77
|
+
if (!key.includes('cli_auth_credentials_store')) continue;
|
|
78
|
+
if (section || seen || !/^\s*(?:cli_auth_credentials_store|["']cli_auth_credentials_store["'])\s*=\s*["']file["']\s*(?:#.*)?$/.test(line)) fail('file_auth_required');
|
|
79
|
+
seen = true;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function readFileAuth(home, options) {
|
|
84
|
+
const platform = options.platform ?? process.platform;
|
|
85
|
+
let handle, guard;
|
|
86
|
+
try {
|
|
87
|
+
// A non-file store can leave a stale auth.json behind. Never export that
|
|
88
|
+
// stale copy as if it were the actual native login. Unknown TOML is refused.
|
|
89
|
+
let config = '';
|
|
90
|
+
try {
|
|
91
|
+
const file = join(home, 'config.toml');
|
|
92
|
+
if ((await lstat(file)).size > 128_000) fail('unsupported_auth');
|
|
93
|
+
config = await readFile(file, 'utf8');
|
|
94
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
95
|
+
requireFileStore(config);
|
|
96
|
+
const file = join(home, 'auth.json');
|
|
97
|
+
if (platform === 'win32') guard = await holdWindowsPrivatePath(file, { ...options, kind: 'file' });
|
|
98
|
+
const before = await lstat(file);
|
|
99
|
+
privateAuthFile(before, platform);
|
|
100
|
+
handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
101
|
+
const opened = await handle.stat();
|
|
102
|
+
privateAuthFile(opened, platform);
|
|
103
|
+
if (!unchangedFile(opened, before)) fail('file_auth_required');
|
|
104
|
+
// Bounded even if the file grows after stat.
|
|
105
|
+
const bytes = Buffer.alloc(AUTH_MAX_BYTES + 1);
|
|
106
|
+
const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
|
|
107
|
+
const after = await handle.stat(), pathAfter = await lstat(file);
|
|
108
|
+
privateAuthFile(after, platform);
|
|
109
|
+
if (bytesRead > AUTH_MAX_BYTES || bytesRead !== opened.size || !unchangedFile(opened, after) || !unchangedFile(opened, pathAfter)) fail('file_auth_required');
|
|
110
|
+
if (guard && !guard.valid()) fail('file_auth_required');
|
|
111
|
+
return chatgptAuth(JSON.parse(bytes.subarray(0, bytesRead).toString('utf8')));
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (['file_auth_required', 'unsupported_auth'].includes(error.code)) throw error;
|
|
114
|
+
fail('file_auth_required');
|
|
115
|
+
} finally { try { await handle?.close(); } finally { await guard?.release(); } }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Called only by explicit POST export, against opaque registered profile IDs. */
|
|
119
|
+
export async function createCodexShare({ ids } = {}, options = {}) {
|
|
120
|
+
if (!Array.isArray(ids) || ids.length < 1 || ids.length > CODEX_SHARE_MAX_ACCOUNTS
|
|
121
|
+
|| new Set(ids).size !== ids.length || ids.some(id => typeof id !== 'string' || !/^[a-f0-9]{20}$/.test(id))) fail('invalid_profiles');
|
|
122
|
+
const selection = await readCodexSelection(options);
|
|
123
|
+
const profiles = ids.map(id => selection.profiles.find(profile => profile.id === id));
|
|
124
|
+
if (profiles.some(profile => !profile)) fail('unknown_profile');
|
|
125
|
+
const accounts = [];
|
|
126
|
+
for (const profile of profiles) {
|
|
127
|
+
const label = selection.profileLabels.find(entry => entry.id === profile.id)?.label ?? null;
|
|
128
|
+
accounts.push({ label, auth: await readFileAuth(profile.home, options) });
|
|
129
|
+
}
|
|
130
|
+
const blob = CODEX_SHARE_PREFIX + Buffer.from(JSON.stringify({ version: 1, provider: 'codex', accounts })).toString('base64url');
|
|
131
|
+
if (blob.length > CODEX_SHARE_MAX_LENGTH) fail('share_too_large');
|
|
132
|
+
return { ok: true, blob, count: accounts.length };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function parseShare(blob) {
|
|
136
|
+
if (typeof blob !== 'string' || blob.length > CODEX_SHARE_MAX_LENGTH) fail('invalid_share');
|
|
137
|
+
const code = blob.trim();
|
|
138
|
+
if (!code.startsWith(CODEX_SHARE_PREFIX)) fail('invalid_share');
|
|
139
|
+
const encoded = code.slice(CODEX_SHARE_PREFIX.length);
|
|
140
|
+
if (!/^[A-Za-z0-9_-]+$/.test(encoded)) fail('invalid_share');
|
|
141
|
+
let payload;
|
|
142
|
+
try {
|
|
143
|
+
const decoded = Buffer.from(encoded, 'base64url');
|
|
144
|
+
if (decoded.toString('base64url') !== encoded) fail('invalid_share');
|
|
145
|
+
payload = JSON.parse(decoded.toString('utf8'));
|
|
146
|
+
} catch { fail('invalid_share'); }
|
|
147
|
+
if (!keys(payload, ['version', 'provider', 'accounts']) || payload.version !== 1 || payload.provider !== 'codex'
|
|
148
|
+
|| !Array.isArray(payload.accounts) || payload.accounts.length < 1 || payload.accounts.length > CODEX_SHARE_MAX_ACCOUNTS) fail('invalid_share');
|
|
149
|
+
return payload.accounts.map(entry => {
|
|
150
|
+
if (!keys(entry, ['label', 'auth']) || !safeLabel(entry.label)) fail('invalid_share');
|
|
151
|
+
const auth = chatgptAuth(entry.auth);
|
|
152
|
+
// Exact credential dedup only. No unsigned JWT claim is used as authority
|
|
153
|
+
// to replace another account's login or suppress a different credential.
|
|
154
|
+
const fingerprint = createHash('sha256').update(auth.tokens.refresh_token).digest('hex');
|
|
155
|
+
return { label: entry.label, auth, fingerprint };
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The logins a share carries, validated as an import validates them, without
|
|
160
|
+
* touching disk: Local network reads who a login is before it lands. */
|
|
161
|
+
export function readCodexShare(blob) { return parseShare(blob); }
|
|
162
|
+
|
|
163
|
+
/** Put the one login a share carries into a registered profile's home in place
|
|
164
|
+
* of the login there — only while `stillDead(auth)` says that login is still
|
|
165
|
+
* the one the caller proved superseded. The check and the write happen under
|
|
166
|
+
* the registry lock every sign-in and move of this deck takes, so a sign-in
|
|
167
|
+
* that lands meanwhile is never overwritten. Local network's heal, and only
|
|
168
|
+
* that: an import never replaces anything (see importCodexShare). */
|
|
169
|
+
export async function replaceCodexLoginFromShare({ blob, id, stillDead } = {}, options = {}) {
|
|
170
|
+
const entries = parseShare(blob);
|
|
171
|
+
if (entries.length !== 1 || typeof stillDead !== 'function') fail('invalid_share');
|
|
172
|
+
return withCodexProfileLocked({ id }, async home => {
|
|
173
|
+
const target = join(home, 'auth.json');
|
|
174
|
+
let current = null;
|
|
175
|
+
try {
|
|
176
|
+
const info = await lstat(target);
|
|
177
|
+
if (info.isFile() && info.size <= AUTH_MAX_BYTES) current = JSON.parse(await readFile(target, 'utf8'));
|
|
178
|
+
} catch { /* no login there to replace */ }
|
|
179
|
+
if (!current || !stillDead(current)) fail('login_changed');
|
|
180
|
+
let tmp, guard;
|
|
181
|
+
try {
|
|
182
|
+
// ON WINDOWS ONLY INTO A PRIVATE FOLDER, by the rule secureCodexImportHome
|
|
183
|
+
// states: a profile that arrived over the network has one, while a folder
|
|
184
|
+
// made by a plain mkdir (a sign-in profile, or ~/.codex) does not and is
|
|
185
|
+
// refused here rather than repaired — its permissions are never changed.
|
|
186
|
+
if ((options.platform ?? process.platform) === 'win32') guard = await holdWindowsPrivatePath(home, { ...options, kind: 'directory' });
|
|
187
|
+
const staged = await createTemp(target, { mode: 0o600 });
|
|
188
|
+
tmp = staged.tmp;
|
|
189
|
+
try { await staged.handle.writeFile(JSON.stringify(entries[0].auth) + '\n'); await staged.handle.sync(); }
|
|
190
|
+
finally { await staged.handle.close(); }
|
|
191
|
+
await chmod(tmp, 0o600);
|
|
192
|
+
if (guard && !guard.valid()) fail('windows_permissions_failed');
|
|
193
|
+
await renameWithRetry(tmp, target);
|
|
194
|
+
tmp = null;
|
|
195
|
+
} catch (error) {
|
|
196
|
+
if (tmp) await unlink(tmp).catch(() => {});
|
|
197
|
+
if (error.code === 'windows_permissions_failed' || error.code === 'windows_private_path_unsafe') fail('windows_permissions_failed');
|
|
198
|
+
fail('import_write_failed');
|
|
199
|
+
} finally { await guard?.release(); }
|
|
200
|
+
return { ok: true, home };
|
|
201
|
+
}, options);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The common Windows helper creates the directory with its protected DACL
|
|
205
|
+
* atomically. Never stage a secret into a directory created by plain mkdir on
|
|
206
|
+
* Windows; chmod there controls read-only, not confidentiality. */
|
|
207
|
+
export async function secureCodexImportHome(home, options = {}) {
|
|
208
|
+
if ((options.platform ?? process.platform) !== 'win32') { await mkdir(home, { mode: 0o700 }); return; }
|
|
209
|
+
try { await ensureWindowsPrivateDirectory(home, options); }
|
|
210
|
+
catch { fail('windows_permissions_failed'); }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export async function importCodexShare({ blob, expectedRevision } = {}, options = {}) {
|
|
214
|
+
const entries = parseShare(blob); // validate the entire batch before touching disk
|
|
215
|
+
const metadata = entries.map(({ label, fingerprint }) => ({ label, fingerprint }));
|
|
216
|
+
const result = await importCodexProfiles({ entries: metadata, expectedRevision }, async (home, index) => {
|
|
217
|
+
let tmp, guard;
|
|
218
|
+
try {
|
|
219
|
+
await secureCodexImportHome(home, options);
|
|
220
|
+
if ((options.platform ?? process.platform) === 'win32') guard = await holdWindowsPrivatePath(home, { ...options, kind: 'directory' });
|
|
221
|
+
const target = join(home, 'auth.json');
|
|
222
|
+
const staged = await createTemp(target, { mode: 0o600 });
|
|
223
|
+
tmp = staged.tmp;
|
|
224
|
+
try { await staged.handle.writeFile(JSON.stringify(entries[index].auth) + '\n'); await staged.handle.sync(); }
|
|
225
|
+
finally { await staged.handle.close(); }
|
|
226
|
+
await chmod(tmp, 0o600);
|
|
227
|
+
await renameWithRetry(tmp, target);
|
|
228
|
+
// Keep the Windows directory pinned until the registry commit completes.
|
|
229
|
+
return guard;
|
|
230
|
+
} catch (error) {
|
|
231
|
+
await guard?.release();
|
|
232
|
+
if (tmp) await unlink(tmp).catch(() => {});
|
|
233
|
+
if (error.code === 'windows_permissions_failed' || error.code === 'windows_private_path_unsafe') fail('windows_permissions_failed');
|
|
234
|
+
fail('import_write_failed');
|
|
235
|
+
}
|
|
236
|
+
}, options);
|
|
237
|
+
return { ok: true, ...result };
|
|
238
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Copied with
|
|
1
|
+
// Copied with its engine dependencies into the durable terminal integration directory.
|
|
2
2
|
// No dependency on an npx cache, running server, or OAuth credential store.
|
|
3
3
|
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
@@ -39,6 +39,43 @@ export async function terminalCodexHome(file, env = process.env) {
|
|
|
39
39
|
|
|
40
40
|
export async function runSelectedCodex(file, executable, args, { env = process.env } = {}) {
|
|
41
41
|
const home = await terminalCodexHome(file, env);
|
|
42
|
+
// Explicit account pins and ordinary interactive/utility commands retain the
|
|
43
|
+
// existing path. Only supervised exec JSON sessions opt into continuation.
|
|
44
|
+
if (home && !env.CODEX_HOME?.trim()) {
|
|
45
|
+
const { createCodexEngineAdapter } = await import('./codex-engine-adapter.mjs');
|
|
46
|
+
if (process.stdin.isTTY && process.stdout.isTTY) {
|
|
47
|
+
const { codexInteractiveInvocation, supportsCodexInteractiveEngine, runInteractiveCodex } = await import('./codex-interactive-engine.mjs');
|
|
48
|
+
const policy = createCodexEngineAdapter(file, executable, ['exec', '--json'], home, { env });
|
|
49
|
+
if (codexInteractiveInvocation(args) && !(await policy.settings()).custom && await supportsCodexInteractiveEngine(executable, env)) {
|
|
50
|
+
return runInteractiveCodex(file, executable, args, home, { env });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const adapter = createCodexEngineAdapter(file, executable, args, home, { env });
|
|
54
|
+
if (adapter && (await adapter.settings()).enabled) {
|
|
55
|
+
const { runAccountEngine } = await import('./account-engine.mjs');
|
|
56
|
+
const controller = new AbortController();
|
|
57
|
+
const cancel = () => controller.abort();
|
|
58
|
+
process.on('SIGINT', cancel);
|
|
59
|
+
process.on('SIGTERM', cancel);
|
|
60
|
+
process.on('SIGHUP', cancel);
|
|
61
|
+
try {
|
|
62
|
+
const id = createHash('sha256').update(await realpath(home)).digest('hex').slice(0, 20);
|
|
63
|
+
const result = await runAccountEngine(adapter, { id, home, args, threadId: adapter.invocation.threadId }, {
|
|
64
|
+
signal: controller.signal,
|
|
65
|
+
onSwitch: () => process.stderr.write('ccdeck: continuing this Codex conversation on another account.\n'),
|
|
66
|
+
});
|
|
67
|
+
if (result.code !== 0 && ['handoff_failed', 'no_account_with_room', 'thread_changed', 'attempt_limit'].includes(result.reason)) {
|
|
68
|
+
process.stderr.write(`ccdeck: automatic continuation stopped (${result.reason}); reopen this conversation manually.\n`);
|
|
69
|
+
}
|
|
70
|
+
return result;
|
|
71
|
+
} finally {
|
|
72
|
+
await adapter.close();
|
|
73
|
+
process.removeListener('SIGINT', cancel);
|
|
74
|
+
process.removeListener('SIGTERM', cancel);
|
|
75
|
+
process.removeListener('SIGHUP', cancel);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
42
79
|
const spec = spawnSpec(executable, args);
|
|
43
80
|
const child = spawn(spec.file, spec.args, { ...spec.opts, stdio: 'inherit', env: home ? { ...env, CODEX_HOME: home } : env });
|
|
44
81
|
// Terminal Ctrl+C already reaches both processes. Keep the wrapper alive
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { readFile, mkdir, chmod, access, stat, cp } from 'node:fs/promises';
|
|
2
3
|
import { constants } from 'node:fs';
|
|
3
|
-
import { basename, join, isAbsolute } from 'node:path';
|
|
4
|
+
import { basename, dirname, join, isAbsolute } from 'node:path';
|
|
4
5
|
import { homedir } from 'node:os';
|
|
5
6
|
import { execFile } from 'node:child_process';
|
|
6
7
|
import { promisify } from 'node:util';
|
|
@@ -85,10 +86,21 @@ export async function configureCodexTerminal(action, options = {}) {
|
|
|
85
86
|
const data = options.store ?? deckDataDir(undefined, env, home);
|
|
86
87
|
const directory = join(data, 'codex-terminal');
|
|
87
88
|
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
88
|
-
|
|
89
|
+
// Keep Node's package lookup inside the durable helper. An unrelated
|
|
90
|
+
// package.json above the data directory must not prevent startup.
|
|
91
|
+
const manifest = join(directory, 'package.json');
|
|
92
|
+
await writeFileAtomic(manifest, JSON.stringify({ private: true, type: 'module' }) + '\n');
|
|
93
|
+
await chmod(manifest, 0o600);
|
|
94
|
+
for (const name of ['codex-terminal-runner.mjs', 'exec-spec.mjs', 'account-engine.mjs', 'codex-engine-adapter.mjs', 'codex-handoff.mjs',
|
|
95
|
+
'codex-interactive-engine.mjs', 'codex-engine-config.mjs', 'codex-engine-rpc.mjs', 'codex-engine-bridge.mjs',
|
|
96
|
+
'codex-auto.mjs', 'codex-selection.mjs', 'codex-profiles.mjs', 'codex-lan-identity.mjs', 'codex-native-account.mjs',
|
|
97
|
+
'codex-auth.mjs', 'codex-dir.mjs', 'deck-home.mjs', 'claude-dir.mjs', 'atomic-write.mjs', 'brand.mjs', 'exec-children.mjs']) {
|
|
89
98
|
await writeFileAtomic(join(directory, name), await readFile(new URL(`./${name}`, import.meta.url), 'utf8'));
|
|
90
99
|
await chmod(join(directory, name), 0o600);
|
|
91
100
|
}
|
|
101
|
+
// Keep the RFC6455 implementation and its MIT notice with the durable helper.
|
|
102
|
+
const wsPackage = dirname(createRequire(import.meta.url).resolve('ws/package.json'));
|
|
103
|
+
await cp(wsPackage, join(directory, 'node_modules', 'ws'), { recursive: true, force: true });
|
|
92
104
|
const runner = join(directory, 'codex-terminal-runner.mjs');
|
|
93
105
|
const file = codexSelectionPath({ store: data });
|
|
94
106
|
const node = options.node ?? hookRuntime(env);
|
|
@@ -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
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// cwd and the chunked reader from the modules that own them — nothing here
|
|
9
9
|
// reads the ring or the SSE clients. index.mjs starts the watcher. The bodies
|
|
10
10
|
// are unchanged.
|
|
11
|
+
import { codexHandoffOffset } from './codex-handoff.mjs';
|
|
11
12
|
import { stat, readdir } from "node:fs/promises";
|
|
12
13
|
import { basename, dirname, join } from "node:path";
|
|
13
14
|
import { PRODUCT } from "./brand.mjs";
|
|
@@ -361,7 +362,8 @@ async function openCodexCursor(path, st, now, firstRun, recover = false) {
|
|
|
361
362
|
// UsageObserved in the file to every tab, and re-appending the lot to
|
|
362
363
|
// the shared events.jsonl if this deck is the elected writer (#981).
|
|
363
364
|
const fresh = !codexSeenEver.has(path);
|
|
364
|
-
const
|
|
365
|
+
const copiedPrefix = fresh ? await codexHandoffOffset(path, header.sid, st.size) : 0;
|
|
366
|
+
const state = { offset: fresh ? copiedPrefix : st.size, sid: header.sid, cwd: header.cwd, link: header.link, skip: false, sawBeginning: fresh && copiedPrefix === 0, rootOpened: false, seenAt: now, path };
|
|
365
367
|
codexFileState.set(path, state);
|
|
366
368
|
rememberCodexPath(path);
|
|
367
369
|
if (firstRun) {
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Windows has no POSIX UID/O_NOFOLLOW contract. The fixed PowerShell helper
|
|
2
|
+
// checks the current token SID and a handle's DACL, never path-supplied code.
|
|
3
|
+
import { execFile, spawn } from 'node:child_process';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { win32 } from 'node:path';
|
|
7
|
+
|
|
8
|
+
const runFile = promisify(execFile);
|
|
9
|
+
const helper = fileURLToPath(new URL('./codex-windows-private.ps1', import.meta.url));
|
|
10
|
+
const unsafe = () => Object.assign(new Error('windows_private_path_unsafe'), { code: 'windows_private_path_unsafe' });
|
|
11
|
+
// The first Windows PowerShell invocation compiles the fixed Win32 helper.
|
|
12
|
+
// Compilation on a contended Windows host can exceed ten seconds. This only
|
|
13
|
+
// bounds helper startup; the ACL/reparse checks and native RPC limits stay intact.
|
|
14
|
+
const deadline = options => Math.max(1, Math.min(30000, options.timeoutMs ?? 30000));
|
|
15
|
+
function command(path, operation, options) {
|
|
16
|
+
if ((options.platform ?? process.platform) !== 'win32' || typeof path !== 'string'
|
|
17
|
+
|| !/^(?:[a-z]:\\|\\\\\?\\[a-z]:\\)/i.test(path) || /[\x00-\x1f"<>|]/.test(path)
|
|
18
|
+
|| path.replace(/^\\\\\?\\/, '').slice(2).includes(':')) throw unsafe();
|
|
19
|
+
const kind = options.kind ?? 'directory';
|
|
20
|
+
if (!['directory', 'file', 'socket'].includes(kind)) throw unsafe();
|
|
21
|
+
// Use the OS copy, not a powershell.exe supplied by PATH or the profile cwd.
|
|
22
|
+
const root = process.env.SystemRoot ?? 'C:\\Windows';
|
|
23
|
+
return { file: win32.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
|
|
24
|
+
args: ['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', helper,
|
|
25
|
+
'-Operation', operation, '-TargetPath', path, '-Kind', kind] };
|
|
26
|
+
}
|
|
27
|
+
function result(stdout) {
|
|
28
|
+
const value = JSON.parse(stdout.replace(/^\uFEFF/, '').trim());
|
|
29
|
+
if (typeof value.path !== 'string' || !value.path || value.path.includes('\0')) throw unsafe();
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
async function check(path, operation, options) {
|
|
33
|
+
try {
|
|
34
|
+
const spec = command(path, operation, options);
|
|
35
|
+
const output = await (options.execFile ?? runFile)(spec.file, spec.args,
|
|
36
|
+
{ timeout: deadline(options), maxBuffer: 16 * 1024, windowsHide: true, shell: false });
|
|
37
|
+
return result(output.stdout);
|
|
38
|
+
} catch { throw unsafe(); }
|
|
39
|
+
}
|
|
40
|
+
/** Create with a protected inheritable current-user DACL atomically. Existing
|
|
41
|
+
* directories must already be private; their permissions are never repaired.
|
|
42
|
+
* execFile is an async (file, args, options) => { stdout } test seam.
|
|
43
|
+
*/
|
|
44
|
+
export const ensureWindowsPrivateDirectory = async (path, options = {}) => (await check(path, 'ensure', { ...options, kind: 'directory' })).path;
|
|
45
|
+
export const assertWindowsPrivatePath = async (path, options = {}) => (await check(path, 'check', options)).path;
|
|
46
|
+
export async function inspectWindowsPrivateSocket(path, options = {}) {
|
|
47
|
+
const value = await check(path, 'check', { ...options, kind: 'socket' });
|
|
48
|
+
if (typeof value.generation !== 'string' || !/^\d+(?::\d+){4}$/.test(value.generation)) throw unsafe();
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Pin the checked directory (and a regular file, when requested) until release.
|
|
53
|
+
* The helper holds handles without FILE_SHARE_DELETE; file guards also exclude
|
|
54
|
+
* writers. A bounded startup and lifetime prevent abandoned helpers lingering.
|
|
55
|
+
*/
|
|
56
|
+
export async function holdWindowsPrivatePath(path, options = {}) {
|
|
57
|
+
let child;
|
|
58
|
+
try {
|
|
59
|
+
const spec = command(path, 'hold', options);
|
|
60
|
+
child = (options.spawnChild ?? spawn)(spec.file, spec.args, { windowsHide: true, shell: false, stdio: ['pipe', 'pipe', 'ignore'] });
|
|
61
|
+
let alive = true;
|
|
62
|
+
child.on('exit', () => { alive = false; });
|
|
63
|
+
child.on('error', () => { alive = false; });
|
|
64
|
+
child.stdin.on('error', () => {});
|
|
65
|
+
const captured = await new Promise((ready, reject) => {
|
|
66
|
+
let output = '';
|
|
67
|
+
const timer = setTimeout(() => reject(unsafe()), deadline(options));
|
|
68
|
+
const finish = fn => value => { clearTimeout(timer); fn(value); };
|
|
69
|
+
child.once('error', finish(() => reject(unsafe())));
|
|
70
|
+
child.once('exit', finish(() => reject(unsafe())));
|
|
71
|
+
child.stdout.on('data', data => {
|
|
72
|
+
output += data.toString('utf8');
|
|
73
|
+
if (output.length > 16 * 1024) { clearTimeout(timer); reject(unsafe()); }
|
|
74
|
+
else if (output.includes('\n')) {
|
|
75
|
+
try { finish(ready)(result(output)); } catch { finish(reject)(unsafe()); }
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
let released = false, expired = false, releasing;
|
|
80
|
+
const release = () => {
|
|
81
|
+
if (released) return releasing;
|
|
82
|
+
released = true; clearTimeout(lifetime);
|
|
83
|
+
releasing = new Promise(resolve => {
|
|
84
|
+
if (child.exitCode !== null || child.signalCode !== null) { resolve(); return; }
|
|
85
|
+
const timer = setTimeout(resolve, 2000);
|
|
86
|
+
child.once('exit', () => { clearTimeout(timer); resolve(); });
|
|
87
|
+
child.stdin.destroy(); child.kill();
|
|
88
|
+
});
|
|
89
|
+
return releasing;
|
|
90
|
+
};
|
|
91
|
+
// Covers cold native startup and the subsequent bounded ACL rechecks.
|
|
92
|
+
const lifetime = setTimeout(() => { expired = true; release(); }, 120000); lifetime.unref();
|
|
93
|
+
return { path: captured.path, generation: captured.generation, valid: () => alive && !released && !expired && child.exitCode === null && child.signalCode === null,
|
|
94
|
+
release };
|
|
95
|
+
} catch { child?.stdin?.destroy(); child?.kill(); throw unsafe(); }
|
|
96
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
param(
|
|
2
|
+
[ValidateSet('ensure','check','hold')][string]$Operation,
|
|
3
|
+
[Parameter(Mandatory=$true)][string]$TargetPath,
|
|
4
|
+
[ValidateSet('directory','file','socket')][string]$Kind = 'directory'
|
|
5
|
+
)
|
|
6
|
+
$ErrorActionPreference = 'Stop'
|
|
7
|
+
try {
|
|
8
|
+
# Fixed source only. Paths arrive via -File arguments, never interpolation.
|
|
9
|
+
Microsoft.PowerShell.Utility\Add-Type -TypeDefinition @'
|
|
10
|
+
using System;
|
|
11
|
+
using System.IO;
|
|
12
|
+
using System.Runtime.InteropServices;
|
|
13
|
+
using System.Security.AccessControl;
|
|
14
|
+
using System.Security.Principal;
|
|
15
|
+
using System.Text;
|
|
16
|
+
using Microsoft.Win32.SafeHandles;
|
|
17
|
+
public static class CodexPrivatePath {
|
|
18
|
+
[StructLayout(LayoutKind.Sequential)] struct SecurityAttributes {
|
|
19
|
+
public int Length; public IntPtr Descriptor; public int Inherit;
|
|
20
|
+
}
|
|
21
|
+
[StructLayout(LayoutKind.Sequential)] struct FileInfo {
|
|
22
|
+
public uint Attributes; public System.Runtime.InteropServices.ComTypes.FILETIME Created, Accessed, Written;
|
|
23
|
+
public uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow;
|
|
24
|
+
}
|
|
25
|
+
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
|
|
26
|
+
static extern SafeFileHandle CreateFileW(string p, uint access, uint share, IntPtr sa, uint creation, uint flags, IntPtr template);
|
|
27
|
+
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
|
|
28
|
+
static extern bool CreateDirectoryW(string p, ref SecurityAttributes sa);
|
|
29
|
+
[DllImport("kernel32.dll", SetLastError=true)]
|
|
30
|
+
static extern bool GetFileInformationByHandle(SafeFileHandle h, out FileInfo info);
|
|
31
|
+
[StructLayout(LayoutKind.Sequential)] struct AttributeTagInfo { public uint Attributes, Tag; }
|
|
32
|
+
[DllImport("kernel32.dll", SetLastError=true)]
|
|
33
|
+
static extern bool GetFileInformationByHandleEx(SafeFileHandle h, int type, out AttributeTagInfo info, uint size);
|
|
34
|
+
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
|
|
35
|
+
static extern uint GetFinalPathNameByHandleW(SafeFileHandle h, StringBuilder b, uint size, uint flags);
|
|
36
|
+
[DllImport("advapi32.dll", SetLastError=true)]
|
|
37
|
+
static extern uint GetSecurityInfo(SafeFileHandle h, uint type, uint what, out IntPtr owner, out IntPtr group, out IntPtr dacl, out IntPtr sacl, out IntPtr descriptor);
|
|
38
|
+
[DllImport("advapi32.dll")] static extern uint GetSecurityDescriptorLength(IntPtr sd);
|
|
39
|
+
[DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr p);
|
|
40
|
+
static void Require(bool valid) { if (!valid) throw new IOException("unsafe"); }
|
|
41
|
+
public static string Canonical(SafeFileHandle h) {
|
|
42
|
+
var b = new StringBuilder(32768);
|
|
43
|
+
uint length = GetFinalPathNameByHandleW(h, b, (uint)b.Capacity, 0);
|
|
44
|
+
Require(length > 0 && length < b.Capacity);
|
|
45
|
+
return b.ToString();
|
|
46
|
+
}
|
|
47
|
+
public static SafeFileHandle Open(string path, bool directory) {
|
|
48
|
+
// OPEN_REPARSE_POINT prevents following a substituted final link. Listing
|
|
49
|
+
// access makes omission of SHARE_DELETE actually pin a directory on Windows.
|
|
50
|
+
var h = CreateFileW(path, 0x20000u | 0x80u | 1u, directory ? 3u : 1u,
|
|
51
|
+
IntPtr.Zero, 3, 0x02000000u | 0x00200000u, IntPtr.Zero);
|
|
52
|
+
if (h.IsInvalid) { h.Dispose(); throw new IOException("unsafe"); }
|
|
53
|
+
try {
|
|
54
|
+
FileInfo info;
|
|
55
|
+
Require(GetFileInformationByHandle(h, out info));
|
|
56
|
+
Require((info.Attributes & 0x400u) == 0 && ((info.Attributes & 0x10u) != 0) == directory);
|
|
57
|
+
if (!directory) Require(info.Links == 1);
|
|
58
|
+
ValidateAcl(h, directory);
|
|
59
|
+
return h;
|
|
60
|
+
} catch { h.Dispose(); throw; }
|
|
61
|
+
}
|
|
62
|
+
static void ValidateAcl(SafeFileHandle h, bool directory) {
|
|
63
|
+
IntPtr owner, group, dacl, sacl, descriptor;
|
|
64
|
+
Require(GetSecurityInfo(h, 1, 5, out owner, out group, out dacl, out sacl, out descriptor) == 0);
|
|
65
|
+
try {
|
|
66
|
+
Require(owner != IntPtr.Zero && dacl != IntPtr.Zero);
|
|
67
|
+
var bytes = new byte[GetSecurityDescriptorLength(descriptor)];
|
|
68
|
+
Marshal.Copy(descriptor, bytes, 0, bytes.Length);
|
|
69
|
+
var sd = new RawSecurityDescriptor(bytes, 0);
|
|
70
|
+
var user = WindowsIdentity.GetCurrent().User;
|
|
71
|
+
Require(sd.Owner == user && sd.DiscretionaryAcl != null && sd.DiscretionaryAcl.Count > 0);
|
|
72
|
+
if (directory) Require((sd.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0);
|
|
73
|
+
bool userAccess = false;
|
|
74
|
+
foreach (GenericAce entry in sd.DiscretionaryAcl) {
|
|
75
|
+
var ace = entry as CommonAce;
|
|
76
|
+
Require(ace != null && !ace.IsCallback && ace.AceQualifier == AceQualifier.AccessAllowed);
|
|
77
|
+
Require(ace.SecurityIdentifier == user || ace.SecurityIdentifier.Value == "S-1-5-18");
|
|
78
|
+
if (ace.SecurityIdentifier == user && (ace.AceFlags & AceFlags.InheritOnly) == 0 && (ace.AccessMask & 0x1f01ff) == 0x1f01ff) {
|
|
79
|
+
if (directory) Require((ace.AceFlags & (AceFlags.ContainerInherit | AceFlags.ObjectInherit)) == (AceFlags.ContainerInherit | AceFlags.ObjectInherit));
|
|
80
|
+
userAccess = true;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
Require(userAccess);
|
|
84
|
+
} finally { if (descriptor != IntPtr.Zero) LocalFree(descriptor); }
|
|
85
|
+
}
|
|
86
|
+
public static string SocketGeneration(string path) {
|
|
87
|
+
// Node/libuv lstat returns EACCES on Windows AF_UNIX entries. Open only
|
|
88
|
+
// reparse metadata, never follow a symlink/junction or read socket bytes.
|
|
89
|
+
using (var h = CreateFileW(path, 0x80u, 3, IntPtr.Zero, 3, 0x00200000u | 0x02000000u, IntPtr.Zero)) {
|
|
90
|
+
Require(!h.IsInvalid);
|
|
91
|
+
AttributeTagInfo tag; FileInfo info;
|
|
92
|
+
Require(GetFileInformationByHandleEx(h, 9, out tag, (uint)Marshal.SizeOf(typeof(AttributeTagInfo))));
|
|
93
|
+
Require((tag.Attributes & 0x400u) != 0 && tag.Tag == 0x80000023u && (tag.Attributes & 0x10u) == 0);
|
|
94
|
+
Require(GetFileInformationByHandle(h, out info));
|
|
95
|
+
return info.Volume + ":" + info.IndexHigh + ":" + info.IndexLow + ":" + (uint)info.Created.dwHighDateTime + ":" + (uint)info.Created.dwLowDateTime;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
public static void Ensure(string path) {
|
|
99
|
+
// The security descriptor is supplied to creation, never applied afterwards.
|
|
100
|
+
var user = WindowsIdentity.GetCurrent().User;
|
|
101
|
+
var sd = new RawSecurityDescriptor("O:" + user.Value + "D:P(A;OICI;FA;;;" + user.Value + ")");
|
|
102
|
+
var bytes = new byte[sd.BinaryLength]; sd.GetBinaryForm(bytes, 0);
|
|
103
|
+
var pinned = GCHandle.Alloc(bytes, GCHandleType.Pinned);
|
|
104
|
+
try {
|
|
105
|
+
var sa = new SecurityAttributes { Length = Marshal.SizeOf(typeof(SecurityAttributes)), Descriptor = pinned.AddrOfPinnedObject(), Inherit = 0 };
|
|
106
|
+
if (!CreateDirectoryW(path, ref sa)) Require(Marshal.GetLastWin32Error() == 183);
|
|
107
|
+
} finally { pinned.Free(); }
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
'@
|
|
111
|
+
$guards = [System.Collections.Generic.List[System.IDisposable]]::new()
|
|
112
|
+
try {
|
|
113
|
+
$path = [IO.Path]::GetFullPath($TargetPath)
|
|
114
|
+
if ($Operation -eq 'ensure') {
|
|
115
|
+
if ($Kind -ne 'directory') { throw 'unsafe' }
|
|
116
|
+
[CodexPrivatePath]::Ensure($path)
|
|
117
|
+
}
|
|
118
|
+
if ($Kind -eq 'directory') {
|
|
119
|
+
$guard = [CodexPrivatePath]::Open($path, $true)
|
|
120
|
+
$guards.Add($guard)
|
|
121
|
+
$canonical = [CodexPrivatePath]::Canonical($guard)
|
|
122
|
+
} else {
|
|
123
|
+
$parent = [CodexPrivatePath]::Open([IO.Path]::GetDirectoryName($path), $true)
|
|
124
|
+
$guards.Add($parent)
|
|
125
|
+
$canonical = [IO.Path]::Combine([CodexPrivatePath]::Canonical($parent), [IO.Path]::GetFileName($path))
|
|
126
|
+
if ($Kind -eq 'file') {
|
|
127
|
+
$guard = [CodexPrivatePath]::Open($canonical, $false)
|
|
128
|
+
$guards.Add($guard)
|
|
129
|
+
$canonical = [CodexPrivatePath]::Canonical($guard)
|
|
130
|
+
} else {
|
|
131
|
+
$generation = [CodexPrivatePath]::SocketGeneration($canonical)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
$result = @{ path = $canonical }
|
|
135
|
+
if ($Kind -eq 'socket') { $result.generation = $generation }
|
|
136
|
+
[Console]::Out.WriteLine(($result | Microsoft.PowerShell.Utility\ConvertTo-Json -Compress))
|
|
137
|
+
[Console]::Out.Flush()
|
|
138
|
+
if ($Operation -eq 'hold') { $null = [Console]::In.ReadLine() }
|
|
139
|
+
} finally { foreach ($guard in $guards) { $guard.Dispose() } }
|
|
140
|
+
} catch { [Console]::Error.WriteLine('windows_private_path_unsafe'); exit 1 }
|