@openai/codex-security 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -86,6 +86,7 @@ from workbench_scan_start import (
86
86
  safe_segment,
87
87
  scan_diff_identity,
88
88
  scan_target_identity,
89
+ stored_diff_target,
89
90
  )
90
91
  from workbench_schema import MIGRATIONS, normalize_pre_release_migrations, sql_statements
91
92
  from workbench_source_excerpt import finding_source_excerpt
@@ -504,19 +505,6 @@ def expected_target_kinds(scan: sqlite3.Row) -> list[str]:
504
505
  return ["git_worktree"]
505
506
 
506
507
 
507
- def stored_diff_target(row: sqlite3.Row) -> dict[str, str] | None:
508
- if not row["diff_target_kind"]:
509
- return None
510
- target = {
511
- "baseRevision": row["diff_base_revision"],
512
- "headRevision": row["diff_head_revision"],
513
- "kind": row["diff_target_kind"],
514
- }
515
- if row["diff_content_digest"]:
516
- target["contentDigest"] = row["diff_content_digest"]
517
- return target
518
-
519
-
520
508
  def requested_scan_paths(scan: sqlite3.Row) -> list[str]:
521
509
  if "recipe_json" in scan.keys() and scan["recipe_json"] is not None:
522
510
  recipe = json.loads(scan["recipe_json"], parse_constant=reject_non_finite_json)
@@ -1374,11 +1362,15 @@ def pin_legacy_manifest_digest(
1374
1362
  raise
1375
1363
 
1376
1364
 
1377
- def complete_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:
1365
+ def complete_scan(
1366
+ connection: sqlite3.Connection, args: argparse.Namespace, *, prepare_only: bool = False
1367
+ ) -> dict[str, Any]:
1378
1368
  scan_id = require_uuid(args.scan_id, "scan-id")
1379
- cost_json = parse_scan_cost(args.cost_json)
1369
+ cost_json = None if prepare_only else parse_scan_cost(args.cost_json)
1380
1370
  with scan_completion_lock(scan_id):
1381
- return complete_scan_locked(connection, scan_id, args.claim_token, cost_json)
1371
+ return complete_scan_locked(
1372
+ connection, scan_id, args.claim_token, cost_json, prepare_only=prepare_only
1373
+ )
1382
1374
 
1383
1375
 
1384
1376
  def complete_scan_locked(
@@ -1386,6 +1378,8 @@ def complete_scan_locked(
1386
1378
  scan_id: str,
1387
1379
  claim_token: str | None,
1388
1380
  cost_json: str | None,
1381
+ *,
1382
+ prepare_only: bool = False,
1389
1383
  ) -> dict[str, Any]:
1390
1384
  scan = require_scan(connection, scan_id)
1391
1385
  if scan["status"] == "complete":
@@ -1412,9 +1406,9 @@ def complete_scan_locked(
1412
1406
  )
1413
1407
  if scan["recipe_json"] is None:
1414
1408
  deep_scan.require_deep_scan_ready_for_parent_completion(connection, scan)
1415
- warnings = []
1409
+ warnings = json.loads(scan["completion_warnings_json"])
1416
1410
  warning = scan_target_warning(scan)
1417
- if warning is not None:
1411
+ if warning is not None and warning not in warnings:
1418
1412
  warnings.append(warning)
1419
1413
  scan_dir = require_canonical_scan_directory(Path(scan["scan_dir"]))
1420
1414
  completion_timestamp = now()
@@ -1430,6 +1424,7 @@ def complete_scan_locked(
1430
1424
  scan_dir,
1431
1425
  expected_coverage_mode=expected_coverage_mode(scan),
1432
1426
  completion_binding=completion_binding,
1427
+ completion_warnings=warnings,
1433
1428
  )
1434
1429
  warning = scan_target_warning(scan)
1435
1430
  if warning is not None and warning not in warnings:
@@ -1442,9 +1437,23 @@ def complete_scan_locked(
1442
1437
  for kind, filename in ARTIFACTS.items()
1443
1438
  }
1444
1439
  manifest_digest = published_manifest_digest(scan_dir, manifest)
1440
+ if prepare_only:
1441
+ connection.execute("BEGIN IMMEDIATE")
1442
+ try:
1443
+ updated = connection.execute(
1444
+ "UPDATE scans SET completion_warnings_json = ? WHERE id = ? AND status = 'running'",
1445
+ (json.dumps(warnings), scan["id"]),
1446
+ )
1447
+ if updated.rowcount != 1:
1448
+ raise SystemExit("Only a running scan can be prepared for completion.")
1449
+ connection.commit()
1450
+ except BaseException:
1451
+ connection.rollback()
1452
+ raise
1453
+ return scan_context(connection, scan["id"])
1445
1454
  connection.execute("BEGIN IMMEDIATE")
1446
1455
  try:
1447
- timestamp = completion_timestamp
1456
+ timestamp = manifest["scan"]["completedAt"]
1448
1457
  scan = require_scan(connection, scan["id"])
1449
1458
  if scan["status"] == "complete":
1450
1459
  connection.commit()
@@ -1608,7 +1617,14 @@ def register_cli_scan(connection: sqlite3.Connection, args: argparse.Namespace)
1608
1617
  except BaseException:
1609
1618
  connection.rollback()
1610
1619
  raise
1611
- return {"scanDir": str(scan_dir), "scanId": scan_id, "targetId": target_id}
1620
+ scan = require_scan(connection, scan_id)
1621
+ return {
1622
+ "contract": scan_contract(scan),
1623
+ "scanDir": str(scan_dir),
1624
+ "scanId": scan_id,
1625
+ "targetId": target_id,
1626
+ "targetRevision": scan["target_revision"],
1627
+ }
1612
1628
 
1613
1629
 
1614
1630
  def parse_scan_recipe(value: str, repository: Path) -> dict[str, Any]:
@@ -3435,7 +3451,7 @@ def artifact_path(scan_dir: Path, file_name: str, *, required: bool) -> Path | N
3435
3451
  raise SystemExit(
3436
3452
  f"{file_name}: expected a regular file inside the scan directory."
3437
3453
  ) from exc
3438
- if resolved != candidate or not candidate.is_file():
3454
+ if os.path.normcase(resolved) != os.path.normcase(candidate) or not candidate.is_file():
3439
3455
  raise SystemExit(f"{file_name}: expected a regular non-symlink file.")
3440
3456
  return resolved
3441
3457
 
@@ -3449,7 +3465,9 @@ def require_canonical_scan_directory(scan_dir: Path) -> Path:
3449
3465
  raise SystemExit(
3450
3466
  "Scan directory must be an existing canonical non-symlink directory."
3451
3467
  ) from exc
3452
- if not stat.S_ISDIR(metadata.st_mode) or resolved != scan_dir:
3468
+ if not stat.S_ISDIR(metadata.st_mode) or os.path.normcase(resolved) != os.path.normcase(
3469
+ scan_dir
3470
+ ):
3453
3471
  raise SystemExit("Scan directory must be an existing canonical non-symlink directory.")
3454
3472
  return scan_dir
3455
3473
 
@@ -3593,8 +3611,10 @@ def main() -> None:
3593
3611
  require_scan=require_scan,
3594
3612
  scan_context=scan_context,
3595
3613
  )
3596
- elif args.command == "complete-scan":
3597
- result = complete_scan(connection, args)
3614
+ elif args.command in {"prepare-scan-completion", "complete-scan"}:
3615
+ result = complete_scan(
3616
+ connection, args, prepare_only=args.command == "prepare-scan-completion"
3617
+ )
3598
3618
  elif args.command == "cancel-scan":
3599
3619
  result = cancel_scan(connection, args)
3600
3620
  elif args.command == "fail-scan":
@@ -72,6 +72,19 @@ def scan_diff_identity(
72
72
  )
73
73
 
74
74
 
75
+ def stored_diff_target(row: sqlite3.Row) -> dict[str, str] | None:
76
+ if not row["diff_target_kind"]:
77
+ return None
78
+ target = {
79
+ "baseRevision": row["diff_base_revision"],
80
+ "headRevision": row["diff_head_revision"],
81
+ "kind": row["diff_target_kind"],
82
+ }
83
+ if row["diff_content_digest"]:
84
+ target["contentDigest"] = row["diff_content_digest"]
85
+ return target
86
+
87
+
75
88
  def archive_scan(
76
89
  connection: sqlite3.Connection,
77
90
  args: argparse.Namespace,
package/dist/api.d.ts CHANGED
@@ -97,6 +97,7 @@ interface ScanEventRunOptions {
97
97
  scanDir: string;
98
98
  pluginRoot: string;
99
99
  expectation: ScanExpectation;
100
+ workbenchValidated?: boolean;
100
101
  model?: string;
101
102
  onFinalize?: (usage: unknown) => Promise<unknown>;
102
103
  onThreadStarted?: (threadId: string) => void;
@@ -108,7 +109,7 @@ interface ScanEventRunOptions {
108
109
  export declare function runScanEvents(options: ScanEventRunOptions): Promise<ScanResult>;
109
110
  export declare function scanAuthentication(environment: ProcessEnvironment, auth?: ScanAuthMode): ScanAuthentication;
110
111
  export declare function classifyConnectionFailure(error: unknown): "rate_limited" | "unauthorized" | "forbidden" | "network_error" | "timeout" | "unknown";
111
- export declare function scanRuntimeCodexConfig(config: JsonObject, stateDirectory: string): JsonObject;
112
+ export declare function scanRuntimeCodexConfig(config: JsonObject, stateDirectory: string, protectedCredentialHome?: string): JsonObject;
112
113
  export declare function scanPreflightCodexConfig(config: JsonObject): JsonObject;
113
114
  export declare function environmentValue(environment: ProcessEnvironment, requested: string): string | undefined;
114
115
  export {};
package/dist/api.d.ts.map CHANGED
@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13
  import { ScanResult } from "./result.js";
14
14
  import { workerStatusFromEvent, } from "./worker-progress.js";
15
15
  import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";
16
- import { bootstrapPlugin, cleanupSdkDirectory, codexSecurityStateDirectory, createIsolatedHome, importAmbientAuth, pluginExecutionEnvironment, planOutputArchive, prepareOutputDir, preparePersistentScanRoot, requireModelSafeOutputDir, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, validateOutputDir, } from "./runtime.js";
16
+ import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, planOutputArchive, prepareOutputDir, preparePersistentScanRoot, requireModelSafeOutputDir, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
17
17
  import { enclosingGitWorktreeRoot, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateMode, } from "./targets.js";
18
18
  const DEFAULT_DEPENDENCIES = {
19
19
  createCodex: (options) => new Codex(options),
@@ -84,6 +84,8 @@ export class CodexSecurity {
84
84
  let targetPathsFile = null;
85
85
  let knowledgeBase = null;
86
86
  let costTracker = null;
87
+ let releaseCredentialHome = null;
88
+ let completionCost = null;
87
89
  let activeScan = null;
88
90
  const workbench = this.#dependencies.runWorkbench ?? runWorkbench;
89
91
  try {
@@ -112,7 +114,18 @@ export class CodexSecurity {
112
114
  checkOpen();
113
115
  const authentication = scanAuthentication(this.#dependencies.environment, options.auth);
114
116
  const scanEnvironment = selectedScanEnvironment(this.#dependencies.environment, options.auth);
117
+ if (authentication.method === "stored_credentials" &&
118
+ this.#dependencies.prepareRuntime === undefined) {
119
+ const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"));
120
+ releaseCredentialHome = await acquireCodexSecurityCredentialHomeLock(credentialHome, signal);
121
+ }
122
+ const previousRuntime = this.#runtime;
115
123
  const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"), options.auth);
124
+ if (runtime === previousRuntime &&
125
+ runtime.persistentCredentialHome === true &&
126
+ this.#dependencies.prepareRuntime === undefined) {
127
+ await this.#refreshPersistentRuntime(runtime, scanEnvironment, signal);
128
+ }
116
129
  const runtimeHome = await realpath(runtime.codexHome);
117
130
  requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");
118
131
  if (options.expectedPluginVersion !== undefined &&
@@ -133,15 +146,17 @@ export class CodexSecurity {
133
146
  ? environmentApiKey(this.#dependencies.environment)
134
147
  : null;
135
148
  if (apiKey !== null) {
136
- const codexCommand = this.#codexCommand();
137
- const login = await persistApiKey(codexCommand, runtime.environment, apiKey, signal);
138
- if (!login.success) {
139
- throw new CodexSecurityError(`Codex API-key login failed: ${login.stderr.trim() || login.stdout.trim() || "unknown error"}`);
140
- }
141
- runtime.credentialsAvailable = true;
142
149
  this.#runtimeCredentialSource = "api_key";
143
150
  }
144
- if (!runtime.credentialsAvailable) {
151
+ if (!runtime.credentialsAvailable &&
152
+ authentication.method === "stored_credentials") {
153
+ const status = await accountStatus(this.#codexCommand(), runtime.environment, signal);
154
+ runtime.credentialsAvailable = status.authenticated;
155
+ this.#runtimeCredentialSource = status.authenticated
156
+ ? "stored_credentials"
157
+ : null;
158
+ }
159
+ if (!runtime.credentialsAvailable && apiKey === null) {
145
160
  throw new AuthenticationRequiredError("No credentials were found. Run 'codex-security login', use " +
146
161
  "'codex-security login --device-auth' on a remote or headless machine, or set " +
147
162
  "OPENAI_API_KEY or CODEX_API_KEY for CI.");
@@ -233,11 +248,43 @@ export class CodexSecurity {
233
248
  ]);
234
249
  const scanId = registration["scanId"];
235
250
  const targetId = registration["targetId"];
251
+ const contract = registration["contract"];
252
+ const contractTarget = isRecord(contract)
253
+ ? contract["target"]
254
+ : undefined;
255
+ const allowedKinds = isRecord(contractTarget)
256
+ ? contractTarget["allowedKinds"]
257
+ : undefined;
258
+ const targetKind = Array.isArray(allowedKinds) && allowedKinds.length === 1
259
+ ? allowedKinds[0]
260
+ : undefined;
261
+ const diffTarget = isRecord(contract)
262
+ ? contract["diffTarget"]
263
+ : undefined;
264
+ const snapshotDigest = targetKind === "git_diff" && isRecord(diffTarget)
265
+ ? diffTarget["contentDigest"]
266
+ : isRecord(contractTarget)
267
+ ? contractTarget["requiredSnapshotDigest"]
268
+ : undefined;
269
+ const registeredRevision = registration["targetRevision"];
236
270
  if (typeof scanId !== "string" ||
237
271
  typeof targetId !== "string" ||
238
- registration["scanDir"] !== scanDir) {
272
+ registration["scanDir"] !== scanDir ||
273
+ typeof targetKind !== "string" ||
274
+ ![
275
+ "git_revision",
276
+ "git_worktree",
277
+ "git_diff",
278
+ "directory_snapshot",
279
+ ].includes(targetKind) ||
280
+ (snapshotDigest !== undefined && typeof snapshotDigest !== "string") ||
281
+ ((targetKind === "git_worktree" ||
282
+ targetKind === "directory_snapshot") &&
283
+ typeof snapshotDigest !== "string") ||
284
+ typeof registeredRevision !== "string") {
239
285
  throw new CodexSecurityError("The Codex Security workbench returned an invalid scan registration.");
240
286
  }
287
+ const targetRevision = registeredRevision === "unversioned" ? null : registeredRevision;
241
288
  activeScan = { id: scanId, options: workbenchOptions };
242
289
  checkOpen();
243
290
  const feedback = await workbench({
@@ -281,6 +328,13 @@ export class CodexSecurity {
281
328
  CODEX_SECURITY_SCAN_ID: scanId,
282
329
  CODEX_SECURITY_TARGET_ID: targetId,
283
330
  CODEX_SECURITY_TARGET_DISPLAY_NAME: basename(repo),
331
+ CODEX_SECURITY_TARGET_KIND: targetKind,
332
+ ...(targetRevision === null
333
+ ? {}
334
+ : { CODEX_SECURITY_TARGET_REVISION: targetRevision }),
335
+ ...(typeof snapshotDigest === "string"
336
+ ? { CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST: snapshotDigest }
337
+ : {}),
284
338
  ...(knowledgeBase === null
285
339
  ? {}
286
340
  : { CODEX_SECURITY_KNOWLEDGE_BASE: knowledgeBase.path }),
@@ -297,7 +351,8 @@ export class CodexSecurity {
297
351
  ...runtimePaths,
298
352
  };
299
353
  const codex = this.#dependencies.createCodex({
300
- env: definedEnvironment(environment),
354
+ ...(apiKey === null ? {} : { apiKey }),
355
+ env: definedEnvironment(selectedScanEnvironment(environment, "chatgpt")),
301
356
  config: {
302
357
  default_permissions: SCAN_PERMISSION_PROFILE,
303
358
  allow_login_shell: false,
@@ -335,6 +390,7 @@ export class CodexSecurity {
335
390
  scanDir,
336
391
  pluginRoot: runtime.plugin.installedRoot,
337
392
  expectation,
393
+ workbenchValidated: true,
338
394
  model,
339
395
  onThreadStarted: (threadId) => tracker.start(threadId),
340
396
  onFinalize: async (usage) => {
@@ -343,23 +399,12 @@ export class CodexSecurity {
343
399
  if (options.maxCostUsd !== undefined && snapshot.cost === null) {
344
400
  notifyObserver("onWarning", options.onWarning, options.onObserverError, "Scan completed, but its cost limit could not be verified because model pricing or token usage is unavailable.");
345
401
  }
346
- const cost = snapshot.cost;
347
- const completion = await workbench(workbenchOptions, [
348
- "complete-scan",
402
+ completionCost = snapshot.cost;
403
+ await workbench(workbenchOptions, [
404
+ "prepare-scan-completion",
349
405
  "--scan-id",
350
406
  scanId,
351
- ...(cost === null ? [] : ["--cost-json", JSON.stringify(cost)]),
352
407
  ]);
353
- activeScan = null;
354
- const completedScan = completion["scan"];
355
- if (isRecord(completedScan) &&
356
- Array.isArray(completedScan["warnings"])) {
357
- for (const warning of completedScan["warnings"]) {
358
- if (typeof warning === "string") {
359
- notifyObserver("onWarning", options.onWarning, options.onObserverError, warning);
360
- }
361
- }
362
- }
363
408
  return snapshot.usage;
364
409
  },
365
410
  onScanStarted: options.onScanStarted,
@@ -368,6 +413,23 @@ export class CodexSecurity {
368
413
  onObserverError: options.onObserverError,
369
414
  });
370
415
  checkOpen();
416
+ const completion = await workbench(workbenchOptions, [
417
+ "complete-scan",
418
+ "--scan-id",
419
+ scanId,
420
+ ...(completionCost === null
421
+ ? []
422
+ : ["--cost-json", JSON.stringify(completionCost)]),
423
+ ]);
424
+ activeScan = null;
425
+ const completedScan = completion["scan"];
426
+ if (isRecord(completedScan) && Array.isArray(completedScan["warnings"])) {
427
+ for (const warning of completedScan["warnings"]) {
428
+ if (typeof warning === "string") {
429
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, warning);
430
+ }
431
+ }
432
+ }
371
433
  return result;
372
434
  }
373
435
  catch (error) {
@@ -400,25 +462,33 @@ export class CodexSecurity {
400
462
  throw failure;
401
463
  }
402
464
  finally {
403
- await Promise.all([
404
- knowledgeBase?.cleanup(),
405
- removeTargetPathsFile(targetPathsFile),
406
- ]);
465
+ try {
466
+ await Promise.all([
467
+ knowledgeBase?.cleanup(),
468
+ removeTargetPathsFile(targetPathsFile),
469
+ ]);
470
+ }
471
+ finally {
472
+ await releaseCredentialHome?.();
473
+ }
407
474
  }
408
475
  }
409
476
  async loginApiKey(apiKey) {
410
477
  const { result, runtime } = await this.#runOperation(async (preparedRuntime, signal) => ({
411
478
  runtime: preparedRuntime,
412
479
  result: await persistApiKey(this.#codexCommand(), preparedRuntime.environment, apiKey, signal),
413
- }));
480
+ }), "chatgpt");
414
481
  if (!result.success) {
415
482
  throw new CodexSecurityError(`Codex API-key login failed: ${result.stderr.trim() || result.stdout.trim() || "unknown error"}`);
416
483
  }
484
+ if (runtime.persistentCredentialHome === true) {
485
+ await setCodexSecurityCredentialLogout(runtime.codexHome, false);
486
+ }
417
487
  runtime.credentialsAvailable = true;
418
488
  this.#runtimeCredentialSource = "api_key";
419
489
  }
420
490
  async loginChatGPT() {
421
- const runtime = await this.#ensureRuntime();
491
+ const runtime = await this.#ensureRuntime(undefined, undefined, undefined, "chatgpt");
422
492
  this.#requireOpen();
423
493
  const handle = this.#trackLoginHandle(new CodexLoginHandle(this.#codexCommand(), ["login"], runtime.environment, () => {
424
494
  runtime.credentialsAvailable = true;
@@ -429,7 +499,7 @@ export class CodexSecurity {
429
499
  return handle;
430
500
  }
431
501
  async loginChatGPTDeviceCode() {
432
- const runtime = await this.#ensureRuntime();
502
+ const runtime = await this.#ensureRuntime(undefined, undefined, undefined, "chatgpt");
433
503
  this.#requireOpen();
434
504
  const handle = this.#trackLoginHandle(new CodexLoginHandle(this.#codexCommand(), ["login", "--device-auth"], runtime.environment, () => {
435
505
  runtime.credentialsAvailable = true;
@@ -455,7 +525,10 @@ export class CodexSecurity {
455
525
  const runtime = await this.#runOperation(async (preparedRuntime, signal) => {
456
526
  await codexLogout(this.#codexCommand(), preparedRuntime.environment, signal);
457
527
  return preparedRuntime;
458
- });
528
+ }, "chatgpt");
529
+ if (runtime.persistentCredentialHome === true) {
530
+ await setCodexSecurityCredentialLogout(runtime.codexHome, true);
531
+ }
459
532
  runtime.credentialsAvailable = false;
460
533
  this.#runtimeCredentialSource = null;
461
534
  }
@@ -481,22 +554,28 @@ export class CodexSecurity {
481
554
  this.#runtime = null;
482
555
  this.#runtimePromise = null;
483
556
  if (runtime !== null && runtime !== undefined) {
484
- const cleanupResults = await Promise.allSettled([runtime.codexHome, runtime.bootstrapWorkspace]
485
- .filter((path) => path !== undefined)
486
- .map((path) => cleanupSdkDirectory(path)));
487
- for (const result of cleanupResults) {
488
- if (result.status === "rejected")
489
- throw result.reason;
490
- }
557
+ await this.#cleanupRuntime(runtime);
558
+ }
559
+ }
560
+ async #cleanupRuntime(runtime) {
561
+ const cleanupResults = await Promise.allSettled([
562
+ runtime.persistentCredentialHome ? undefined : runtime.codexHome,
563
+ runtime.bootstrapWorkspace,
564
+ ]
565
+ .filter((path) => path !== undefined)
566
+ .map((path) => cleanupSdkDirectory(path)));
567
+ for (const result of cleanupResults) {
568
+ if (result.status === "rejected")
569
+ throw result.reason;
491
570
  }
492
571
  }
493
572
  async [Symbol.asyncDispose]() {
494
573
  await this.close();
495
574
  }
496
- async #runOperation(operation) {
575
+ async #runOperation(operation, auth = "auto") {
497
576
  return await this.#trackOperation(async () => {
498
577
  const signal = this.#abortController.signal;
499
- const runtime = await this.#ensureRuntime(signal);
578
+ const runtime = await this.#ensureRuntime(signal, undefined, undefined, auth);
500
579
  this.#requireOpen();
501
580
  const result = await operation(runtime, signal);
502
581
  this.#requireOpen();
@@ -521,8 +600,20 @@ export class CodexSecurity {
521
600
  }
522
601
  async #ensureRuntime(signal, temporaryRoot, validateLocation, auth = "auto") {
523
602
  this.#requireOpen();
524
- if (this.#runtime !== null)
525
- return this.#runtime;
603
+ if (this.#runtime !== null) {
604
+ const usePersistentCredentials = scanAuthentication(this.#dependencies.environment, auth).method ===
605
+ "stored_credentials";
606
+ if (this.#dependencies.prepareRuntime !== undefined ||
607
+ this.#runtime.persistentCredentialHome === undefined ||
608
+ this.#runtime.persistentCredentialHome === usePersistentCredentials) {
609
+ return this.#runtime;
610
+ }
611
+ await this.#cleanupRuntime(this.#runtime);
612
+ this.#runtime = null;
613
+ this.#runtimePromise = null;
614
+ this.#runtimeCredentialSource = null;
615
+ this.#requireOpen();
616
+ }
526
617
  if (this.#runtimePromise === null) {
527
618
  const runtimePromise = this.#prepareRuntime(signal ?? this.#abortController.signal, temporaryRoot, validateLocation, auth);
528
619
  this.#runtimePromise = runtimePromise;
@@ -548,6 +639,20 @@ export class CodexSecurity {
548
639
  #codexCommand() {
549
640
  return (this.#dependencies.resolveCodexCommand ?? resolveCodexCommand)();
550
641
  }
642
+ async #refreshPersistentRuntime(runtime, environment, signal) {
643
+ throwIfAborted(signal);
644
+ const mergedConfig = await mergedCodexConfig(this.config);
645
+ const config = await preserveCodexSecurityPluginRegistration(runtime.codexHome, scanRuntimeCodexConfig(mergedConfig, codexSecurityStateDirectory(environment), runtime.codexHome));
646
+ await writeCodexConfig(join(runtime.codexHome, "config.toml"), config);
647
+ if (runtime.configPath !== undefined) {
648
+ await writeCodexConfig(runtime.configPath, scanPreflightCodexConfig(mergedConfig));
649
+ }
650
+ runtime.plugin = await bootstrapPlugin(runtime.codexHome, runtime.plugin.pluginRoot, {
651
+ environment: withoutCodexHome(environment),
652
+ signal,
653
+ });
654
+ runtime.effectiveConfig = mergedConfig;
655
+ }
551
656
  async #validateLocalInputs(repository, options, signal) {
552
657
  if (options.maxCostUsd !== undefined &&
553
658
  (!Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0)) {
@@ -579,18 +684,22 @@ export class CodexSecurity {
579
684
  if (this.#dependencies.prepareRuntime !== undefined) {
580
685
  return await this.#dependencies.prepareRuntime(this.config, signal);
581
686
  }
582
- const codexHome = await createIsolatedHome(temporaryRoot, validateLocation);
687
+ const processEnvironment = selectedScanEnvironment(this.#dependencies.environment, auth);
688
+ const persistentCredentialHome = scanAuthentication(this.#dependencies.environment, auth).method ===
689
+ "stored_credentials";
690
+ const codexHome = persistentCredentialHome
691
+ ? await prepareCodexSecurityCredentialHome(processEnvironment, validateLocation)
692
+ : await createIsolatedHome(temporaryRoot, validateLocation);
583
693
  let bootstrapWorkspace;
584
694
  try {
585
695
  throwIfAborted(signal);
586
- bootstrapWorkspace = await createIsolatedHome(dirname(codexHome), validateLocation);
696
+ bootstrapWorkspace = await createIsolatedHome(temporaryRoot, validateLocation);
587
697
  const pluginRoot = await resolvePluginPath(this.config.pluginPath, bootstrapWorkspace, signal);
588
- const processEnvironment = selectedScanEnvironment(this.#dependencies.environment, auth);
589
698
  const nodeAmbientHome = join(homedir(), ".codex");
590
699
  const configuredAmbientHome = environmentValue(processEnvironment, "CODEX_HOME");
591
700
  const ambientHome = configuredAmbientHome ?? nodeAmbientHome;
592
701
  const mergedConfig = await mergedCodexConfig(this.config);
593
- const codexConfig = scanRuntimeCodexConfig(mergedConfig, codexSecurityStateDirectory(processEnvironment));
702
+ const codexConfig = await preserveCodexSecurityPluginRegistration(codexHome, scanRuntimeCodexConfig(mergedConfig, codexSecurityStateDirectory(processEnvironment), persistentCredentialHome ? codexHome : undefined));
594
703
  await writeCodexConfig(join(codexHome, "config.toml"), codexConfig);
595
704
  const configPath = join(bootstrapWorkspace, "config-preflight.toml");
596
705
  await writeCodexConfig(configPath, scanPreflightCodexConfig(mergedConfig));
@@ -602,6 +711,7 @@ export class CodexSecurity {
602
711
  const credentialsAvailable = await initialCredentialsAvailable(processEnvironment, ambientHome, codexHome);
603
712
  return {
604
713
  codexHome,
714
+ persistentCredentialHome,
605
715
  bootstrapWorkspace,
606
716
  configPath,
607
717
  plugin,
@@ -615,7 +725,7 @@ export class CodexSecurity {
615
725
  };
616
726
  }
617
727
  catch (error) {
618
- const cleanupResults = await Promise.allSettled([bootstrapWorkspace, codexHome]
728
+ const cleanupResults = await Promise.allSettled([bootstrapWorkspace, persistentCredentialHome ? undefined : codexHome]
619
729
  .filter((path) => path !== undefined)
620
730
  .map((path) => cleanupSdkDirectory(path)));
621
731
  const cleanupFailures = cleanupResults.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
@@ -633,6 +743,11 @@ export class CodexSecurity {
633
743
  export async function initialCredentialsAvailable(environment, ambientHome, isolatedHome, importer = importAmbientAuth) {
634
744
  if (environmentApiKey(environment) !== null)
635
745
  return false;
746
+ if (!(await codexSecurityCredentialAllowsAmbientImport(isolatedHome))) {
747
+ return false;
748
+ }
749
+ if (await codexSecurityHasStoredFileCredentials(isolatedHome))
750
+ return true;
636
751
  return await importer(ambientHome, isolatedHome);
637
752
  }
638
753
  async function removeTargetPathsFile(path) {
@@ -720,7 +835,7 @@ export async function runScanEvents(options) {
720
835
  finalResponse,
721
836
  usage,
722
837
  ...(options.model === undefined ? {} : { model: options.model }),
723
- }, threadId, options.scanDir, options.pluginRoot, options.expectation, options.signal);
838
+ }, threadId, options.scanDir, options.pluginRoot, options.expectation, options.signal, options.workbenchValidated);
724
839
  if (options.signal.aborted) {
725
840
  throw new ScanInterruptedError(`Codex Security scan was interrupted; partial output remains at ${options.scanDir}.`, options.scanDir);
726
841
  }
@@ -758,6 +873,9 @@ async function scanPrompt(pluginRoot, target, mode, hasConfigPath = false, hasKn
758
873
  'Use exactly "$CODEX_SECURITY_SCAN_ID" as the scan ID in the manifest, findings, and coverage.',
759
874
  'Use exactly "$CODEX_SECURITY_TARGET_ID" as scan.target.targetId; do not derive a different target ID.',
760
875
  'Use exactly "$CODEX_SECURITY_TARGET_DISPLAY_NAME" as scan.target.displayName; do not infer a display name from the Git remote.',
876
+ 'Use exactly "$CODEX_SECURITY_TARGET_KIND" as scan.target.kind; do not infer the target kind from the checkout.',
877
+ 'When "$CODEX_SECURITY_TARGET_REVISION" is set, use its exact value as scan.target.revision.',
878
+ 'When "$CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST" is set, use its exact value as scan.target.snapshotDigest. For git_revision, omit scan.target.snapshotDigest.',
761
879
  'Use exactly "codex-security-plugin" as scan.producer.name.',
762
880
  ...(hasConfigPath
763
881
  ? [
@@ -822,7 +940,7 @@ function validateScanCostLimit(maxCostUsd, model) {
822
940
  throw new CodexSecurityError(`A scan cost limit is not available for the configured model: ${model}.`);
823
941
  }
824
942
  }
825
- async function collectResult(turnResult, threadId, scanDir, pluginRoot, expectation, signal) {
943
+ async function collectResult(turnResult, threadId, scanDir, pluginRoot, expectation, signal, workbenchValidated = false) {
826
944
  const required = [
827
945
  "scan-manifest.json",
828
946
  "findings.json",
@@ -846,6 +964,7 @@ async function collectResult(turnResult, threadId, scanDir, pluginRoot, expectat
846
964
  const { manifest, findings, coverage } = await loadContract(scanDir, {
847
965
  pluginRoot,
848
966
  expectation,
967
+ workbenchValidated,
849
968
  signal,
850
969
  });
851
970
  let sarifPath = null;
@@ -960,7 +1079,7 @@ export function classifyConnectionFailure(error) {
960
1079
  return "timeout";
961
1080
  return "unknown";
962
1081
  }
963
- export function scanRuntimeCodexConfig(config, stateDirectory) {
1082
+ export function scanRuntimeCodexConfig(config, stateDirectory, protectedCredentialHome) {
964
1083
  const hardened = structuredClone(config);
965
1084
  delete hardened["sandbox_mode"];
966
1085
  const configuredPermissions = isRecord(hardened["permissions"])
@@ -977,6 +1096,9 @@ export function scanRuntimeCodexConfig(config, stateDirectory) {
977
1096
  ":root": "read",
978
1097
  ":workspace_roots": "write",
979
1098
  [stateDirectory]: "write",
1099
+ ...(protectedCredentialHome === undefined
1100
+ ? {}
1101
+ : { [protectedCredentialHome]: "read" }),
980
1102
  },
981
1103
  },
982
1104
  },