@preventive/triage 1.0.0-alpha.6 → 1.0.0-alpha.60

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 (406) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +17 -0
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +3 -0
  13. package/common/bundle-compare-diff.js +376 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-metadata.d.ts +15 -0
  20. package/common/bundle-metadata.js +226 -0
  21. package/common/bundle-pkg-of.d.ts +1 -0
  22. package/common/bundle-pkg-of.js +90 -0
  23. package/common/bundle-reasons.d.ts +2 -0
  24. package/common/bundle-reasons.js +21 -0
  25. package/common/bundle-source-links.d.ts +6 -0
  26. package/common/bundle-source-links.js +216 -0
  27. package/common/bundle-sourcemap.d.ts +10 -0
  28. package/common/bundle-sourcemap.js +100 -0
  29. package/common/bundle-sources.d.ts +7 -0
  30. package/common/bundle-sources.js +333 -0
  31. package/common/bundle-stats.js +41 -0
  32. package/common/bundle-tabs.js +1 -0
  33. package/common/code-language.js +65 -0
  34. package/common/default-scan-models.ts +35 -0
  35. package/common/dependency-reviews.d.ts +18 -0
  36. package/common/dependency-reviews.js +64 -0
  37. package/common/finding-duplicates.js +58 -0
  38. package/common/finding-filters.js +274 -0
  39. package/common/finding-id.js +47 -0
  40. package/common/finding-repo.d.ts +5 -0
  41. package/common/finding-repo.js +67 -0
  42. package/common/github-issue-labels.d.ts +1 -0
  43. package/common/github-issue-labels.js +11 -0
  44. package/common/github-pr.ts +56 -0
  45. package/common/gzip.js +59 -0
  46. package/common/line-diff.d.ts +8 -0
  47. package/common/line-diff.js +57 -0
  48. package/common/linked-workspace-groups.js +63 -0
  49. package/common/managed/agent-tasks.ts +292 -0
  50. package/common/managed/comments.ts +34 -0
  51. package/common/managed/finding-detail.d.ts +5 -0
  52. package/common/managed/finding-detail.js +75 -0
  53. package/common/managed/finding-values.d.ts +2 -0
  54. package/common/managed/finding-values.js +44 -0
  55. package/common/managed/github-agents.ts +114 -0
  56. package/common/managed/github-logins.ts +49 -0
  57. package/common/managed/lite-name.d.ts +2 -0
  58. package/common/managed/lite-name.js +20 -0
  59. package/common/managed/npm-packages.d.ts +7 -0
  60. package/common/managed/npm-packages.js +51 -0
  61. package/common/managed/permissions.ts +31 -0
  62. package/common/managed/report-content.ts +72 -0
  63. package/common/managed/report-filter.ts +120 -0
  64. package/common/managed/repository-alias.ts +65 -0
  65. package/common/managed/roles.ts +35 -0
  66. package/common/managed/routes.d.ts +2 -0
  67. package/common/managed/routes.js +363 -0
  68. package/common/managed/scan-models.ts +6 -0
  69. package/common/managed/team-app.d.ts +15 -0
  70. package/common/managed/team-app.js +100 -0
  71. package/common/managed/team-filters.js +26 -0
  72. package/common/managed/triage.ts +83 -0
  73. package/common/managed/upload-seal.ts +126 -0
  74. package/common/pretty-print.d.ts +5 -0
  75. package/common/pretty-print.js +24 -0
  76. package/common/repo-commit.d.ts +4 -0
  77. package/common/repo-commit.js +30 -0
  78. package/common/revalidation-conflicts.js +48 -0
  79. package/common/revalidation-input-groups.js +56 -0
  80. package/common/save-error-reason.ts +20 -7
  81. package/common/scan-server.ts +13 -0
  82. package/common/security-links.d.ts +5 -0
  83. package/common/security-links.js +33 -0
  84. package/common/server-info.ts +46 -0
  85. package/common/utf8.d.ts +3 -0
  86. package/common/utf8.js +45 -0
  87. package/common/workspace-app.js +71 -0
  88. package/common/workspace-groups.js +176 -0
  89. package/out/activity.js +4 -0
  90. package/out/brotli-fallback.js +3 -3
  91. package/out/chunk-2SY4PYUQ.js +4 -0
  92. package/out/chunk-2XUEZHIP.js +28 -0
  93. package/out/chunk-4EMM6UCD.js +1 -0
  94. package/out/chunk-4HI2MSAV.js +17 -0
  95. package/out/chunk-4ISO5F7Y.js +7 -0
  96. package/out/chunk-4TQKM3JC.js +42 -0
  97. package/out/chunk-4XIH7YTX.js +1 -0
  98. package/out/chunk-6VDDCFHT.js +3 -0
  99. package/out/chunk-74AEKRES.js +10 -0
  100. package/out/chunk-7BKKYVWR.js +7 -0
  101. package/out/chunk-7C7DWL7I.js +1 -0
  102. package/out/chunk-C4Z6ZBXV.js +10 -0
  103. package/out/chunk-DEVAORP2.js +1 -0
  104. package/out/chunk-E3LFSUDJ.js +9 -0
  105. package/out/chunk-EEQHVKR3.js +1 -0
  106. package/out/chunk-G3LY2FV4.js +1 -0
  107. package/out/chunk-GO7FT4OD.js +1 -0
  108. package/out/chunk-HAZKDK4M.js +4 -0
  109. package/out/chunk-HNQNDNIE.js +12 -0
  110. package/out/chunk-HOB3YPS5.js +1 -0
  111. package/out/chunk-IYPY47MC.js +1 -0
  112. package/out/chunk-IZ6MYRYB.js +3 -0
  113. package/out/chunk-J2FWBXFV.js +1 -0
  114. package/out/chunk-JCIIBLKR.js +1 -0
  115. package/out/chunk-JFL7WLRV.js +1 -0
  116. package/out/chunk-JMG5DXII.js +2 -0
  117. package/out/chunk-JOXLZXMI.js +1 -0
  118. package/out/chunk-M37X4LCF.js +14 -0
  119. package/out/chunk-M3Y6SLC4.js +1 -0
  120. package/out/chunk-NRPC74AM.js +1 -0
  121. package/out/chunk-NXATZJQ2.js +1 -0
  122. package/out/chunk-OFPDMZJF.js +244 -0
  123. package/out/chunk-OOJM4CTU.js +1 -0
  124. package/out/chunk-OQRSIBSC.js +1 -0
  125. package/out/chunk-PAD2JHZT.js +1 -0
  126. package/out/chunk-PNHBZGDD.js +1 -0
  127. package/out/chunk-PTFQKLKO.js +1 -0
  128. package/out/chunk-PWFUOLZK.js +17 -0
  129. package/out/chunk-PXK7EU4V.js +1 -0
  130. package/out/chunk-QMVOEBWC.js +13 -0
  131. package/out/chunk-QRKFPLA4.js +80 -0
  132. package/out/chunk-R3NZFXVR.js +1 -0
  133. package/out/chunk-R5O6FAW4.js +2 -0
  134. package/out/chunk-RRBIJL2B.js +1 -0
  135. package/out/chunk-SYXT3SFP.js +2 -0
  136. package/out/chunk-TOXMUOIW.js +5 -0
  137. package/out/chunk-TUII34K2.js +1 -0
  138. package/out/chunk-TZS7KERJ.js +52 -0
  139. package/out/chunk-UCP3JRE2.js +1 -0
  140. package/out/chunk-VFWMQ3LG.js +2 -0
  141. package/out/chunk-VRX2APNA.js +9 -0
  142. package/out/chunk-VZJIHHTQ.js +1 -0
  143. package/out/chunk-WCPJDAYA.js +10 -0
  144. package/out/chunk-WMFDQS2L.js +11 -0
  145. package/out/chunk-WREU7JAG.js +1 -0
  146. package/out/chunk-Y5ZHFNBD.js +2 -0
  147. package/out/chunk-YF4M5OCI.js +1 -0
  148. package/out/chunk-YGRRXC2L.js +1 -0
  149. package/out/chunk-YTO6AQZM.js +2 -0
  150. package/out/chunk-Z667U2UJ.js +1 -0
  151. package/out/chunk-ZQHLECTI.js +1 -0
  152. package/out/client-managed-import.js +4 -0
  153. package/out/client-managed.js +34 -0
  154. package/out/client-sync.js +11 -17
  155. package/out/compare.js +35 -0
  156. package/out/dialogs.js +40 -0
  157. package/out/github-issue-authorized.html +3 -0
  158. package/out/github-issue-authorized.js +1 -0
  159. package/out/graph.js +19 -4
  160. package/out/index.html +106 -8
  161. package/out/prism.js +14 -10
  162. package/out/scan.js +2 -0
  163. package/out/stasis.svg +20 -0
  164. package/out/terminal.js +366 -39
  165. package/out/view.css +1 -1
  166. package/out/view.js +19 -144
  167. package/package.json +379 -62
  168. package/risk/actions/findings.js +161 -0
  169. package/risk/actions/resolve.js +250 -0
  170. package/risk/actions/scripts/commands.js +182 -0
  171. package/risk/actions/scripts/grade.js +113 -0
  172. package/risk/actions/scripts/packages.js +123 -0
  173. package/risk/actions/scripts/shell.js +169 -0
  174. package/risk/actions/uses.js +76 -0
  175. package/risk/actions/workflow.js +110 -0
  176. package/risk/files/characters.js +196 -0
  177. package/risk/files/hosts.js +205 -0
  178. package/risk/files/readability.js +177 -0
  179. package/risk/files/runs-code.js +615 -0
  180. package/risk/files/script.js +118 -0
  181. package/risk/files/stamps.js +47 -0
  182. package/risk/index.d.ts +272 -0
  183. package/risk/index.js +11 -0
  184. package/risk/npm/assess.js +285 -0
  185. package/risk/npm/combined.js +68 -0
  186. package/risk/npm/compare.js +257 -0
  187. package/risk/npm/dependencies.js +172 -0
  188. package/risk/npm/diff.js +79 -0
  189. package/risk/npm/downloads.js +84 -0
  190. package/risk/npm/files.js +445 -0
  191. package/risk/npm/held.js +63 -0
  192. package/risk/npm/install-scripts.js +34 -0
  193. package/risk/npm/malware.js +38 -0
  194. package/risk/npm/manifest.js +65 -0
  195. package/risk/npm/new-dependency.js +60 -0
  196. package/risk/npm/old-version.js +108 -0
  197. package/risk/npm/registry.js +390 -0
  198. package/risk/npm/release.js +85 -0
  199. package/risk/npm/score.js +59 -0
  200. package/risk/npm/specs.js +124 -0
  201. package/risk/npm/tarball.js +96 -0
  202. package/server-common/database-config.ts +16 -0
  203. package/server-common/initialize.ts +18 -0
  204. package/server-common/npm-advisories.ts +101 -0
  205. package/{server → server-common}/origin.ts +5 -5
  206. package/server-common/reap.ts +48 -0
  207. package/server-common/scan-config.ts +19 -0
  208. package/server-common/standalone.ts +29 -0
  209. package/server-common/storage-crypto.ts +182 -0
  210. package/server-common/storage-log.ts +38 -0
  211. package/server-common/vercel-blob.ts +103 -0
  212. package/server-e2e/app.ts +487 -0
  213. package/{server → server-e2e}/bus-receiver.ts +2 -1
  214. package/{server → server-e2e}/cli.js +9 -4
  215. package/{server → server-e2e}/config.ts +50 -42
  216. package/{server → server-e2e}/db-neon.ts +2 -2
  217. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  218. package/{server → server-e2e}/db-stmt.ts +2 -2
  219. package/{server → server-e2e}/db.ts +7 -7
  220. package/{server → server-e2e}/http.ts +44 -13
  221. package/{server → server-e2e}/hub.ts +40 -9
  222. package/server-e2e/index.ts +17 -0
  223. package/server-e2e/lifecycle.ts +95 -0
  224. package/{server → server-e2e}/neon-driver.ts +2 -2
  225. package/{server → server-e2e}/npm-proxy.ts +12 -145
  226. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  227. package/{server → server-e2e}/objstore/blob.ts +1 -1
  228. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  229. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  230. package/{server → server-e2e}/objstore/init.ts +19 -27
  231. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  232. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  233. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  234. package/{server → server-e2e}/objstore/rest.ts +3 -3
  235. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  236. package/{server → server-e2e}/objstore/store.ts +7 -7
  237. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  238. package/{server → server-e2e}/pubsub.ts +12 -9
  239. package/{server → server-e2e}/sign.ts +4 -4
  240. package/{server → server-e2e}/sse-server.ts +60 -33
  241. package/{server → server-e2e}/static.ts +31 -21
  242. package/{server → server-e2e}/sync-handlers.ts +64 -30
  243. package/{server → server-e2e}/ws-server.ts +20 -9
  244. package/server-managed/activity.ts +258 -0
  245. package/server-managed/agent-merges.ts +109 -0
  246. package/server-managed/app-agents.ts +23 -0
  247. package/server-managed/avatar-store.ts +13 -0
  248. package/server-managed/blob-store.ts +17 -0
  249. package/server-managed/brotli.ts +10 -0
  250. package/server-managed/bundle-advisories.ts +102 -0
  251. package/server-managed/bundle-advisory-inventory.ts +77 -0
  252. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  253. package/server-managed/bundle-build-diagnostics.js +23 -0
  254. package/server-managed/bundle-build-leases.ts +41 -0
  255. package/server-managed/bundle-build-worker.js +203 -0
  256. package/server-managed/bundle-build.ts +232 -0
  257. package/server-managed/bundle-cache.ts +211 -0
  258. package/server-managed/bundle-catalog.ts +29 -0
  259. package/server-managed/bundle-commits.ts +140 -0
  260. package/server-managed/bundle-dependency-reviews.ts +74 -0
  261. package/server-managed/bundle-store.ts +24 -0
  262. package/server-managed/bundle-summary-cache.ts +130 -0
  263. package/server-managed/bundle-validation.ts +32 -0
  264. package/server-managed/bundle.ts +119 -0
  265. package/server-managed/cache-storage.ts +20 -0
  266. package/server-managed/cli.js +21 -0
  267. package/server-managed/combined.ts +47 -0
  268. package/server-managed/comments.ts +151 -0
  269. package/server-managed/commit-coauthors.ts +106 -0
  270. package/server-managed/commit-lockfiles.ts +76 -0
  271. package/server-managed/comparison.ts +52 -0
  272. package/server-managed/config.ts +164 -0
  273. package/server-managed/content-access.ts +15 -0
  274. package/server-managed/crypto.ts +25 -0
  275. package/server-managed/db-methods.ts +1958 -0
  276. package/server-managed/db-neon.ts +484 -0
  277. package/server-managed/db-schema.ts +238 -0
  278. package/server-managed/db-table-names.ts +22 -0
  279. package/server-managed/db.ts +152 -0
  280. package/server-managed/dependabot-access.ts +60 -0
  281. package/server-managed/dependabot-alerts.ts +185 -0
  282. package/server-managed/dependency-review-comments.ts +98 -0
  283. package/server-managed/dependency-reviews.ts +364 -0
  284. package/server-managed/github-accounts.ts +60 -0
  285. package/server-managed/github-actions.ts +71 -0
  286. package/server-managed/github-app.ts +376 -0
  287. package/server-managed/github-errors.ts +70 -0
  288. package/server-managed/github-graphql.ts +39 -0
  289. package/server-managed/github-issue-links.ts +244 -0
  290. package/server-managed/github-issue-oauth.ts +47 -0
  291. package/server-managed/github-issues.ts +155 -0
  292. package/server-managed/github-link-oauth.ts +69 -0
  293. package/server-managed/github-links.ts +204 -0
  294. package/server-managed/github-metadata.ts +213 -0
  295. package/server-managed/github-oauth.ts +238 -0
  296. package/server-managed/github-pulls.ts +246 -0
  297. package/server-managed/github-requests.ts +166 -0
  298. package/server-managed/github-users.ts +30 -0
  299. package/server-managed/history-windows.ts +172 -0
  300. package/server-managed/http-response.ts +76 -0
  301. package/server-managed/http.ts +5855 -0
  302. package/server-managed/import-triage.ts +51 -0
  303. package/server-managed/index.ts +204 -0
  304. package/server-managed/kept-briefly.ts +37 -0
  305. package/server-managed/kept.ts +28 -0
  306. package/server-managed/link-reports.ts +162 -0
  307. package/server-managed/listed-activity.ts +39 -0
  308. package/server-managed/locked-packages.ts +152 -0
  309. package/server-managed/lockfile-scope.ts +49 -0
  310. package/server-managed/lru.ts +30 -0
  311. package/server-managed/managed-issues.ts +92 -0
  312. package/server-managed/management-catalog.ts +45 -0
  313. package/server-managed/management.ts +99 -0
  314. package/server-managed/npm-delta-worker.js +23 -0
  315. package/server-managed/npm-delta.ts +194 -0
  316. package/server-managed/npm-insights.ts +450 -0
  317. package/server-managed/npm-kept.ts +233 -0
  318. package/server-managed/npm-loads.ts +264 -0
  319. package/server-managed/npm-manifest.ts +115 -0
  320. package/server-managed/npm-packages.ts +454 -0
  321. package/server-managed/npm-patch.ts +325 -0
  322. package/server-managed/npm-provenance.ts +123 -0
  323. package/server-managed/npm-risk.ts +285 -0
  324. package/server-managed/object-storage-disk.ts +148 -0
  325. package/server-managed/object-storage-vercel.ts +67 -0
  326. package/server-managed/object-storage.ts +75 -0
  327. package/server-managed/package-entry-points.ts +79 -0
  328. package/server-managed/pretty-print.ts +436 -0
  329. package/server-managed/public-workspace.ts +238 -0
  330. package/server-managed/pull-comment-reviews.ts +161 -0
  331. package/server-managed/pull-dependencies.ts +351 -0
  332. package/server-managed/pull-dependency-reviews.ts +334 -0
  333. package/server-managed/pull-reviews.ts +205 -0
  334. package/server-managed/queue.ts +39 -0
  335. package/server-managed/release-commits.ts +84 -0
  336. package/server-managed/rename-diff-worker.js +26 -0
  337. package/server-managed/rename-diff.ts +279 -0
  338. package/server-managed/repo-path.ts +21 -0
  339. package/server-managed/report-migration.ts +35 -0
  340. package/server-managed/report-query.ts +10 -0
  341. package/server-managed/report-response.ts +16 -0
  342. package/server-managed/report-sources.ts +185 -0
  343. package/server-managed/report-store.ts +85 -0
  344. package/server-managed/repository-actions.ts +221 -0
  345. package/server-managed/repository-agents.ts +448 -0
  346. package/server-managed/repository-aliases.ts +91 -0
  347. package/server-managed/repository-browser.ts +301 -0
  348. package/server-managed/repository-changes.ts +284 -0
  349. package/server-managed/repository-code.ts +215 -0
  350. package/server-managed/repository-dependency-reviews.ts +166 -0
  351. package/server-managed/repository-discovery.ts +82 -0
  352. package/server-managed/repository-history.ts +432 -0
  353. package/server-managed/repository-issues.ts +195 -0
  354. package/server-managed/repository-policy.ts +27 -0
  355. package/server-managed/repository-pulls.ts +212 -0
  356. package/server-managed/repository-pulse.ts +471 -0
  357. package/server-managed/repository-risk-assess.ts +105 -0
  358. package/server-managed/repository-risk-audit.ts +78 -0
  359. package/server-managed/repository-risk-read.ts +170 -0
  360. package/server-managed/repository-risk.ts +491 -0
  361. package/server-managed/repository-squashes.ts +168 -0
  362. package/server-managed/repository-stamp.ts +41 -0
  363. package/server-managed/request-timing.ts +63 -0
  364. package/server-managed/reviewed-dependencies.ts +149 -0
  365. package/server-managed/revisions.ts +35 -0
  366. package/server-managed/scan-downloads.ts +87 -0
  367. package/server-managed/session.ts +132 -0
  368. package/server-managed/slugs.ts +38 -0
  369. package/server-managed/solidity-entry-points.ts +71 -0
  370. package/server-managed/sql-postgres.ts +34 -0
  371. package/server-managed/sql.ts +89 -0
  372. package/server-managed/stasis-config.ts +55 -0
  373. package/server-managed/static.ts +28 -0
  374. package/server-managed/storage-command.ts +16 -0
  375. package/server-managed/storage-db.ts +183 -0
  376. package/server-managed/storage-encryption.ts +290 -0
  377. package/server-managed/storage-maintenance.ts +259 -0
  378. package/server-managed/storage-payload.ts +121 -0
  379. package/server-managed/storage-stores.ts +91 -0
  380. package/server-managed/storage.ts +82 -0
  381. package/server-managed/team-app-summaries.ts +54 -0
  382. package/server-managed/team-app.ts +157 -0
  383. package/server-managed/team-catalog.ts +7 -0
  384. package/server-managed/team-feed.ts +180 -0
  385. package/server-managed/team-npm-scopes.ts +106 -0
  386. package/server-managed/team-reports.ts +351 -0
  387. package/server-managed/triage-response.ts +16 -0
  388. package/server-managed/type-only-worker.js +19 -0
  389. package/server-managed/type-only.ts +105 -0
  390. package/server-managed/uploads.ts +106 -0
  391. package/server-managed/upstream-cache.ts +252 -0
  392. package/server-managed/view-as.ts +58 -0
  393. package/server-managed/workspace-shares.ts +171 -0
  394. package/server.ts +70 -0
  395. package/server/index.ts +0 -480
  396. package/server/lifecycle.ts +0 -208
  397. /package/{LICENSE → LICENSE-MIT} +0 -0
  398. /package/{server → server-e2e}/auth.ts +0 -0
  399. /package/{server → server-e2e}/config.example.json +0 -0
  400. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  401. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  402. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  403. /package/{server → server-e2e}/peer.ts +0 -0
  404. /package/{server → server-e2e}/sse-session.ts +0 -0
  405. /package/{server → server-e2e}/util.ts +0 -0
  406. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,113 @@
1
+ // What a `run:` script fetches and runs (commands.js), graded (README.md).
2
+ import { HOST_TAGS, npmExfiltration, npmHostTags } from '../../files/hosts.js'
3
+ import { lineOf } from '../../files/script.js'
4
+ import { installsOf, scriptFinds } from './commands.js'
5
+
6
+ // The events a workflow runs on with its secrets for anyone's pull request.
7
+ const PRIVILEGED_TRIGGERS = new Set(['pull_request_target', 'workflow_run', 'issue_comment', 'issues', 'discussion', 'discussion_comment',
8
+ 'pull_request_review', 'pull_request_review_comment', 'fork', 'watch'])
9
+
10
+ // The expressions anyone can write: a title, a body, a branch's name, a
11
+ // commit's message, a fork's description.
12
+ const INDEX = String.raw`(?:\s*\[[^\]]*\]|\.\*)`
13
+ const AUTHOR = String.raw`(?:author|committer)\.(?:email|name)`
14
+ const UNTRUSTED = new RegExp(String.raw`\bgithub\s*\.\s*(?:head_ref|event\s*\.\s*(?:`
15
+ + [String.raw`issue\.(?:title|body)`,
16
+ String.raw`pull_request\.(?:title|body|head\.(?:ref|label|repo\.(?:default_branch|description|homepage)))`,
17
+ String.raw`(?:comment|review|review_comment)\.body`,
18
+ String.raw`pages${INDEX}\.page_name`,
19
+ String.raw`commits${INDEX}\.(?:message|${AUTHOR})`,
20
+ String.raw`head_commit\.(?:message|${AUTHOR})`,
21
+ String.raw`workflow_run\.(?:head_branch|display_title|head_commit\.(?:message|${AUTHOR})|head_repository\.(?:description|homepage|default_branch)|pull_requests${INDEX}\.head\.ref)`,
22
+ String.raw`discussion\.(?:title|body)`].join('|')
23
+ + String.raw`))(?![\w-])`, 'gu')
24
+
25
+ // An expression with its index syntax's properties (`github['event']`) as
26
+ // dereferences, as GitHub reads either.
27
+ export const dotted = text => text.replaceAll(/\[\s*'([\w-]+)'\s*\]/gu, '.$1')
28
+
29
+ // Each expression anyone can write in a script's `text`, a finding with
30
+ // the `index` its `${{` is at: red where the workflow runs with its secrets
31
+ // for anyone (`triggers`), else orange.
32
+ export function scriptInjections(text, triggers) {
33
+ if (typeof text !== 'string' || !text.includes('${{')) return []
34
+ const severity = triggers.some(event => PRIVILEGED_TRIGGERS.has(event)) ? 'critical' : 'high'
35
+ return [...text.matchAll(/\$\{\{([\s\S]*?)\}\}/gu)].flatMap(({ 1: inner, index }) =>
36
+ [...dotted(inner).matchAll(UNTRUSTED)].map(({ 0: expression }) => ({ id: 'script-injection', severity, expression: expression.replaceAll(/\s+/gu, ''), index })))
37
+ }
38
+
39
+ // A ref or a repository naming a pull request's own code, as
40
+ // `actions/checkout` checks it out: its head's commit or branch (a
41
+ // `workflow_run`'s pull requests' too), or the fork's repository, whose
42
+ // default branch it is then.
43
+ const PULL_HEAD = new RegExp(String.raw`\bgithub\.(?:head_ref|event\.(?:number|pull_request\.(?:number|merge_commit_sha|head\.(?:sha|ref|repo\.(?:full_name|owner\.login)))|workflow_run\.(?:head_sha|head_branch|head_commit\.id|pull_requests\[[^\]]*\]\.head\.(?:sha|ref)|head_repository\.(?:full_name|owner\.login))))\b`
44
+ .replaceAll('\\.', String.raw`\s*\.\s*`) + String.raw`|refs\/pull\/`, 'u')
45
+ export const namesPullHead = text => typeof text === 'string' && PULL_HEAD.test(dotted(text))
46
+
47
+ // Programs whose package is named otherwise: `npx tsc` runs typescript's.
48
+ const KNOWN_BINS = new Map([['tsc', 'typescript'], ['tsserver', 'typescript'], ['ng', '@angular/cli'], ['nest', '@nestjs/cli'],
49
+ ['changeset', '@changesets/cli'], ['biome', '@biomejs/biome'], ['svelte-kit', '@sveltejs/kit'], ['api-extractor', '@microsoft/api-extractor'],
50
+ ['commitlint', '@commitlint/cli'], ['attw', '@arethetypeswrong/cli'], ['ncu', 'npm-check-updates'], ['vue-cli-service', '@vue/cli-service'],
51
+ ['firebase', 'firebase-tools'], ['netlify', 'netlify-cli'], ['cdk', 'aws-cdk'], ['sls', 'serverless'], ['playwright', '@playwright/test'],
52
+ ['eas', 'eas-cli'], ['expo', 'expo'], ['vsce', '@vscode/vsce'], ['wdio', '@wdio/cli'], ['lhci', '@lhci/cli'], ['tsx', 'tsx'], ['webpack', 'webpack-cli']])
53
+ const PACKAGING = new Set(['pip', 'setuptools', 'wheel'])
54
+
55
+ // Whether `locked` (a Set) has what npx runs by `name`, or the package giving it.
56
+ export const lockedName = (locked, name) => locked.has(name) || (KNOWN_BINS.has(name) && locked.has(KNOWN_BINS.get(name)))
57
+
58
+ // How severe fetching a package is; null for none.
59
+ function packageSeverity(found, { locked, installed, external }) {
60
+ const runsOwn = found.ecosystem === 'npm' && found.localFirst && found.registry && (found.spec === null || found.exact)
61
+ if (runsOwn && (external ? installed : locked && installed)) return null
62
+ if (found.ecosystem === 'go' && found.exact) return null
63
+ if (found.ecosystem === 'crates' && found.exact && found.locked) return null
64
+ if (found.ecosystem === 'pypi' && PACKAGING.has(found.name.toLowerCase())) return 'notice'
65
+ // A version a variable names may be one, set elsewhere in the workflow.
66
+ return found.exact || found.spec?.includes('$') ? 'moderate' : 'high'
67
+ }
68
+
69
+ // The findings of one find of a script, `locked` what a lockfile says of it.
70
+ function graded(found, context, locked) {
71
+ if (found.kind === 'package') {
72
+ const { tool, name, spec, localFirst } = found, installed = context.installed
73
+ const severity = packageSeverity(found, { locked, installed, external: context.external })
74
+ return severity ? [{ id: 'fetched-package', severity, tool, name, spec, ...localFirst ? { localFirst, locked, installed } : {} }] : []
75
+ }
76
+ if (found.kind === 'unlocked-install') return [{ id: 'unlocked-install', severity: /^(?:yarn|bun)\b/u.test(found.tool) ? 'low' : 'moderate', tool: found.tool }]
77
+ if (found.kind === 'remote-script') return [{ id: 'remote-script', severity: 'high', command: found.command }]
78
+ if (found.kind === 'image') return found.read?.digest ? [] : [imageFinding(found.text, found.read)]
79
+ return found.kind === 'clone' ? [{ id: 'clone', severity: 'low', url: found.url }] : []
80
+ }
81
+
82
+ // An image run by a tag: orange with none or `latest`, else yellow.
83
+ export const imageFinding = (text, read) => ({ id: 'unpinned-image', severity: !read || read.tag === null || read.tag === 'latest' ? 'high' : 'moderate', image: text })
84
+
85
+ // The file's line a script's line is on: a `|` block scalar's own, else `run:`'s.
86
+ const fileLine = (run, line) => run.start === null ? run.line : run.start + line
87
+
88
+ // Whether `dir` is `directory` or above it, as node finds a package there;
89
+ // null for anywhere.
90
+ export const within = (dir, directory) => dir === null || dir === '' || directory === dir || directory.startsWith(`${dir}/`)
91
+
92
+ // Every finding of a `run` script (workflow.js runOf); `context`'s
93
+ // `locked(name, dir)` whether a lockfile there locks it (`dev` where
94
+ // devDependencies alone need it), `installed(dev, dir)` whether an install
95
+ // ran before that installs such a package there, `dir` a path from the
96
+ // step's directory, as a `cd` moves to.
97
+ export function scriptFindings(run, context) {
98
+ const findings = []
99
+ // An install earlier in the script counts as one in a step before.
100
+ const installs = installsOf(run.script, run.production)
101
+ for (const found of scriptFinds(run.script)) {
102
+ const dir = found.dir ?? ''
103
+ const locked = found.kind === 'package' && found.ecosystem === 'npm' && found.localFirst && context.locked(found.exact ? `${found.name}@${found.spec.replace(/^[v=]/u, '')}` : found.name, dir)
104
+ const before = context.installed(locked === 'dev', dir) || installs.some(({ order, into, prod }) => order < found.order && within(into, dir) && !(prod && locked === 'dev'))
105
+ for (const finding of graded(found, { ...context, installed: before }, Boolean(locked))) findings.push({ ...finding, line: fileLine(run, found.line) })
106
+ }
107
+ for (const [tag, services] of npmHostTags(npmExfiltration('run.sh', run.script, true))) {
108
+ findings.push({ id: 'hosts', severity: HOST_TAGS.get(tag), tag, services: [...services.keys()], line: fileLine(run, Math.min(...[...services.values()].flat()) - 1) })
109
+ }
110
+ const line = lineOf(run.script)
111
+ for (const { index, ...finding } of scriptInjections(run.script, context.triggers)) findings.push({ ...finding, line: fileLine(run, line(index) - 1) })
112
+ return findings
113
+ }
@@ -0,0 +1,123 @@
1
+ // What a command of npm's tools fetches and runs past what a lockfile locks
2
+ // (commands.js), npx's and its kin's the project's own where installed
3
+ // (`localFirst`), and an install that resolves anew (`unlocked`).
4
+ import { isExactVersion } from '@preventive/upstream/semver.js'
5
+
6
+ // A package spec's name and spec, `exact` for a version, `registry: false` for
7
+ // a URL, a path, git or a GitHub shorthand.
8
+ export function npmSpec(text) {
9
+ if (/^(?:\.{0,2}\/|~|[a-z][\w+.-]*:|[\w.-]+\/[\w.-]+(?:#.*)?$)/iu.test(text) && !/^@[\w.-]+\//u.test(text)) {
10
+ return { name: text, spec: null, exact: false, registry: false }
11
+ }
12
+ const at = text.indexOf('@', text.startsWith('@') ? 1 : 0)
13
+ const name = at === -1 ? text : text.slice(0, at)
14
+ const spec = at === -1 ? null : text.slice(at + 1)
15
+ if (!/^(?:@[\w.-]+\/)?[\w.-]+$/u.test(name)) return null
16
+ return { name, spec, exact: spec !== null && isExactVersion(spec.replace(/^[v=]/u, '')), registry: true }
17
+ }
18
+
19
+ // A package a tool fetches, as a script's find; none for none.
20
+ export const fetched = (tool, spec, { ecosystem = 'npm', localFirst = false, ...more } = {}) => spec ? [{ kind: 'package', tool, ecosystem, localFirst, ...more, ...spec }] : []
21
+
22
+ // What `npm create x` runs: `create-x`, `@s/create` for `@s`, `@s/create-x`.
23
+ function createPackage(text) {
24
+ const scoped = /^(@[\w.-]+)(?:@(.+))?$/u.exec(text)
25
+ if (scoped) return npmSpec(`${scoped[1]}/create${scoped[2] ? `@${scoped[2]}` : ''}`)
26
+ const spec = npmSpec(text)
27
+ if (!spec?.registry) return spec
28
+ const [scope, name] = spec.name.startsWith('@') ? spec.name.split('/') : [null, spec.name]
29
+ const named = scope ? (name ? `${scope}/create-${name}` : `${scope}/create`) : `create-${name}`
30
+ return { ...spec, name: named }
31
+ }
32
+
33
+ // Options of npm's tools that take a value.
34
+ const VALUED = /^(?:-[pcwC]|--(?:package|call|cache|userconfig|registry|workspace|prefix|filter|dir|global-dir|store-dir|loglevel|cwd|spec|location|include|omit|only))$/u
35
+ const GLOBAL = /^(?:-g|--global|--location=global)$/u
36
+
37
+ // A command's words past `from`: those not options (`operands`), all past
38
+ // `--` too, and each option's values (`values`), of `--x=v`, and `--x v` for
39
+ // one `valued` names.
40
+ export function optionsOf(argv, from, valued = VALUED) {
41
+ const operands = [], values = new Map()
42
+ for (let at = from; at < argv.length; at++) {
43
+ const [, name, joined] = /^(--[\w-]+)=(.*)$/u.exec(argv[at]) ?? [], word = argv[at]
44
+ if (word === '--') return { operands: [...operands, ...argv.slice(at + 1)], values }
45
+ if (name || valued.test(word)) values.set(name ?? word, [...values.get(name ?? word) ?? [], joined ?? argv[++at] ?? ''])
46
+ else if (!word.startsWith('-')) operands.push(word)
47
+ }
48
+ return { operands, values }
49
+ }
50
+ const positional = (argv, from) => optionsOf(argv, from).operands
51
+ // The values of `names`' options, in their order.
52
+ export const valuesOf = ({ values }, ...names) => names.flatMap(name => values.get(name) ?? [])
53
+
54
+ // What an exec (npx, `npm exec`, bunx, dlx) fetches: its `--package`s, else
55
+ // its command's; none with `--no`, `--offline`, or a command line (`-c`).
56
+ function execPackages(tool, argv, from, localFirst) {
57
+ if (argv.some(word => /^(?:--no|--no-install|--offline)$/u.test(word))) return []
58
+ const named = valuesOf(optionsOf(argv, 1), '-p', '--package').filter(Boolean)
59
+ if (named.length === 0 && argv.some(word => word === '-c' || word === '--call')) return []
60
+ return (named.length > 0 ? named : positional(argv, from).slice(0, 1)).flatMap(text => fetched(tool, npmSpec(text), { localFirst }))
61
+ }
62
+
63
+ // The directory an install names for its project (`--prefix`, `-C`, `--dir`,
64
+ // `--cwd`); null for the one it runs in, `.` too.
65
+ export function projectOf(argv) {
66
+ const [dir = null] = valuesOf(optionsOf(argv, 1), '-C', '--prefix', '--dir', '--cwd')
67
+ return dir === null || /^\.\/?$/u.test(dir) ? null : dir
68
+ }
69
+
70
+ const installs = (tool, words) => words.flatMap(text => fetched(tool, npmSpec(text)))
71
+ // npm's install command and its aliases (commands.js installsOf).
72
+ export const NPM_INSTALLS = 'i|in|ins|inst|insta|instal|install|isnt|isnta|isntal|isntall|add|it|install-test'
73
+ const created = (tool, text) => text ? fetched(tool, createPackage(text)) : []
74
+ const unlocked = tool => [{ kind: 'unlocked-install', tool }]
75
+ const isInstalled = word => /^(?:\.{1,2}(?:\/|$)|file:|link:|workspace:)/u.test(word)
76
+
77
+ function npm(argv) {
78
+ const [command = '', ...rest] = positional(argv, 1)
79
+ if (command === 'exec' || command === 'x') return execPackages(`npm ${command}`, argv, argv.indexOf(command) + 1, true)
80
+ if (/^(?:create|init|innit)$/u.test(command)) return created(`npm ${command}`, rest[0])
81
+ if (new RegExp(`^(?:${NPM_INSTALLS})$`, 'u').test(command)) {
82
+ const named = rest.filter(word => !isInstalled(word))
83
+ if (argv.some(word => GLOBAL.test(word))) return installs(`npm ${command} -g`, named)
84
+ return named.length > 0 ? installs(`npm ${command}`, named) : unlocked(`npm ${command}`)
85
+ }
86
+ return /^(?:update|up|upgrade|udpate)$/u.test(command) ? unlocked(`npm ${command}`) : []
87
+ }
88
+
89
+ // pnpm's and bun's, by the word each runs a package with (`exec`), what an
90
+ // install resolving anew is told by (`anew`, null for none), and its updates.
91
+ const pnpmLike = (program, exec, localFirst, anew, updates) => argv => {
92
+ const [command = '', ...rest] = positional(argv, 1)
93
+ if (command === exec) return execPackages(`${program} ${exec}`, argv, argv.indexOf(exec) + 1, localFirst)
94
+ if (command === 'create') return created(`${program} create`, rest[0])
95
+ const global = argv.some(word => GLOBAL.test(word)), installing = command === 'install' || command === 'i'
96
+ if (command === 'add' || (installing && rest.length > 0)) return installs(`${program} ${command}${global ? ' -g' : ''}`, rest.filter(word => !isInstalled(word)))
97
+ if (installing && anew(argv) !== null) return unlocked(`${program} ${command}${anew(argv)}`)
98
+ return updates.test(command) ? unlocked(`${program} ${command}`) : []
99
+ }
100
+ const pnpm = pnpmLike('pnpm', 'dlx', false, argv => argv.includes('--no-frozen-lockfile') ? ' --no-frozen-lockfile' : null, /^(?:update|up|upgrade)$/u)
101
+ const bun = pnpmLike('bun', 'x', true, argv => argv.some(word => word === '--frozen-lockfile' || word === '--ci') ? null : '', /^update$/u)
102
+
103
+ function yarn(argv) {
104
+ const [command = '', ...rest] = positional(argv, 1)
105
+ if (command === 'dlx') return execPackages('yarn dlx', argv, argv.indexOf('dlx') + 1, false)
106
+ if (command === 'create') return created('yarn create', rest[0])
107
+ if (command === 'global' && rest[0] === 'add') return installs('yarn global add', rest.slice(1))
108
+ if (command === 'add') return installs('yarn add', rest.filter(word => !isInstalled(word)))
109
+ const frozen = argv.some(word => /^--(?:frozen-lockfile|immutable)$/u.test(word))
110
+ if ((command === '' || command === 'install') && !frozen) return unlocked(command ? 'yarn install' : 'yarn')
111
+ return /^(?:upgrade|up)$/u.test(command) ? unlocked(`yarn ${command}`) : []
112
+ }
113
+
114
+ // The tools that run a package (whether one installed first), and the rest.
115
+ const EXECS = new Map([['npx', true], ['bunx', true], ['pnpx', false]])
116
+ const TOOLS = new Map([['npm', npm], ['pnpm', pnpm], ['yarn', yarn], ['bun', bun]])
117
+
118
+ // What a command of npm's tools fetches, by its program's name: packages and
119
+ // installs resolving anew.
120
+ export function npmToolFinds(program, argv) {
121
+ if (EXECS.has(program)) return execPackages(program, argv, 1, EXECS.get(program))
122
+ return TOOLS.get(program)?.(argv) ?? []
123
+ }
@@ -0,0 +1,169 @@
1
+ // A `run:` script read into the commands it runs, as a shell would split
2
+ // them, for commands.js. A quick read, not a shell's parse: a command built
3
+ // as the script runs goes unseen.
4
+ import { SHELLS } from '../../files/runs-code.js'
5
+ import { resolved } from '../../npm/files.js'
6
+
7
+ // A shell, by its program, wherever it is, Windows' `.exe` too (risk's
8
+ // runs-code.js SHELLS).
9
+ const SHELL = new RegExp(String.raw`^(?:.*[\/\\])?${SHELLS}(?:\.exe)?$`, 'iu')
10
+
11
+ // A line of a script, its continuations joined (an escaped line's end, or a
12
+ // pipe, `&&` or `||` the next line goes on from), and the line it starts
13
+ // on, counting from 0.
14
+ export function scriptLines(script) {
15
+ // An expression (`${{ … }}`), which GitHub writes in before the shell reads
16
+ // the script, read as a variable is: a value unknown here, each line it
17
+ // spans past its first continuing the one it is on; a `}}` in one of its
18
+ // strings (`format('{{0}}')`) not its end.
19
+ const lines = script.replaceAll(/\$\{\{(?:'[^']*'|[^'])*?\}\}/gu, expression => `$EXPRESSION${' \\\n'.repeat(expression.split('\n').length - 1)}`).split('\n')
20
+ const joined = []
21
+ for (let at = 0; at < lines.length; at++) {
22
+ const start = at
23
+ let text = lines[at].replace(/\r$/u, '')
24
+ for (;;) {
25
+ const escaped = /(?:^|[^\\])(?:\\\\)*[\\`^]$/u.test(text), piped = /(?:\||&&)\s*$/u.test(text) && !/(?:^|\s)#/u.test(text)
26
+ if (!(escaped || piped) || at + 1 === lines.length) break
27
+ text = `${escaped ? text.slice(0, -1) : text} ${lines[++at].replace(/\r$/u, '')}`
28
+ }
29
+ joined.push({ text, line: start })
30
+ }
31
+ return joined
32
+ }
33
+
34
+ const WRAPPERS = new Set(['sudo', 'env', 'time', 'nohup', 'exec', 'command', 'nice', 'stdbuf', 'xvfb-run', 'timeout', 'corepack'])
35
+ // A wrapper's options taking a value, as `sudo -u user`, `timeout 10m` do.
36
+ const WRAPPER_VALUES = new Map([['sudo', /^-[ugCDhpRrTU]$/u], ['env', /^-[uC]$/u], ['nice', /^-n$/u], ['timeout', /^-[sk]$/u]])
37
+
38
+ // What a command runs (`argv`): its words past settings, kept (`env`), and
39
+ // wrappers, a wrapper's options and their values, and `timeout`'s duration.
40
+ function argvOf(words) {
41
+ const env = {}
42
+ let at = 0
43
+ for (;;) {
44
+ for (; at < words.length && /^[A-Za-z_]\w*=/u.test(words[at]); at++) env[words[at].slice(0, words[at].indexOf('='))] = words[at].slice(words[at].indexOf('=') + 1)
45
+ const wrapper = words[at]?.replace(/^.*\//u, '')
46
+ if (!WRAPPERS.has(wrapper)) return { argv: words.slice(at), env }
47
+ at++
48
+ while (at < words.length && words[at].startsWith('-')) at += WRAPPER_VALUES.get(wrapper)?.test(words[at]) ? 2 : 1
49
+ if (wrapper === 'timeout' && /^\d/u.test(words[at] ?? '')) at++
50
+ }
51
+ }
52
+
53
+ // A command's words, quotes taken off, redirections dropped, and the file
54
+ // its output is written to (`> file`, `>> file`), or null.
55
+ function wordsOf(text) {
56
+ const words = []
57
+ let quote = null, word = null
58
+ for (let at = 0; at <= text.length; at++) {
59
+ const char = text[at]
60
+ if (quote) {
61
+ if (char === quote) quote = null
62
+ else if (char === undefined) break
63
+ else word += quote === '"' && char === '\\' && /["\\$`]/u.test(text[at + 1] ?? '') ? text[++at] : char
64
+ } else if (char === undefined || /\s/u.test(char)) {
65
+ if (word !== null) words.push(word)
66
+ word = null
67
+ } else if (char === '"' || char === "'") { quote = char; word ??= '' }
68
+ // A redirection joined to a word before it (`url>file`) starts its own.
69
+ else if ((char === '>' || char === '<') && word !== null && !/^\d*&?$|[<>]$/u.test(word)) { words.push(word); word = char }
70
+ else word = (word ?? '') + (char === '\\' && at + 1 < text.length ? text[++at] : char)
71
+ }
72
+ const kept = []
73
+ let out = null
74
+ for (let at = 0; at < words.length; at++) {
75
+ const redirect = /^(\d*)(>>?|<<?|&>>?)(.*)$/u.exec(words[at])
76
+ if (!redirect) { kept.push(words[at]); continue }
77
+ const target = redirect[3] === '' ? words[++at] : redirect[3]
78
+ if (redirect[2].includes('>') && (redirect[1] === '' || redirect[1] === '1') && target && !target.startsWith('&')) out = target
79
+ }
80
+ return { words: kept, out }
81
+ }
82
+
83
+ // Where a `$(…)` starting at `from` (its `(`) closes, or the line's end.
84
+ function closing(text, from) {
85
+ let depth = 0, quote = null
86
+ for (let at = from; at < text.length; at++) {
87
+ const char = text[at]
88
+ if (quote) { if (char === quote) quote = null; else if (char === '\\') at++ }
89
+ else if (char === "'" || char === '"') quote = char
90
+ else if (char === '(') depth++
91
+ else if (char === ')' && --depth === 0) return at
92
+ }
93
+ return text.length
94
+ }
95
+
96
+ // A line's commands, each `{ argv, env, piped, out, nested }`, `env` the
97
+ // settings it runs with, `piped` where a pipe feeds it, `out` the file it writes its output to and `nested` its
98
+ // command substitutions' text, to read as lines of their own; and those of
99
+ // none of them (`nested`).
100
+ function commandsOf(text) {
101
+ const commands = []
102
+ let nested = [], piped = false, quote = null, start = 0
103
+ const end = (at, next) => {
104
+ const { words, out } = wordsOf(text.slice(start, at))
105
+ const { argv, env } = argvOf(words)
106
+ if (argv.length > 0) { commands.push({ argv, env, piped, out, nested }); nested = [] }
107
+ piped = next
108
+ }
109
+ for (let at = 0; at < text.length; at++) {
110
+ const char = text[at]
111
+ if (quote === "'") { if (char === "'") quote = null; continue }
112
+ if (char === '\\') { at++; continue }
113
+ if (char === '$' && text[at + 1] === '(') {
114
+ const close = closing(text, at + 1)
115
+ nested.push(text.slice(at + 2, close))
116
+ at = close
117
+ } else if (quote === '"') { if (char === '"') quote = null }
118
+ else if (char === '"' || char === "'") quote = char
119
+ else if (char === '#' && (at === 0 || /\s/u.test(text[at - 1]))) { end(at, false); start = text.length; break }
120
+ else if ((char === '&' || char === '|') && text[at + 1] === char) { end(at, false); start = ++at + 1 }
121
+ else if (char === ';' || (char === '&' && !/[<>]/u.test(text[at - 1] ?? '') && text[at + 1] !== '>')) { end(at, false); start = at + 1 }
122
+ else if (char === '|') { end(at, true); start = at + (text[at + 1] === '&' ? 2 : 1); if (text[at + 1] === '&') at++ }
123
+ }
124
+ if (start < text.length) end(text.length, false)
125
+ return { commands, nested }
126
+ }
127
+
128
+ // The command line a shell is given to run (`bash -euc '…'`, `pwsh
129
+ // -Command '…'`), else null.
130
+ function shellLine([program, ...words]) {
131
+ if (!SHELL.test(program)) return null
132
+ const option = /(?:pwsh|powershell)(?:\.exe)?$/iu.test(program) ? /^-(?:c|command)$/iu : /^-[a-z]*c[a-z]*$/u
133
+ const at = words.findIndex(word => option.test(word))
134
+ return at === -1 ? null : words[at + 1] ?? null
135
+ }
136
+
137
+ // A path `to` from `dir`, both from the step's directory ('' for it); as
138
+ // written where a variable, `~`, `-` or an absolute path names it.
139
+ export const pathFrom = (dir, to) => /^[$~/-]/u.test(to) ? to : resolved(dir ? dir.split('/') : [], to)?.join('/') ?? [dir, to].filter(Boolean).join('/')
140
+
141
+ // Each command of a script, in the order they run (`order`): its `line` from
142
+ // 0, the directory the `cd`s before it moved to (`dir`, by pathFrom), and
143
+ // `pipedTo`, the commands its output is piped through; a command
144
+ // substitution's before its command's, a shell's command line's (`sh -c`)
145
+ // after it.
146
+ export function scriptCommands(script) {
147
+ const found = []
148
+ let dir = '', read = 0
149
+ // A substitution's or a shell's command line (`apart`) moves no `cd` of its caller's.
150
+ const readLine = (text, line, apart = false) => {
151
+ if (read++ >= 64) return
152
+ const outer = dir, { commands, nested } = commandsOf(text)
153
+ commands.forEach(({ nested: substituted, ...command }, at) => {
154
+ for (const each of substituted) readLine(each, line, true)
155
+ const end = commands.findIndex((each, after) => after > at && !each.piped)
156
+ found.push({ ...command, line, dir, order: found.length, pipedTo: commands.slice(at + 1, end === -1 ? undefined : end) })
157
+ if (command.argv[0] === 'cd') dir = pathFrom(dir, command.argv.slice(1).find(word => !/^-[LPe@]+$/u.test(word)) ?? '~')
158
+ const shell = shellLine(command.argv)
159
+ if (shell) readLine(shell, line, true)
160
+ })
161
+ for (const each of nested) readLine(each, line, true)
162
+ if (apart) dir = outer
163
+ }
164
+ for (const { text, line } of scriptLines(script)) {
165
+ read = 0
166
+ readLine(text, line)
167
+ }
168
+ return found
169
+ }
@@ -0,0 +1,76 @@
1
+ // What a `uses:` names, as GitHub reads it (`owner/repo[/path]@ref`, `./path`,
2
+ // `$/path`, `docker://image`), and an image a job runs in.
3
+
4
+ const GITHUB_OWNERS = new Set(['actions', 'github'])
5
+
6
+ const OWNER = /^[\da-z](?:[\da-z]|-(?=[\da-z])){0,38}$/iu
7
+ const NAME = /^(?!\.{1,2}$)[\w.-]{1,100}$/u
8
+ const SHA = /^[\da-f]{40}$/u
9
+ const SHORT_SHA = /^[\da-f]{7,39}$/u
10
+ // A version a comment beside a pin names, as Dependabot, Renovate, pinact
11
+ // and ratchet write one (`# v4.1.1`, `# tag=v4.1.1`, `# ratchet:x@v4`).
12
+ const VERSION_COMMENT = /^#\s*(?:tag\s*[=:]\s*|pin@|ratchet:[^\s@]+@)?(v?\d+(?:\.\d+){0,3}(?:[-+][\w.-]+)?)(?![\w.])/iu
13
+
14
+ // `sha`, `short-sha`, `ref` (a tag or a branch), or `expression`, which GitHub refuses.
15
+ function pinOf(ref) {
16
+ if (/\$\{\{/u.test(ref)) return 'expression'
17
+ if (SHA.test(ref)) return 'sha'
18
+ return SHORT_SHA.test(ref) ? 'short-sha' : 'ref'
19
+ }
20
+
21
+ // An image's name, tag and digest (`[host[:port]/]path[:tag][@digest]`), null
22
+ // for none; null where it isn't one.
23
+ export function readImage(text) {
24
+ if (typeof text !== 'string' || text === '' || /\$\{\{|\s/u.test(text)) return null
25
+ const at = text.indexOf('@')
26
+ const digest = at === -1 ? null : text.slice(at + 1)
27
+ const named = at === -1 ? text : text.slice(0, at)
28
+ const colon = named.lastIndexOf(':')
29
+ const tagged = colon > named.lastIndexOf('/')
30
+ if (digest !== null && !/^sha256:[\da-f]{64}$/u.test(digest)) return null
31
+ return { image: tagged ? named.slice(0, colon) : named, tag: tagged ? named.slice(colon + 1) : null, digest }
32
+ }
33
+
34
+ const commentVersion = comment => typeof comment === 'string' ? VERSION_COMMENT.exec(comment.trim())?.[1] ?? null : null
35
+
36
+ export const isWorkflowPath = path => /^\.github\/workflows\/[^/]+\.ya?ml$/u.test(path)
37
+
38
+ // `{ kind, uses, … }`: `action`, or `workflow` at a job's level (`job`), with
39
+ // its `repo`, `path`, `ref`, `pin` and `comment`'s version; `local`, `self`
40
+ // at the commit running, `job` a reusable workflow's, at the calling
41
+ // workflow's commit; `docker`; or `invalid`, which GitHub won't run.
42
+ export function readUses(text, { job = false, comment = null } = {}) {
43
+ const uses = typeof text === 'string' ? text.trim() : ''
44
+ if (uses.startsWith('./') || uses.startsWith('$/')) {
45
+ return { kind: 'local', uses, path: uses.slice(2).replace(/\/+$/u, ''), ...uses.startsWith('$/') ? { self: true } : {}, ...job ? { job: true } : {} }
46
+ }
47
+ if (uses.startsWith('docker://')) {
48
+ const image = job ? null : readImage(uses.slice('docker://'.length))
49
+ return image ? { kind: 'docker', uses, ...image } : { kind: 'invalid', uses }
50
+ }
51
+ const at = uses.indexOf('@')
52
+ const [owner = '', name = '', ...path] = (at === -1 ? uses : uses.slice(0, at)).split('/')
53
+ const ref = at === -1 ? '' : uses.slice(at + 1)
54
+ if (!OWNER.test(owner) || !NAME.test(name) || ref === '' || path.some(part => !NAME.test(part)) || (job && !isWorkflowPath(path.join('/')))) {
55
+ return { kind: 'invalid', uses }
56
+ }
57
+ return { kind: job ? 'workflow' : 'action', uses, repo: `${owner}/${name}`, path: path.join('/'), ref, pin: pinOf(ref), comment: commentVersion(comment) }
58
+ }
59
+
60
+ // The key a reference is resolved once by, a commit's with its comment's version.
61
+ export const usesKey = ({ repo, path, ref, pin, comment }) => `${repo.toLowerCase()}${path ? `/${path}` : ''}@${ref}${pin === 'sha' && comment ? ` # ${comment}` : ''}`
62
+
63
+ // A reference from its key, a reusable workflow's by its path's.
64
+ export function usesOfKey(key) {
65
+ const m = typeof key === 'string' ? /^([^@\s]+@\S+)(?: # (\S+))?$/u.exec(key) : null
66
+ const job = Boolean(m && /^[^/]+\/[^/]+\/\.github\/workflows\/[^/@]+\.ya?ml@/u.test(m[1]))
67
+ const read = m ? readUses(m[1], { job, comment: m[2] ? `# ${m[2]}` : null }) : null
68
+ return read && (read.kind === 'action' || read.kind === 'workflow') && usesKey(read) === key ? read : null
69
+ }
70
+
71
+ // GitHub's own, the workflow's owner's, or another's.
72
+ export function ownerKind(repo, owner) {
73
+ const of = repo.split('/')[0].toLowerCase()
74
+ if (GITHUB_OWNERS.has(of)) return 'github'
75
+ return typeof owner === 'string' && of === owner.toLowerCase() ? 'own' : 'third-party'
76
+ }
@@ -0,0 +1,110 @@
1
+ // A workflow, or an action's metadata, read for what it runs: its events, its
2
+ // jobs' steps (`uses`, `run`) and images, each on its line from 1.
3
+ import { YamlError, parseYaml } from '@preventive/lockfile/yaml.js'
4
+ import { readImage, readUses } from './uses.js'
5
+
6
+ const isMap = value => value !== null && typeof value === 'object' && !Array.isArray(value)
7
+ const stringOf = value => typeof value === 'string' ? value : null
8
+
9
+ // The line, from 1, `key` of a mapping or an entry of a sequence is on.
10
+ function lineOf(file, container, key, fallback) {
11
+ const at = container !== null && typeof container === 'object' ? file.positions.get(container) : undefined
12
+ const line = at instanceof Map ? at.get(key) : at?.[key]
13
+ return line === undefined ? fallback : line + 1
14
+ }
15
+
16
+ // A step's or a job's `uses`, on its line, with the comment that line ends with.
17
+ function usesOf(file, owner, fallback, job = false) {
18
+ if (typeof owner.uses !== 'string') return null
19
+ const line = lineOf(file, owner, 'uses', fallback)
20
+ return { ...readUses(owner.uses, { job, comment: /(?:^|[ \t])(#.*)$/u.exec(file.lines[line - 1] ?? '')?.[1] ?? null }), line }
21
+ }
22
+
23
+ function triggersOf(on) {
24
+ if (typeof on === 'string') return [on]
25
+ if (Array.isArray(on)) return on.filter(event => typeof event === 'string')
26
+ return isMap(on) ? Object.keys(on) : []
27
+ }
28
+
29
+ // The line a `|` block scalar's text starts on, after its key's; else null.
30
+ const LITERAL_HEADER = /:[ \t]+(?:&\S+[ \t]+)?\|[1-9+-]{0,2}[ \t]*(?:#.*)?$/u
31
+ const literalStart = (file, line) => line !== null && LITERAL_HEADER.test(file.lines[line - 1] ?? '') ? line + 1 : null
32
+
33
+ // A `run:` step's script, and its directory, else `directory` (defaults.run);
34
+ // `production` where its `env`, else the job's or the workflow's (`env`),
35
+ // sets NODE_ENV so, as an install then leaves devDependencies out.
36
+ const envOf = (owner, outer = {}) => ({ ...outer, ...isMap(owner?.env) ? owner.env : {} })
37
+ function runOf(file, step, directory, env) {
38
+ const script = stringOf(step.run)
39
+ if (script === null) return null
40
+ const line = lineOf(file, step, 'run', null)
41
+ return { script, line, start: literalStart(file, line), workingDirectory: stringOf(step['working-directory']) ?? directory,
42
+ production: envOf(step, env).NODE_ENV === 'production' }
43
+ }
44
+
45
+ // A step's or a job's `with`, and the line each input is on.
46
+ function inputsOf(file, owner, line) {
47
+ const inputs = isMap(owner.with) ? owner.with : null
48
+ return { with: inputs, withLines: inputs ? Object.fromEntries(Object.keys(inputs).map(key => [key, lineOf(file, inputs, key, line)])) : {} }
49
+ }
50
+
51
+ function stepsOf(file, steps, directory, env = {}) {
52
+ if (!Array.isArray(steps)) return []
53
+ return steps.flatMap((step, index) => {
54
+ if (!isMap(step)) return []
55
+ const line = lineOf(file, steps, index, null)
56
+ return [{ line, uses: usesOf(file, step, line), run: runOf(file, step, directory, env), ...inputsOf(file, step, line) }]
57
+ })
58
+ }
59
+
60
+ // The directory a workflow's or a job's `defaults.run` names, else `outer`.
61
+ const directoryOf = (owner, outer) => stringOf(isMap(owner?.defaults) && isMap(owner.defaults.run) ? owner.defaults.run['working-directory'] : null) ?? outer
62
+
63
+ // The images a job runs in: its container's and its services'.
64
+ function imagesOf(file, job) {
65
+ const images = []
66
+ const container = isMap(job.container) ? job.container.image : job.container
67
+ if (typeof container === 'string') images.push({ text: container, line: lineOf(file, isMap(job.container) ? job.container : job, isMap(job.container) ? 'image' : 'container', null) })
68
+ if (isMap(job.services)) {
69
+ for (const service of Object.values(job.services)) {
70
+ if (isMap(service) && typeof service.image === 'string') images.push({ text: service.image, line: lineOf(file, service, 'image', null) })
71
+ }
72
+ }
73
+ return images.map(image => ({ ...image, read: readImage(image.text) }))
74
+ }
75
+
76
+ function jobsOf(file, doc) {
77
+ if (!isMap(doc.jobs)) throw new YamlError('a workflow has no jobs')
78
+ const directory = directoryOf(doc, null)
79
+ return Object.values(doc.jobs).filter(isMap).map(job => ({ uses: usesOf(file, job, null, true), secrets: job.secrets ?? null, ...inputsOf(file, job, null),
80
+ steps: stepsOf(file, job.steps, directoryOf(job, directory), envOf(job, envOf(doc))), images: imagesOf(file, job) }))
81
+ }
82
+
83
+ // An action's `runs`: its runtime, a composite one's steps as a job, and a
84
+ // Docker one's image or Dockerfile.
85
+ function runsOf(file, doc) {
86
+ const runs = isMap(doc.runs) ? doc.runs : null
87
+ if (!runs || typeof runs.using !== 'string') throw new YamlError('an action has no runs.using')
88
+ const using = runs.using.toLowerCase()
89
+ const usingLine = lineOf(file, runs, 'using', null)
90
+ const image = using === 'docker' ? stringOf(runs.image) : null
91
+ const imageLine = lineOf(file, runs, 'image', usingLine)
92
+ const docker = image?.startsWith('docker://') ? { text: image.slice('docker://'.length), line: imageLine, read: readImage(image.slice('docker://'.length)) } : null
93
+ const steps = using === 'composite' ? stepsOf(file, runs.steps, null) : []
94
+ return { using, usingLine, dockerfile: image && !docker ? { path: image.replace(/^\.\//u, ''), line: imageLine } : null, jobs: [{ uses: null, steps, images: docker ? [docker] : [] }] }
95
+ }
96
+
97
+ // A workflow (`kind` 'workflow') or an action's metadata ('action') read, or
98
+ // the YamlError of one GitHub can't run.
99
+ export function readWorkflow(kind, text) {
100
+ try {
101
+ const file = { lines: text.split('\n'), positions: new WeakMap() }
102
+ const doc = parseYaml(text, { workflow: true, lines: file.positions })
103
+ if (!isMap(doc)) throw new YamlError(`${kind === 'action' ? 'an action' : 'a workflow'} is not a mapping`)
104
+ if (kind === 'action') return { triggers: [], ...runsOf(file, doc) }
105
+ return { triggers: triggersOf(doc.on), using: null, usingLine: null, dockerfile: null, jobs: jobsOf(file, doc) }
106
+ } catch (error) {
107
+ if (error instanceof YamlError) return error
108
+ throw error
109
+ }
110
+ }