@openai/codex-security 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +306 -0
  3. package/_bundled_plugin/.app.json +20 -0
  4. package/_bundled_plugin/.codex-plugin/plugin.json +41 -0
  5. package/_bundled_plugin/.mcp.json +20 -0
  6. package/_bundled_plugin/assets/logo.png +0 -0
  7. package/_bundled_plugin/examples/completed-scan/coverage.json +22 -0
  8. package/_bundled_plugin/examples/completed-scan/findings.json +51 -0
  9. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +43 -0
  10. package/_bundled_plugin/mcp/mcp-app.html.br +0 -0
  11. package/_bundled_plugin/mcp/server.mjs +24 -0
  12. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  13. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  14. package/_bundled_plugin/preflight/capability-profiles.toml +179 -0
  15. package/_bundled_plugin/references/config-preflight.md +115 -0
  16. package/_bundled_plugin/references/final-report.md +205 -0
  17. package/_bundled_plugin/references/finding-detail-fields.md +162 -0
  18. package/_bundled_plugin/references/sarif-adapter.md +26 -0
  19. package/_bundled_plugin/references/scan-artifacts.md +116 -0
  20. package/_bundled_plugin/references/scan-contract.md +164 -0
  21. package/_bundled_plugin/references/security-guidance.md +15 -0
  22. package/_bundled_plugin/references/shared-hard-rules.md +15 -0
  23. package/_bundled_plugin/references/static-finding-assessment.md +75 -0
  24. package/_bundled_plugin/schemas/coverage.schema.json +228 -0
  25. package/_bundled_plugin/schemas/findings.schema.json +359 -0
  26. package/_bundled_plugin/schemas/scan-manifest.schema.json +332 -0
  27. package/_bundled_plugin/scripts/config_preflight.py +901 -0
  28. package/_bundled_plugin/scripts/deep_scan_config.py +108 -0
  29. package/_bundled_plugin/scripts/deep_scan_workbench.py +1547 -0
  30. package/_bundled_plugin/scripts/filesystem_identity.py +30 -0
  31. package/_bundled_plugin/scripts/finalize_scan_contract.py +2208 -0
  32. package/_bundled_plugin/scripts/finding_preview.py +270 -0
  33. package/_bundled_plugin/scripts/generate_rank_input.py +1013 -0
  34. package/_bundled_plugin/scripts/normalize_candidates.py +320 -0
  35. package/_bundled_plugin/scripts/rank_preview.py +968 -0
  36. package/_bundled_plugin/scripts/report_projection.py +844 -0
  37. package/_bundled_plugin/scripts/resolve_security_md.py +158 -0
  38. package/_bundled_plugin/scripts/snapshot_sqlite.py +26 -0
  39. package/_bundled_plugin/scripts/validate_report_format.py +138 -0
  40. package/_bundled_plugin/scripts/validate_scan_contract.py +108 -0
  41. package/_bundled_plugin/scripts/validate_tracking_source.py +92 -0
  42. package/_bundled_plugin/scripts/windows_scan_local_files.py +612 -0
  43. package/_bundled_plugin/scripts/workbench/__init__.py +1 -0
  44. package/_bundled_plugin/scripts/workbench/handoff.py +238 -0
  45. package/_bundled_plugin/scripts/workbench_cli.py +325 -0
  46. package/_bundled_plugin/scripts/workbench_constants.py +81 -0
  47. package/_bundled_plugin/scripts/workbench_db.py +3728 -0
  48. package/_bundled_plugin/scripts/workbench_native_indexes.py +242 -0
  49. package/_bundled_plugin/scripts/workbench_progress.py +226 -0
  50. package/_bundled_plugin/scripts/workbench_remediation.py +125 -0
  51. package/_bundled_plugin/scripts/workbench_scan_history.py +829 -0
  52. package/_bundled_plugin/scripts/workbench_scan_start.py +149 -0
  53. package/_bundled_plugin/scripts/workbench_schema.py +714 -0
  54. package/_bundled_plugin/scripts/workbench_source_excerpt.py +99 -0
  55. package/_bundled_plugin/scripts/workbench_target.py +469 -0
  56. package/_bundled_plugin/scripts/workbench_target_state.py +63 -0
  57. package/_bundled_plugin/scripts/workbench_validation.py +294 -0
  58. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +117 -0
  59. package/_bundled_plugin/skills/attack-path-analysis/agents/openai.yaml +4 -0
  60. package/_bundled_plugin/skills/attack-path-analysis/references/attack-path-facts.md +76 -0
  61. package/_bundled_plugin/skills/attack-path-analysis/references/severity-policy.md +153 -0
  62. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +166 -0
  63. package/_bundled_plugin/skills/deep-security-scan/agents/openai.yaml +4 -0
  64. package/_bundled_plugin/skills/define-security-policy/SKILL.md +93 -0
  65. package/_bundled_plugin/skills/define-security-policy/agents/openai.yaml +4 -0
  66. package/_bundled_plugin/skills/finding-discovery/SKILL.md +155 -0
  67. package/_bundled_plugin/skills/finding-discovery/agents/openai.yaml +4 -0
  68. package/_bundled_plugin/skills/fix-finding/SKILL.md +112 -0
  69. package/_bundled_plugin/skills/fix-finding/agents/openai.yaml +4 -0
  70. package/_bundled_plugin/skills/propose-security-hardening/SKILL.md +240 -0
  71. package/_bundled_plugin/skills/propose-security-hardening/agents/openai.yaml +4 -0
  72. package/_bundled_plugin/skills/propose-security-hardening/references/proposal-format.md +424 -0
  73. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +167 -0
  74. package/_bundled_plugin/skills/security-diff-scan/agents/openai.yaml +4 -0
  75. package/_bundled_plugin/skills/security-scan/SKILL.md +42 -0
  76. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +4 -0
  77. package/_bundled_plugin/skills/security-scan/references/repository-wide-scan.md +48 -0
  78. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +85 -0
  79. package/_bundled_plugin/skills/threat-model/SKILL.md +59 -0
  80. package/_bundled_plugin/skills/threat-model/agents/openai.yaml +4 -0
  81. package/_bundled_plugin/skills/threat-model/references/threat-model-guidance.md +48 -0
  82. package/_bundled_plugin/skills/track-findings/SKILL.md +222 -0
  83. package/_bundled_plugin/skills/track-findings/agents/openai.yaml +6 -0
  84. package/_bundled_plugin/skills/track-findings/references/github-security-advisories.md +54 -0
  85. package/_bundled_plugin/skills/track-findings/references/jira.md +77 -0
  86. package/_bundled_plugin/skills/triage-finding/SKILL.md +342 -0
  87. package/_bundled_plugin/skills/triage-finding/agents/openai.yaml +4 -0
  88. package/_bundled_plugin/skills/triage-finding/references/github-rest-intake.md +168 -0
  89. package/_bundled_plugin/skills/triage-finding/references/ticket-intake.md +62 -0
  90. package/_bundled_plugin/skills/triage-finding/references/triage-result-contract.md +108 -0
  91. package/_bundled_plugin/skills/validation/SKILL.md +110 -0
  92. package/_bundled_plugin/skills/validation/agents/openai.yaml +4 -0
  93. package/_bundled_plugin/skills/validation/references/validation-guidance.md +122 -0
  94. package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +263 -0
  95. package/_bundled_plugin/skills/vulnerability-writeup/agents/openai.yaml +4 -0
  96. package/_bundled_plugin/skills/vulnerability-writeup/references/report-format.md +104 -0
  97. package/bin/codex-security.mjs +26 -0
  98. package/dist/api.d.ts +112 -0
  99. package/dist/api.d.ts.map +1 -0
  100. package/dist/api.js +1051 -0
  101. package/dist/api.js.map +1 -0
  102. package/dist/auth.d.ts +29 -0
  103. package/dist/auth.d.ts.map +1 -0
  104. package/dist/auth.js +246 -0
  105. package/dist/auth.js.map +1 -0
  106. package/dist/bulk-scan-discovery.d.ts +35 -0
  107. package/dist/bulk-scan-discovery.d.ts.map +1 -0
  108. package/dist/bulk-scan-discovery.js +217 -0
  109. package/dist/bulk-scan-discovery.js.map +1 -0
  110. package/dist/cli.d.ts +67 -0
  111. package/dist/cli.d.ts.map +1 -0
  112. package/dist/cli.js +2128 -0
  113. package/dist/cli.js.map +1 -0
  114. package/dist/config.d.ts +19 -0
  115. package/dist/config.d.ts.map +1 -0
  116. package/dist/config.js +199 -0
  117. package/dist/config.js.map +1 -0
  118. package/dist/contract.d.ts +21 -0
  119. package/dist/contract.d.ts.map +1 -0
  120. package/dist/contract.js +848 -0
  121. package/dist/contract.js.map +1 -0
  122. package/dist/cost.d.ts +30 -0
  123. package/dist/cost.d.ts.map +1 -0
  124. package/dist/cost.js +280 -0
  125. package/dist/cost.js.map +1 -0
  126. package/dist/errors.d.ts +38 -0
  127. package/dist/errors.d.ts.map +1 -0
  128. package/dist/errors.js +52 -0
  129. package/dist/errors.js.map +1 -0
  130. package/dist/index.d.ts +22 -0
  131. package/dist/index.d.ts.map +1 -0
  132. package/dist/index.js +11 -0
  133. package/dist/index.js.map +1 -0
  134. package/dist/knowledge-base.d.ts +7 -0
  135. package/dist/knowledge-base.d.ts.map +1 -0
  136. package/dist/knowledge-base.js +181 -0
  137. package/dist/knowledge-base.js.map +1 -0
  138. package/dist/models.d.ts +231 -0
  139. package/dist/models.d.ts.map +1 -0
  140. package/dist/models.js +3 -0
  141. package/dist/models.js.map +1 -0
  142. package/dist/multiscan.d.ts +30 -0
  143. package/dist/multiscan.d.ts.map +1 -0
  144. package/dist/multiscan.js +397 -0
  145. package/dist/multiscan.js.map +1 -0
  146. package/dist/result.d.ts +39 -0
  147. package/dist/result.d.ts.map +1 -0
  148. package/dist/result.js +71 -0
  149. package/dist/result.js.map +1 -0
  150. package/dist/runtime.d.ts +69 -0
  151. package/dist/runtime.d.ts.map +1 -0
  152. package/dist/runtime.js +997 -0
  153. package/dist/runtime.js.map +1 -0
  154. package/dist/scan-comparison.d.ts +42 -0
  155. package/dist/scan-comparison.d.ts.map +1 -0
  156. package/dist/scan-comparison.js +153 -0
  157. package/dist/scan-comparison.js.map +1 -0
  158. package/dist/scan-history-renderer.d.ts +13 -0
  159. package/dist/scan-history-renderer.d.ts.map +1 -0
  160. package/dist/scan-history-renderer.js +297 -0
  161. package/dist/scan-history-renderer.js.map +1 -0
  162. package/dist/targets.d.ts +39 -0
  163. package/dist/targets.d.ts.map +1 -0
  164. package/dist/targets.js +295 -0
  165. package/dist/targets.js.map +1 -0
  166. package/dist/trusted-executable.d.ts +6 -0
  167. package/dist/trusted-executable.d.ts.map +1 -0
  168. package/dist/trusted-executable.js +77 -0
  169. package/dist/trusted-executable.js.map +1 -0
  170. package/dist/version.d.ts +6 -0
  171. package/dist/version.d.ts.map +1 -0
  172. package/dist/version.js +42 -0
  173. package/dist/version.js.map +1 -0
  174. package/dist/worker-progress.d.ts +13 -0
  175. package/dist/worker-progress.d.ts.map +1 -0
  176. package/dist/worker-progress.js +113 -0
  177. package/dist/worker-progress.js.map +1 -0
  178. package/package.json +74 -0
@@ -0,0 +1,997 @@
1
+ import { execFile as execFileCallback } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
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";
5
+ import { homedir, tmpdir } from "node:os";
6
+ import { createRequire } from "node:module";
7
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep, } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { promisify } from "node:util";
10
+ import { crc32 } from "node:zlib";
11
+ import extractZip from "extract-zip";
12
+ import { parse } from "smol-toml";
13
+ import { CodexSecurityError, OutputDirectoryError, PluginBootstrapError, PluginPythonUnavailableError, } from "./errors.js";
14
+ import { resolveTrustedExecutable } from "./trusted-executable.js";
15
+ const execFile = promisify(execFileCallback);
16
+ export const MARKETPLACE_NAME = "codex-security-sdk";
17
+ export const PLUGIN_NAME = "codex-security";
18
+ const MAX_ZIP_ENTRIES = 4_096;
19
+ const MAX_ZIP_CENTRAL_DIRECTORY = 16 * 1024 * 1024;
20
+ const MAX_ZIP_ENTRY_SIZE = 128 * 1024 * 1024;
21
+ const MAX_ZIP_EXPANDED_SIZE = 512 * 1024 * 1024;
22
+ const MAX_PLUGIN_MANIFEST_SIZE = 1024 * 1024;
23
+ const MAX_PLUGIN_COPY_ENTRIES = 4_096;
24
+ const MAX_PLUGIN_COPY_FILE_SIZE = 128 * 1024 * 1024;
25
+ const MAX_PLUGIN_COPY_SIZE = 512 * 1024 * 1024;
26
+ const MODEL_UNSAFE_PATH = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u;
27
+ export function codexSecurityStateDirectory(environment = process.env) {
28
+ const environmentValue = (requested) => {
29
+ const exact = environment[requested]?.trim();
30
+ if (exact)
31
+ return exact;
32
+ return Object.entries(environment)
33
+ .find(([name, value]) => name.toUpperCase() === requested && value?.trim())?.[1]
34
+ ?.trim();
35
+ };
36
+ const configured = environmentValue("CODEX_SECURITY_STATE_DIR");
37
+ if (configured !== undefined)
38
+ return resolve(expandHome(configured));
39
+ const codexHome = environmentValue("CODEX_HOME") ?? join(homedir(), ".codex");
40
+ return resolve(expandHome(codexHome), "state", "plugins", "codex-security");
41
+ }
42
+ export async function preparePersistentScanRoot(stateDirectory, repositoryName) {
43
+ const root = join(stateDirectory, "scans", safePrefix(repositoryName));
44
+ await mkdir(root, { recursive: true, mode: 0o700 });
45
+ return await realpath(root);
46
+ }
47
+ export async function runWorkbench(options, args) {
48
+ let stdout;
49
+ try {
50
+ ({ stdout } = await execFile(options.python, [
51
+ "-I",
52
+ "-B",
53
+ join(options.pluginRoot, "scripts", "workbench_db.py"),
54
+ ...args,
55
+ ], {
56
+ env: Object.fromEntries(Object.entries(options.environment).filter(([name]) => name.toUpperCase() !== "OPENAI_API_KEY" &&
57
+ name.toUpperCase() !== "CODEX_API_KEY")),
58
+ encoding: "utf8",
59
+ maxBuffer: 4 * 1024 * 1024,
60
+ windowsHide: true,
61
+ signal: options.signal,
62
+ }));
63
+ }
64
+ catch (error) {
65
+ if (options.signal?.aborted)
66
+ throw error;
67
+ throw new CodexSecurityError(`${options.failureMessage ?? "Could not run the Codex Security workbench"}: ${processErrorDetail(error)}`, { cause: error });
68
+ }
69
+ let result;
70
+ try {
71
+ result = JSON.parse(stdout);
72
+ }
73
+ catch (error) {
74
+ throw new CodexSecurityError("The Codex Security workbench returned invalid JSON.", { cause: error });
75
+ }
76
+ if (!isRecord(result)) {
77
+ throw new CodexSecurityError("The Codex Security workbench returned an invalid response.");
78
+ }
79
+ return result;
80
+ }
81
+ export function bundledPluginCandidates(moduleDirectory) {
82
+ const packageCandidates = [
83
+ resolve(moduleDirectory, "_bundled_plugin"),
84
+ resolve(moduleDirectory, "../_bundled_plugin"),
85
+ ];
86
+ return basename(moduleDirectory) === "src"
87
+ ? [
88
+ resolve(moduleDirectory, "../../../plugins/codex-security"),
89
+ ...packageCandidates,
90
+ ]
91
+ : packageCandidates;
92
+ }
93
+ export async function bundledPluginRoot() {
94
+ const moduleDirectory = dirname(fileURLToPath(import.meta.url));
95
+ for (const candidate of bundledPluginCandidates(moduleDirectory)) {
96
+ if (await hasPluginManifest(candidate)) {
97
+ return await realpath(candidate);
98
+ }
99
+ }
100
+ throw new PluginBootstrapError("The bundled Codex Security plugin is missing.");
101
+ }
102
+ export async function validateOutputDir(outputDirectory, archiveExisting = false) {
103
+ if (outputDirectory === undefined) {
104
+ return null;
105
+ }
106
+ requireModelSafeOutputDir(outputDirectory);
107
+ const path = resolve(expandHome(outputDirectory));
108
+ try {
109
+ const metadata = await lstat(path).catch((error) => {
110
+ if (nodeErrorCode(error) === "ENOENT")
111
+ return null;
112
+ throw error;
113
+ });
114
+ if (metadata !== null) {
115
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
116
+ throw new OutputDirectoryError(`Scan output is not a directory: ${path}`);
117
+ }
118
+ if (!archiveExisting && (await readdir(path)).length !== 0) {
119
+ throw new OutputDirectoryError(`Scan output directory is not empty: ${path}. To keep the existing results and start a new scan, add --archive-existing.`);
120
+ }
121
+ requirePrivateOutputDirectory(metadata, path);
122
+ const canonical = await realpath(path);
123
+ requireModelSafeOutputDir(canonical);
124
+ return canonical;
125
+ }
126
+ let parent = dirname(path);
127
+ while (true) {
128
+ try {
129
+ if ((await stat(parent)).isDirectory()) {
130
+ const canonical = resolve(await realpath(parent), relative(parent, path));
131
+ requireModelSafeOutputDir(canonical);
132
+ return canonical;
133
+ }
134
+ break;
135
+ }
136
+ catch (error) {
137
+ if (nodeErrorCode(error) !== "ENOENT")
138
+ throw error;
139
+ const next = dirname(parent);
140
+ if (next === parent)
141
+ break;
142
+ parent = next;
143
+ }
144
+ }
145
+ throw new OutputDirectoryError(`Unable to create scan output directory: ${path}`);
146
+ }
147
+ catch (error) {
148
+ if (error instanceof OutputDirectoryError)
149
+ throw error;
150
+ throw new OutputDirectoryError(`Unable to inspect scan output directory: ${outputDirectory}`, { cause: error });
151
+ }
152
+ }
153
+ export async function planOutputArchive(outputDirectory) {
154
+ if (outputDirectory === null)
155
+ return null;
156
+ const entries = await readdir(outputDirectory).catch((error) => {
157
+ if (nodeErrorCode(error) === "ENOENT")
158
+ return null;
159
+ throw error;
160
+ });
161
+ if (entries === null || entries.length === 0)
162
+ return null;
163
+ const timestamp = new Date()
164
+ .toISOString()
165
+ .replaceAll(/[-:]/g, "")
166
+ .replace(/\.\d{3}Z$/, "");
167
+ return `${outputDirectory}.previous-${timestamp}-${randomUUID().slice(0, 8)}`;
168
+ }
169
+ export function requireModelSafeOutputDir(path) {
170
+ if (MODEL_UNSAFE_PATH.test(path)) {
171
+ throw new OutputDirectoryError("Scan output directory must not contain control or line-separator characters.");
172
+ }
173
+ }
174
+ export async function prepareOutputDir(outputDirectory, repositoryName, temporaryRoot = tmpdir(), validateLocation, archiveExisting = false, onOutputArchived) {
175
+ if (outputDirectory === undefined) {
176
+ requireModelSafeOutputDir(temporaryRoot);
177
+ requireModelSafeOutputDir(await realpath(temporaryRoot));
178
+ }
179
+ const path = await validateOutputDir(outputDirectory, archiveExisting);
180
+ validateLocation?.(path ?? (await realpath(temporaryRoot)));
181
+ if (path === null) {
182
+ const created = await mkdtemp(join(temporaryRoot, `codex-security-${safePrefix(repositoryName)}-`));
183
+ if ((process.umask() & 0o700) !== 0)
184
+ await chmod(created, 0o700);
185
+ try {
186
+ return await validatePreparedOutputDir(created, validateLocation);
187
+ }
188
+ catch (error) {
189
+ await rmdir(created).catch(() => undefined);
190
+ throw error;
191
+ }
192
+ }
193
+ let createdRoot;
194
+ try {
195
+ let existing = await lstat(path).catch((error) => {
196
+ if (nodeErrorCode(error) === "ENOENT")
197
+ return null;
198
+ throw error;
199
+ });
200
+ if (existing !== null && archiveExisting) {
201
+ const archiveDir = await planOutputArchive(path);
202
+ if (archiveDir !== null) {
203
+ await rename(path, archiveDir);
204
+ onOutputArchived?.(archiveDir);
205
+ existing = null;
206
+ }
207
+ }
208
+ if (existing === null) {
209
+ createdRoot = await mkdir(path, { recursive: true, mode: 0o700 });
210
+ if ((process.umask() & 0o700) !== 0)
211
+ await chmod(path, 0o700);
212
+ }
213
+ return await validatePreparedOutputDir(path, validateLocation);
214
+ }
215
+ catch (error) {
216
+ if (createdRoot !== undefined) {
217
+ await removeEmptyDirectories(path, createdRoot);
218
+ }
219
+ if (error instanceof OutputDirectoryError)
220
+ throw error;
221
+ throw new OutputDirectoryError(`Unable to create scan output directory: ${path}`, {
222
+ cause: error,
223
+ });
224
+ }
225
+ }
226
+ export async function validatePreparedOutputDir(path, validateLocation) {
227
+ const metadata = await lstat(path);
228
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
229
+ throw new OutputDirectoryError(`Scan output is not a directory: ${path}`);
230
+ }
231
+ const canonical = await realpath(path);
232
+ requireModelSafeOutputDir(canonical);
233
+ validateLocation?.(canonical);
234
+ const entries = await readdir(canonical);
235
+ if (entries.length !== 0) {
236
+ throw new OutputDirectoryError(`Scan output directory must be empty: ${path}`);
237
+ }
238
+ requirePrivateOutputDirectory(metadata, path);
239
+ return canonical;
240
+ }
241
+ export function requirePrivateOutputDirectory(metadata, path, effectiveUid = process.geteuid?.()) {
242
+ if (process.platform === "win32")
243
+ return;
244
+ if ((metadata.mode & 0o077) !== 0) {
245
+ throw new OutputDirectoryError(`Scan output directory must not be accessible to other users (chmod 700): ${path}`);
246
+ }
247
+ if (effectiveUid !== undefined && metadata.uid !== effectiveUid) {
248
+ throw new OutputDirectoryError(`Scan output directory must be owned by the current user: ${path}`);
249
+ }
250
+ }
251
+ async function removeEmptyDirectories(path, root) {
252
+ let current = path;
253
+ while (true) {
254
+ try {
255
+ await rmdir(current);
256
+ }
257
+ catch {
258
+ return;
259
+ }
260
+ if (current === root)
261
+ return;
262
+ current = dirname(current);
263
+ }
264
+ }
265
+ export async function createIsolatedHome(temporaryRoot = tmpdir(), validateLocation) {
266
+ const path = await mkdtemp(join(temporaryRoot, "openai-codex-security-home-"));
267
+ try {
268
+ if ((process.umask() & 0o700) !== 0)
269
+ await chmod(path, 0o700);
270
+ return await validatePreparedOutputDir(path, validateLocation);
271
+ }
272
+ catch (error) {
273
+ await rmdir(path).catch(() => undefined);
274
+ throw error;
275
+ }
276
+ }
277
+ export async function importAmbientAuth(ambientHome, isolatedHome) {
278
+ const source = join(expandHome(ambientHome), "auth.json");
279
+ let metadata;
280
+ try {
281
+ metadata = await stat(source);
282
+ }
283
+ catch (error) {
284
+ if (nodeErrorCode(error) === "ENOENT")
285
+ return false;
286
+ throw new PluginBootstrapError(`Unable to inspect ambient Codex authentication: ${source}`, {
287
+ cause: error,
288
+ });
289
+ }
290
+ if (!metadata.isFile()) {
291
+ return false;
292
+ }
293
+ await mkdir(isolatedHome, { recursive: true, mode: 0o700 });
294
+ const destination = join(isolatedHome, "auth.json");
295
+ const temporary = join(isolatedHome, `.auth-${process.pid}-${Date.now()}.tmp`);
296
+ try {
297
+ await copyFile(source, temporary, constants.COPYFILE_EXCL);
298
+ await chmod(temporary, 0o600);
299
+ await rename(temporary, destination);
300
+ await chmod(destination, 0o600);
301
+ return true;
302
+ }
303
+ catch (error) {
304
+ await rm(temporary, { force: true }).catch(() => undefined);
305
+ throw new PluginBootstrapError("Unable to copy ambient Codex authentication.", {
306
+ cause: error,
307
+ });
308
+ }
309
+ }
310
+ export async function extractPluginZip(archive, destination, signal) {
311
+ const archivePath = resolve(expandHome(archive));
312
+ await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
313
+ const staging = await realpath(await mkdtemp(join(dirname(destination), ".codex-security-plugin-")));
314
+ try {
315
+ throwIfSignalAborted(signal);
316
+ await rejectBackslashZipNames(archivePath, signal);
317
+ let expandedSize = 0;
318
+ const paths = new Set();
319
+ const checksums = [];
320
+ await extractZip(archivePath, {
321
+ dir: staging,
322
+ defaultDirMode: 0o700,
323
+ defaultFileMode: 0o600,
324
+ onEntry(entry, archive) {
325
+ throwIfSignalAborted(signal);
326
+ if (archive.entryCount > MAX_ZIP_ENTRIES) {
327
+ throw new PluginBootstrapError(`Plugin ZIP contains too many entries: ${archive.entryCount}.`);
328
+ }
329
+ const path = safeArchivePath(entry.fileName);
330
+ const collisionKey = path.toLowerCase();
331
+ if (paths.has(collisionKey)) {
332
+ throw new PluginBootstrapError(`Plugin ZIP contains a duplicate path: ${entry.fileName}`);
333
+ }
334
+ paths.add(collisionKey);
335
+ if (((entry.externalFileAttributes >>> 16) & 0o170000) === 0o120000) {
336
+ throw new PluginBootstrapError(`Plugin ZIP contains an unsafe path: ${entry.fileName}`);
337
+ }
338
+ if (entry.uncompressedSize > MAX_ZIP_ENTRY_SIZE) {
339
+ throw new PluginBootstrapError(`Plugin ZIP entry exceeds the safety limit: ${entry.fileName}`);
340
+ }
341
+ expandedSize += entry.uncompressedSize;
342
+ if (expandedSize > MAX_ZIP_EXPANDED_SIZE) {
343
+ throw new PluginBootstrapError("Plugin ZIP expanded size exceeds the safety limit.");
344
+ }
345
+ const mode = (entry.externalFileAttributes >>> 16) & 0o170000;
346
+ const directory = entry.fileName.endsWith("/") ||
347
+ mode === 0o040000 ||
348
+ (entry.versionMadeBy >>> 8 === 0 &&
349
+ entry.externalFileAttributes === 16);
350
+ if (!directory) {
351
+ checksums.push({ path, checksum: entry.crc32 >>> 0 });
352
+ }
353
+ },
354
+ });
355
+ for (const { path, checksum } of checksums) {
356
+ throwIfSignalAborted(signal);
357
+ const bytes = await readFile(join(staging, ...path.split("/")));
358
+ if (crc32(bytes) !== checksum) {
359
+ throw new PluginBootstrapError(`Plugin ZIP entry failed CRC-32 validation: ${path}`);
360
+ }
361
+ }
362
+ const pluginRoot = await discoverPluginRoot(staging);
363
+ throwIfSignalAborted(signal);
364
+ const relativeRoot = relative(staging, pluginRoot);
365
+ await rename(staging, destination);
366
+ return await validatePluginRoot(join(destination, relativeRoot));
367
+ }
368
+ catch (error) {
369
+ await rm(staging, { recursive: true, force: true }).catch(() => undefined);
370
+ throwIfSignalAborted(signal);
371
+ if (error instanceof PluginBootstrapError)
372
+ throw error;
373
+ throw new PluginBootstrapError(`Invalid plugin ZIP: ${archivePath}`, {
374
+ cause: error,
375
+ });
376
+ }
377
+ }
378
+ async function rejectBackslashZipNames(path, signal) {
379
+ const handle = await open(path, "r");
380
+ try {
381
+ const metadata = await handle.stat();
382
+ if (!metadata.isFile() || metadata.size < 22) {
383
+ throw new Error("missing end of central directory");
384
+ }
385
+ const tailSize = Math.min(metadata.size, 65_557);
386
+ const tail = await readExactly(handle, tailSize, metadata.size - tailSize, signal);
387
+ let end = tail.byteLength - 22;
388
+ while (end >= 0 &&
389
+ (tail.readUInt32LE(end) !== 0x06054b50 ||
390
+ end + 22 + tail.readUInt16LE(end + 20) !== tail.byteLength)) {
391
+ end -= 1;
392
+ }
393
+ if (end < 0)
394
+ throw new Error("missing end of central directory");
395
+ const entries = tail.readUInt16LE(end + 10);
396
+ const centralSize = tail.readUInt32LE(end + 12);
397
+ const centralOffset = tail.readUInt32LE(end + 16);
398
+ if (entries === 0xffff ||
399
+ centralSize === 0xffffffff ||
400
+ centralOffset === 0xffffffff) {
401
+ throw new Error("unsupported ZIP64 archive");
402
+ }
403
+ if (entries > MAX_ZIP_ENTRIES) {
404
+ throw new PluginBootstrapError(`Plugin ZIP contains too many entries: ${entries}.`);
405
+ }
406
+ if (centralSize > MAX_ZIP_CENTRAL_DIRECTORY) {
407
+ throw new PluginBootstrapError("Plugin ZIP central directory exceeds the safety limit.");
408
+ }
409
+ const endOffset = metadata.size - tailSize + end;
410
+ if (centralOffset + centralSize > endOffset) {
411
+ throw new Error("invalid central directory bounds");
412
+ }
413
+ const central = await readExactly(handle, centralSize, centralOffset, signal);
414
+ let offset = 0;
415
+ for (let index = 0; index < entries; index += 1) {
416
+ if (offset + 46 > central.byteLength ||
417
+ central.readUInt32LE(offset) !== 0x02014b50) {
418
+ throw new Error("invalid central directory");
419
+ }
420
+ const nameLength = central.readUInt16LE(offset + 28);
421
+ const extraLength = central.readUInt16LE(offset + 30);
422
+ const commentLength = central.readUInt16LE(offset + 32);
423
+ const nameStart = offset + 46;
424
+ const nameEnd = nameStart + nameLength;
425
+ if (nameEnd > central.byteLength) {
426
+ throw new Error("invalid central directory name");
427
+ }
428
+ if (central.subarray(nameStart, nameEnd).includes(0x5c)) {
429
+ throw new PluginBootstrapError("Plugin ZIP contains a backslash-qualified path.");
430
+ }
431
+ offset = nameEnd + extraLength + commentLength;
432
+ }
433
+ if (offset !== central.byteLength) {
434
+ throw new Error("invalid central directory size");
435
+ }
436
+ }
437
+ finally {
438
+ await handle.close();
439
+ }
440
+ }
441
+ export async function resolvePluginPath(pluginPath, workspace, signal) {
442
+ if (pluginPath === undefined) {
443
+ return await bundledPluginRoot();
444
+ }
445
+ const path = resolve(expandHome(pluginPath));
446
+ const metadata = await lstat(path).catch(() => null);
447
+ if (metadata?.isFile() && extname(path).toLowerCase() === ".zip") {
448
+ return await extractPluginZip(path, join(workspace, "extracted-plugin"), signal);
449
+ }
450
+ if (metadata?.isDirectory() && !metadata.isSymbolicLink()) {
451
+ throwIfSignalAborted(signal);
452
+ return await validatePluginRoot(path);
453
+ }
454
+ throw new PluginBootstrapError(`Plugin path must be a directory or ZIP: ${path}`);
455
+ }
456
+ export async function createMarketplace(codexHome, pluginRoot, signal) {
457
+ throwIfSignalAborted(signal);
458
+ const root = await realpath(pluginRoot);
459
+ const marketplace = join(codexHome, "sdk-marketplace");
460
+ const pluginDestination = join(marketplace, "plugins", PLUGIN_NAME);
461
+ const projectionContract = join(root, ".internal", "external-promotion", "external-projection-contract.json");
462
+ if (root === (await bundledPluginRoot()) &&
463
+ (await isRegularFile(projectionContract))) {
464
+ await copyExternalPayload(root, pluginDestination);
465
+ }
466
+ else {
467
+ await copyPluginTree(root, pluginDestination, signal);
468
+ }
469
+ throwIfSignalAborted(signal);
470
+ const manifest = {
471
+ name: MARKETPLACE_NAME,
472
+ interface: { displayName: "Codex Security SDK" },
473
+ plugins: [
474
+ {
475
+ name: PLUGIN_NAME,
476
+ source: { source: "local", path: `./plugins/${PLUGIN_NAME}` },
477
+ policy: { installation: "AVAILABLE", authentication: "ON_INSTALL" },
478
+ category: "Security",
479
+ },
480
+ ],
481
+ };
482
+ const manifestPath = join(marketplace, ".agents", "plugins", "marketplace.json");
483
+ await mkdir(dirname(manifestPath), { recursive: true, mode: 0o700 });
484
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, {
485
+ encoding: "utf8",
486
+ flag: "wx",
487
+ mode: 0o600,
488
+ signal,
489
+ });
490
+ throwIfSignalAborted(signal);
491
+ return marketplace;
492
+ }
493
+ export function resolveCodexCommand() {
494
+ const { packageName, targetTriple } = codexPlatformPackage();
495
+ const require = createRequire(import.meta.url);
496
+ const codexPackageJson = require.resolve("@openai/codex/package.json");
497
+ const packageJson = createRequire(codexPackageJson).resolve(`${packageName}/package.json`);
498
+ const command = join(dirname(packageJson), "vendor", targetTriple, "bin", process.platform === "win32" ? "codex.exe" : "codex");
499
+ if (!existsSync(command)) {
500
+ throw new PluginBootstrapError(`The ${packageName} package does not contain the Codex executable for ${targetTriple}.`);
501
+ }
502
+ return { command, prefixArgs: [] };
503
+ }
504
+ export function codexPlatformPackage(platform = process.platform, architecture = process.arch) {
505
+ const key = `${platform}:${architecture}`;
506
+ const target = {
507
+ "android:arm64": [
508
+ "@openai/codex-linux-arm64",
509
+ "aarch64-unknown-linux-musl",
510
+ ],
511
+ "android:x64": ["@openai/codex-linux-x64", "x86_64-unknown-linux-musl"],
512
+ "darwin:arm64": ["@openai/codex-darwin-arm64", "aarch64-apple-darwin"],
513
+ "darwin:x64": ["@openai/codex-darwin-x64", "x86_64-apple-darwin"],
514
+ "linux:arm64": ["@openai/codex-linux-arm64", "aarch64-unknown-linux-musl"],
515
+ "linux:x64": ["@openai/codex-linux-x64", "x86_64-unknown-linux-musl"],
516
+ "win32:arm64": ["@openai/codex-win32-arm64", "aarch64-pc-windows-msvc"],
517
+ "win32:x64": ["@openai/codex-win32-x64", "x86_64-pc-windows-msvc"],
518
+ }[key];
519
+ if (target === undefined) {
520
+ throw new PluginBootstrapError(`Codex does not support this platform: ${platform} (${architecture}).`);
521
+ }
522
+ return { packageName: target[0], targetTriple: target[1] };
523
+ }
524
+ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
525
+ const root = await realpath(pluginRoot);
526
+ const { name, version } = await pluginMetadata(root);
527
+ const marketplace = await createMarketplace(codexHome, root, options.signal);
528
+ const command = options.codexCommand ?? resolveCodexCommand();
529
+ const environment = {
530
+ ...(options.environment ?? process.env),
531
+ CODEX_HOME: codexHome,
532
+ };
533
+ const run = options.runCodex ?? runCodex;
534
+ await run(command, ["plugin", "marketplace", "add", marketplace], environment, options.signal);
535
+ await run(command, ["plugin", "add", `${PLUGIN_NAME}@${MARKETPLACE_NAME}`], environment, options.signal);
536
+ await verifyPluginRegistration(codexHome, marketplace);
537
+ const installedRoot = await findInstalledPlugin(codexHome);
538
+ const installed = await pluginMetadata(installedRoot);
539
+ if (installed.name !== name || installed.version !== version) {
540
+ throw new PluginBootstrapError("Installed Codex Security plugin metadata does not match the selected plugin.");
541
+ }
542
+ return {
543
+ pluginRoot: root,
544
+ marketplaceRoot: marketplace,
545
+ installedRoot,
546
+ marketplaceName: MARKETPLACE_NAME,
547
+ name,
548
+ version,
549
+ };
550
+ }
551
+ export async function pluginMetadata(root) {
552
+ const manifestPath = join(root, ".codex-plugin", "plugin.json");
553
+ let manifest;
554
+ try {
555
+ const expected = await lstat(manifestPath);
556
+ if (!expected.isFile() ||
557
+ expected.isSymbolicLink() ||
558
+ expected.size > MAX_PLUGIN_MANIFEST_SIZE) {
559
+ throw new Error("plugin manifest is not a bounded regular file");
560
+ }
561
+ const input = await open(manifestPath, constants.O_RDONLY |
562
+ (process.platform === "win32"
563
+ ? 0
564
+ : constants.O_NOFOLLOW | constants.O_NONBLOCK));
565
+ try {
566
+ const opened = await input.stat();
567
+ if (!samePluginFile(expected, opened)) {
568
+ throw new Error("plugin manifest changed before reading");
569
+ }
570
+ const bytes = await readExactly(input, expected.size, 0);
571
+ if (!samePluginFile(expected, await input.stat())) {
572
+ throw new Error("plugin manifest changed while reading");
573
+ }
574
+ manifest = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
575
+ }
576
+ finally {
577
+ await input.close();
578
+ }
579
+ }
580
+ catch (error) {
581
+ throw new PluginBootstrapError(`Invalid Codex plugin directory: ${root}`, {
582
+ cause: error,
583
+ });
584
+ }
585
+ if (!isRecord(manifest) || manifest["name"] !== PLUGIN_NAME) {
586
+ throw new PluginBootstrapError("Plugin manifest must have name 'codex-security'.");
587
+ }
588
+ const version = manifest["version"];
589
+ if (typeof version !== "string" || version.trim().length === 0) {
590
+ throw new PluginBootstrapError("Plugin manifest must have a non-empty version.");
591
+ }
592
+ return { name: PLUGIN_NAME, version };
593
+ }
594
+ export async function resolvePluginPython(options = {}) {
595
+ const environment = options.environment ?? process.env;
596
+ const protectedRoot = options.protectedRoot ?? process.cwd();
597
+ if (options.configuredPath !== undefined) {
598
+ return await requirePython(options.configuredPath, "configured plugin Python", environment, protectedRoot, options.signal);
599
+ }
600
+ const inherited = environment["PYTHON"]?.trim();
601
+ if (inherited) {
602
+ return await requirePython(inherited, "PYTHON", environment, protectedRoot, options.signal);
603
+ }
604
+ const home = options.homeDirectory ?? homedir();
605
+ const managedRoots = options.managedRuntimeRoots ?? [
606
+ join(home, ".cache", "codex-runtimes", "codex-primary-runtime"),
607
+ ];
608
+ const relativeCandidates = process.platform === "win32"
609
+ ? [
610
+ join("dependencies", "python", "python.exe"),
611
+ join("dependencies", "python", "python", "python.exe"),
612
+ join("dependencies", "python", "bin", "python.exe"),
613
+ ]
614
+ : [
615
+ join("dependencies", "python", "bin", "python3"),
616
+ join("dependencies", "python", "bin", "python"),
617
+ ];
618
+ for (const root of managedRoots) {
619
+ for (const relativeCandidate of relativeCandidates) {
620
+ const candidate = join(root, relativeCandidate);
621
+ const resolved = await usablePython(candidate, environment, protectedRoot, options.signal);
622
+ if (resolved !== null)
623
+ return resolved;
624
+ }
625
+ }
626
+ for (const candidate of process.platform === "win32"
627
+ ? ["python", "python3"]
628
+ : ["python3", "python"]) {
629
+ const resolved = await usablePython(candidate, environment, protectedRoot, options.signal);
630
+ if (resolved !== null)
631
+ return resolved;
632
+ }
633
+ throw new PluginPythonUnavailableError("The bundled Codex Security plugin requires Python 3.10 or later (Python 3.10 also requires tomli), but no usable interpreter was found. " +
634
+ "Set pythonPath, --python, or PYTHON, install the Codex managed runtime, or add python3/python to PATH.");
635
+ }
636
+ export function pluginExecutionEnvironment(python, environment = process.env) {
637
+ return { ...environment, PYTHON: python };
638
+ }
639
+ export async function cleanupSdkDirectory(path) {
640
+ await rm(path, { recursive: true, force: true });
641
+ }
642
+ async function runCodex(command, args, environment, signal) {
643
+ try {
644
+ const { stdout } = await execFile(command.command, [...command.prefixArgs, ...args], {
645
+ env: environment,
646
+ encoding: "utf8",
647
+ signal,
648
+ });
649
+ return stdout;
650
+ }
651
+ catch (error) {
652
+ const detail = processErrorDetail(error);
653
+ throw new PluginBootstrapError(`Codex plugin bootstrap failed: ${detail}`, {
654
+ cause: error,
655
+ });
656
+ }
657
+ }
658
+ async function findInstalledPlugin(codexHome) {
659
+ const root = join(codexHome, "plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME);
660
+ const candidates = [];
661
+ for (const entry of await readdir(root, { withFileTypes: true }).catch(() => [])) {
662
+ if (entry.isDirectory()) {
663
+ const candidate = join(root, entry.name);
664
+ if (await hasPluginManifest(candidate))
665
+ candidates.push(candidate);
666
+ }
667
+ }
668
+ if (candidates.length !== 1) {
669
+ throw new PluginBootstrapError("Codex plugin install did not produce one installed Codex Security plugin.");
670
+ }
671
+ return await realpath(candidates[0]);
672
+ }
673
+ async function discoverPluginRoot(root) {
674
+ if (await hasPluginManifest(root))
675
+ return await validatePluginRoot(root);
676
+ const children = (await readdir(root, { withFileTypes: true })).filter((entry) => entry.isDirectory());
677
+ if (children.length === 1) {
678
+ const candidate = join(root, children[0].name);
679
+ if (await hasPluginManifest(candidate))
680
+ return await validatePluginRoot(candidate);
681
+ }
682
+ throw new PluginBootstrapError("Plugin ZIP must contain Codex Security at its root or in one top-level directory.");
683
+ }
684
+ async function validatePluginRoot(root) {
685
+ await pluginMetadata(root);
686
+ return await realpath(root);
687
+ }
688
+ async function verifyPluginRegistration(codexHome, marketplace) {
689
+ const configPath = join(codexHome, "config.toml");
690
+ let config;
691
+ try {
692
+ config = parse(await readFile(configPath, "utf8"));
693
+ }
694
+ catch (error) {
695
+ throw new PluginBootstrapError("Codex plugin bootstrap produced an unreadable config.toml.", {
696
+ cause: error,
697
+ });
698
+ }
699
+ const marketplaces = isRecord(config) ? config["marketplaces"] : undefined;
700
+ const plugins = isRecord(config) ? config["plugins"] : undefined;
701
+ const marketplaceConfig = isRecord(marketplaces)
702
+ ? marketplaces[MARKETPLACE_NAME]
703
+ : undefined;
704
+ const pluginConfig = isRecord(plugins)
705
+ ? plugins[`${PLUGIN_NAME}@${MARKETPLACE_NAME}`]
706
+ : undefined;
707
+ if (!isRecord(marketplaceConfig) || !isRecord(pluginConfig)) {
708
+ throw new PluginBootstrapError("Codex plugin bootstrap did not preserve plugin registration.");
709
+ }
710
+ const registeredSource = String(marketplaceConfig["source"] ?? "");
711
+ if (!(await sameFile(registeredSource, marketplace))) {
712
+ throw new PluginBootstrapError("Codex plugin marketplace registration has the wrong source.");
713
+ }
714
+ if (pluginConfig["enabled"] !== true) {
715
+ throw new PluginBootstrapError("Codex Security plugin is not enabled after bootstrap.");
716
+ }
717
+ }
718
+ async function copyPluginTree(source, destination, signal) {
719
+ const pending = [
720
+ { source, destination },
721
+ ];
722
+ const directories = new Map();
723
+ let entries = 0;
724
+ let size = 0;
725
+ await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
726
+ try {
727
+ while (pending.length > 0) {
728
+ throwIfSignalAborted(signal);
729
+ const current = pending.pop();
730
+ await requirePluginAncestors(source, current.source, directories, signal);
731
+ const metadata = await lstat(current.source);
732
+ if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
733
+ throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${current.source}`);
734
+ }
735
+ if (metadata.isSymbolicLink()) {
736
+ throw new PluginBootstrapError(`Plugin contains an unsafe source path: ${current.source}`);
737
+ }
738
+ if (metadata.isDirectory()) {
739
+ const children = await readdir(current.source);
740
+ const afterRead = await lstat(current.source);
741
+ if (!samePluginFile(metadata, afterRead)) {
742
+ throw new PluginBootstrapError(`Plugin directory changed while it was being copied: ${current.source}`);
743
+ }
744
+ directories.set(current.source, afterRead);
745
+ await mkdir(current.destination, { mode: 0o700 });
746
+ for (const child of children) {
747
+ pending.push({
748
+ source: join(current.source, child),
749
+ destination: join(current.destination, child),
750
+ });
751
+ }
752
+ continue;
753
+ }
754
+ if (!metadata.isFile()) {
755
+ throw new PluginBootstrapError(`Plugin contains a non-regular file: ${current.source}`);
756
+ }
757
+ if (metadata.size > MAX_PLUGIN_COPY_FILE_SIZE) {
758
+ throw new PluginBootstrapError(`Plugin source exceeds the per-file safety limit: ${current.source}`);
759
+ }
760
+ size += metadata.size;
761
+ if (size > MAX_PLUGIN_COPY_SIZE) {
762
+ throw new PluginBootstrapError("Plugin source exceeds the copy safety limit.");
763
+ }
764
+ const input = await open(current.source, constants.O_RDONLY |
765
+ (process.platform === "win32"
766
+ ? 0
767
+ : constants.O_NOFOLLOW | constants.O_NONBLOCK));
768
+ let output;
769
+ try {
770
+ if (!samePluginFile(metadata, await input.stat())) {
771
+ throw new PluginBootstrapError(`Plugin source changed before it could be copied: ${current.source}`);
772
+ }
773
+ await requirePluginAncestors(source, current.source, directories, signal);
774
+ const bytes = await readExactly(input, metadata.size, 0, signal);
775
+ if (!samePluginFile(metadata, await input.stat())) {
776
+ throw new PluginBootstrapError(`Plugin source changed while it was being copied: ${current.source}`);
777
+ }
778
+ await requirePluginAncestors(source, current.source, directories, signal);
779
+ output = await open(current.destination, constants.O_WRONLY |
780
+ constants.O_CREAT |
781
+ constants.O_EXCL |
782
+ (process.platform === "win32" ? 0 : constants.O_NOFOLLOW), 0o600);
783
+ await output.writeFile(bytes);
784
+ await output.chmod(metadata.mode & 0o777);
785
+ }
786
+ finally {
787
+ await output?.close();
788
+ await input.close();
789
+ }
790
+ }
791
+ }
792
+ catch (error) {
793
+ await rm(destination, { recursive: true, force: true });
794
+ throw error;
795
+ }
796
+ }
797
+ async function requirePluginAncestors(root, path, directories, signal) {
798
+ const relativePath = relative(root, path);
799
+ if (relativePath === ".." ||
800
+ relativePath.startsWith(`..${sep}`) ||
801
+ isAbsolute(relativePath)) {
802
+ throw new PluginBootstrapError(`Plugin source path escapes its root: ${path}`);
803
+ }
804
+ if (relativePath === "")
805
+ return;
806
+ let ancestor = root;
807
+ const parents = ["", ...relativePath.split(sep).slice(0, -1)];
808
+ for (const component of parents) {
809
+ throwIfSignalAborted(signal);
810
+ if (component !== "")
811
+ ancestor = join(ancestor, component);
812
+ const expected = directories.get(ancestor);
813
+ const actual = await lstat(ancestor);
814
+ if (expected === undefined ||
815
+ actual.isSymbolicLink() ||
816
+ !actual.isDirectory() ||
817
+ !samePluginFile(expected, actual)) {
818
+ throw new PluginBootstrapError(`Plugin source directory changed while it was being copied: ${ancestor}`);
819
+ }
820
+ }
821
+ }
822
+ function samePluginFile(first, second) {
823
+ return (first.dev === second.dev &&
824
+ first.ino === second.ino &&
825
+ first.size === second.size &&
826
+ first.mtimeMs === second.mtimeMs &&
827
+ first.mode === second.mode &&
828
+ first.isFile() === second.isFile() &&
829
+ first.isDirectory() === second.isDirectory());
830
+ }
831
+ async function readExactly(handle, length, position, signal) {
832
+ const buffer = Buffer.alloc(length);
833
+ let offset = 0;
834
+ while (offset < length) {
835
+ throwIfSignalAborted(signal);
836
+ const { bytesRead } = await handle.read(buffer, offset, length - offset, position + offset);
837
+ if (bytesRead === 0)
838
+ throw new Error("unexpected end of plugin file");
839
+ offset += bytesRead;
840
+ }
841
+ return buffer;
842
+ }
843
+ async function copyExternalPayload(source, destination) {
844
+ const contractPath = join(source, ".internal", "external-promotion", "external-projection-contract.json");
845
+ let contract;
846
+ try {
847
+ contract = JSON.parse(await readFile(contractPath, "utf8"));
848
+ }
849
+ catch (error) {
850
+ throw new PluginBootstrapError(`Invalid plugin projection contract: ${contractPath}`, {
851
+ cause: error,
852
+ });
853
+ }
854
+ const shippedExact = isRecord(contract)
855
+ ? contract["shippedExact"]
856
+ : undefined;
857
+ if (!Array.isArray(shippedExact) ||
858
+ !shippedExact.every((value) => typeof value === "string")) {
859
+ throw new PluginBootstrapError("Plugin projection contract must contain shippedExact paths.");
860
+ }
861
+ const paths = [".codex-plugin/plugin.json", ...shippedExact].filter((value) => !value.startsWith("sdk/"));
862
+ for (const path of paths) {
863
+ const normalized = safeArchivePath(path);
864
+ const sourcePath = join(source, ...normalized.split("/"));
865
+ const destinationPath = join(destination, ...normalized.split("/"));
866
+ const metadata = await lstat(sourcePath).catch(() => null);
867
+ if (metadata === null || !metadata.isFile() || metadata.isSymbolicLink()) {
868
+ throw new PluginBootstrapError(`Bundled plugin file is missing or unsafe: ${sourcePath}`);
869
+ }
870
+ await mkdir(dirname(destinationPath), { recursive: true, mode: 0o700 });
871
+ await copyFile(sourcePath, destinationPath, constants.COPYFILE_EXCL);
872
+ }
873
+ }
874
+ function safeArchivePath(value) {
875
+ const parts = value.split("/");
876
+ const normalized = parts
877
+ .filter((part) => part !== "" && part !== ".")
878
+ .join("/");
879
+ if (value.length === 0 ||
880
+ value.startsWith("/") ||
881
+ value.startsWith("//") ||
882
+ /^[A-Za-z]:/.test(value) ||
883
+ parts.includes("..") ||
884
+ value.includes("\\") ||
885
+ value.includes("\0") ||
886
+ parts.some((part) => part.includes(":")) ||
887
+ normalized.length === 0) {
888
+ throw new PluginBootstrapError(`Plugin ZIP contains an unsafe path: ${value}`);
889
+ }
890
+ return normalized;
891
+ }
892
+ async function requirePython(candidate, source, environment, protectedRoot, signal) {
893
+ const resolved = await usablePython(candidate, environment, protectedRoot, signal);
894
+ if (resolved !== null)
895
+ return resolved;
896
+ throw new PluginPythonUnavailableError(`The ${source} interpreter is unavailable or unusable: ${candidate}. ` +
897
+ "The bundled Codex Security plugin requires Python 3.10 or later for scan execution; Python 3.10 also requires tomli.");
898
+ }
899
+ async function usablePython(candidate, environment = process.env, protectedRoot = process.cwd(), signal) {
900
+ const command = await resolveTrustedExecutable(isPythonPathCandidate(candidate) ? expandHome(candidate) : candidate, environment, protectedRoot);
901
+ if (command === null)
902
+ return null;
903
+ try {
904
+ const { stdout } = await execFile(command.executable, [
905
+ "-I",
906
+ "-c",
907
+ "import importlib.util,sys\nif sys.version_info < (3, 10): raise SystemExit(1)\nif sys.version_info < (3, 11) and importlib.util.find_spec('tomli') is None: raise SystemExit(1)\nprint('codex-security-python-ok')",
908
+ ], {
909
+ env: command.environment,
910
+ encoding: "utf8",
911
+ timeout: 5_000,
912
+ windowsHide: true,
913
+ signal,
914
+ });
915
+ return stdout.trim() === "codex-security-python-ok"
916
+ ? command.executable
917
+ : null;
918
+ }
919
+ catch (error) {
920
+ if (signal?.aborted)
921
+ throw error;
922
+ return null;
923
+ }
924
+ }
925
+ export function isPythonPathCandidate(candidate) {
926
+ return (candidate.includes("/") ||
927
+ candidate.includes("\\") ||
928
+ candidate.startsWith("."));
929
+ }
930
+ async function hasPluginManifest(root) {
931
+ return await isRegularFile(join(root, ".codex-plugin", "plugin.json"));
932
+ }
933
+ async function isRegularFile(path) {
934
+ try {
935
+ const metadata = await lstat(path);
936
+ return metadata.isFile() && !metadata.isSymbolicLink();
937
+ }
938
+ catch {
939
+ return false;
940
+ }
941
+ }
942
+ async function sameFile(left, right) {
943
+ try {
944
+ const [leftMetadata, rightMetadata] = await Promise.all([
945
+ stat(left),
946
+ stat(right),
947
+ ]);
948
+ return (leftMetadata.dev === rightMetadata.dev &&
949
+ leftMetadata.ino === rightMetadata.ino);
950
+ }
951
+ catch {
952
+ return false;
953
+ }
954
+ }
955
+ export function expandHome(value) {
956
+ if (value === "~")
957
+ return homedir();
958
+ if (value.startsWith("~/") || value.startsWith("~\\")) {
959
+ return join(homedir(), value.slice(2));
960
+ }
961
+ return value;
962
+ }
963
+ function safePrefix(value) {
964
+ return basename(value).replace(/[^A-Za-z0-9._-]/g, "-") || "repository";
965
+ }
966
+ function processErrorDetail(error) {
967
+ if (isRecord(error)) {
968
+ for (const key of ["stderr", "stdout", "message"]) {
969
+ const value = error[key];
970
+ if (typeof value === "string" && value.trim())
971
+ return value.trim();
972
+ if (value instanceof Uint8Array) {
973
+ const decoded = new TextDecoder().decode(value).trim();
974
+ if (decoded)
975
+ return decoded;
976
+ }
977
+ }
978
+ }
979
+ return String(error) || "unknown error";
980
+ }
981
+ function isRecord(value) {
982
+ return typeof value === "object" && value !== null && !Array.isArray(value);
983
+ }
984
+ function nodeErrorCode(error) {
985
+ return isRecord(error) && typeof error["code"] === "string"
986
+ ? error["code"]
987
+ : undefined;
988
+ }
989
+ function abortReason(signal) {
990
+ return (signal.reason ??
991
+ new DOMException("The operation was aborted.", "AbortError"));
992
+ }
993
+ function throwIfSignalAborted(signal) {
994
+ if (signal?.aborted)
995
+ throw abortReason(signal);
996
+ }
997
+ //# sourceMappingURL=runtime.js.map