@lornatang/dsh-codex-security 0.1.7 → 0.1.8

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 (55) hide show
  1. package/CHANGELOG.md +118 -103
  2. package/README.md +196 -189
  3. package/README.zh.md +196 -189
  4. package/docs/ARCHITECTURE.md +59 -53
  5. package/docs/ARTIFACTS.md +49 -46
  6. package/docs/CODEX-COMPATIBILITY.md +17 -0
  7. package/docs/SPEC.md +43 -43
  8. package/docs/TOOLS.md +364 -341
  9. package/docs/VALIDATION.md +33 -31
  10. package/docs/superpowers/plans/2026-11-16-deep-scan.md +71 -0
  11. package/docs/superpowers/specs/2026-11-16-deep-scan-design.md +31 -0
  12. package/lib/constants.js +3 -3
  13. package/lib/contracts.js +114 -34
  14. package/lib/deep-coordinator.js +599 -0
  15. package/lib/deep-host.js +36 -0
  16. package/lib/deep-worker.js +254 -0
  17. package/lib/git.js +24 -22
  18. package/lib/index.js +23 -1
  19. package/lib/secure-read.js +229 -0
  20. package/lib/service.js +403 -62
  21. package/lib/state-lock.js +71 -0
  22. package/lib/store.js +33 -15
  23. package/lib/target.js +33 -13
  24. package/lib/tools.js +54 -19
  25. package/lib/types/constants.d.ts +1 -1
  26. package/lib/types/contracts.d.ts +5 -2
  27. package/lib/types/deep-coordinator.d.ts +70 -0
  28. package/lib/types/deep-host.d.ts +32 -0
  29. package/lib/types/deep-worker.d.ts +110 -0
  30. package/lib/types/git.d.ts +10 -10
  31. package/lib/types/index.d.ts +1 -1
  32. package/lib/types/secure-read.d.ts +15 -0
  33. package/lib/types/service.d.ts +20 -4
  34. package/lib/types/state-lock.d.ts +9 -0
  35. package/lib/types/store.d.ts +5 -2
  36. package/lib/types/target.d.ts +1 -0
  37. package/lib/types/tools.d.ts +3 -2
  38. package/lib/types/types.d.ts +42 -7
  39. package/lib/types/util.d.ts +4 -0
  40. package/lib/types/worker-preset.d.ts +18 -0
  41. package/lib/util.js +27 -4
  42. package/lib/worker-preset.js +8 -0
  43. package/package.json +131 -123
  44. package/schemas/coverage.schema.json +136 -134
  45. package/skills/README.md +122 -116
  46. package/skills/assess-patch-risk/SKILL.md +10 -0
  47. package/skills/attack-path-analysis/SKILL.md +10 -0
  48. package/skills/deep-security-scan/SKILL.md +15 -116
  49. package/skills/define-security-policy/SKILL.md +10 -0
  50. package/skills/finding-discovery/SKILL.md +10 -0
  51. package/skills/fix-finding/SKILL.md +14 -112
  52. package/skills/propose-security-hardening/SKILL.md +10 -0
  53. package/skills/track-findings/SKILL.md +12 -113
  54. package/skills/validation/SKILL.md +10 -0
  55. package/skills/verify-fix/SKILL.md +14 -108
@@ -0,0 +1,110 @@
1
+ import type { TargetInfo } from './types.js';
2
+ export interface WorkerSnapshot {
3
+ rootPath: string;
4
+ maxFileBytes: number;
5
+ files: Record<string, {
6
+ sha256: string;
7
+ }>;
8
+ rootIdentity?: {
9
+ dev: string;
10
+ ino: string;
11
+ };
12
+ unavailable?: {
13
+ path: string;
14
+ reason: string;
15
+ }[];
16
+ observedDigests?: Record<string, string>;
17
+ }
18
+ export interface StepPosition {
19
+ turn: number;
20
+ step: number;
21
+ }
22
+ export interface ReceiptRange {
23
+ start: number;
24
+ end: number;
25
+ total: number;
26
+ position?: StepPosition;
27
+ }
28
+ /** Compact adjacent chunks conservatively using their latest model step. */
29
+ export declare function mergeReceiptRanges(ranges: ReceiptRange[], next: ReceiptRange): ReceiptRange[];
30
+ /** Capture exact source bytes without allowing links or paths outside the target. */
31
+ export declare function captureWorkerSnapshot(rootPath: string, paths: string[], maxFileBytes: number, signal?: AbortSignal): Promise<WorkerSnapshot>;
32
+ /** Verify that the secure per-file capture is exactly the target originally bound. */
33
+ export declare function assertWorkerSnapshotMatches(target: TargetInfo, paths: string[], snapshot: WorkerSnapshot): void;
34
+ /** Bind each worker to a fixed target and exact file digests. */
35
+ export declare class WorkerRegistry {
36
+ private readonly workers;
37
+ reserve(childId: string, snapshot: WorkerSnapshot, options?: {
38
+ allowUnpositionedReceipts?: boolean;
39
+ }): void;
40
+ release(childId: string): void;
41
+ has(childId: string): boolean;
42
+ list(childId: string): string[];
43
+ receipts(childId: string): string[];
44
+ acceptFinalStep(childId: string, position: StepPosition): void;
45
+ read(childId: string, path: string): Promise<string>;
46
+ private readText;
47
+ readChunk(childId: string, path: string, offset: number): Promise<{
48
+ path: string;
49
+ content: string;
50
+ offset: number;
51
+ nextOffset: number | null;
52
+ totalLength: number;
53
+ }>;
54
+ /** Verify each delivered chunk against the snapshot before counting its covered range. */
55
+ acceptChunk(childId: string, value: {
56
+ path: string;
57
+ content: string;
58
+ offset: number;
59
+ nextOffset: number | null;
60
+ totalLength: number;
61
+ }, position?: StepPosition): void;
62
+ /** Called only after the host accepts the tool's authoritative result. */
63
+ acceptRead(childId: string, path: string, content: string): void;
64
+ private binding;
65
+ }
66
+ interface GuardContext {
67
+ tools: {
68
+ guard(callback: (execution: {
69
+ name: string;
70
+ }) => string | undefined): () => void;
71
+ };
72
+ }
73
+ /** Install in the persistent worker preset, so resumed child sessions remain confined. */
74
+ export declare function installWorkerGuard(ctx: GuardContext): () => void;
75
+ interface WorkerExecution {
76
+ name: string;
77
+ callId?: string;
78
+ agent?: {
79
+ id?: string;
80
+ session?: {
81
+ snapshotEvents?: () => readonly {
82
+ type: string;
83
+ data?: Record<string, unknown>;
84
+ }[];
85
+ };
86
+ };
87
+ arguments?: unknown;
88
+ }
89
+ interface WorkerToolsContext {
90
+ tools: {
91
+ register(definition: Record<string, unknown>, options: {
92
+ when: (context: {
93
+ agent: {
94
+ id?: string;
95
+ };
96
+ }) => boolean;
97
+ }): () => void;
98
+ };
99
+ on(event: string, listener: (execution: WorkerExecution, result: {
100
+ isError: boolean;
101
+ value?: unknown;
102
+ content?: {
103
+ type: string;
104
+ text?: string;
105
+ }[];
106
+ }) => void): (() => void) | undefined;
107
+ }
108
+ /** Register worker-only tools; ordinary agents never receive them in their tool set. */
109
+ export declare function registerWorkerTools(ctx: WorkerToolsContext, registry: WorkerRegistry): () => void;
110
+ export {};
@@ -3,20 +3,20 @@ export interface GitResult {
3
3
  stdout: string;
4
4
  stderr: string;
5
5
  }
6
- export declare function git(root: string, args: string[], timeoutMs?: number): Promise<GitResult>;
7
- export declare function gitString(root: string, args: string[], timeoutMs?: number): Promise<string | undefined>;
6
+ export declare function git(root: string, args: string[], timeoutMs?: number, signal?: AbortSignal): Promise<GitResult>;
7
+ export declare function gitString(root: string, args: string[], timeoutMs?: number, signal?: AbortSignal): Promise<string | undefined>;
8
8
  export declare function isGitRepo(root: string): Promise<boolean>;
9
- export declare function repoRoot(path: string): Promise<string | undefined>;
10
- export declare function headRevision(root: string): Promise<string | undefined>;
11
- export declare function currentBranch(root: string): Promise<string | undefined>;
12
- export declare function remoteUrl(root: string): Promise<string | undefined>;
13
- export declare function resolveRevision(root: string, ref: string): Promise<string | undefined>;
9
+ export declare function repoRoot(path: string, signal?: AbortSignal): Promise<string | undefined>;
10
+ export declare function headRevision(root: string, signal?: AbortSignal): Promise<string | undefined>;
11
+ export declare function currentBranch(root: string, signal?: AbortSignal): Promise<string | undefined>;
12
+ export declare function remoteUrl(root: string, signal?: AbortSignal): Promise<string | undefined>;
13
+ export declare function resolveRevision(root: string, ref: string, signal?: AbortSignal): Promise<string | undefined>;
14
14
  export interface StatusEntry {
15
15
  code: string;
16
16
  path: string;
17
17
  }
18
- export declare function statusEntries(root: string): Promise<StatusEntry[]>;
19
- export declare function trackedFiles(root: string): Promise<string[]>;
18
+ export declare function statusEntries(root: string, signal?: AbortSignal): Promise<StatusEntry[]>;
19
+ export declare function trackedFiles(root: string, signal?: AbortSignal): Promise<string[]>;
20
20
  export interface ChangedFile {
21
21
  status: string;
22
22
  path: string;
@@ -29,4 +29,4 @@ export declare function changedFiles(root: string, options: {
29
29
  }): Promise<ChangedFile[]>;
30
30
  /** Digest of the working tree diff including untracked files, used for snapshot identity. */
31
31
  export declare function worktreeDigest(root: string): Promise<string>;
32
- export declare function fileDigest(path: string): Promise<string | undefined>;
32
+ export declare function fileDigest(path: string, signal?: AbortSignal): Promise<string | undefined>;
@@ -6,7 +6,7 @@ import type { PluginContext } from './types.js';
6
6
  export declare const name = "codex-security";
7
7
  export declare const inject: string[];
8
8
  export { Config };
9
- export declare const version = "0.1.7";
9
+ export declare const version = "0.1.8";
10
10
  export declare const packageName = "@lornatang/dsh-codex-security";
11
11
  export { SecurityService };
12
12
  export type { ConfigType };
@@ -0,0 +1,15 @@
1
+ type Identity = {
2
+ dev: bigint;
3
+ ino: bigint;
4
+ };
5
+ /** Require an exact portable relative path; never normalize away traversal. */
6
+ export declare function workerSourcePath(value: string): string;
7
+ export declare function sourceRootIdentity(root: string): {
8
+ path: string;
9
+ identity: Identity;
10
+ };
11
+ /** Read through pinned handles, then verify the exact bytes against the bound snapshot. */
12
+ export declare function readWorkerSource(root: string, path: string, maxBytes: number, identity: Identity, expectedHash?: string): Buffer;
13
+ /** Hash oversized files through the same pinned handles without exposing their contents. */
14
+ export declare function digestWorkerSource(root: string, path: string, identity: Identity, signal?: AbortSignal): Promise<string>;
15
+ export {};
@@ -1,6 +1,7 @@
1
1
  import type { Config } from './config.js';
2
2
  import type { PluginContext } from './types.js';
3
3
  import { ScanStore } from './store.js';
4
+ import type { WorkerSnapshot } from './deep-worker.js';
4
5
  export declare const FORMATS: readonly ["sarif", "json", "csv", "markdown"];
5
6
  export type ExportFormat = (typeof FORMATS)[number];
6
7
  type Json = Record<string, unknown>;
@@ -13,9 +14,12 @@ export declare class SecurityService {
13
14
  readonly config: Config;
14
15
  private readonly ctx;
15
16
  private readonly scanLocks;
17
+ private readonly managedInvocations;
16
18
  constructor(ctx: PluginContext, options?: SecurityServiceOptions);
17
- /** Serialize complete read-modify-write operations for each scan within this process. */
19
+ /** Serialize complete read-modify-write operations across instances and processes. */
18
20
  private withScanLock;
21
+ /** Internal capability: tool-provided JSON cannot grant access to a managed scan. */
22
+ withManagedAccess<T>(args: Json, operation: () => Promise<T>): Promise<T>;
19
23
  private requireRunningScan;
20
24
  private ready;
21
25
  private requireScan;
@@ -24,7 +28,11 @@ export declare class SecurityService {
24
28
  inspectSetup(): Promise<Json>;
25
29
  inspectTarget(args: Json): Promise<Json>;
26
30
  startDefaultScan(args: Json): Promise<Json>;
27
- startScan(args: Json, kind: 'standard' | 'prompt-only' | 'deep'): Promise<Json>;
31
+ startScan(args: Json, kind: 'standard' | 'prompt-only' | 'deep', options?: {
32
+ scanId?: string;
33
+ managedParent?: string;
34
+ signal?: AbortSignal;
35
+ }): Promise<Json>;
28
36
  private scanInstructions;
29
37
  private promptOnlyPrompt;
30
38
  getScanContext(args: Json): Promise<Json>;
@@ -32,10 +40,16 @@ export declare class SecurityService {
32
40
  updateScanContext(args: Json): Promise<Json>;
33
41
  private updateScanContextUnlocked;
34
42
  updateScanProgress(args: Json): Promise<Json>;
43
+ /** Set an absolute count from the durable coordinator journal after a restart. */
44
+ setManagedProgress(args: Json): Promise<void>;
35
45
  private updateScanProgressUnlocked;
36
- recordScanDraft(args: Json): Promise<Json>;
46
+ recordScanDraft(args: Json, options?: {
47
+ workerSnapshot: WorkerSnapshot;
48
+ signal?: AbortSignal;
49
+ }): Promise<Json>;
37
50
  private recordScanDraftUnlocked;
38
51
  private collectEvidenceLines;
52
+ private collectBoundEvidenceLines;
39
53
  recordDiscoveryCandidates(args: Json): Promise<Json>;
40
54
  private recordDiscoveryCandidatesUnlocked;
41
55
  private severityOf;
@@ -47,7 +61,9 @@ export declare class SecurityService {
47
61
  saveArtifact(args: Json): Promise<Json>;
48
62
  private saveArtifactUnlocked;
49
63
  readArtifact(args: Json): Promise<Json>;
50
- completeScan(args: Json): Promise<Json>;
64
+ completeScan(args: Json, options?: {
65
+ signal?: AbortSignal;
66
+ }): Promise<Json>;
51
67
  private completeScanUnlocked;
52
68
  failScan(args: Json): Promise<Json>;
53
69
  private failScanUnlocked;
@@ -0,0 +1,9 @@
1
+ export interface StateLockOptions {
2
+ signal?: AbortSignal;
3
+ timeoutMs?: number;
4
+ }
5
+ /**
6
+ * Hold SQLite's OS-backed writer lock on a persistent local lock database.
7
+ * The database is never removed; the OS releases the lock on process exit.
8
+ */
9
+ export declare function acquireStateLock(path: string, options?: StateLockOptions): Promise<() => void>;
@@ -7,6 +7,8 @@ export interface ScanIndex {
7
7
  }
8
8
  export interface CreateScanInput {
9
9
  scanId: string;
10
+ managedParent?: string;
11
+ managedRootIdentity?: ScanRecord['managedRootIdentity'];
10
12
  mode: ScanRecord['mode'];
11
13
  promptOnly: boolean;
12
14
  target: ScanRecord['target'];
@@ -24,7 +26,6 @@ export declare function repoKeyFor(rootPath: string): string;
24
26
  export declare function summarize(record: ScanRecord): ScanSummary;
25
27
  export declare class ScanStore {
26
28
  readonly stateDir: string;
27
- private indexCache;
28
29
  private queue;
29
30
  constructor(stateDir: string);
30
31
  private get indexPath();
@@ -34,7 +35,9 @@ export declare class ScanStore {
34
35
  loadIndex(): Promise<ScanIndex>;
35
36
  private rebuildIndex;
36
37
  saveIndex(index: ScanIndex): Promise<void>;
37
- create(input: CreateScanInput): Promise<ScanRecord>;
38
+ create(input: CreateScanInput, options?: {
39
+ signal?: AbortSignal;
40
+ }): Promise<ScanRecord>;
38
41
  private writeRecord;
39
42
  get(scanId: string): Promise<{
40
43
  record: ScanRecord;
@@ -7,6 +7,7 @@ export interface ResolveTargetOptions {
7
7
  workingTree?: boolean;
8
8
  maxFiles: number;
9
9
  maxFileBytes: number;
10
+ signal?: AbortSignal;
10
11
  }
11
12
  export interface ResolvedTarget {
12
13
  target: TargetInfo;
@@ -1,4 +1,5 @@
1
1
  import type { SecurityService } from './service.js';
2
2
  import type { PluginContext, ToolDefinition } from './types.js';
3
- export declare function createSecurityTools(service: SecurityService): ToolDefinition[];
4
- export declare function registerSecurityTools(ctx: PluginContext, service: SecurityService): () => void;
3
+ import type { DeepCoordinator } from './deep-coordinator.js';
4
+ export declare function createSecurityTools(service: SecurityService, getCoordinator?: () => DeepCoordinator | undefined): ToolDefinition[];
5
+ export declare function registerSecurityTools(ctx: PluginContext, service: SecurityService, getCoordinator?: () => DeepCoordinator | undefined): () => void;
@@ -16,6 +16,7 @@ export interface FindingLocation {
16
16
  startLine: number;
17
17
  endLine?: number;
18
18
  role?: string;
19
+ [key: string]: unknown;
19
20
  }
20
21
  export interface FindingValidation {
21
22
  status?: string;
@@ -57,6 +58,7 @@ export interface Finding {
57
58
  level: Severity;
58
59
  score: number;
59
60
  scoringSystem?: string;
61
+ vector?: string;
60
62
  rationale?: string;
61
63
  changeConditions?: string;
62
64
  };
@@ -70,8 +72,10 @@ export interface Finding {
70
72
  };
71
73
  locations: FindingLocation[];
72
74
  remediation: string;
73
- rootCause?: string;
75
+ rootCause?: string | Record<string, unknown>;
76
+ root_cause?: string | Record<string, unknown> | null;
74
77
  codeEvidence?: unknown[];
78
+ code_evidence?: unknown[] | null;
75
79
  validation?: FindingValidation;
76
80
  attackPath?: FindingAttackPath;
77
81
  remediationTests?: unknown[];
@@ -93,18 +97,22 @@ export interface DraftSurface {
93
97
  receiptRefs?: string[];
94
98
  riskArea?: string;
95
99
  notes?: string;
100
+ [key: string]: unknown;
96
101
  }
97
102
  export interface DraftExclusion {
98
103
  pattern: string;
99
104
  reason: string;
105
+ [key: string]: unknown;
100
106
  }
101
107
  export interface DraftDeferred {
102
108
  id: string;
103
109
  reason: string;
104
110
  paths?: string[];
105
111
  surfaceIds?: string[];
112
+ [key: string]: unknown;
106
113
  }
107
114
  export interface DraftReviewState {
115
+ completeness?: 'complete' | 'partial' | 'unknown';
108
116
  surfaces: DraftSurface[];
109
117
  explicitExclusions?: DraftExclusion[];
110
118
  deferred?: DraftDeferred[];
@@ -116,6 +124,7 @@ export interface DraftReviewState {
116
124
  question: string;
117
125
  followUpPrompt?: string;
118
126
  }[];
127
+ [key: string]: unknown;
119
128
  }
120
129
  export interface DraftFinding {
121
130
  ruleId: string;
@@ -126,6 +135,7 @@ export interface DraftFinding {
126
135
  score?: number;
127
136
  rationale?: string;
128
137
  scoringSystem?: string;
138
+ vector?: string;
129
139
  changeConditions?: string;
130
140
  };
131
141
  confidence: {
@@ -140,8 +150,14 @@ export interface DraftFinding {
140
150
  remediation: string;
141
151
  anchor?: string;
142
152
  instance?: string;
143
- rootCause?: string;
153
+ identity?: {
154
+ anchor: string;
155
+ instance?: string;
156
+ };
157
+ rootCause?: string | Record<string, unknown>;
158
+ root_cause?: string | Record<string, unknown> | null;
144
159
  codeEvidence?: unknown[];
160
+ code_evidence?: unknown[] | null;
145
161
  validation?: FindingValidation;
146
162
  attackPath?: FindingAttackPath;
147
163
  remediationTests?: unknown[];
@@ -154,14 +170,20 @@ export interface DraftFinding {
154
170
  [key: string]: unknown;
155
171
  };
156
172
  extensions?: Record<string, unknown>;
173
+ [key: string]: unknown;
157
174
  }
158
175
  export interface ScanDraftInput {
159
176
  scanId?: string;
160
177
  complete?: boolean;
161
178
  scope?: {
162
- includePaths: string[];
163
- excludePaths: string[];
179
+ includePaths?: string[];
180
+ excludePaths?: string[];
164
181
  summary?: string;
182
+ runtimeStatus?: string;
183
+ validationMode?: string;
184
+ context?: string;
185
+ limitations?: string[];
186
+ [key: string]: unknown;
165
187
  };
166
188
  threatModel?: Record<string, unknown> | string;
167
189
  findings: DraftFinding[];
@@ -211,6 +233,12 @@ export interface DeepBudget {
211
233
  }
212
234
  export interface ScanRecord {
213
235
  scanId: string;
236
+ /** A managed Deep campaign owns mutations of this scan while it runs. */
237
+ managedParent?: string;
238
+ managedRootIdentity?: {
239
+ dev: string;
240
+ ino: string;
241
+ };
214
242
  repoKey: string;
215
243
  mode: ScanMode;
216
244
  status: ScanStatus;
@@ -279,9 +307,9 @@ export interface ScanSummary {
279
307
  }
280
308
  export interface Candidate {
281
309
  candidateId: string;
282
- ruleId: string;
310
+ ruleId?: string;
283
311
  title: string;
284
- severity: Severity;
312
+ severity?: Severity;
285
313
  path: string;
286
314
  startLine?: number;
287
315
  anchor: string;
@@ -289,6 +317,9 @@ export interface Candidate {
289
317
  summary?: string;
290
318
  status: 'discovered' | 'validating' | 'validated' | 'rejected' | 'reported';
291
319
  createdAt: string;
320
+ discovery?: Record<string, unknown>;
321
+ validation?: Record<string, unknown>;
322
+ attackPath?: Record<string, unknown>;
292
323
  }
293
324
  export interface CandidateValidation {
294
325
  candidateId: string;
@@ -298,6 +329,7 @@ export interface CandidateValidation {
298
329
  evidence?: unknown[];
299
330
  limitations?: string[];
300
331
  recordedAt: string;
332
+ validation?: Record<string, unknown>;
301
333
  }
302
334
  export interface CandidateAttackPath {
303
335
  candidateId: string;
@@ -308,6 +340,7 @@ export interface CandidateAttackPath {
308
340
  preconditions?: string[];
309
341
  controls?: string[];
310
342
  recordedAt: string;
343
+ attackPath?: Record<string, unknown>;
311
344
  }
312
345
  export interface ReviewItem {
313
346
  reviewId: string;
@@ -337,6 +370,7 @@ export interface CoverageDocument {
337
370
  schemaVersion: '1.0';
338
371
  scanId: string;
339
372
  mode: string;
373
+ completeness?: 'complete' | 'partial' | 'unknown';
340
374
  inventoryStrategy: string;
341
375
  includePaths: string[];
342
376
  excludePaths: string[];
@@ -388,7 +422,8 @@ export interface PluginContext {
388
422
  warn(...args: unknown[]): void;
389
423
  error(...args: unknown[]): void;
390
424
  };
391
- effect(callback: () => void | (() => void), label?: string): () => void;
425
+ effect(callback: () => void | (() => void | Promise<void>), label?: string): () => void;
426
+ inject?(services: string[], callback: (ctx: PluginContext) => void): unknown;
392
427
  on?(event: string, callback: (name?: string) => void): (() => void) | undefined;
393
428
  get?(name: string): unknown;
394
429
  profileContext?: {
@@ -1,4 +1,6 @@
1
1
  export declare function sha256(value: string | Uint8Array): string;
2
+ /** A workspace's identity must not depend on its current revision or scan mode. */
3
+ export declare function stableTargetId(rootPath: string): string;
2
4
  export declare function nowIso(): string;
3
5
  export declare function newId(prefix: string, hexChars?: number): string;
4
6
  export declare function shortId(value: string, length?: number): string;
@@ -34,9 +36,11 @@ export declare function listFiles(root: string, options: {
34
36
  include?: string[];
35
37
  filter?: (path: string) => boolean;
36
38
  followSymlinks?: boolean;
39
+ signal?: AbortSignal;
37
40
  }): Promise<{
38
41
  files: string[];
39
42
  truncated: boolean;
40
43
  excluded: string[];
44
+ symlinks: string[];
41
45
  }>;
42
46
  export declare function normalizeLine(value: string): string;
@@ -0,0 +1,18 @@
1
+ export declare const name = "codex-security-worker-preset";
2
+ export declare const inject: string[];
3
+ interface WorkerPresetContext {
4
+ tools: {
5
+ guard(callback: (execution: {
6
+ name: string;
7
+ }) => string | undefined): () => void;
8
+ };
9
+ effect(callback: () => () => void, label?: string): () => void;
10
+ }
11
+ /** A worker's own preset retains this guard on cold resume. */
12
+ export declare function apply(ctx: WorkerPresetContext): void;
13
+ declare const _default: {
14
+ name: string;
15
+ inject: string[];
16
+ apply: typeof apply;
17
+ };
18
+ export default _default;
package/lib/util.js CHANGED
@@ -1,9 +1,14 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
2
  import { link, mkdir, open, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
3
3
  import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
4
+ import { setTimeout as delay } from 'node:timers/promises';
4
5
  export function sha256(value) {
5
6
  return createHash('sha256').update(value).digest('hex');
6
7
  }
8
+ /** A workspace's identity must not depend on its current revision or scan mode. */
9
+ export function stableTargetId(rootPath) {
10
+ return 'target_sha256_' + sha256('local-workspace\u0000' + resolve(rootPath));
11
+ }
7
12
  export function nowIso() {
8
13
  return new Date().toISOString();
9
14
  }
@@ -21,7 +26,21 @@ export async function writeFileAtomic(path, data) {
21
26
  const tmp = join(dirname(path), '.' + process.pid + '.' + Date.now() + '.' + randomBytes(4).toString('hex') + '.tmp');
22
27
  try {
23
28
  await writeFile(tmp, data);
24
- await rename(tmp, path);
29
+ const deadline = Date.now() + 2000;
30
+ let pause = 10;
31
+ for (;;) {
32
+ try {
33
+ await rename(tmp, path);
34
+ break;
35
+ }
36
+ catch (error) {
37
+ const code = error.code;
38
+ if (process.platform !== 'win32' || !['EPERM', 'EACCES', 'EBUSY'].includes(code ?? '') || Date.now() >= deadline)
39
+ throw error;
40
+ await delay(pause);
41
+ pause = Math.min(100, pause * 2);
42
+ }
43
+ }
25
44
  }
26
45
  catch (error) {
27
46
  await rm(tmp, { force: true }).catch(() => undefined);
@@ -243,19 +262,22 @@ export function formatBytes(value) {
243
262
  export async function listFiles(root, options) {
244
263
  const files = [];
245
264
  const excluded = [];
265
+ const symlinks = [];
246
266
  let truncated = false;
247
267
  const walk = async (dir, relBase) => {
268
+ options.signal?.throwIfAborted();
248
269
  if (truncated)
249
270
  return;
250
271
  let entries;
251
272
  try {
252
273
  entries = await readdir(dir, { withFileTypes: true });
253
274
  }
254
- catch {
255
- return;
275
+ catch (error) {
276
+ throw new Error('codex-security: cannot enumerate target directory: ' + dir, { cause: error });
256
277
  }
257
278
  entries.sort((a, b) => a.name.localeCompare(b.name));
258
279
  for (const entry of entries) {
280
+ options.signal?.throwIfAborted();
259
281
  if (truncated)
260
282
  return;
261
283
  const rel = relBase ? relBase + '/' + entry.name : entry.name;
@@ -269,6 +291,7 @@ export async function listFiles(root, options) {
269
291
  }
270
292
  if (entry.isSymbolicLink()) {
271
293
  excluded.push(rel);
294
+ symlinks.push(rel);
272
295
  continue;
273
296
  }
274
297
  if (entry.isDirectory()) {
@@ -289,7 +312,7 @@ export async function listFiles(root, options) {
289
312
  }
290
313
  };
291
314
  await walk(root, '');
292
- return { files, truncated, excluded };
315
+ return { files, truncated, excluded, symlinks };
293
316
  }
294
317
  export function normalizeLine(value) {
295
318
  return value.replace(/\s+/g, ' ').trim();
@@ -0,0 +1,8 @@
1
+ import { installWorkerGuard } from './deep-worker.js';
2
+ export const name = 'codex-security-worker-preset';
3
+ export const inject = ['tools'];
4
+ /** A worker's own preset retains this guard on cold resume. */
5
+ export function apply(ctx) {
6
+ ctx.effect(() => installWorkerGuard(ctx), 'codex-security: worker guard');
7
+ }
8
+ export default { name, inject, apply };