@dataparade/cli 0.0.35 → 0.1.1

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 (140) hide show
  1. package/README.md +1 -0
  2. package/dist/package.json +4 -4
  3. package/dist/src/ai-enrichment/pii-signal-rules.d.ts +5 -0
  4. package/dist/src/ai-enrichment/pii-signal-rules.js +2 -3
  5. package/dist/src/ai-enrichment/provider-prompt.js +1 -0
  6. package/dist/src/ai-enrichment/providers/provider-contract.js +2 -44
  7. package/dist/src/ai-enrichment/third-party-data-flow.js +5 -4
  8. package/dist/src/cli.js +9 -3
  9. package/dist/src/discoveries/contract/ocsf-discovery-record.d.ts +4 -1
  10. package/dist/src/discoveries/contract/ocsf-discovery-record.js +1 -1
  11. package/dist/src/discoveries/contract/ontology-pins.d.ts +6 -4
  12. package/dist/src/discoveries/contract/ontology-pins.js +7 -5
  13. package/dist/src/facts/build-facts.d.ts +2 -0
  14. package/dist/src/facts/build-facts.js +18 -0
  15. package/dist/src/facts/layout.d.ts +4 -0
  16. package/dist/src/facts/layout.js +5 -1
  17. package/dist/src/facts/scan-stamps.d.ts +7 -0
  18. package/dist/src/facts/scan-stamps.js +30 -0
  19. package/dist/src/facts/schema.d.ts +178 -0
  20. package/dist/src/facts/schema.js +37 -1
  21. package/dist/src/kb/data-category-catalog.generated.d.ts +34 -0
  22. package/dist/src/kb/data-category-catalog.generated.js +962 -0
  23. package/dist/src/kb/kb-store.js +4 -1
  24. package/dist/src/kb/migrate.js +4 -2
  25. package/dist/src/kb/slot-shapes.d.ts +3 -2
  26. package/dist/src/kb/slot-shapes.js +13 -8
  27. package/dist/src/kb/taxonomy.d.ts +12 -6
  28. package/dist/src/kb/taxonomy.js +13 -18
  29. package/dist/src/output/scan-output-excludes.js +2 -0
  30. package/dist/src/output/write-scan-knowledge.d.ts +5 -1
  31. package/dist/src/output/write-scan-knowledge.js +21 -0
  32. package/dist/src/threat-model/build-threat-model.d.ts +3 -0
  33. package/dist/src/threat-model/build-threat-model.js +71 -0
  34. package/dist/src/threat-model/carry-forward-person-set-statuses.d.ts +8 -0
  35. package/dist/src/threat-model/carry-forward-person-set-statuses.js +87 -0
  36. package/dist/src/threat-model/io.d.ts +19 -0
  37. package/dist/src/threat-model/io.js +63 -0
  38. package/dist/src/threat-model/schema.d.ts +214 -0
  39. package/dist/src/threat-model/schema.js +75 -0
  40. package/dist/src/ui/scan-progress-renderer.d.ts +8 -1
  41. package/dist/src/ui/scan-progress-renderer.js +20 -1
  42. package/dist/src/upload/collect-scan-sidecars.d.ts +2 -1
  43. package/dist/src/upload/collect-scan-sidecars.js +3 -1
  44. package/dist/tests/cli/cli.spec.js +10 -1
  45. package/dist/tests/helpers/facts-fixture.js +16 -16
  46. package/dist/tests/schema/scan-result.schema.spec.js +1 -1
  47. package/dist/tests/unit/ai-enrichment/provider-contract.spec.js +1 -1
  48. package/dist/tests/unit/ai-enrichment/third-party-data-flow.spec.js +5 -5
  49. package/dist/tests/unit/core/graph-mapping.spec.js +4 -3
  50. package/dist/tests/unit/discoveries/write-ocsf-discoveries-long-ids.spec.js +3 -3
  51. package/dist/tests/unit/export/export-ocsf.spec.js +4 -4
  52. package/dist/tests/unit/facts/apply-answers.spec.js +20 -20
  53. package/dist/tests/unit/facts/build-facts.spec.js +143 -45
  54. package/dist/tests/unit/facts/identity.spec.js +13 -0
  55. package/dist/tests/unit/facts/scan-stamps.spec.js +32 -0
  56. package/dist/tests/unit/facts/slug.spec.js +2 -0
  57. package/dist/tests/unit/kb/answer-fingerprint.spec.js +9 -9
  58. package/dist/tests/unit/kb/data-category-catalog.spec.d.ts +1 -0
  59. package/dist/tests/unit/kb/data-category-catalog.spec.js +65 -0
  60. package/dist/tests/unit/kb/kb-interview-loop.spec.js +8 -7
  61. package/dist/tests/unit/kb/migrate.spec.js +2 -2
  62. package/dist/tests/unit/output/scan-output-excludes.spec.js +1 -1
  63. package/dist/tests/unit/threat-model/build-threat-model.spec.d.ts +1 -0
  64. package/dist/tests/unit/threat-model/build-threat-model.spec.js +189 -0
  65. package/dist/tests/unit/threat-model/carry-forward-person-set-statuses.spec.d.ts +1 -0
  66. package/dist/tests/unit/threat-model/carry-forward-person-set-statuses.spec.js +163 -0
  67. package/dist/tests/unit/threat-model/io.spec.d.ts +1 -0
  68. package/dist/tests/unit/threat-model/io.spec.js +103 -0
  69. package/dist/tests/unit/threat-model/schema.spec.d.ts +1 -0
  70. package/dist/tests/unit/threat-model/schema.spec.js +42 -0
  71. package/dist/tests/unit/ui/scan-progress-renderer.spec.js +58 -0
  72. package/dist/tests/unit/upload/collect-scan-sidecars.spec.js +8 -5
  73. package/dist/vendor/scanner/dist/src/analyze/code-navigator.d.ts +1 -1
  74. package/dist/vendor/scanner/dist/src/analyze/code-navigator.js +4 -0
  75. package/dist/vendor/scanner/dist/src/analyze/column-catalog.d.ts +1 -1
  76. package/dist/vendor/scanner/dist/src/analyze/column-catalog.js +2 -2
  77. package/dist/vendor/scanner/dist/src/analyze/concept-profile.d.ts +2 -2
  78. package/dist/vendor/scanner/dist/src/analyze/concept-profile.js +5 -3
  79. package/dist/vendor/scanner/dist/src/core/pipeline/build-scan-personal-data-layers.js +1 -1
  80. package/dist/vendor/scanner/dist/src/core/pipeline/deterministic-scan.js +43 -0
  81. package/dist/vendor/scanner/dist/src/core/pipeline/graph-mapping.js +23 -2
  82. package/dist/vendor/scanner/dist/src/core/pipeline/mixed-app-terraform-scan.js +1 -0
  83. package/dist/vendor/scanner/dist/src/core/pipeline/orchestrator-result.d.ts +2 -2
  84. package/dist/vendor/scanner/dist/src/core/pipeline/terraform-minimal-services.js +1 -0
  85. package/dist/vendor/scanner/dist/src/core/schema/scan-result.schema.d.ts +160 -2
  86. package/dist/vendor/scanner/dist/src/core/schema/scan-result.schema.js +24 -0
  87. package/dist/vendor/scanner/dist/src/core/types/data-flow.d.ts +48 -0
  88. package/dist/vendor/scanner/dist/src/core/types/data-flow.js +53 -0
  89. package/dist/vendor/scanner/dist/src/data-flow/detect.js +1 -0
  90. package/dist/vendor/scanner/dist/src/data-flow/ensure-hub-linked-assets.js +1 -0
  91. package/dist/vendor/scanner/dist/src/data-flow/ensure-manifest-declared-flows.js +1 -0
  92. package/dist/vendor/scanner/dist/src/data-flow/flow-authentication.d.ts +30 -0
  93. package/dist/vendor/scanner/dist/src/data-flow/flow-authentication.js +277 -0
  94. package/dist/vendor/scanner/dist/src/data-flow/flow-builder.js +6 -0
  95. package/dist/vendor/scanner/dist/src/data-flow/flow-controls.d.ts +24 -0
  96. package/dist/vendor/scanner/dist/src/data-flow/flow-controls.js +238 -0
  97. package/dist/vendor/scanner/dist/src/data-flow/flow-data-categories.d.ts +22 -0
  98. package/dist/vendor/scanner/dist/src/data-flow/flow-data-categories.js +69 -0
  99. package/dist/vendor/scanner/dist/src/data-flow/flow-interaction-description.d.ts +13 -0
  100. package/dist/vendor/scanner/dist/src/data-flow/flow-interaction-description.js +263 -0
  101. package/dist/vendor/scanner/dist/src/data-flow/hub-link-policy.d.ts +2 -1
  102. package/dist/vendor/scanner/dist/src/data-flow/hub-link-policy.js +3 -0
  103. package/dist/vendor/scanner/dist/src/data-flow/human-interaction-channels.d.ts +37 -0
  104. package/dist/vendor/scanner/dist/src/data-flow/human-interaction-channels.js +483 -0
  105. package/dist/vendor/scanner/dist/src/data-flow/intra-component-lineage.d.ts +3 -0
  106. package/dist/vendor/scanner/dist/src/data-flow/intra-component-lineage.js +12 -17
  107. package/dist/vendor/scanner/dist/src/data-flow/terraform-flows.js +5 -1
  108. package/dist/vendor/scanner/dist/src/data-flow/transformation-patterns.d.ts +5 -1
  109. package/dist/vendor/scanner/dist/src/data-flow/transformation-patterns.js +17 -37
  110. package/dist/vendor/scanner/dist/src/eval/canonical/concept-map.d.ts +36 -5
  111. package/dist/vendor/scanner/dist/src/eval/canonical/concept-map.js +53 -60
  112. package/dist/vendor/scanner/dist/src/eval/canonical/graph/endpoints.js +2 -9
  113. package/dist/vendor/scanner/dist/src/eval/canonical/scanner/personal-data.js +10 -7
  114. package/dist/vendor/scanner/dist/src/graph/build-dataparade-graph.js +3 -1
  115. package/dist/vendor/scanner/dist/src/index.d.ts +6 -0
  116. package/dist/vendor/scanner/dist/src/index.js +16 -1
  117. package/dist/vendor/scanner/dist/src/patterns/engine.js +1 -0
  118. package/dist/vendor/scanner/dist/src/pii-signals/match-pii-signals.d.ts +1 -1
  119. package/dist/vendor/scanner/dist/src/pii-signals/match-pii-signals.js +2 -2
  120. package/dist/vendor/scanner/dist/src/pii-signals/occurrence-group.d.ts +3 -3
  121. package/dist/vendor/scanner/dist/src/pii-signals/occurrence-group.js +12 -11
  122. package/dist/vendor/scanner/dist/src/pii-signals/personal-data-taxonomy.d.ts +44 -0
  123. package/dist/vendor/scanner/dist/src/pii-signals/personal-data-taxonomy.js +167 -0
  124. package/dist/vendor/scanner/dist/src/pii-signals/pii-signal-aliases.js +43 -43
  125. package/dist/vendor/scanner/dist/src/pii-signals/pii-signal-rules.d.ts +12 -1
  126. package/dist/vendor/scanner/dist/src/pii-signals/pii-signal-rules.js +28 -7
  127. package/dist/vendor/scanner/dist/src/pii-signals/signal-token.js +1 -1
  128. package/dist/vendor/scanner/dist/src/threats/stride.d.ts +98 -0
  129. package/dist/vendor/scanner/dist/src/threats/stride.js +179 -0
  130. package/dist/vendor/scanner/package.json +2 -2
  131. package/dist/vendor/scanner/patterns/concept-profiles.yaml +2 -2
  132. package/dist/vendor/scanner/patterns/flow-authentication.rules.yaml +75 -0
  133. package/dist/vendor/scanner/patterns/flow-controls.rules.yaml +68 -0
  134. package/dist/vendor/scanner/patterns/personal-data-taxonomy.yaml +155 -0
  135. package/dist/vendor/scanner/patterns/pii-signals.rules.yaml +38 -49
  136. package/dist/vendor/scanner/patterns/stride.rules.yaml +86 -0
  137. package/package.json +4 -4
  138. package/dist/vendor/scanner/dist/src/eval/canonical/concept-map.validate.d.ts +0 -17
  139. package/dist/vendor/scanner/dist/src/eval/canonical/concept-map.validate.js +0 -108
  140. package/dist/vendor/scanner/patterns/personal-data-concept-map.yaml +0 -76
@@ -12,6 +12,7 @@ const fs_1 = __importDefault(require("fs"));
12
12
  const apply_answers_1 = require("../facts/apply-answers");
13
13
  Object.defineProperty(exports, "SYSTEM_FACT_ID", { enumerable: true, get: function () { return apply_answers_1.SYSTEM_FACT_ID; } });
14
14
  const io_1 = require("../facts/io");
15
+ const data_category_catalog_generated_1 = require("./data-category-catalog.generated");
15
16
  const layout_1 = require("../facts/layout");
16
17
  function resolveKbPaths(kbDir) {
17
18
  return (0, layout_1.layoutForDir)(kbDir);
@@ -70,7 +71,9 @@ function appliedStateToDocument(applied) {
70
71
  }),
71
72
  dataFlows: applied.facts.dataFlows.map((f) => {
72
73
  const extra = f;
73
- const categories = asStringList(extra.data_categories);
74
+ const answeredCategories = asStringList(extra.data_categories);
75
+ const resolvedCategories = answeredCategories ? (0, data_category_catalog_generated_1.resolveDataCategoryValues)(answeredCategories) : [];
76
+ const categories = resolvedCategories.length > 0 ? resolvedCategories : undefined;
74
77
  const purpose = asString(extra.purpose);
75
78
  return {
76
79
  id: f.id,
@@ -10,6 +10,7 @@ const path_1 = __importDefault(require("path"));
10
10
  const load_ocsf_discoveries_1 = require("../discoveries/load-ocsf-discoveries");
11
11
  const scan_entity_uri_1 = require("../discoveries/scan-entity-uri");
12
12
  const io_1 = require("../facts/io");
13
+ const data_category_catalog_generated_1 = require("./data-category-catalog.generated");
13
14
  const kb_store_1 = require("./kb-store");
14
15
  /** Same record, same id, so running migrate twice adds nothing. */
15
16
  function migratedAnswerId(recordUid) {
@@ -19,8 +20,9 @@ function storedValue(slot, text) {
19
20
  if (slot === "data_categories") {
20
21
  try {
21
22
  const parsed = JSON.parse(text);
22
- if (Array.isArray(parsed))
23
- return parsed;
23
+ if (Array.isArray(parsed)) {
24
+ return parsed.map((token) => typeof token === "string" ? ((0, data_category_catalog_generated_1.resolveCatalogDataCategoryValue)(token) ?? token) : token);
25
+ }
24
26
  }
25
27
  catch {
26
28
  // Not a list; keep the text.
@@ -17,7 +17,8 @@ export declare class SlotValueError extends Error {
17
17
  }
18
18
  /**
19
19
  * The value as it is stored in `asserted_value`: an enum token, a JSON-encoded
20
- * list of DataCategory tokens, or approved scope text. Throws on anything that
21
- * isn't ontology-shaped, so a model can't land an invented category.
20
+ * list of DPV data category concepts (an older category name is mapped to its
21
+ * concept), or approved scope text. Throws on anything that isn't
22
+ * vocabulary-shaped, so a model can't land an invented category.
22
23
  */
23
24
  export declare function normalizeSlotValue(slot: InterviewSlot, raw: string): string;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SlotValueError = exports.SHAPE_FOR_SLOT = exports.SYSTEM_ASSERTS_URI = void 0;
4
4
  exports.isInterviewSlot = isInterviewSlot;
5
5
  exports.normalizeSlotValue = normalizeSlotValue;
6
+ const data_category_catalog_generated_1 = require("./data-category-catalog.generated");
6
7
  const taxonomy_1 = require("./taxonomy");
7
8
  /**
8
9
  * The interview answers that may land as Discoveries (write-back rules §3).
@@ -28,8 +29,9 @@ class SlotValueError extends Error {
28
29
  exports.SlotValueError = SlotValueError;
29
30
  /**
30
31
  * The value as it is stored in `asserted_value`: an enum token, a JSON-encoded
31
- * list of DataCategory tokens, or approved scope text. Throws on anything that
32
- * isn't ontology-shaped, so a model can't land an invented category.
32
+ * list of DPV data category concepts (an older category name is mapped to its
33
+ * concept), or approved scope text. Throws on anything that isn't
34
+ * vocabulary-shaped, so a model can't land an invented category.
33
35
  */
34
36
  function normalizeSlotValue(slot, raw) {
35
37
  const value = raw.trim();
@@ -54,21 +56,24 @@ function normalizeSlotValue(slot, raw) {
54
56
  case "data_categories": {
55
57
  const tokens = parseCategoryList(value);
56
58
  if (tokens.length === 0) {
57
- throw new SlotValueError("data_categories needs at least one category (use 'other' when none fits)");
59
+ throw new SlotValueError(`data_categories needs at least one category (use '${taxonomy_1.UNCATEGORISED_DATA_CATEGORY}' when none fits)`);
58
60
  }
61
+ const concepts = [];
59
62
  for (const token of tokens) {
60
63
  if (token === "unspecified") {
61
- throw new SlotValueError("data_categories has no 'unspecified'; use 'other' for a gap");
64
+ throw new SlotValueError(`data_categories has no 'unspecified'; use '${taxonomy_1.UNCATEGORISED_DATA_CATEGORY}' for a gap`);
62
65
  }
63
- if (!taxonomy_1.DATA_CATEGORIES.includes(token)) {
64
- throw new SlotValueError(`unknown data category '${token}'; use one of ${taxonomy_1.DATA_CATEGORIES.join(", ")}`);
66
+ const concept = (0, data_category_catalog_generated_1.resolveCatalogDataCategoryValue)(token);
67
+ if (!concept) {
68
+ throw new SlotValueError(`unknown data category '${token}'; use a W3C DPV, DPV-PD or dpx concept, one of ${taxonomy_1.DATA_CATEGORIES.join(", ")}`);
65
69
  }
70
+ concepts.push(concept);
66
71
  }
67
- return JSON.stringify(Array.from(new Set(tokens)).sort());
72
+ return JSON.stringify(Array.from(new Set(concepts)).sort());
68
73
  }
69
74
  }
70
75
  }
71
- /** Accepts a JSON array (`["contact"]`) or a comma-separated list (`contact, identifiers`). */
76
+ /** Accepts a JSON array (`["pd:EmailAddress"]`) or a comma-separated list (`pd:EmailAddress, pd:Name`). */
72
77
  function parseCategoryList(value) {
73
78
  if (value.startsWith("[")) {
74
79
  let parsed;
@@ -1,12 +1,18 @@
1
1
  /**
2
- * Ontology controlled vocabularies used by interview write-back.
3
- * Source: DataParade-io/ontology v0.3.0 (taxonomy/data_category.yaml,
4
- * purpose.yaml, actor_kind.yaml). Update together with PINNED_ONTOLOGY_*.
2
+ * Controlled vocabularies used by interview write-back.
3
+ *
4
+ * Data categories are W3C DPV, DPV-PD and dpx: concepts (DATAP-961), the same concepts the
5
+ * scanner puts on data flows, so interview answers and scan results use one vocabulary. The
6
+ * catalog is generated from the scanner taxonomy by scripts/data-categories/. Purposes and actor
7
+ * kinds come from DataParade-io/ontology (taxonomy/purpose.yaml, actor_kind.yaml); update them
8
+ * together with PINNED_ONTOLOGY_*.
5
9
  */
6
- export declare const DATA_CATEGORIES: readonly ["personal", "identifiers", "contact", "demographic", "credentials", "financial", "health", "location", "communications", "commercial", "other"];
7
- /** `unspecified` is a Purpose only; DataCategory uses `other` for a gap. */
10
+ export declare const DATA_CATEGORIES: readonly string[];
11
+ /** The value an interview answer uses when no more specific data category fits. */
12
+ export declare const UNCATEGORISED_DATA_CATEGORY = "dpv:UncategorisedData";
13
+ /** `unspecified` is a Purpose only; a data category gap is dpv:UncategorisedData. */
8
14
  export declare const PURPOSES: readonly ["service_provision", "analytics", "marketing", "security", "legal_obligation", "research", "debugging", "unspecified"];
9
15
  export declare const ACTOR_KINDS: readonly ["person", "role", "persona"];
10
- export type DataCategory = (typeof DATA_CATEGORIES)[number];
16
+ export type DataCategory = string;
11
17
  export type Purpose = (typeof PURPOSES)[number];
12
18
  export type ActorKind = (typeof ACTOR_KINDS)[number];
@@ -1,25 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ACTOR_KINDS = exports.PURPOSES = exports.DATA_CATEGORIES = void 0;
3
+ exports.ACTOR_KINDS = exports.PURPOSES = exports.UNCATEGORISED_DATA_CATEGORY = exports.DATA_CATEGORIES = void 0;
4
+ const data_category_catalog_generated_1 = require("./data-category-catalog.generated");
4
5
  /**
5
- * Ontology controlled vocabularies used by interview write-back.
6
- * Source: DataParade-io/ontology v0.3.0 (taxonomy/data_category.yaml,
7
- * purpose.yaml, actor_kind.yaml). Update together with PINNED_ONTOLOGY_*.
6
+ * Controlled vocabularies used by interview write-back.
7
+ *
8
+ * Data categories are W3C DPV, DPV-PD and dpx: concepts (DATAP-961), the same concepts the
9
+ * scanner puts on data flows, so interview answers and scan results use one vocabulary. The
10
+ * catalog is generated from the scanner taxonomy by scripts/data-categories/. Purposes and actor
11
+ * kinds come from DataParade-io/ontology (taxonomy/purpose.yaml, actor_kind.yaml); update them
12
+ * together with PINNED_ONTOLOGY_*.
8
13
  */
9
- exports.DATA_CATEGORIES = [
10
- "personal",
11
- "identifiers",
12
- "contact",
13
- "demographic",
14
- "credentials",
15
- "financial",
16
- "health",
17
- "location",
18
- "communications",
19
- "commercial",
20
- "other",
21
- ];
22
- /** `unspecified` is a Purpose only; DataCategory uses `other` for a gap. */
14
+ exports.DATA_CATEGORIES = data_category_catalog_generated_1.DATA_CATEGORY_CONCEPTS.map((concept) => concept.value);
15
+ /** The value an interview answer uses when no more specific data category fits. */
16
+ exports.UNCATEGORISED_DATA_CATEGORY = "dpv:UncategorisedData";
17
+ /** `unspecified` is a Purpose only; a data category gap is dpv:UncategorisedData. */
23
18
  exports.PURPOSES = [
24
19
  "service_provision",
25
20
  "analytics",
@@ -13,6 +13,8 @@ const path_1 = __importDefault(require("path"));
13
13
  const SCAN_OUTPUT_ENTRIES = [
14
14
  "dataflow.json",
15
15
  "facts.json",
16
+ "threat-model.json",
17
+ "threat-model.unreadable.json",
16
18
  "sensitive-findings.json",
17
19
  "data-items/**",
18
20
  "graphify.json",
@@ -1,7 +1,8 @@
1
1
  import { type DataParadeGraph, type OrchestratorScanResult } from '../../vendor/scanner/dist/src/index.js';
2
2
  import type { OutputLayout } from '../facts/layout';
3
3
  import { type DataflowHierarchy } from './c4-hierarchy';
4
- import type { ScanStamps } from "../facts/schema";
4
+ import type { FactsFile, ScanStamps } from "../facts/schema";
5
+ import { type PersonSetStatusCarryForwardResult } from '../threat-model/carry-forward-person-set-statuses';
5
6
  /**
6
7
  * Where Graphify keeps its working files and cache between scans, outside the output
7
8
  * folder: `~/.cache/dataparade/graphify/<hash of the scan root>`.
@@ -30,6 +31,9 @@ export interface WriteScanFactsOptions {
30
31
  scannerVersion: string;
31
32
  scannedAt?: string;
32
33
  stamps?: ScanStamps;
34
+ gitBranch?: string | null;
33
35
  }
34
36
  /** Write facts.json and data-items/. answers.json is not touched. */
35
37
  export declare function writeScanFacts(layout: OutputLayout, options: WriteScanFactsOptions): import("../facts/build-facts").BuiltFacts;
38
+ /** Write threat-model.json from the Facts, keeping the statuses people set in the previous file. */
39
+ export declare function writeScanThreatModel(layout: OutputLayout, facts: FactsFile): PersonSetStatusCarryForwardResult;
@@ -7,12 +7,14 @@ exports.graphifyCacheDir = graphifyCacheDir;
7
7
  exports.prepareScanKnowledge = prepareScanKnowledge;
8
8
  exports.buildScanHierarchy = buildScanHierarchy;
9
9
  exports.writeScanFacts = writeScanFacts;
10
+ exports.writeScanThreatModel = writeScanThreatModel;
10
11
  /**
11
12
  * What a scan writes besides dataflow.json (DATAP-735):
12
13
  *
13
14
  * facts.json Facts from this scan, replaced on every scan
14
15
  * data-items/*.json one file per data item, with its occurrences
15
16
  * graphify.json Graphify's code-structure graph (graph.json, renamed)
17
+ * threat-model.json STRIDE threats per element; person-set statuses are carried forward
16
18
  *
17
19
  * Graphify (https://github.com/Graphify-Labs/graphify) maps the code; the scanner's
18
20
  * knowledge graph links Facts to those code nodes. The graph is built in memory and only
@@ -27,6 +29,9 @@ const scanner_1 = require("../../vendor/scanner/dist/src/index.js");
27
29
  const build_facts_1 = require("../facts/build-facts");
28
30
  const io_1 = require("../facts/io");
29
31
  const c4_hierarchy_1 = require("./c4-hierarchy");
32
+ const build_threat_model_1 = require("../threat-model/build-threat-model");
33
+ const carry_forward_person_set_statuses_1 = require("../threat-model/carry-forward-person-set-statuses");
34
+ const io_2 = require("../threat-model/io");
30
35
  function warn(message) {
31
36
  console.warn(`[scan] ${message}`);
32
37
  }
@@ -110,7 +115,23 @@ function writeScanFacts(layout, options) {
110
115
  scannerVersion: options.scannerVersion,
111
116
  scannedAt: options.scannedAt,
112
117
  stamps: options.stamps,
118
+ gitBranch: options.gitBranch,
113
119
  });
114
120
  (0, io_1.writeFactsOutput)(layout, built.facts, built.dataItemFiles);
115
121
  return built;
116
122
  }
123
+ /** Write threat-model.json from the Facts, keeping the statuses people set in the previous file. */
124
+ function writeScanThreatModel(layout, facts) {
125
+ const previousThreatModelRead = (0, io_2.readPreviousThreatModelForCarryForward)(layout);
126
+ if (previousThreatModelRead.outcome === 'unreadable') {
127
+ const whereThePreviousFileWasKept = previousThreatModelRead.unreadableCopyPath
128
+ ? ` The previous file was kept at ${previousThreatModelRead.unreadableCopyPath}.`
129
+ : '';
130
+ warn(`warning: the previous threat-model.json could not be read (${previousThreatModelRead.reason}); person-set statuses were not carried forward.${whereThePreviousFileWasKept}`);
131
+ }
132
+ const carryForwardResult = (0, carry_forward_person_set_statuses_1.carryForwardPersonSetStatuses)((0, build_threat_model_1.buildThreatModel)(facts), previousThreatModelRead.outcome === 'read'
133
+ ? previousThreatModelRead.threatModel
134
+ : undefined);
135
+ (0, io_2.writeThreatModel)(layout, carryForwardResult.threatModel);
136
+ return carryForwardResult;
137
+ }
@@ -0,0 +1,3 @@
1
+ import type { FactsFile } from "../facts/schema";
2
+ import { type ThreatModelFile } from "./schema";
3
+ export declare function buildThreatModel(facts: FactsFile): ThreatModelFile;
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildThreatModel = buildThreatModel;
4
+ /**
5
+ * Builds the threat model file (DATAP-920) from Facts with the scanner's STRIDE rules.
6
+ * It reads only Facts, so every evidence path is already relative to the scan root.
7
+ */
8
+ const scanner_1 = require("../../vendor/scanner/dist/src/index.js");
9
+ const schema_1 = require("./schema");
10
+ function groupDataFlowsByComponentId(dataFlows) {
11
+ const dataFlowsByComponentId = new Map();
12
+ const addDataFlowToComponent = (componentId, dataFlow) => {
13
+ const existingDataFlows = dataFlowsByComponentId.get(componentId) ?? [];
14
+ existingDataFlows.push(dataFlow);
15
+ dataFlowsByComponentId.set(componentId, existingDataFlows);
16
+ };
17
+ for (const dataFlow of dataFlows) {
18
+ addDataFlowToComponent(dataFlow.sourceComponentId, dataFlow);
19
+ if (dataFlow.targetComponentId !== dataFlow.sourceComponentId) {
20
+ addDataFlowToComponent(dataFlow.targetComponentId, dataFlow);
21
+ }
22
+ }
23
+ return dataFlowsByComponentId;
24
+ }
25
+ function toThreatModelThreat(scannerThreat, element, elementKind, frameworkElementKind) {
26
+ return {
27
+ id: (0, schema_1.threatIdForElementAndCategory)({
28
+ elementId: element.id,
29
+ framework: scannerThreat.framework,
30
+ category: scannerThreat.category,
31
+ }),
32
+ elementId: element.id,
33
+ elementKind,
34
+ frameworkElementKind,
35
+ ...(element.identity ? { elementIdentityKey: element.identity.key } : {}),
36
+ framework: scannerThreat.framework,
37
+ category: scannerThreat.category,
38
+ ruleStatus: scannerThreat.status,
39
+ ruleId: scannerThreat.ruleId,
40
+ ...(scannerThreat.statusRuleId !== undefined ? { statusRuleId: scannerThreat.statusRuleId } : {}),
41
+ evidence: scannerThreat.evidence ?? [],
42
+ };
43
+ }
44
+ function buildComponentThreats(component, dataFlowsOfComponent) {
45
+ const componentForRules = { type: component.type, subType: component.subType || undefined };
46
+ const frameworkElementKind = (0, scanner_1.strideComponentKind)(componentForRules);
47
+ if (frameworkElementKind === undefined)
48
+ return [];
49
+ return (0, scanner_1.strideThreatsForComponent)(componentForRules, dataFlowsOfComponent).map((scannerThreat) => toThreatModelThreat(scannerThreat, component, "component", frameworkElementKind));
50
+ }
51
+ function buildDataFlowThreats(dataFlow) {
52
+ return (0, scanner_1.strideThreatsForFlow)(dataFlow).map((scannerThreat) => toThreatModelThreat(scannerThreat, dataFlow, "dataFlow", "data_flow"));
53
+ }
54
+ function buildThreatModel(facts) {
55
+ const strideRules = (0, scanner_1.loadStrideRules)();
56
+ const dataFlowsByComponentId = groupDataFlowsByComponentId(facts.dataFlows);
57
+ const componentThreats = facts.components.flatMap((component) => buildComponentThreats(component, dataFlowsByComponentId.get(component.id) ?? []));
58
+ const dataFlowThreats = facts.dataFlows.flatMap(buildDataFlowThreats);
59
+ const strideFramework = {
60
+ id: strideRules.framework,
61
+ rulesVersion: strideRules.version,
62
+ categories: strideRules.categories.map(({ id, name }) => ({ id, name })),
63
+ };
64
+ return {
65
+ schemaVersion: schema_1.THREAT_MODEL_SCHEMA_VERSION,
66
+ scan: facts.scan,
67
+ frameworks: [strideFramework],
68
+ threats: [...componentThreats, ...dataFlowThreats],
69
+ unmatchedPersonSetStatuses: [],
70
+ };
71
+ }
@@ -0,0 +1,8 @@
1
+ /** Carries person-set threat statuses from the previous threat-model.json onto a fresh scan (DATAP-920). */
2
+ import type { ThreatModelFile } from "./schema";
3
+ export interface PersonSetStatusCarryForwardResult {
4
+ threatModel: ThreatModelFile;
5
+ carriedForwardCount: number;
6
+ unmatchedCount: number;
7
+ }
8
+ export declare function carryForwardPersonSetStatuses(freshThreatModel: ThreatModelFile, previousThreatModel: ThreatModelFile | undefined): PersonSetStatusCarryForwardResult;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.carryForwardPersonSetStatuses = carryForwardPersonSetStatuses;
4
+ const KEY_SEPARATOR = "\u0000";
5
+ function buildIdentityKey(entry) {
6
+ return [entry.elementKind, entry.elementIdentityKey, entry.framework, entry.category].join(KEY_SEPARATOR);
7
+ }
8
+ function buildElementIdKey(entry) {
9
+ return [entry.elementKind, entry.elementId, entry.framework, entry.category].join(KEY_SEPARATOR);
10
+ }
11
+ function collectPreviousPersonSetEntries(previousThreatModel) {
12
+ const entriesFromCurrentThreats = [];
13
+ for (const threat of previousThreatModel.threats) {
14
+ if (!threat.personSetStatus)
15
+ continue;
16
+ entriesFromCurrentThreats.push({
17
+ threatId: threat.id,
18
+ elementId: threat.elementId,
19
+ elementKind: threat.elementKind,
20
+ ...(threat.elementIdentityKey !== undefined ? { elementIdentityKey: threat.elementIdentityKey } : {}),
21
+ framework: threat.framework,
22
+ category: threat.category,
23
+ personSetStatus: threat.personSetStatus,
24
+ lastMatchedScannedAt: previousThreatModel.scan.scannedAt,
25
+ });
26
+ }
27
+ return [...entriesFromCurrentThreats, ...previousThreatModel.unmatchedPersonSetStatuses];
28
+ }
29
+ function compareText(left, right) {
30
+ if (left < right)
31
+ return -1;
32
+ if (left > right)
33
+ return 1;
34
+ return 0;
35
+ }
36
+ function compareUnmatchedEntries(left, right) {
37
+ return (compareText(left.elementKind, right.elementKind) ||
38
+ compareText(left.elementId, right.elementId) ||
39
+ compareText(left.framework, right.framework) ||
40
+ compareText(left.category, right.category) ||
41
+ compareText(left.lastMatchedScannedAt, right.lastMatchedScannedAt));
42
+ }
43
+ function carryForwardPersonSetStatuses(freshThreatModel, previousThreatModel) {
44
+ if (!previousThreatModel) {
45
+ return { threatModel: freshThreatModel, carriedForwardCount: 0, unmatchedCount: 0 };
46
+ }
47
+ const previousEntries = collectPreviousPersonSetEntries(previousThreatModel);
48
+ const entryByIdentityKey = new Map();
49
+ const entryByElementIdKey = new Map();
50
+ for (const entry of previousEntries) {
51
+ if (entry.elementIdentityKey !== undefined) {
52
+ const identityKey = buildIdentityKey(entry);
53
+ if (!entryByIdentityKey.has(identityKey))
54
+ entryByIdentityKey.set(identityKey, entry);
55
+ }
56
+ const elementIdKey = buildElementIdKey(entry);
57
+ if (!entryByElementIdKey.has(elementIdKey))
58
+ entryByElementIdKey.set(elementIdKey, entry);
59
+ }
60
+ const consumedEntries = new Set();
61
+ const threatsWithCarriedStatuses = freshThreatModel.threats.map((freshThreat) => {
62
+ let matchedEntry;
63
+ if (freshThreat.elementIdentityKey !== undefined) {
64
+ const byIdentity = entryByIdentityKey.get(buildIdentityKey(freshThreat));
65
+ if (byIdentity && !consumedEntries.has(byIdentity))
66
+ matchedEntry = byIdentity;
67
+ }
68
+ if (!matchedEntry) {
69
+ const byElementId = entryByElementIdKey.get(buildElementIdKey(freshThreat));
70
+ if (byElementId && !consumedEntries.has(byElementId))
71
+ matchedEntry = byElementId;
72
+ }
73
+ if (!matchedEntry)
74
+ return freshThreat;
75
+ consumedEntries.add(matchedEntry);
76
+ return { ...freshThreat, personSetStatus: { ...matchedEntry.personSetStatus } };
77
+ });
78
+ const unmatchedPersonSetStatuses = previousEntries
79
+ .filter((entry) => !consumedEntries.has(entry))
80
+ .map((entry) => ({ ...entry, personSetStatus: { ...entry.personSetStatus } }))
81
+ .sort(compareUnmatchedEntries);
82
+ return {
83
+ threatModel: { ...freshThreatModel, threats: threatsWithCarriedStatuses, unmatchedPersonSetStatuses },
84
+ carriedForwardCount: consumedEntries.size,
85
+ unmatchedCount: unmatchedPersonSetStatuses.length,
86
+ };
87
+ }
@@ -0,0 +1,19 @@
1
+ import type { OutputLayout } from "../facts/layout";
2
+ import { type ThreatModelFile } from "./schema";
3
+ export declare class ThreatModelError extends Error {
4
+ readonly code: string;
5
+ constructor(code: string, message: string);
6
+ }
7
+ export type PreviousThreatModelReadResult = {
8
+ outcome: "absent";
9
+ } | {
10
+ outcome: "read";
11
+ threatModel: ThreatModelFile;
12
+ } | {
13
+ outcome: "unreadable";
14
+ reason: string;
15
+ unreadableCopyPath?: string;
16
+ };
17
+ export declare function readPreviousThreatModelForCarryForward(layout: OutputLayout): PreviousThreatModelReadResult;
18
+ export declare function writeThreatModel(layout: OutputLayout, threatModel: ThreatModelFile): void;
19
+ export declare function readThreatModel(layout: OutputLayout): ThreatModelFile;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ThreatModelError = void 0;
7
+ exports.readPreviousThreatModelForCarryForward = readPreviousThreatModelForCarryForward;
8
+ exports.writeThreatModel = writeThreatModel;
9
+ exports.readThreatModel = readThreatModel;
10
+ /** Reads and writes .dataparade/threat-model.json (DATAP-920). */
11
+ const fs_1 = __importDefault(require("fs"));
12
+ const path_1 = __importDefault(require("path"));
13
+ const schema_1 = require("./schema");
14
+ class ThreatModelError extends Error {
15
+ constructor(code, message) {
16
+ super(message);
17
+ this.code = code;
18
+ this.name = "ThreatModelError";
19
+ }
20
+ }
21
+ exports.ThreatModelError = ThreatModelError;
22
+ function keepUnreadableCopy(layout) {
23
+ try {
24
+ fs_1.default.copyFileSync(layout.threatModelPath, layout.threatModelUnreadableCopyPath);
25
+ return layout.threatModelUnreadableCopyPath;
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ function describeUnreadableFile(layout, reason) {
32
+ const unreadableCopyPath = keepUnreadableCopy(layout);
33
+ return unreadableCopyPath ? { outcome: "unreadable", reason, unreadableCopyPath } : { outcome: "unreadable", reason };
34
+ }
35
+ function readPreviousThreatModelForCarryForward(layout) {
36
+ if (!fs_1.default.existsSync(layout.threatModelPath))
37
+ return { outcome: "absent" };
38
+ let parsedJson;
39
+ try {
40
+ parsedJson = JSON.parse(fs_1.default.readFileSync(layout.threatModelPath, "utf8"));
41
+ }
42
+ catch (error) {
43
+ return describeUnreadableFile(layout, error instanceof Error ? error.message : String(error));
44
+ }
45
+ const schemaResult = schema_1.threatModelFileSchema.safeParse(parsedJson);
46
+ if (!schemaResult.success) {
47
+ const firstIssue = schemaResult.error.issues[0];
48
+ const reason = firstIssue ? `${firstIssue.path.join(".") || "(root)"}: ${firstIssue.message}` : "does not match the threat model schema";
49
+ return describeUnreadableFile(layout, reason);
50
+ }
51
+ return { outcome: "read", threatModel: schemaResult.data };
52
+ }
53
+ function writeThreatModel(layout, threatModel) {
54
+ schema_1.threatModelFileSchema.parse(threatModel);
55
+ fs_1.default.mkdirSync(path_1.default.dirname(layout.threatModelPath), { recursive: true });
56
+ fs_1.default.writeFileSync(layout.threatModelPath, `${JSON.stringify(threatModel, null, 2)}\n`, "utf8");
57
+ }
58
+ function readThreatModel(layout) {
59
+ if (!fs_1.default.existsSync(layout.threatModelPath)) {
60
+ throw new ThreatModelError("NO_THREAT_MODEL", `No threat-model.json in ${layout.dir}. Scan first: dataparade scan <repo> -o ${layout.dataflowPath}`);
61
+ }
62
+ return schema_1.threatModelFileSchema.parse(JSON.parse(fs_1.default.readFileSync(layout.threatModelPath, "utf8")));
63
+ }