Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Prevent injection in weekly report script (#773)
Dhruv Bhanushali840b56e7bf2b
diff --git a/.github/workflows/weekly_updates.yml b/.github/workflows/weekly_updates.ymlindex 2e2a1176a..c45043395 100644--- a/.github/workflows/weekly_updates.yml+++ b/.github/workflows/weekly_updates.yml@@ -46,5 +46,4 @@ jobs:run: "pnpm install"- name: Create draft post- working-directory: ./automations/js- run: node src/last_week_tonight.js+ run: just automations/js/reportdiff --git a/automations/js/justfile b/automations/js/justfileindex 5519b88df..3b97a4887 100644--- a/automations/js/justfile+++ b/automations/js/justfile@@ -10,9 +10,13 @@ NO_COLOR := "\\033[0m"just --list --unsorted-# Install dependencies-install:- pnpm install+#################+# Weekly report #+#################++# Generate and post the weekly report+report:+ node src/last_week_tonight.mjs########### Render #diff --git a/automations/js/package.json b/automations/js/package.jsonindex 1b9d8de29..71aeb2844 100644--- a/automations/js/package.json+++ b/automations/js/package.json@@ -7,7 +7,7 @@"@octokit/rest": "19.0.7","js-yaml": "^4.1.0","k6": "0.0.0",- "node-fetch": "2",+ "node-fetch": "^3.3.0","nunjucks": "^3.2.3"}}diff --git a/automations/js/src/html.mjs b/automations/js/src/html.mjsnew file mode 100644index 000000000..816602846--- /dev/null+++ b/automations/js/src/html.mjs@@ -0,0 +1,17 @@+/**+ * Replace characters in the string that have special meanings in HTML with+ * their HTML character entities to prevent injection.+ *+ * @param text {string} - the string to sanitise+ * @returns {string} the clean string that can be interpolated into HTML markup+ */+export const escapeHtml = (text) => {+ const charHtmlMap = {+ "'": ''',+ '"': '"',+ '<': '<',+ '>': '>',+ '&': '&',+ }+ return text.replace(/[&"'<>]/g, (c) => charHtmlMap[c])+}diff --git a/automations/js/src/last_week_tonight.js b/automations/js/src/last_week_tonight.mjssimilarity index 69%rename from automations/js/src/last_week_tonight.jsrename to automations/js/src/last_week_tonight.mjsindex 6ea42f6c1..377762021 100644--- a/automations/js/src/last_week_tonight.js+++ b/automations/js/src/last_week_tonight.mjs@@ -3,12 +3,14 @@* Openverse repos.*/-const fs = require('fs')-const path = require('path')+import { readFileSync } from 'fs'+import { resolve } from 'path'-const yaml = require('js-yaml')-const fetch = require('node-fetch')-const { Octokit } = require('@octokit/rest')+import yaml from 'js-yaml'+import fetch from 'node-fetch'+import { Octokit } from '@octokit/rest'++import { escapeHtml } from './html.mjs'/* Environment variables */@@ -32,8 +34,8 @@ if (!(pat && username && password)) process.exit(1)/* Read GitHub information from the data files */-const githubDataFile = path.resolve(__dirname, '../../data/github.yml')-const githubInfo = yaml.load(fs.readFileSync(githubDataFile))+const githubDataFile = resolve('../data/github.yml') // resolved from `package.json`+const githubInfo = yaml.load(readFileSync(githubDataFile))const org = githubInfo.orgconst repos = Object.values(githubInfo.repos)@@ -59,7 +61,8 @@ const closedIssuesQ = (repo) =>/*** Generate the HTML for one closed issues or merged PRs section.- * @param {string} title - the the title to use for the section+ *+ * @param {string} title - the title to use for the section* @param {{html_url: string, number: int, title: string}[]} items - the list of issues/PRs* @returns {string[]} - lines of HTML*/@@ -69,15 +72,19 @@ const getItemsHtml = (title, items) => {return [`<h3>${title}</h3>`,'<ul>',- ...items.map(- (item) =>- `<li><a href="${item.html_url}">#${item.number}</a>: ${item.title}`- ),+ ...items.map((item) => {+ const href = item.html_url+ const number = `#${item.number}`+ const title = escapeHtml(item.title)+ return `<li><a href="${href}">${number}</a>: ${title}`+ }),'</ul>',]}+/*** Generate the HTML for the closed issues or merged PRs of one repository.+ ** @param {string} repo - the name of the repository* @param {{html_url: string, number: int, title: string}[]} mergedPrs - the list of PRs* @param {{html_url: string, number: int, title: string}[]} closedIssues - the list of issues@@ -91,9 +98,8 @@ const getRepoHtml = ({ repo, mergedPrs, closedIssues }) => {]}-// Create post on Make site-const MAKE_SITE_API = 'https://make.wordpress.org/openverse/wp-json/wp/v2'-const token = Buffer.from(`${username}:${password}`).toString('base64')+/* Create post on Make site. */+/*** Post the activities to the Make site.* @param {{@@ -105,6 +111,10 @@ const token = Buffer.from(`${username}:${password}`).toString('base64')*/const postActivities = (activities) => {const report = activities.map(getRepoHtml).flat().join('\n')++ const MAKE_SITE_API = 'https://make.wordpress.org/openverse/wp-json/wp/v2'+ const token = Buffer.from(`${username}:${password}`).toString('base64')+return fetch(`${MAKE_SITE_API}/posts`, {method: 'POST',headers: {@@ -126,35 +136,21 @@ const postActivities = (activities) => {}// Entry point-Promise.all(- repos.map((repo) =>- Promise.all([- octokit.rest.search- .issuesAndPullRequests({ q: closedIssuesQ(repo) })- .then((res) => res.data.items),- octokit.rest.search- .issuesAndPullRequests({ q: mergedPrsQ(repo) })- .then((res) => res.data.items),- ]).then(([closedIssues, mergedPrs]) => {- if (closedIssues.length || mergedPrs.length) {- return {- repo: repo,- closedIssues,- mergedPrs,- }- }- return null- })- )-)- .then((activities) => activities.filter((activity) => Boolean(activity)))- .then(postActivities)- .then((res) => {- if (res.status !== 201) {- console.error('Create post request failed. See the logs.')- process.exitCode = 1- }- return res.json()- })- .then((data) => JSON.stringify(data, null, 2))- .then(console.log)+const reportData = []+for (const repo of repos) {+ const closedIssues = (+ await octokit.rest.search.issuesAndPullRequests({ q: closedIssuesQ(repo) })+ ).data.items+ const mergedPrs = (+ await octokit.rest.search.issuesAndPullRequests({ q: mergedPrsQ(repo) })+ ).data.items+ if (closedIssues.length || mergedPrs.length)+ reportData.push({ repo, closedIssues, mergedPrs })+}++const res = await postActivities(reportData)+if (res.status !== 201) {+ console.error('Create post request failed. See the logs.')+ process.exitCode = 1+}+console.log(JSON.stringify(res.json(), null, 2))diff --git a/automations/js/src/weekly_report.js b/automations/js/src/weekly_report.jsdeleted file mode 100644index 76232342b..000000000--- a/automations/js/src/weekly_report.js+++ /dev/null@@ -1,65 +0,0 @@-// # Generate a weekly report of completed issues per repo-const fetch = require('node-fetch')-const {- compose,- zipObj,- mapAwait,- prop,- gte,- map,- filter,- branch,- entries,-} = require('./utils')--// check for arg-const date = process.argv?.[2]-if (!date) {- throw new Error(- 'Please call this script with a date in the YYYY-MM-DD format.'- )-}--// get auth key-const ghKey = process.argv?.[3]-if (!ghKey) {- throw new Error(- 'Please supply a GitHub access token with public repo permissions'- )-}--// data-const repos = [- 'openverse',- 'openverse-frontend',- 'openverse-api',- 'openverse-catalog',-]--// internals-const API_ROOT = `https://api.github.com`-const makeIssueUrl = (owner) => (repo) =>- `${API_ROOT}/repos/${owner}/${repo}/issues?state=closed&since=${date}&per_page=10000`-const makeWpIssueUrl = makeIssueUrl('wordpress')-// this key only has public repo access, i don't care about showing it-const authFetch = (url) =>- fetch(url, {- headers: {- Authorization: `Basic ${ghKey}`,- },- })-const fetchRepoIssues = compose(authFetch, makeWpIssueUrl)-const getJSON = (i) => i.json()-const filterClosed = compose(gte(date), prop('closed_at'))-const logRepo = (repo) =>- console.log(`\n## [${repo}](https://github.com/wordpress/${repo}) \n`)-const logIssue = (issue) =>- console.log(`- [#${issue.number} ${issue.title}](${issue.html_url})`)--// run it-mapAwait(fetchRepoIssues)(repos)- .then(mapAwait(getJSON))- .then(map(filter(filterClosed)))- .then(zipObj(repos))- .then(compose(map(branch(logRepo, map(logIssue))), entries))- .catch(console.error)diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 29fe6da38..cae7d571d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -10,13 +10,13 @@ importers:'@octokit/rest': 19.0.7js-yaml: ^4.1.0k6: 0.0.0- node-fetch: '2'+ node-fetch: ^3.3.0nunjucks: ^3.2.3dependencies:'@octokit/rest': 19.0.7js-yaml: 4.1.0k6: 0.0.0- node-fetch: 2.6.7+ node-fetch: 3.3.0nunjucks: 3.2.3frontend:@@ -8255,6 +8255,11 @@ packages:/cyclist/1.0.1:resolution: {integrity: sha512-NJGVKPS81XejHcLhaLJS7plab0fK3slPh11mESeeDq2W4ZI5kUKK/LRRdVDvjJseojbPB7ZwjnyOybg3Igea/A==}+ /data-uri-to-buffer/4.0.1:+ resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}+ engines: {node: '>= 12'}+ dev: false+/data-urls/2.0.0:resolution: {integrity: sha512-X5eWTSXO/BJmpdIKCRuKUgSCgAN0OwliVK3yPKbwIWU1Tdw5BRajxlzMidvh+gwko9AfQ9zIj52pzF91Q3YAvQ==}engines: {node: '>=10'}@@ -9481,6 +9486,14 @@ packages:bser: 2.1.1dev: true+ /fetch-blob/3.2.0:+ resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}+ engines: {node: ^12.20 || >= 14.13}+ dependencies:+ node-domexception: 1.0.0+ web-streams-polyfill: 3.2.1+ dev: false+/fetch-retry/5.0.3:resolution: {integrity: sha512-uJQyMrX5IJZkhoEUBQ3EjxkeiZkppBd5jS/fMTJmfZxLSiaQjv2zD0kTvuvkSH89uFvgSlB6ueGpjD3HWN7Bxw==}dev: true@@ -9759,6 +9772,13 @@ packages:combined-stream: 1.0.8mime-types: 2.1.34+ /formdata-polyfill/4.0.10:+ resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==}+ engines: {node: '>=12.20.0'}+ dependencies:+ fetch-blob: 3.2.0+ dev: false+/forwarded/0.2.0:resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==}engines: {node: '>= 0.6'}@@ -12831,6 +12851,11 @@ packages:minimatch: 3.1.2dev: true+ /node-domexception/1.0.0:+ resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}+ engines: {node: '>=10.5.0'}+ dev: false+/node-fetch/2.6.7:resolution: {integrity: sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==}engines: {node: 4.x || >=6.0.0}@@ -12842,6 +12867,15 @@ packages:dependencies:whatwg-url: 5.0.0+ /node-fetch/3.3.0:+ resolution: {integrity: sha512-BKwRP/O0UvoMKp7GNdwPlObhYGB5DQqwhEDQlNKuoqwVYSxkSZCSbHjnFFmUEtwSKRPU4kNK8PbDYYitwaE3QA==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}+ dependencies:+ data-uri-to-buffer: 4.0.1+ fetch-blob: 3.2.0+ formdata-polyfill: 4.0.10+ dev: false+/node-html-parser/3.3.6:resolution: {integrity: sha512-VkWDHvNgFGB3mbQGMyzqRE1i/BG7TKX9wRXC8e/v8kL0kZR/Oy6RjYxXH91K6/+m3g8iQ8dTqRy75lTYoA2Cjg==}dependencies:@@ -17867,6 +17901,11 @@ packages:resolution: {integrity: sha512-wYxSGajtmoP4WxfejAPIr4l0fVh+jeMXZb08wNc0tMg6xsfZXj3cECqIK0G7ZAqUq0PP8WlMDtaOGVBTAWztNw==}dev: true+ /web-streams-polyfill/3.2.1:+ resolution: {integrity: sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==}+ engines: {node: '>= 8'}+ dev: false+/webidl-conversions/3.0.1:resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}