@openai/codex-security 0.1.5 → 0.1.6

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 (94) hide show
  1. package/README.md +79 -8
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  3. package/_bundled_plugin/.mcp.json +8 -1
  4. package/_bundled_plugin/mcp/mcp-app.html.br +0 -0
  5. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  6. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  7. package/_bundled_plugin/preflight/capability-profiles.toml +0 -57
  8. package/_bundled_plugin/references/config-preflight.md +1 -1
  9. package/_bundled_plugin/references/final-report.md +15 -7
  10. package/_bundled_plugin/references/scan-artifacts.md +11 -9
  11. package/_bundled_plugin/references/scan-contract.md +3 -1
  12. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +42 -0
  13. package/_bundled_plugin/schemas/definitions/discovery-candidate.schema.json +100 -0
  14. package/_bundled_plugin/schemas/tools/candidate-attack-paths.schema.json +181 -0
  15. package/_bundled_plugin/schemas/tools/candidate-validations.schema.json +166 -0
  16. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +120 -0
  17. package/_bundled_plugin/schemas/tools/discovery-candidates.schema.json +83 -0
  18. package/_bundled_plugin/schemas/tools/review-items.schema.json +80 -0
  19. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +572 -0
  20. package/_bundled_plugin/schemas/tools/worker-threat-model.schema.json +18 -0
  21. package/_bundled_plugin/scripts/deep_scan_config.py +11 -3
  22. package/_bundled_plugin/scripts/deep_scan_workbench.py +153 -133
  23. package/_bundled_plugin/scripts/finalize_scan_contract.py +21 -0
  24. package/_bundled_plugin/scripts/generate_in_scope_files.py +134 -0
  25. package/_bundled_plugin/scripts/workbench_cli.py +33 -1
  26. package/_bundled_plugin/scripts/workbench_db.py +127 -117
  27. package/_bundled_plugin/scripts/workbench_feedback.py +2 -0
  28. package/_bundled_plugin/scripts/workbench_native_indexes.py +5 -49
  29. package/_bundled_plugin/scripts/workbench_progress.py +86 -3
  30. package/_bundled_plugin/scripts/workbench_remediation.py +19 -1
  31. package/_bundled_plugin/scripts/workbench_scan_history.py +7 -1
  32. package/_bundled_plugin/scripts/workbench_scan_start.py +11 -5
  33. package/_bundled_plugin/scripts/workbench_scan_usage.py +557 -0
  34. package/_bundled_plugin/scripts/workbench_schema.py +501 -0
  35. package/_bundled_plugin/scripts/workbench_validation.py +117 -13
  36. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +4 -4
  37. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +34 -28
  38. package/_bundled_plugin/skills/finding-discovery/SKILL.md +1 -1
  39. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +11 -8
  40. package/_bundled_plugin/skills/security-scan/SKILL.md +16 -9
  41. package/_bundled_plugin/skills/security-scan/references/repository-wide-scan.md +26 -14
  42. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +1 -1
  43. package/_bundled_plugin/skills/threat-model/SKILL.md +2 -2
  44. package/_bundled_plugin/skills/validation/SKILL.md +5 -5
  45. package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +145 -227
  46. package/_bundled_plugin/skills/vulnerability-writeup/references/report-format.md +53 -68
  47. package/dist/api.d.ts +29 -7
  48. package/dist/api.d.ts.map +1 -1
  49. package/dist/api.js +323 -47
  50. package/dist/api.js.map +1 -1
  51. package/dist/auth.js +1 -1
  52. package/dist/auth.js.map +1 -1
  53. package/dist/cli.d.ts +3 -2
  54. package/dist/cli.d.ts.map +1 -1
  55. package/dist/cli.js +458 -40
  56. package/dist/cli.js.map +1 -1
  57. package/dist/config.d.ts +28 -0
  58. package/dist/config.d.ts.map +1 -1
  59. package/dist/config.js +39 -2
  60. package/dist/config.js.map +1 -1
  61. package/dist/cost.d.ts +7 -0
  62. package/dist/cost.d.ts.map +1 -1
  63. package/dist/cost.js +345 -17
  64. package/dist/cost.js.map +1 -1
  65. package/dist/index.d.ts +3 -2
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js.map +1 -1
  68. package/dist/multiscan.d.ts +1 -0
  69. package/dist/multiscan.d.ts.map +1 -1
  70. package/dist/multiscan.js +3 -0
  71. package/dist/multiscan.js.map +1 -1
  72. package/dist/runtime.d.ts +16 -0
  73. package/dist/runtime.d.ts.map +1 -1
  74. package/dist/runtime.js +540 -25
  75. package/dist/runtime.js.map +1 -1
  76. package/dist/scan-activity.d.ts +13 -0
  77. package/dist/scan-activity.d.ts.map +1 -0
  78. package/dist/scan-activity.js +319 -0
  79. package/dist/scan-activity.js.map +1 -0
  80. package/dist/scan-dashboard.d.ts +47 -0
  81. package/dist/scan-dashboard.d.ts.map +1 -0
  82. package/dist/scan-dashboard.js +444 -0
  83. package/dist/scan-dashboard.js.map +1 -0
  84. package/dist/scan-history-renderer.d.ts.map +1 -1
  85. package/dist/scan-history-renderer.js +4 -1
  86. package/dist/scan-history-renderer.js.map +1 -1
  87. package/dist/version.d.ts +1 -1
  88. package/dist/version.js +1 -1
  89. package/dist/version.js.map +1 -1
  90. package/dist/worker-progress.d.ts +7 -0
  91. package/dist/worker-progress.d.ts.map +1 -1
  92. package/dist/worker-progress.js +68 -0
  93. package/dist/worker-progress.js.map +1 -1
  94. package/package.json +3 -3
package/dist/runtime.js CHANGED
@@ -1,17 +1,18 @@
1
- import { execFile as execFileCallback } from "node:child_process";
1
+ import { execFile as execFileCallback, spawn } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { constants, existsSync } from "node:fs";
4
4
  import { chmod, copyFile, link, lstat, mkdir, mkdtemp, open, opendir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile, } from "node:fs/promises";
5
5
  import { homedir, tmpdir } from "node:os";
6
6
  import { createRequire } from "node:module";
7
7
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep, } from "node:path";
8
+ import { createInterface } from "node:readline";
8
9
  import { fileURLToPath } from "node:url";
9
10
  import { promisify } from "node:util";
10
11
  import { crc32 } from "node:zlib";
11
12
  import { setTimeout as delay } from "node:timers/promises";
12
13
  import extractZip from "extract-zip";
13
14
  import { parse } from "smol-toml";
14
- import { CodexSecurityError, OutputDirectoryError, PluginBootstrapError, PluginPythonUnavailableError, } from "./errors.js";
15
+ import { CodexSecurityError, OutputDirectoryError, PluginBootstrapError, PluginPythonUnavailableError, redactedErrorMessage, } from "./errors.js";
15
16
  import { resolveTrustedExecutable } from "./trusted-executable.js";
16
17
  const execFile = promisify(execFileCallback);
17
18
  export const MARKETPLACE_NAME = "codex-security-sdk";
@@ -29,6 +30,7 @@ const CREDENTIAL_LOCK_NAME = ".codex-security-scan.lock";
29
30
  const CREDENTIAL_LOGOUT_MARKER = ".codex-security-logged-out";
30
31
  const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;
31
32
  const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;
33
+ const MAX_WINDOWS_CREDENTIAL_ACL_STDERR = 64 * 1024;
32
34
  export function codexSecurityStateDirectory(environment = process.env) {
33
35
  const environmentValue = (requested) => {
34
36
  const exact = environment[requested]?.trim();
@@ -144,38 +146,549 @@ export async function requirePrivateCredentialHome(metadata, path, options = {})
144
146
  await (options.secureWindowsHome ?? secureWindowsCredentialHome)(path);
145
147
  }
146
148
  catch (error) {
147
- throw new OutputDirectoryError(`Unable to create a private Windows credential home: ${path}`, { cause: error });
149
+ const detail = windowsCredentialAclFailure(error);
150
+ throw new OutputDirectoryError(`Unable to create a private Windows credential home: ${path}${detail}`, { cause: error });
148
151
  }
149
152
  }
153
+ function windowsCredentialAclFailure(error) {
154
+ const stderr = typeof error === "object" && error !== null && "stderr" in error
155
+ ? error.stderr
156
+ : undefined;
157
+ const detail = typeof stderr === "string" && stderr.trim() !== ""
158
+ ? stderr
159
+ : error instanceof Error
160
+ ? error.message
161
+ : String(error);
162
+ const sanitized = redactedErrorMessage(detail)
163
+ .replace(/\s+/gu, " ")
164
+ .trim()
165
+ .slice(0, 512);
166
+ return sanitized === "" ? "" : `. ${sanitized}`;
167
+ }
168
+ const WINDOWS_SYSTEM_SID = "S-1-5-18";
169
+ const WINDOWS_ADMINISTRATORS_SID = "S-1-5-32-544";
170
+ const WINDOWS_TRUSTED_INSTALLER_SID = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
171
+ const WINDOWS_LOCAL_SERVICE_SID = "S-1-5-19";
172
+ const WINDOWS_NETWORK_SERVICE_SID = "S-1-5-20";
173
+ const WINDOWS_EVERYONE_SID = "S-1-1-0";
174
+ const WINDOWS_AUTHENTICATED_USERS_SID = "S-1-5-11";
175
+ const WINDOWS_USERS_SID = "S-1-5-32-545";
176
+ const WINDOWS_CREATOR_OWNER_SID = "S-1-3-0";
177
+ const WINDOWS_CREATOR_GROUP_SID = "S-1-3-1";
178
+ const WINDOWS_OWNER_RIGHTS_SID = "S-1-3-4";
179
+ const WINDOWS_ALL_APPLICATION_PACKAGES_SID = "S-1-15-2-1";
180
+ const WINDOWS_PRINCIPAL_ALIASES = {
181
+ SY: WINDOWS_SYSTEM_SID,
182
+ BA: WINDOWS_ADMINISTRATORS_SID,
183
+ LS: WINDOWS_LOCAL_SERVICE_SID,
184
+ NS: WINDOWS_NETWORK_SERVICE_SID,
185
+ WD: WINDOWS_EVERYONE_SID,
186
+ AU: WINDOWS_AUTHENTICATED_USERS_SID,
187
+ BU: WINDOWS_USERS_SID,
188
+ CO: WINDOWS_CREATOR_OWNER_SID,
189
+ CG: WINDOWS_CREATOR_GROUP_SID,
190
+ OW: WINDOWS_OWNER_RIGHTS_SID,
191
+ AC: WINDOWS_ALL_APPLICATION_PACKAGES_SID,
192
+ AN: "S-1-5-7",
193
+ IU: "S-1-5-4",
194
+ NU: "S-1-5-2",
195
+ SU: "S-1-5-6",
196
+ RC: "S-1-5-12",
197
+ ED: "S-1-5-9",
198
+ BG: "S-1-5-32-546",
199
+ PU: "S-1-5-32-547",
200
+ AO: "S-1-5-32-548",
201
+ SO: "S-1-5-32-549",
202
+ PO: "S-1-5-32-550",
203
+ BO: "S-1-5-32-551",
204
+ RE: "S-1-5-32-552",
205
+ RU: "S-1-5-32-554",
206
+ RD: "S-1-5-32-555",
207
+ NO: "S-1-5-32-556",
208
+ MU: "S-1-5-32-558",
209
+ LU: "S-1-5-32-559",
210
+ IS: "S-1-5-32-568",
211
+ CY: "S-1-5-32-569",
212
+ ER: "S-1-5-32-573",
213
+ CD: "S-1-5-32-574",
214
+ RA: "S-1-5-32-575",
215
+ ES: "S-1-5-32-576",
216
+ HA: "S-1-5-32-578",
217
+ AA: "S-1-5-32-579",
218
+ };
219
+ const WINDOWS_SID = /^S-1-(?:\d+-)*\d+$/u;
220
+ const WINDOWS_GUID = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu;
221
+ const WINDOWS_SDDL_SID = "(?:S-1-(?:\\d+-)*\\d+|[A-Z]{2})";
222
+ const WINDOWS_SECURITY_DESCRIPTOR = new RegExp(`^O:(${WINDOWS_SDDL_SID})(?:G:${WINDOWS_SDDL_SID})?D:([A-Z_]*)(.*)$`, "u");
223
+ class UntrustedWindowsCredentialOwnerError extends Error {
224
+ constructor(owner) {
225
+ super(`Windows credential ACL owner is not a trusted principal: ${owner}`);
226
+ }
227
+ }
228
+ class RepairableWindowsCredentialAclError extends Error {
229
+ constructor(cause) {
230
+ super("Windows credential ACL requires repair", { cause });
231
+ }
232
+ }
233
+ /** Inspect a Windows DACL without translating locale-specific account names. */
234
+ export function inspectWindowsCredentialAcl(descriptor, currentUserSid, options = {}) {
235
+ if (!WINDOWS_SID.test(currentUserSid)) {
236
+ throw new Error("Unable to identify the current Windows user SID");
237
+ }
238
+ const match = WINDOWS_SECURITY_DESCRIPTOR.exec(descriptor.trim());
239
+ if (match === null) {
240
+ throw new Error("Windows credential ACL has no owner or DACL");
241
+ }
242
+ const principalAliases = {
243
+ ...WINDOWS_PRINCIPAL_ALIASES,
244
+ ...options.resolvedAliases,
245
+ };
246
+ const trustedPrincipals = new Set([
247
+ currentUserSid,
248
+ WINDOWS_SYSTEM_SID,
249
+ WINDOWS_ADMINISTRATORS_SID,
250
+ principalAliases["LA"] ?? "LA",
251
+ ]);
252
+ if (options.scope === "ancestor") {
253
+ trustedPrincipals.add(WINDOWS_TRUSTED_INSTALLER_SID);
254
+ }
255
+ const normalizePrincipal = (principal) => principalAliases[principal] ?? principal;
256
+ const trustedPrincipal = (principal) => trustedPrincipals.has(principal);
257
+ const owner = normalizePrincipal(match[1]);
258
+ if (!trustedPrincipal(owner)) {
259
+ throw new UntrustedWindowsCredentialOwnerError(owner);
260
+ }
261
+ const flags = match[2];
262
+ if (flags.includes("NO_ACCESS_CONTROL")) {
263
+ throw new Error("Windows credential ACL grants unrestricted access");
264
+ }
265
+ let remaining = match[3];
266
+ let grantsCurrentDirectoryAccess = false;
267
+ let grantsCurrentFileAccess = false;
268
+ let grantsCurrentContainerAccess = false;
269
+ let hasAccessRules = false;
270
+ const untrustedPrincipals = new Set();
271
+ const deniedPrincipals = new Set();
272
+ while (remaining.startsWith("(")) {
273
+ const { rule, rest } = windowsSecurityDescriptorRule(remaining);
274
+ const fields = rule.split(";");
275
+ const callback = ["XA", "XD", "ZA"].includes(fields[0]);
276
+ if ((callback && fields.length < 7) || (!callback && fields.length !== 6)) {
277
+ throw new Error("Windows credential ACL has a malformed access rule");
278
+ }
279
+ const [type, inheritance, rights, objectGuid, inheritObjectGuid, rawPrincipal,] = fields;
280
+ if (!["A", "OA", "D", "OD", "XA", "XD", "ZA"].includes(type)) {
281
+ throw new Error("Windows credential ACL has an unsupported access rule");
282
+ }
283
+ if (rawPrincipal === "" || rights === "") {
284
+ throw new Error("Windows credential ACL has an incomplete access rule");
285
+ }
286
+ const objectRule = type === "OA" || type === "OD" || type === "ZA";
287
+ for (const guid of [objectGuid, inheritObjectGuid]) {
288
+ if (guid !== "" && (!objectRule || !WINDOWS_GUID.test(guid))) {
289
+ throw new Error("Windows credential ACL has a malformed object rule");
290
+ }
291
+ }
292
+ const inheritanceFlags = windowsAceFlags(inheritance);
293
+ hasAccessRules = true;
294
+ const principal = normalizePrincipal(rawPrincipal);
295
+ if (type === "A" || type === "OA" || type === "XA" || type === "ZA") {
296
+ if (!trustedPrincipal(principal)) {
297
+ if (options.scope !== "ancestor" ||
298
+ windowsAceAllowsAncestorReplacement(rights, inheritanceFlags)) {
299
+ untrustedPrincipals.add(principal);
300
+ }
301
+ }
302
+ else if (!callback &&
303
+ objectGuid === "" &&
304
+ inheritObjectGuid === "" &&
305
+ principal === currentUserSid &&
306
+ windowsAceGrantsFullControl(rights)) {
307
+ if (!inheritanceFlags.has("IO")) {
308
+ grantsCurrentDirectoryAccess = true;
309
+ }
310
+ if (inheritanceFlags.has("OI") && !inheritanceFlags.has("NP")) {
311
+ grantsCurrentFileAccess = true;
312
+ }
313
+ if (inheritanceFlags.has("CI") && !inheritanceFlags.has("NP")) {
314
+ grantsCurrentContainerAccess = true;
315
+ }
316
+ }
317
+ }
318
+ else {
319
+ deniedPrincipals.add(principal);
320
+ }
321
+ remaining = rest;
322
+ }
323
+ if (!hasAccessRules || (remaining !== "" && !remaining.startsWith("S:"))) {
324
+ throw new Error("Windows credential ACL has an invalid access-rule list");
325
+ }
326
+ return {
327
+ owner,
328
+ protected: flags.includes("P"),
329
+ grantsCurrentUserAccess: grantsCurrentDirectoryAccess &&
330
+ (options.scope === "file" ||
331
+ (grantsCurrentFileAccess && grantsCurrentContainerAccess)) &&
332
+ deniedPrincipals.size === 0,
333
+ untrustedPrincipals: [...untrustedPrincipals],
334
+ deniedPrincipals: [...deniedPrincipals],
335
+ };
336
+ }
337
+ function windowsSecurityDescriptorRule(value) {
338
+ let depth = 0;
339
+ let quoted = false;
340
+ let escaped = false;
341
+ for (let index = 0; index < value.length; index += 1) {
342
+ const character = value[index];
343
+ if (quoted) {
344
+ if (!escaped && character === '"')
345
+ quoted = false;
346
+ escaped = character === "\\" && !escaped;
347
+ continue;
348
+ }
349
+ if (character === '"') {
350
+ quoted = true;
351
+ }
352
+ else if (character === "(") {
353
+ depth += 1;
354
+ }
355
+ else if (character === ")") {
356
+ depth -= 1;
357
+ if (depth === 0) {
358
+ return { rule: value.slice(1, index), rest: value.slice(index + 1) };
359
+ }
360
+ }
361
+ }
362
+ throw new Error("Windows credential ACL has a malformed rule");
363
+ }
364
+ function windowsAceFlags(value) {
365
+ if (value.length % 2 !== 0) {
366
+ throw new Error("Windows credential ACL has malformed inheritance flags");
367
+ }
368
+ const flags = new Set();
369
+ for (let offset = 0; offset < value.length; offset += 2) {
370
+ const flag = value.slice(offset, offset + 2);
371
+ if (!["OI", "CI", "NP", "IO", "ID"].includes(flag)) {
372
+ throw new Error("Windows credential ACL has unsupported inheritance flags");
373
+ }
374
+ flags.add(flag);
375
+ }
376
+ return flags;
377
+ }
378
+ function windowsAceGrantsFullControl(rights) {
379
+ if (rights === "FA" || rights === "GA")
380
+ return true;
381
+ if (!/^0x[\da-f]+$/iu.test(rights))
382
+ return false;
383
+ const mask = BigInt(rights);
384
+ return (mask & 0x1f01ffn) === 0x1f01ffn || (mask & 0x10000000n) !== 0n;
385
+ }
386
+ function windowsAceAllowsAncestorReplacement(rights, inheritanceFlags) {
387
+ if (inheritanceFlags.has("IO"))
388
+ return false;
389
+ if (/^0x[\da-f]+$/iu.test(rights)) {
390
+ return (BigInt(rights) & 0x100d0040n) !== 0n;
391
+ }
392
+ for (let index = 0; index < rights.length; index += 2) {
393
+ if (["FA", "GA", "FW", "GW", "SD", "WD", "WO", "DC", "DT"].includes(rights.slice(index, index + 2))) {
394
+ return true;
395
+ }
396
+ }
397
+ return false;
398
+ }
399
+ export async function verifyStableWindowsCredentialDescendants(path, inspectDescriptors) {
400
+ for (let attempt = 0; attempt < 3; attempt += 1) {
401
+ let descendants = 0;
402
+ const pending = [path];
403
+ while (pending.length !== 0) {
404
+ const current = pending.pop();
405
+ const directory = await opendir(current);
406
+ for await (const entry of directory) {
407
+ const child = join(current, entry.name);
408
+ const metadata = await lstat(child);
409
+ if (metadata.isSymbolicLink()) {
410
+ throw new Error("Windows credential home contains a symbolic link or junction");
411
+ }
412
+ if (!metadata.isDirectory() && !metadata.isFile()) {
413
+ throw new Error("Windows credential home contains an unsafe entry");
414
+ }
415
+ descendants += 1;
416
+ if (metadata.isDirectory())
417
+ pending.push(child);
418
+ }
419
+ }
420
+ if (descendants === 0)
421
+ return;
422
+ if ((await inspectDescriptors()) === descendants)
423
+ return;
424
+ }
425
+ throw new Error("Windows credential descendants could not be verified");
426
+ }
427
+ export async function streamWindowsCredentialAclDescriptors(command, args, inspectDescriptor, options = {}) {
428
+ const child = spawn(command, [...args], {
429
+ env: options.environment,
430
+ stdio: ["ignore", "pipe", "pipe"],
431
+ windowsHide: true,
432
+ });
433
+ let stderr = "";
434
+ child.stderr.setEncoding("utf8");
435
+ child.stderr.on("data", (chunk) => {
436
+ const remaining = MAX_WINDOWS_CREDENTIAL_ACL_STDERR - stderr.length;
437
+ if (remaining > 0)
438
+ stderr += chunk.slice(0, remaining);
439
+ });
440
+ const completion = new Promise((resolve, reject) => {
441
+ child.once("error", reject);
442
+ child.once("close", (code, signal) => {
443
+ if (code === 0) {
444
+ resolve();
445
+ return;
446
+ }
447
+ const reason = signal === null ? `exit code ${code}` : `signal ${signal}`;
448
+ reject(Object.assign(new Error(`Windows credential ACL inspection failed with ${reason}`), { code, signal, stderr }));
449
+ });
450
+ });
451
+ let descriptors = 0;
452
+ try {
453
+ await Promise.all([
454
+ completion,
455
+ (async () => {
456
+ const lines = createInterface({
457
+ input: child.stdout,
458
+ crlfDelay: Infinity,
459
+ });
460
+ for await (const descriptor of lines) {
461
+ if (descriptor === "")
462
+ continue;
463
+ await inspectDescriptor(descriptor);
464
+ descriptors += 1;
465
+ }
466
+ })(),
467
+ ]);
468
+ }
469
+ catch (error) {
470
+ if (child.exitCode === null && child.signalCode === null)
471
+ child.kill();
472
+ throw error;
473
+ }
474
+ return descriptors;
475
+ }
150
476
  async function secureWindowsCredentialHome(path) {
151
477
  const systemRoot = process.env["SystemRoot"] ?? "C:\\Windows";
152
- const powershell = join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
153
- const script = [
154
- "$ErrorActionPreference = 'Stop'",
155
- "$path = [Environment]::GetEnvironmentVariable('CODEX_SECURITY_CREDENTIAL_ACL_PATH', 'Process')",
156
- "$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()",
157
- "if ($null -eq $identity.User) { throw 'Unable to identify the current Windows user' }",
158
- "$acl = New-Object System.Security.AccessControl.DirectorySecurity",
159
- "$acl.SetAccessRuleProtection($true, $false)",
160
- "$inheritance = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit",
161
- "$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($identity.User, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow)",
162
- "$acl.SetOwner($identity.User)",
163
- "$acl.SetAccessRule($rule)",
164
- "[System.IO.Directory]::SetAccessControl($path, $acl)",
165
- "$verified = [System.IO.Directory]::GetAccessControl($path)",
166
- "if (-not $verified.AreAccessRulesProtected) { throw 'Credential ACL still inherits access rules' }",
167
- "$unexpected = @($verified.Access | Where-Object { $_.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -ne $identity.User.Value })",
168
- "if ($unexpected.Count -ne 0) { throw 'Credential ACL grants access to another identity' }",
169
- ].join("; ");
170
- await execFile(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
478
+ const systemDirectory = join(systemRoot, "System32");
479
+ const powershell = join(systemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe");
480
+ const inheritedEnvironment = Object.fromEntries(Object.entries(process.env).filter(([name]) => name.toUpperCase() !== "PSMODULEPATH"));
481
+ const processOptions = {
171
482
  env: {
172
- ...process.env,
483
+ ...inheritedEnvironment,
173
484
  CODEX_SECURITY_CREDENTIAL_ACL_PATH: path,
485
+ PSModulePath: join(systemDirectory, "WindowsPowerShell", "v1.0", "Modules"),
174
486
  },
175
487
  encoding: "utf8",
176
488
  windowsHide: true,
177
489
  maxBuffer: 1024 * 1024,
178
- });
490
+ };
491
+ const identity = await execFile(join(systemDirectory, "whoami.exe"), ["/user", "/fo", "csv", "/nh"], processOptions);
492
+ const sid = /^"(?:[^"]|"")*","(S-1-(?:\d+-)*\d+)"$/u.exec(identity.stdout.trim())?.[1];
493
+ if (sid === undefined) {
494
+ throw new Error("Unable to identify the current Windows user SID");
495
+ }
496
+ // Signed built-in cmdlets remain available under ConstrainedLanguage;
497
+ // arbitrary .NET constructors, static methods, and SID translation do not.
498
+ const script = [
499
+ "$ErrorActionPreference = 'Stop'",
500
+ "Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl",
501
+ ].join("; ");
502
+ const resolvePrincipalScript = [
503
+ "$ErrorActionPreference = 'Stop'",
504
+ "$descriptor = 'O:' + $env:CODEX_SECURITY_CREDENTIAL_PRINCIPAL + 'G:SYD:(A;;GA;;;SY)'",
505
+ "Microsoft.PowerShell.Utility\\ConvertFrom-SddlString -Sddl $descriptor | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty RawDescriptor | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Owner | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Value",
506
+ ].join("; ");
507
+ const resolvedAliases = {};
508
+ const resolvePrincipal = async (principal) => {
509
+ if (!/^[A-Z]{2}$/u.test(principal) ||
510
+ WINDOWS_PRINCIPAL_ALIASES[principal] !== undefined ||
511
+ resolvedAliases[principal] !== undefined) {
512
+ return;
513
+ }
514
+ const resolved = await execFile(powershell, [
515
+ "-NoLogo",
516
+ "-NoProfile",
517
+ "-NonInteractive",
518
+ "-Command",
519
+ resolvePrincipalScript,
520
+ ], {
521
+ ...processOptions,
522
+ env: {
523
+ ...processOptions.env,
524
+ CODEX_SECURITY_CREDENTIAL_PRINCIPAL: principal,
525
+ },
526
+ });
527
+ const numeric = resolved.stdout.trim();
528
+ if (!WINDOWS_SID.test(numeric)) {
529
+ throw new Error("Windows credential ACL contains an unresolvable identity");
530
+ }
531
+ resolvedAliases[principal] = numeric;
532
+ };
533
+ const resolveDescriptorAliases = async (descriptor) => {
534
+ const header = WINDOWS_SECURITY_DESCRIPTOR.exec(descriptor.trim());
535
+ if (header === null)
536
+ return;
537
+ await resolvePrincipal(header[1]);
538
+ let remaining = header[3];
539
+ while (remaining.startsWith("(")) {
540
+ const { rule, rest } = windowsSecurityDescriptorRule(remaining);
541
+ const principal = rule.split(";")[5];
542
+ if (principal !== undefined)
543
+ await resolvePrincipal(principal);
544
+ remaining = rest;
545
+ }
546
+ };
547
+ const readAcl = async () => {
548
+ const descriptor = await execFile(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], processOptions);
549
+ try {
550
+ await resolveDescriptorAliases(descriptor.stdout);
551
+ return inspectWindowsCredentialAcl(descriptor.stdout, sid, {
552
+ resolvedAliases,
553
+ });
554
+ }
555
+ catch (error) {
556
+ if (error instanceof UntrustedWindowsCredentialOwnerError)
557
+ throw error;
558
+ throw new RepairableWindowsCredentialAclError(error);
559
+ }
560
+ };
561
+ const icacls = join(systemDirectory, "icacls.exe");
562
+ const installTrustedAcl = async (target = path) => {
563
+ await execFile(icacls, [
564
+ target,
565
+ "/inheritance:r",
566
+ "/grant:r",
567
+ `*${sid}:(OI)(CI)F`,
568
+ `*${WINDOWS_SYSTEM_SID}:(OI)(CI)F`,
569
+ `*${WINDOWS_ADMINISTRATORS_SID}:(OI)(CI)F`,
570
+ ], processOptions);
571
+ };
572
+ const ancestorScript = [
573
+ "$ErrorActionPreference = 'Stop'",
574
+ "$path = $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
575
+ "while ($true) { $parent = Microsoft.PowerShell.Management\\Split-Path -Path $path -Parent; if (-not $parent -or $parent -eq $path) { break }; Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $parent | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl; $path = $parent }",
576
+ ].join("; ");
577
+ const ancestorPaths = [];
578
+ for (let ancestor = dirname(path);; ancestor = dirname(ancestor)) {
579
+ ancestorPaths.push(ancestor);
580
+ if (ancestor === dirname(ancestor))
581
+ break;
582
+ }
583
+ const ancestry = await execFile(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", ancestorScript], processOptions);
584
+ const ancestorDescriptors = ancestry.stdout
585
+ .split(/\r?\n/u)
586
+ .filter((descriptor) => descriptor !== "");
587
+ if (ancestorDescriptors.length !== ancestorPaths.length) {
588
+ throw new Error("Windows credential-home ancestry could not be verified");
589
+ }
590
+ for (const descriptor of ancestorDescriptors) {
591
+ await resolveDescriptorAliases(descriptor);
592
+ const ancestor = inspectWindowsCredentialAcl(descriptor, sid, {
593
+ resolvedAliases,
594
+ scope: "ancestor",
595
+ });
596
+ if (ancestor.untrustedPrincipals.length === 0)
597
+ continue;
598
+ throw new Error("Windows credential-home ancestor allows another identity to replace the directory");
599
+ }
600
+ const descendantsArePrivate = async () => {
601
+ const descendantScript = [
602
+ "$ErrorActionPreference = 'Stop'",
603
+ "Microsoft.PowerShell.Management\\Get-ChildItem -LiteralPath $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH -Recurse -Force | Microsoft.PowerShell.Security\\Get-Acl | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl",
604
+ ].join("; ");
605
+ let privateDescendants = true;
606
+ await verifyStableWindowsCredentialDescendants(path, async () => {
607
+ privateDescendants = true;
608
+ return streamWindowsCredentialAclDescriptors(powershell, [
609
+ "-NoLogo",
610
+ "-NoProfile",
611
+ "-NonInteractive",
612
+ "-Command",
613
+ descendantScript,
614
+ ], async (descriptor) => {
615
+ await resolveDescriptorAliases(descriptor);
616
+ const descendant = inspectWindowsCredentialAcl(descriptor, sid, {
617
+ resolvedAliases,
618
+ scope: "file",
619
+ });
620
+ if (!descendant.grantsCurrentUserAccess ||
621
+ descendant.untrustedPrincipals.length !== 0) {
622
+ privateDescendants = false;
623
+ }
624
+ }, { environment: processOptions.env });
625
+ });
626
+ return privateDescendants;
627
+ };
628
+ let existing;
629
+ for (let attempt = 0; existing === undefined && attempt < 3; attempt += 1) {
630
+ try {
631
+ existing = await readAcl();
632
+ }
633
+ catch (error) {
634
+ if (error instanceof UntrustedWindowsCredentialOwnerError) {
635
+ await execFile(icacls, [path, "/setowner", `*${sid}`], processOptions);
636
+ }
637
+ else if (error instanceof RepairableWindowsCredentialAclError) {
638
+ await installTrustedAcl();
639
+ }
640
+ else {
641
+ throw error;
642
+ }
643
+ }
644
+ }
645
+ if (existing === undefined) {
646
+ throw new Error("Windows credential ACL could not be repaired");
647
+ }
648
+ if (existing.grantsCurrentUserAccess &&
649
+ existing.untrustedPrincipals.length === 0 &&
650
+ !existing.protected) {
651
+ await execFile(icacls, [path, "/inheritance:d"], processOptions);
652
+ existing = await readAcl();
653
+ }
654
+ let verified = existing;
655
+ if (!verified.protected ||
656
+ !verified.grantsCurrentUserAccess ||
657
+ verified.untrustedPrincipals.length !== 0) {
658
+ await installTrustedAcl();
659
+ verified = await readAcl();
660
+ for (const principal of verified.untrustedPrincipals) {
661
+ if (!WINDOWS_SID.test(principal)) {
662
+ throw new Error("Windows credential ACL contains an unresolvable identity");
663
+ }
664
+ await execFile(icacls, [path, "/remove:g", `*${principal}`], processOptions);
665
+ }
666
+ for (const principal of verified.deniedPrincipals) {
667
+ if (!WINDOWS_SID.test(principal)) {
668
+ throw new Error("Windows credential ACL contains an unresolvable identity");
669
+ }
670
+ await execFile(icacls, [path, "/remove:d", `*${principal}`], processOptions);
671
+ }
672
+ if (verified.untrustedPrincipals.length !== 0 ||
673
+ verified.deniedPrincipals.length !== 0) {
674
+ verified = await readAcl();
675
+ }
676
+ }
677
+ if (!verified.protected) {
678
+ throw new Error("Windows credential ACL still inherits access rules");
679
+ }
680
+ if (!verified.grantsCurrentUserAccess) {
681
+ throw new Error("Windows credential ACL does not grant the current user access");
682
+ }
683
+ if (verified.untrustedPrincipals.length !== 0) {
684
+ throw new Error("Windows credential ACL grants access to another identity");
685
+ }
686
+ if (!(await descendantsArePrivate())) {
687
+ await execFile(icacls, [join(path, "*"), "/reset", "/t", "/q"], processOptions);
688
+ if (!(await descendantsArePrivate())) {
689
+ throw new Error("Windows credential descendants remain accessible");
690
+ }
691
+ }
179
692
  }
180
693
  export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal, securityOptions = {}) {
181
694
  const homeMetadata = await requireSecureCredentialHome(codexHome, securityOptions);
@@ -418,7 +931,9 @@ export async function runWorkbench(options, args) {
418
931
  ...args,
419
932
  ], {
420
933
  env: Object.fromEntries(Object.entries(options.environment).filter(([name]) => name.toUpperCase() !== "OPENAI_API_KEY" &&
421
- name.toUpperCase() !== "CODEX_API_KEY")),
934
+ name.toUpperCase() !== "CODEX_API_KEY" &&
935
+ name.toUpperCase() !== "OPENROUTER_API_KEY" &&
936
+ name.toUpperCase() !== "FIREWORKS_API_KEY")),
422
937
  encoding: "utf8",
423
938
  maxBuffer: 4 * 1024 * 1024,
424
939
  windowsHide: true,