1 #!/usr/bin/env node
2 // Create Linear triage tickets in the DX team for TRIAGE-state repository security
3 // advisories (reported at github.com/medusajs/medusa/security/advisories).
4 //
5 // Triage advisories are NOT delivered by the `repository_advisory` workflow event
6 // (that only fires on published/reported), so this polls the REST API for the
7 // `triage` state and creates one Linear issue per advisory. Dedup is stateless:
8 // before creating, we check the DX team for an existing issue whose title
9 // contains the advisory's GHSA id, so re-runs never duplicate.
10 //
11 // Usage:
12 // node scripts/security-advisories-to-linear.mjs
13 //
14 // Requires env:
15 // GH_TOKEN PAT / App token with "Repository security advisories: Read"
16 // (the built-in GITHUB_TOKEN cannot read advisories, esp. drafts).
17 // LINEAR_API_KEY Linear API key (personal or workspace).
18 // LINEAR_TEAM_ID UUID of the target Linear team (DX).
19
20 import { execSync } from "node:child_process"
21
22 const REPO = process.env.GITHUB_REPOSITORY || "medusajs/medusa"
23 const LINEAR_API = "https://api.linear.app/graphql"
24 const LINEAR_API_KEY = process.env.LINEAR_API_KEY
25 const LINEAR_TEAM_ID = process.env.LINEAR_TEAM_ID
26
27 if (!LINEAR_API_KEY || !LINEAR_TEAM_ID) {
28 console.error("Missing LINEAR_API_KEY or LINEAR_TEAM_ID env variable.")
29 process.exit(1)
30 }
31
32 // Fetch triage advisories via the `gh` CLI (auth comes from GH_TOKEN).
33 // --paginate follows the cursor Link headers; --slurp yields an array-of-pages.
34 function fetchAdvisories() {
35 const pages = JSON.parse(
36 execSync(
37 `gh api "/repos/${REPO}/security-advisories?state=triage&per_page=100" --paginate --slurp`,
38 { encoding: "utf8", maxBuffer: 50 * 1024 * 1024 }
39 )
40 ).flat()
41 return pages.filter((a) => a?.ghsa_id)
42 }
43
44 async function linear(query, variables) {
45 const res = await fetch(LINEAR_API, {
46 method: "POST",
47 headers: {
48 "Content-Type": "application/json",
49 Authorization: LINEAR_API_KEY,
50 },
51 body: JSON.stringify({ query, variables }),
52 })
53 const json = await res.json()
54 if (!res.ok || json.errors) {
55 throw new Error(`Linear API error: ${res.status} ${JSON.stringify(json.errors ?? json)}`)
56 }
57 return json.data
58 }
59
60 // Resolve the DX team's Triage workflow state so created issues land in Triage
61 // explicitly, regardless of the API's default-state behaviour.
62 async function getTriageStateId() {
63 const data = await linear(
64 `query ($id: String!) {
65 team(id: $id) { states { nodes { id type } } }
66 }`,
67 { id: LINEAR_TEAM_ID }
68 )
69 return data.team.states.nodes.find((s) => s.type === "triage")?.id ?? null
70 }
71
72 // A ticket already exists if any non-archived DX issue has the GHSA id in its title.
73 async function issueExists(ghsaId) {
74 const data = await linear(
75 `query ($teamId: ID!, $q: String!) {
76 issues(
77 filter: { team: { id: { eq: $teamId } }, title: { contains: $q } }
78 first: 1
79 ) { nodes { identifier } }
80 }`,
81 { teamId: LINEAR_TEAM_ID, q: ghsaId }
82 )
83 return data.issues.nodes.length > 0
84 }
85
86 function buildDescription(a) {
87 return [
88 `**GHSA:** ${a.ghsa_id}`,
89 a.cve_id ? `**CVE:** ${a.cve_id}` : null,
90 `**Severity:** ${a.severity ?? "unknown"}`,
91 `**State:** ${a.state}`,
92 `**Advisory:** ${a.html_url}`,
93 "",
94 a.description || a.summary || "_No description provided yet._",
95 "",
96 "---",
97 "_Automatically opened from a GitHub repository security advisory._",
98 ]
99 .filter((line) => line !== null)
100 .join("\n")
101 }
102
103 async function createIssue(a, triageStateId) {
104 const summary = a.summary ? `: ${a.summary}` : ""
105 const title = `[Security Advisory] ${a.ghsa_id}${summary}`.slice(0, 250)
106 const data = await linear(
107 `mutation ($input: IssueCreateInput!) {
108 issueCreate(input: $input) { success issue { identifier url } }
109 }`,
110 {
111 input: {
112 teamId: LINEAR_TEAM_ID,
113 title,
114 description: buildDescription(a),
115 ...(triageStateId ? { stateId: triageStateId } : {}),
116 },
117 }
118 )
119 if (!data.issueCreate.success) {
120 throw new Error(`issueCreate returned success=false for ${a.ghsa_id}`)
121 }
122 return data.issueCreate.issue
123 }
124
125 async function main() {
126 const advisories = fetchAdvisories()
127 console.log(`Found ${advisories.length} triage advisories in ${REPO}.`)
128
129 const triageStateId = await getTriageStateId()
130 if (!triageStateId) {
131 console.warn("No Triage state found on the team; issues will use the team default state.")
132 }
133
134 let created = 0
135 let skipped = 0
136 const failures = []
137
138 for (const a of advisories) {
139 try {
140 if (await issueExists(a.ghsa_id)) {
141 skipped++
142 console.log(`skip ${a.ghsa_id} (ticket already exists)`)
143 continue
144 }
145 const issue = await createIssue(a, triageStateId)
146 created++
147 console.log(`create ${a.ghsa_id} -> ${issue.identifier} ${issue.url}`)
148 } catch (err) {
149 failures.push(a.ghsa_id)
150 console.error(`error ${a.ghsa_id}: ${err.message}`)
151 }
152 }
153
154 console.log(`\nDone. created=${created} skipped=${skipped} failed=${failures.length}`)
155 if (failures.length) {
156 console.error(`Failed advisories: ${failures.join(", ")}`)
157 process.exit(1)
158 }
159 }
160
161 main().catch((err) => {
162 console.error(err)
163 process.exit(1)
164 })