@openai/codex-security 0.1.3 → 0.1.5

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 (49) hide show
  1. package/README.md +224 -14
  2. package/_bundled_plugin/examples/completed-scan/findings.json +6 -0
  3. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +1 -1
  4. package/_bundled_plugin/references/finding-detail-fields.md +10 -2
  5. package/_bundled_plugin/references/scan-contract.md +2 -0
  6. package/_bundled_plugin/scripts/finalize_scan_contract.py +18 -0
  7. package/_bundled_plugin/scripts/workbench_cli.py +4 -0
  8. package/_bundled_plugin/scripts/workbench_db.py +93 -23
  9. package/_bundled_plugin/scripts/workbench_scan_start.py +13 -0
  10. package/_bundled_plugin/scripts/workbench_target.py +14 -1
  11. package/dist/api.d.ts +3 -2
  12. package/dist/api.d.ts.map +1 -1
  13. package/dist/api.js +288 -70
  14. package/dist/api.js.map +1 -1
  15. package/dist/auth.d.ts.map +1 -1
  16. package/dist/auth.js +262 -44
  17. package/dist/auth.js.map +1 -1
  18. package/dist/cli.d.ts +4 -3
  19. package/dist/cli.d.ts.map +1 -1
  20. package/dist/cli.js +364 -154
  21. package/dist/cli.js.map +1 -1
  22. package/dist/config.d.ts.map +1 -1
  23. package/dist/config.js +29 -1
  24. package/dist/config.js.map +1 -1
  25. package/dist/contract.d.ts +1 -0
  26. package/dist/contract.d.ts.map +1 -1
  27. package/dist/contract.js +33 -22
  28. package/dist/contract.js.map +1 -1
  29. package/dist/cost.d.ts.map +1 -1
  30. package/dist/cost.js +57 -14
  31. package/dist/cost.js.map +1 -1
  32. package/dist/errors.d.ts +2 -0
  33. package/dist/errors.d.ts.map +1 -1
  34. package/dist/errors.js +48 -0
  35. package/dist/errors.js.map +1 -1
  36. package/dist/multiscan.d.ts.map +1 -1
  37. package/dist/multiscan.js +2 -7
  38. package/dist/multiscan.js.map +1 -1
  39. package/dist/runtime.d.ts +34 -0
  40. package/dist/runtime.d.ts.map +1 -1
  41. package/dist/runtime.js +655 -20
  42. package/dist/runtime.js.map +1 -1
  43. package/dist/scan-comparison.d.ts +2 -0
  44. package/dist/scan-comparison.d.ts.map +1 -1
  45. package/dist/scan-comparison.js +26 -2
  46. package/dist/scan-comparison.js.map +1 -1
  47. package/dist/trusted-executable.js +1 -1
  48. package/dist/trusted-executable.js.map +1 -1
  49. package/package.json +5 -4
package/dist/runtime.js CHANGED
@@ -1,13 +1,14 @@
1
1
  import { execFile as execFileCallback } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  import { constants, existsSync } from "node:fs";
4
- import { chmod, copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile, } from "node:fs/promises";
4
+ import { chmod, copyFile, link, lstat, mkdir, mkdtemp, open, opendir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile, } from "node:fs/promises";
5
5
  import { homedir, tmpdir } from "node:os";
6
6
  import { createRequire } from "node:module";
7
7
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep, } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { promisify } from "node:util";
10
10
  import { crc32 } from "node:zlib";
11
+ import { setTimeout as delay } from "node:timers/promises";
11
12
  import extractZip from "extract-zip";
12
13
  import { parse } from "smol-toml";
13
14
  import { CodexSecurityError, OutputDirectoryError, PluginBootstrapError, PluginPythonUnavailableError, } from "./errors.js";
@@ -24,6 +25,10 @@ const MAX_PLUGIN_COPY_ENTRIES = 4_096;
24
25
  const MAX_PLUGIN_COPY_FILE_SIZE = 128 * 1024 * 1024;
25
26
  const MAX_PLUGIN_COPY_SIZE = 512 * 1024 * 1024;
26
27
  const MODEL_UNSAFE_PATH = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u;
28
+ const CREDENTIAL_LOCK_NAME = ".codex-security-scan.lock";
29
+ const CREDENTIAL_LOGOUT_MARKER = ".codex-security-logged-out";
30
+ const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;
31
+ const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;
27
32
  export function codexSecurityStateDirectory(environment = process.env) {
28
33
  const environmentValue = (requested) => {
29
34
  const exact = environment[requested]?.trim();
@@ -39,6 +44,365 @@ export function codexSecurityStateDirectory(environment = process.env) {
39
44
  const codexHome = environmentValue("CODEX_HOME") ?? join(homedir(), ".codex");
40
45
  return resolve(expandHome(codexHome), "state", "plugins", "codex-security");
41
46
  }
47
+ export function codexSecurityCredentialHome(environment = process.env) {
48
+ return join(codexSecurityStateDirectory(environment), "codex-home");
49
+ }
50
+ export async function prepareCodexSecurityCredentialHome(environment = process.env, validateLocation) {
51
+ const path = codexSecurityCredentialHome(environment);
52
+ try {
53
+ try {
54
+ await mkdir(path, { recursive: true, mode: 0o700 });
55
+ }
56
+ catch (error) {
57
+ if (nodeErrorCode(error) === "EEXIST") {
58
+ const existing = await lstat(path).catch(() => null);
59
+ if (existing !== null &&
60
+ (!existing.isDirectory() || existing.isSymbolicLink())) {
61
+ throw new OutputDirectoryError(`Codex Security credential home is not a directory: ${path}`, { cause: error });
62
+ }
63
+ }
64
+ throw error;
65
+ }
66
+ if ((process.umask() & 0o700) !== 0)
67
+ await chmod(path, 0o700);
68
+ const metadata = await lstat(path);
69
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
70
+ throw new OutputDirectoryError(`Codex Security credential home is not a directory: ${path}`);
71
+ }
72
+ const canonical = await realpath(path);
73
+ requireModelSafeOutputDir(canonical);
74
+ validateLocation?.(canonical);
75
+ await requireSecureCredentialHome(canonical, {
76
+ metadata,
77
+ });
78
+ return canonical;
79
+ }
80
+ catch (error) {
81
+ if (error instanceof OutputDirectoryError)
82
+ throw error;
83
+ throw new OutputDirectoryError(`Unable to prepare the Codex Security credential home: ${path}`, { cause: error });
84
+ }
85
+ }
86
+ /**
87
+ * Re-verify the credential home before every use.
88
+ *
89
+ * Durable cross-process `(st_dev, st_ino)` pins are deferred: there is no
90
+ * workbench row for credential homes, and path+mode+trusted-ancestry checks on
91
+ * each use already close the cross-user rename/replace class. Lock acquisition
92
+ * still pins identity for the duration of a single lock session.
93
+ */
94
+ export async function requireSecureCredentialHome(path, options = {}) {
95
+ const platform = options.platform ?? process.platform;
96
+ let metadata = options.metadata;
97
+ if (metadata === undefined) {
98
+ try {
99
+ metadata = await lstat(path);
100
+ }
101
+ catch (error) {
102
+ throw new OutputDirectoryError(`Unable to inspect the Codex Security credential home: ${path}`, { cause: error });
103
+ }
104
+ }
105
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
106
+ throw new OutputDirectoryError(`Codex Security credential home is not a directory: ${path}`);
107
+ }
108
+ const canonical = await realpath(path);
109
+ requireModelSafeOutputDir(canonical);
110
+ const canonicalMetadata = await lstat(canonical);
111
+ if (canonicalMetadata.dev !== metadata.dev ||
112
+ canonicalMetadata.ino !== metadata.ino) {
113
+ throw new OutputDirectoryError(`Codex Security credential home was replaced: ${canonical}`);
114
+ }
115
+ metadata = canonicalMetadata;
116
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
117
+ throw new OutputDirectoryError(`Codex Security credential home is not a directory: ${path}`);
118
+ }
119
+ if (options.expectedDevice !== undefined &&
120
+ options.expectedInode !== undefined &&
121
+ (metadata.dev !== options.expectedDevice ||
122
+ metadata.ino !== options.expectedInode)) {
123
+ throw new OutputDirectoryError(`Codex Security credential home was replaced: ${canonical}`);
124
+ }
125
+ if (platform === "win32") {
126
+ if (options.validateWindowsAcl !== false) {
127
+ await requirePrivateCredentialHome(metadata, canonical, {
128
+ platform,
129
+ secureWindowsHome: options.secureWindowsHome,
130
+ });
131
+ }
132
+ return metadata;
133
+ }
134
+ await requirePrivateCredentialHome(metadata, canonical, { platform });
135
+ await requireSecureOutputAncestry(canonical);
136
+ return metadata;
137
+ }
138
+ export async function requirePrivateCredentialHome(metadata, path, options = {}) {
139
+ if ((options.platform ?? process.platform) !== "win32") {
140
+ requirePrivateOutputDirectory(metadata, path);
141
+ return;
142
+ }
143
+ try {
144
+ await (options.secureWindowsHome ?? secureWindowsCredentialHome)(path);
145
+ }
146
+ catch (error) {
147
+ throw new OutputDirectoryError(`Unable to create a private Windows credential home: ${path}`, { cause: error });
148
+ }
149
+ }
150
+ async function secureWindowsCredentialHome(path) {
151
+ const systemRoot = process.env["SystemRoot"] ?? "C:\\Windows";
152
+ const powershell = join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
153
+ const script = [
154
+ "$ErrorActionPreference = 'Stop'",
155
+ "$path = [Environment]::GetEnvironmentVariable('CODEX_SECURITY_CREDENTIAL_ACL_PATH', 'Process')",
156
+ "$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()",
157
+ "if ($null -eq $identity.User) { throw 'Unable to identify the current Windows user' }",
158
+ "$acl = New-Object System.Security.AccessControl.DirectorySecurity",
159
+ "$acl.SetAccessRuleProtection($true, $false)",
160
+ "$inheritance = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit",
161
+ "$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($identity.User, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow)",
162
+ "$acl.SetOwner($identity.User)",
163
+ "$acl.SetAccessRule($rule)",
164
+ "[System.IO.Directory]::SetAccessControl($path, $acl)",
165
+ "$verified = [System.IO.Directory]::GetAccessControl($path)",
166
+ "if (-not $verified.AreAccessRulesProtected) { throw 'Credential ACL still inherits access rules' }",
167
+ "$unexpected = @($verified.Access | Where-Object { $_.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -ne $identity.User.Value })",
168
+ "if ($unexpected.Count -ne 0) { throw 'Credential ACL grants access to another identity' }",
169
+ ].join("; ");
170
+ await execFile(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
171
+ env: {
172
+ ...process.env,
173
+ CODEX_SECURITY_CREDENTIAL_ACL_PATH: path,
174
+ },
175
+ encoding: "utf8",
176
+ windowsHide: true,
177
+ maxBuffer: 1024 * 1024,
178
+ });
179
+ }
180
+ export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal, securityOptions = {}) {
181
+ const homeMetadata = await requireSecureCredentialHome(codexHome, securityOptions);
182
+ const expectedDevice = homeMetadata.dev;
183
+ const expectedInode = homeMetadata.ino;
184
+ const lock = join(codexHome, CREDENTIAL_LOCK_NAME);
185
+ const ownerPath = join(lock, "owner.json");
186
+ const token = randomUUID();
187
+ while (true) {
188
+ throwIfSignalAborted(signal);
189
+ await requireSecureCredentialHome(codexHome, {
190
+ ...securityOptions,
191
+ expectedDevice,
192
+ expectedInode,
193
+ validateWindowsAcl: false,
194
+ });
195
+ const existingLock = await lstat(lock).catch((error) => {
196
+ if (nodeErrorCode(error) === "ENOENT")
197
+ return null;
198
+ throw error;
199
+ });
200
+ if (existingLock !== null) {
201
+ if (await recoverStaleCredentialHomeLock(lock))
202
+ continue;
203
+ await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
204
+ continue;
205
+ }
206
+ await requireSecureCredentialHome(codexHome, {
207
+ ...securityOptions,
208
+ expectedDevice,
209
+ expectedInode,
210
+ });
211
+ try {
212
+ await mkdir(lock, { mode: 0o700 });
213
+ }
214
+ catch (error) {
215
+ if (nodeErrorCode(error) !== "EEXIST")
216
+ throw error;
217
+ if (await recoverStaleCredentialHomeLock(lock))
218
+ continue;
219
+ await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
220
+ continue;
221
+ }
222
+ try {
223
+ await writeFile(ownerPath, `${JSON.stringify({ pid: process.pid, token })}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
224
+ }
225
+ catch (error) {
226
+ await rm(lock, { recursive: true, force: true }).catch(() => undefined);
227
+ throw error;
228
+ }
229
+ let released = false;
230
+ return async () => {
231
+ if (released)
232
+ return;
233
+ await requireSecureCredentialHome(codexHome, {
234
+ ...securityOptions,
235
+ expectedDevice,
236
+ expectedInode,
237
+ });
238
+ const owner = JSON.parse(await readFile(ownerPath, "utf8"));
239
+ if (owner.token !== token) {
240
+ throw new PluginBootstrapError("The Codex Security credential-home lock is no longer owned by this scan.");
241
+ }
242
+ await rm(lock, { recursive: true, force: true });
243
+ released = true;
244
+ };
245
+ }
246
+ }
247
+ async function recoverStaleCredentialHomeLock(lock) {
248
+ const metadata = await lstat(lock).catch((error) => {
249
+ if (nodeErrorCode(error) === "ENOENT")
250
+ return null;
251
+ throw error;
252
+ });
253
+ if (metadata === null)
254
+ return true;
255
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
256
+ throw new OutputDirectoryError(`Codex Security credential-home lock is not a directory: ${lock}`);
257
+ }
258
+ let owner;
259
+ try {
260
+ owner = JSON.parse(await readFile(join(lock, "owner.json"), "utf8"));
261
+ }
262
+ catch (error) {
263
+ if (nodeErrorCode(error) !== "ENOENT" && !(error instanceof SyntaxError)) {
264
+ throw error;
265
+ }
266
+ if (Date.now() - metadata.mtimeMs <
267
+ INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS) {
268
+ return false;
269
+ }
270
+ }
271
+ if (isRecord(owner) && typeof owner["pid"] === "number") {
272
+ try {
273
+ process.kill(owner["pid"], 0);
274
+ return false;
275
+ }
276
+ catch (error) {
277
+ if (nodeErrorCode(error) !== "ESRCH") {
278
+ if (nodeErrorCode(error) === "EPERM")
279
+ return false;
280
+ throw error;
281
+ }
282
+ }
283
+ }
284
+ else if (Date.now() - metadata.mtimeMs <
285
+ INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS) {
286
+ return false;
287
+ }
288
+ const quarantine = `${lock}.stale-${randomUUID()}`;
289
+ try {
290
+ await rename(lock, quarantine);
291
+ }
292
+ catch (error) {
293
+ if (nodeErrorCode(error) === "ENOENT")
294
+ return true;
295
+ throw error;
296
+ }
297
+ await rm(quarantine, { recursive: true, force: true });
298
+ return true;
299
+ }
300
+ export async function setCodexSecurityCredentialLogout(codexHome, loggedOut) {
301
+ await requireSecureCredentialHome(codexHome);
302
+ const marker = join(codexHome, CREDENTIAL_LOGOUT_MARKER);
303
+ if (!loggedOut) {
304
+ await rm(marker, { force: true });
305
+ return;
306
+ }
307
+ const temporary = join(codexHome, `.codex-security-logout-${randomUUID()}.tmp`);
308
+ try {
309
+ const handle = await open(temporary, "wx", 0o600);
310
+ try {
311
+ await handle.chmod(0o600);
312
+ await handle.writeFile("logged out\n", "utf8");
313
+ await handle.sync();
314
+ }
315
+ finally {
316
+ await handle.close();
317
+ }
318
+ await rename(temporary, marker);
319
+ }
320
+ finally {
321
+ await rm(temporary, { force: true });
322
+ }
323
+ }
324
+ export async function codexSecurityCredentialAllowsAmbientImport(codexHome) {
325
+ await requireSecureCredentialHome(codexHome);
326
+ try {
327
+ const marker = await lstat(join(codexHome, CREDENTIAL_LOGOUT_MARKER));
328
+ if (!marker.isFile() || marker.isSymbolicLink()) {
329
+ throw new OutputDirectoryError(`Codex Security logout marker is not a regular file: ${codexHome}`);
330
+ }
331
+ return false;
332
+ }
333
+ catch (error) {
334
+ if (nodeErrorCode(error) === "ENOENT")
335
+ return true;
336
+ throw error;
337
+ }
338
+ }
339
+ export async function codexSecurityHasStoredFileCredentials(codexHome) {
340
+ await requireSecureCredentialHome(codexHome);
341
+ const path = join(codexHome, "auth.json");
342
+ let metadata;
343
+ try {
344
+ metadata = await lstat(path);
345
+ }
346
+ catch (error) {
347
+ if (nodeErrorCode(error) === "ENOENT")
348
+ return false;
349
+ throw error;
350
+ }
351
+ if (!metadata.isFile() || metadata.isSymbolicLink()) {
352
+ throw new OutputDirectoryError(`Codex Security stored authentication is not a regular file: ${path}`);
353
+ }
354
+ requirePrivateCredentialFile(metadata, path);
355
+ return true;
356
+ }
357
+ export function requirePrivateCredentialFile(metadata, path, effectiveUid = process.geteuid?.()) {
358
+ if (process.platform === "win32")
359
+ return;
360
+ if ((metadata.mode & 0o077) !== 0) {
361
+ throw new OutputDirectoryError(`Codex Security stored authentication must not be accessible to other users: ${path}`);
362
+ }
363
+ if (effectiveUid !== undefined && metadata.uid !== effectiveUid) {
364
+ throw new OutputDirectoryError(`Codex Security stored authentication must be owned by the current user: ${path}`);
365
+ }
366
+ }
367
+ export async function preserveCodexSecurityPluginRegistration(codexHome, config) {
368
+ let existing;
369
+ try {
370
+ existing = parse(await readFile(join(codexHome, "config.toml"), "utf8"));
371
+ }
372
+ catch (error) {
373
+ if (nodeErrorCode(error) === "ENOENT")
374
+ return config;
375
+ throw new PluginBootstrapError("Unable to read the existing Codex Security plugin registration.", { cause: error });
376
+ }
377
+ const marketplaces = isRecord(existing)
378
+ ? existing["marketplaces"]
379
+ : undefined;
380
+ const plugins = isRecord(existing) ? existing["plugins"] : undefined;
381
+ const marketplace = isRecord(marketplaces)
382
+ ? marketplaces[MARKETPLACE_NAME]
383
+ : undefined;
384
+ const plugin = isRecord(plugins)
385
+ ? plugins[`${PLUGIN_NAME}@${MARKETPLACE_NAME}`]
386
+ : undefined;
387
+ const source = isRecord(marketplace) ? marketplace["source"] : undefined;
388
+ if (!isRecord(marketplace) ||
389
+ marketplace["source_type"] !== "local" ||
390
+ typeof source !== "string" ||
391
+ !(await sameFile(source, join(codexHome, "sdk-marketplace"))) ||
392
+ !isRecord(plugin) ||
393
+ plugin["enabled"] !== true) {
394
+ return config;
395
+ }
396
+ return {
397
+ ...config,
398
+ marketplaces: {
399
+ [MARKETPLACE_NAME]: { source_type: "local", source },
400
+ },
401
+ plugins: {
402
+ [`${PLUGIN_NAME}@${MARKETPLACE_NAME}`]: { enabled: true },
403
+ },
404
+ };
405
+ }
42
406
  export async function preparePersistentScanRoot(stateDirectory, repositoryName) {
43
407
  const root = join(stateDirectory, "scans", safePrefix(repositoryName));
44
408
  await mkdir(root, { recursive: true, mode: 0o700 });
@@ -124,6 +488,7 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
124
488
  throw new OutputDirectoryError(`Scan output directory is not empty: ${path}. To keep the existing results and start a new scan, add --archive-existing.`);
125
489
  }
126
490
  requirePrivateOutputDirectory(metadata, path);
491
+ await requireSecureOutputAncestry(path);
127
492
  const canonical = await realpath(path);
128
493
  requireModelSafeOutputDir(canonical);
129
494
  return canonical;
@@ -134,6 +499,7 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
134
499
  if ((await stat(parent)).isDirectory()) {
135
500
  const canonical = resolve(await realpath(parent), relative(parent, path));
136
501
  requireModelSafeOutputDir(canonical);
502
+ await requireSecureOutputAncestry(canonical);
137
503
  return canonical;
138
504
  }
139
505
  break;
@@ -241,6 +607,7 @@ export async function validatePreparedOutputDir(path, validateLocation) {
241
607
  throw new OutputDirectoryError(`Scan output directory must be empty: ${path}`);
242
608
  }
243
609
  requirePrivateOutputDirectory(metadata, path);
610
+ await requireSecureOutputAncestry(canonical);
244
611
  return canonical;
245
612
  }
246
613
  export function requirePrivateOutputDirectory(metadata, path, effectiveUid = process.geteuid?.()) {
@@ -253,6 +620,57 @@ export function requirePrivateOutputDirectory(metadata, path, effectiveUid = pro
253
620
  throw new OutputDirectoryError(`Scan output directory must be owned by the current user: ${path}`);
254
621
  }
255
622
  }
623
+ /** Reject shared parents whose owner can rename or replace private scan output. */
624
+ export async function requireSecureOutputAncestry(path, effectiveUid = process.geteuid?.()) {
625
+ if (process.platform === "win32")
626
+ return;
627
+ let current = dirname(resolve(path));
628
+ while (true) {
629
+ try {
630
+ current = await realpath(current);
631
+ break;
632
+ }
633
+ catch (error) {
634
+ if (nodeErrorCode(error) !== "ENOENT") {
635
+ throw new OutputDirectoryError(`Unable to inspect scan output parent directory: ${current}`, { cause: error });
636
+ }
637
+ const parent = dirname(current);
638
+ if (parent === current) {
639
+ throw new OutputDirectoryError(`Unable to inspect scan output parent directory: ${current}`, { cause: error });
640
+ }
641
+ current = parent;
642
+ }
643
+ }
644
+ while (true) {
645
+ let metadata;
646
+ try {
647
+ metadata = await lstat(current);
648
+ }
649
+ catch (error) {
650
+ throw new OutputDirectoryError(`Unable to inspect scan output parent directory: ${current}`, { cause: error });
651
+ }
652
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
653
+ throw new OutputDirectoryError(`Scan output parent must be a non-symlink directory: ${current}`);
654
+ }
655
+ requireTrustedOutputAncestor(metadata, current, effectiveUid);
656
+ const parent = dirname(current);
657
+ if (parent === current)
658
+ return;
659
+ current = parent;
660
+ }
661
+ }
662
+ export function requireTrustedOutputAncestor(metadata, path, effectiveUid = process.geteuid?.()) {
663
+ if (effectiveUid !== undefined &&
664
+ metadata.uid !== 0 &&
665
+ metadata.uid !== effectiveUid) {
666
+ throw new OutputDirectoryError(`Scan output parent must have a trusted owner: ${path}`);
667
+ }
668
+ if ((metadata.mode & 0o022) === 0)
669
+ return;
670
+ if ((metadata.mode & 0o1000) === 0) {
671
+ throw new OutputDirectoryError(`Scan output parent must not be group- or world-writable without the sticky bit: ${path}`);
672
+ }
673
+ }
256
674
  async function removeEmptyDirectories(path, root) {
257
675
  let current = path;
258
676
  while (true) {
@@ -296,21 +714,45 @@ export async function importAmbientAuth(ambientHome, isolatedHome) {
296
714
  return false;
297
715
  }
298
716
  await mkdir(isolatedHome, { recursive: true, mode: 0o700 });
717
+ if (process.platform !== "win32" && (process.umask() & 0o700) !== 0) {
718
+ await chmod(isolatedHome, 0o700);
719
+ }
720
+ if (await codexSecurityHasStoredFileCredentials(isolatedHome))
721
+ return true;
299
722
  const destination = join(isolatedHome, "auth.json");
300
- const temporary = join(isolatedHome, `.auth-${process.pid}-${Date.now()}.tmp`);
723
+ const temporary = join(isolatedHome, `.auth-${randomUUID()}.tmp`);
301
724
  try {
302
725
  await copyFile(source, temporary, constants.COPYFILE_EXCL);
303
726
  await chmod(temporary, 0o600);
304
- await rename(temporary, destination);
727
+ try {
728
+ try {
729
+ await link(temporary, destination);
730
+ }
731
+ catch (error) {
732
+ if (!["EPERM", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "EMLINK"].includes(nodeErrorCode(error) ?? "")) {
733
+ throw error;
734
+ }
735
+ await copyFile(temporary, destination, constants.COPYFILE_EXCL);
736
+ }
737
+ }
738
+ catch (error) {
739
+ if (nodeErrorCode(error) === "EEXIST" &&
740
+ (await codexSecurityHasStoredFileCredentials(isolatedHome))) {
741
+ return true;
742
+ }
743
+ throw error;
744
+ }
305
745
  await chmod(destination, 0o600);
306
746
  return true;
307
747
  }
308
748
  catch (error) {
309
- await rm(temporary, { force: true }).catch(() => undefined);
310
749
  throw new PluginBootstrapError("Unable to copy ambient Codex authentication.", {
311
750
  cause: error,
312
751
  });
313
752
  }
753
+ finally {
754
+ await rm(temporary, { force: true }).catch(() => undefined);
755
+ }
314
756
  }
315
757
  export async function extractPluginZip(archive, destination, signal) {
316
758
  const archivePath = resolve(expandHome(archive));
@@ -495,6 +937,120 @@ export async function createMarketplace(codexHome, pluginRoot, signal) {
495
937
  throwIfSignalAborted(signal);
496
938
  return marketplace;
497
939
  }
940
+ async function pluginProjectionFingerprint(root, signal) {
941
+ throwIfSignalAborted(signal);
942
+ const canonical = await realpath(root);
943
+ const contractPath = join(canonical, ".internal", "external-promotion", "external-projection-contract.json");
944
+ let paths;
945
+ if (canonical === (await bundledPluginRoot()) &&
946
+ (await isRegularFile(contractPath))) {
947
+ let contract;
948
+ try {
949
+ contract = JSON.parse(await readFile(contractPath, "utf8"));
950
+ }
951
+ catch (error) {
952
+ throw new PluginBootstrapError(`Invalid plugin projection contract: ${contractPath}`, { cause: error });
953
+ }
954
+ const shipped = isRecord(contract) ? contract["shippedExact"] : undefined;
955
+ if (!Array.isArray(shipped) ||
956
+ !shipped.every((path) => typeof path === "string")) {
957
+ throw new PluginBootstrapError("Plugin projection contract must contain shippedExact paths.");
958
+ }
959
+ paths = [
960
+ ...new Set([".codex-plugin/plugin.json", ...shipped]
961
+ .filter((path) => !path.startsWith("sdk/"))
962
+ .map((path) => safeArchivePath(path))),
963
+ ];
964
+ }
965
+ else {
966
+ paths = [];
967
+ const pending = [canonical];
968
+ let entries = 1;
969
+ while (pending.length > 0) {
970
+ throwIfSignalAborted(signal);
971
+ const path = pending.pop();
972
+ const metadata = await lstat(path);
973
+ if (metadata.isSymbolicLink()) {
974
+ throw new PluginBootstrapError(`Plugin contains an unsafe source path: ${path}`);
975
+ }
976
+ if (metadata.isDirectory()) {
977
+ for await (const entry of pluginDirectoryEntries(path, signal)) {
978
+ const child = join(path, entry);
979
+ if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
980
+ throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${child}`);
981
+ }
982
+ pending.push(child);
983
+ }
984
+ }
985
+ else if (metadata.isFile()) {
986
+ paths.push(relative(canonical, path).split(sep).join("/"));
987
+ }
988
+ else {
989
+ throw new PluginBootstrapError(`Plugin contains a non-regular file: ${path}`);
990
+ }
991
+ }
992
+ }
993
+ paths.sort();
994
+ const fingerprint = createHash("sha256");
995
+ let totalSize = 0;
996
+ for (const relativePath of paths) {
997
+ throwIfSignalAborted(signal);
998
+ const path = join(canonical, ...relativePath.split("/"));
999
+ const metadata = await lstat(path);
1000
+ if (!metadata.isFile() || metadata.isSymbolicLink()) {
1001
+ throw new PluginBootstrapError(`Plugin projection contains an unsafe source path: ${path}`);
1002
+ }
1003
+ if (metadata.size > MAX_PLUGIN_COPY_FILE_SIZE) {
1004
+ throw new PluginBootstrapError(`Plugin source exceeds the per-file safety limit: ${path}`);
1005
+ }
1006
+ totalSize += metadata.size;
1007
+ if (totalSize > MAX_PLUGIN_COPY_SIZE) {
1008
+ throw new PluginBootstrapError("Plugin source exceeds the copy safety limit.");
1009
+ }
1010
+ const handle = await open(path, constants.O_RDONLY |
1011
+ (process.platform === "win32"
1012
+ ? 0
1013
+ : constants.O_NOFOLLOW | constants.O_NONBLOCK));
1014
+ try {
1015
+ if (!samePluginFile(metadata, await handle.stat())) {
1016
+ throw new PluginBootstrapError(`Plugin source changed before its integrity could be verified: ${path}`);
1017
+ }
1018
+ const contents = await readExactly(handle, metadata.size, 0, signal);
1019
+ if (!samePluginFile(metadata, await handle.stat())) {
1020
+ throw new PluginBootstrapError(`Plugin source changed while its integrity was being verified: ${path}`);
1021
+ }
1022
+ fingerprint.update(relativePath);
1023
+ fingerprint.update("\0");
1024
+ fingerprint.update(String(metadata.size));
1025
+ fingerprint.update("\0");
1026
+ fingerprint.update(contents);
1027
+ fingerprint.update("\0");
1028
+ }
1029
+ finally {
1030
+ await handle.close();
1031
+ }
1032
+ }
1033
+ return fingerprint.digest("hex");
1034
+ }
1035
+ async function codexSecurityPluginRegistration(codexHome) {
1036
+ let config;
1037
+ try {
1038
+ config = parse(await readFile(join(codexHome, "config.toml"), "utf8"));
1039
+ }
1040
+ catch (error) {
1041
+ if (nodeErrorCode(error) === "ENOENT") {
1042
+ return { marketplace: false, plugin: false };
1043
+ }
1044
+ throw new PluginBootstrapError("Unable to inspect the existing Codex Security plugin registration.", { cause: error });
1045
+ }
1046
+ const marketplaces = isRecord(config) ? config["marketplaces"] : undefined;
1047
+ const plugins = isRecord(config) ? config["plugins"] : undefined;
1048
+ return {
1049
+ marketplace: isRecord(marketplaces) && isRecord(marketplaces[MARKETPLACE_NAME]),
1050
+ plugin: isRecord(plugins) &&
1051
+ isRecord(plugins[`${PLUGIN_NAME}@${MARKETPLACE_NAME}`]),
1052
+ };
1053
+ }
498
1054
  export function resolveCodexCommand() {
499
1055
  const { packageName, targetTriple } = codexPlatformPackage();
500
1056
  const require = createRequire(import.meta.url);
@@ -529,25 +1085,87 @@ export function codexPlatformPackage(platform = process.platform, architecture =
529
1085
  export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
530
1086
  const root = await realpath(pluginRoot);
531
1087
  const { name, version } = await pluginMetadata(root);
532
- const marketplace = await createMarketplace(codexHome, root, options.signal);
1088
+ const existingMarketplace = join(codexHome, "sdk-marketplace");
1089
+ let upgradeExistingPlugin = false;
1090
+ let repairIncompletePlugin = false;
1091
+ let installedRoot = null;
1092
+ try {
1093
+ await verifyPluginRegistration(codexHome, existingMarketplace);
1094
+ installedRoot = await findInstalledPlugin(codexHome);
1095
+ }
1096
+ catch (error) {
1097
+ throwIfSignalAborted(options.signal);
1098
+ if (!(error instanceof PluginBootstrapError) &&
1099
+ nodeErrorCode(error) !== "ENOENT") {
1100
+ throw error;
1101
+ }
1102
+ const marketplace = await lstat(existingMarketplace).catch((failure) => {
1103
+ if (nodeErrorCode(failure) === "ENOENT")
1104
+ return null;
1105
+ throw failure;
1106
+ });
1107
+ if (marketplace !== null &&
1108
+ (!marketplace.isDirectory() || marketplace.isSymbolicLink())) {
1109
+ throw new PluginBootstrapError(`Codex Security marketplace is not a safe directory: ${existingMarketplace}`);
1110
+ }
1111
+ const registration = await codexSecurityPluginRegistration(codexHome);
1112
+ repairIncompletePlugin =
1113
+ marketplace !== null || registration.marketplace || registration.plugin;
1114
+ }
1115
+ if (installedRoot !== null) {
1116
+ const installed = await pluginMetadata(installedRoot);
1117
+ if (installed.name === name && installed.version === version) {
1118
+ const [selectedFingerprint, marketplaceFingerprint] = await Promise.all([
1119
+ pluginProjectionFingerprint(root, options.signal),
1120
+ pluginProjectionFingerprint(join(existingMarketplace, "plugins", PLUGIN_NAME), options.signal),
1121
+ ]);
1122
+ if (selectedFingerprint === marketplaceFingerprint) {
1123
+ return {
1124
+ pluginRoot: root,
1125
+ marketplaceRoot: existingMarketplace,
1126
+ installedRoot,
1127
+ marketplaceName: MARKETPLACE_NAME,
1128
+ name,
1129
+ version,
1130
+ };
1131
+ }
1132
+ }
1133
+ upgradeExistingPlugin = true;
1134
+ }
1135
+ throwIfSignalAborted(options.signal);
533
1136
  const command = options.codexCommand ?? resolveCodexCommand();
534
1137
  const environment = {
535
1138
  ...(options.environment ?? process.env),
536
1139
  CODEX_HOME: codexHome,
537
1140
  };
538
1141
  const run = options.runCodex ?? runCodex;
1142
+ if (upgradeExistingPlugin || repairIncompletePlugin) {
1143
+ const registration = await codexSecurityPluginRegistration(codexHome);
1144
+ if (registration.plugin) {
1145
+ await run(command, ["plugin", "remove", `${PLUGIN_NAME}@${MARKETPLACE_NAME}`], environment, options.signal);
1146
+ throwIfSignalAborted(options.signal);
1147
+ }
1148
+ if (registration.marketplace) {
1149
+ await run(command, ["plugin", "marketplace", "remove", MARKETPLACE_NAME], environment, options.signal);
1150
+ throwIfSignalAborted(options.signal);
1151
+ }
1152
+ throwIfSignalAborted(options.signal);
1153
+ await rm(existingMarketplace, { recursive: true, force: true });
1154
+ throwIfSignalAborted(options.signal);
1155
+ }
1156
+ const marketplace = await createMarketplace(codexHome, root, options.signal);
539
1157
  await run(command, ["plugin", "marketplace", "add", marketplace], environment, options.signal);
540
1158
  await run(command, ["plugin", "add", `${PLUGIN_NAME}@${MARKETPLACE_NAME}`], environment, options.signal);
541
1159
  await verifyPluginRegistration(codexHome, marketplace);
542
- const installedRoot = await findInstalledPlugin(codexHome);
543
- const installed = await pluginMetadata(installedRoot);
1160
+ const verifiedInstalledRoot = await findInstalledPlugin(codexHome);
1161
+ const installed = await pluginMetadata(verifiedInstalledRoot);
544
1162
  if (installed.name !== name || installed.version !== version) {
545
1163
  throw new PluginBootstrapError("Installed Codex Security plugin metadata does not match the selected plugin.");
546
1164
  }
547
1165
  return {
548
1166
  pluginRoot: root,
549
1167
  marketplaceRoot: marketplace,
550
- installedRoot,
1168
+ installedRoot: verifiedInstalledRoot,
551
1169
  marketplaceName: MARKETPLACE_NAME,
552
1170
  name,
553
1171
  version,
@@ -725,7 +1343,7 @@ async function copyPluginTree(source, destination, signal) {
725
1343
  { source, destination },
726
1344
  ];
727
1345
  const directories = new Map();
728
- let entries = 0;
1346
+ let entries = 1;
729
1347
  let size = 0;
730
1348
  await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
731
1349
  try {
@@ -734,26 +1352,26 @@ async function copyPluginTree(source, destination, signal) {
734
1352
  const current = pending.pop();
735
1353
  await requirePluginAncestors(source, current.source, directories, signal);
736
1354
  const metadata = await lstat(current.source);
737
- if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
738
- throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${current.source}`);
739
- }
740
1355
  if (metadata.isSymbolicLink()) {
741
1356
  throw new PluginBootstrapError(`Plugin contains an unsafe source path: ${current.source}`);
742
1357
  }
743
1358
  if (metadata.isDirectory()) {
744
- const children = await readdir(current.source);
1359
+ for await (const entry of pluginDirectoryEntries(current.source, signal)) {
1360
+ const childSource = join(current.source, entry);
1361
+ if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
1362
+ throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${childSource}`);
1363
+ }
1364
+ pending.push({
1365
+ source: childSource,
1366
+ destination: join(current.destination, entry),
1367
+ });
1368
+ }
745
1369
  const afterRead = await lstat(current.source);
746
1370
  if (!samePluginFile(metadata, afterRead)) {
747
1371
  throw new PluginBootstrapError(`Plugin directory changed while it was being copied: ${current.source}`);
748
1372
  }
749
1373
  directories.set(current.source, afterRead);
750
1374
  await mkdir(current.destination, { mode: 0o700 });
751
- for (const child of children) {
752
- pending.push({
753
- source: join(current.source, child),
754
- destination: join(current.destination, child),
755
- });
756
- }
757
1375
  continue;
758
1376
  }
759
1377
  if (!metadata.isFile()) {
@@ -799,6 +1417,23 @@ async function copyPluginTree(source, destination, signal) {
799
1417
  throw error;
800
1418
  }
801
1419
  }
1420
+ async function* pluginDirectoryEntries(path, signal) {
1421
+ throwIfSignalAborted(signal);
1422
+ const directory = await opendir(path);
1423
+ try {
1424
+ for (;;) {
1425
+ throwIfSignalAborted(signal);
1426
+ const entry = await directory.read();
1427
+ throwIfSignalAborted(signal);
1428
+ if (entry === null)
1429
+ return;
1430
+ yield entry.name;
1431
+ }
1432
+ }
1433
+ finally {
1434
+ await directory.close();
1435
+ }
1436
+ }
802
1437
  async function requirePluginAncestors(root, path, directories, signal) {
803
1438
  const relativePath = relative(root, path);
804
1439
  if (relativePath === ".." ||