@openai/codex-security 0.1.19 → 0.1.21
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.
- package/README.md +585 -833
- package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
- package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
- package/_bundled_plugin/schemas/patch-risk-assessment.schema.json +243 -0
- package/_bundled_plugin/scripts/finalize_scan_contract.py +92 -11
- package/_bundled_plugin/scripts/launch_codex_security_mcp +0 -0
- package/_bundled_plugin/scripts/workbench_cli.py +5 -1
- package/_bundled_plugin/scripts/workbench_db.py +53 -0
- package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +88 -0
- package/_bundled_plugin/skills/assess-patch-risk/agents/openai.yaml +4 -0
- package/_bundled_plugin/skills/assess-patch-risk/references/risk-rubric.md +76 -0
- package/_bundled_plugin/skills/assess-patch-risk/scripts/validate_patch_risk_assessment.py +163 -0
- package/_bundled_plugin/skills/fix-finding/SKILL.md +16 -48
- package/dist/api.d.ts +1 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +14 -18
- package/dist/api.js.map +1 -1
- package/dist/bulk-scan-discovery.d.ts +8 -0
- package/dist/bulk-scan-discovery.d.ts.map +1 -1
- package/dist/bulk-scan-discovery.js +21 -25
- package/dist/bulk-scan-discovery.js.map +1 -1
- package/dist/cli.d.ts +27 -4
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +561 -114
- package/dist/cli.js.map +1 -1
- package/dist/cloud-publish.d.ts +5 -1
- package/dist/cloud-publish.d.ts.map +1 -1
- package/dist/cloud-publish.js +323 -21
- package/dist/cloud-publish.js.map +1 -1
- package/dist/component-plan.d.ts.map +1 -1
- package/dist/component-plan.js +5 -1
- package/dist/component-plan.js.map +1 -1
- package/dist/github.d.ts +161 -0
- package/dist/github.d.ts.map +1 -0
- package/dist/github.js +158 -0
- package/dist/github.js.map +1 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/linear.d.ts +5 -0
- package/dist/linear.d.ts.map +1 -1
- package/dist/linear.js +8 -3
- package/dist/linear.js.map +1 -1
- package/dist/publication-events.d.ts +40 -13
- package/dist/publication-events.d.ts.map +1 -1
- package/dist/publication-events.js +218 -104
- package/dist/publication-events.js.map +1 -1
- package/dist/publication-store.d.ts +1 -0
- package/dist/publication-store.d.ts.map +1 -1
- package/dist/publication-store.js +73 -26
- package/dist/publication-store.js.map +1 -1
- package/dist/publication.d.ts +5 -0
- package/dist/publication.d.ts.map +1 -1
- package/dist/publication.js +12 -0
- package/dist/publication.js.map +1 -1
- package/dist/publish.d.ts +50 -1
- package/dist/publish.d.ts.map +1 -1
- package/dist/publish.js +640 -256
- package/dist/publish.js.map +1 -1
- package/dist/runtime.d.ts +0 -3
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +258 -185
- package/dist/runtime.js.map +1 -1
- package/dist/scan-comparison.d.ts +3 -0
- package/dist/scan-comparison.d.ts.map +1 -1
- package/dist/scan-comparison.js +6 -1
- package/dist/scan-comparison.js.map +1 -1
- package/dist/targets.d.ts.map +1 -1
- package/dist/targets.js +1 -0
- package/dist/targets.js.map +1 -1
- package/dist/thread-source.d.ts +8 -0
- package/dist/thread-source.d.ts.map +1 -0
- package/dist/thread-source.js +7 -0
- package/dist/thread-source.js.map +1 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +8 -5
package/dist/runtime.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { execFile as execFileCallback, spawn } from "node:child_process";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { constants, existsSync, readdirSync, } from "node:fs";
|
|
4
|
-
import { chmod, cp, copyFile, link, lstat, mkdir, mkdtemp, open,
|
|
3
|
+
import { chmodSync, constants, existsSync, readdirSync, } from "node:fs";
|
|
4
|
+
import { chmod, cp, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, stat, utimes, 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";
|
|
@@ -24,12 +24,15 @@ const MAX_ZIP_ENTRY_SIZE = 128 * 1024 * 1024;
|
|
|
24
24
|
const MAX_ZIP_EXPANDED_SIZE = 512 * 1024 * 1024;
|
|
25
25
|
const MODEL_UNSAFE_PATH = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u;
|
|
26
26
|
const CREDENTIAL_LOCK_NAME = ".codex-security-scan.lock";
|
|
27
|
+
const CREDENTIAL_LOCK_DATABASE = ".codex-security-scan.sqlite3";
|
|
27
28
|
const CREDENTIAL_LOGOUT_MARKER = ".codex-security-logged-out";
|
|
28
29
|
const CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS = 5_000;
|
|
29
30
|
const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;
|
|
30
31
|
const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;
|
|
31
32
|
const MAX_PROCESS_ID = 2_147_483_647;
|
|
32
33
|
const MAX_WINDOWS_CREDENTIAL_ACL_STDERR = 64 * 1024;
|
|
34
|
+
const WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX = "CODEX_SECURITY_ACL_COMPLETE:";
|
|
35
|
+
const WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE = 2;
|
|
33
36
|
function environmentValue(environment, requested) {
|
|
34
37
|
const exact = environment[requested]?.trim();
|
|
35
38
|
if (exact)
|
|
@@ -234,6 +237,8 @@ class RepairableWindowsCredentialOwnerError extends Error {
|
|
|
234
237
|
super(cause.message, { cause });
|
|
235
238
|
}
|
|
236
239
|
}
|
|
240
|
+
class WindowsCredentialDescendantsChangedError extends Error {
|
|
241
|
+
}
|
|
237
242
|
/** Inspect a Windows DACL without translating locale-specific account names. */
|
|
238
243
|
export function inspectWindowsCredentialAcl(descriptor, currentUserSid, options = {}) {
|
|
239
244
|
if (!WINDOWS_SID.test(currentUserSid)) {
|
|
@@ -400,43 +405,6 @@ function windowsAceAllowsAncestorReplacement(rights, inheritanceFlags) {
|
|
|
400
405
|
}
|
|
401
406
|
return false;
|
|
402
407
|
}
|
|
403
|
-
export async function verifyStableWindowsCredentialDescendants(path, inspectDescriptors, options = {}) {
|
|
404
|
-
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
405
|
-
let descendants = 0;
|
|
406
|
-
const pending = [path];
|
|
407
|
-
try {
|
|
408
|
-
while (pending.length !== 0) {
|
|
409
|
-
const current = pending.pop();
|
|
410
|
-
const directory = await opendir(current);
|
|
411
|
-
for await (const entry of directory) {
|
|
412
|
-
const child = join(current, entry.name);
|
|
413
|
-
const metadata = await lstat(child);
|
|
414
|
-
if (metadata.isSymbolicLink()) {
|
|
415
|
-
throw new Error("Windows credential home contains a symbolic link or junction");
|
|
416
|
-
}
|
|
417
|
-
if (!metadata.isDirectory() && !metadata.isFile()) {
|
|
418
|
-
throw new Error("Windows credential home contains an unsafe entry");
|
|
419
|
-
}
|
|
420
|
-
descendants += 1;
|
|
421
|
-
if (metadata.isDirectory())
|
|
422
|
-
pending.push(child);
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
catch (error) {
|
|
427
|
-
const failure = error;
|
|
428
|
-
if (failure.code === "ENOENT" && failure.path !== path) {
|
|
429
|
-
continue;
|
|
430
|
-
}
|
|
431
|
-
throw error;
|
|
432
|
-
}
|
|
433
|
-
if (descendants === 0 && options.inspectEmpty !== true)
|
|
434
|
-
return;
|
|
435
|
-
if ((await inspectDescriptors()) === descendants)
|
|
436
|
-
return;
|
|
437
|
-
}
|
|
438
|
-
throw new Error("Windows credential descendants could not be verified");
|
|
439
|
-
}
|
|
440
408
|
export async function streamWindowsCredentialAclDescriptors(command, args, inspectDescriptor, options = {}) {
|
|
441
409
|
const child = spawn(command, [...args], {
|
|
442
410
|
env: options.environment,
|
|
@@ -450,6 +418,7 @@ export async function streamWindowsCredentialAclDescriptors(command, args, inspe
|
|
|
450
418
|
if (remaining > 0)
|
|
451
419
|
stderr += chunk.slice(0, remaining);
|
|
452
420
|
});
|
|
421
|
+
let descendantsChanged = false;
|
|
453
422
|
const completion = new Promise((resolve, reject) => {
|
|
454
423
|
child.once("error", reject);
|
|
455
424
|
child.once("close", (code, signal) => {
|
|
@@ -457,6 +426,11 @@ export async function streamWindowsCredentialAclDescriptors(command, args, inspe
|
|
|
457
426
|
resolve();
|
|
458
427
|
return;
|
|
459
428
|
}
|
|
429
|
+
if (code === WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE) {
|
|
430
|
+
descendantsChanged = true;
|
|
431
|
+
resolve();
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
460
434
|
const reason = signal === null ? `exit code ${code}` : `signal ${signal}`;
|
|
461
435
|
reject(Object.assign(new Error(`Windows credential ACL inspection failed with ${reason}`), { code, signal, stderr }));
|
|
462
436
|
});
|
|
@@ -484,6 +458,10 @@ export async function streamWindowsCredentialAclDescriptors(command, args, inspe
|
|
|
484
458
|
child.kill();
|
|
485
459
|
throw error;
|
|
486
460
|
}
|
|
461
|
+
if (descendantsChanged) {
|
|
462
|
+
// Finish descriptor callbacks before allowing another snapshot attempt.
|
|
463
|
+
throw new WindowsCredentialDescendantsChangedError("Windows credential descendants changed during ACL inspection");
|
|
464
|
+
}
|
|
487
465
|
return descriptors;
|
|
488
466
|
}
|
|
489
467
|
export async function inspectWindowsCredentialAclSnapshot(path, currentUserSid, options) {
|
|
@@ -493,58 +471,78 @@ export async function inspectWindowsCredentialAclSnapshot(path, currentUserSid,
|
|
|
493
471
|
if (ancestor === dirname(ancestor))
|
|
494
472
|
break;
|
|
495
473
|
}
|
|
496
|
-
let
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
home = undefined;
|
|
500
|
-
descendantsArePrivate = true;
|
|
474
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
475
|
+
let home;
|
|
476
|
+
let descendantsArePrivate = true;
|
|
501
477
|
let inspected = 0;
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
const ancestor = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
|
|
508
|
-
resolvedAliases: options.resolvedAliases,
|
|
509
|
-
scope: "ancestor",
|
|
510
|
-
});
|
|
511
|
-
if (ancestor.untrustedPrincipals.length !== 0) {
|
|
512
|
-
throw new Error("Windows credential-home ancestor allows another identity to replace the directory");
|
|
478
|
+
let completed = false;
|
|
479
|
+
try {
|
|
480
|
+
await streamWindowsCredentialAclDescriptors(options.command, options.args, async (descriptor) => {
|
|
481
|
+
if (completed) {
|
|
482
|
+
throw new Error("Windows credential ACL inspection continued after completion");
|
|
513
483
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
484
|
+
if (descriptor.startsWith(WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX)) {
|
|
485
|
+
if (descriptor !==
|
|
486
|
+
`${WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX}${inspected}`) {
|
|
487
|
+
throw new Error("Windows credential descendants could not be verified");
|
|
488
|
+
}
|
|
489
|
+
completed = true;
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
const index = inspected;
|
|
493
|
+
inspected += 1;
|
|
494
|
+
await options.resolveDescriptorAliases?.(descriptor);
|
|
495
|
+
if (index < ancestors) {
|
|
496
|
+
const ancestor = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
|
|
519
497
|
resolvedAliases: options.resolvedAliases,
|
|
498
|
+
scope: "ancestor",
|
|
520
499
|
});
|
|
500
|
+
if (ancestor.untrustedPrincipals.length !== 0) {
|
|
501
|
+
throw new Error("Windows credential-home ancestor allows another identity to replace the directory");
|
|
502
|
+
}
|
|
503
|
+
return;
|
|
521
504
|
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
505
|
+
if (index === ancestors) {
|
|
506
|
+
try {
|
|
507
|
+
home = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
|
|
508
|
+
resolvedAliases: options.resolvedAliases,
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
catch (error) {
|
|
512
|
+
if (error instanceof UntrustedWindowsCredentialOwnerError) {
|
|
513
|
+
throw new RepairableWindowsCredentialOwnerError(error);
|
|
514
|
+
}
|
|
515
|
+
throw new RepairableWindowsCredentialAclError(error);
|
|
525
516
|
}
|
|
526
|
-
|
|
517
|
+
return;
|
|
527
518
|
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
519
|
+
const descendant = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
|
|
520
|
+
resolvedAliases: options.resolvedAliases,
|
|
521
|
+
scope: "file",
|
|
522
|
+
});
|
|
523
|
+
if (!descendant.grantsCurrentUserAccess ||
|
|
524
|
+
descendant.untrustedPrincipals.length !== 0) {
|
|
525
|
+
descendantsArePrivate = false;
|
|
526
|
+
}
|
|
527
|
+
}, { environment: options.environment });
|
|
528
|
+
}
|
|
529
|
+
catch (error) {
|
|
530
|
+
if (error instanceof WindowsCredentialDescendantsChangedError)
|
|
531
|
+
continue;
|
|
532
|
+
throw error;
|
|
533
|
+
}
|
|
534
|
+
if (inspected <= ancestors) {
|
|
540
535
|
throw new Error("Windows credential-home ancestry could not be verified");
|
|
541
536
|
}
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
537
|
+
if (!completed) {
|
|
538
|
+
throw new Error("Windows credential descendants could not be verified");
|
|
539
|
+
}
|
|
540
|
+
if (home === undefined) {
|
|
541
|
+
throw new Error("Windows credential ACL could not be verified");
|
|
542
|
+
}
|
|
543
|
+
return { home, descendantsArePrivate };
|
|
546
544
|
}
|
|
547
|
-
|
|
545
|
+
throw new Error("Windows credential descendants could not be verified");
|
|
548
546
|
}
|
|
549
547
|
async function secureWindowsCredentialHome(path) {
|
|
550
548
|
const systemRoot = process.env["SystemRoot"] ?? "C:\\Windows";
|
|
@@ -568,15 +566,33 @@ async function secureWindowsCredentialHome(path) {
|
|
|
568
566
|
}
|
|
569
567
|
// Signed built-in cmdlets remain available under ConstrainedLanguage;
|
|
570
568
|
// arbitrary .NET constructors, static methods, and SID translation do not.
|
|
569
|
+
// Enumerate and count ACLs in the same process: parallel startup can create
|
|
570
|
+
// or remove private cache and lock files while this traversal is running.
|
|
571
571
|
const script = [
|
|
572
572
|
"$ErrorActionPreference = 'Stop'",
|
|
573
|
+
"$script:descriptorCount = 0",
|
|
574
|
+
"function Write-CredentialAcl($path) { $descriptor = Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $path | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl; if (-not $descriptor) { throw 'Windows credential ACL could not be verified' }; $script:descriptorCount += 1; $descriptor }",
|
|
575
|
+
"function Read-CredentialDescendants($path) {",
|
|
576
|
+
" try { $entries = @(Microsoft.PowerShell.Management\\Get-ChildItem -LiteralPath $path -Force) } catch {",
|
|
577
|
+
// A child can disappear while an existing directory is being enumerated.
|
|
578
|
+
// Retry that incomplete listing before accepting a vanished descendant.
|
|
579
|
+
` if ($_.FullyQualifiedErrorId -eq 'System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.GetChildItemCommand') { exit ${WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE} }`,
|
|
580
|
+
" if ($path -ne $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH -and $_.CategoryInfo.Category -eq 'ObjectNotFound') { return }",
|
|
581
|
+
" throw",
|
|
582
|
+
" }",
|
|
583
|
+
" foreach ($entry in $entries) {",
|
|
584
|
+
" if (($entry.Attributes -band 1024) -and ($entry.LinkType -in @('SymbolicLink', 'Junction'))) { throw 'Windows credential home contains a symbolic link or junction' }",
|
|
585
|
+
" if ($entry.PSObject.TypeNames -notcontains 'System.IO.DirectoryInfo' -and $entry.PSObject.TypeNames -notcontains 'System.IO.FileInfo') { throw 'Windows credential home contains an unsafe entry' }",
|
|
586
|
+
" try { Write-CredentialAcl $entry.FullName } catch { if ($_.FullyQualifiedErrorId -like 'GetAcl_PathNotFound,*') { continue }; throw }",
|
|
587
|
+
" if ($entry.PSIsContainer) { Read-CredentialDescendants $entry.FullName }",
|
|
588
|
+
" }",
|
|
589
|
+
"}",
|
|
573
590
|
"$path = $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
|
|
574
|
-
"while ($true) { $parent = Microsoft.PowerShell.Management\\Split-Path -Path $path -Parent; if (-not $parent -or $parent -eq $path) { break };
|
|
575
|
-
"
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
].join("; ");
|
|
591
|
+
"while ($true) { $parent = Microsoft.PowerShell.Management\\Split-Path -Path $path -Parent; if (-not $parent -or $parent -eq $path) { break }; Write-CredentialAcl $parent; $path = $parent }",
|
|
592
|
+
"Write-CredentialAcl $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
|
|
593
|
+
"Read-CredentialDescendants $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
|
|
594
|
+
`"${WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX}$script:descriptorCount"`,
|
|
595
|
+
].join("\n");
|
|
580
596
|
const resolvePrincipalScript = [
|
|
581
597
|
"$ErrorActionPreference = 'Stop'",
|
|
582
598
|
"$descriptor = 'O:' + $env:CODEX_SECURITY_CREDENTIAL_PRINCIPAL + 'G:SYD:(A;;GA;;;SY)'",
|
|
@@ -712,82 +728,155 @@ async function secureWindowsCredentialHome(path) {
|
|
|
712
728
|
}
|
|
713
729
|
}
|
|
714
730
|
export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal, securityOptions = {}) {
|
|
731
|
+
throwIfSignalAborted(signal);
|
|
715
732
|
const homeMetadata = await requireSecureCredentialHome(codexHome, securityOptions);
|
|
716
733
|
const expectedDevice = homeMetadata.dev;
|
|
717
734
|
const expectedInode = homeMetadata.ino;
|
|
718
735
|
const lock = join(codexHome, CREDENTIAL_LOCK_NAME);
|
|
719
736
|
const ownerPath = join(lock, "owner.json");
|
|
720
737
|
const token = randomUUID();
|
|
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
|
-
|
|
738
|
+
const databasePath = join(codexHome, CREDENTIAL_LOCK_DATABASE);
|
|
739
|
+
const existingDatabaseMetadata = await lstat(databasePath).catch((error) => {
|
|
740
|
+
if (nodeErrorCode(error) === "ENOENT")
|
|
741
|
+
return null;
|
|
742
|
+
throw error;
|
|
743
|
+
});
|
|
744
|
+
if (existingDatabaseMetadata !== null) {
|
|
745
|
+
requireCredentialLockDatabaseFile(existingDatabaseMetadata, databasePath);
|
|
746
|
+
}
|
|
747
|
+
const require = createRequire(import.meta.url);
|
|
748
|
+
// Both supported runtimes bundle SQLite. Keep the transaction in the process
|
|
749
|
+
// doing the protected work, so pausing it cannot expire its lock.
|
|
750
|
+
const Database = process.versions["bun"]
|
|
751
|
+
? require("bun:sqlite")
|
|
752
|
+
.Database
|
|
753
|
+
: require("node:sqlite").DatabaseSync;
|
|
754
|
+
// Let SQLite create a missing guard so no separate descriptor can close after
|
|
755
|
+
// another connection acquires its process-owned POSIX lock. Keep the guard
|
|
756
|
+
// across releases so every contender locks the same inode.
|
|
757
|
+
const database = new Database(databasePath);
|
|
758
|
+
let databaseLocked = false;
|
|
759
|
+
try {
|
|
760
|
+
// SQLite creates new databases with the process umask. Tighten or repair
|
|
761
|
+
// the guard synchronously before yielding so concurrent first-time callers
|
|
762
|
+
// cannot reject its transient mode. The credential home is already private,
|
|
763
|
+
// and the pre-open check above rejects linked existing files.
|
|
764
|
+
if (process.platform !== "win32")
|
|
765
|
+
chmodSync(databasePath, 0o600);
|
|
766
|
+
const databaseMetadata = await lstat(databasePath);
|
|
767
|
+
requireCredentialLockDatabaseFile(databaseMetadata, databasePath);
|
|
768
|
+
if (existingDatabaseMetadata !== null &&
|
|
769
|
+
(databaseMetadata.dev !== existingDatabaseMetadata.dev ||
|
|
770
|
+
databaseMetadata.ino !== existingDatabaseMetadata.ino)) {
|
|
771
|
+
throw new OutputDirectoryError(`Codex Security credential-home lock changed while opening it: ${databasePath}`);
|
|
772
|
+
}
|
|
773
|
+
requirePrivateCredentialFile(databaseMetadata, databasePath);
|
|
774
|
+
database.exec("PRAGMA busy_timeout = 0");
|
|
775
|
+
while (true) {
|
|
776
|
+
throwIfSignalAborted(signal);
|
|
777
|
+
await requireSecureCredentialHome(codexHome, {
|
|
778
|
+
...securityOptions,
|
|
779
|
+
expectedDevice,
|
|
780
|
+
expectedInode,
|
|
781
|
+
validateWindowsAcl: false,
|
|
782
|
+
});
|
|
783
|
+
if (!databaseLocked) {
|
|
784
|
+
try {
|
|
785
|
+
database.exec("BEGIN EXCLUSIVE");
|
|
786
|
+
}
|
|
787
|
+
catch (error) {
|
|
788
|
+
if (!isRecord(error) ||
|
|
789
|
+
(error["errcode"] !== 5 && error["code"] !== "SQLITE_BUSY")) {
|
|
790
|
+
throw error;
|
|
791
|
+
}
|
|
792
|
+
await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
|
|
793
|
+
continue;
|
|
794
|
+
}
|
|
795
|
+
const currentDatabase = await lstat(databasePath);
|
|
796
|
+
if (currentDatabase.dev !== databaseMetadata.dev ||
|
|
797
|
+
currentDatabase.ino !== databaseMetadata.ino) {
|
|
798
|
+
throw new OutputDirectoryError(`Codex Security credential-home lock changed while acquiring it: ${databasePath}`);
|
|
799
|
+
}
|
|
800
|
+
databaseLocked = true;
|
|
801
|
+
}
|
|
802
|
+
const existingLock = await lstat(lock).catch((error) => {
|
|
803
|
+
if (nodeErrorCode(error) === "ENOENT")
|
|
804
|
+
return null;
|
|
750
805
|
throw error;
|
|
751
|
-
|
|
806
|
+
});
|
|
807
|
+
if (existingLock !== null) {
|
|
808
|
+
if (await recoverStaleCredentialHomeLock(lock))
|
|
809
|
+
continue;
|
|
810
|
+
await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
|
|
752
811
|
continue;
|
|
753
|
-
await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
|
|
754
|
-
continue;
|
|
755
|
-
}
|
|
756
|
-
try {
|
|
757
|
-
await writeFile(ownerPath, `${JSON.stringify({ pid: process.pid, token })}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
|
|
758
|
-
}
|
|
759
|
-
catch (error) {
|
|
760
|
-
await rm(lock, { recursive: true, force: true }).catch(() => undefined);
|
|
761
|
-
throw error;
|
|
762
|
-
}
|
|
763
|
-
const heartbeat = setInterval(async () => {
|
|
764
|
-
try {
|
|
765
|
-
const now = new Date();
|
|
766
|
-
await utimes(lock, now, now);
|
|
767
812
|
}
|
|
768
|
-
catch { }
|
|
769
|
-
}, CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS);
|
|
770
|
-
heartbeat.unref();
|
|
771
|
-
let released = false;
|
|
772
|
-
return async () => {
|
|
773
|
-
if (released)
|
|
774
|
-
return;
|
|
775
|
-
clearInterval(heartbeat);
|
|
776
813
|
await requireSecureCredentialHome(codexHome, {
|
|
777
814
|
...securityOptions,
|
|
778
815
|
expectedDevice,
|
|
779
816
|
expectedInode,
|
|
780
817
|
});
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
818
|
+
try {
|
|
819
|
+
await mkdir(lock, { mode: 0o700 });
|
|
820
|
+
}
|
|
821
|
+
catch (error) {
|
|
822
|
+
if (nodeErrorCode(error) !== "EEXIST")
|
|
823
|
+
throw error;
|
|
824
|
+
if (await recoverStaleCredentialHomeLock(lock))
|
|
825
|
+
continue;
|
|
826
|
+
await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
try {
|
|
830
|
+
await writeFile(ownerPath, `${JSON.stringify({ pid: process.pid, token, protocol: "sqlite" })}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
|
|
831
|
+
}
|
|
832
|
+
catch (error) {
|
|
833
|
+
await rm(lock, { recursive: true, force: true }).catch(() => undefined);
|
|
834
|
+
throw error;
|
|
784
835
|
}
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
836
|
+
// Released clients use the directory heartbeat instead of the SQLite lock.
|
|
837
|
+
const heartbeat = setInterval(async () => {
|
|
838
|
+
try {
|
|
839
|
+
const now = new Date();
|
|
840
|
+
await utimes(lock, now, now);
|
|
841
|
+
}
|
|
842
|
+
catch { }
|
|
843
|
+
}, CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS);
|
|
844
|
+
heartbeat.unref();
|
|
845
|
+
let released = false;
|
|
846
|
+
return async () => {
|
|
847
|
+
if (released)
|
|
848
|
+
return;
|
|
849
|
+
released = true;
|
|
850
|
+
try {
|
|
851
|
+
await requireSecureCredentialHome(codexHome, {
|
|
852
|
+
...securityOptions,
|
|
853
|
+
expectedDevice,
|
|
854
|
+
expectedInode,
|
|
855
|
+
});
|
|
856
|
+
const owner = JSON.parse(await readFile(ownerPath, "utf8"));
|
|
857
|
+
if (owner.token !== token) {
|
|
858
|
+
throw new PluginBootstrapError("The Codex Security credential-home lock is no longer owned by this scan.");
|
|
859
|
+
}
|
|
860
|
+
await rm(lock, { recursive: true, force: true });
|
|
861
|
+
}
|
|
862
|
+
finally {
|
|
863
|
+
clearInterval(heartbeat);
|
|
864
|
+
database.close();
|
|
865
|
+
}
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
catch (error) {
|
|
870
|
+
database.close();
|
|
871
|
+
throw error;
|
|
788
872
|
}
|
|
789
873
|
}
|
|
790
|
-
|
|
874
|
+
function requireCredentialLockDatabaseFile(metadata, path) {
|
|
875
|
+
if (!metadata.isFile() || metadata.nlink !== 1) {
|
|
876
|
+
throw new OutputDirectoryError(`Codex Security credential-home lock must be a regular file, not a symlink or hard link: ${path}`);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
async function recoverStaleCredentialHomeLock(lock) {
|
|
791
880
|
const metadata = await lstat(lock).catch((error) => {
|
|
792
881
|
if (nodeErrorCode(error) === "ENOENT")
|
|
793
882
|
return null;
|
|
@@ -807,47 +896,31 @@ async function recoverStaleCredentialHomeLock(lock, signal) {
|
|
|
807
896
|
throw error;
|
|
808
897
|
}
|
|
809
898
|
}
|
|
810
|
-
//
|
|
811
|
-
//
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
if (!ownerExited &&
|
|
833
|
-
Date.now() - metadata.mtimeMs < INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS) {
|
|
834
|
-
return false;
|
|
835
|
-
}
|
|
836
|
-
if (ownerIsAlive) {
|
|
837
|
-
await delay(CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS, undefined, { signal });
|
|
838
|
-
const refreshedMetadata = await lstat(lock).catch((error) => {
|
|
839
|
-
if (nodeErrorCode(error) === "ENOENT")
|
|
840
|
-
return null;
|
|
841
|
-
throw error;
|
|
842
|
-
});
|
|
843
|
-
if (refreshedMetadata === null)
|
|
844
|
-
return true;
|
|
845
|
-
if (!refreshedMetadata.isDirectory() ||
|
|
846
|
-
refreshedMetadata.isSymbolicLink()) {
|
|
847
|
-
throw new OutputDirectoryError(`Codex Security credential-home lock is not a directory: ${lock}`);
|
|
899
|
+
// We hold the SQLite transaction, so a record from that protocol is orphaned.
|
|
900
|
+
// Older clients only record a PID: a live one must be respected at any age.
|
|
901
|
+
if (!isRecord(owner) || owner["protocol"] !== "sqlite") {
|
|
902
|
+
// Only positive signed-32-bit PIDs identify an owner. Other values can name
|
|
903
|
+
// process groups or fail argument validation, so use the stale-age check.
|
|
904
|
+
const ownerPid = isRecord(owner) ? owner["pid"] : undefined;
|
|
905
|
+
if (typeof ownerPid === "number" &&
|
|
906
|
+
Number.isInteger(ownerPid) &&
|
|
907
|
+
ownerPid > 0 &&
|
|
908
|
+
ownerPid <= MAX_PROCESS_ID) {
|
|
909
|
+
try {
|
|
910
|
+
process.kill(ownerPid, 0);
|
|
911
|
+
return false;
|
|
912
|
+
}
|
|
913
|
+
catch (error) {
|
|
914
|
+
if (nodeErrorCode(error) === "EPERM")
|
|
915
|
+
return false;
|
|
916
|
+
if (nodeErrorCode(error) !== "ESRCH")
|
|
917
|
+
throw error;
|
|
918
|
+
}
|
|
848
919
|
}
|
|
849
|
-
if (
|
|
920
|
+
else if (Date.now() - metadata.mtimeMs <
|
|
921
|
+
INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS) {
|
|
850
922
|
return false;
|
|
923
|
+
}
|
|
851
924
|
}
|
|
852
925
|
const quarantine = `${lock}.stale-${randomUUID()}`;
|
|
853
926
|
try {
|