Repository navigation
Expand file tree
/
Copy pathapi.ts
More file actions
6366 lines (6232 loc) · 218 KB
/
Copy pathapi.ts
File metadata and controls
6366 lines (6232 loc) · 218 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference lib="esnext.disposable" preserve="true" />
import { workbenchArgs } from "./workbench-arguments.js";
import { isSafeNonNegativeInteger as safeInteger } from "./value.js";
import {
ScanExecutionError,
ScanExecutionResultSchema,
type ScanExecutor,
type ScanExecutionEvent,
type ScanExecutionRequest,
} from "./scan-executor.js";
import {
chmod,
lstat,
mkdir,
mkdtemp,
readFile,
readdir,
realpath,
rm,
stat,
writeFile,
} from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { tmpdir } from "node:os";
import { isDeepStrictEqual } from "node:util";
import { pathToFileURL } from "node:url";
import {
basename,
dirname,
isAbsolute,
join,
posix,
relative,
resolve,
sep,
win32,
} from "node:path";
import {
Codex,
type CodexOptions,
type ModelReasoningEffort,
type ThreadOptions,
type TurnOptions,
} from "@openai/codex-sdk";
import { z } from "zod";
import { readThreatModelPath } from "./artifact-export.js";
import { scanSkillConfig } from "./scan-skill-paths.js";
import { isRecord } from "./record.js";
import {
STATIC_VERIFICATION_INSTRUCTIONS,
VerificationModeSchema,
} from "./remediation.js";
import {
createProfileCodex,
createProviderProfile,
providerPreflightCommand,
type ProviderProfile,
} from "./provider-profile.js";
import {
CODEX_AUTH_CONFIG_KEYS,
NO_CREDENTIALS_MESSAGE,
accountStatus,
configuredCodexHome,
CodexLoginHandle,
loginApiKey as persistApiKey,
logout as codexLogout,
withoutOpenAiApiKeys,
type AccountStatus,
} from "./auth.js";
import {
jsonForPrompt,
pluginPythonCommand,
shellEnvironmentReference,
} from "./codex-prompt.js";
import {
DEFAULT_CODEX_CONFIG,
EXTERNAL_CODEX_PROVIDERS,
inlineToml,
isExternalModelProvider,
hasCommandAuth,
mergedCodexConfig,
resolveCodexProfile,
resolveCommandAuthConfig,
scanApprovalPolicy,
scanCyberAccessConfig,
scanModelConfiguration,
scanModelProvider,
structuredCodexConfig,
type CodexSecurityConfig,
type JsonObject,
type ScanModelConfiguration,
writeCodexConfig,
} from "./config.js";
import {
estimateScanCost,
ScanCostTracker,
type ScanCost,
type ScanSessionEvent,
type ScanUsageObservation,
type ScanWorkerEvent,
} from "./cost.js";
import type { ScanTokenUsage } from "./cost-model.js";
import { ScanProgressTracker, type DeepScanProgress } from "./scan-progress.js";
import { findScanSession } from "./scan-logs.js";
import { DIRECT_DEEP_SCAN_CONTROL_USAGE, runDeepScan } from "./deep-scan.js";
import {
deepScanOptions,
resolveDeepScanConfig,
writeDeepScanConfig,
type DeepScanSources,
type ResolvedDeepScanConfig,
} from "./deep-config.js";
import {
DEFAULT_SCAN_AUTH,
DEFAULT_SCAN_MODE,
SCAN_AUTH_MODES,
ScanSettingsSchema,
type DeepScanOptions,
type ScanAuthMode,
type ScanSettings,
type ScanPromptSettings,
} from "./scan-settings.js";
import { resolveScanPrompts } from "./prompt-files.js";
import {
readScanTimeBudgetPolicy,
renderScanTimeBudgetPolicy,
scanTimeBudget,
} from "./scan-time-budget.js";
import { standaloneValidationPrompt } from "./standalone-validation-prompt.js";
export { SCAN_AUTH_MODES } from "./scan-settings.js";
export type { DeepScanOptions, ScanAuthMode } from "./scan-settings.js";
import {
loadContract,
readScanFile,
requireScanFile,
type ScanExpectation,
} from "./contract.js";
import {
runCustomValidation,
writeCustomValidationStatus,
} from "./custom-validation.js";
import {
customDiscoveryPrompt,
customValidationConfig,
} from "./custom-validation-prompt.js";
import {
AuthenticationRequiredError,
CodexSecurityError,
ConfigurationError,
IncompleteScanError,
OutputDirectoryError,
OutputDirectoryNotEmptyError,
errorMessage,
ScanCostLimitExceededError,
ScanInterruptedError,
} from "./errors.js";
import { forwardExternalImportSetting } from "./external-imports-feature.js";
import {
knowledgeBaseProtectedRoots,
prepareKnowledgeBase,
readKnowledgeBaseSnapshot,
type PreparedKnowledgeBase,
type KnowledgeBaseSnapshot,
} from "./knowledge-base.js";
import { scanInputIdentity, saveScanKnowledge } from "./scan-inputs.js";
import {
FindingWorkflow,
scanArtifactDigest,
workflowDigest,
} from "./finding-workflow.js";
import { reviewSqliteHome } from "./deduplication/codex-review.js";
import {
ScanResult,
type RepositoryFinding,
type TurnResultMetadata,
type ScanResultOptions,
} from "./result.js";
import type { SeverityLevel } from "./models.js";
import {
formatSecurityPolicyText,
inspectSecurityPolicySources,
readSecurityPolicySnapshot,
requireUnchangedSecurityPolicy,
resolveSecurityPolicyGuidance,
resolveSecurityPolicyTarget,
runSecurityPolicyStages,
parseSecurityPolicyStageResult,
securityPolicyDiff,
securityPolicyProtectedRoots,
requireSecurityPolicyRepositoryBinding,
securityPolicyStageOutputSchema,
type SecurityPolicyDraft,
type SecurityPolicyOptions,
type SecurityPolicyPreflight,
type SecurityPolicyStage,
type SecurityPolicyStageResult,
type SecurityPolicyTarget,
} from "./security-policy.js";
import { writeMockScanDraft } from "./mock-scan.js";
import { scanActivitiesFromEvent, type ScanActivity } from "./scan-activity.js";
import {
matchCompletedScan,
matchScanFindingsInternal,
} from "./scan-comparison.js";
import {
scanProgressUpdatesFromEvent,
scanPhaseSchema,
workerStatusFromEvent,
type ScanProgress,
type ScanWorkerStatus,
} from "./worker-progress.js";
import { CODEX_SECURITY_THREAD_SOURCES } from "./thread-source.js";
import { codexSecurityRequestContext } from "./request-metadata.js";
import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";
import { bundledCodexSdkEnvironment } from "./codex-sdk-environment.js";
import {
canonicalConfigPath,
acquireCodexSecurityCredentialHomeLock,
withCredentialHomeLock,
bootstrapPlugin,
bundledPluginRoot,
cleanupSdkDirectory,
codexSecurityCredentialAllowsAmbientImport,
codexSecurityCredentialHome,
codexSecurityHasStoredFileCredentials,
codexSecurityStateDirectory,
codexExecutableReadPaths,
createIsolatedHome,
executablePathForSpawn,
expandHome,
importAmbientAuth,
prepareCodexSecurityCredentialHome,
preserveCodexSecurityPluginRegistration,
pluginExecutionEnvironment,
environmentWithGit,
pluginMetadata,
planOutputArchive,
prepareScanArtifactRestorer,
prepareOutputDir,
prepareScanRegistrationOutput,
preparePersistentOutputRoot,
probeCodexSandbox,
requireModelSafeOutputDir,
requireOutputOutsideRepositories,
requireOutputOutsideRepository,
requirePrivateCredentialHome,
preparePolicyOutputDirectory,
resolveCodexCommand,
resolvePluginPath,
resolvePluginPython,
runWorkbench,
setCodexSecurityCredentialLogout,
type CodexCommand,
type PluginInstall,
type ProcessEnvironment,
type ScanArtifactRestorer,
type WorkbenchCommandOptions,
validateOutputDir,
} from "./runtime.js";
import {
enclosingGitWorktreeRoot,
normalizeRepository,
normalizeTarget,
gitMarkerRoot,
repositoryRevision,
resolveRepositoryPath,
type NormalizedTarget,
type ScanMode,
validatedGitEnvironment,
validateCommittedDiffCheckout,
validateMode,
} from "./targets.js";
import {
inspectTrustedExecutable,
isWithin,
type InspectedExecutable,
} from "./trusted-executable.js";
interface CodexThreadLike {
readonly id: string | null;
runStreamed(
input: string,
options: TurnOptions,
): Promise<{ events: AsyncGenerator<ScanEvent> }>;
}
interface ScanEvent {
readonly type: string;
readonly [key: string]: unknown;
}
interface CodexClientLike {
startThread(options: ThreadOptions): CodexThreadLike;
resumeThread?(threadId: string, options: ThreadOptions): CodexThreadLike;
}
interface PreparedRuntime {
codexHome: string;
bootstrapWorkspace?: string;
configPath?: string;
deepScanConfigDirectory?: string;
deepScanConfigPath?: string;
providerProfile?: ProviderProfile;
plugin: PluginInstall;
environment: Record<string, string>;
credentialsAvailable: boolean;
}
interface PreparedSession {
safetyIdentifier?: string;
runtime: PreparedRuntime;
runtimeHome: string;
effectiveConfig: JsonObject;
preflightConfig: JsonObject;
sessionConfig: JsonObject;
modelProvider: unknown;
externalProvider:
| (typeof EXTERNAL_CODEX_PROVIDERS)[keyof typeof EXTERNAL_CODEX_PROVIDERS]
| null;
apiKey: string | null;
scanEnvironment: ProcessEnvironment;
authentication: ScanAuthentication;
approvalPolicy: "never" | "on-request";
python: string;
}
const DEEP_SCAN_CONFIG_PATH_ENVIRONMENT =
"CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH";
export interface ScanOptions extends ScanSettings {
/** @internal Reuse captured knowledge inputs for related operations or resume. */
knowledgeBaseSnapshot?: KnowledgeBaseSnapshot;
/** @internal Resume a CLI Deep Scan with its saved launch recipe. */
resumeScanId?: string;
/** Save synthetic Standard scan results without calling Codex or a model. */
mock?: boolean;
/** Opt into a durable scan -> custom publication -> dedupe workflow. */
workflowId?: string;
/** Stable, privacy-preserving end-user ID for this scan's model requests. */
safetyIdentifier?: string;
archiveExisting?: boolean;
parentScanId?: string;
expectedPluginVersion?: string;
onCost?: (cost: Readonly<ScanCost>, maxCostUsd?: number) => void;
/** Observed tokens, including models without a price estimate. */
onUsage?: (usage: Readonly<ScanTokenUsage>) => void;
/** The last reportable token total's measurement time and latest account limits from this scan's sessions. */
onUsageObservation?: (observation: ScanUsageObservation) => void;
onBudgetApproaching?: (
budget: ScanBudget,
) => number | undefined | Promise<number | undefined>;
onOutputArchived?: (archiveDir: string) => void;
onOutputDirReady?: (scanDir: string) => void;
/** @internal Authoritative registration receipt for CLI scan navigation. */
onScanRegistered?: (scan: {
scanId: string;
scanDir: string;
startedAt?: string;
}) => void;
onAuthentication?: (authentication: ScanAuthentication) => void;
onTrustedAccessStatus?: (status: ScanTrustedAccessStatus) => void;
onScanStarted?: () => void;
onReconnect?: (
attempt: number,
maxAttempts: number,
details?: ScanReconnectDetails,
) => void;
onActivity?: (activity: ScanActivity) => void;
onSessionEvent?: (event: ScanSessionEvent) => void;
onProgress?: (progress: ScanProgress) => void;
onDeepProgress?: (progress: DeepScanProgress) => void;
/** Best-effort, model-reported phase dispatch counts. */
onWorkerStatus?: (status: ScanWorkerStatus) => void;
/**
* Reports each persisted worker session once when discovered during this run.
* Worker numbers match onActivity/onSessionEvent. Includes saved workers on
* resume; observation ends before postScanPrompt. Persistence and polling can
* delay delivery. Does not report failed spawns, phase, or planned counts and
* cannot gate dispatch; use maxCostUsd or signal for cancellation.
*/
onWorkerEvent?: (event: ScanWorkerEvent) => void;
onWarning?: (warning: string, details?: ScanWarningDetails) => void;
onObserverError?: (observer: ScanObserverName, error: unknown) => void;
signal?: AbortSignal;
}
export interface ValidationOptions extends Pick<
ScanOptions,
| "auth"
| "cyberAccessProgram"
| "knowledgeBasePaths"
| "outputDir"
| "safetyIdentifier"
| "signal"
> {
repositoryPath: string;
/** @internal Reuse the scan's captured knowledge inputs during validation. */
knowledgeBaseSnapshot?: KnowledgeBaseSnapshot;
/** Finding text or a JSON-serializable object. Strings are never file paths. */
finding: string | object;
/** @internal Verify the recorded target for CLI post-scan validation. */
scanId?: string;
/** @internal Reuse completed CLI validation assessments on workflow retries. */
workflowId?: string;
}
const validationResponseSchema = z.strictObject({
disposition: z.enum([
"reportable",
"suppressed",
"not_applicable",
"deferred",
]),
report: z.string().trim().min(1),
});
export interface ValidationResult extends z.infer<
typeof validationResponseSchema
> {
outputDir: string;
threadId: string | null;
}
const validationResultSchema = validationResponseSchema.extend({
outputDir: z.string(),
threadId: z.string().nullable(),
});
const cachedValidationSchema = z.object({
assessment: validationResultSchema,
evidenceDigest: z.string(),
});
export interface PatchOptions extends Pick<
ScanOptions,
| "auth"
| "safetyIdentifier"
| "signal"
| "onAuthentication"
| "onActivity"
| "onSessionEvent"
| "onCost"
| "onReconnect"
| "onWarning"
| "onObserverError"
> {
repositoryPath: string;
/** Finding text or a JSON-serializable object. Strings are never file paths. */
finding: string | object;
/** Override the constructor's configured model for this patch operation. */
model?: string;
/** Overrides constructor effort. Support depends on the runtime, model, and provider. */
reasoningEffort?: string;
/** Assess source only with static; omitted or standard retains ordinary verification. */
verificationMode?: z.infer<typeof VerificationModeSchema>;
}
interface PatchResultMetadata {
readonly threadId: string | null;
readonly cost: Readonly<ScanCost> | null;
}
type PatchOutcome = { readonly changedFiles: readonly string[] } & (
| {
readonly status: "verified";
readonly verificationReport: string;
readonly reason?: never;
}
| {
readonly status: "no_change";
readonly verificationReport: string;
readonly reason?: never;
}
| {
readonly status: "blocked";
readonly reason: string;
readonly verificationReport?: string;
}
| {
readonly status: "failed";
readonly reason: string;
readonly verificationReport?: string;
}
);
export type PatchResult = PatchResultMetadata & PatchOutcome;
function isRepositoryRelativePatchPath(value: string): boolean {
const posixPath = posix.normalize(value);
const windowsPath = win32.normalize(value);
return (
!posix.isAbsolute(value) &&
win32.parse(value).root === "" &&
posixPath !== "." &&
posixPath !== ".." &&
!posixPath.startsWith("../") &&
windowsPath !== "." &&
windowsPath !== ".." &&
!windowsPath.startsWith("..\\")
);
}
const patchChangedFilesSchema = z.array(
z.string().min(1).refine(isRepositoryRelativePatchPath),
);
const patchResponseSchema = z
.object({
status: z.enum(["verified", "no_change", "blocked", "failed"]),
changedFiles: patchChangedFilesSchema,
verificationReport: z.string().trim().min(1).nullable(),
reason: z.string().trim().min(1).nullable(),
})
.strict();
const patchOutputSchema = z.toJSONSchema(patchResponseSchema);
delete patchOutputSchema.$schema;
function patchOutcomeFromResponse(
response: z.infer<typeof patchResponseSchema>,
): PatchOutcome {
const { status, changedFiles, verificationReport, reason } = response;
switch (status) {
case "verified":
if (
changedFiles.length === 0 ||
verificationReport === null ||
reason !== null
)
throw new Error("Invalid verified patch result.");
return { status, changedFiles, verificationReport };
case "no_change":
if (
changedFiles.length !== 0 ||
verificationReport === null ||
reason !== null
)
throw new Error("Invalid no-change patch result.");
return { status, changedFiles, verificationReport };
case "blocked":
case "failed":
if (reason === null)
throw new Error("Invalid unsuccessful patch result.");
return {
status,
changedFiles,
reason,
...(verificationReport === null ? {} : { verificationReport }),
};
}
}
export type ScanAuthentication =
| { method: "host"; verified: false }
| { method: "command"; verified: false }
| {
method: "api_key";
source: string;
verified: false;
}
| {
method: "stored_credentials";
credentialType?: "api_key" | "chatgpt";
verified: false;
}
| {
method: "aws_credentials";
source:
| "AWS_BEARER_TOKEN_BEDROCK"
| "AWS_ACCESS_KEY_ID"
| "AWS_PROFILE"
| "AWS_WEB_IDENTITY_TOKEN_FILE"
| "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"
| "AWS_CONTAINER_CREDENTIALS_FULL_URI"
| "default_credential_chain";
verified: false;
};
export type ScanTrustedAccessStatus = "granted" | "not_granted" | "unknown";
export interface ScanReconnectDetails {
reason: "rate_limit" | "network" | "authentication" | "authorization";
retryAfterSeconds?: number;
}
export interface ScanWarningDetails {
kind: "target_changed";
}
export interface ScanBudget {
maxCostUsd: number;
cost: Readonly<ScanCost>;
signal: AbortSignal;
}
type ScanObserverName =
| "onAuthentication"
| "onCost"
| "onUsage"
| "onUsageObservation"
| "onOutputArchived"
| "onOutputDirReady"
| "onScanRegistered"
| "onScanStarted"
| "onTrustedAccessStatus"
| "onReconnect"
| "onActivity"
| "onSessionEvent"
| "onProgress"
| "onDeepProgress"
| "onWorkerStatus"
| "onWorkerEvent"
| "onStage"
| "onWarning";
export interface ScanPreflight extends DeepScanOptions, ScanModelConfiguration {
maxTimeMinutes?: number;
repository: string;
target: NormalizedTarget;
mode: ScanMode;
knowledgeBasePaths?: string[];
outputDir: string | null;
archiveDir?: string;
authentication: ScanAuthentication;
modelProvider?: string;
maxCostUsd?: number;
deepScanSources?: DeepScanSources;
}
interface LocalScanInputs extends Omit<
ScanPreflight,
"model" | "reasoningEffort" | "authentication"
> {
protectedRoot: string;
protectedRoots: readonly string[];
stateDirectory: string;
deepScanConfiguration?: ResolvedDeepScanConfig;
prompts: ScanPromptSettings;
}
export interface CodexSecurityMetadata {
sdk: "@openai/codex-sdk";
sdkVersion: string;
executable: "@openai/codex";
executableVersion: string;
}
export type CodexSecuritySurface = "cli" | "sdk";
interface CodexSecurityRuntimeOptions {
surface: CodexSecuritySurface;
}
interface ClientDependencies {
/** Explicit hosted execution; never falls back to createCodex. */
hostedScan?: {
executor: ScanExecutor;
context: Pick<
ScanExecutionRequest,
"repository" | "revision" | "scope" | "identity"
>;
onEvent(event: ScanExecutionEvent): void;
};
now?: () => number;
createCodex(
options: CodexOptions & { nativeProfile?: string },
): CodexClientLike | Promise<CodexClientLike>;
environment: ProcessEnvironment;
prepareRuntime?: (
config: Readonly<CodexSecurityConfig>,
signal?: AbortSignal,
) => Promise<PreparedRuntime>;
resolvePluginPython?: typeof resolvePluginPython;
prepareOutputDir?: typeof prepareOutputDir;
preparePolicyOutputDirectory?: typeof preparePolicyOutputDirectory;
prepareScanArtifactRestorer?: typeof prepareScanArtifactRestorer;
repositoryRevision?: typeof repositoryRevision;
resolveCodexCommand?: () => CodexCommand;
probeCodexSandbox?: typeof probeCodexSandbox;
runWorkbench?: typeof runWorkbench;
matchFindings?: typeof matchScanFindingsInternal;
runDeepScan?: typeof runDeepScan;
canRunDirectDeepScan?: () => boolean;
}
/** @internal */
export const DEFAULT_DEPENDENCIES: ClientDependencies = {
createCodex: ({ nativeProfile, ...options }) =>
nativeProfile === undefined
? new Codex(options)
: createProfileCodex(options, nativeProfile),
environment: process.env,
};
const SCAN_PERMISSION_PROFILE = "codex_security_scan";
const VALIDATION_PERMISSION_PROFILE = "codex_security_validation";
const POLICY_PERMISSION_PROFILE = "codex_security_policy";
const SAFETY_IDENTIFIER_ENV = "CODEX_SAFETY_IDENTIFIER";
const PERSONAL_TRUSTED_ACCESS_URL = "https://chatgpt.com/cyber";
const ORGANIZATIONAL_TRUSTED_ACCESS_URL =
"https://openai.com/form/enterprise-trusted-access-for-cyber/";
export class CodexSecurity {
public readonly config: Readonly<CodexSecurityConfig>;
public readonly metadata: CodexSecurityMetadata = {
sdk: "@openai/codex-sdk",
sdkVersion: CODEX_SDK_VERSION,
executable: "@openai/codex",
executableVersion: CODEX_EXECUTABLE_VERSION,
};
readonly #dependencies: ClientDependencies;
readonly #surface: CodexSecuritySurface;
readonly #loginHandles = new Set<CodexLoginHandle>();
readonly #abortController = new AbortController();
#activeOperation: Promise<unknown> | null = null;
#runtime: PreparedRuntime | null = null;
#runtimeCredentialSource: "api_key" | "stored_credentials" | null = null;
#closed = false;
#closePromise: Promise<void> | null = null;
public constructor(config?: CodexSecurityConfig);
/** @internal */
public constructor(
config: CodexSecurityConfig,
dependencies: ClientDependencies | undefined,
runtimeOptions: CodexSecurityRuntimeOptions,
);
public constructor(
config: CodexSecurityConfig = {},
dependencies: ClientDependencies = DEFAULT_DEPENDENCIES,
runtimeOptions: CodexSecurityRuntimeOptions = { surface: "sdk" },
) {
this.config = structuredClone(config);
this.#dependencies = dependencies;
this.#surface = runtimeOptions.surface;
}
public async run(
repository: string,
options: ScanOptions = {},
): Promise<ScanResult> {
// Reject the removed experimental option rather than starting local inference.
if ("hosted" in options)
throw new CodexSecurityError(
"Use runHostedScan with an executor for hosted execution.",
);
return await this.#trackOperation(() =>
options.workflowId === undefined
? this.#run(repository, { ...options })
: this.#runWorkflow(repository, { ...options }, options.workflowId),
);
}
async #runWorkflow(
repository: string,
options: ScanOptions,
workflowId: string,
): Promise<ScanResult> {
this.#requireOpen();
const signal = AbortSignal.any([
this.#abortController.signal,
...(options.signal ? [options.signal] : []),
]);
const local = await this.#prepareLocalInputs(
repository,
{ ...options, outputDir: undefined, archiveExisting: false },
signal,
);
const workflow = new FindingWorkflow(
workflowId,
this.#dependencies.environment,
this.#dependencies.runWorkbench,
this.config.pythonPath,
);
if (options.outputDir !== undefined)
await workflow.protectArtifacts(options.outputDir);
const state = await workflow.bind({
repositoryPath: local.repository,
scanRequestDigest: workflowDigest({
config: this.config,
options: {
...options,
...local.prompts,
target: options.target ?? "repository",
mode: options.mode ?? DEFAULT_SCAN_MODE,
outputDir:
options.outputDir === undefined
? undefined
: resolve(expandHome(options.outputDir)),
workflowId: undefined,
signal: undefined,
auth: undefined,
archiveExisting: undefined,
},
}),
});
type ScanMetadata = Pick<
ScanResultOptions,
| "threadId"
| "turnResult"
| "sarifPath"
| "repositoryFindings"
| "ownerSuggestionsPath"
| "ownerSuggestionsError"
>;
if (state.scanId && state.scanDir) {
await workflow.protectArtifacts(state.scanDir);
let metadata = state.stages.scan.result as ScanMetadata | undefined;
let completed = state.stages.scan.status === "completed";
if (!completed) {
const scan = await workflow.registeredScan(state.scanId);
completed =
(scan["progress"] as JsonObject | undefined)?.["status"] ===
"complete";
if (completed)
metadata ??= {
threadId: (scan["continuationThreadId"] as string) ?? "",
turnResult: { status: "completed" },
};
}
if (completed) {
const contract = await loadContract(state.scanDir, {
pluginRoot: await bundledPluginRoot(),
expectedScanId: state.scanId,
signal,
});
await workflow.bind({ artifactDigest: scanArtifactDigest(contract) });
metadata ??= { threadId: "", turnResult: { status: "completed" } };
await workflow.complete("scan", metadata);
return new ScanResult({
...contract,
scanDir: state.scanDir,
...metadata,
threatModelPath: await readThreatModelPath(state.scanDir, {
pythonPath: this.config.pythonPath,
protectedRoot: local.protectedRoot,
signal,
}),
});
}
}
await workflow.begin("scan");
let metadata: ScanMetadata | undefined;
try {
const result = await this.#run(repository, options, local);
metadata = {
threadId: result.threadId,
turnResult: result.turnResult,
sarifPath: result.sarifPath,
repositoryFindings: result.repositoryFindings,
ownerSuggestionsPath: result.ownerSuggestionsPath,
ownerSuggestionsError: result.ownerSuggestionsError,
};
await workflow.protectArtifacts(result.scanDir);
await workflow.bind({
scanId: result.manifest.scan.id,
scanDir: result.scanDir,
artifactDigest: scanArtifactDigest(result),
});
await workflow.complete("scan", metadata);
return result;
} catch (error) {
await workflow.fail("scan", error, metadata);
throw error;
}
}
public async validate(options: ValidationOptions): Promise<ValidationResult> {
return await this.#trackOperation(() => this.#validate(options));
}
async #validate(options: ValidationOptions): Promise<ValidationResult> {
const signal = AbortSignal.any([
this.#abortController.signal,
...(options.signal === undefined ? [] : [options.signal]),
]);
let outputDir = "";
let knowledgeBase: PreparedKnowledgeBase | undefined;
try {
throwIfAborted(signal);
const finding = standaloneFindingForPrompt(options.finding);
const snapshot = options.knowledgeBasePaths?.length
? (options.knowledgeBaseSnapshot ??
(await readKnowledgeBaseSnapshot(options.knowledgeBasePaths, signal)))
: undefined;
let protectedRoots: string[] | undefined;
if (snapshot !== undefined) {
const repository = await normalizeRepository(
resolveRepositoryPath(options.repositoryPath),
signal,
);
protectedRoots = [
(await enclosingGitWorktreeRoot(repository, signal)) ?? repository,
...(await knowledgeBaseProtectedRoots(snapshot, signal)),
];
}
// Cached validation may already own this output. Regeneration below still
// requires an empty directory through prepareOutputDir.
const inputs = await this.#prepareLocalInputs(
options.repositoryPath,
options,
signal,
protectedRoots,
options.workflowId !== undefined,
);
const temporaryRoot = await realpath(tmpdir());
requireOutputOutsideRepositories(
inputs.protectedRoots,
temporaryRoot,
"temporary",
);
if (snapshot !== undefined) {
knowledgeBase = await prepareKnowledgeBase(snapshot, signal);
}
const session = await this.#prepareSession(
inputs,
options,
signal,
temporaryRoot,
);
const { runtime } = session;
const validationInstructions = await standaloneValidationPrompt(
runtime.plugin.pluginRoot,
);
const git = await inspectTrustedExecutable(
"git",
selectedScanEnvironment(
runtime.environment,
options.auth,
session.modelProvider,
),
[
(await gitMarkerRoot(inputs.repository, signal, "outermost")) ??
inputs.repository,
...(knowledgeBase?.protectedRoots ?? []),
],
);
const workbench = this.#dependencies.runWorkbench ?? runWorkbench;
const workbenchOptions: WorkbenchCommandOptions = {
python: session.python,
pluginRoot: runtime.plugin.pluginRoot,
environment: {
...environmentWithGit(git.environment, git),
CODEX_SECURITY_STATE_DIR: inputs.stateDirectory,
},
signal,
failureMessage: "Could not verify or save the validation assessment",
};
const checkTarget = async (): Promise<void> => {
if (options.scanId === undefined) return;
const context = await workbench(workbenchOptions, [
"get-scan",
"--scan-id",
options.scanId,
"--check-target",
]);
const scan = context["scan"];
if (!isRecord(scan) || scan["targetPath"] !== inputs.repository) {
throw new CodexSecurityError(
"The recorded scan target does not match the validation repository.",
);
}
};
await checkTarget();
const outputSchema = z.toJSONSchema(validationResponseSchema, {
target: "openapi-3.0",
});
let checkpoint:
| {
workflow: FindingWorkflow;
binding: JsonObject;
key: string;
replace: boolean;
}
| undefined;
const privateStatePaths: string[] = [];
const outputRoot =
inputs.outputDir === null
? await preparePersistentOutputRoot(
inputs.stateDirectory,
"validations",
basename(inputs.repository),
)
: temporaryRoot;
const knowledgeBasePath = knowledgeBase?.path;
// Codex resolves file-backed instructions in its validation working directory.
const canCache = async (): Promise<boolean> => {
if (this.config.pluginPath !== undefined) return false;
const configuration = resolveCodexProfile(session.effectiveConfig);
if (typeof configuration["model_instructions_file"] === "string")
return false;
// Codex owns instruction discovery. Leave file-backed native guidance to it.
const fallback = configuration["project_doc_fallback_filenames"];
const names = [
"AGENTS.override.md",
"AGENTS.md",
...(Array.isArray(fallback)
? fallback.filter(
(name): name is string => typeof name === "string",
)
: []),