@dataparade/cli 0.0.32 → 0.0.33

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 (100) hide show
  1. package/README.md +56 -1
  2. package/dist/package.json +4 -3
  3. package/dist/src/cli.js +47 -4
  4. package/dist/src/diff/register-diff-command.d.ts +4 -0
  5. package/dist/src/diff/register-diff-command.js +79 -0
  6. package/dist/src/diff/run-diff.d.ts +80 -0
  7. package/dist/src/diff/run-diff.js +206 -0
  8. package/dist/src/diff/upload-diff.d.ts +26 -0
  9. package/dist/src/diff/upload-diff.js +69 -0
  10. package/dist/src/facts/apply-answers.js +1 -1
  11. package/dist/src/facts/build-facts.d.ts +3 -1
  12. package/dist/src/facts/build-facts.js +10 -1
  13. package/dist/src/facts/identity.d.ts +27 -0
  14. package/dist/src/facts/identity.js +203 -0
  15. package/dist/src/facts/io.d.ts +2 -0
  16. package/dist/src/facts/io.js +7 -0
  17. package/dist/src/facts/scan-stamps.d.ts +55 -0
  18. package/dist/src/facts/scan-stamps.js +165 -0
  19. package/dist/src/facts/schema.d.ts +243 -7
  20. package/dist/src/facts/schema.js +71 -1
  21. package/dist/src/kb/answer-fingerprint.d.ts +44 -0
  22. package/dist/src/kb/answer-fingerprint.js +173 -0
  23. package/dist/src/kb/brief.d.ts +8 -1
  24. package/dist/src/kb/brief.js +18 -2
  25. package/dist/src/kb/land.js +3 -0
  26. package/dist/src/kb/register-kb-commands.js +7 -1
  27. package/dist/src/output/git-context.d.ts +8 -0
  28. package/dist/src/output/git-context.js +18 -0
  29. package/dist/src/output/scan-output-excludes.js +5 -1
  30. package/dist/src/output/write-scan-knowledge.d.ts +2 -0
  31. package/dist/src/output/write-scan-knowledge.js +1 -0
  32. package/dist/src/platform-api/dataparade-app-base-url.d.ts +8 -4
  33. package/dist/src/platform-api/dataparade-app-base-url.js +10 -5
  34. package/dist/src/platform-api/upload-client.d.ts +1 -1
  35. package/dist/src/platform-api/upload-client.js +32 -1
  36. package/dist/src/platform-api/upload.types.d.ts +55 -0
  37. package/dist/src/sensitive-scan/process.d.ts +5 -0
  38. package/dist/src/sensitive-scan/process.js +48 -0
  39. package/dist/src/sensitive-scan/project.d.ts +12 -0
  40. package/dist/src/sensitive-scan/project.js +177 -0
  41. package/dist/src/sensitive-scan/report.d.ts +50 -0
  42. package/dist/src/sensitive-scan/report.js +32 -0
  43. package/dist/src/sensitive-scan/sessions.d.ts +2 -0
  44. package/dist/src/sensitive-scan/sessions.js +120 -0
  45. package/dist/src/ui/scan-progress-renderer.d.ts +1 -0
  46. package/dist/src/ui/scan-progress-renderer.js +8 -0
  47. package/dist/src/upload/build-preview-url.d.ts +2 -2
  48. package/dist/src/upload/build-preview-url.js +4 -4
  49. package/dist/src/upload/run-upload.js +6 -2
  50. package/dist/src/upload/types.d.ts +2 -0
  51. package/dist/tests/unit/diff/run-diff.spec.d.ts +1 -0
  52. package/dist/tests/unit/diff/run-diff.spec.js +189 -0
  53. package/dist/tests/unit/diff/upload-diff.spec.d.ts +1 -0
  54. package/dist/tests/unit/diff/upload-diff.spec.js +81 -0
  55. package/dist/tests/unit/facts/apply-answers.spec.js +1 -1
  56. package/dist/tests/unit/facts/build-facts.spec.js +67 -1
  57. package/dist/tests/unit/facts/identity.spec.d.ts +1 -0
  58. package/dist/tests/unit/facts/identity.spec.js +148 -0
  59. package/dist/tests/unit/facts/scan-stamps.spec.d.ts +1 -0
  60. package/dist/tests/unit/facts/scan-stamps.spec.js +95 -0
  61. package/dist/tests/unit/kb/answer-fingerprint.spec.d.ts +1 -0
  62. package/dist/tests/unit/kb/answer-fingerprint.spec.js +157 -0
  63. package/dist/tests/unit/kb/kb-interview-loop.spec.js +16 -0
  64. package/dist/tests/unit/output/git-context.spec.js +19 -0
  65. package/dist/tests/unit/platform-api/dataparade-app-base-url.spec.js +9 -0
  66. package/dist/tests/unit/platform-api/upload-client.spec.js +101 -1
  67. package/dist/tests/unit/sensitive-scan/project.spec.d.ts +1 -0
  68. package/dist/tests/unit/sensitive-scan/project.spec.js +98 -0
  69. package/dist/tests/unit/upload/build-preview-url.spec.js +4 -0
  70. package/dist/tests/unit/upload/collect-scan-sidecars.spec.js +1 -0
  71. package/dist/tests/unit/upload/run-upload.spec.js +32 -0
  72. package/dist/vendor/kb-compare/dist/src/canonical.d.ts +80 -0
  73. package/dist/vendor/kb-compare/dist/src/canonical.js +119 -0
  74. package/dist/vendor/kb-compare/dist/src/change-set.d.ts +144 -0
  75. package/dist/vendor/kb-compare/dist/src/change-set.js +80 -0
  76. package/dist/vendor/kb-compare/dist/src/comparable.d.ts +23 -0
  77. package/dist/vendor/kb-compare/dist/src/comparable.js +48 -0
  78. package/dist/vendor/kb-compare/dist/src/compare.d.ts +52 -0
  79. package/dist/vendor/kb-compare/dist/src/compare.js +370 -0
  80. package/dist/vendor/kb-compare/dist/src/fingerprint.d.ts +40 -0
  81. package/dist/vendor/kb-compare/dist/src/fingerprint.js +88 -0
  82. package/dist/vendor/kb-compare/dist/src/index.d.ts +15 -0
  83. package/dist/vendor/kb-compare/dist/src/index.js +34 -0
  84. package/dist/vendor/kb-compare/dist/src/input.d.ts +128 -0
  85. package/dist/vendor/kb-compare/dist/src/input.js +75 -0
  86. package/dist/vendor/kb-compare/dist/src/slot-rules.d.ts +69 -0
  87. package/dist/vendor/kb-compare/dist/src/slot-rules.js +203 -0
  88. package/dist/vendor/kb-compare/dist/src/summary.d.ts +3 -0
  89. package/dist/vendor/kb-compare/dist/src/summary.js +47 -0
  90. package/dist/vendor/kb-compare/package.json +6 -0
  91. package/dist/vendor/scanner/dist/src/classifier/application-injection.js +5 -0
  92. package/dist/vendor/scanner/dist/src/core/pipeline/stable-component-ids.d.ts +8 -0
  93. package/dist/vendor/scanner/dist/src/core/pipeline/stable-component-ids.js +11 -1
  94. package/dist/vendor/scanner/dist/src/index.d.ts +1 -1
  95. package/dist/vendor/scanner/dist/src/index.js +4 -2
  96. package/dist/vendor/scanner/package.json +3 -1
  97. package/dist/vendor/scanner/patterns/classifier/third-party.classifier.yaml +10 -0
  98. package/dist/vendor/scanner/patterns/component-taxonomy.yaml +1 -1
  99. package/dist/vendor/scanner/patterns/third-party.patterns.yaml +25 -0
  100. package/package.json +4 -3
@@ -0,0 +1,157 @@
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
+ const fs_1 = __importDefault(require("fs"));
7
+ const path_1 = __importDefault(require("path"));
8
+ const scanner_1 = require("../../../vendor/scanner/dist/src/index.js");
9
+ const io_1 = require("../../../src/facts/io");
10
+ const answer_fingerprint_1 = require("../../../src/kb/answer-fingerprint");
11
+ const brief_1 = require("../../../src/kb/brief");
12
+ const land_1 = require("../../../src/kb/land");
13
+ const facts_fixture_1 = require("../../helpers/facts-fixture");
14
+ const SKILL_SHA = "f".repeat(40);
15
+ const REVIEWER = "dev@example.com";
16
+ const KEYS = {
17
+ cmp_api: "app:backend|asset|service|backend/src/main.ts|backend",
18
+ cmp_mail: "app:<unsectioned>|third_party|email||sendgrid",
19
+ cmp_user: "app:<unsectioned>|actor|||customer",
20
+ flow_mail: '["flow/v1","app:backend|asset|service|backend/src/main.ts|backend","app:<unsectioned>|third_party|email||sendgrid","api_call","","",""]',
21
+ flow_login: '["flow/v1","app:<unsectioned>|actor|||customer","app:backend|asset|service|backend/src/main.ts|backend","api_call","","",""]',
22
+ "data_item:email": "email",
23
+ "data_item:phone": "phone",
24
+ "group:email:customer": "email:customer",
25
+ "group:email:staff": "email:staff",
26
+ "group:phone:customer": "phone:customer",
27
+ };
28
+ function identity(kind, id) {
29
+ return { kind, key: KEYS[id] ?? id, parts: {} };
30
+ }
31
+ /** The sample scan with identities, optionally with some ids or keys changed (a later revision). */
32
+ function keyedFacts(change = () => { }) {
33
+ const { facts, files } = (0, facts_fixture_1.sampleFacts)();
34
+ facts.components = facts.components.map((c) => ({ ...c, identity: identity("component", c.id) }));
35
+ facts.dataFlows = facts.dataFlows.map((f) => ({ ...f, identity: identity("dataFlow", f.id) }));
36
+ const keyGroups = (item) => ({
37
+ ...item,
38
+ groups: item.groups.map((g) => ({ ...g, identity: identity("group", g.id) })),
39
+ });
40
+ facts.dataItems = facts.dataItems.map((item) => keyGroups({ ...item, identity: identity("dataItem", item.id) }));
41
+ const keyedFiles = files.map((file) => keyGroups({ ...file, identity: identity("dataItem", file.id) }));
42
+ change(facts);
43
+ return { facts, files: keyedFiles };
44
+ }
45
+ function writeScan(paths, change) {
46
+ const { facts, files } = keyedFacts(change);
47
+ (0, io_1.writeFactsOutput)(paths, facts, new Map(files.map((file) => [`data-items/${file.name}.json`, file])));
48
+ return facts;
49
+ }
50
+ describe("answer fingerprints (DATAP-873)", () => {
51
+ let paths;
52
+ const evidence = "evidence/session.md";
53
+ beforeEach(() => {
54
+ paths = (0, facts_fixture_1.makeKbDir)();
55
+ fs_1.default.mkdirSync(paths.evidenceDir, { recursive: true });
56
+ fs_1.default.writeFileSync(path_1.default.join(paths.dir, evidence), "Q: What goes to Sendgrid?\nA: Email addresses.\n");
57
+ });
58
+ afterEach(() => fs_1.default.rmSync(paths.dir, { recursive: true, force: true }));
59
+ const land = (briefSha, target, slot, value) => (0, land_1.landInterviewAnswer)(paths, { briefSha, target, slot, value, reviewer: REVIEWER, evidence, skillSha: SKILL_SHA });
60
+ it("finds a Fact's element by id across components, flows, data items and groups", () => {
61
+ const { facts } = keyedFacts();
62
+ expect((0, answer_fingerprint_1.elementOfFact)(facts, "cmp_mail")).toEqual({ subject: "component", key: KEYS.cmp_mail });
63
+ expect((0, answer_fingerprint_1.elementOfFact)(facts, "flow_mail")).toEqual({ subject: "dataFlow", key: KEYS.flow_mail });
64
+ expect((0, answer_fingerprint_1.elementOfFact)(facts, "data_item:email")).toEqual({ subject: "dataItem", key: "email" });
65
+ expect((0, answer_fingerprint_1.elementOfFact)(facts, "group:email:staff")).toEqual({ subject: "group", key: "email:staff" });
66
+ expect((0, answer_fingerprint_1.elementOfFact)(facts, "nope")).toBeNull();
67
+ });
68
+ it("writes the identity key and fingerprint with each new interview answer", () => {
69
+ writeScan(paths);
70
+ const { sha } = (0, brief_1.writeKbBrief)(paths);
71
+ const flow = land(sha, "flow_mail", "purpose", "service_provision").answer;
72
+ expect(flow).toMatchObject({ identityKey: KEYS.flow_mail, fingerprintSource: "landed" });
73
+ expect(flow.fingerprint).toMatchObject({
74
+ subject: "dataFlow",
75
+ key: KEYS.flow_mail,
76
+ neighbours: { source: KEYS.cmp_api, target: KEYS.cmp_mail },
77
+ });
78
+ const actor = land(sha, "cmp_user", "actor_kind", "persona").answer;
79
+ expect(actor.fingerprint).toMatchObject({ subject: "component", shape: { type: "actor" } });
80
+ const system = land(sha, "dp:a0/system", "in_scope", "The web app").answer;
81
+ expect(system).toMatchObject({ identityKey: "dp:a0/system", fingerprintSource: "landed" });
82
+ expect(system.fingerprint).toBeUndefined();
83
+ // Stored as landed.
84
+ expect((0, io_1.readAnswers)(paths).answers.every((a) => a.identityKey)).toBe(true);
85
+ });
86
+ it("writes them with review answers, including the groups a component handles", () => {
87
+ writeScan(paths);
88
+ const answer = (0, land_1.landReviewAnswer)(paths, { target: "cmp_mail", action: "set", property: "name", value: "SendGrid", reviewer: REVIEWER }).answer;
89
+ expect(answer.identityKey).toBe(KEYS.cmp_mail);
90
+ expect(answer.fingerprint?.handledGroups).toEqual(["email:staff"]);
91
+ });
92
+ it("leaves the fields out for a scan without identities", () => {
93
+ const { facts } = (0, facts_fixture_1.sampleFacts)();
94
+ expect((0, answer_fingerprint_1.fingerprintFields)(facts, "cmp_mail")).toEqual({});
95
+ });
96
+ describe("migration of old answers", () => {
97
+ const old = (id, factId, extra = {}) => ({
98
+ id,
99
+ factId,
100
+ action: "set",
101
+ property: "purpose",
102
+ value: "service_provision",
103
+ by: REVIEWER,
104
+ at: "2026-10-01T00:00:00.000Z",
105
+ source: "interview",
106
+ ...extra,
107
+ });
108
+ it("keys an answer through its brief even after the Fact's id changed", () => {
109
+ writeScan(paths);
110
+ const { sha } = (0, brief_1.writeKbBrief)(paths);
111
+ // A later scan gives the flow a new id; the old answer still cites the old one.
112
+ writeScan(paths, (facts) => {
113
+ facts.dataFlows = facts.dataFlows.map((f) => (f.id === "flow_mail" ? { ...f, id: "flow_mail_2" } : f));
114
+ });
115
+ (0, io_1.appendAnswers)(paths, [old("ans_a", "flow_mail", { briefSha: sha })]);
116
+ const result = (0, answer_fingerprint_1.migrateAnswerFingerprints)(paths);
117
+ expect(result).toMatchObject({ migrated: 1, outcomes: { ans_a: "brief" }, unresolved: [], withoutFingerprint: [] });
118
+ const [answer] = (0, io_1.readAnswers)(paths).answers;
119
+ expect(answer).toMatchObject({ identityKey: KEYS.flow_mail, fingerprintSource: "migrated" });
120
+ expect(answer.fingerprint?.key).toBe(KEYS.flow_mail);
121
+ });
122
+ it("falls back to the current scan, keys system answers, and is idempotent", () => {
123
+ writeScan(paths);
124
+ (0, io_1.appendAnswers)(paths, [
125
+ old("ans_b", "cmp_user", { property: "actor_kind", value: "persona" }),
126
+ old("ans_c", "dp:a0/system", { property: "in_scope", value: "The web app" }),
127
+ old("ans_d", "cmp_gone"),
128
+ ]);
129
+ const first = (0, answer_fingerprint_1.migrateAnswerFingerprints)(paths);
130
+ expect(first.outcomes).toEqual({ ans_b: "scan", ans_c: "system", ans_d: "unresolved" });
131
+ expect(first.unresolved).toEqual(["ans_d"]);
132
+ const again = (0, answer_fingerprint_1.migrateAnswerFingerprints)(paths);
133
+ expect(again).toMatchObject({ migrated: 0, alreadyKeyed: 2, unresolved: ["ans_d"] });
134
+ });
135
+ it("maps the root Application named after the folder to the project-name token (DATAP-858)", () => {
136
+ const rootKey = `app:<unsectioned>|asset|application|package.json|${scanner_1.PROJECT_NAME_KEY_TOKEN}`;
137
+ const folderKey = "app:<unsectioned>|asset|application|package.json|my-checkout";
138
+ const root = { id: "cmp_root", name: "my-checkout", type: "asset", subType: "application", confidence: 1, sourceLocations: [], codeRefs: [] };
139
+ // The brief was written before DATAP-858: the root's key and id came from the folder name.
140
+ writeScan(paths, (facts) => {
141
+ facts.components.push({ ...root, identity: { kind: "component", key: folderKey, parts: {} } });
142
+ facts.dataFlows.push({ id: "flow_root", sourceComponentId: "cmp_root", targetComponentId: "cmp_mail", type: "api_call", confidence: 0.9, sourceLocations: [], codeRefs: [], identity: { kind: "dataFlow", key: "flow-root", parts: {} } });
143
+ });
144
+ const { sha } = (0, brief_1.writeKbBrief)(paths);
145
+ writeScan(paths, (facts) => {
146
+ facts.components.push({ ...root, id: "cmp_root_new", identity: { kind: "component", key: rootKey, parts: {} } });
147
+ });
148
+ (0, io_1.appendAnswers)(paths, [old("ans_root", "cmp_root", { briefSha: sha, property: "actor_kind" })]);
149
+ const result = (0, answer_fingerprint_1.migrateAnswerFingerprints)(paths, { dryRun: true });
150
+ expect(result.outcomes).toEqual({ ans_root: "root" });
151
+ // A dry run writes nothing.
152
+ expect((0, io_1.readAnswers)(paths).answers[0].identityKey).toBeUndefined();
153
+ (0, answer_fingerprint_1.migrateAnswerFingerprints)(paths);
154
+ expect((0, io_1.readAnswers)(paths).answers[0]).toMatchObject({ identityKey: rootKey, fingerprintSource: "migrated" });
155
+ });
156
+ });
157
+ });
@@ -44,6 +44,22 @@ describe("live interview loop: brief → land → project", () => {
44
44
  // Same KB state, same snapshot.
45
45
  expect((0, brief_1.writeKbBrief)(paths).sha).toBe(sha);
46
46
  });
47
+ it("puts each Fact's identity in the brief, and leaves it out for KBs without identity", () => {
48
+ expect((0, brief_1.writeKbBrief)(paths).brief.flows.every((f) => f.identity === undefined)).toBe(true);
49
+ const { facts, files } = (0, facts_fixture_1.sampleFacts)();
50
+ const mail = { kind: "dataFlow", key: "app:api|…|mail", parts: { type: "api_call" } };
51
+ const sendgrid = { kind: "component", key: "app:<unsectioned>|third_party||src/mail.ts|sendgrid", parts: { name: "sendgrid" } };
52
+ facts.dataFlows = facts.dataFlows.map((f) => (f.id === "flow_mail" ? { ...f, identity: mail } : f));
53
+ facts.components = facts.components.map((c) => (c.id === "cmp_mail" ? { ...c, identity: sendgrid } : c));
54
+ (0, io_1.writeFactsOutput)(paths, facts, new Map(files.map((file) => [`data-items/${file.name}.json`, file])));
55
+ const { brief, sha } = (0, brief_1.writeKbBrief)(paths);
56
+ const flow = brief.flows.find((f) => f.id === "flow_mail");
57
+ expect(flow.identity).toEqual(mail);
58
+ expect(flow.target.identity).toEqual(sendgrid);
59
+ expect(brief.external_systems.find((e) => e.id === "cmp_mail")?.identity).toEqual(sendgrid);
60
+ // The snapshot keeps the identity, and its SHA still checks.
61
+ expect((0, brief_1.readKbBrief)(paths, sha).flows.find((f) => f.id === "flow_mail")?.identity).toEqual(mail);
62
+ });
47
63
  it("lands confirmed answers and projects them onto the diagram", () => {
48
64
  const { sha } = (0, brief_1.writeKbBrief)(paths);
49
65
  land(sha, "flow_mail", "data_categories", "contact, identifiers");
@@ -20,6 +20,19 @@ describe('parseGitRemote', () => {
20
20
  expect((0, git_context_1.parseGitRemote)(remote)).toBeNull();
21
21
  });
22
22
  });
23
+ describe('normalizeGitRemoteUrl', () => {
24
+ it.each([
25
+ ['git@GitHub.com:org/repo.git', 'https://github.com/org/repo'],
26
+ ['ssh://git@github.com:22/org/repo.git', 'https://github.com/org/repo'],
27
+ ['https://user:pw@GitLab.com/group/sub/repo.git/', 'https://gitlab.com/group/sub/repo'],
28
+ ['http://git.internal/org/repo', 'http://git.internal/org/repo'],
29
+ ])('normalizes %s', (remote, expected) => {
30
+ expect((0, git_context_1.normalizeGitRemoteUrl)(remote)).toBe(expected);
31
+ });
32
+ it('returns null for a remote it cannot parse', () => {
33
+ expect((0, git_context_1.normalizeGitRemoteUrl)('/local/path/repo')).toBeNull();
34
+ });
35
+ });
23
36
  describe('gitContextFromRemote', () => {
24
37
  it('maps GitHub and gitlab.com without a base URL', () => {
25
38
  expect((0, git_context_1.gitContextFromRemote)('git@github.com:org/repo.git', SHA)).toEqual({
@@ -61,6 +74,12 @@ describe('detectGitContext', () => {
61
74
  it('returns null for a repository without an origin', () => {
62
75
  git('init', '-q');
63
76
  expect((0, git_context_1.detectGitContext)(dir)).toBeNull();
77
+ expect((0, git_context_1.readOriginRemoteUrl)(dir)).toBeNull();
78
+ });
79
+ it('reads the normalized origin remote', () => {
80
+ git('init', '-q');
81
+ git('remote', 'add', 'origin', 'https://token@github.com/Org/repo.git');
82
+ expect((0, git_context_1.readOriginRemoteUrl)(dir)).toBe('https://github.com/Org/repo');
64
83
  });
65
84
  it('reads origin and HEAD', () => {
66
85
  git('init', '-q');
@@ -10,4 +10,13 @@ describe("getDataparadeAppBaseUrl", () => {
10
10
  DATAPARADE_APP_URL: "http://localhost:3001/",
11
11
  })).toBe("http://localhost:3001");
12
12
  });
13
+ it("uses the app the API names when DATAPARADE_APP_URL is unset", () => {
14
+ expect((0, dataparade_app_base_url_1.getDataparadeAppBaseUrl)({}, "https://dev-app.example.com/")).toBe("https://dev-app.example.com");
15
+ });
16
+ it("prefers DATAPARADE_APP_URL over the app the API names", () => {
17
+ expect((0, dataparade_app_base_url_1.getDataparadeAppBaseUrl)({ DATAPARADE_APP_URL: "http://localhost:3001" }, "https://dev-app.example.com")).toBe("http://localhost:3001");
18
+ });
19
+ it("ignores an app URL from the API that is not http(s)", () => {
20
+ expect((0, dataparade_app_base_url_1.getDataparadeAppBaseUrl)({}, "javascript:alert(1)")).toBe(dataparade_app_base_url_1.DEFAULT_DATAPARADE_APP_URL);
21
+ });
13
22
  });
@@ -88,7 +88,7 @@ describe('cliUploadPreview', () => {
88
88
  },
89
89
  ],
90
90
  });
91
- expect(global.fetch).toHaveBeenCalledTimes(2);
91
+ expect(global.fetch).toHaveBeenCalledTimes(3);
92
92
  const diagram = JSON.parse(global.fetch.mock.calls[0][1].body);
93
93
  expect(diagram.graphifyGraph).toBeUndefined();
94
94
  const filesUrl = global.fetch.mock.calls[1][0];
@@ -96,6 +96,106 @@ describe('cliUploadPreview', () => {
96
96
  const filesBody = JSON.parse(global.fetch.mock.calls[1][1].body);
97
97
  expect(filesBody.files[0]?.relativePath).toBe('graphify.json');
98
98
  });
99
+ it('completes the upload once after the files, with the remote URL', async () => {
100
+ global.fetch = jest
101
+ .fn()
102
+ .mockResolvedValueOnce({
103
+ ok: true,
104
+ json: async () => ({ draftId: 'draft-4', projectName: 'proj' }),
105
+ })
106
+ .mockResolvedValue({
107
+ ok: true,
108
+ json: async () => ({ ok: true }),
109
+ });
110
+ await (0, upload_client_1.cliUploadPreview)({
111
+ apiKey: 'dp_live_testkey123456',
112
+ dataflow: {},
113
+ files: [{ relativePath: 'facts.json', content: '{"scan":{}}' }],
114
+ remoteUrl: 'https://github.com/org/repo',
115
+ });
116
+ const calls = global.fetch.mock.calls;
117
+ expect(calls).toHaveLength(3);
118
+ expect(calls[2][0]).toContain('/api/scans/cli/upload/draft-4/complete');
119
+ expect(calls[2][1]).toMatchObject({
120
+ method: 'POST',
121
+ headers: expect.objectContaining({
122
+ Authorization: 'Bearer dp_live_testkey123456',
123
+ }),
124
+ });
125
+ expect(JSON.parse(calls[2][1].body)).toEqual({
126
+ remoteUrl: 'https://github.com/org/repo',
127
+ });
128
+ });
129
+ it('sends the rename map with a diff --upload head and returns the comparison (DATAP-890)', async () => {
130
+ const complete = {
131
+ stored: true,
132
+ scanId: 'scan-1',
133
+ repositoryId: 'repo-1',
134
+ created: true,
135
+ comparable: true,
136
+ comparison: { compared: false, reason: 'no_base_scan', message: 'none' },
137
+ };
138
+ global.fetch = jest
139
+ .fn()
140
+ .mockResolvedValueOnce({
141
+ ok: true,
142
+ json: async () => ({ draftId: 'draft-5' }),
143
+ })
144
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ ok: true }) })
145
+ .mockResolvedValueOnce({
146
+ ok: true,
147
+ json: async () => complete,
148
+ });
149
+ const compare = {
150
+ baseCommitSha: 'b'.repeat(40),
151
+ rootCommitSha: 'a'.repeat(40),
152
+ renames: [{ from: 'a.ts', to: 'b.ts', similarity: 90 }],
153
+ };
154
+ const result = await (0, upload_client_1.cliUploadPreview)({
155
+ apiKey: 'dp_live_testkey123456',
156
+ dataflow: {},
157
+ files: [{ relativePath: 'facts.json', content: '{"scan":{}}' }],
158
+ remoteUrl: null,
159
+ compare,
160
+ });
161
+ const calls = global.fetch.mock.calls;
162
+ expect(JSON.parse(calls[2][1].body)).toEqual({ compare });
163
+ expect(result.complete).toEqual(complete);
164
+ });
165
+ it('does not complete an upload without scan files', async () => {
166
+ global.fetch = jest.fn().mockResolvedValue({
167
+ ok: true,
168
+ json: async () => ({ draftId: 'draft-5' }),
169
+ });
170
+ await (0, upload_client_1.cliUploadPreview)({ apiKey: 'dp_live_testkey123456', dataflow: {} });
171
+ expect(global.fetch).toHaveBeenCalledTimes(1);
172
+ });
173
+ it.each([
174
+ ['a rejected completion', { ok: false, status: 500, json: async () => ({}) }],
175
+ ['a network error', new Error('socket hang up')],
176
+ ])('only warns on %s', async (_label, outcome) => {
177
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
178
+ const fetchMock = jest
179
+ .fn()
180
+ .mockResolvedValueOnce({
181
+ ok: true,
182
+ json: async () => ({ draftId: 'draft-6' }),
183
+ })
184
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ ok: true }) });
185
+ if (outcome instanceof Error)
186
+ fetchMock.mockRejectedValueOnce(outcome);
187
+ else
188
+ fetchMock.mockResolvedValueOnce(outcome);
189
+ global.fetch = fetchMock;
190
+ const result = await (0, upload_client_1.cliUploadPreview)({
191
+ apiKey: 'dp_live_testkey123456',
192
+ dataflow: {},
193
+ files: [{ relativePath: 'facts.json', content: '{}' }],
194
+ });
195
+ expect(result.draftId).toBe('draft-6');
196
+ expect(JSON.parse(fetchMock.mock.calls[2][1].body)).toEqual({});
197
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('not stored for comparison'));
198
+ });
99
199
  it('throws with API error message', async () => {
100
200
  global.fetch = jest.fn().mockResolvedValue({
101
201
  ok: false,
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,98 @@
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
+ const node_fs_1 = require("node:fs");
7
+ const node_os_1 = __importDefault(require("node:os"));
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const process_1 = require("../../../src/sensitive-scan/process");
10
+ const project_1 = require("../../../src/sensitive-scan/project");
11
+ const scan_output_excludes_1 = require("../../../src/output/scan-output-excludes");
12
+ jest.mock('../../../src/sensitive-scan/process');
13
+ it('preserves a data-flow output named sensitive-findings.json', async () => {
14
+ const root = await node_fs_1.promises.mkdtemp(node_path_1.default.join(node_os_1.default.tmpdir(), 'dataparade-sensitive-scan-'));
15
+ try {
16
+ const output = node_path_1.default.join(root, 'sensitive-findings.json');
17
+ await node_fs_1.promises.writeFile(output, 'existing data-flow artifact');
18
+ await (0, project_1.writeProjectSensitiveScan)(output, {
19
+ root,
20
+ target: root,
21
+ excludes: [],
22
+ modelMode: 'off',
23
+ enabled: false,
24
+ }, jest.fn());
25
+ expect(await node_fs_1.promises.readFile(output, 'utf8')).toBe('existing data-flow artifact');
26
+ }
27
+ finally {
28
+ await node_fs_1.promises.rm(root, { recursive: true, force: true });
29
+ }
30
+ });
31
+ it('keeps rule locations when the model is unavailable and scopes the input files', async () => {
32
+ const root = await node_fs_1.promises.mkdtemp(node_path_1.default.join(node_os_1.default.tmpdir(), 'dataparade-sensitive-scan-'));
33
+ try {
34
+ const output = node_path_1.default.join(root, '.dataparade');
35
+ await node_fs_1.promises.mkdir(output);
36
+ await node_fs_1.promises.writeFile(node_path_1.default.join(output, 'sensitive-findings.json'), '{}');
37
+ await node_fs_1.promises.writeFile(node_path_1.default.join(root, 'notes.txt'), 'synthetic test value');
38
+ await node_fs_1.promises.writeFile(node_path_1.default.join(root, 'exclude.txt'), 'excluded');
39
+ await node_fs_1.promises.writeFile(node_path_1.default.join(root, 'ignored.txt'), 'ignored');
40
+ await node_fs_1.promises.writeFile(node_path_1.default.join(root, '.gitignore'), 'ignored.txt\n');
41
+ if (process.platform !== 'win32') {
42
+ await node_fs_1.promises.symlink(node_path_1.default.join(root, 'exclude.txt'), node_path_1.default.join(root, 'link.txt'));
43
+ }
44
+ const ids = [];
45
+ jest
46
+ .mocked(process_1.runLocalScanner)
47
+ .mockImplementationOnce(async (_executable, _args, input) => {
48
+ for await (const record of input)
49
+ ids.push(JSON.parse(record).id);
50
+ return {
51
+ code: 1,
52
+ output: JSON.stringify({
53
+ schemaVersion: 1,
54
+ rules: { status: 'completed', findingCount: 1 },
55
+ privacyFilter: {
56
+ status: 'unavailable',
57
+ reason: 'missing-dependencies',
58
+ },
59
+ findings: [
60
+ {
61
+ id: 'notes.txt',
62
+ line: 1,
63
+ start: 0,
64
+ end: 20,
65
+ rule: 'example-rule',
66
+ kind: 'secret',
67
+ finding_id: 'synthetic',
68
+ value: 'synthetic test value',
69
+ },
70
+ ],
71
+ }),
72
+ };
73
+ });
74
+ const warn = jest.fn();
75
+ await (0, project_1.writeProjectSensitiveScan)(node_path_1.default.join(output, 'dataflow.json'), {
76
+ root,
77
+ target: root,
78
+ enabled: true,
79
+ modelMode: 'auto',
80
+ excludes: [
81
+ ...(0, scan_output_excludes_1.scanOutputExcludes)(root, node_path_1.default.join(output, 'dataflow.json')),
82
+ 'exclude.txt',
83
+ ],
84
+ }, warn);
85
+ expect(ids).toEqual(['.gitignore', 'notes.txt']);
86
+ const outputText = await node_fs_1.promises.readFile(node_path_1.default.join(output, 'sensitive-findings.json'), 'utf8');
87
+ expect(outputText).not.toContain('synthetic test value');
88
+ const report = JSON.parse(outputText);
89
+ expect(report.findings).toEqual([
90
+ expect.objectContaining({ file: 'notes.txt', line: 1 }),
91
+ ]);
92
+ expect(report.privacyFilter.status).toBe('unavailable');
93
+ expect(warn).toHaveBeenCalledTimes(1);
94
+ }
95
+ finally {
96
+ await node_fs_1.promises.rm(root, { recursive: true, force: true });
97
+ }
98
+ });
@@ -16,6 +16,10 @@ describe("buildImportPreviewUrl", () => {
16
16
  const url = (0, build_preview_url_1.buildImportPreviewUrl)("draft-abc");
17
17
  expect(url).toBe("http://localhost:3001/dashboard?importDraft=draft-abc");
18
18
  });
19
+ it("links to the app the API named when DATAPARADE_APP_URL is unset", () => {
20
+ delete process.env.DATAPARADE_APP_URL;
21
+ expect((0, build_preview_url_1.buildImportPreviewUrl)("draft-abc", undefined, "https://dev-app.example.com/")).toBe("https://dev-app.example.com/dashboard?importDraft=draft-abc");
22
+ });
19
23
  it("appends cliSession when provided", () => {
20
24
  process.env.DATAPARADE_APP_URL = "http://localhost:3001";
21
25
  const url = (0, build_preview_url_1.buildImportPreviewUrl)("draft-abc", "11111111-1111-4111-8111-111111111111");
@@ -24,6 +24,7 @@ describe('collectScanUploadFiles', () => {
24
24
  fs_1.default.writeFileSync(path_1.default.join(dir, 'data-items', 'email.json'), '{"id":"data_item:email"}');
25
25
  fs_1.default.writeFileSync(path_1.default.join(dir, 'graphify.json'), '{"nodes":[]}');
26
26
  fs_1.default.writeFileSync(path_1.default.join(dir, 'answers.json'), '{"schemaVersion":1,"answers":[]}');
27
+ fs_1.default.writeFileSync(path_1.default.join(dir, 'sensitive-findings.json'), '{"schemaVersion":1,"findings":[]}');
27
28
  const files = (0, collect_scan_sidecars_1.collectScanUploadFiles)(path_1.default.join(dir, 'dataflow.json'));
28
29
  expect(files.map((file) => file.relativePath)).toEqual([
29
30
  'facts.json',
@@ -8,12 +8,16 @@ jest.mock('../../../src/platform-api/upload-client', () => ({
8
8
  jest.mock('../../../src/platform-api/telemetry-client', () => ({
9
9
  reportCliUsageEvent: jest.fn().mockResolvedValue(undefined),
10
10
  }));
11
+ jest.mock('../../../src/output/git-context', () => ({
12
+ readOriginRemoteUrl: jest.fn(() => 'https://github.com/org/repo'),
13
+ }));
11
14
  jest.mock('../../../src/upload/build-preview-url', () => ({
12
15
  buildAnonymousCliPreviewUrl: jest.fn((token) => `https://app.example/preview/cli/${token}`),
13
16
  buildImportPreviewUrl: jest.fn((draftId) => `https://app.example/dashboard?importDraft=${draftId}`),
14
17
  }));
15
18
  const upload_client_1 = require("../../../src/platform-api/upload-client");
16
19
  const telemetry_client_1 = require("../../../src/platform-api/telemetry-client");
20
+ const git_context_1 = require("../../../src/output/git-context");
17
21
  describe('runDataflowUpload anonymous path', () => {
18
22
  const logSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined);
19
23
  afterEach(() => {
@@ -65,3 +69,31 @@ describe('runDataflowUpload anonymous path', () => {
65
69
  }));
66
70
  });
67
71
  });
72
+ describe('runDataflowUpload with an API key', () => {
73
+ const logSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined);
74
+ afterEach(() => {
75
+ jest.clearAllMocks();
76
+ });
77
+ afterAll(() => {
78
+ logSpy.mockRestore();
79
+ });
80
+ it('sends the origin remote of the scanned checkout', async () => {
81
+ upload_client_1.cliUploadPreview.mockResolvedValue({ draftId: 'draft-1' });
82
+ await (0, run_upload_1.runDataflowUpload)({
83
+ apiKey: 'dp_live_testkey123456',
84
+ dataflow: { schemaVersion: '1.0' },
85
+ repositoryDir: '/work/shop',
86
+ });
87
+ expect(git_context_1.readOriginRemoteUrl).toHaveBeenCalledWith('/work/shop');
88
+ expect(upload_client_1.cliUploadPreview).toHaveBeenCalledWith(expect.objectContaining({ remoteUrl: 'https://github.com/org/repo' }));
89
+ });
90
+ it('sends no remote when no checkout folder is known', async () => {
91
+ upload_client_1.cliUploadPreview.mockResolvedValue({ draftId: 'draft-1' });
92
+ await (0, run_upload_1.runDataflowUpload)({
93
+ apiKey: 'dp_live_testkey123456',
94
+ dataflow: { schemaVersion: '1.0' },
95
+ });
96
+ expect(git_context_1.readOriginRemoteUrl).not.toHaveBeenCalled();
97
+ expect(upload_client_1.cliUploadPreview).toHaveBeenCalledWith(expect.objectContaining({ remoteUrl: null }));
98
+ });
99
+ });
@@ -0,0 +1,80 @@
1
+ import type { FactsInput } from "./input";
2
+ /**
3
+ * Canonical form of a scan (DATAP-849): what the scan says about the system, with everything
4
+ * that changes when nothing real changed left out.
5
+ *
6
+ * Left out: the `scan` block (time, project name, versions), ids (they are derived from keys),
7
+ * source locations, line numbers, code refs, occurrence counts, relations (flows already hold
8
+ * them), and the order of the arrays. Confidence is kept only as a band, so a small score
9
+ * change is not a change.
10
+ *
11
+ * Components, flows, data items and groups are matched by `identity.key`. Facts without an
12
+ * identity (CLI 0.0.32 and earlier) cannot be matched; they are listed in `withoutIdentity`
13
+ * and are not in the model hash.
14
+ */
15
+ export type ConfidenceBand = "low" | "medium" | "high";
16
+ /** low: below 0.5; medium: 0.5 to below 0.8; high: 0.8 and above. */
17
+ export declare function confidenceBand(confidence: number): ConfidenceBand;
18
+ export interface CanonicalComponent {
19
+ key: string;
20
+ duplicateIndex?: number;
21
+ name: string;
22
+ type: string;
23
+ subType: string;
24
+ confidence: ConfidenceBand;
25
+ }
26
+ export interface CanonicalDataFlow {
27
+ key: string;
28
+ duplicateIndex?: number;
29
+ /** Keys of the endpoints; `id:<id>` when an endpoint has no identity. */
30
+ source: string;
31
+ target: string;
32
+ type: string;
33
+ targetScope: string | null;
34
+ confidence: ConfidenceBand;
35
+ }
36
+ export interface CanonicalGroup {
37
+ key: string;
38
+ duplicateIndex?: number;
39
+ label: string;
40
+ basis: string | null;
41
+ /** Keys of the components that handle the group, sorted. */
42
+ handledBy: string[];
43
+ }
44
+ export interface CanonicalDataItem {
45
+ key: string;
46
+ labels: string[];
47
+ groups: CanonicalGroup[];
48
+ }
49
+ export interface WithoutIdentity {
50
+ subject: "component" | "dataFlow" | "dataItem" | "group";
51
+ id: string;
52
+ }
53
+ /**
54
+ * What rename matching needs to rebuild a key (DATAP-866): the identity parts and the element's
55
+ * files, sorted. Not part of the model, so it is not in the model hash.
56
+ */
57
+ export interface KeySource {
58
+ parts: Record<string, string>;
59
+ files: string[];
60
+ }
61
+ export interface CanonicalScan {
62
+ components: CanonicalComponent[];
63
+ dataFlows: CanonicalDataFlow[];
64
+ dataItems: CanonicalDataItem[];
65
+ withoutIdentity: WithoutIdentity[];
66
+ /** By element key (with its `#n`). */
67
+ keySources: {
68
+ components: Record<string, KeySource>;
69
+ dataFlows: Record<string, KeySource>;
70
+ };
71
+ }
72
+ export declare function canonicalize(facts: FactsInput): CanonicalScan;
73
+ /** JSON with sorted object keys, so equal values always give equal text. */
74
+ export declare function canonicalJson(value: unknown): string;
75
+ export declare function sha256(text: string): string;
76
+ /**
77
+ * The model hash: `sha256:` + the SHA-256 of the canonical form without `withoutIdentity`.
78
+ * Two scans with the same model hash say the same thing, so "nothing changed" is a hash compare.
79
+ */
80
+ export declare function modelHash(scan: CanonicalScan): string;