@quantakrypto/core 0.5.0 → 0.6.0

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 (46) hide show
  1. package/dist/crypto-agility.d.ts +158 -0
  2. package/dist/crypto-agility.d.ts.map +1 -0
  3. package/dist/crypto-agility.js +285 -0
  4. package/dist/crypto-agility.js.map +1 -0
  5. package/dist/dependencies.d.ts.map +1 -1
  6. package/dist/dependencies.js +180 -18
  7. package/dist/dependencies.js.map +1 -1
  8. package/dist/detectors/source.d.ts.map +1 -1
  9. package/dist/detectors/source.js +52 -0
  10. package/dist/detectors/source.js.map +1 -1
  11. package/dist/hndl.d.ts +241 -0
  12. package/dist/hndl.d.ts.map +1 -0
  13. package/dist/hndl.js +752 -0
  14. package/dist/hndl.js.map +1 -0
  15. package/dist/index.d.ts +4 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +4 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/parallel.d.ts.map +1 -1
  20. package/dist/parallel.js +22 -23
  21. package/dist/parallel.js.map +1 -1
  22. package/dist/report.d.ts +8 -0
  23. package/dist/report.d.ts.map +1 -1
  24. package/dist/report.js +75 -19
  25. package/dist/report.js.map +1 -1
  26. package/dist/types.d.ts +1 -1
  27. package/dist/types.d.ts.map +1 -1
  28. package/dist/types.js.map +1 -1
  29. package/dist/version.d.ts +1 -1
  30. package/dist/version.js +1 -1
  31. package/dist/version.js.map +1 -1
  32. package/dist/walk.d.ts +31 -1
  33. package/dist/walk.d.ts.map +1 -1
  34. package/dist/walk.js +30 -9
  35. package/dist/walk.js.map +1 -1
  36. package/package.json +1 -1
  37. package/src/crypto-agility.ts +407 -0
  38. package/src/dependencies.ts +182 -16
  39. package/src/detectors/source.ts +62 -0
  40. package/src/hndl.ts +1012 -0
  41. package/src/index.ts +52 -0
  42. package/src/parallel.ts +21 -20
  43. package/src/report.ts +84 -19
  44. package/src/types.ts +9 -1
  45. package/src/version.ts +1 -1
  46. package/src/walk.ts +47 -10
package/dist/walk.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"walk.js","sourceRoot":"","sources":["../src/walk.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD,8EAA8E;AAC9E,MAAM,eAAe,GAAsB;IACzC,cAAc;IACd,MAAM;IACN,MAAM;IACN,OAAO;IACP,OAAO;IACP,KAAK;IACL,UAAU;IACV,QAAQ;IACR,QAAQ;IACR,QAAQ;CACT,CAAC;AAEF,gDAAgD;AAChD,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAErD;;;GAGG;AACH,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAS;IACxC,SAAS;IACT,MAAM;IACN,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,MAAM;IACN,MAAM;IACN,OAAO;IACP,OAAO;IACP,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,MAAM;IACN,MAAM;IACN,MAAM;IACN,wBAAwB;IACxB,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,KAAK;IACL,KAAK;IACL,MAAM;IACN,MAAM;IACN,QAAQ;IACR,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,uBAAuB;IACvB,MAAM;IACN,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,MAAM;IACN,MAAM;IACN,KAAK;IACL,QAAQ;IACR,MAAM;IACN,IAAI;IACJ,IAAI;IACJ,QAAQ;IACR,OAAO;IACP,kBAAkB;IAClB,KAAK;IACL,SAAS;IACT,UA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SAAS;YAC3C,KAAK,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;YAC9B,SAAS;QACX,CAAC;QAED,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE;YAAE,SAAS;QAC9B,IAAI,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,CAAC;YAAE,SAAS;QAC3C,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,CAAC;YAAE,SAAS;QAC5C,4EAA4E;QAC5E,8EAA8E;QAC9E,MAAM,QAAQ,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;QACrC,IAAI,CAAC,QAAQ,IAAI,YAAY,CAAC,GAAG,CAAC;YAAE,SAAS;QAC7C,IAAI,CAAC,QAAQ,IAAI,eAAe,CAAC,GAAG,CAAC;YAAE,SAAS;QAEhD,IAAI,CAAC;YACH,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,CAAC;YAC1B,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,WAAW,CAAC;gBAAE,SAAS;QAC/D,CAAC;QAAC,MAAM,CAAC;YACP,SAAS;QACX,CAAC;QAED,MAAM,GAAG,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["/**\n * Filesystem walker. A zero-dependency recursive async generator that yields\n * scannable text files as relative POSIX paths. It honours a default ignore\n * list, user-supplied exclude patterns, a max file size, and a binary-extension\n * filter. The root may be a directory or a single file.\n */\nimport { readdir, stat } from \"node:fs/promises\";\nimport type { Dirent } from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { isManifestFile } from \"./dependencies.js\";\n\n/** Directories ignored by default (can be disabled with noDefaultIgnores). */\nconst DEFAULT_IGNORES: readonly string[] = [\n \"node_modules\",\n \".git\",\n \"dist\",\n \"build\",\n \".next\",\n \"out\",\n \"coverage\",\n \"vendor\",\n \".turbo\",\n \".cache\",\n];\n\n/** Default maximum file size to read: 2 MiB. */\nexport const DEFAULT_MAX_FILE_SIZE = 2 * 1024 * 1024;\n\n/**\n * File extensions we treat as binary / non-text and therefore skip. Keeping this\n * as an extension allow-list-by-exclusion is cheap and avoids reading bytes.\n */\nconst BINARY_EXTENSIONS = new Set<string>([\n // images\n \".png\",\n \".jpg\",\n \".jpeg\",\n \".gif\",\n \".webp\",\n \".bmp\",\n \".ico\",\n \".tiff\",\n \".avif\",\n // fonts\n \".woff\",\n \".woff2\",\n \".ttf\",\n \".otf\",\n \".eot\",\n // archives / compressed\n \".zip\",\n \".gz\",\n \".tgz\",\n \".bz2\",\n \".xz\",\n \".7z\",\n \".rar\",\n \".tar\",\n // media\n \".mp3\",\n \".mp4\",\n \".mov\",\n \".avi\",\n \".mkv\",\n \".wav\",\n \".flac\",\n \".ogg\",\n \".webm\",\n // documents / binaries\n \".pdf\",\n \".doc\",\n \".docx\",\n \".xls\",\n \".xlsx\",\n \".ppt\",\n \".pptx\",\n \".exe\",\n \".dll\",\n \".so\",\n \".dylib\",\n \".bin\",\n \".o\",\n \".a\",\n \".class\",\n \".wasm\",\n // data blobs / db\n \".db\",\n \".sqlite\",\n \".sqlite3\",\n \".dat\",\n \".pack\",\n \".idx\",\n // misc\n \".lock\",\n \".map\",\n \".min.js\",\n \".node\",\n]);\n\n/** Options accepted by {@link walkFiles}. */\ninterface WalkOptions {\n /**\n * Restrict to paths matching one of these include patterns (substring or\n * relative-path-prefix match). When omitted/empty, all files pass.\n */\n include?: string[];\n /** Extra exclude patterns (substring or relative-path-prefix match). */\n exclude?: string[];\n /** Disable the built-in directory ignore list. */\n noDefaultIgnores?: boolean;\n /** Max file size in bytes; larger files are skipped. */\n maxFileSize?: number;\n}\n\n/** Normalise a path to forward-slash POSIX separators. */\nexport function toPosix(p: string): string {\n return p.split(path.sep).join(\"/\");\n}\n\n/** A pattern is treated as a glob when it contains one of these metacharacters. */\nfunction hasGlobMeta(pattern: string): boolean {\n return /[*?[]/.test(pattern);\n}\n\n/**\n * Translate a glob into an anchored RegExp: `*` matches within a path segment\n * (not `/`), `**` matches across segments, a leading `**` before a slash is an\n * optional path prefix, `?` matches a single non-`/` char, `[...]` is a\n * character class. Other regex\n * metacharacters are escaped.\n */\nfunction globToRegExp(glob: string): RegExp {\n let re = \"\";\n for (let i = 0; i < glob.length; i++) {\n const c = glob[i];\n if (c === \"*\") {\n if (glob[i + 1] === \"*\") {\n i++; // consume the second '*'\n if (glob[i + 1] === \"/\") {\n i++; // consume the trailing '/'\n re += \"(?:.*/)?\"; // zero or more path segments\n } else {\n re += \".*\"; // '**' spanning segments\n }\n } else {\n re += \"[^/]*\"; // '*' within a segment\n }\n } else if (c === \"?\") {\n re += \"[^/]\";\n } else if (c === \"[\") {\n // Pass a character class through; find its closing ']'.\n const end = glob.indexOf(\"]\", i + 1);\n if (end === -1) {\n re += \"\\\\[\";\n } else {\n re += glob.slice(i, end + 1);\n i = end;\n }\n } else if (\"\\\\^$.|+(){}\".includes(c)) {\n re += \"\\\\\" + c;\n } else {\n re += c;\n }\n }\n return new RegExp(`^${re}$`);\n}\n\n/** Memoized glob→RegExp so a pattern is compiled once, not once per file. */\nconst GLOB_CACHE = new Map<string, RegExp>();\nfunction globRegExp(pattern: string): RegExp {\n let re = GLOB_CACHE.get(pattern);\n if (!re) {\n re = globToRegExp(pattern);\n GLOB_CACHE.set(pattern, re);\n }\n return re;\n}\n\n/**\n * True if `rel` (a POSIX relative path) matches any pattern. A pattern with a\n * glob metacharacter (`*`, `?`, `[`) is matched as an anchored glob; a plain\n * pattern keeps the historical substring / path-prefix semantics (so `\"src\"`\n * still matches `src/a.ts` and `\"secrets\"` matches anywhere).\n */\nexport function matchesAny(rel: string, patterns: readonly string[]): boolean {\n for (const pattern of patterns) {\n if (!pattern) continue;\n const p = toPosix(pattern).replace(/\\/+$/, \"\");\n if (hasGlobMeta(p)) {\n if (globRegExp(p).test(rel)) return true;\n continue;\n }\n // Plain pattern: substring match (handles \"src/legacy\" or \"secrets\")...\n if (rel.includes(p)) return true;\n // ...and explicit path-prefix match (\"foo\" should match \"foo/bar.ts\").\n if (rel === p || rel.startsWith(`${p}/`)) return true;\n }\n return false;\n}\n\n/** True if `rel` (a POSIX relative path) matches any exclude pattern. */\nfunction isExcluded(rel: string, exclude: readonly string[]): boolean {\n return matchesAny(rel, exclude);\n}\n\n/**\n * True if `rel` passes the include filter. An empty include list means \"include\n * everything\"; otherwise the file must match at least one include pattern.\n */\nfunction isIncluded(rel: string, include: readonly string[]): boolean {\n if (include.length === 0) return true;\n return matchesAny(rel, include);\n}\n\n/** True if the file's extension marks it as binary / non-text. */\nexport function isBinaryPath(rel: string): boolean {\n const lower = rel.toLowerCase();\n // Handle compound extensions like \".min.js\" first.\n if (lower.endsWith(\".min.js\")) return true;\n const ext = path.posix.extname(lower);\n return BINARY_EXTENSIONS.has(ext);\n}\n\n/**\n * Binary cryptographic key containers we DO want to scan — Java/PKCS#12 keystores\n * and binary OpenPGP keyrings/messages. Unlike the images/archives above these are\n * read byte-preserving (latin1) and exempted from the minified skip, so the\n * keystore + openpgp detectors can identify them by magic number / packet tag.\n * Kept separate from {@link BINARY_EXTENSIONS} so those detectors can opt in.\n */\nconst KEYSTORE_EXTENSIONS = new Set<string>([\n \".jks\",\n \".keystore\",\n \".jceks\",\n \".bks\",\n \".p12\",\n \".pfx\",\n // Binary OpenPGP keyrings / messages (armored .asc is text; handled elsewhere).\n \".gpg\",\n \".pgp\",\n \".kbx\",\n]);\n\n/**\n * True if the path is a binary cryptographic key container we scan byte-preserving.\n * Uses a suffix match (not `extname`) so it agrees with the detectors' `hasExtension`\n * even for a bare dotfile literally named e.g. `.gpg` (where `extname` returns \"\").\n */\nexport function isKeystorePath(rel: string): boolean {\n const lower = rel.toLowerCase();\n for (const ext of KEYSTORE_EXTENSIONS) if (lower.endsWith(ext)) return true;\n return false;\n}\n\n/**\n * Compound / pattern extensions that mark generated or bundled output we skip\n * by default (beyond `.min.js` / `.map`, which {@link isBinaryPath} handles).\n */\nconst GENERATED_PATH_RE =\n /(?:\\.min\\.[mc]?js|[.-]min\\.[mc]?js|\\.bundle\\.[mc]?js|\\.chunk\\.[mc]?js|\\.generated\\.[jt]sx?|_pb\\.js|\\.pb\\.go)$/i;\n\n/** True if the path looks like generated / bundled output (by name). */\nexport function isGeneratedPath(rel: string): boolean {\n return GENERATED_PATH_RE.test(rel.toLowerCase());\n}\n\n/**\n * Heuristic content check for machine-minified / generated files with no\n * telltale extension: a very long average line length, or any single line over\n * ~50 KB, in the first ~64 KB sampled. Used at read time, not in the walker.\n */\nexport function looksMinified(content: string): boolean {\n const sample = content.length > 65_536 ? content.slice(0, 65_536) : content;\n if (sample.length === 0) return false;\n let maxLine = 0;\n let cur = 0;\n let lines = 1;\n for (let i = 0; i < sample.length; i++) {\n if (sample.charCodeAt(i) === 10 /* \\n */) {\n if (cur > maxLine) maxLine = cur;\n cur = 0;\n lines++;\n } else {\n cur++;\n }\n }\n if (cur > maxLine) maxLine = cur;\n if (maxLine > 50_000) return true;\n const avgLine = sample.length / lines;\n return avgLine > 1_000;\n}\n\n/**\n * Recursively yield scannable file paths (relative to `root`, POSIX) under a\n * directory. If `root` points at a single file, yields just that file's\n * basename (subject to the size / binary filters).\n */\nexport async function* walkFiles(root: string, options: WalkOptions = {}): AsyncGenerator<string> {\n const include = options.include ?? [];\n const exclude = options.exclude ?? [];\n const maxFileSize = options.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n const ignores = options.noDefaultIgnores ? [] : DEFAULT_IGNORES;\n\n const rootStat = await stat(root);\n\n // Single-file mode: yield the file itself (by basename) if it passes filters.\n if (rootStat.isFile()) {\n const name = toPosix(path.basename(root));\n if (\n !isBinaryPath(name) &&\n isIncluded(name, include) &&\n passesSizeLimit(name, rootStat.size, maxFileSize)\n ) {\n yield name;\n }\n return;\n }\n\n yield* walkDir(root, \"\", { include, exclude, maxFileSize, ignores });\n}\n\ninterface WalkContext {\n include: readonly string[];\n exclude: readonly string[];\n maxFileSize: number;\n ignores: readonly string[];\n}\n\n/**\n * True if a file passes the size limit. Dependency manifests (package.json /\n * package-lock.json) are exempt from the cap so large lockfiles still get\n * scanned for vulnerable dependencies instead of being silently dropped.\n */\nfunction passesSizeLimit(rel: string, size: number, maxFileSize: number): boolean {\n // Dependency manifests are always read (they can exceed the size cap but carry\n // the whole dependency tree). Uses the single {@link isManifestFile} definition.\n if (isManifestFile(rel)) return true;\n return size <= maxFileSize;\n}\n\n/** Internal recursive directory walker. `relDir` is POSIX-relative to the root. */\nasync function* walkDir(absDir: string, relDir: string, ctx: WalkContext): AsyncGenerator<string> {\n let entries: Dirent[];\n try {\n entries = await readdir(absDir, { withFileTypes: true });\n } catch {\n // Unreadable directory (permissions, transient races) — skip silently.\n return;\n }\n\n // Stable, deterministic ordering for reproducible scans.\n entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n\n for (const entry of entries) {\n const rel = relDir ? `${relDir}/${entry.name}` : entry.name;\n const abs = path.join(absDir, entry.name);\n\n if (entry.isSymbolicLink()) {\n // Don't follow symlinks: avoids cycles and escaping the root.\n continue;\n }\n\n if (entry.isDirectory()) {\n if (ctx.ignores.includes(entry.name)) continue;\n if (isExcluded(rel, ctx.exclude)) continue;\n yield* walkDir(abs, rel, ctx);\n continue;\n }\n\n if (!entry.isFile()) continue;\n if (isExcluded(rel, ctx.exclude)) continue;\n if (!isIncluded(rel, ctx.include)) continue;\n // Dependency manifests (incl. yarn.lock / pnpm-lock.yaml) are always read —\n // they carry the dependency tree and must not be dropped as binary/generated.\n const manifest = isManifestFile(rel);\n if (!manifest && isBinaryPath(rel)) continue;\n if (!manifest && isGeneratedPath(rel)) continue;\n\n try {\n const s = await stat(abs);\n if (!passesSizeLimit(rel, s.size, ctx.maxFileSize)) continue;\n } catch {\n continue;\n }\n\n yield rel;\n }\n}\n"]}
1
+ {"version":3,"file":"walk.js","sourceRoot":"","sources":["../src/walk.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,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YAC3B,8DAA8D;YAC9D,SAAS;QACX,CAAC;QAED,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;YACxB,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC;gBAAE,SAAS;YAC/C,IAAI,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,CAAC;gBAAE,SAAS;YAC3C,KAAK,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;YAC9B,SAAS;QACX,CAAC;QAED,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE;YAAE,SAAS;QAC9B,IAAI,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,CAAC;YAAE,SAAS;QAC3C,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,CAAC;YAAE,SAAS;QAC5C,4EAA4E;QAC5E,8EAA8E;QAC9E,MAAM,QAAQ,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;QACrC,IAAI,CAAC,QAAQ,IAAI,YAAY,CAAC,GAAG,CAAC;YAAE,SAAS;QAC7C,IAAI,CAAC,QAAQ,IAAI,eAAe,CAAC,GAAG,CAAC;YAAE,SAAS;QAEhD,IAAI,IAAY,CAAC;QACjB,IAAI,CAAC;YACH,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,CAAC;YAC1B,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,WAAW,CAAC;gBAAE,SAAS;YAC7D,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC;QAChB,CAAC;QAAC,MAAM,CAAC;YACP,SAAS;QACX,CAAC;QAED,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC;IACtB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Filesystem walker. A zero-dependency recursive async generator that yields\n * scannable text files as relative POSIX paths. It honours a default ignore\n * list, user-supplied exclude patterns, a max file size, and a binary-extension\n * filter. The root may be a directory or a single file.\n */\nimport { readdir, stat } from \"node:fs/promises\";\nimport type { Dirent } from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { isManifestFile } from \"./dependencies.js\";\n\n/** Directories ignored by default (can be disabled with noDefaultIgnores). */\nconst DEFAULT_IGNORES: readonly string[] = [\n \"node_modules\",\n \".git\",\n \"dist\",\n \"build\",\n \".next\",\n \"out\",\n \"coverage\",\n \"vendor\",\n \".turbo\",\n \".cache\",\n];\n\n/** Default maximum file size to read: 2 MiB. */\nexport const DEFAULT_MAX_FILE_SIZE = 2 * 1024 * 1024;\n\n/**\n * File extensions we treat as binary / non-text and therefore skip. Keeping this\n * as an extension allow-list-by-exclusion is cheap and avoids reading bytes.\n */\nconst BINARY_EXTENSIONS = new Set<string>([\n // images\n \".png\",\n \".jpg\",\n \".jpeg\",\n \".gif\",\n \".webp\",\n \".bmp\",\n \".ico\",\n \".tiff\",\n \".avif\",\n // fonts\n \".woff\",\n \".woff2\",\n \".ttf\",\n \".otf\",\n \".eot\",\n // archives / compressed\n \".zip\",\n \".gz\",\n \".tgz\",\n \".bz2\",\n \".xz\",\n \".7z\",\n \".rar\",\n \".tar\",\n // media\n \".mp3\",\n \".mp4\",\n \".mov\",\n \".avi\",\n \".mkv\",\n \".wav\",\n \".flac\",\n \".ogg\",\n \".webm\",\n // documents / binaries\n \".pdf\",\n \".doc\",\n \".docx\",\n \".xls\",\n \".xlsx\",\n \".ppt\",\n \".pptx\",\n \".exe\",\n \".dll\",\n \".so\",\n \".dylib\",\n \".bin\",\n \".o\",\n \".a\",\n \".class\",\n \".wasm\",\n // data blobs / db\n \".db\",\n \".sqlite\",\n \".sqlite3\",\n \".dat\",\n \".pack\",\n \".idx\",\n // misc\n \".lock\",\n \".map\",\n \".min.js\",\n \".node\",\n]);\n\n/** Options accepted by {@link walkFiles}. */\ninterface WalkOptions {\n /**\n * Restrict to paths matching one of these include patterns (substring or\n * relative-path-prefix match). When omitted/empty, all files pass.\n */\n include?: string[];\n /** Extra exclude patterns (substring or relative-path-prefix match). */\n exclude?: string[];\n /** Disable the built-in directory ignore list. */\n noDefaultIgnores?: boolean;\n /** Max file size in bytes; larger files are skipped. */\n maxFileSize?: number;\n}\n\n/** Normalise a path to forward-slash POSIX separators. */\nexport function toPosix(p: string): string {\n return p.split(path.sep).join(\"/\");\n}\n\n/** A pattern is treated as a glob when it contains one of these metacharacters. */\nfunction hasGlobMeta(pattern: string): boolean {\n return /[*?[]/.test(pattern);\n}\n\n/**\n * Translate a glob into an anchored RegExp: `*` matches within a path segment\n * (not `/`), `**` matches across segments, a leading `**` before a slash is an\n * optional path prefix, `?` matches a single non-`/` char, `[...]` is a\n * character class. Other regex\n * metacharacters are escaped.\n */\nfunction globToRegExp(glob: string): RegExp {\n let re = \"\";\n for (let i = 0; i < glob.length; i++) {\n const c = glob[i];\n if (c === \"*\") {\n if (glob[i + 1] === \"*\") {\n i++; // consume the second '*'\n if (glob[i + 1] === \"/\") {\n i++; // consume the trailing '/'\n re += \"(?:.*/)?\"; // zero or more path segments\n } else {\n re += \".*\"; // '**' spanning segments\n }\n } else {\n re += \"[^/]*\"; // '*' within a segment\n }\n } else if (c === \"?\") {\n re += \"[^/]\";\n } else if (c === \"[\") {\n // Pass a character class through; find its closing ']'.\n const end = glob.indexOf(\"]\", i + 1);\n if (end === -1) {\n re += \"\\\\[\";\n } else {\n re += glob.slice(i, end + 1);\n i = end;\n }\n } else if (\"\\\\^$.|+(){}\".includes(c)) {\n re += \"\\\\\" + c;\n } else {\n re += c;\n }\n }\n return new RegExp(`^${re}$`);\n}\n\n/** Memoized glob→RegExp so a pattern is compiled once, not once per file. */\nconst GLOB_CACHE = new Map<string, RegExp>();\nfunction globRegExp(pattern: string): RegExp {\n let re = GLOB_CACHE.get(pattern);\n if (!re) {\n re = globToRegExp(pattern);\n GLOB_CACHE.set(pattern, re);\n }\n return re;\n}\n\n/**\n * True if `rel` (a POSIX relative path) matches any pattern. A pattern with a\n * glob metacharacter (`*`, `?`, `[`) is matched as an anchored glob; a plain\n * pattern keeps the historical substring / path-prefix semantics (so `\"src\"`\n * still matches `src/a.ts` and `\"secrets\"` matches anywhere).\n */\nexport function matchesAny(rel: string, patterns: readonly string[]): boolean {\n for (const pattern of patterns) {\n if (!pattern) continue;\n const p = toPosix(pattern).replace(/\\/+$/, \"\");\n if (hasGlobMeta(p)) {\n if (globRegExp(p).test(rel)) return true;\n continue;\n }\n // Plain pattern: substring match (handles \"src/legacy\" or \"secrets\")...\n if (rel.includes(p)) return true;\n // ...and explicit path-prefix match (\"foo\" should match \"foo/bar.ts\").\n if (rel === p || rel.startsWith(`${p}/`)) return true;\n }\n return false;\n}\n\n/** True if `rel` (a POSIX relative path) matches any exclude pattern. */\nfunction isExcluded(rel: string, exclude: readonly string[]): boolean {\n return matchesAny(rel, exclude);\n}\n\n/**\n * True if `rel` passes the include filter. An empty include list means \"include\n * everything\"; otherwise the file must match at least one include pattern.\n */\nfunction isIncluded(rel: string, include: readonly string[]): boolean {\n if (include.length === 0) return true;\n return matchesAny(rel, include);\n}\n\n/** True if the file's extension marks it as binary / non-text. */\nexport function isBinaryPath(rel: string): boolean {\n const lower = rel.toLowerCase();\n // Handle compound extensions like \".min.js\" first.\n if (lower.endsWith(\".min.js\")) return true;\n const ext = path.posix.extname(lower);\n return BINARY_EXTENSIONS.has(ext);\n}\n\n/**\n * Binary cryptographic key containers we DO want to scan — Java/PKCS#12 keystores\n * and binary OpenPGP keyrings/messages. Unlike the images/archives above these are\n * read byte-preserving (latin1) and exempted from the minified skip, so the\n * keystore + openpgp detectors can identify them by magic number / packet tag.\n * Kept separate from {@link BINARY_EXTENSIONS} so those detectors can opt in.\n */\nconst KEYSTORE_EXTENSIONS = new Set<string>([\n \".jks\",\n \".keystore\",\n \".jceks\",\n \".bks\",\n \".p12\",\n \".pfx\",\n // Binary OpenPGP keyrings / messages (armored .asc is text; handled elsewhere).\n \".gpg\",\n \".pgp\",\n \".kbx\",\n]);\n\n/**\n * True if the path is a binary cryptographic key container we scan byte-preserving.\n * Uses a suffix match (not `extname`) so it agrees with the detectors' `hasExtension`\n * even for a bare dotfile literally named e.g. `.gpg` (where `extname` returns \"\").\n */\nexport function isKeystorePath(rel: string): boolean {\n const lower = rel.toLowerCase();\n for (const ext of KEYSTORE_EXTENSIONS) if (lower.endsWith(ext)) return true;\n return false;\n}\n\n/**\n * Compound / pattern extensions that mark generated or bundled output we skip\n * by default (beyond `.min.js` / `.map`, which {@link isBinaryPath} handles).\n */\nconst GENERATED_PATH_RE =\n /(?:\\.min\\.[mc]?js|[.-]min\\.[mc]?js|\\.bundle\\.[mc]?js|\\.chunk\\.[mc]?js|\\.generated\\.[jt]sx?|_pb\\.js|\\.pb\\.go)$/i;\n\n/** True if the path looks like generated / bundled output (by name). */\nexport function isGeneratedPath(rel: string): boolean {\n return GENERATED_PATH_RE.test(rel.toLowerCase());\n}\n\n/**\n * Heuristic content check for machine-minified / generated files with no\n * telltale extension: a very long average line length, or any single line over\n * ~50 KB, in the first ~64 KB sampled. Used at read time, not in the walker.\n */\nexport function looksMinified(content: string): boolean {\n const sample = content.length > 65_536 ? content.slice(0, 65_536) : content;\n if (sample.length === 0) return false;\n let maxLine = 0;\n let cur = 0;\n let lines = 1;\n for (let i = 0; i < sample.length; i++) {\n if (sample.charCodeAt(i) === 10 /* \\n */) {\n if (cur > maxLine) maxLine = cur;\n cur = 0;\n lines++;\n } else {\n cur++;\n }\n }\n if (cur > maxLine) maxLine = cur;\n if (maxLine > 50_000) return true;\n const avgLine = sample.length / lines;\n return avgLine > 1_000;\n}\n\n/** A scannable file plus the byte size the walker already stat'd for it. */\nexport interface WalkedFile {\n /** Relative POSIX path from the walk root. */\n rel: string;\n /** File size in bytes (from the walker's own stat; never re-stat downstream). */\n size: number;\n}\n\n/**\n * Recursively yield scannable file paths (relative to `root`, POSIX) under a\n * directory. If `root` points at a single file, yields just that file's\n * basename (subject to the size / binary filters). Thin wrapper over\n * {@link walkFilesSized} that drops the size (the historical string-yielding API).\n */\nexport async function* walkFiles(root: string, options: WalkOptions = {}): AsyncGenerator<string> {\n for await (const f of walkFilesSized(root, options)) yield f.rel;\n}\n\n/**\n * Like {@link walkFiles} but yields each file WITH the byte size the walker\n * already obtained while applying the size limit. Callers that need sizes (the\n * parallel scanner's byte-balanced chunking) consume this directly so they do\n * not stat every file a second time (P2 double-stat elimination).\n */\nexport async function* walkFilesSized(\n root: string,\n options: WalkOptions = {},\n): AsyncGenerator<WalkedFile> {\n const include = options.include ?? [];\n const exclude = options.exclude ?? [];\n const maxFileSize = options.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n const ignores = options.noDefaultIgnores ? [] : DEFAULT_IGNORES;\n\n const rootStat = await stat(root);\n\n // Single-file mode: yield the file itself (by basename) if it passes filters.\n if (rootStat.isFile()) {\n const name = toPosix(path.basename(root));\n if (\n !isBinaryPath(name) &&\n isIncluded(name, include) &&\n passesSizeLimit(name, rootStat.size, maxFileSize)\n ) {\n yield { rel: name, size: rootStat.size };\n }\n return;\n }\n\n yield* walkDir(root, \"\", { include, exclude, maxFileSize, ignores });\n}\n\ninterface WalkContext {\n include: readonly string[];\n exclude: readonly string[];\n maxFileSize: number;\n ignores: readonly string[];\n}\n\n/**\n * Manifests bypass the normal file-size cap (they carry the whole dependency\n * tree and must not be dropped), but still get a generous hard ceiling so a\n * pathological or hostile lockfile can't be read unbounded and OOM the scan.\n * 16 MiB comfortably covers real monorepo lockfiles (npm's own is well under 5).\n */\nexport const MANIFEST_MAX_BYTES = 16 * 1024 * 1024;\n\n/**\n * True if a file passes the size limit. Dependency manifests (package.json /\n * package-lock.json / yarn.lock / …) get the larger {@link MANIFEST_MAX_BYTES}\n * ceiling instead of the ordinary cap, so large lockfiles still get scanned for\n * vulnerable dependencies without letting an enormous one exhaust memory.\n * Exported for unit testing.\n */\nexport function passesSizeLimit(rel: string, size: number, maxFileSize: number): boolean {\n // Uses the single {@link isManifestFile} definition.\n if (isManifestFile(rel)) return size <= MANIFEST_MAX_BYTES;\n return size <= maxFileSize;\n}\n\n/** Internal recursive directory walker. `relDir` is POSIX-relative to the root. */\nasync function* walkDir(\n absDir: string,\n relDir: string,\n ctx: WalkContext,\n): AsyncGenerator<WalkedFile> {\n let entries: Dirent[];\n try {\n entries = await readdir(absDir, { withFileTypes: true });\n } catch {\n // Unreadable directory (permissions, transient races) — skip silently.\n return;\n }\n\n // Stable, deterministic ordering for reproducible scans.\n entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n\n for (const entry of entries) {\n const rel = relDir ? `${relDir}/${entry.name}` : entry.name;\n const abs = path.join(absDir, entry.name);\n\n if (entry.isSymbolicLink()) {\n // Don't follow symlinks: avoids cycles and escaping the root.\n continue;\n }\n\n if (entry.isDirectory()) {\n if (ctx.ignores.includes(entry.name)) continue;\n if (isExcluded(rel, ctx.exclude)) continue;\n yield* walkDir(abs, rel, ctx);\n continue;\n }\n\n if (!entry.isFile()) continue;\n if (isExcluded(rel, ctx.exclude)) continue;\n if (!isIncluded(rel, ctx.include)) continue;\n // Dependency manifests (incl. yarn.lock / pnpm-lock.yaml) are always read —\n // they carry the dependency tree and must not be dropped as binary/generated.\n const manifest = isManifestFile(rel);\n if (!manifest && isBinaryPath(rel)) continue;\n if (!manifest && isGeneratedPath(rel)) continue;\n\n let size: number;\n try {\n const s = await stat(abs);\n if (!passesSizeLimit(rel, s.size, ctx.maxFileSize)) continue;\n size = s.size;\n } catch {\n continue;\n }\n\n yield { rel, size };\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quantakrypto/core",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Shared post-quantum readiness library: crypto detectors, vulnerable-dependency database, inventory + SARIF reporting. Zero runtime dependencies.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Dandelion Labs <hello@dandelionlabs.io> (https://dandelionlabs.io)",
@@ -0,0 +1,407 @@
1
+ /**
2
+ * Crypto-agility manifest: an agent-consumable crypto-posture document.
3
+ *
4
+ * A small, versioned JSON manifest a project publishes at a well-known URL
5
+ * (`/.well-known/crypto-agility.json`, see docs/CRYPTO-AGILITY-MANIFEST.md) so any
6
+ * agent, scanner, or CI bot can read the project's cryptographic posture the way it
7
+ * reads `security.txt` or `robots.txt`. It is a compact, decision-oriented summary
8
+ * DERIVED from a qScan result: the readiness score, the count of quantum-vulnerable
9
+ * findings by severity, the CBOM's algorithm families, an optional attestation URL,
10
+ * and the migration-policy deadlines.
11
+ *
12
+ * This module owns two pure operations and their shared schema:
13
+ * - {@link buildCryptoAgilityManifest}: derive a manifest from a {@link ScanResult}.
14
+ * - {@link validateCryptoAgilityManifest}: check an untrusted value against the
15
+ * schema, returning a list of problems (used by the local validator; a network
16
+ * fetch-and-validate lives on the website, never in this offline-boundary tool).
17
+ *
18
+ * Zero dependencies; hand-rolled JSON shape and validation so the package stays
19
+ * runtime-dependency-free.
20
+ */
21
+
22
+ import { toCbom } from "./cbom.js";
23
+ import { PQC_STANDARDS } from "./standards.js";
24
+ import { SEVERITY_ORDER } from "./severity.js";
25
+ import type { CryptoPolicy } from "./policy.js";
26
+ import type { ScanResult, Severity } from "./types.js";
27
+ import { VERSION } from "./version.js";
28
+
29
+ /**
30
+ * Schema version of the manifest this module emits and validates. Bumped only on a
31
+ * breaking change to the manifest shape; consumers key their parsing off it.
32
+ */
33
+ export const CRYPTO_AGILITY_MANIFEST_VERSION = 1;
34
+
35
+ /** The conventional path a manifest is served from, relative to the site origin. */
36
+ export const CRYPTO_AGILITY_WELL_KNOWN_PATH = "/.well-known/crypto-agility.json";
37
+
38
+ /** A single algorithm family in use, mirroring the CBOM's grouping. */
39
+ export interface CryptoAgilityFamily {
40
+ /** The algorithm family (e.g. `RSA`, `ECDH`, `ECDSA`), or `unknown`. */
41
+ family: string;
42
+ /** How many findings referenced this family. */
43
+ count: number;
44
+ /** Always true today: every detected family is classical (Shor-broken). */
45
+ quantumVulnerable: boolean;
46
+ }
47
+
48
+ /** The project's cryptographic posture, distilled from the scan inventory. */
49
+ export interface CryptoAgilityPosture {
50
+ /** qScan readiness score, 0–100 (100 = no classical asymmetric crypto found). */
51
+ readinessScore: number;
52
+ /**
53
+ * Whether the project negotiates hybrid post-quantum key exchange. qScan is a
54
+ * static scanner and cannot observe a negotiated TLS group, so this is `null`
55
+ * ("not determined by this generator") unless the operator asserts it
56
+ * (`--hybrid-kex` / `--no-hybrid-kex`). A live probe (qProbe) or the website can
57
+ * fill it authoritatively.
58
+ */
59
+ hybridKexInUse: boolean | null;
60
+ /** Count of quantum-vulnerable findings, total and broken down by severity. */
61
+ quantumVulnerable: {
62
+ total: number;
63
+ bySeverity: Record<Severity, number>;
64
+ };
65
+ /** How many findings are exposed to harvest-now-decrypt-later. */
66
+ hndlExposedCount: number;
67
+ }
68
+
69
+ /** A compact summary of the full CBOM, linking to it by serial number. */
70
+ export interface CryptoAgilityCbomSummary {
71
+ /** The CycloneDX `serialNumber` of the full CBOM this summary was derived from. */
72
+ serialNumber: string;
73
+ /** Number of distinct cryptographic-asset components in the full CBOM. */
74
+ assetCount: number;
75
+ /** Algorithm families in use, most-referenced first. */
76
+ algorithmFamilies: CryptoAgilityFamily[];
77
+ }
78
+
79
+ /** The migration policy the project declares it is measured against. */
80
+ export interface CryptoAgilityPolicy {
81
+ /** Human label for the policy source (a standard name, or `operator-declared`). */
82
+ source: string;
83
+ /** Year after which classical public-key crypto is deprecated. */
84
+ deprecateClassicalAfter: number;
85
+ /** Year after which classical public-key crypto is disallowed. */
86
+ disallowClassicalAfter: number;
87
+ /** Operator-declared migration deadline (ISO date / year), or `null`. */
88
+ transitionDeadline: string | null;
89
+ /** Citation for the deadlines (spec / publication). */
90
+ citation: string;
91
+ }
92
+
93
+ /** The full crypto-agility manifest. */
94
+ export interface CryptoAgilityManifest {
95
+ /** Manifest schema version ({@link CRYPTO_AGILITY_MANIFEST_VERSION}). */
96
+ version: number;
97
+ /** Discriminator so a consumer can tell this document apart from other JSON. */
98
+ manifestType: "crypto-agility";
99
+ /** ISO 8601 timestamp the manifest was generated (caller-supplied). */
100
+ generatedAt: string;
101
+ /** What produced the manifest. */
102
+ generator: { name: string; version: string };
103
+ /** What the manifest describes. */
104
+ subject: { root: string; repository: string | null; commit: string | null };
105
+ /** The distilled cryptographic posture. */
106
+ posture: CryptoAgilityPosture;
107
+ /** A compact summary of the CBOM. */
108
+ cbomSummary: CryptoAgilityCbomSummary;
109
+ /** Optional link to a quantakrypto (or other) posture credential. */
110
+ attestation?: { url: string };
111
+ /** The declared migration policy / deadlines. */
112
+ policy: CryptoAgilityPolicy;
113
+ }
114
+
115
+ /** Inputs the CLI/runtime supplies that are not derivable from the scan. */
116
+ export interface CryptoAgilityManifestOptions {
117
+ /**
118
+ * ISO 8601 generation timestamp. The caller supplies it (`Date.now()` is fine in
119
+ * the CLI runtime) so the builder itself stays pure and deterministic.
120
+ */
121
+ generatedAt: string;
122
+ /** Optional URL to a posture credential (recorded verbatim, never fetched here). */
123
+ attestationUrl?: string;
124
+ /**
125
+ * Operator assertion of hybrid-KEX use. `undefined` leaves the manifest's
126
+ * `hybridKexInUse` as `null` (not determined).
127
+ */
128
+ hybridKexInUse?: boolean;
129
+ /** Optional org crypto policy; its `transitionDeadline` overlays the defaults. */
130
+ policy?: CryptoPolicy;
131
+ /** Repository URL (e.g. `GITHUB_REPOSITORY`); omitted → null. */
132
+ repository?: string;
133
+ /** Commit SHA (e.g. `GITHUB_SHA`); omitted → null. */
134
+ commit?: string;
135
+ }
136
+
137
+ /**
138
+ * Build a crypto-agility manifest from a scan result. Pure: every runtime input
139
+ * (timestamp, attestation, hybrid-KEX assertion, policy) arrives via `opts`.
140
+ *
141
+ * The posture and CBOM summary are derived straight from the scan's inventory and
142
+ * its CycloneDX CBOM, so the manifest can never disagree with the full `--cbom` /
143
+ * `--format json` outputs of the same scan.
144
+ */
145
+ export function buildCryptoAgilityManifest(
146
+ result: ScanResult,
147
+ opts: CryptoAgilityManifestOptions,
148
+ ): CryptoAgilityManifest {
149
+ const cbom = toCbom(result);
150
+ const inv = result.inventory;
151
+
152
+ const algorithmFamilies: CryptoAgilityFamily[] = Object.entries(inv.byAlgorithm)
153
+ .filter(([, count]) => (count ?? 0) > 0)
154
+ .map(([family, count]) => ({
155
+ family,
156
+ count: count as number,
157
+ // Every family the detectors surface is classical, hence quantum-vulnerable
158
+ // by construction (mirrors cbom.ts `isQuantumVulnerable`).
159
+ quantumVulnerable: true,
160
+ }))
161
+ .sort((a, b) => b.count - a.count || a.family.localeCompare(b.family));
162
+
163
+ const bySeverity = { ...inv.bySeverity };
164
+
165
+ // Default policy: the NIST IR 8547 transition timeline. An operator crypto policy
166
+ // (`--policy`) does not override the standards deadlines but layers its own
167
+ // `transitionDeadline` on top and re-labels the source as operator-declared.
168
+ const timeline = PQC_STANDARDS.transitionTimeline;
169
+ const policy: CryptoAgilityPolicy = {
170
+ source: opts.policy ? "operator-declared" : timeline.source,
171
+ deprecateClassicalAfter: timeline.deprecateAfter,
172
+ disallowClassicalAfter: timeline.disallowAfter,
173
+ transitionDeadline: opts.policy?.transitionDeadline ?? null,
174
+ citation: timeline.source,
175
+ };
176
+
177
+ const manifest: CryptoAgilityManifest = {
178
+ version: CRYPTO_AGILITY_MANIFEST_VERSION,
179
+ manifestType: "crypto-agility",
180
+ generatedAt: opts.generatedAt,
181
+ generator: { name: "qScan", version: result.toolVersion || VERSION },
182
+ subject: {
183
+ root: result.root,
184
+ repository: opts.repository ?? null,
185
+ commit: opts.commit ?? null,
186
+ },
187
+ posture: {
188
+ readinessScore: inv.readinessScore,
189
+ hybridKexInUse: opts.hybridKexInUse ?? null,
190
+ quantumVulnerable: {
191
+ total: result.findings.length,
192
+ bySeverity,
193
+ },
194
+ hndlExposedCount: inv.hndlCount,
195
+ },
196
+ cbomSummary: {
197
+ serialNumber: cbom.serialNumber,
198
+ assetCount: cbom.components.length,
199
+ algorithmFamilies,
200
+ },
201
+ ...(opts.attestationUrl ? { attestation: { url: opts.attestationUrl } } : {}),
202
+ policy,
203
+ };
204
+ return manifest;
205
+ }
206
+
207
+ /** Outcome of {@link validateCryptoAgilityManifest}. */
208
+ export interface ManifestValidation {
209
+ /** True when the value satisfies the manifest schema. */
210
+ valid: boolean;
211
+ /** One human-readable message per problem found (empty when `valid`). */
212
+ errors: string[];
213
+ }
214
+
215
+ /** True for a plain (non-array, non-null) object. */
216
+ function isObject(v: unknown): v is Record<string, unknown> {
217
+ return typeof v === "object" && v !== null && !Array.isArray(v);
218
+ }
219
+
220
+ /**
221
+ * Validate an untrusted value against the crypto-agility manifest schema.
222
+ *
223
+ * Checks structure, required fields, types, and the schema version. Purely local:
224
+ * it parses an already-in-memory value and NEVER performs I/O or network fetches;
225
+ * a fetch-and-validate of a remote manifest is a website-side concern, deliberately
226
+ * kept out of this offline-boundary tool. Returns every problem it finds rather than
227
+ * throwing on the first, so a caller can report them all at once.
228
+ */
229
+ export function validateCryptoAgilityManifest(value: unknown): ManifestValidation {
230
+ const errors: string[] = [];
231
+ const err = (m: string): void => void errors.push(m);
232
+
233
+ if (!isObject(value)) {
234
+ return { valid: false, errors: ["manifest must be a JSON object"] };
235
+ }
236
+
237
+ // version
238
+ if (value.version === undefined) {
239
+ err("missing required field: version");
240
+ } else if (typeof value.version !== "number" || !Number.isInteger(value.version)) {
241
+ err("version must be an integer");
242
+ } else if (value.version !== CRYPTO_AGILITY_MANIFEST_VERSION) {
243
+ err(
244
+ `unsupported version ${value.version} (this validator understands version ${CRYPTO_AGILITY_MANIFEST_VERSION})`,
245
+ );
246
+ }
247
+
248
+ // manifestType
249
+ if (value.manifestType === undefined) {
250
+ err("missing required field: manifestType");
251
+ } else if (value.manifestType !== "crypto-agility") {
252
+ err('manifestType must be the string "crypto-agility"');
253
+ }
254
+
255
+ // generatedAt
256
+ if (value.generatedAt === undefined) {
257
+ err("missing required field: generatedAt");
258
+ } else if (typeof value.generatedAt !== "string" || value.generatedAt.length === 0) {
259
+ err("generatedAt must be a non-empty ISO 8601 string");
260
+ } else if (Number.isNaN(Date.parse(value.generatedAt))) {
261
+ err("generatedAt must be a parseable ISO 8601 timestamp");
262
+ }
263
+
264
+ // generator
265
+ if (value.generator === undefined) {
266
+ err("missing required field: generator");
267
+ } else if (!isObject(value.generator)) {
268
+ err("generator must be an object");
269
+ } else {
270
+ if (typeof value.generator.name !== "string") err("generator.name must be a string");
271
+ if (typeof value.generator.version !== "string") err("generator.version must be a string");
272
+ }
273
+
274
+ // subject
275
+ if (value.subject === undefined) {
276
+ err("missing required field: subject");
277
+ } else if (!isObject(value.subject)) {
278
+ err("subject must be an object");
279
+ } else {
280
+ if (typeof value.subject.root !== "string") err("subject.root must be a string");
281
+ if (value.subject.repository !== null && typeof value.subject.repository !== "string") {
282
+ err("subject.repository must be a string or null");
283
+ }
284
+ if (value.subject.commit !== null && typeof value.subject.commit !== "string") {
285
+ err("subject.commit must be a string or null");
286
+ }
287
+ }
288
+
289
+ // posture
290
+ validatePosture(value.posture, err);
291
+
292
+ // cbomSummary
293
+ validateCbomSummary(value.cbomSummary, err);
294
+
295
+ // attestation (optional)
296
+ if (value.attestation !== undefined) {
297
+ if (!isObject(value.attestation)) {
298
+ err("attestation must be an object when present");
299
+ } else if (typeof value.attestation.url !== "string" || value.attestation.url.length === 0) {
300
+ err("attestation.url must be a non-empty string");
301
+ }
302
+ }
303
+
304
+ // policy
305
+ validatePolicy(value.policy, err);
306
+
307
+ return { valid: errors.length === 0, errors };
308
+ }
309
+
310
+ /** Validate the `posture` block. */
311
+ function validatePosture(posture: unknown, err: (m: string) => void): void {
312
+ if (posture === undefined) {
313
+ err("missing required field: posture");
314
+ return;
315
+ }
316
+ if (!isObject(posture)) {
317
+ err("posture must be an object");
318
+ return;
319
+ }
320
+ if (
321
+ typeof posture.readinessScore !== "number" ||
322
+ posture.readinessScore < 0 ||
323
+ posture.readinessScore > 100
324
+ ) {
325
+ err("posture.readinessScore must be a number between 0 and 100");
326
+ }
327
+ if (posture.hybridKexInUse !== null && typeof posture.hybridKexInUse !== "boolean") {
328
+ err("posture.hybridKexInUse must be a boolean or null");
329
+ }
330
+ if (typeof posture.hndlExposedCount !== "number" || posture.hndlExposedCount < 0) {
331
+ err("posture.hndlExposedCount must be a non-negative number");
332
+ }
333
+ const qv = posture.quantumVulnerable;
334
+ if (!isObject(qv)) {
335
+ err("posture.quantumVulnerable must be an object");
336
+ return;
337
+ }
338
+ if (typeof qv.total !== "number" || qv.total < 0) {
339
+ err("posture.quantumVulnerable.total must be a non-negative number");
340
+ }
341
+ if (!isObject(qv.bySeverity)) {
342
+ err("posture.quantumVulnerable.bySeverity must be an object");
343
+ } else {
344
+ for (const sev of SEVERITY_ORDER) {
345
+ if (typeof qv.bySeverity[sev] !== "number") {
346
+ err(`posture.quantumVulnerable.bySeverity.${sev} must be a number`);
347
+ }
348
+ }
349
+ }
350
+ }
351
+
352
+ /** Validate the `cbomSummary` block. */
353
+ function validateCbomSummary(summary: unknown, err: (m: string) => void): void {
354
+ if (summary === undefined) {
355
+ err("missing required field: cbomSummary");
356
+ return;
357
+ }
358
+ if (!isObject(summary)) {
359
+ err("cbomSummary must be an object");
360
+ return;
361
+ }
362
+ if (typeof summary.serialNumber !== "string") err("cbomSummary.serialNumber must be a string");
363
+ if (typeof summary.assetCount !== "number" || summary.assetCount < 0) {
364
+ err("cbomSummary.assetCount must be a non-negative number");
365
+ }
366
+ if (!Array.isArray(summary.algorithmFamilies)) {
367
+ err("cbomSummary.algorithmFamilies must be an array");
368
+ return;
369
+ }
370
+ summary.algorithmFamilies.forEach((fam, i) => {
371
+ if (!isObject(fam)) {
372
+ err(`cbomSummary.algorithmFamilies[${i}] must be an object`);
373
+ return;
374
+ }
375
+ if (typeof fam.family !== "string")
376
+ err(`cbomSummary.algorithmFamilies[${i}].family must be a string`);
377
+ if (typeof fam.count !== "number" || fam.count < 0) {
378
+ err(`cbomSummary.algorithmFamilies[${i}].count must be a non-negative number`);
379
+ }
380
+ if (typeof fam.quantumVulnerable !== "boolean") {
381
+ err(`cbomSummary.algorithmFamilies[${i}].quantumVulnerable must be a boolean`);
382
+ }
383
+ });
384
+ }
385
+
386
+ /** Validate the `policy` block. */
387
+ function validatePolicy(policy: unknown, err: (m: string) => void): void {
388
+ if (policy === undefined) {
389
+ err("missing required field: policy");
390
+ return;
391
+ }
392
+ if (!isObject(policy)) {
393
+ err("policy must be an object");
394
+ return;
395
+ }
396
+ if (typeof policy.source !== "string") err("policy.source must be a string");
397
+ if (typeof policy.deprecateClassicalAfter !== "number") {
398
+ err("policy.deprecateClassicalAfter must be a number (year)");
399
+ }
400
+ if (typeof policy.disallowClassicalAfter !== "number") {
401
+ err("policy.disallowClassicalAfter must be a number (year)");
402
+ }
403
+ if (policy.transitionDeadline !== null && typeof policy.transitionDeadline !== "string") {
404
+ err("policy.transitionDeadline must be a string or null");
405
+ }
406
+ if (typeof policy.citation !== "string") err("policy.citation must be a string");
407
+ }