@lornatang/dsh-codex-security 0.1.8 → 0.1.10

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/CHANGELOG.md CHANGED
@@ -1,118 +1,150 @@
1
- # Changelog
2
-
3
- ## [0.1.8] - 2026-11-16
4
-
5
- ### Added
6
-
7
- - Coordinate independent, restricted Deep review workers with bounded concurrency, attempts, no-new stopping and wall-clock time.
8
- - Persist campaign progress and recovery claims, with authenticated cross-process resume and cancellation.
9
- - Add Codex-compatible skill workflows and artifact contracts, plus cross-platform worker, recovery and concurrency tests.
10
-
11
- ### Fixed
12
-
13
- - Bind worker reads and evidence to verified target objects and file snapshots; keep incomplete coverage and conflicting findings visible.
14
- - Serialize shared indexes and scan mutations across processes and tolerate transient Windows file-sharing conflicts during atomic replacement.
15
- - Fail closed when target inventory cannot be enumerated or Git metadata cannot be resolved.
16
- - Use the macOS 26 ARM runner when macOS 15 ARM runners are unavailable.
17
-
18
- ## [0.1.7] - 2026-11-16
19
-
20
- ### Fixed
21
-
22
- - Load platform-specific native export binaries without dependency install scripts,
23
- so a new DSH profile can install the bundle under pnpm's default build policy.
24
-
25
- ## [0.1.6] - 2026-11-15
26
-
27
- ### Changed
28
-
29
- - Allow safe links inside scan storage and Git metadata while rejecting direct or transitive aliases of an export destination.
30
- - Reduce duplicate protected-tree checks and inspect reachable directories concurrently with bounded work.
31
- - Add cross-platform tests for linked directories, cycles, dangling targets and concurrent retargeting.
32
-
33
- ## [0.1.5] - 2026-11-15
34
-
35
- ### Fixed
36
-
37
- - Revalidate scan storage and Git metadata at export checkpoints, including when a directory snapshot becomes a Git repository.
38
- - Reject aliases inside protected storage and logical output paths that escape through links.
39
- - Cover POSIX moves, protected-root changes and Git metadata redirection with cross-platform regression tests.
40
-
41
- ## [0.1.4] - 2026-11-15
42
-
43
- ### Fixed
44
-
45
- - Pin export directory identities across parent creation, exclusive publication and cleanup, detecting directory moves while preserving existing export boundaries.
46
- - Add cross-process race tests and Linux, macOS and Windows CI coverage. This release is available on GitHub only; no npm version is published.
47
-
48
- ## [0.1.3] - 2026-11-15
49
-
50
- ### Fixed
51
-
52
- - Prevent exports from replacing existing files or escaping through symlinked directories, and return complete large export documents.
53
- - Include a GitHub release archive; npm is not published for this release.
54
-
55
- All notable changes to this project will be documented in this file.
56
-
57
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
58
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
59
-
60
- ## [0.1.2] - 2026-11-15
61
-
62
- ### Fixed
63
-
64
- - Declare the required DSH skill service and register loadable bundled skills.
65
- - Validate tool arguments and JSON output through the real DSH host contract.
66
- - Bind accurate target scopes, file contents and complete Git diffs, including untracked files.
67
- - Require explicit review coverage and diff dispositions before sealing; reject changed targets,
68
- incompatible comparisons and writes to sealed artifacts.
69
- - Serialize scan mutations, rebuild missing indexes and validate sealed JSON against the bundled schemas.
70
-
71
- ### Added
72
-
73
- - A default-mode start tool, a diff review-item update tool and real-host regression tests.
74
-
75
- ### Changed
76
-
77
- - Publish the plugin as the scoped npm package `@lornatang/dsh-codex-security`. The
78
- initial bare `dsh-codex-security@0.1.0` publish is deprecated in favour of the scoped
79
- name; install with `dsh plugin --profile <profile> add @lornatang/dsh-codex-security`.
80
- - Ship the English documentation and examples with the package; align the architecture,
81
- tool reference and skill workflows with the implementation.
82
- - Rewrite the README to the package-bundle documentation convention and add a Chinese
83
- translation; the package now ships `README.md` and `README.zh.md`.
84
- - Publish `cordis.patch.yml` through the package `exports` map.
85
-
86
- ## [0.1.0] - 2026-11-13
87
-
88
- Initial public release of the DeepSeek Harness port of the codex-security scan model.
89
-
90
- ### Added
91
-
92
- - DSH plugin `codex-security` (`dsh-codex-security`) with a loader patch row,
93
- a host plugin entry point, HTTP routes under `/plugins/codex-security` and a
94
- **Codex Security** settings section in the web UI.
95
- - 27 `codex_security_*` host tools covering setup/target inspection, standard,
96
- prompt-only and deep scan lifecycle, discovery candidates, validations, attack
97
- paths, artifacts, drafts, findings and triage, diff review items, export and scan
98
- comparison.
99
- - Ten agent skills registered from `skills/`: `security-scan`,
100
- `security-diff-scan`, `deep-security-scan`, `fix-finding`, `verify-fix`,
101
- `triage-finding`, `threat-model`, `track-findings`,
102
- `resolve-dependency-alert` and `vulnerability-writeup`.
103
- - Sealed scan contract adapted from OpenAI codex-security: `findings.json`,
104
- `coverage.json`, `scan-manifest.json` and `report.md`, with stable
105
- `csf_`/`occ_` ids and `codex-security/v1` fingerprints.
106
- - Deep-scan orchestration with worker count, discovery-run budget,
107
- stop-after-no-new and time limits recorded on the scan.
108
- - Diff scanning for pull requests, commit ranges, branches and working trees, with
109
- per-file review items.
110
- - Exports in SARIF 2.1.0, JSON, CSV and Markdown, plus a `failOnSeverity`
111
- policy gate.
112
- - Web workbench: status header, scan list, findings table with severity chips and
113
- triage state, coverage summary and export links.
114
- - Configuration through Schemastery: `stateDir`, `maxFiles`, `maxFileBytes`,
115
- `defaultMode`, `failOnSeverity`, `allowExportOutsideWorkspace`,
116
- `maxScanAgeDays`, `deepWorkers` and `deepMaxDiscoveryRuns`.
117
- - Documentation: README, architecture, tool reference,
118
- artifact contract, validation guide, and a GitHub Actions CI workflow.
1
+ # Changelog
2
+
3
+ ## [0.1.10] - 2026-11-18
4
+
5
+ ### Security
6
+
7
+ - Refuse export destinations inside the scan state directory but outside its exports directory, so a scan cannot publish a file that aborts or rewrites another Deep run.
8
+ - Require the Deep status tool to authorize the caller like every other Deep operation.
9
+ - Reject cross-site and non-JSON HTTP mutations, and return 403 for managed scans instead of 500.
10
+
11
+ ### Fixed
12
+
13
+ - Validate the scan manifest before publishing sealed artifacts, so an invalid threat model cannot leave a scan stuck as running with sealed files.
14
+ - Key collected evidence by the sanitized location path so fingerprints, deduplication and scan comparison stay stable.
15
+ - Require a unique non-empty id for every deferred coverage entry instead of stringifying a missing one.
16
+ - Cache verified worker text per binding, so transferring a file in 4 KiB chunks no longer re-reads the whole file twice per chunk.
17
+
18
+ ## [0.1.9] - 2026-11-17
19
+
20
+ ### Security
21
+
22
+ - Contain evidence reads to the scan target: sanitize and validate finding location paths, rejecting traversal, absolute paths and symlink escapes before reading any host file.
23
+ - Eliminate catastrophic backtracking (ReDoS) in scope glob matching by collapsing nested quantifiers and matching include/exclude globs with a cached linear-time matcher.
24
+
25
+ ### Fixed
26
+
27
+ - Read at most the requested byte limit when loading artifacts instead of buffering entire files into memory.
28
+ - Create atomic-write temporary files exclusively (`wx`) with 96-bit random suffixes.
29
+ - Reject option-like Git revision arguments (leading `-`) before invoking `rev-parse`.
30
+
31
+ ### Performance
32
+
33
+ - Compile scope globs once and cache them, removing per-file/per-pattern RegExp recompilation during inventory walks.
34
+
35
+ ## [0.1.8] - 2026-11-16
36
+
37
+ ### Added
38
+
39
+ - Coordinate independent, restricted Deep review workers with bounded concurrency, attempts, no-new stopping and wall-clock time.
40
+ - Persist campaign progress and recovery claims, with authenticated cross-process resume and cancellation.
41
+ - Add Codex-compatible skill workflows and artifact contracts, plus cross-platform worker, recovery and concurrency tests.
42
+
43
+ ### Fixed
44
+
45
+ - Bind worker reads and evidence to verified target objects and file snapshots; keep incomplete coverage and conflicting findings visible.
46
+ - Serialize shared indexes and scan mutations across processes and tolerate transient Windows file-sharing conflicts during atomic replacement.
47
+ - Fail closed when target inventory cannot be enumerated or Git metadata cannot be resolved.
48
+ - Use the macOS 26 ARM runner when macOS 15 ARM runners are unavailable.
49
+
50
+ ## [0.1.7] - 2026-11-16
51
+
52
+ ### Fixed
53
+
54
+ - Load platform-specific native export binaries without dependency install scripts,
55
+ so a new DSH profile can install the bundle under pnpm's default build policy.
56
+
57
+ ## [0.1.6] - 2026-11-15
58
+
59
+ ### Changed
60
+
61
+ - Allow safe links inside scan storage and Git metadata while rejecting direct or transitive aliases of an export destination.
62
+ - Reduce duplicate protected-tree checks and inspect reachable directories concurrently with bounded work.
63
+ - Add cross-platform tests for linked directories, cycles, dangling targets and concurrent retargeting.
64
+
65
+ ## [0.1.5] - 2026-11-15
66
+
67
+ ### Fixed
68
+
69
+ - Revalidate scan storage and Git metadata at export checkpoints, including when a directory snapshot becomes a Git repository.
70
+ - Reject aliases inside protected storage and logical output paths that escape through links.
71
+ - Cover POSIX moves, protected-root changes and Git metadata redirection with cross-platform regression tests.
72
+
73
+ ## [0.1.4] - 2026-11-15
74
+
75
+ ### Fixed
76
+
77
+ - Pin export directory identities across parent creation, exclusive publication and cleanup, detecting directory moves while preserving existing export boundaries.
78
+ - Add cross-process race tests and Linux, macOS and Windows CI coverage. This release is available on GitHub only; no npm version is published.
79
+
80
+ ## [0.1.3] - 2026-11-15
81
+
82
+ ### Fixed
83
+
84
+ - Prevent exports from replacing existing files or escaping through symlinked directories, and return complete large export documents.
85
+ - Include a GitHub release archive; npm is not published for this release.
86
+
87
+ All notable changes to this project will be documented in this file.
88
+
89
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
90
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
91
+
92
+ ## [0.1.2] - 2026-11-15
93
+
94
+ ### Fixed
95
+
96
+ - Declare the required DSH skill service and register loadable bundled skills.
97
+ - Validate tool arguments and JSON output through the real DSH host contract.
98
+ - Bind accurate target scopes, file contents and complete Git diffs, including untracked files.
99
+ - Require explicit review coverage and diff dispositions before sealing; reject changed targets,
100
+ incompatible comparisons and writes to sealed artifacts.
101
+ - Serialize scan mutations, rebuild missing indexes and validate sealed JSON against the bundled schemas.
102
+
103
+ ### Added
104
+
105
+ - A default-mode start tool, a diff review-item update tool and real-host regression tests.
106
+
107
+ ### Changed
108
+
109
+ - Publish the plugin as the scoped npm package `@lornatang/dsh-codex-security`. The
110
+ initial bare `dsh-codex-security@0.1.0` publish is deprecated in favour of the scoped
111
+ name; install with `dsh plugin --profile <profile> add @lornatang/dsh-codex-security`.
112
+ - Ship the English documentation and examples with the package; align the architecture,
113
+ tool reference and skill workflows with the implementation.
114
+ - Rewrite the README to the package-bundle documentation convention and add a Chinese
115
+ translation; the package now ships `README.md` and `README.zh.md`.
116
+ - Publish `cordis.patch.yml` through the package `exports` map.
117
+
118
+ ## [0.1.0] - 2026-11-13
119
+
120
+ Initial public release of the DeepSeek Harness port of the codex-security scan model.
121
+
122
+ ### Added
123
+
124
+ - DSH plugin `codex-security` (`dsh-codex-security`) with a loader patch row,
125
+ a host plugin entry point, HTTP routes under `/plugins/codex-security` and a
126
+ **Codex Security** settings section in the web UI.
127
+ - 27 `codex_security_*` host tools covering setup/target inspection, standard,
128
+ prompt-only and deep scan lifecycle, discovery candidates, validations, attack
129
+ paths, artifacts, drafts, findings and triage, diff review items, export and scan
130
+ comparison.
131
+ - Ten agent skills registered from `skills/`: `security-scan`,
132
+ `security-diff-scan`, `deep-security-scan`, `fix-finding`, `verify-fix`,
133
+ `triage-finding`, `threat-model`, `track-findings`,
134
+ `resolve-dependency-alert` and `vulnerability-writeup`.
135
+ - Sealed scan contract adapted from OpenAI codex-security: `findings.json`,
136
+ `coverage.json`, `scan-manifest.json` and `report.md`, with stable
137
+ `csf_`/`occ_` ids and `codex-security/v1` fingerprints.
138
+ - Deep-scan orchestration with worker count, discovery-run budget,
139
+ stop-after-no-new and time limits recorded on the scan.
140
+ - Diff scanning for pull requests, commit ranges, branches and working trees, with
141
+ per-file review items.
142
+ - Exports in SARIF 2.1.0, JSON, CSV and Markdown, plus a `failOnSeverity`
143
+ policy gate.
144
+ - Web workbench: status header, scan list, findings table with severity chips and
145
+ triage state, coverage summary and export links.
146
+ - Configuration through Schemastery: `stateDir`, `maxFiles`, `maxFileBytes`,
147
+ `defaultMode`, `failOnSeverity`, `allowExportOutsideWorkspace`,
148
+ `maxScanAgeDays`, `deepWorkers` and `deepMaxDiscoveryRuns`.
149
+ - Documentation: README, architecture, tool reference,
150
+ artifact contract, validation guide, and a GitHub Actions CI workflow.
package/README.md CHANGED
@@ -34,7 +34,7 @@ dsh plugin --profile <name> add @lornatang/dsh-codex-security
34
34
  dsh plugin --profile <name> remove @lornatang/dsh-codex-security
35
35
  ```
36
36
 
37
- For the GitHub 0.1.8 release, use `dsh plugin --profile <name> add https://github.com/Lornatang/dsh-codex-security/releases/download/v0.1.8/lornatang-dsh-codex-security-0.1.8.tgz`. The npm registry version may be older.
37
+ For the GitHub 0.1.10 release, use `dsh plugin --profile <name> add https://github.com/Lornatang/dsh-codex-security/releases/download/v0.1.10/lornatang-dsh-codex-security-0.1.10.tgz`. The npm registry version may be older.
38
38
 
39
39
  The `add` command composes the layer into the profile: the profile's `cordis.patch.yml` gains an insert entry, row id `codex-security`, whose `config` starts from the bundle defaults `maxFiles: 5000`, `maxFileBytes: 1048576`, and `defaultMode: standard`; every other field takes its default from `src/config.ts`. The package manifest points `dsh.bundle.patch` at that document. The `remove` command deletes the row and leaves scans already written under the profile data directory untouched.
40
40
 
package/README.zh.md CHANGED
@@ -34,7 +34,7 @@ dsh plugin --profile <name> add @lornatang/dsh-codex-security
34
34
  dsh plugin --profile <name> remove @lornatang/dsh-codex-security
35
35
  ```
36
36
 
37
- 安装 GitHub 上的 0.1.8 版本,请运行 `dsh plugin --profile <name> add https://github.com/Lornatang/dsh-codex-security/releases/download/v0.1.8/lornatang-dsh-codex-security-0.1.8.tgz`。npm 仓库中的版本可能较旧。
37
+ 安装 GitHub 上的 0.1.10 版本,请运行 `dsh plugin --profile <name> add https://github.com/Lornatang/dsh-codex-security/releases/download/v0.1.10/lornatang-dsh-codex-security-0.1.10.tgz`。npm 仓库中的版本可能较旧。
38
38
 
39
39
  `add` 命令把这一层组合进 profile:profile 的 `cordis.patch.yml` 中新增一条 insert 条目,row id 为 `codex-security`,其 `config` 从本包默认值 `maxFiles: 5000`、`maxFileBytes: 1048576`、`defaultMode: standard` 开始;其余字段取 `src/config.ts` 中的默认值。包清单把 `dsh.bundle.patch` 指向该文档。`remove` 命令删除该条目,已经写入 profile 数据目录的扫描保持不变。
40
40
 
package/lib/constants.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export const PACKAGE_NAME = '@lornatang/dsh-codex-security';
2
2
  export const PLUGIN_NAME = 'codex-security';
3
- export const VERSION = '0.1.8';
3
+ export const VERSION = '0.1.10';
4
4
  export const ROUTE_PREFIX = '/plugins/codex-security';
5
5
  export const PRODUCER = { name: '@lornatang/dsh-codex-security', version: VERSION };
6
6
  export const DEFAULT_EXCLUDES = ['.git/**', 'node_modules/**', 'dist/**', 'build/**', 'out/**', 'coverage/**', '.next/**', '.nuxt/**', 'vendor/**', 'target/**', '.venv/**', '__pycache__/**'];
package/lib/contracts.js CHANGED
@@ -202,8 +202,18 @@ export function validateDraft(input) {
202
202
  }
203
203
  if (reviewState.explicitExclusions !== undefined && !Array.isArray(reviewState.explicitExclusions))
204
204
  throw new Error('codex-security: reviewState.explicitExclusions must be an array');
205
- if (reviewState.deferred !== undefined && !Array.isArray(reviewState.deferred))
206
- throw new Error('codex-security: reviewState.deferred must be an array');
205
+ if (reviewState.deferred !== undefined) {
206
+ if (!Array.isArray(reviewState.deferred))
207
+ throw new Error('codex-security: reviewState.deferred must be an array');
208
+ const deferredIds = new Set();
209
+ for (const entry of reviewState.deferred) {
210
+ if (!entry || typeof entry.id !== 'string' || entry.id.trim().length === 0)
211
+ throw new Error('codex-security: each deferred entry needs a non-empty id');
212
+ if (deferredIds.has(entry.id))
213
+ throw new Error('codex-security: reviewState.deferred ids must be unique');
214
+ deferredIds.add(entry.id);
215
+ }
216
+ }
207
217
  return draft;
208
218
  }
209
219
  export function buildFindingsDocument(scanId, findings) {
@@ -12,13 +12,27 @@ const OUTPUT_SCHEMA = {
12
12
  required: ['draftJson'], additionalProperties: false,
13
13
  };
14
14
  const errorText = (error) => (error instanceof Error ? error.message : String(error)).slice(0, 1200);
15
+ function authorizeJournal(journal, actor, claim) {
16
+ if (!actor?.agent || typeof actor.agent.id !== 'string' || !actor.agent.id)
17
+ throw new Error('codex-security: a live calling agent is required');
18
+ if (actor.agent.id === journal.owner)
19
+ return;
20
+ if (typeof claim === 'string' && /^[a-f0-9]{64}$/.test(claim)) {
21
+ const provided = Buffer.from(sha256(claim), 'hex');
22
+ const expected = Buffer.from(journal.claimHash, 'hex');
23
+ if (provided.length === expected.length && timingSafeEqual(provided, expected))
24
+ return;
25
+ }
26
+ throw new Error('codex-security: Deep scan recovery claim is required');
27
+ }
15
28
  /** Public status omits the recovery-claim digest, source snapshots and worker output. */
16
- export async function readDeepStatus(service, scanId) {
29
+ export async function readDeepStatus(service, scanId, actor) {
17
30
  if (!/^cs_[a-f0-9]{24}$/.test(scanId))
18
31
  throw new Error('codex-security: invalid Deep scan id');
19
32
  const journal = await readJson(join(service.store.stateDir, 'deep', scanId + '.json'));
20
33
  if (!journal || journal.version !== 1 || journal.scanId !== scanId)
21
34
  throw new Error('codex-security: Deep scan journal not found');
35
+ authorizeJournal(journal, actor);
22
36
  return {
23
37
  ok: true, scanId, status: journal.status, createdAt: journal.createdAt, deadline: new Date(journal.deadline).toISOString(),
24
38
  budget: journal.budget, attempts: journal.runs.length, noNew: journal.noNew,
@@ -29,6 +43,13 @@ export async function readDeepStatus(service, scanId) {
29
43
  ...(run.complete !== undefined ? { complete: run.complete } : {}), ...(run.error ? { error: run.error } : {}) })),
30
44
  };
31
45
  }
46
+ /** Whether a Deep journal exists for a scan id, without disclosing its contents. */
47
+ export async function hasDeepJournal(service, scanId) {
48
+ if (!/^cs_[a-f0-9]{24}$/.test(scanId))
49
+ return false;
50
+ const journal = await readJson(join(service.store.stateDir, 'deep', scanId + '.json'));
51
+ return Boolean(journal && journal.version === 1 && journal.scanId === scanId);
52
+ }
32
53
  /** Owns a Deep campaign until it seals or is interrupted. State lives on disk, not in this instance. */
33
54
  export class DeepCoordinator {
34
55
  service;
@@ -56,17 +77,7 @@ export class DeepCoordinator {
56
77
  return journal;
57
78
  }
58
79
  authorize(journal, actor, claim) {
59
- if (!actor?.agent || typeof actor.agent.id !== 'string' || !actor.agent.id)
60
- throw new Error('codex-security: a live calling agent is required');
61
- if (actor.agent.id === journal.owner)
62
- return;
63
- if (typeof claim === 'string' && /^[a-f0-9]{64}$/.test(claim)) {
64
- const provided = Buffer.from(sha256(claim), 'hex');
65
- const expected = Buffer.from(journal.claimHash, 'hex');
66
- if (provided.length === expected.length && timingSafeEqual(provided, expected))
67
- return;
68
- }
69
- throw new Error('codex-security: Deep scan recovery claim is required');
80
+ authorizeJournal(journal, actor, claim);
70
81
  }
71
82
  async start(args, actor) {
72
83
  if (!actor?.agent || typeof actor.agent.id !== 'string' || !actor.agent.id)
@@ -1,6 +1,8 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { setImmediate as yieldEventLoop } from 'node:timers/promises';
3
3
  import { digestWorkerSource, readWorkerSource, sourceRootIdentity, workerSourcePath } from './secure-read.js';
4
+ const TEXT_CACHE_ENTRIES = 8;
5
+ const TEXT_CACHE_BYTES = 4 * 1024 * 1024;
4
6
  /** Compact adjacent chunks conservatively using their latest model step. */
5
7
  export function mergeReceiptRanges(ranges, next) {
6
8
  const compare = (a, b) => (a?.turn ?? -1) - (b?.turn ?? -1) || (a?.step ?? -1) - (b?.step ?? -1);
@@ -94,7 +96,7 @@ export class WorkerRegistry {
94
96
  }
95
97
  if (!Number.isSafeInteger(snapshot.maxFileBytes) || snapshot.maxFileBytes < 1)
96
98
  throw new Error('codex-security: invalid worker size limit');
97
- this.workers.set(childId, { rootPath: root.path, rootNode: root.identity, maxFileBytes: snapshot.maxFileBytes, files, receipts: new Set(), ranges: new Map(), allowUnpositioned: options.allowUnpositionedReceipts === true });
99
+ this.workers.set(childId, { rootPath: root.path, rootNode: root.identity, maxFileBytes: snapshot.maxFileBytes, files, receipts: new Set(), ranges: new Map(), allowUnpositioned: options.allowUnpositionedReceipts === true, textCache: new Map() });
98
100
  }
99
101
  release(childId) { this.workers.delete(childId); }
100
102
  has(childId) { return this.workers.has(childId); }
@@ -137,8 +139,30 @@ export class WorkerRegistry {
137
139
  const text = bytes.toString('utf8');
138
140
  if (!Buffer.from(text, 'utf8').equals(bytes))
139
141
  throw new Error('codex-security: worker source is not valid UTF-8');
142
+ this.cacheText(binding, source, text);
140
143
  return text;
141
144
  }
145
+ /** Reuse the bytes verified by the preceding read; fall back to a fresh verified read. */
146
+ cachedText(childId, path) {
147
+ const binding = this.binding(childId);
148
+ const source = workerSourcePath(path);
149
+ const cached = binding.textCache.get(source);
150
+ return cached !== undefined ? cached : this.readText(childId, path);
151
+ }
152
+ /** Cache the verified text so chunk acceptance does not re-read whole files. */
153
+ cacheText(binding, source, text) {
154
+ binding.textCache.set(source, text);
155
+ let bytes = 0;
156
+ for (const value of binding.textCache.values())
157
+ bytes += Buffer.byteLength(value, 'utf8');
158
+ while (binding.textCache.size > TEXT_CACHE_ENTRIES || bytes > TEXT_CACHE_BYTES) {
159
+ const oldest = binding.textCache.keys().next().value;
160
+ if (oldest === undefined)
161
+ break;
162
+ bytes -= Buffer.byteLength(binding.textCache.get(oldest) ?? '', 'utf8');
163
+ binding.textCache.delete(oldest);
164
+ }
165
+ }
142
166
  async readChunk(childId, path, offset) {
143
167
  if (!Number.isSafeInteger(offset) || offset < 0)
144
168
  throw new Error('codex-security: invalid worker source offset');
@@ -158,7 +182,7 @@ export class WorkerRegistry {
158
182
  const end = value.offset + value.content.length;
159
183
  if (value.offset < 0 || end > value.totalLength || (value.nextOffset !== null && value.nextOffset !== end) || (value.nextOffset === null && end !== value.totalLength))
160
184
  return;
161
- const original = this.readText(childId, value.path);
185
+ const original = this.cachedText(childId, value.path);
162
186
  if (original.length !== value.totalLength || original.slice(value.offset, end) !== value.content)
163
187
  return;
164
188
  const ranges = mergeReceiptRanges(binding.ranges.get(value.path) ?? [], { start: value.offset, end, total: value.totalLength, ...(position ? { position } : {}) });
package/lib/git.js CHANGED
@@ -36,6 +36,8 @@ export async function remoteUrl(root, signal) {
36
36
  return gitString(root, ['config', '--get', 'remote.origin.url'], undefined, signal);
37
37
  }
38
38
  export async function resolveRevision(root, ref, signal) {
39
+ if (typeof ref !== 'string' || ref.length === 0 || ref.startsWith('-'))
40
+ throw new Error('codex-security: invalid git revision: ' + ref);
39
41
  return gitString(root, ['rev-parse', '--verify', ref + '^{commit}'], undefined, signal);
40
42
  }
41
43
  export async function statusEntries(root, signal) {
package/lib/routes.js CHANGED
@@ -43,6 +43,30 @@ function scanIdFromPath(pathname) {
43
43
  const parts = pathname.split('/').filter(Boolean);
44
44
  return parts.length >= 2 ? parts[1] : undefined;
45
45
  }
46
+ /** Mutating HTTP routes must be same-origin JSON requests, never cross-site form posts. */
47
+ function requireJsonMutation(req) {
48
+ const contentType = String(req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase();
49
+ if (contentType !== 'application/json')
50
+ throw new Error('request content-type must be application/json');
51
+ const site = req.headers['sec-fetch-site'];
52
+ const siteValue = Array.isArray(site) ? site[0] : site;
53
+ if (siteValue !== undefined && siteValue !== 'same-origin' && siteValue !== 'none')
54
+ throw new Error('cross-site request rejected');
55
+ const origin = req.headers.origin;
56
+ if (origin !== undefined) {
57
+ const rawOrigin = Array.isArray(origin) ? origin[0] : origin;
58
+ let originHost = '';
59
+ try {
60
+ originHost = new URL(rawOrigin ?? '').host;
61
+ }
62
+ catch {
63
+ throw new Error('invalid request origin');
64
+ }
65
+ const host = req.headers.host ?? '';
66
+ if (!host || originHost.toLowerCase() !== host.toLowerCase())
67
+ throw new Error('cross-site request rejected');
68
+ }
69
+ }
46
70
  export async function handleRequest(service, req, res) {
47
71
  try {
48
72
  const url = new URL(req.url ?? '/', 'http://localhost');
@@ -83,11 +107,13 @@ export async function handleRequest(service, req, res) {
83
107
  return;
84
108
  }
85
109
  if (action === '/triage' && method === 'POST') {
110
+ requireJsonMutation(req);
86
111
  const body = await readBody(req);
87
112
  sendJson(res, 200, await service.setFindingTriage({ scanId, findingId: body['findingId'], status: body['status'], note: body['note'] }));
88
113
  return;
89
114
  }
90
115
  if (action === '/remediation' && method === 'POST') {
116
+ requireJsonMutation(req);
91
117
  const body = await readBody(req);
92
118
  sendJson(res, 200, await service.setFindingRemediation({ scanId, findingId: body['findingId'], remediation: body['remediation'], status: body['status'] }));
93
119
  return;
@@ -111,7 +137,9 @@ export async function handleRequest(service, req, res) {
111
137
  }
112
138
  catch (error) {
113
139
  const message = error instanceof Error ? error.message : String(error);
114
- const status = /scan not found/.test(message) ? 404 : /required|must be|invalid|format|refusing/.test(message) ? 400 : 500;
140
+ const status = /scan not found/.test(message) ? 404
141
+ : /managed scans can only be modified/.test(message) ? 403
142
+ : /required|must be|invalid|format|refusing|cross-site/.test(message) ? 400 : 500;
115
143
  sendJson(res, status, { ok: false, error: message });
116
144
  }
117
145
  }