@openai/codex-security 0.1.12 → 0.1.14

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 (50) hide show
  1. package/README.md +161 -26
  2. package/_bundled_plugin/scripts/workbench_cli.py +4 -0
  3. package/_bundled_plugin/scripts/workbench_db.py +258 -0
  4. package/_bundled_plugin/scripts/workbench_scan_usage.py +26 -0
  5. package/_bundled_plugin/scripts/workbench_schema.py +40 -0
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.d.ts.map +1 -1
  8. package/dist/api.js +25 -7
  9. package/dist/api.js.map +1 -1
  10. package/dist/bulk-scan-discovery.d.ts +5 -1
  11. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  12. package/dist/bulk-scan-discovery.js +24 -7
  13. package/dist/bulk-scan-discovery.js.map +1 -1
  14. package/dist/cli.d.ts +3 -0
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +579 -19
  17. package/dist/cli.js.map +1 -1
  18. package/dist/config.d.ts +1 -0
  19. package/dist/config.d.ts.map +1 -1
  20. package/dist/config.js +8 -1
  21. package/dist/config.js.map +1 -1
  22. package/dist/contract.d.ts +12 -0
  23. package/dist/contract.d.ts.map +1 -1
  24. package/dist/contract.js +30 -2
  25. package/dist/contract.js.map +1 -1
  26. package/dist/index.d.ts +2 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +1 -0
  29. package/dist/index.js.map +1 -1
  30. package/dist/publication-events.d.ts +16 -0
  31. package/dist/publication-events.d.ts.map +1 -0
  32. package/dist/publication-events.js +141 -0
  33. package/dist/publication-events.js.map +1 -0
  34. package/dist/publication-store.d.ts +5 -0
  35. package/dist/publication-store.d.ts.map +1 -0
  36. package/dist/publication-store.js +102 -0
  37. package/dist/publication-store.js.map +1 -0
  38. package/dist/publication.d.ts +27 -0
  39. package/dist/publication.d.ts.map +1 -0
  40. package/dist/publication.js +207 -0
  41. package/dist/publication.js.map +1 -0
  42. package/dist/publish.d.ts +77 -0
  43. package/dist/publish.d.ts.map +1 -0
  44. package/dist/publish.js +748 -0
  45. package/dist/publish.js.map +1 -0
  46. package/dist/scan-dashboard.d.ts +2 -0
  47. package/dist/scan-dashboard.d.ts.map +1 -1
  48. package/dist/scan-dashboard.js +25 -8
  49. package/dist/scan-dashboard.js.map +1 -1
  50. package/package.json +3 -2
@@ -0,0 +1,141 @@
1
+ export function collectPublicationEvents(output, publication, failureMessage) {
2
+ const created = new Map();
3
+ const failed = new Map();
4
+ const unexpected = [];
5
+ for (const line of output.split(/\r?\n/)) {
6
+ if (line.trim().length === 0)
7
+ continue;
8
+ let event;
9
+ try {
10
+ event = JSON.parse(line);
11
+ }
12
+ catch {
13
+ continue;
14
+ }
15
+ if (!isRecord(event) || event["type"] !== "item.completed")
16
+ continue;
17
+ const item = event["item"];
18
+ if (!isRecord(item) ||
19
+ item["type"] !== "mcp_tool_call" ||
20
+ item["server"] !== "codex_apps" ||
21
+ (item["tool"] !== "linear.save_issue" &&
22
+ item["tool"] !== "linear_save_issue")) {
23
+ continue;
24
+ }
25
+ const args = item["arguments"];
26
+ const issue = isRecord(args)
27
+ ? matchPublicationIssue(publication, args)
28
+ : undefined;
29
+ if (issue === undefined) {
30
+ unexpected.push("Codex attempted to create an unexpected Linear issue.");
31
+ continue;
32
+ }
33
+ if (failed.has(issue.findingId) || created.has(issue.findingId)) {
34
+ failed.set(issue.findingId, "Codex attempted to create more than one Linear issue for this finding.");
35
+ continue;
36
+ }
37
+ if (item["status"] !== "completed") {
38
+ const error = item["error"];
39
+ failed.set(issue.findingId, isRecord(error) && typeof error["message"] === "string"
40
+ ? error["message"]
41
+ : failureMessage);
42
+ continue;
43
+ }
44
+ const saved = savedIssue(item["result"]);
45
+ if (saved === undefined) {
46
+ failed.set(issue.findingId, "The connected Linear app did not return a created issue identifier.");
47
+ continue;
48
+ }
49
+ created.set(issue.findingId, {
50
+ findingId: issue.findingId,
51
+ occurrenceId: issue.occurrenceId,
52
+ issueIdentifier: saved.issueIdentifier,
53
+ ...(saved.url === undefined ? {} : { url: saved.url }),
54
+ });
55
+ }
56
+ if (unexpected.length > 0 && publication.issues.length > 0) {
57
+ const target = publication.issues.find((issue) => !created.has(issue.findingId)) ??
58
+ publication.issues[0];
59
+ failed.set(target.findingId, unexpected.join(" "));
60
+ }
61
+ return {
62
+ created: publication.issues.flatMap((issue) => {
63
+ if (failed.has(issue.findingId))
64
+ return [];
65
+ const result = created.get(issue.findingId);
66
+ return result === undefined ? [] : [result];
67
+ }),
68
+ failed: publication.issues.flatMap((issue) => {
69
+ const error = failed.get(issue.findingId);
70
+ if (error !== undefined)
71
+ return [{ findingId: issue.findingId, error }];
72
+ return created.has(issue.findingId)
73
+ ? []
74
+ : [{ findingId: issue.findingId, error: failureMessage }];
75
+ }),
76
+ };
77
+ }
78
+ export function matchPublicationIssue(publication, arguments_) {
79
+ const description = arguments_["description"];
80
+ if (typeof description !== "string") {
81
+ return undefined;
82
+ }
83
+ const matches = publication.issues.filter((issue) => descriptionIdentifiesIssue(description, issue));
84
+ return matches.length === 1 ? matches[0] : undefined;
85
+ }
86
+ function descriptionIdentifiesIssue(description, issue) {
87
+ return (containsIdentifier(description, issue.findingId) &&
88
+ containsIdentifier(description, issue.occurrenceId));
89
+ }
90
+ function containsIdentifier(value, identifier) {
91
+ const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
92
+ return new RegExp(`(?<![\\w-])${escaped}(?![\\w-])`, "u").test(value);
93
+ }
94
+ function savedIssue(result) {
95
+ if (!isRecord(result))
96
+ return undefined;
97
+ const candidates = [
98
+ result["structured_content"],
99
+ result["structuredContent"],
100
+ ];
101
+ if (Array.isArray(result["content"])) {
102
+ for (const content of result["content"]) {
103
+ if (!isRecord(content) || typeof content["text"] !== "string")
104
+ continue;
105
+ try {
106
+ candidates.push(JSON.parse(content["text"]));
107
+ }
108
+ catch {
109
+ continue;
110
+ }
111
+ }
112
+ }
113
+ for (const candidate of candidates) {
114
+ if (!isRecord(candidate))
115
+ continue;
116
+ const nested = candidate["issue"];
117
+ const data = candidate["data"];
118
+ for (const value of [
119
+ candidate,
120
+ nested,
121
+ isRecord(data) ? data["issue"] : undefined,
122
+ ]) {
123
+ if (!isRecord(value))
124
+ continue;
125
+ const identifier = value["identifier"] ?? value["issueIdentifier"] ?? value["id"];
126
+ if (typeof identifier !== "string" || identifier.trim().length === 0) {
127
+ continue;
128
+ }
129
+ const url = value["url"];
130
+ return {
131
+ issueIdentifier: identifier,
132
+ ...(typeof url !== "string" || url.trim().length === 0 ? {} : { url }),
133
+ };
134
+ }
135
+ }
136
+ return undefined;
137
+ }
138
+ function isRecord(value) {
139
+ return typeof value === "object" && value !== null && !Array.isArray(value);
140
+ }
141
+ //# sourceMappingURL=publication-events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publication-events.js","sourceRoot":"","sources":["../src/publication-events.ts"],"names":[],"mappings":"AAeA,MAAM,UAAU,wBAAwB,CACtC,MAAc,EACd,WAAoC,EACpC,cAAsB;IAEtB,MAAM,OAAO,GAAG,IAAI,GAAG,EAGpB,CAAC;IACJ,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAC;IACzC,MAAM,UAAU,GAAa,EAAE,CAAC;IAEhC,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QACzC,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QACvC,IAAI,KAAc,CAAC;QACnB,IAAI,CAAC;YACH,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAY,CAAC;QACtC,CAAC;QAAC,MAAM,CAAC;YACP,SAAS;QACX,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,gBAAgB;YAAE,SAAS;QACrE,MAAM,IAAI,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC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SAAS;YAC/B,MAAM,UAAU,GACd,KAAK,CAAC,YAAY,CAAC,IAAI,KAAK,CAAC,iBAAiB,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC;YACjE,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBACrE,SAAS;YACX,CAAC;YACD,MAAM,GAAG,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;YACzB,OAAO;gBACL,eAAe,EAAE,UAAU;gBAC3B,GAAG,CAAC,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC;aACvE,CAAC;QACJ,CAAC;IACH,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import type {\n PreparedPublicationIssue,\n PreparedScanPublication,\n} from \"./publication.js\";\n\nexport interface CollectedPublicationEvents {\n created: Array<{\n findingId: string;\n occurrenceId: string;\n issueIdentifier: string;\n url?: string;\n }>;\n failed: Array<{ findingId: string; error: string }>;\n}\n\nexport function collectPublicationEvents(\n output: string,\n publication: PreparedScanPublication,\n failureMessage: string,\n): CollectedPublicationEvents {\n const created = new Map<\n string,\n CollectedPublicationEvents[\"created\"][number]\n >();\n const failed = new Map<string, string>();\n const unexpected: string[] = [];\n\n for (const line of output.split(/\\r?\\n/)) {\n if (line.trim().length === 0) continue;\n let event: unknown;\n try {\n event = JSON.parse(line) as unknown;\n } catch {\n continue;\n }\n if (!isRecord(event) || event[\"type\"] !== \"item.completed\") continue;\n const item = event[\"item\"];\n if (\n !isRecord(item) ||\n item[\"type\"] !== \"mcp_tool_call\" ||\n item[\"server\"] !== \"codex_apps\" ||\n (item[\"tool\"] !== \"linear.save_issue\" &&\n item[\"tool\"] !== \"linear_save_issue\")\n ) {\n continue;\n }\n\n const args = item[\"arguments\"];\n const issue = isRecord(args)\n ? matchPublicationIssue(publication, args)\n : undefined;\n if (issue === undefined) {\n unexpected.push(\"Codex attempted to create an unexpected Linear issue.\");\n continue;\n }\n if (failed.has(issue.findingId) || created.has(issue.findingId)) {\n failed.set(\n issue.findingId,\n \"Codex attempted to create more than one Linear issue for this finding.\",\n );\n continue;\n }\n if (item[\"status\"] !== \"completed\") {\n const error = item[\"error\"];\n failed.set(\n issue.findingId,\n isRecord(error) && typeof error[\"message\"] === \"string\"\n ? error[\"message\"]\n : failureMessage,\n );\n continue;\n }\n\n const saved = savedIssue(item[\"result\"]);\n if (saved === undefined) {\n failed.set(\n issue.findingId,\n \"The connected Linear app did not return a created issue identifier.\",\n );\n continue;\n }\n created.set(issue.findingId, {\n findingId: issue.findingId,\n occurrenceId: issue.occurrenceId,\n issueIdentifier: saved.issueIdentifier,\n ...(saved.url === undefined ? {} : { url: saved.url }),\n });\n }\n\n if (unexpected.length > 0 && publication.issues.length > 0) {\n const target =\n publication.issues.find((issue) => !created.has(issue.findingId)) ??\n publication.issues[0]!;\n failed.set(target.findingId, unexpected.join(\" \"));\n }\n\n return {\n created: publication.issues.flatMap((issue) => {\n if (failed.has(issue.findingId)) return [];\n const result = created.get(issue.findingId);\n return result === undefined ? [] : [result];\n }),\n failed: publication.issues.flatMap((issue) => {\n const error = failed.get(issue.findingId);\n if (error !== undefined) return [{ findingId: issue.findingId, error }];\n return created.has(issue.findingId)\n ? []\n : [{ findingId: issue.findingId, error: failureMessage }];\n }),\n };\n}\n\nexport function matchPublicationIssue(\n publication: PreparedScanPublication,\n arguments_: Record<string, unknown>,\n): PreparedPublicationIssue | undefined {\n const description = arguments_[\"description\"];\n if (typeof description !== \"string\") {\n return undefined;\n }\n\n const matches = publication.issues.filter((issue) =>\n descriptionIdentifiesIssue(description, issue),\n );\n return matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction descriptionIdentifiesIssue(\n description: string,\n issue: PreparedPublicationIssue,\n): boolean {\n return (\n containsIdentifier(description, issue.findingId) &&\n containsIdentifier(description, issue.occurrenceId)\n );\n}\n\nfunction containsIdentifier(value: string, identifier: string): boolean {\n const escaped = identifier.replace(/[.*+?^${}()|[\\]\\\\]/gu, \"\\\\$&\");\n return new RegExp(`(?<![\\\\w-])${escaped}(?![\\\\w-])`, \"u\").test(value);\n}\n\nfunction savedIssue(\n result: unknown,\n): { issueIdentifier: string; url?: string } | undefined {\n if (!isRecord(result)) return undefined;\n const candidates: unknown[] = [\n result[\"structured_content\"],\n result[\"structuredContent\"],\n ];\n if (Array.isArray(result[\"content\"])) {\n for (const content of result[\"content\"]) {\n if (!isRecord(content) || typeof content[\"text\"] !== \"string\") continue;\n try {\n candidates.push(JSON.parse(content[\"text\"]) as unknown);\n } catch {\n continue;\n }\n }\n }\n\n for (const candidate of candidates) {\n if (!isRecord(candidate)) continue;\n const nested = candidate[\"issue\"];\n const data = candidate[\"data\"];\n for (const value of [\n candidate,\n nested,\n isRecord(data) ? data[\"issue\"] : undefined,\n ]) {\n if (!isRecord(value)) continue;\n const identifier =\n value[\"identifier\"] ?? value[\"issueIdentifier\"] ?? value[\"id\"];\n if (typeof identifier !== \"string\" || identifier.trim().length === 0) {\n continue;\n }\n const url = value[\"url\"];\n return {\n issueIdentifier: identifier,\n ...(typeof url !== \"string\" || url.trim().length === 0 ? {} : { url }),\n };\n }\n }\n return undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import type { PreparedScanPublication } from "./publication.js";
2
+ import type { PublishedScanIssue } from "./publish.js";
3
+ export declare function preparePublicationStore(publication: PreparedScanPublication, environment: NodeJS.ProcessEnv): Promise<void>;
4
+ export declare function recordPublishedIssues(publication: PreparedScanPublication, issues: readonly PublishedScanIssue[], environment: NodeJS.ProcessEnv): Promise<PublishedScanIssue[]>;
5
+ //# sourceMappingURL=publication-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publication-store.d.ts","sourceRoot":"","sources":["../src/publication-store.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAQvD,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,uBAAuB,EACpC,WAAW,EAAE,MAAM,CAAC,UAAU,GAC7B,OAAO,CAAC,IAAI,CAAC,CAcf;AAED,wBAAsB,qBAAqB,CACzC,WAAW,EAAE,uBAAuB,EACpC,MAAM,EAAE,SAAS,kBAAkB,EAAE,EACrC,WAAW,EAAE,MAAM,CAAC,UAAU,GAC7B,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAmD/B"}
@@ -0,0 +1,102 @@
1
+ import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { CodexSecurityError } from "./errors.js";
4
+ import { bundledPluginRoot, codexSecurityStateDirectory, resolvePluginPython, runWorkbench, } from "./runtime.js";
5
+ export async function preparePublicationStore(publication, environment) {
6
+ const result = await runPublicationWorkbench("prepare-linear-publication", publication, environment);
7
+ if (result["scanId"] !== publication.scanId ||
8
+ result["findingCount"] !== publication.issues.length) {
9
+ throw new CodexSecurityError("The workbench could not verify every finding selected for publication.");
10
+ }
11
+ }
12
+ export async function recordPublishedIssues(publication, issues, environment) {
13
+ const result = await runPublicationWorkbench("record-linear-publications", publication, environment, issues);
14
+ const created = result["created"];
15
+ const destination = result["destination"];
16
+ if (result["scanId"] !== publication.scanId ||
17
+ !isRecord(destination) ||
18
+ destination["type"] !== publication.destination.type ||
19
+ destination["teamId"] !== publication.destination.teamId ||
20
+ destination["projectId"] !== publication.destination.projectId ||
21
+ !Array.isArray(created) ||
22
+ created.length !== issues.length) {
23
+ throw invalidPublicationRecords();
24
+ }
25
+ const expected = new Map(issues.map((issue) => [issue.findingId, issue]));
26
+ const ordered = publication.issues.flatMap((issue) => {
27
+ const record = expected.get(issue.findingId);
28
+ return record === undefined ? [] : [record];
29
+ });
30
+ if (expected.size !== issues.length || ordered.length !== issues.length) {
31
+ throw invalidPublicationRecords();
32
+ }
33
+ return created.map((value, index) => {
34
+ const expectedIssue = ordered[index];
35
+ if (!isRecord(value) ||
36
+ expectedIssue === undefined ||
37
+ value["findingId"] !== expectedIssue.findingId ||
38
+ value["occurrenceId"] !== expectedIssue.occurrenceId ||
39
+ value["issueIdentifier"] !== expectedIssue.issueIdentifier ||
40
+ (value["url"] !== undefined && typeof value["url"] !== "string") ||
41
+ (expectedIssue.url !== undefined && value["url"] !== expectedIssue.url)) {
42
+ throw invalidPublicationRecords();
43
+ }
44
+ return {
45
+ findingId: value["findingId"],
46
+ occurrenceId: value["occurrenceId"],
47
+ issueIdentifier: value["issueIdentifier"],
48
+ ...(typeof value["url"] === "string" ? { url: value["url"] } : {}),
49
+ };
50
+ });
51
+ }
52
+ async function runPublicationWorkbench(command, publication, environment, issues) {
53
+ const stateDirectory = codexSecurityStateDirectory(environment);
54
+ const database = join(stateDirectory, "workbench.sqlite3");
55
+ try {
56
+ if (!(await stat(database)).isFile())
57
+ throw new Error("not a regular file");
58
+ }
59
+ catch (error) {
60
+ throw new CodexSecurityError("Cannot publish findings because the local Codex Security scan-history database does not exist. Use the state directory where this scan was completed.", { cause: error });
61
+ }
62
+ const [python, pluginRoot] = await Promise.all([
63
+ resolvePluginPython({
64
+ environment,
65
+ protectedRoot: publication.scanDirectory,
66
+ }),
67
+ bundledPluginRoot(),
68
+ ]);
69
+ const findings = publication.issues.map(({ findingId, occurrenceId }) => ({
70
+ findingId,
71
+ occurrenceId,
72
+ }));
73
+ const directory = await mkdtemp(join(stateDirectory, "publication-"));
74
+ try {
75
+ const input = join(directory, "publication.json");
76
+ await writeFile(input, JSON.stringify({
77
+ scanId: publication.scanId,
78
+ scanDirectory: publication.scanDirectory,
79
+ destination: publication.destination,
80
+ findings,
81
+ ...(issues === undefined ? {} : { publications: issues }),
82
+ }), { encoding: "utf8", flag: "wx", mode: 0o600 });
83
+ return await runWorkbench({
84
+ python,
85
+ pluginRoot,
86
+ environment,
87
+ failureMessage: command === "prepare-linear-publication"
88
+ ? "Cannot publish findings without their existing local Codex Security scan history"
89
+ : "Could not persist created Linear issues in the local Codex Security scan history",
90
+ }, [command, "--input-file", input]);
91
+ }
92
+ finally {
93
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);
94
+ }
95
+ }
96
+ function invalidPublicationRecords() {
97
+ return new CodexSecurityError("The workbench returned invalid persisted Linear publication records.");
98
+ }
99
+ function isRecord(value) {
100
+ return typeof value === "object" && value !== null && !Array.isArray(value);
101
+ }
102
+ //# sourceMappingURL=publication-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publication-store.js","sourceRoot":"","sources":["../src/publication-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGjD,OAAO,EACL,iBAAiB,EACjB,2BAA2B,EAC3B,mBAAmB,EACnB,YAAY,GACb,MAAM,cAAc,CAAC;AAEtB,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,WAAoC,EACpC,WAA8B;IAE9B,MAAM,MAAM,GAAG,MAAM,uBAAuB,CAC1C,4BAA4B,EAC5B,WAAW,EACX,WAAW,CACZ,CAAC;IACF,IACE,MAAM,CAAC,QAAQ,CAAC,KAAK,WAAW,CAAC,MAAM;QACvC,MAAM,CAAC,cAAc,CAAC,KAAK,W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,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC;SAC1D,CAAC,EACF,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAC9C,CAAC;QACF,OAAO,MAAM,YAAY,CACvB;YACE,MAAM;YACN,UAAU;YACV,WAAW;YACX,cAAc,EACZ,OAAO,KAAK,4BAA4B;gBACtC,CAAC,CAAC,kFAAkF;gBACpF,CAAC,CAAC,kFAAkF;SACzF,EACD,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,CACjC,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,MAAM,EAAE,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK,CACzD,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,yBAAyB;IAChC,OAAO,IAAI,kBAAkB,CAC3B,sEAAsE,CACvE,CAAC;AACJ,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { mkdtemp, rm, stat, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { CodexSecurityError } from \"./errors.js\";\nimport type { PreparedScanPublication } from \"./publication.js\";\nimport type { PublishedScanIssue } from \"./publish.js\";\nimport {\n bundledPluginRoot,\n codexSecurityStateDirectory,\n resolvePluginPython,\n runWorkbench,\n} from \"./runtime.js\";\n\nexport async function preparePublicationStore(\n publication: PreparedScanPublication,\n environment: NodeJS.ProcessEnv,\n): Promise<void> {\n const result = await runPublicationWorkbench(\n \"prepare-linear-publication\",\n publication,\n environment,\n );\n if (\n result[\"scanId\"] !== publication.scanId ||\n result[\"findingCount\"] !== publication.issues.length\n ) {\n throw new CodexSecurityError(\n \"The workbench could not verify every finding selected for publication.\",\n );\n }\n}\n\nexport async function recordPublishedIssues(\n publication: PreparedScanPublication,\n issues: readonly PublishedScanIssue[],\n environment: NodeJS.ProcessEnv,\n): Promise<PublishedScanIssue[]> {\n const result = await runPublicationWorkbench(\n \"record-linear-publications\",\n publication,\n environment,\n issues,\n );\n const created = result[\"created\"];\n const destination = result[\"destination\"];\n if (\n result[\"scanId\"] !== publication.scanId ||\n !isRecord(destination) ||\n destination[\"type\"] !== publication.destination.type ||\n destination[\"teamId\"] !== publication.destination.teamId ||\n destination[\"projectId\"] !== publication.destination.projectId ||\n !Array.isArray(created) ||\n created.length !== issues.length\n ) {\n throw invalidPublicationRecords();\n }\n\n const expected = new Map(issues.map((issue) => [issue.findingId, issue]));\n const ordered = publication.issues.flatMap((issue) => {\n const record = expected.get(issue.findingId);\n return record === undefined ? [] : [record];\n });\n if (expected.size !== issues.length || ordered.length !== issues.length) {\n throw invalidPublicationRecords();\n }\n\n return created.map((value, index) => {\n const expectedIssue = ordered[index];\n if (\n !isRecord(value) ||\n expectedIssue === undefined ||\n value[\"findingId\"] !== expectedIssue.findingId ||\n value[\"occurrenceId\"] !== expectedIssue.occurrenceId ||\n value[\"issueIdentifier\"] !== expectedIssue.issueIdentifier ||\n (value[\"url\"] !== undefined && typeof value[\"url\"] !== \"string\") ||\n (expectedIssue.url !== undefined && value[\"url\"] !== expectedIssue.url)\n ) {\n throw invalidPublicationRecords();\n }\n\n return {\n findingId: value[\"findingId\"] as string,\n occurrenceId: value[\"occurrenceId\"] as string,\n issueIdentifier: value[\"issueIdentifier\"] as string,\n ...(typeof value[\"url\"] === \"string\" ? { url: value[\"url\"] } : {}),\n };\n });\n}\n\nasync function runPublicationWorkbench(\n command: \"prepare-linear-publication\" | \"record-linear-publications\",\n publication: PreparedScanPublication,\n environment: NodeJS.ProcessEnv,\n issues?: readonly PublishedScanIssue[],\n): Promise<Record<string, unknown>> {\n const stateDirectory = codexSecurityStateDirectory(environment);\n const database = join(stateDirectory, \"workbench.sqlite3\");\n try {\n if (!(await stat(database)).isFile()) throw new Error(\"not a regular file\");\n } catch (error) {\n throw new CodexSecurityError(\n \"Cannot publish findings because the local Codex Security scan-history database does not exist. Use the state directory where this scan was completed.\",\n { cause: error },\n );\n }\n const [python, pluginRoot] = await Promise.all([\n resolvePluginPython({\n environment,\n protectedRoot: publication.scanDirectory,\n }),\n bundledPluginRoot(),\n ]);\n const findings = publication.issues.map(({ findingId, occurrenceId }) => ({\n findingId,\n occurrenceId,\n }));\n const directory = await mkdtemp(join(stateDirectory, \"publication-\"));\n try {\n const input = join(directory, \"publication.json\");\n await writeFile(\n input,\n JSON.stringify({\n scanId: publication.scanId,\n scanDirectory: publication.scanDirectory,\n destination: publication.destination,\n findings,\n ...(issues === undefined ? {} : { publications: issues }),\n }),\n { encoding: \"utf8\", flag: \"wx\", mode: 0o600 },\n );\n return await runWorkbench(\n {\n python,\n pluginRoot,\n environment,\n failureMessage:\n command === \"prepare-linear-publication\"\n ? \"Cannot publish findings without their existing local Codex Security scan history\"\n : \"Could not persist created Linear issues in the local Codex Security scan history\",\n },\n [command, \"--input-file\", input],\n );\n } finally {\n await rm(directory, { recursive: true, force: true }).catch(\n () => undefined,\n );\n }\n}\n\nfunction invalidPublicationRecords(): CodexSecurityError {\n return new CodexSecurityError(\n \"The workbench returned invalid persisted Linear publication records.\",\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
@@ -0,0 +1,27 @@
1
+ export interface LinearPublicationDestination {
2
+ type: "linear";
3
+ teamId: string;
4
+ projectId?: string;
5
+ }
6
+ export interface PrepareScanPublicationOptions {
7
+ destination: "linear";
8
+ teamId: string;
9
+ projectId?: string;
10
+ uploadedAt?: string;
11
+ }
12
+ export interface PreparedPublicationIssue {
13
+ findingId: string;
14
+ occurrenceId: string;
15
+ title: string;
16
+ description: string;
17
+ priority?: 1 | 2 | 3 | 4;
18
+ }
19
+ export interface PreparedScanPublication {
20
+ scanId: string;
21
+ uploadId: string;
22
+ scanDirectory: string;
23
+ destination: LinearPublicationDestination;
24
+ issues: PreparedPublicationIssue[];
25
+ }
26
+ export declare function prepareScanPublication(scanDirectory: string, options: PrepareScanPublicationOptions): Promise<PreparedScanPublication>;
27
+ //# sourceMappingURL=publication.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publication.d.ts","sourceRoot":"","sources":["../src/publication.ts"],"names":[],"mappings":"AAWA,MAAM,WAAW,4BAA4B;IAC3C,IAAI,EAAE,QAAQ,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,6BAA6B;IAC5C,WAAW,EAAE,QAAQ,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,wBAAwB;IACvC,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;CAC1B;AAED,MAAM,WAAW,uBAAuB;IACtC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,4BAA4B,CAAC;IAC1C,MAAM,EAAE,wBAAwB,EAAE,CAAC;CACpC;AAUD,wBAAsB,sBAAsB,CAC1C,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,6BAA6B,GACrC,OAAO,CAAC,uBAAuB,CAAC,CA6BlC"}
@@ -0,0 +1,207 @@
1
+ import { resolve } from "node:path";
2
+ import { loadContract } from "./contract.js";
3
+ import { bundledPluginRoot } from "./runtime.js";
4
+ const LINEAR_PRIORITIES = {
5
+ critical: 1,
6
+ high: 2,
7
+ medium: 3,
8
+ low: 4,
9
+ informational: undefined,
10
+ };
11
+ export async function prepareScanPublication(scanDirectory, options) {
12
+ const contract = await loadContract(scanDirectory, {
13
+ pluginRoot: await bundledPluginRoot(),
14
+ });
15
+ const uploadedAt = options.uploadedAt ?? new Date().toISOString();
16
+ const scanId = contract.manifest.scan.id;
17
+ return {
18
+ scanId,
19
+ uploadId: scanId,
20
+ scanDirectory: resolve(scanDirectory),
21
+ destination: {
22
+ type: options.destination,
23
+ teamId: options.teamId,
24
+ ...(options.projectId === undefined
25
+ ? {}
26
+ : { projectId: options.projectId }),
27
+ },
28
+ issues: contract.findings.findings.map((finding) => {
29
+ const priority = LINEAR_PRIORITIES[finding.severity.level];
30
+ return {
31
+ findingId: finding.findingId,
32
+ occurrenceId: finding.occurrenceId,
33
+ title: `[Codex Security][${finding.severity.level.toUpperCase()}] ${finding.title}`,
34
+ description: renderFindingDescription(contract, finding, uploadedAt),
35
+ ...(priority === undefined ? {} : { priority }),
36
+ };
37
+ }),
38
+ };
39
+ }
40
+ function renderFindingDescription(contract, finding, uploadedAt) {
41
+ const { coverage } = contract;
42
+ const { scan } = contract.manifest;
43
+ const lines = [
44
+ "## Codex Security finding",
45
+ "",
46
+ `**Scan ID:** ${scan.id}`,
47
+ `**Finding ID:** ${finding.findingId}`,
48
+ `**Occurrence ID:** ${finding.occurrenceId}`,
49
+ `**Fingerprint:** ${finding.fingerprints.primary}`,
50
+ `**Severity:** ${finding.severity.level.toUpperCase()}`,
51
+ `**Confidence:** ${finding.confidence.level.toUpperCase()}`,
52
+ ...(finding.taxonomy.cwe.length === 0
53
+ ? []
54
+ : [`**CWE:** ${finding.taxonomy.cwe.join(", ")}`]),
55
+ "",
56
+ "## Scanned code",
57
+ "",
58
+ `**Repository:** ${scan.target.displayName}`,
59
+ ...(scan.target.remote === undefined
60
+ ? []
61
+ : [`**Remote:** ${scan.target.remote}`]),
62
+ ...renderTargetIdentity(scan.target),
63
+ `**Scanned scope:** ${scan.scope.includePaths.join(", ") || "entire repository"}`,
64
+ ...(scan.scope.excludePaths.length === 0
65
+ ? []
66
+ : [`**Excluded scope:** ${scan.scope.excludePaths.join(", ")}`]),
67
+ `**Coverage:** ${coverage.completeness}`,
68
+ `**Coverage mode:** ${coverage.mode}`,
69
+ `**Scan mode:** ${scanMode(coverage.mode)}`,
70
+ `**Started:** ${scan.startedAt}`,
71
+ `**Completed:** ${scan.completedAt}`,
72
+ `**Uploaded:** ${uploadedAt}`,
73
+ "",
74
+ "### Affected locations",
75
+ "",
76
+ ...finding.locations.map((location) => renderLocation(scan.target, location)),
77
+ "",
78
+ "## Summary",
79
+ "",
80
+ finding.summary,
81
+ ];
82
+ const rootCause = finding.rootCause;
83
+ if (typeof rootCause === "string") {
84
+ lines.push("", "## Root cause", "", rootCause);
85
+ }
86
+ else if (rootCause !== undefined) {
87
+ lines.push("", "## Root cause", "", rootCause.summary);
88
+ if (rootCause.code !== undefined) {
89
+ lines.push("", fencedCode(rootCause.code, rootCause.language));
90
+ }
91
+ }
92
+ if (finding.codeEvidence !== undefined && finding.codeEvidence.length > 0) {
93
+ lines.push("", "## Source-code evidence");
94
+ for (const evidence of finding.codeEvidence) {
95
+ lines.push("", ...renderCodeEvidence(scan.target, evidence));
96
+ }
97
+ }
98
+ lines.push("", "## Remediation", "", finding.remediation);
99
+ return `${lines.join("\n")}\n`;
100
+ }
101
+ function renderTargetIdentity(target) {
102
+ const lines = [];
103
+ if (target.revision !== undefined) {
104
+ const label = target.kind === "git_revision" ? "Revision" : "Base revision";
105
+ lines.push(`**${label}:** ${target.revision}`);
106
+ }
107
+ if (target.baseRevision !== undefined) {
108
+ lines.push(`**Diff base revision:** ${target.baseRevision}`);
109
+ }
110
+ if (target.headRevision !== undefined) {
111
+ lines.push(`**Diff head revision:** ${target.headRevision}`);
112
+ }
113
+ if (target.snapshotDigest !== undefined) {
114
+ lines.push(`**Snapshot digest:** ${target.snapshotDigest}`);
115
+ }
116
+ return lines;
117
+ }
118
+ function scanMode(mode) {
119
+ if (mode === "deep_repository")
120
+ return "deep";
121
+ if (mode === "repository")
122
+ return "standard";
123
+ return mode;
124
+ }
125
+ function renderLocation(target, location) {
126
+ const role = location.role === undefined ? "Location" : humanizeRole(location.role);
127
+ const label = `${location.path}:${location.startLine}${location.endLine === undefined || location.endLine === location.startLine
128
+ ? ""
129
+ : `-${location.endLine}`}`;
130
+ const sourceUrl = immutableSourceUrl(target, location);
131
+ return `- **${role}:** ${sourceUrl === undefined ? `\`${label}\`` : `[\`${label}\`](${sourceUrl})`}`;
132
+ }
133
+ function renderCodeEvidence(target, evidence) {
134
+ const location = {
135
+ path: evidence.path,
136
+ startLine: evidence.startLine,
137
+ ...(evidence.endLine === undefined ? {} : { endLine: evidence.endLine }),
138
+ ...(evidence.role === undefined ? {} : { role: evidence.role }),
139
+ };
140
+ return [
141
+ `### ${evidence.label}`,
142
+ "",
143
+ renderLocation(target, location),
144
+ "",
145
+ fencedCode(evidence.code, evidence.language),
146
+ "",
147
+ evidence.explanation,
148
+ ];
149
+ }
150
+ function humanizeRole(role) {
151
+ const words = role.replaceAll("_", " ");
152
+ return `${words.slice(0, 1).toUpperCase()}${words.slice(1)}`;
153
+ }
154
+ function fencedCode(code, language) {
155
+ let fenceLength = 3;
156
+ for (const match of code.matchAll(/`+/g)) {
157
+ fenceLength = Math.max(fenceLength, match[0].length + 1);
158
+ }
159
+ const fence = "`".repeat(fenceLength);
160
+ const tag = language !== undefined && /^[A-Za-z0-9_+.-]+$/.test(language)
161
+ ? language
162
+ : "";
163
+ return `${fence}${tag}\n${code}\n${fence}`;
164
+ }
165
+ function immutableSourceUrl(target, location) {
166
+ if (target.kind !== "git_revision" ||
167
+ target.remote === undefined ||
168
+ target.revision === undefined ||
169
+ !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(target.revision) ||
170
+ !isSafeRepositoryPath(location.path)) {
171
+ return undefined;
172
+ }
173
+ let remote;
174
+ try {
175
+ remote = new URL(target.remote);
176
+ }
177
+ catch {
178
+ return undefined;
179
+ }
180
+ if (remote.protocol !== "https:" ||
181
+ (remote.hostname !== "github.com" && !remote.hostname.endsWith(".ghe.com"))) {
182
+ return undefined;
183
+ }
184
+ const repository = remote.pathname
185
+ .replace(/\.git\/?$/, "")
186
+ .replace(/\/$/, "");
187
+ const path = location.path.split("/").map(encodeURIComponent).join("/");
188
+ remote.pathname = `${repository}/blob/${target.revision}/${path}`;
189
+ remote.hash = `L${location.startLine}${location.endLine === undefined || location.endLine === location.startLine
190
+ ? ""
191
+ : `-L${location.endLine}`}`;
192
+ return remote.toString();
193
+ }
194
+ function isSafeRepositoryPath(path) {
195
+ if (path.includes("\\") ||
196
+ /^[A-Za-z]:/.test(path) ||
197
+ /[\u0000-\u001f\u007f]/.test(path)) {
198
+ return false;
199
+ }
200
+ return path
201
+ .split("/")
202
+ .every((segment) => segment.length > 0 &&
203
+ segment !== "." &&
204
+ segment !== ".." &&
205
+ !/%(?:2e|2f|5c)/i.test(segment));
206
+ }
207
+ //# sourceMappingURL=publication.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publication.js","sourceRoot":"","sources":["../src/publication.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,YAAY,EAAuB,MAAM,eAAe,CAAC;AAQlE,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AA+BjD,MAAM,iBAAiB,GAAG;IACxB,QAAQ,EAAE,CAAC;IACX,IAAI,EAAE,CAAC;IACP,MAAM,EAAE,CAAC;IACT,GAAG,EAAE,CAAC;IACN,aAAa,EAAE,SAAS;CAC2C,CAAC;AAEtE,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,aAAqB,EACrB,OAAsC;IAEtC,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC,aA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CAAC;QACnB,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC;QACvB,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,EAClC,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,IAAI;SACR,KAAK,CAAC,GAAG,CAAC;SACV,KAAK,CACJ,CAAC,OAAO,EAAE,EAAE,CACV,OAAO,CAAC,MAAM,GAAG,CAAC;QAClB,OAAO,KAAK,GAAG;QACf,OAAO,KAAK,IAAI;QAChB,CAAC,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,CAClC,CAAC;AACN,CAAC","sourcesContent":["import { resolve } from \"node:path\";\nimport { loadContract, type LoadedContract } from \"./contract.js\";\nimport type {\n Finding,\n FindingCodeEvidence,\n FindingLocation,\n ScanTargetRecord,\n SeverityLevel,\n} from \"./models.js\";\nimport { bundledPluginRoot } from \"./runtime.js\";\n\nexport interface LinearPublicationDestination {\n type: \"linear\";\n teamId: string;\n projectId?: string;\n}\n\nexport interface PrepareScanPublicationOptions {\n destination: \"linear\";\n teamId: string;\n projectId?: string;\n uploadedAt?: string;\n}\n\nexport interface PreparedPublicationIssue {\n findingId: string;\n occurrenceId: string;\n title: string;\n description: string;\n priority?: 1 | 2 | 3 | 4;\n}\n\nexport interface PreparedScanPublication {\n scanId: string;\n uploadId: string;\n scanDirectory: string;\n destination: LinearPublicationDestination;\n issues: PreparedPublicationIssue[];\n}\n\nconst LINEAR_PRIORITIES = {\n critical: 1,\n high: 2,\n medium: 3,\n low: 4,\n informational: undefined,\n} as const satisfies Record<SeverityLevel, 1 | 2 | 3 | 4 | undefined>;\n\nexport async function prepareScanPublication(\n scanDirectory: string,\n options: PrepareScanPublicationOptions,\n): Promise<PreparedScanPublication> {\n const contract = await loadContract(scanDirectory, {\n pluginRoot: await bundledPluginRoot(),\n });\n const uploadedAt = options.uploadedAt ?? new Date().toISOString();\n const scanId = contract.manifest.scan.id;\n\n return {\n scanId,\n uploadId: scanId,\n scanDirectory: resolve(scanDirectory),\n destination: {\n type: options.destination,\n teamId: options.teamId,\n ...(options.projectId === undefined\n ? {}\n : { projectId: options.projectId }),\n },\n issues: contract.findings.findings.map((finding) => {\n const priority = LINEAR_PRIORITIES[finding.severity.level];\n return {\n findingId: finding.findingId,\n occurrenceId: finding.occurrenceId,\n title: `[Codex Security][${finding.severity.level.toUpperCase()}] ${finding.title}`,\n description: renderFindingDescription(contract, finding, uploadedAt),\n ...(priority === undefined ? {} : { priority }),\n };\n }),\n };\n}\n\nfunction renderFindingDescription(\n contract: LoadedContract,\n finding: Finding,\n uploadedAt: string,\n): string {\n const { coverage } = contract;\n const { scan } = contract.manifest;\n const lines = [\n \"## Codex Security finding\",\n \"\",\n `**Scan ID:** ${scan.id}`,\n `**Finding ID:** ${finding.findingId}`,\n `**Occurrence ID:** ${finding.occurrenceId}`,\n `**Fingerprint:** ${finding.fingerprints.primary}`,\n `**Severity:** ${finding.severity.level.toUpperCase()}`,\n `**Confidence:** ${finding.confidence.level.toUpperCase()}`,\n ...(finding.taxonomy.cwe.length === 0\n ? []\n : [`**CWE:** ${finding.taxonomy.cwe.join(\", \")}`]),\n \"\",\n \"## Scanned code\",\n \"\",\n `**Repository:** ${scan.target.displayName}`,\n ...(scan.target.remote === undefined\n ? []\n : [`**Remote:** ${scan.target.remote}`]),\n ...renderTargetIdentity(scan.target),\n `**Scanned scope:** ${scan.scope.includePaths.join(\", \") || \"entire repository\"}`,\n ...(scan.scope.excludePaths.length === 0\n ? []\n : [`**Excluded scope:** ${scan.scope.excludePaths.join(\", \")}`]),\n `**Coverage:** ${coverage.completeness}`,\n `**Coverage mode:** ${coverage.mode}`,\n `**Scan mode:** ${scanMode(coverage.mode)}`,\n `**Started:** ${scan.startedAt}`,\n `**Completed:** ${scan.completedAt}`,\n `**Uploaded:** ${uploadedAt}`,\n \"\",\n \"### Affected locations\",\n \"\",\n ...finding.locations.map((location) =>\n renderLocation(scan.target, location),\n ),\n \"\",\n \"## Summary\",\n \"\",\n finding.summary,\n ];\n\n const rootCause = finding.rootCause;\n if (typeof rootCause === \"string\") {\n lines.push(\"\", \"## Root cause\", \"\", rootCause);\n } else if (rootCause !== undefined) {\n lines.push(\"\", \"## Root cause\", \"\", rootCause.summary);\n if (rootCause.code !== undefined) {\n lines.push(\"\", fencedCode(rootCause.code, rootCause.language));\n }\n }\n\n if (finding.codeEvidence !== undefined && finding.codeEvidence.length > 0) {\n lines.push(\"\", \"## Source-code evidence\");\n for (const evidence of finding.codeEvidence) {\n lines.push(\"\", ...renderCodeEvidence(scan.target, evidence));\n }\n }\n\n lines.push(\"\", \"## Remediation\", \"\", finding.remediation);\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction renderTargetIdentity(target: ScanTargetRecord): string[] {\n const lines: string[] = [];\n if (target.revision !== undefined) {\n const label = target.kind === \"git_revision\" ? \"Revision\" : \"Base revision\";\n lines.push(`**${label}:** ${target.revision}`);\n }\n if (target.baseRevision !== undefined) {\n lines.push(`**Diff base revision:** ${target.baseRevision}`);\n }\n if (target.headRevision !== undefined) {\n lines.push(`**Diff head revision:** ${target.headRevision}`);\n }\n if (target.snapshotDigest !== undefined) {\n lines.push(`**Snapshot digest:** ${target.snapshotDigest}`);\n }\n return lines;\n}\n\nfunction scanMode(mode: LoadedContract[\"coverage\"][\"mode\"]): string {\n if (mode === \"deep_repository\") return \"deep\";\n if (mode === \"repository\") return \"standard\";\n return mode;\n}\n\nfunction renderLocation(\n target: ScanTargetRecord,\n location: FindingLocation,\n): string {\n const role =\n location.role === undefined ? \"Location\" : humanizeRole(location.role);\n const label = `${location.path}:${location.startLine}${\n location.endLine === undefined || location.endLine === location.startLine\n ? \"\"\n : `-${location.endLine}`\n }`;\n const sourceUrl = immutableSourceUrl(target, location);\n return `- **${role}:** ${sourceUrl === undefined ? `\\`${label}\\`` : `[\\`${label}\\`](${sourceUrl})`}`;\n}\n\nfunction renderCodeEvidence(\n target: ScanTargetRecord,\n evidence: FindingCodeEvidence,\n): string[] {\n const location: FindingLocation = {\n path: evidence.path,\n startLine: evidence.startLine,\n ...(evidence.endLine === undefined ? {} : { endLine: evidence.endLine }),\n ...(evidence.role === undefined ? {} : { role: evidence.role }),\n };\n return [\n `### ${evidence.label}`,\n \"\",\n renderLocation(target, location),\n \"\",\n fencedCode(evidence.code, evidence.language),\n \"\",\n evidence.explanation,\n ];\n}\n\nfunction humanizeRole(role: string): string {\n const words = role.replaceAll(\"_\", \" \");\n return `${words.slice(0, 1).toUpperCase()}${words.slice(1)}`;\n}\n\nfunction fencedCode(code: string, language?: string): string {\n let fenceLength = 3;\n for (const match of code.matchAll(/`+/g)) {\n fenceLength = Math.max(fenceLength, match[0].length + 1);\n }\n const fence = \"`\".repeat(fenceLength);\n const tag =\n language !== undefined && /^[A-Za-z0-9_+.-]+$/.test(language)\n ? language\n : \"\";\n return `${fence}${tag}\\n${code}\\n${fence}`;\n}\n\nfunction immutableSourceUrl(\n target: ScanTargetRecord,\n location: FindingLocation,\n): string | undefined {\n if (\n target.kind !== \"git_revision\" ||\n target.remote === undefined ||\n target.revision === undefined ||\n !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(target.revision) ||\n !isSafeRepositoryPath(location.path)\n ) {\n return undefined;\n }\n\n let remote: URL;\n try {\n remote = new URL(target.remote);\n } catch {\n return undefined;\n }\n if (\n remote.protocol !== \"https:\" ||\n (remote.hostname !== \"github.com\" && !remote.hostname.endsWith(\".ghe.com\"))\n ) {\n return undefined;\n }\n\n const repository = remote.pathname\n .replace(/\\.git\\/?$/, \"\")\n .replace(/\\/$/, \"\");\n const path = location.path.split(\"/\").map(encodeURIComponent).join(\"/\");\n remote.pathname = `${repository}/blob/${target.revision}/${path}`;\n remote.hash = `L${location.startLine}${\n location.endLine === undefined || location.endLine === location.startLine\n ? \"\"\n : `-L${location.endLine}`\n }`;\n return remote.toString();\n}\n\nfunction isSafeRepositoryPath(path: string): boolean {\n if (\n path.includes(\"\\\\\") ||\n /^[A-Za-z]:/.test(path) ||\n /[\\u0000-\\u001f\\u007f]/.test(path)\n ) {\n return false;\n }\n\n return path\n .split(\"/\")\n .every(\n (segment) =>\n segment.length > 0 &&\n segment !== \".\" &&\n segment !== \"..\" &&\n !/%(?:2e|2f|5c)/i.test(segment),\n );\n}\n"]}