@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.
Files changed (48) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +196 -196
  3. package/README.zh.md +196 -196
  4. package/docs/ARCHITECTURE.md +59 -59
  5. package/docs/ARTIFACTS.md +49 -49
  6. package/docs/CODEX-COMPATIBILITY.md +17 -17
  7. package/docs/SPEC.md +43 -43
  8. package/docs/TOOLS.md +364 -364
  9. package/docs/VALIDATION.md +33 -33
  10. package/docs/superpowers/plans/2026-11-16-deep-scan.md +71 -71
  11. package/docs/superpowers/specs/2026-11-16-deep-scan-design.md +31 -31
  12. package/lib/constants.js +1 -2
  13. package/lib/contracts.js +12 -2
  14. package/lib/deep-coordinator.js +23 -12
  15. package/lib/deep-worker.js +26 -2
  16. package/lib/git.js +0 -21
  17. package/lib/index.js +0 -1
  18. package/lib/routes.js +28 -5
  19. package/lib/service.js +45 -28
  20. package/lib/store.js +17 -3
  21. package/lib/target.js +30 -7
  22. package/lib/tools.js +4 -12
  23. package/lib/types/constants.d.ts +1 -2
  24. package/lib/types/deep-coordinator.d.ts +3 -1
  25. package/lib/types/deep-worker.d.ts +4 -0
  26. package/lib/types/git.d.ts +0 -3
  27. package/lib/types/index.d.ts +1 -2
  28. package/lib/types/routes.d.ts +0 -2
  29. package/lib/types/service.d.ts +0 -1
  30. package/lib/types/util.d.ts +0 -5
  31. package/lib/util.js +1 -45
  32. package/package.json +2 -2
  33. package/references/core-scan.md +1 -1
  34. package/references/final-report.md +1 -1
  35. package/references/scan-contract.md +1 -1
  36. package/schemas/coverage.schema.json +136 -136
  37. package/skills/README.md +122 -122
  38. package/skills/assess-patch-risk/SKILL.md +10 -10
  39. package/skills/attack-path-analysis/SKILL.md +10 -10
  40. package/skills/deep-security-scan/SKILL.md +15 -15
  41. package/skills/define-security-policy/SKILL.md +10 -10
  42. package/skills/finding-discovery/SKILL.md +10 -10
  43. package/skills/fix-finding/SKILL.md +14 -14
  44. package/skills/propose-security-hardening/SKILL.md +10 -10
  45. package/skills/track-findings/SKILL.md +12 -12
  46. package/skills/validation/SKILL.md +10 -10
  47. package/skills/verify-fix/SKILL.md +14 -14
  48. package/schemas/tools/scan-draft.schema.json +0 -766
package/lib/service.js CHANGED
@@ -8,7 +8,7 @@ import { FINDING_STATUSES, SEVERITIES } from './types.js';
8
8
  import { ScanStore, defaultStateDir } from './store.js';
9
9
  import { readEvidenceLine, resolveTarget } from './target.js';
10
10
  import { assertArtifactContract } from './schema.js';
11
- import { canonicalProspectivePath, ensureDir, joinWithin, newId, normalizeLine, nowIso, readFullText, readJson, sanitizeRelative, sha256, truncate, writeFileAtomic, writeJsonAtomic } from './util.js';
11
+ import { canonicalProspectivePath, ensureDir, isWithin, joinWithin, newId, normalizeLine, nowIso, readFullText, readJson, sanitizeRelative, sha256, truncate, writeFileAtomic, writeJsonAtomic } from './util.js';
12
12
  import { createExportValidator, writeSecureExport } from './secure-export.js';
13
13
  import { acquireStateLock } from './state-lock.js';
14
14
  import { WorkerRegistry } from './deep-worker.js';
@@ -93,18 +93,24 @@ function manifestThreatModel(value) {
93
93
  return { format: 'markdown', content: renderThreatModel(value) };
94
94
  }
95
95
  function validateThreatModel(value) {
96
- if ((typeof value === 'string' && value.trim()) || asObject(value))
97
- return;
98
- throw new Error('codex-security: threatModel must be a non-empty string or an object');
96
+ if (typeof value === 'string') {
97
+ if (value.trim())
98
+ return;
99
+ throw new Error('codex-security: threatModel must be a non-empty string or an object');
100
+ }
101
+ const object = asObject(value);
102
+ if (!object)
103
+ throw new Error('codex-security: threatModel must be a non-empty string or an object');
104
+ if (object['format'] === 'markdown' && (typeof object['content'] !== 'string' || object['content'].trim().length === 0)) {
105
+ throw new Error('codex-security: threatModel markdown content must be a non-empty string');
106
+ }
99
107
  }
100
108
  export class SecurityService {
101
109
  store;
102
110
  config;
103
- ctx;
104
111
  scanLocks = new Map();
105
112
  managedInvocations = new WeakSet();
106
113
  constructor(ctx, options = {}) {
107
- this.ctx = ctx;
108
114
  this.config = { ...DEFAULT_CONFIG, ...(options.config ?? {}) };
109
115
  const profile = ctx.get?.('profileContext') ?? (Object.hasOwn(ctx, 'profileContext') ? ctx.profileContext : undefined);
110
116
  const patchPath = options.patchPath ?? profile?.patchPath;
@@ -555,9 +561,16 @@ export class SecurityService {
555
561
  const location = finding.locations?.[0];
556
562
  if (!location)
557
563
  continue;
558
- const key = location.path + ':' + location.startLine;
564
+ let path;
565
+ try {
566
+ path = sanitizeRelative(location.path);
567
+ }
568
+ catch {
569
+ continue;
570
+ }
571
+ const key = path + ':' + location.startLine;
559
572
  if (!keys.has(key))
560
- keys.set(key, { path: location.path, line: location.startLine });
573
+ keys.set(key, { path, line: location.startLine });
561
574
  if (keys.size >= 500)
562
575
  break;
563
576
  }
@@ -965,6 +978,8 @@ export class SecurityService {
965
978
  }
966
979
  }
967
980
  const threatModel = draft.input.threatModel ?? record.threatModel;
981
+ if (threatModel !== undefined)
982
+ validateThreatModel(threatModel);
968
983
  const sealedAt = nowIso();
969
984
  const findingsDocument = buildFindingsDocument(scanId, findings);
970
985
  const sarif = toSarif(record, findings);
@@ -972,28 +987,20 @@ export class SecurityService {
972
987
  validateFindingEvidence(findings);
973
988
  assertArtifactContract('findings', findingsDocument);
974
989
  assertArtifactContract('coverage', coverage);
975
- await writeJsonAtomic(join(dir, 'findings.json'), findingsDocument);
976
- await writeJsonAtomic(join(dir, 'coverage.json'), coverage);
977
- await writeJsonAtomic(join(dir, 'sarif.json'), sarif);
978
- await writeFileAtomic(join(dir, 'report.md'), report);
979
- if (threatModel !== undefined) {
980
- await writeFileAtomic(join(dir, 'threat-model.md'), renderThreatModel(threatModel));
981
- await writeFileAtomic(join(dir, 'threatmodel.md'), renderThreatModel(threatModel));
982
- }
983
- const sealFiles = [
984
- { path: 'findings.json', mediaType: 'application/json' },
985
- { path: 'coverage.json', mediaType: 'application/json' },
986
- { path: 'sarif.json', mediaType: 'application/sarif+json' },
987
- { path: 'report.md', mediaType: 'text/markdown' },
990
+ // Build every sealed document in memory and validate the manifest before
991
+ // publishing any file, so a schema failure can never leave sealed artifacts
992
+ // behind on a scan that is still running.
993
+ const sealedFiles = [
994
+ { path: 'findings.json', mediaType: 'application/json', content: JSON.stringify(findingsDocument, null, 2) + '\n' },
995
+ { path: 'coverage.json', mediaType: 'application/json', content: JSON.stringify(coverage, null, 2) + '\n' },
996
+ { path: 'sarif.json', mediaType: 'application/sarif+json', content: JSON.stringify(sarif, null, 2) + '\n' },
997
+ { path: 'report.md', mediaType: 'text/markdown', content: report },
988
998
  ];
989
- if (threatModel !== undefined)
990
- sealFiles.push({ path: 'threat-model.md', mediaType: 'text/markdown' }, { path: 'threatmodel.md', mediaType: 'text/markdown' });
991
- const artifacts = [];
992
- for (const file of sealFiles) {
993
- options?.signal?.throwIfAborted();
994
- const data = await readFile(joinWithin(dir, file.path));
995
- artifacts.push({ path: file.path, sha256: sha256(data), mediaType: file.mediaType });
999
+ if (threatModel !== undefined) {
1000
+ const rendered = renderThreatModel(threatModel);
1001
+ sealedFiles.push({ path: 'threat-model.md', mediaType: 'text/markdown', content: rendered }, { path: 'threatmodel.md', mediaType: 'text/markdown', content: rendered });
996
1002
  }
1003
+ const artifacts = sealedFiles.map((file) => ({ path: file.path, sha256: sha256(file.content), mediaType: file.mediaType }));
997
1004
  for (const artifact of record.artifacts) {
998
1005
  options?.signal?.throwIfAborted();
999
1006
  const data = await readFile(joinWithin(dir, artifact.path));
@@ -1041,6 +1048,10 @@ export class SecurityService {
1041
1048
  },
1042
1049
  };
1043
1050
  assertArtifactContract('scan-manifest', manifest);
1051
+ for (const file of sealedFiles) {
1052
+ options?.signal?.throwIfAborted();
1053
+ await writeFileAtomic(joinWithin(dir, file.path), file.content);
1054
+ }
1044
1055
  await writeJsonAtomic(join(dir, 'scan-manifest.json'), manifest);
1045
1056
  const counts = severityCounts(findings);
1046
1057
  options?.signal?.throwIfAborted();
@@ -1262,6 +1273,12 @@ export class SecurityService {
1262
1273
  const requestedOutput = requested
1263
1274
  ? resolvePath(requested)
1264
1275
  : join(this.store.stateDir, 'exports', scanId + '.' + extension);
1276
+ const stateRoot = await canonicalProspectivePath(this.store.stateDir);
1277
+ const exportsRoot = await canonicalProspectivePath(join(this.store.stateDir, 'exports'));
1278
+ const canonicalOutput = await canonicalProspectivePath(requestedOutput);
1279
+ if (isWithin(stateRoot, canonicalOutput) && !isWithin(exportsRoot, canonicalOutput)) {
1280
+ throw new Error('codex-security: refusing to export into scan storage outside the exports directory: ' + requestedOutput);
1281
+ }
1265
1282
  const allowedRoots = await Promise.all([this.store.stateDir, process.cwd(), record.target.rootPath].map(canonicalProspectivePath));
1266
1283
  const scanRoot = join(this.store.stateDir, 'repositories');
1267
1284
  let requireGit = record.target.kind !== 'directory_snapshot';
package/lib/store.js CHANGED
@@ -5,6 +5,19 @@ import { acquireStateLock } from './state-lock.js';
5
5
  /** Files owned by the seal step; agents cannot overwrite them through save_artifact. */
6
6
  const SEALED_FILES = new Set(['scan.json', 'findings.json', 'coverage.json', 'scan-manifest.json', 'sarif.json', 'report.md', 'threat-model.md', 'threatmodel.md']);
7
7
  const INTERNAL_FILES = new Set([...SEALED_FILES, 'candidates.json', 'validations.json', 'attack-paths.json', 'review-items.json', 'triage.json']);
8
+ /**
9
+ * Fold an artifact path into the form Win32 uses when resolving it. Windows
10
+ * filesystems are case-insensitive and silently drop trailing dots and spaces,
11
+ * so 'SCAN.JSON', 'Scan.json.' and 'checkpoints\scan-draft.json' all address
12
+ * the same file as their lowercase spelling. Compare guard names in this folded
13
+ * form while keeping the original spelling on disk.
14
+ */
15
+ function guardName(relativePath) {
16
+ return relativePath
17
+ .split('/')
18
+ .map((segment) => segment.replace(/[ .]+$/, '').toLowerCase())
19
+ .join('/');
20
+ }
8
21
  export function defaultStateDir(patchPath, configured) {
9
22
  if (configured.length > 0)
10
23
  return configured;
@@ -211,7 +224,8 @@ export class ScanStore {
211
224
  if (found.record.status !== 'running')
212
225
  throw new Error('codex-security: cannot change artifacts after scan is ' + found.record.status);
213
226
  const clean = sanitizeRelative(relativePath);
214
- if (INTERNAL_FILES.has(clean) || clean === 'checkpoints' || clean.startsWith('checkpoints/'))
227
+ const guarded = guardName(clean);
228
+ if (INTERNAL_FILES.has(guarded) || guarded === 'checkpoints' || guarded.startsWith('checkpoints/'))
215
229
  throw new Error('codex-security: cannot overwrite internal scan path: ' + clean);
216
230
  const target = joinWithin(found.dir, clean);
217
231
  const data = Buffer.from(content, 'utf8');
@@ -249,7 +263,7 @@ export class ScanStore {
249
263
  for (const entry of entries) {
250
264
  const rel = relBase.length > 0 ? relBase + '/' + entry.name : entry.name;
251
265
  if (entry.isDirectory()) {
252
- if (relBase.length === 0 && entry.name === 'checkpoints')
266
+ if (relBase.length === 0 && guardName(entry.name) === 'checkpoints')
253
267
  continue;
254
268
  await walk(join(dir, entry.name), rel);
255
269
  continue;
@@ -258,7 +272,7 @@ export class ScanStore {
258
272
  continue;
259
273
  if (/^\.\d+\.(?:\d+\.[a-f0-9]{8}|[a-f0-9]{24})\.tmp$/.test(entry.name))
260
274
  continue;
261
- if (relBase.length === 0 && SEALED_FILES.has(entry.name))
275
+ if (relBase.length === 0 && SEALED_FILES.has(guardName(entry.name)))
262
276
  continue;
263
277
  const { stat } = await import('node:fs/promises');
264
278
  const info = await stat(join(dir, entry.name)).catch((error) => {
package/lib/target.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { lstat, realpath, stat } from 'node:fs/promises';
2
2
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
3
3
  import { createHash } from 'node:crypto';
4
- import { isProbablyBinary, isWithin, languageOf, listFiles, matchesAny, matchesScopePath, normalizeLine, sanitizeRelative, stableTargetId, truncate } from './util.js';
4
+ import { isProbablyBinary, isWithin, joinWithin, languageOf, listFiles, matchesAny, matchesScopePath, normalizeLine, stableTargetId, truncate } from './util.js';
5
5
  import { changedFiles, currentBranch, fileDigest, headRevision, remoteUrl, repoRoot, resolveRevision, statusEntries, trackedFiles } from './git.js';
6
6
  const DEFAULT_EXCLUDES = ['.git/**', 'node_modules/**', 'dist/**', 'build/**', 'out/**', 'coverage/**', '.next/**', '.nuxt/**', 'vendor/**', 'target/**', '.venv/**', '__pycache__/**', '*.min.js', '*.min.css', '*.map', '*.lock', 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'Cargo.lock', 'poetry.lock', 'uv.lock', 'composer.lock', 'go.sum'];
7
7
  export async function resolveTarget(options) {
@@ -179,18 +179,41 @@ export async function resolveDiff(rootPath, options) {
179
179
  /** Read one source line for anchor derivation without trusting it as instructions. */
180
180
  export async function readEvidenceLine(rootPath, path, line, maxBytes) {
181
181
  const { open } = await import('node:fs/promises');
182
+ const { constants } = await import('node:fs');
182
183
  if (!Number.isFinite(line) || line < 1)
183
184
  return undefined;
185
+ if (typeof path !== 'string' || path.length === 0)
186
+ return undefined;
187
+ let absolute;
188
+ try {
189
+ absolute = joinWithin(rootPath, path);
190
+ }
191
+ catch {
192
+ return undefined;
193
+ }
194
+ const realRoot = await realpath(rootPath).catch(() => undefined);
195
+ if (!realRoot)
196
+ return undefined;
184
197
  let handle;
185
198
  try {
186
- const absolute = resolve(rootPath, sanitizeRelative(path));
187
- if (!isWithin(rootPath, absolute))
199
+ const before = await lstat(absolute).catch(() => undefined);
200
+ if (!before || !before.isFile())
201
+ return undefined;
202
+ const flags = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
203
+ handle = await open(absolute, flags);
204
+ const opened = await handle.stat();
205
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino || opened.size !== before.size)
206
+ return undefined;
207
+ // Parent directories are not covered by O_NOFOLLOW, so a symlinked parent
208
+ // could still redirect the read outside the target. Resolve the opened
209
+ // path and require it to stay inside the real target root and to still
210
+ // name the inode we actually opened.
211
+ const canonical = await realpath(absolute).catch(() => undefined);
212
+ if (!canonical || !isWithin(realRoot, canonical))
188
213
  return undefined;
189
- const realRoot = await realpath(rootPath).catch(() => rootPath);
190
- const real = await realpath(absolute).catch(() => undefined);
191
- if (real && !isWithin(realRoot, real))
214
+ const current = await lstat(canonical).catch(() => undefined);
215
+ if (!current || !current.isFile() || current.dev !== opened.dev || current.ino !== opened.ino || current.size !== opened.size)
192
216
  return undefined;
193
- handle = await open(absolute, 'r');
194
217
  const buffer = Buffer.alloc(Math.min(maxBytes, 256 * 1024));
195
218
  const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
196
219
  const text = buffer.subarray(0, bytesRead).toString('utf8');
package/lib/tools.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { compileToolArguments } from './schema.js';
2
- import { readDeepStatus } from './deep-coordinator.js';
2
+ import { hasDeepJournal, readDeepStatus } from './deep-coordinator.js';
3
3
  const OUTPUT_SCHEMA = { type: 'object', additionalProperties: true };
4
4
  const STRING = { type: 'string' };
5
5
  const STRING_ARRAY = { type: 'array', items: { type: 'string' } };
@@ -84,7 +84,7 @@ export function createSecurityTools(service, getCoordinator = () => undefined) {
84
84
  }, ['scanId'], (args, exec) => coordinator().resume(args, exec), 60000),
85
85
  tool('codex_security_get_deep_scan_status', 'Read durable Deep orchestration status and budget usage without exposing the recovery claim.', {
86
86
  scanId: SCAN_ID,
87
- }, ['scanId'], (args) => readDeepStatus(service, String(args['scanId'])), 60000),
87
+ }, ['scanId'], (args, exec) => readDeepStatus(service, String(args['scanId']), exec), 60000),
88
88
  tool('codex_security_get_scan_context', 'Read the current state of a scan: record, progress, draft presence, candidate/validation/attack-path counts, review items and saved artifacts. Call this when resuming work or after a context loss.', { scanId: SCAN_ID }, ['scanId'], (args) => service.getScanContext(args), 60000),
89
89
  tool('codex_security_update_scan_context', 'Append notes or store a threat model. The bound include/exclude scope cannot be changed.', {
90
90
  scanId: SCAN_ID, notes: STRING, threatModel: JSON_OBJECT, includePaths: INCLUDE_PATHS, excludePaths: EXCLUDE_PATHS,
@@ -136,16 +136,8 @@ export function createSecurityTools(service, getCoordinator = () => undefined) {
136
136
  }, ['scanId'], async (args, exec) => {
137
137
  const record = await service.store.get(String(args['scanId']));
138
138
  let managed = record?.record.managedParent === args['scanId'];
139
- if (!record) {
140
- try {
141
- await readDeepStatus(service, String(args['scanId']));
142
- managed = true;
143
- }
144
- catch (error) {
145
- if (!(error instanceof Error) || !error.message.includes('Deep scan journal not found'))
146
- throw error;
147
- }
148
- }
139
+ if (!record && await hasDeepJournal(service, String(args['scanId'])))
140
+ managed = true;
149
141
  return managed ? coordinator().cancel(args, exec) : service.cancelScan(args);
150
142
  }, 60000),
151
143
  tool('codex_security_list_scans', 'List saved scans with status, mode, target, finding counts and severity counts. Filter by status/mode/target substring. Use it to find previous scans for comparison or triage.', {
@@ -1,11 +1,10 @@
1
1
  export declare const PACKAGE_NAME = "@lornatang/dsh-codex-security";
2
2
  export declare const PLUGIN_NAME = "codex-security";
3
- export declare const VERSION = "0.1.9";
3
+ export declare const VERSION = "0.1.11";
4
4
  export declare const ROUTE_PREFIX = "/plugins/codex-security";
5
5
  export declare const PRODUCER: {
6
6
  name: string;
7
7
  version: string;
8
8
  };
9
- export declare const DEFAULT_EXCLUDES: string[];
10
9
  export declare const SKILL_NAMES: string[];
11
10
  export declare const TOOL_NAMES: string[];
@@ -26,7 +26,9 @@ export interface DeepHost {
26
26
  }): Promise<DeepActivation>;
27
27
  }
28
28
  /** Public status omits the recovery-claim digest, source snapshots and worker output. */
29
- export declare function readDeepStatus(service: SecurityService, scanId: string): Promise<Json>;
29
+ export declare function readDeepStatus(service: SecurityService, scanId: string, actor: DeepActor): Promise<Json>;
30
+ /** Whether a Deep journal exists for a scan id, without disclosing its contents. */
31
+ export declare function hasDeepJournal(service: SecurityService, scanId: string): Promise<boolean>;
30
32
  /** Owns a Deep campaign until it seals or is interrupted. State lives on disk, not in this instance. */
31
33
  export declare class DeepCoordinator {
32
34
  private readonly service;
@@ -44,6 +44,10 @@ export declare class WorkerRegistry {
44
44
  acceptFinalStep(childId: string, position: StepPosition): void;
45
45
  read(childId: string, path: string): Promise<string>;
46
46
  private readText;
47
+ /** Reuse the bytes verified by the preceding read; fall back to a fresh verified read. */
48
+ private cachedText;
49
+ /** Cache the verified text so chunk acceptance does not re-read whole files. */
50
+ private cacheText;
47
51
  readChunk(childId: string, path: string, offset: number): Promise<{
48
52
  path: string;
49
53
  content: string;
@@ -5,7 +5,6 @@ export interface GitResult {
5
5
  }
6
6
  export declare function git(root: string, args: string[], timeoutMs?: number, signal?: AbortSignal): Promise<GitResult>;
7
7
  export declare function gitString(root: string, args: string[], timeoutMs?: number, signal?: AbortSignal): Promise<string | undefined>;
8
- export declare function isGitRepo(root: string): Promise<boolean>;
9
8
  export declare function repoRoot(path: string, signal?: AbortSignal): Promise<string | undefined>;
10
9
  export declare function headRevision(root: string, signal?: AbortSignal): Promise<string | undefined>;
11
10
  export declare function currentBranch(root: string, signal?: AbortSignal): Promise<string | undefined>;
@@ -27,6 +26,4 @@ export declare function changedFiles(root: string, options: {
27
26
  staged?: boolean;
28
27
  workingTree?: boolean;
29
28
  }): Promise<ChangedFile[]>;
30
- /** Digest of the working tree diff including untracked files, used for snapshot identity. */
31
- export declare function worktreeDigest(root: string): Promise<string>;
32
29
  export declare function fileDigest(path: string, signal?: AbortSignal): Promise<string | undefined>;
@@ -6,8 +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.9";
10
- export declare const packageName = "@lornatang/dsh-codex-security";
9
+ export declare const version = "0.1.11";
11
10
  export { SecurityService };
12
11
  export type { ConfigType };
13
12
  export declare function loadBundledSkills(packageRoot: string): SkillRegistration[];
@@ -1,7 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import type { SecurityService } from './service.js';
3
3
  import type { PluginContext } from './types.js';
4
- declare function scanIdFromPath(pathname: string): string | undefined;
5
4
  export declare function handleRequest(service: SecurityService, req: IncomingMessage, res: ServerResponse): Promise<void>;
6
5
  export declare function bindRoutes(ctx: PluginContext, service: SecurityService): () => void;
7
- export { scanIdFromPath };
@@ -12,7 +12,6 @@ export interface SecurityServiceOptions {
12
12
  export declare class SecurityService {
13
13
  readonly store: ScanStore;
14
14
  readonly config: Config;
15
- private readonly ctx;
16
15
  private readonly scanLocks;
17
16
  private readonly managedInvocations;
18
17
  constructor(ctx: PluginContext, options?: SecurityServiceOptions);
@@ -3,18 +3,14 @@ export declare function sha256(value: string | Uint8Array): string;
3
3
  export declare function stableTargetId(rootPath: string): string;
4
4
  export declare function nowIso(): string;
5
5
  export declare function newId(prefix: string, hexChars?: number): string;
6
- export declare function shortId(value: string, length?: number): string;
7
6
  export declare function ensureDir(path: string): Promise<void>;
8
7
  export declare function writeFileAtomic(path: string, data: string | Uint8Array): Promise<void>;
9
- /** Publish a complete file without ever replacing an existing destination. */
10
- export declare function writeFileExclusive(path: string, data: string | Uint8Array): Promise<void>;
11
8
  /** Resolve symlinked ancestors even when the final path does not yet exist. */
12
9
  export declare function canonicalProspectivePath(path: string): Promise<string>;
13
10
  export declare function writeJsonAtomic(path: string, value: unknown): Promise<void>;
14
11
  export declare function readJson<T>(path: string): Promise<T | undefined>;
15
12
  export declare function readText(path: string, limit?: number): Promise<string | undefined>;
16
13
  export declare function readFullText(path: string): Promise<string | undefined>;
17
- export declare function posixRelative(root: string, path: string): string;
18
14
  /** Reject absolute paths, drive letters and .. segments; return a normalized posix relative path. */
19
15
  export declare function sanitizeRelative(input: string): string;
20
16
  export declare function isWithin(parent: string, child: string): boolean;
@@ -29,7 +25,6 @@ export declare function languageOf(path: string): string;
29
25
  export declare function slugify(value: string, max?: number): string;
30
26
  export declare function compareSeverity(a: string, b: string): number;
31
27
  export declare function truncate(value: string, max: number): string;
32
- export declare function formatBytes(value: number): string;
33
28
  export declare function listFiles(root: string, options: {
34
29
  maxFiles: number;
35
30
  exclude: string[];
package/lib/util.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
- import { link, mkdir, open, readFile, readdir, realpath, rename, rm } from 'node:fs/promises';
2
+ import { mkdir, open, readFile, readdir, realpath, rename, rm } from 'node:fs/promises';
3
3
  import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
5
  export function sha256(value) {
@@ -15,9 +15,6 @@ export function nowIso() {
15
15
  export function newId(prefix, hexChars = 24) {
16
16
  return prefix + randomBytes(Math.ceil(hexChars / 2)).toString('hex').slice(0, hexChars);
17
17
  }
18
- export function shortId(value, length = 8) {
19
- return value.slice(0, length);
20
- }
21
18
  export async function ensureDir(path) {
22
19
  await mkdir(path, { recursive: true, mode: 0o700 });
23
20
  }
@@ -53,37 +50,6 @@ export async function writeFileAtomic(path, data) {
53
50
  throw error;
54
51
  }
55
52
  }
56
- /** Publish a complete file without ever replacing an existing destination. */
57
- export async function writeFileExclusive(path, data) {
58
- const tmp = join(dirname(path), '.' + process.pid + '.' + randomBytes(12).toString('hex') + '.tmp');
59
- const handle = await open(tmp, 'wx', 0o600);
60
- try {
61
- try {
62
- await handle.writeFile(data);
63
- }
64
- finally {
65
- await handle.close();
66
- }
67
- try {
68
- await link(tmp, path);
69
- }
70
- catch (error) {
71
- // Some writable filesystems do not support hard links.
72
- if (!['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS'].includes(error.code ?? ''))
73
- throw error;
74
- const destination = await open(path, 'wx', 0o600);
75
- try {
76
- await destination.writeFile(data);
77
- }
78
- finally {
79
- await destination.close();
80
- }
81
- }
82
- }
83
- finally {
84
- await rm(tmp, { force: true });
85
- }
86
- }
87
53
  /** Resolve symlinked ancestors even when the final path does not yet exist. */
88
54
  export async function canonicalProspectivePath(path) {
89
55
  let current = resolve(path);
@@ -146,9 +112,6 @@ export async function readFullText(path) {
146
112
  throw error;
147
113
  }
148
114
  }
149
- export function posixRelative(root, path) {
150
- return relative(root, path).split(sep).join('/');
151
- }
152
115
  /** Reject absolute paths, drive letters and .. segments; return a normalized posix relative path. */
153
116
  export function sanitizeRelative(input) {
154
117
  if (typeof input !== 'string' || input.length === 0)
@@ -373,13 +336,6 @@ export function compareSeverity(a, b) {
373
336
  export function truncate(value, max) {
374
337
  return value.length <= max ? value : value.slice(0, Math.max(0, max - 1)) + '\u2026';
375
338
  }
376
- export function formatBytes(value) {
377
- if (value < 1024)
378
- return value + ' B';
379
- if (value < 1024 * 1024)
380
- return (value / 1024).toFixed(1) + ' KB';
381
- return (value / (1024 * 1024)).toFixed(1) + ' MB';
382
- }
383
339
  export async function listFiles(root, options) {
384
340
  const files = [];
385
341
  const excluded = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lornatang/dsh-codex-security",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "Agent-native security review workbench for DeepSeek Harness, modeled on OpenAI codex-security: sealed scans, findings contract, deep-scan orchestration and SARIF/JSON export.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -91,7 +91,7 @@
91
91
  "@deepseek-ai/dsh-subagent-spawn-in-process": "0.2.2-rc.2",
92
92
  "@deepseek-ai/dsh-tool-executor-native": "0.2.2-rc.2",
93
93
  "@deepseek-ai/dsh-tools": "0.2.2-rc.2",
94
- "@types/node": "^22.18.0",
94
+ "@types/node": "^26.6.6",
95
95
  "@types/react": "^18.3.31",
96
96
  "typescript": "^5.9.0"
97
97
  },
@@ -13,7 +13,7 @@ Include any caller-supplied rendered investigation time allowance unchanged amon
13
13
  5. Delegate independent packet groups when parallel review is useful, within the caller's worker allowance. Point each worker to its readable copy of [the investigator brief](focused-investigator.md) and send its packets with the same authorized source and security context. For packets you handle in the parent, read the investigator brief and follow its investigation instructions yourself. Choose assignments by complexity and shared code rather than a fixed worker or file count. Supporting code may explain an in-scope finding, but its affected entry point, control, or operation must remain in scope.
14
14
  6. Preserve returned candidates and counterevidence through the bound `record_codex_security_scan_draft` tool when available, before combining or validating them. Use `complete: false`, stable `candidateId` values, and `reviewState.deferred` entries with a reason and the original payload under `candidate`. Checkpoint validation decisions: accepted findings retain `provenance.candidateId`; rejections retain the candidate identity, original evidence, and source-backed counterevidence on a `rejected` coverage surface. Record reviewed surfaces, exclusions, and unresolved questions without creating extra receipts or claiming exhaustive coverage. Group observations only when they share the broken control and effective remediation, preserving affected routes, operations, and locations; a shared CWE alone is not a reason to merge.
15
15
  7. Follow the caller’s validation handoff if supplied. Otherwise [validate each distinct candidate](validate-scan-findings.md) against the source.
16
- 8. Assemble `scope`, `threatModel`, `findings`, and `reviewState` following `final-report.md` and `schemas/tools/scan-draft.schema.json`. Follow `finding-detail-fields.md` for rich evidence and narrative fields. Preserve genuine findings, source provenance, supplied assumptions, exclusions, pending work, and uncertainty. Examples under `examples/completed-scan/` illustrate shape, not values to copy.
16
+ 8. Assemble `scope`, `threatModel`, `findings`, and `reviewState` following `final-report.md`. Follow `finding-detail-fields.md` for rich evidence and narrative fields. Preserve genuine findings, source provenance, supplied assumptions, exclusions, pending work, and uncertainty. Examples under `examples/completed-scan/` illustrate shape, not values to copy.
17
17
 
18
18
  Keep discovery, validation, and attack-path reasoning within this one self-contained audit; do not invoke separate phase skills or add ranking phases, per-file ledgers, separate phase worker pools, or receipt files.
19
19
 
@@ -17,7 +17,7 @@ Completion validates existing artifacts; it does not perform missing phases or c
17
17
 
18
18
  ## Finding Semantics
19
19
 
20
- Use `schemas/tools/scan-draft.schema.json` for new drafts and `finding-detail-fields.md` for rich fields. Supply:
20
+ Use `finding-detail-fields.md` for rich fields. Supply:
21
21
 
22
22
  - An evidence-supported lowercase vulnerability-family `ruleId`, `taxonomy.category`, known `taxonomy.cwe` values (or `[]`), and genuine `provenance.source`. Use `local_plugin` only for findings this plugin discovered; preserve worker/source provenance and candidate identity.
23
23
  - Verified source locations, including the broken control or sink and materially affected entry points or concrete implementations. Preserve independently vulnerable instances. Group observations only when they share the broken control and remediation, not merely a CWE.
@@ -183,7 +183,7 @@ These fields are optional for compatibility with existing v1 canonical artifacts
183
183
 
184
184
  ## Schemas
185
185
 
186
- New completed findings must match the [scan draft schema](../schemas/tools/scan-draft.schema.json). Finalization rejects legacy field aliases, malformed optional details, and invalid semantic slugs instead of repairing them. Historical sealed reports are validated through an in-memory compatibility adapter; their saved bytes remain unchanged. Stopped-scan recovery still salvages saved evidence.
186
+ New completed findings must match the [findings schema](../schemas/findings.schema.json). Finalization rejects legacy field aliases, malformed optional details, and invalid semantic slugs instead of repairing them. Historical sealed reports are validated through an in-memory compatibility adapter; their saved bytes remain unchanged. Stopped-scan recovery still salvages saved evidence.
187
187
 
188
188
  - [Scan manifest schema](../schemas/scan-manifest.schema.json)
189
189
  - [Findings schema](../schemas/findings.schema.json)