@lornatang/dsh-codex-security 0.1.9 → 0.1.11
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 +21 -0
- package/README.md +196 -196
- package/README.zh.md +196 -196
- package/docs/ARCHITECTURE.md +59 -59
- package/docs/ARTIFACTS.md +49 -49
- package/docs/CODEX-COMPATIBILITY.md +17 -17
- package/docs/SPEC.md +43 -43
- package/docs/TOOLS.md +364 -364
- package/docs/VALIDATION.md +33 -33
- package/docs/superpowers/plans/2026-11-16-deep-scan.md +71 -71
- package/docs/superpowers/specs/2026-11-16-deep-scan-design.md +31 -31
- package/lib/constants.js +1 -2
- package/lib/contracts.js +12 -2
- package/lib/deep-coordinator.js +23 -12
- package/lib/deep-worker.js +26 -2
- package/lib/git.js +0 -21
- package/lib/index.js +0 -1
- package/lib/routes.js +28 -5
- package/lib/service.js +45 -28
- package/lib/store.js +17 -3
- package/lib/target.js +30 -7
- package/lib/tools.js +4 -12
- package/lib/types/constants.d.ts +1 -2
- package/lib/types/deep-coordinator.d.ts +3 -1
- package/lib/types/deep-worker.d.ts +4 -0
- package/lib/types/git.d.ts +0 -3
- package/lib/types/index.d.ts +1 -2
- package/lib/types/routes.d.ts +0 -2
- package/lib/types/service.d.ts +0 -1
- package/lib/types/util.d.ts +0 -5
- package/lib/util.js +1 -45
- package/package.json +2 -2
- package/references/core-scan.md +1 -1
- package/references/final-report.md +1 -1
- package/references/scan-contract.md +1 -1
- package/schemas/coverage.schema.json +136 -136
- package/skills/README.md +122 -122
- package/skills/assess-patch-risk/SKILL.md +10 -10
- package/skills/attack-path-analysis/SKILL.md +10 -10
- package/skills/deep-security-scan/SKILL.md +15 -15
- package/skills/define-security-policy/SKILL.md +10 -10
- package/skills/finding-discovery/SKILL.md +10 -10
- package/skills/fix-finding/SKILL.md +14 -14
- package/skills/propose-security-hardening/SKILL.md +10 -10
- package/skills/track-findings/SKILL.md +12 -12
- package/skills/validation/SKILL.md +10 -10
- package/skills/verify-fix/SKILL.md +14 -14
- package/schemas/tools/scan-draft.schema.json +0 -766
package/docs/VALIDATION.md
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
# Validation
|
|
2
|
-
|
|
3
|
-
Run the automated checks from the repository root with Node.js 22.19 or later:
|
|
4
|
-
|
|
5
|
-
```bash
|
|
6
|
-
npm ci --no-audit --no-fund
|
|
7
|
-
npm run typecheck
|
|
8
|
-
npm test
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
`npm test` rebuilds the tracked host and client output and runs the Node test suite. The suite exercises real Cordis, DSH skill and tool registries, and the DSH tool execution pipeline without a user profile. It also covers scoped and diff targets, untracked files, snapshot changes, worker tool guards, bounded reads and delivered-content receipts, Deep budgets and deduplication, process death and authorized takeover, cross-process cancellation and index races, draft completeness, comparison guards, sealed artifacts and schema validation.
|
|
12
|
-
|
|
13
|
-
CI runs these checks on Linux, macOS and Windows with Node 22.19 and 24 as configured in the matrix. After committing any regenerated `lib/` files, `git diff --exit-code -- lib` verifies that another build is reproducible. The integration test uses the pinned DSH 0.2.2-rc.2 development packages. It does not replace a full manual DSH application or agent review.
|
|
14
|
-
|
|
15
|
-
## Package inspection
|
|
16
|
-
|
|
17
|
-
```bash
|
|
18
|
-
npm pack --dry-run
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
The package must include `lib/`, `cordis.patch.yml`, `skills/`, `references/`, `schemas/`, `docs/`, `examples/`, `README.md`, `CHANGELOG.md`, `LICENSE` and `NOTICE`. Source, tests and local dependencies are not published. The README and project documentation are in English.
|
|
22
|
-
|
|
23
|
-
## Optional isolated DSH check
|
|
24
|
-
|
|
25
|
-
Use a disposable DSH home rather than a working profile. Generate a tarball with `npm pack`, capture the actual filename printed by npm, and install it into a profile under that temporary home. Check that the host loads, all 16 skills can be read, and the workbench routes respond. Remove the disposable home after the check. This exercise may need npm registry access to install package dependencies.
|
|
26
|
-
|
|
27
|
-
## Artifact checks
|
|
28
|
-
|
|
29
|
-
Findings, coverage and manifest documents are validated against `schemas/` by the host before sealing. The regression suite independently validates generated examples and checks the SHA-256 digest of a sealed supporting artifact. Check a complete manual review as well when changing the workflow: account for each bound diff file, compare only compatible completed scans, and verify that attempted post-completion writes fail.
|
|
30
|
-
|
|
31
|
-
For an optional interoperability check, set `CODEX_SECURITY_REFERENCE_ROOT` to an installed Codex Security 0.1.32 plugin directory and run `npm test` with Python available on `PATH`. The test passes a generated completed scan to that installation's `scripts/validate_scan_contract.py`. CI does not require that separate plugin.
|
|
32
|
-
|
|
33
|
-
A green build confirms the exercised behavior. It does not establish that an agent actually reviewed every claimed surface or that the target has no vulnerabilities.
|
|
1
|
+
# Validation
|
|
2
|
+
|
|
3
|
+
Run the automated checks from the repository root with Node.js 22.19 or later:
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm ci --no-audit --no-fund
|
|
7
|
+
npm run typecheck
|
|
8
|
+
npm test
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`npm test` rebuilds the tracked host and client output and runs the Node test suite. The suite exercises real Cordis, DSH skill and tool registries, and the DSH tool execution pipeline without a user profile. It also covers scoped and diff targets, untracked files, snapshot changes, worker tool guards, bounded reads and delivered-content receipts, Deep budgets and deduplication, process death and authorized takeover, cross-process cancellation and index races, draft completeness, comparison guards, sealed artifacts and schema validation.
|
|
12
|
+
|
|
13
|
+
CI runs these checks on Linux, macOS and Windows with Node 22.19 and 24 as configured in the matrix. After committing any regenerated `lib/` files, `git diff --exit-code -- lib` verifies that another build is reproducible. The integration test uses the pinned DSH 0.2.2-rc.2 development packages. It does not replace a full manual DSH application or agent review.
|
|
14
|
+
|
|
15
|
+
## Package inspection
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm pack --dry-run
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The package must include `lib/`, `cordis.patch.yml`, `skills/`, `references/`, `schemas/`, `docs/`, `examples/`, `README.md`, `CHANGELOG.md`, `LICENSE` and `NOTICE`. Source, tests and local dependencies are not published. The README and project documentation are in English.
|
|
22
|
+
|
|
23
|
+
## Optional isolated DSH check
|
|
24
|
+
|
|
25
|
+
Use a disposable DSH home rather than a working profile. Generate a tarball with `npm pack`, capture the actual filename printed by npm, and install it into a profile under that temporary home. Check that the host loads, all 16 skills can be read, and the workbench routes respond. Remove the disposable home after the check. This exercise may need npm registry access to install package dependencies.
|
|
26
|
+
|
|
27
|
+
## Artifact checks
|
|
28
|
+
|
|
29
|
+
Findings, coverage and manifest documents are validated against `schemas/` by the host before sealing. The regression suite independently validates generated examples and checks the SHA-256 digest of a sealed supporting artifact. Check a complete manual review as well when changing the workflow: account for each bound diff file, compare only compatible completed scans, and verify that attempted post-completion writes fail.
|
|
30
|
+
|
|
31
|
+
For an optional interoperability check, set `CODEX_SECURITY_REFERENCE_ROOT` to an installed Codex Security 0.1.32 plugin directory and run `npm test` with Python available on `PATH`. The test passes a generated completed scan to that installation's `scripts/validate_scan_contract.py`. CI does not require that separate plugin.
|
|
32
|
+
|
|
33
|
+
A green build confirms the exercised behavior. It does not establish that an agent actually reviewed every claimed surface or that the target has no vulnerabilities.
|
|
@@ -1,71 +1,71 @@
|
|
|
1
|
-
# Deep Scan implementation plan
|
|
2
|
-
|
|
3
|
-
> Execute inline with `superpowers:executing-plans`; use a fresh reviewer before release.
|
|
4
|
-
|
|
5
|
-
**Goal:** Run bounded, isolated DSH review workers with durable cross-process recovery and a sealed, honest parent scan.
|
|
6
|
-
|
|
7
|
-
**Architecture:** A service-owned coordinator persists a campaign journal and uses local DSH activations. SQLite OS locks serialize campaign ownership, scan mutations and the shared index. Worker tools expose only a bound, verified source inventory, while a monotonic tool guard denies all other worker actions. Each accepted worker result is independently recorded and sealed before parent aggregation.
|
|
8
|
-
|
|
9
|
-
**Tech Stack:** TypeScript, Node.js >=22.19, built-in SQLite, DSH 0.2.2-rc.2/rc.3, Node test runner, GitHub Actions.
|
|
10
|
-
|
|
11
|
-
**Spec:** `docs/superpowers/specs/2026-11-16-deep-scan-design.md`.
|
|
12
|
-
|
|
13
|
-
## Global constraints
|
|
14
|
-
|
|
15
|
-
- Keep the npm name `@lornatang/dsh-codex-security`, preserve earlier uncommitted parity work and integrate the published v0.1.7 changes.
|
|
16
|
-
- No unsafe fallback when native/host capabilities, reliable lock semantics or worker confinement are unavailable.
|
|
17
|
-
- Automatic Deep does not accept diff targets; manual diff review remains available.
|
|
18
|
-
- Sealed scans are immutable and the parent may report partial coverage.
|
|
19
|
-
- Run Windows locally, the complete Linux/macOS/Windows matrix in GitHub CI, and the installed Codex artifact validator where available.
|
|
20
|
-
|
|
21
|
-
## Review focus
|
|
22
|
-
|
|
23
|
-
1. Two independent processes race to resume one campaign: exactly one owns it and a killed owner releases its lock.
|
|
24
|
-
2. Different scans update the shared index concurrently: neither scan disappears from the durable index.
|
|
25
|
-
3. A worker uses a scoped tool, transport, absolute path, traversal or swapped symlink: it cannot mutate the target or read outside the bound inventory.
|
|
26
|
-
4. An unfinished worker, process crash, timeout, changed target or conflicting duplicate must not produce a clean completed review.
|
|
27
|
-
5. A different session guesses a parent or child scan ID: every managed mutation fails without its recovery claim.
|
|
28
|
-
|
|
29
|
-
## Tasks
|
|
30
|
-
|
|
31
|
-
### Task 1: Cross-process state locks
|
|
32
|
-
|
|
33
|
-
**Files:** create `src/state-lock.ts`, `tests/state-lock.test.mjs`, `tests/fixtures/state-lock-process.mjs`; modify `src/store.ts`, `src/service.ts`.
|
|
34
|
-
|
|
35
|
-
**Interfaces:** `acquireStateLock(path, { signal?, timeoutMs? }): Promise<() => void>`; `ScanStore.serialize` uses the global index lock and reads the current on-disk index; scan mutation queues also use a per-scan lock.
|
|
36
|
-
|
|
37
|
-
- [x] Write tests for competing real processes, owner termination, timeout, concurrent scan/index updates and independent locks.
|
|
38
|
-
- [x] Run them and observe the intended missing-lock or lost-update failure.
|
|
39
|
-
- [x] Implement SQLite-backed OS-held locks with cancellation, never unlink the databases, and remove stale index-cache writes outside the index lock.
|
|
40
|
-
- [x] Run the lock tests and full suite; verify no unrelated standard scan regresses.
|
|
41
|
-
|
|
42
|
-
### Task 2: Bound worker source and tool guard
|
|
43
|
-
|
|
44
|
-
**Files:** create `src/deep-worker.ts`, `src/secure-read.ts`, `tests/deep-worker.test.mjs` and any process fixtures; modify `src/index.ts`, `src/types.ts`, `src/tools.ts`.
|
|
45
|
-
|
|
46
|
-
**Interfaces:** `WorkerRegistry.reserve(childId, boundSnapshot)` installs an identity before startup; the guard permits only the worker's inventory/read tools and scoped `structured_output`; secure reads return bytes only for a bound inventory path whose digest matches.
|
|
47
|
-
|
|
48
|
-
- [ ] Write tests for scope traversal, outside links, parent replacement, file changes, non-worker access and denial of native/scoped/PTC mutation tools.
|
|
49
|
-
- [ ] Observe the failures; implement pinned, cross-platform reads and the real DSH `tools.guard` integration, failing closed on unavailable enforcement.
|
|
50
|
-
- [ ] Verify tests using actual DSH tool registries and process fixtures, then run the full suite.
|
|
51
|
-
|
|
52
|
-
### Task 3: Durable coordinator and budget enforcement
|
|
53
|
-
|
|
54
|
-
**Files:** create `src/deep-scan.ts`, `tests/deep-scan.test.mjs`, `tests/fixtures/deep-scan-process.mjs`; modify `src/service.ts`, `src/store.ts`, `src/types.ts`.
|
|
55
|
-
|
|
56
|
-
**Interfaces:** `DeepCoordinator.start`, `resume`, `cancel`, `status` accept a host execution identity; a durable journal carries hashed recovery claim, full binding, deadline and run state. The DSH provider boundary uses `startActivation` with reserved child ID and structured output.
|
|
57
|
-
|
|
58
|
-
- [ ] Write tests for worker limits, attempt budget, no-new stopping, elapsed deadline, structured results, missing/failed workers, cancellation, crash/restart, concurrent resumes and target changes.
|
|
59
|
-
- [ ] Observe expected failures; implement journal transitions, exclusive campaign ownership, background lifecycle cleanup and reconciliation of child scans.
|
|
60
|
-
- [ ] Record and seal independent Standard child scans, merge findings and provenance conservatively, then seal the parent with correct complete/partial coverage.
|
|
61
|
-
- [ ] Test all managed parent and child mutations against owner identity and recovery claims; reject auto-deep diff targets.
|
|
62
|
-
- [ ] Run coordinator tests and full suite.
|
|
63
|
-
|
|
64
|
-
### Task 4: Host tools, documentation and release
|
|
65
|
-
|
|
66
|
-
**Files:** modify `src/tools.ts`, `src/index.ts`, `skills/deep-security-scan/SKILL.md`, `docs/CODEX-COMPATIBILITY.md`, user documentation, version files and `.github/workflows/ci.yml` only if needed; test real DSH registration and package output.
|
|
67
|
-
|
|
68
|
-
- [ ] Write a host integration test exercising start, status, resume and cancel with actual DSH tool execution identity; verify it fails before wiring.
|
|
69
|
-
- [ ] Wire generic and named deep start tools, recovery and cancellation, preserve manual Standard/diff behavior, and update the skill and docs.
|
|
70
|
-
- [ ] Run typecheck, the complete test suite, reference artifact validation, package dry run and reproducible build; request one fresh code review.
|
|
71
|
-
- [ ] Commit only after validation. Push the commit, wait for the GitHub OS matrix, publish a new GitHub release, and attempt npm publication; report authentication failures accurately.
|
|
1
|
+
# Deep Scan implementation plan
|
|
2
|
+
|
|
3
|
+
> Execute inline with `superpowers:executing-plans`; use a fresh reviewer before release.
|
|
4
|
+
|
|
5
|
+
**Goal:** Run bounded, isolated DSH review workers with durable cross-process recovery and a sealed, honest parent scan.
|
|
6
|
+
|
|
7
|
+
**Architecture:** A service-owned coordinator persists a campaign journal and uses local DSH activations. SQLite OS locks serialize campaign ownership, scan mutations and the shared index. Worker tools expose only a bound, verified source inventory, while a monotonic tool guard denies all other worker actions. Each accepted worker result is independently recorded and sealed before parent aggregation.
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** TypeScript, Node.js >=22.19, built-in SQLite, DSH 0.2.2-rc.2/rc.3, Node test runner, GitHub Actions.
|
|
10
|
+
|
|
11
|
+
**Spec:** `docs/superpowers/specs/2026-11-16-deep-scan-design.md`.
|
|
12
|
+
|
|
13
|
+
## Global constraints
|
|
14
|
+
|
|
15
|
+
- Keep the npm name `@lornatang/dsh-codex-security`, preserve earlier uncommitted parity work and integrate the published v0.1.7 changes.
|
|
16
|
+
- No unsafe fallback when native/host capabilities, reliable lock semantics or worker confinement are unavailable.
|
|
17
|
+
- Automatic Deep does not accept diff targets; manual diff review remains available.
|
|
18
|
+
- Sealed scans are immutable and the parent may report partial coverage.
|
|
19
|
+
- Run Windows locally, the complete Linux/macOS/Windows matrix in GitHub CI, and the installed Codex artifact validator where available.
|
|
20
|
+
|
|
21
|
+
## Review focus
|
|
22
|
+
|
|
23
|
+
1. Two independent processes race to resume one campaign: exactly one owns it and a killed owner releases its lock.
|
|
24
|
+
2. Different scans update the shared index concurrently: neither scan disappears from the durable index.
|
|
25
|
+
3. A worker uses a scoped tool, transport, absolute path, traversal or swapped symlink: it cannot mutate the target or read outside the bound inventory.
|
|
26
|
+
4. An unfinished worker, process crash, timeout, changed target or conflicting duplicate must not produce a clean completed review.
|
|
27
|
+
5. A different session guesses a parent or child scan ID: every managed mutation fails without its recovery claim.
|
|
28
|
+
|
|
29
|
+
## Tasks
|
|
30
|
+
|
|
31
|
+
### Task 1: Cross-process state locks
|
|
32
|
+
|
|
33
|
+
**Files:** create `src/state-lock.ts`, `tests/state-lock.test.mjs`, `tests/fixtures/state-lock-process.mjs`; modify `src/store.ts`, `src/service.ts`.
|
|
34
|
+
|
|
35
|
+
**Interfaces:** `acquireStateLock(path, { signal?, timeoutMs? }): Promise<() => void>`; `ScanStore.serialize` uses the global index lock and reads the current on-disk index; scan mutation queues also use a per-scan lock.
|
|
36
|
+
|
|
37
|
+
- [x] Write tests for competing real processes, owner termination, timeout, concurrent scan/index updates and independent locks.
|
|
38
|
+
- [x] Run them and observe the intended missing-lock or lost-update failure.
|
|
39
|
+
- [x] Implement SQLite-backed OS-held locks with cancellation, never unlink the databases, and remove stale index-cache writes outside the index lock.
|
|
40
|
+
- [x] Run the lock tests and full suite; verify no unrelated standard scan regresses.
|
|
41
|
+
|
|
42
|
+
### Task 2: Bound worker source and tool guard
|
|
43
|
+
|
|
44
|
+
**Files:** create `src/deep-worker.ts`, `src/secure-read.ts`, `tests/deep-worker.test.mjs` and any process fixtures; modify `src/index.ts`, `src/types.ts`, `src/tools.ts`.
|
|
45
|
+
|
|
46
|
+
**Interfaces:** `WorkerRegistry.reserve(childId, boundSnapshot)` installs an identity before startup; the guard permits only the worker's inventory/read tools and scoped `structured_output`; secure reads return bytes only for a bound inventory path whose digest matches.
|
|
47
|
+
|
|
48
|
+
- [ ] Write tests for scope traversal, outside links, parent replacement, file changes, non-worker access and denial of native/scoped/PTC mutation tools.
|
|
49
|
+
- [ ] Observe the failures; implement pinned, cross-platform reads and the real DSH `tools.guard` integration, failing closed on unavailable enforcement.
|
|
50
|
+
- [ ] Verify tests using actual DSH tool registries and process fixtures, then run the full suite.
|
|
51
|
+
|
|
52
|
+
### Task 3: Durable coordinator and budget enforcement
|
|
53
|
+
|
|
54
|
+
**Files:** create `src/deep-scan.ts`, `tests/deep-scan.test.mjs`, `tests/fixtures/deep-scan-process.mjs`; modify `src/service.ts`, `src/store.ts`, `src/types.ts`.
|
|
55
|
+
|
|
56
|
+
**Interfaces:** `DeepCoordinator.start`, `resume`, `cancel`, `status` accept a host execution identity; a durable journal carries hashed recovery claim, full binding, deadline and run state. The DSH provider boundary uses `startActivation` with reserved child ID and structured output.
|
|
57
|
+
|
|
58
|
+
- [ ] Write tests for worker limits, attempt budget, no-new stopping, elapsed deadline, structured results, missing/failed workers, cancellation, crash/restart, concurrent resumes and target changes.
|
|
59
|
+
- [ ] Observe expected failures; implement journal transitions, exclusive campaign ownership, background lifecycle cleanup and reconciliation of child scans.
|
|
60
|
+
- [ ] Record and seal independent Standard child scans, merge findings and provenance conservatively, then seal the parent with correct complete/partial coverage.
|
|
61
|
+
- [ ] Test all managed parent and child mutations against owner identity and recovery claims; reject auto-deep diff targets.
|
|
62
|
+
- [ ] Run coordinator tests and full suite.
|
|
63
|
+
|
|
64
|
+
### Task 4: Host tools, documentation and release
|
|
65
|
+
|
|
66
|
+
**Files:** modify `src/tools.ts`, `src/index.ts`, `skills/deep-security-scan/SKILL.md`, `docs/CODEX-COMPATIBILITY.md`, user documentation, version files and `.github/workflows/ci.yml` only if needed; test real DSH registration and package output.
|
|
67
|
+
|
|
68
|
+
- [ ] Write a host integration test exercising start, status, resume and cancel with actual DSH tool execution identity; verify it fails before wiring.
|
|
69
|
+
- [ ] Wire generic and named deep start tools, recovery and cancellation, preserve manual Standard/diff behavior, and update the skill and docs.
|
|
70
|
+
- [ ] Run typecheck, the complete test suite, reference artifact validation, package dry run and reproducible build; request one fresh code review.
|
|
71
|
+
- [ ] Commit only after validation. Push the commit, wait for the GitHub OS matrix, publish a new GitHub release, and attempt npm publication; report authentication failures accurately.
|
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
# Deep Scan orchestration design
|
|
2
|
-
|
|
3
|
-
## Objective and constraints
|
|
4
|
-
|
|
5
|
-
Run independent, full-scope DSH security-review workers automatically, persist their results and bounded progress, recover after a host process exits, and produce an honest, compatible parent scan. Preserve the existing manual and standard scan APIs and the previously completed artifact-compatibility work. Do not weaken the user's current filesystem and export protections or silently start unrestricted workers. The npm package remains `@lornatang/dsh-codex-security`.
|
|
6
|
-
|
|
7
|
-
## Approaches considered
|
|
8
|
-
|
|
9
|
-
1. Delegate directly with the existing generic subagent tool. This is simple but inherits the parent's unrestricted tools and leaves budgets and recovery to the model; a prompt alone is not an authority boundary.
|
|
10
|
-
2. Run a plugin-owned coordinator over the DSH in-process subagent service, enforce a tool guard for specifically identified workers, and persist progress behind operating-system-owned cross-process locks. This preserves DSH's model selection while keeping worker authority and campaign state under the plugin's control. This is the selected approach.
|
|
11
|
-
3. Depend on an external Codex CLI or service. This would add separate credentials and a non-DSH execution dependency, so it is not the requested standalone DSH implementation.
|
|
12
|
-
|
|
13
|
-
## Coordinator and lifecycle
|
|
14
|
-
|
|
15
|
-
The coordinator starts or rejoins one deep parent. Its durable journal records immutable target binding and scope, the full file inventory and per-file digests, budgets, wall-clock deadline, run identities, run lifecycle, completed child scan IDs, processed outcomes, no-new count, stop reason, errors and parent assembly progress. It is written atomically before and after each externally visible step. Recovery reconciles the journal with completed or unfinished child scans and never treats lost work as a completed review. Once the elapsed deadline or run budget is exhausted it does not start new work, and it records unfinished coverage instead of claiming completion. Automatic Deep scans reject diff targets because the current worktree inventory cannot represent deleted or revision-only files; existing manual diff workflows remain available.
|
|
16
|
-
|
|
17
|
-
Use the host's `spawn` provider only when it is local, fresh-context, and supports structured results. Each worker receives the same bound target and scope but not prior workers' conclusions. Its prompt requests a complete independent review; its structured result is validated before a separate Standard child scan is recorded and sealed. The DSH structured-output schema uses only its supported subset; the resulting data is then validated against the full artifact contracts. At most `workers` run concurrently; `maxDiscoveryRuns` counts attempts. Process completed runs in a deterministic order when updating `stopAfterNoNew`. Already running workers are canceled or accounted for on stop, timeout, host disposal or explicit cancellation. A failed or interrupted worker is never counted as a clean review.
|
|
18
|
-
|
|
19
|
-
The parent merges matching target/rule/anchor/instance fingerprints only when the reported locations and dataflow are compatible, retains each worker's provenance, keeps unrelated instances separate, and records all worker coverage and unresolved work. Same-fingerprint findings at different locations or with conflicting dataflow remain unresolved and count as new; they are not silently merged. Findings with different identities also count as new even when they might describe the same issue. Conflicting or missing results produce partial coverage. A successful parent draft is sealed through the existing scan service; target changes or invalid evidence fail closed. If no worker yields a valid completed review, the parent is failed with diagnostics rather than reported clean. A completed zero-finding scan requires at least one complete worker with its own successful, full-content read receipt for every in-scope inventory file; receipts from different workers may not be combined to claim a complete review. Unavailable or oversized files remain deferred. If no worker meets that condition and no findings exist, the parent fails with diagnostics instead of remaining indefinitely running or reporting a clean scan. Receipts prove delivery to the agent, not comprehension or absence of vulnerabilities.
|
|
20
|
-
|
|
21
|
-
The start tool returns the scan ID and a random recovery claim promptly and exposes status, cancellation and explicit resume. The journal stores only a digest of the claim and the owner's session identity; resuming, canceling or mutating the parent or its managed child scans from another session requires the claim. If a process dies before the claim is delivered, recovery is limited to the original session; an inaccessible orphan must not be taken over without authorization. Existing manual scans retain their current API. The tool adapter forwards the actual DSH execution identity and cancellation signal; a model-supplied session ID is never trusted. Background work must be owned by the plugin's lifecycle and use the DSH subagent activation's supported lifetime. A restart does not fabricate a parent Agent: resume requires a live authorized calling agent. State survives across processes, while unavailable host services fail with an actionable error rather than silently falling back to unsafe delegation.
|
|
22
|
-
|
|
23
|
-
## Security and concurrency
|
|
24
|
-
|
|
25
|
-
Install a host tool guard before worker startup. Reserve the in-process activation's child ID and identify the worker before its first turn; deny every tool other than the dedicated read-only worker tools and DSH's scoped `structured_output`, including other scoped tools and program-execution transports. A dedicated native-tool worker preset installs its own inherited guard, so a later cold-resume remains confined; removing the preset or plugin makes resume fail closed. Worker access also requires a live coordinator binding. Restrict worker reads to the bound inventory and scope with pinned directory/file handles; reject traversal, links that escape the target and files whose snapshot changes. Count a full-file receipt only after the DSH tool pipeline accepts the read result; flush receipts before accepting a worker result. Existing service evidence reads for worker-submitted locations must use the same verified file handle, not validate a path and then reopen it. Repository contents are untrusted data. Worker outputs and saved receipts are validated, not executed.
|
|
26
|
-
|
|
27
|
-
Each campaign has a persistent local SQLite lock database held in an exclusive write transaction. SQLite uses OS locks and releases them when a process dies; the lock database is never unlinked during normal operation. Every shared parent mutation has a cross-process scan lock, and all index read-modify-write operations have a separate global index lock with fresh reads. Lock acquisition is bounded and cancellation-aware. Atomic checkpoint writes occur while the campaign owner holds the lock. On takeover the new process reconciles journal state before starting work. No PID-only stale-lock deletion or lease timeout may allow two live owners. State storage is a trusted local directory on a filesystem with reliable SQLite locking; unsupported locking or a compromised lock path fails closed.
|
|
28
|
-
|
|
29
|
-
## Verification and release
|
|
30
|
-
|
|
31
|
-
Exercise real filesystem and process behavior on Windows, Linux and macOS, using deterministic fake model responses at the DSH provider boundary. Tests cover concurrency limits, no-new and run budgets, elapsed time, cancellation, independent scopes, malformed results, denied tools and path escapes, process crash/restart, two competing owners, partial worker completion and target changes. Retain the existing export-race and artifact-compatibility suite. Test the actual DSH registries and activation interface in addition to the fake provider, and verify package contents and reproducible output. Run GitHub CI before a versioned GitHub release and attempt the npm release with the configured account.
|
|
1
|
+
# Deep Scan orchestration design
|
|
2
|
+
|
|
3
|
+
## Objective and constraints
|
|
4
|
+
|
|
5
|
+
Run independent, full-scope DSH security-review workers automatically, persist their results and bounded progress, recover after a host process exits, and produce an honest, compatible parent scan. Preserve the existing manual and standard scan APIs and the previously completed artifact-compatibility work. Do not weaken the user's current filesystem and export protections or silently start unrestricted workers. The npm package remains `@lornatang/dsh-codex-security`.
|
|
6
|
+
|
|
7
|
+
## Approaches considered
|
|
8
|
+
|
|
9
|
+
1. Delegate directly with the existing generic subagent tool. This is simple but inherits the parent's unrestricted tools and leaves budgets and recovery to the model; a prompt alone is not an authority boundary.
|
|
10
|
+
2. Run a plugin-owned coordinator over the DSH in-process subagent service, enforce a tool guard for specifically identified workers, and persist progress behind operating-system-owned cross-process locks. This preserves DSH's model selection while keeping worker authority and campaign state under the plugin's control. This is the selected approach.
|
|
11
|
+
3. Depend on an external Codex CLI or service. This would add separate credentials and a non-DSH execution dependency, so it is not the requested standalone DSH implementation.
|
|
12
|
+
|
|
13
|
+
## Coordinator and lifecycle
|
|
14
|
+
|
|
15
|
+
The coordinator starts or rejoins one deep parent. Its durable journal records immutable target binding and scope, the full file inventory and per-file digests, budgets, wall-clock deadline, run identities, run lifecycle, completed child scan IDs, processed outcomes, no-new count, stop reason, errors and parent assembly progress. It is written atomically before and after each externally visible step. Recovery reconciles the journal with completed or unfinished child scans and never treats lost work as a completed review. Once the elapsed deadline or run budget is exhausted it does not start new work, and it records unfinished coverage instead of claiming completion. Automatic Deep scans reject diff targets because the current worktree inventory cannot represent deleted or revision-only files; existing manual diff workflows remain available.
|
|
16
|
+
|
|
17
|
+
Use the host's `spawn` provider only when it is local, fresh-context, and supports structured results. Each worker receives the same bound target and scope but not prior workers' conclusions. Its prompt requests a complete independent review; its structured result is validated before a separate Standard child scan is recorded and sealed. The DSH structured-output schema uses only its supported subset; the resulting data is then validated against the full artifact contracts. At most `workers` run concurrently; `maxDiscoveryRuns` counts attempts. Process completed runs in a deterministic order when updating `stopAfterNoNew`. Already running workers are canceled or accounted for on stop, timeout, host disposal or explicit cancellation. A failed or interrupted worker is never counted as a clean review.
|
|
18
|
+
|
|
19
|
+
The parent merges matching target/rule/anchor/instance fingerprints only when the reported locations and dataflow are compatible, retains each worker's provenance, keeps unrelated instances separate, and records all worker coverage and unresolved work. Same-fingerprint findings at different locations or with conflicting dataflow remain unresolved and count as new; they are not silently merged. Findings with different identities also count as new even when they might describe the same issue. Conflicting or missing results produce partial coverage. A successful parent draft is sealed through the existing scan service; target changes or invalid evidence fail closed. If no worker yields a valid completed review, the parent is failed with diagnostics rather than reported clean. A completed zero-finding scan requires at least one complete worker with its own successful, full-content read receipt for every in-scope inventory file; receipts from different workers may not be combined to claim a complete review. Unavailable or oversized files remain deferred. If no worker meets that condition and no findings exist, the parent fails with diagnostics instead of remaining indefinitely running or reporting a clean scan. Receipts prove delivery to the agent, not comprehension or absence of vulnerabilities.
|
|
20
|
+
|
|
21
|
+
The start tool returns the scan ID and a random recovery claim promptly and exposes status, cancellation and explicit resume. The journal stores only a digest of the claim and the owner's session identity; resuming, canceling or mutating the parent or its managed child scans from another session requires the claim. If a process dies before the claim is delivered, recovery is limited to the original session; an inaccessible orphan must not be taken over without authorization. Existing manual scans retain their current API. The tool adapter forwards the actual DSH execution identity and cancellation signal; a model-supplied session ID is never trusted. Background work must be owned by the plugin's lifecycle and use the DSH subagent activation's supported lifetime. A restart does not fabricate a parent Agent: resume requires a live authorized calling agent. State survives across processes, while unavailable host services fail with an actionable error rather than silently falling back to unsafe delegation.
|
|
22
|
+
|
|
23
|
+
## Security and concurrency
|
|
24
|
+
|
|
25
|
+
Install a host tool guard before worker startup. Reserve the in-process activation's child ID and identify the worker before its first turn; deny every tool other than the dedicated read-only worker tools and DSH's scoped `structured_output`, including other scoped tools and program-execution transports. A dedicated native-tool worker preset installs its own inherited guard, so a later cold-resume remains confined; removing the preset or plugin makes resume fail closed. Worker access also requires a live coordinator binding. Restrict worker reads to the bound inventory and scope with pinned directory/file handles; reject traversal, links that escape the target and files whose snapshot changes. Count a full-file receipt only after the DSH tool pipeline accepts the read result; flush receipts before accepting a worker result. Existing service evidence reads for worker-submitted locations must use the same verified file handle, not validate a path and then reopen it. Repository contents are untrusted data. Worker outputs and saved receipts are validated, not executed.
|
|
26
|
+
|
|
27
|
+
Each campaign has a persistent local SQLite lock database held in an exclusive write transaction. SQLite uses OS locks and releases them when a process dies; the lock database is never unlinked during normal operation. Every shared parent mutation has a cross-process scan lock, and all index read-modify-write operations have a separate global index lock with fresh reads. Lock acquisition is bounded and cancellation-aware. Atomic checkpoint writes occur while the campaign owner holds the lock. On takeover the new process reconciles journal state before starting work. No PID-only stale-lock deletion or lease timeout may allow two live owners. State storage is a trusted local directory on a filesystem with reliable SQLite locking; unsupported locking or a compromised lock path fails closed.
|
|
28
|
+
|
|
29
|
+
## Verification and release
|
|
30
|
+
|
|
31
|
+
Exercise real filesystem and process behavior on Windows, Linux and macOS, using deterministic fake model responses at the DSH provider boundary. Tests cover concurrency limits, no-new and run budgets, elapsed time, cancellation, independent scopes, malformed results, denied tools and path escapes, process crash/restart, two competing owners, partial worker completion and target changes. Retain the existing export-race and artifact-compatibility suite. Test the actual DSH registries and activation interface in addition to the fake provider, and verify package contents and reproducible output. Run GitHub CI before a versioned GitHub release and attempt the npm release with the configured account.
|
package/lib/constants.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
export const PACKAGE_NAME = '@lornatang/dsh-codex-security';
|
|
2
2
|
export const PLUGIN_NAME = 'codex-security';
|
|
3
|
-
export const VERSION = '0.1.
|
|
3
|
+
export const VERSION = '0.1.11';
|
|
4
4
|
export const ROUTE_PREFIX = '/plugins/codex-security';
|
|
5
5
|
export const PRODUCER = { name: '@lornatang/dsh-codex-security', version: VERSION };
|
|
6
|
-
export const DEFAULT_EXCLUDES = ['.git/**', 'node_modules/**', 'dist/**', 'build/**', 'out/**', 'coverage/**', '.next/**', '.nuxt/**', 'vendor/**', 'target/**', '.venv/**', '__pycache__/**'];
|
|
7
6
|
export const SKILL_NAMES = ['security-scan', 'security-diff-scan', 'deep-security-scan', 'fix-finding', 'verify-fix', 'triage-finding', 'threat-model', 'track-findings', 'resolve-dependency-alert', 'vulnerability-writeup', 'assess-patch-risk', 'attack-path-analysis', 'define-security-policy', 'finding-discovery', 'propose-security-hardening', 'validation'];
|
|
8
7
|
export const TOOL_NAMES = [
|
|
9
8
|
'codex_security_inspect_setup', 'codex_security_inspect_target',
|
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
|
|
206
|
-
|
|
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) {
|
package/lib/deep-coordinator.js
CHANGED
|
@@ -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
|
-
|
|
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)
|
package/lib/deep-worker.js
CHANGED
|
@@ -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.
|
|
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
|
@@ -2,7 +2,6 @@ import { execFile } from 'node:child_process';
|
|
|
2
2
|
import { promisify } from 'node:util';
|
|
3
3
|
import { createHash } from 'node:crypto';
|
|
4
4
|
import { createReadStream } from 'node:fs';
|
|
5
|
-
import { join } from 'node:path';
|
|
6
5
|
const run = promisify(execFile);
|
|
7
6
|
const MAX_BUFFER = 64 * 1024 * 1024;
|
|
8
7
|
export async function git(root, args, timeoutMs = 60000, signal) {
|
|
@@ -20,9 +19,6 @@ export async function gitString(root, args, timeoutMs, signal) {
|
|
|
20
19
|
const result = await git(root, args, timeoutMs, signal);
|
|
21
20
|
return result.ok ? result.stdout.trim() : undefined;
|
|
22
21
|
}
|
|
23
|
-
export async function isGitRepo(root) {
|
|
24
|
-
return (await gitString(root, ['rev-parse', '--is-inside-work-tree'])) === 'true';
|
|
25
|
-
}
|
|
26
22
|
export async function repoRoot(path, signal) {
|
|
27
23
|
return gitString(path, ['rev-parse', '--show-toplevel'], undefined, signal);
|
|
28
24
|
}
|
|
@@ -115,23 +111,6 @@ export async function changedFiles(root, options) {
|
|
|
115
111
|
}
|
|
116
112
|
return files;
|
|
117
113
|
}
|
|
118
|
-
/** Digest of the working tree diff including untracked files, used for snapshot identity. */
|
|
119
|
-
export async function worktreeDigest(root) {
|
|
120
|
-
const hash = createHash('sha256');
|
|
121
|
-
const status = await git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);
|
|
122
|
-
hash.update('status\u0000' + (status.ok ? status.stdout : ''));
|
|
123
|
-
const diff = await git(root, ['diff', 'HEAD']);
|
|
124
|
-
hash.update('diff\u0000' + (diff.ok ? diff.stdout : diff.stderr));
|
|
125
|
-
const staged = await git(root, ['diff', '--cached']);
|
|
126
|
-
hash.update('staged\u0000' + (staged.ok ? staged.stdout : ''));
|
|
127
|
-
const untracked = await git(root, ['ls-files', '--others', '--exclude-standard', '-z']);
|
|
128
|
-
if (untracked.ok) {
|
|
129
|
-
const names = untracked.stdout.split('\u0000').filter(Boolean).sort();
|
|
130
|
-
for (const name of names)
|
|
131
|
-
hash.update('untracked\u0000' + name + '\u0000' + (await fileDigest(join(root, name)) ?? 'unavailable'));
|
|
132
|
-
}
|
|
133
|
-
return hash.digest('hex');
|
|
134
|
-
}
|
|
135
114
|
export async function fileDigest(path, signal) {
|
|
136
115
|
try {
|
|
137
116
|
const hash = createHash('sha256');
|
package/lib/index.js
CHANGED
|
@@ -13,7 +13,6 @@ export const name = PLUGIN_NAME;
|
|
|
13
13
|
export const inject = ['tools', 'skills'];
|
|
14
14
|
export { Config };
|
|
15
15
|
export const version = VERSION;
|
|
16
|
-
export const packageName = PACKAGE_NAME;
|
|
17
16
|
export { SecurityService };
|
|
18
17
|
function parseFrontmatter(text) {
|
|
19
18
|
if (!text.startsWith('---'))
|
package/lib/routes.js
CHANGED
|
@@ -39,9 +39,29 @@ function sendFile(res, content, mediaType, filename) {
|
|
|
39
39
|
res.setHeader('content-disposition', 'attachment; filename="' + filename + '"');
|
|
40
40
|
res.end(content);
|
|
41
41
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
42
|
+
/** Mutating HTTP routes must be same-origin JSON requests, never cross-site form posts. */
|
|
43
|
+
function requireJsonMutation(req) {
|
|
44
|
+
const contentType = String(req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase();
|
|
45
|
+
if (contentType !== 'application/json')
|
|
46
|
+
throw new Error('request content-type must be application/json');
|
|
47
|
+
const site = req.headers['sec-fetch-site'];
|
|
48
|
+
const siteValue = Array.isArray(site) ? site[0] : site;
|
|
49
|
+
if (siteValue !== undefined && siteValue !== 'same-origin' && siteValue !== 'none')
|
|
50
|
+
throw new Error('cross-site request rejected');
|
|
51
|
+
const origin = req.headers.origin;
|
|
52
|
+
if (origin !== undefined) {
|
|
53
|
+
const rawOrigin = Array.isArray(origin) ? origin[0] : origin;
|
|
54
|
+
let originHost = '';
|
|
55
|
+
try {
|
|
56
|
+
originHost = new URL(rawOrigin ?? '').host;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
throw new Error('invalid request origin');
|
|
60
|
+
}
|
|
61
|
+
const host = req.headers.host ?? '';
|
|
62
|
+
if (!host || originHost.toLowerCase() !== host.toLowerCase())
|
|
63
|
+
throw new Error('cross-site request rejected');
|
|
64
|
+
}
|
|
45
65
|
}
|
|
46
66
|
export async function handleRequest(service, req, res) {
|
|
47
67
|
try {
|
|
@@ -83,11 +103,13 @@ export async function handleRequest(service, req, res) {
|
|
|
83
103
|
return;
|
|
84
104
|
}
|
|
85
105
|
if (action === '/triage' && method === 'POST') {
|
|
106
|
+
requireJsonMutation(req);
|
|
86
107
|
const body = await readBody(req);
|
|
87
108
|
sendJson(res, 200, await service.setFindingTriage({ scanId, findingId: body['findingId'], status: body['status'], note: body['note'] }));
|
|
88
109
|
return;
|
|
89
110
|
}
|
|
90
111
|
if (action === '/remediation' && method === 'POST') {
|
|
112
|
+
requireJsonMutation(req);
|
|
91
113
|
const body = await readBody(req);
|
|
92
114
|
sendJson(res, 200, await service.setFindingRemediation({ scanId, findingId: body['findingId'], remediation: body['remediation'], status: body['status'] }));
|
|
93
115
|
return;
|
|
@@ -111,7 +133,9 @@ export async function handleRequest(service, req, res) {
|
|
|
111
133
|
}
|
|
112
134
|
catch (error) {
|
|
113
135
|
const message = error instanceof Error ? error.message : String(error);
|
|
114
|
-
const status = /scan not found/.test(message) ? 404
|
|
136
|
+
const status = /scan not found/.test(message) ? 404
|
|
137
|
+
: /managed scans can only be modified/.test(message) ? 403
|
|
138
|
+
: /required|must be|invalid|format|refusing|cross-site/.test(message) ? 400 : 500;
|
|
115
139
|
sendJson(res, status, { ok: false, error: message });
|
|
116
140
|
}
|
|
117
141
|
}
|
|
@@ -128,4 +152,3 @@ export function bindRoutes(ctx, service) {
|
|
|
128
152
|
const off = ctx.on?.('internal/service', () => { register(); });
|
|
129
153
|
return () => { off?.(); disposeRoute?.(); disposeRoute = undefined; };
|
|
130
154
|
}
|
|
131
|
-
export { scanIdFromPath };
|