From 2b9c7abcb86bd0b3104849faa9406e0ed49cb8ee Mon Sep 17 00:00:00 2001 From: anujs3 Date: Mon, 30 Nov 2026 16:38:05 -0800 Subject: [PATCH] Add Read-Only CI Checks Add automatic lint, formatting, and test checks. Validate reply request URLs. --- .eslintrc.cjs | 45 +++++++++ .github/workflows/code-checks.yaml | 37 +++++++ README.md | 15 ++- package.json | 1 + public/scripts/form.js | 2 + public/scripts/hide-reply.js | 2 +- public/scripts/text-parser.js | 14 ++- public/scripts/upload.js | 2 +- src/index.js | 56 +++++++---- test/app-scoped-user-id.test.js | 2 +- test/csrf.test.js | 115 ++++++++++++++++++++- test/lint-regressions.test.js | 154 +++++++++++++++++++++++++++++ test/own-post-deletion.test.js | 8 +- 13 files changed, 418 insertions(+), 35 deletions(-) create mode 100644 .eslintrc.cjs create mode 100644 .github/workflows/code-checks.yaml create mode 100644 test/lint-regressions.test.js diff --git a/.eslintrc.cjs b/.eslintrc.cjs new file mode 100644 index 0000000..2f5b1d3 --- /dev/null +++ b/.eslintrc.cjs @@ -0,0 +1,45 @@ +module.exports = { + root: true, + env: { es2022: true }, + parserOptions: { ecmaVersion: 2022 }, + extends: ['eslint:recommended'], + rules: { + 'no-unused-vars': ['error', { argsIgnorePattern: '^_' }], + }, + overrides: [ + { + files: [ + '.eslintrc.cjs', + 'src/**/*.js', + 'test/**/*.js', + 'test-support/**/*.cjs', + ], + env: { node: true }, + globals: { + fetch: 'readonly', + FormData: 'readonly', + AbortSignal: 'readonly', + }, + }, + { + files: ['public/scripts/**/*.js'], + env: { browser: true }, + }, + { + files: ['public/scripts/text-parser.js'], + env: { node: true }, + }, + { + files: [ + 'public/scripts/publish.js', + 'public/scripts/upload.js', + 'public/scripts/hide-reply.js', + ], + globals: { + processFormAsync: 'readonly', + onAsyncRequestStarting: 'readonly', + onAsyncRequestEnded: 'readonly', + }, + }, + ], +}; diff --git a/.github/workflows/code-checks.yaml b/.github/workflows/code-checks.yaml new file mode 100644 index 0000000..fc0fda7 --- /dev/null +++ b/.github/workflows/code-checks.yaml @@ -0,0 +1,37 @@ +name: Code Checks + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + checks: + name: Checks (Node ${{ matrix.node }}) + runs-on: ubuntu-latest + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + node: [24, 26] + steps: + - name: Check Out Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set Up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ matrix.node }} + package-manager-cache: false + - name: Install Dependencies + run: npm install --ignore-scripts --no-audit --no-fund --package-lock=false + - name: Lint + run: npm run lint + - name: Check Formatting + run: npm run format:check + - name: Run Mocked Tests + run: npm test diff --git a/README.md b/README.md index 7baa903..e95d2e4 100644 --- a/README.md +++ b/README.md @@ -69,9 +69,20 @@ Note: If you are using devcontainers, ensure that containers are enabled and sup - Once the Sample App starts running, go to https://threads-sample.meta:8000 to test the workflow. - If you are using a different domain or port then replace those values accordingly. -## Tests +## Checks -Run `npm test` to check search modes, filters, and pagination with mocked API responses. These tests do not call the Threads API. +Run lint, formatting, and tests before opening a pull request: + +```sh +npm install --ignore-scripts --no-audit --no-fund --package-lock=false +npm run lint +npm run format:check +npm test +``` + +Tests use mocked API responses. They do not call the Threads API. + +GitHub Actions runs these checks for pull requests. It also runs them for pushes to `main`. Both Node.js 24 and 26 are covered. ## License diff --git a/package.json b/package.json index ca68fb2..10afc47 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "scripts": { "start": "node ./src/index.js", "test": "node --test", + "lint": "eslint --max-warnings 0 .eslintrc.cjs src public/scripts test && if [ -d test-support ]; then eslint --max-warnings 0 --ext .cjs test-support; fi", "format:check": "prettier --check .", "format:write": "prettier --write ." }, diff --git a/public/scripts/form.js b/public/scripts/form.js index 434d656..933d36c 100644 --- a/public/scripts/form.js +++ b/public/scripts/form.js @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +/* exported processFormAsync */ + let loadingOverlay; document.addEventListener('DOMContentLoaded', () => { diff --git a/public/scripts/hide-reply.js b/public/scripts/hide-reply.js index f4ee744..37e924c 100644 --- a/public/scripts/hide-reply.js +++ b/public/scripts/hide-reply.js @@ -36,7 +36,7 @@ document.addEventListener('DOMContentLoaded', async () => { alert('An error occurred while hiding/unhiding the reply.'); } } catch (e) { - console.error('There was an error:', error); + console.error('There was an error while hiding the reply.'); alert('error while hiding reply'); } finally { onAsyncRequestEnded(); diff --git a/public/scripts/text-parser.js b/public/scripts/text-parser.js index 7920115..6844828 100644 --- a/public/scripts/text-parser.js +++ b/public/scripts/text-parser.js @@ -33,7 +33,10 @@ function extractSpoilerInfo(text) { } // Add text before the spoiler marker to cleaned text - const textBeforeMarker = text.substring(searchPosition, startMarkerIndex); + const textBeforeMarker = text.substring( + searchPosition, + startMarkerIndex + ); cleanedText += textBeforeMarker; currentPosition += textBeforeMarker.length; @@ -48,11 +51,14 @@ function extractSpoilerInfo(text) { } // Extract spoiler content - const spoilerContent = text.substring(contentStartIndex, endMarkerIndex); + const spoilerContent = text.substring( + contentStartIndex, + endMarkerIndex + ); // Record spoiler info textEntities.push({ - entity_type: "SPOILER", + entity_type: 'SPOILER', offset: currentPosition.toString(), length: spoilerContent.length.toString(), }); @@ -67,6 +73,6 @@ function extractSpoilerInfo(text) { return { textEntities: textEntities, - text: cleanedText + text: cleanedText, }; } diff --git a/public/scripts/upload.js b/public/scripts/upload.js index 491b03e..f4ec0cb 100644 --- a/public/scripts/upload.js +++ b/public/scripts/upload.js @@ -109,7 +109,7 @@ document.addEventListener('DOMContentLoaded', async () => { }); const mediaTypeSelectElem = div.querySelector('select'); - mediaTypeSelectElem.addEventListener('change', async (e) => { + mediaTypeSelectElem.addEventListener('change', async () => { await updateMediaType( attachmentsList.children.length, attachmentsList diff --git a/src/index.js b/src/index.js index 4e17394..1ced1fc 100644 --- a/src/index.js +++ b/src/index.js @@ -228,7 +228,7 @@ app.use(function protectAgainstCsrf(req, res, next) { }); const JSON_TOKEN_PATTERN = - /"(?:[^"\\]|\\.)*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}\[\]:,]/g; + /"(?:[^"\\]|\\.)*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g; function parseUserIdResponse(text) { const stack = []; @@ -909,9 +909,9 @@ app.post( } if (text.includes(spoilerMarker)) { - parsedInput = textParser.extractSpoilerInfo(text); - processedText = parsedInput.text; - textEntites = parsedInput.textEntities; + const parsedInput = textParser.extractSpoilerInfo(text); + const processedText = parsedInput.text; + const textEntites = parsedInput.textEntities; params[PARAMS__TEXT] = processedText; params[PARAMS_TEXT_ENTITES] = JSON.stringify(textEntites); } else { @@ -1581,27 +1581,49 @@ app.get('/threads/:threadId/conversation', loggedInUserChecker, (req, res) => { app.post('/manage_reply/:replyId', upload.array(), async (req, res) => { const { replyId } = req.params; const { hide } = req.query; + if ( + typeof replyId !== 'string' || + !/^[1-9]\d*$/.test(replyId) || + replyId.trim() !== replyId + ) { + return res.status(400).json({ + error: true, + message: 'The reply ID is invalid.', + }); + } const params = {}; if (hide) { params[PARAMS__HIDE] = hide === 'true'; } - const hideReplyUrl = buildGraphAPIURL( - `${replyId}/manage_reply`, - {}, - req.session.access_token - ); - try { - response = await axios.post(hideReplyUrl, params, { + const hideReplyUrl = new URL( + buildGraphAPIURL(`${replyId}/manage_reply`, {}, null) + ); + if ( + hideReplyUrl.origin !== 'https://graph.threads.com' || + hideReplyUrl.username || + hideReplyUrl.password || + hideReplyUrl.hash + ) { + throw new Error('Invalid reply request URL.'); + } + if (req.session.access_token) { + hideReplyUrl.searchParams.append( + PARAMS__ACCESS_TOKEN, + req.session.access_token + ); + } + await axios.post(hideReplyUrl.toString(), params, { httpsAgent: agent, + maxRedirects: 0, }); - } catch (e) { - console.error(e?.message); - return res.status(e?.response?.status ?? 500).json({ + } catch { + console.error('Unable to update the reply.'); + return res.status(502).json({ error: true, - message: `Error while hiding reply: ${e}`, + message: 'Unable to update the reply. Try again.', }); } @@ -2389,11 +2411,11 @@ function addAttachmentFields(target, attachmentType, url, altText) { if (attachmentType === 'Image') { target.media_type = MEDIA_TYPE__IMAGE; target.image_url = url; - target.alt_text = altText; + target[PARAMS__ALT_TEXT] = altText; } else if (attachmentType === 'Video') { target.media_type = MEDIA_TYPE__VIDEO; target.video_url = url; - target.alt_text = altText; + target[PARAMS__ALT_TEXT] = altText; } } diff --git a/test/app-scoped-user-id.test.js b/test/app-scoped-user-id.test.js index 47154ac..c3890c3 100644 --- a/test/app-scoped-user-id.test.js +++ b/test/app-scoped-user-id.test.js @@ -131,7 +131,7 @@ test('OAuth keeps the exact app-scoped ID through token exchange and rejects amb assert.equal(new URL(url).pathname, '/oauth/access_token'); return { data: transform( - `{"access_token":"synthetic-short-token","user_id":${userId},"data":{"user_id":"999"},"note":"\\\"user_id\\\":123"}`, + `{"access_token":"synthetic-short-token","user_id":${userId},"data":{"user_id":"999"},"note":"\\"user_id\\":123"}`, options ), }; diff --git a/test/csrf.test.js b/test/csrf.test.js index 30a6685..d9873ac 100644 --- a/test/csrf.test.js +++ b/test/csrf.test.js @@ -24,9 +24,22 @@ const csrfFailure = { 'The request could not be verified. Reload the page and try again.', }; -async function startApp(t, { api = {}, signedIn = false, onApp } = {}) { +async function startApp( + t, + { api = {}, signedIn = false, onApp, graphBase } = {} +) { let parsedForms = 0; - const app = vm.runInNewContext(fs.readFileSync(entry, 'utf8') + '\napp;', { + const logs = []; + let source = fs.readFileSync(entry, 'utf8'); + if (graphBase) { + const declaration = /const GRAPH_API_BASE_URL =[\s\S]*?;/; + assert.match(source, declaration); + source = source.replace( + declaration, + `const GRAPH_API_BASE_URL = ${JSON.stringify(graphBase)};` + ); + } + const app = vm.runInNewContext(source + '\napp;', { __dirname: path.dirname(entry), process: { env: { @@ -37,7 +50,7 @@ async function startApp(t, { api = {}, signedIn = false, onApp } = {}) { }), }, }, - console: { log() {}, error() {}, warn() {} }, + console: { log() {}, error: (...args) => logs.push(args), warn() {} }, require(name) { if (name === 'axios') return api; if (name === 'dotenv') return { config() {} }; @@ -65,6 +78,7 @@ async function startApp(t, { api = {}, signedIn = false, onApp } = {}) { t.after(() => new Promise((resolve) => server.close(resolve))); const base = `http://127.0.0.1:${server.address().port}`; return { + logs, parsedForms: () => parsedForms, client() { let cookie; @@ -109,11 +123,41 @@ function post(request, route, body, headerToken) { test('mutation routes reject invalid session tokens before form parsing or API calls', async (t) => { const calls = []; + let redirectReply = false; const app = await startApp(t, { signedIn: true, api: { - post: async (url) => { - calls.push(new URL(url)); + post: async (url, body, config) => { + const requestURL = new URL(url); + calls.push(requestURL); + if (requestURL.pathname === '/123/manage_reply') { + assert.equal( + requestURL.origin, + 'https://graph.threads.com' + ); + assert.equal( + requestURL.searchParams.get('access_token'), + 'synthetic-access-token' + ); + assert.deepEqual({ ...body }, { hide: true }); + assert.ok(config.httpsAgent); + assert.equal(config.maxRedirects, 0); + if (redirectReply) { + throw { + message: 'synthetic-secret', + config: { + url: 'https://example.invalid/synthetic-secret', + }, + response: { + status: 302, + headers: { + location: + 'https://example.invalid/synthetic-secret', + }, + }, + }; + } + } return { data: { id: '123', success: true } }; }, }, @@ -189,6 +233,67 @@ test('mutation routes reject invalid session tokens before form parsing or API c !url.toString().includes(token) ) ); + const before = calls.length; + for (const id of [ + '0', + 'https://example.invalid/', + '../123', + '123/456', + '123:456', + '123\n', + ]) { + const response = await post( + request, + `/manage_reply/${encodeURIComponent(id)}?hide=true`, + new FormData(), + token + ); + assert.equal(response.status, 400); + assert.deepEqual(await response.json(), { + error: true, + message: 'The reply ID is invalid.', + }); + assert.equal(calls.length, before); + } + redirectReply = true; + const redirected = await post( + request, + '/manage_reply/123?hide=true', + new FormData(), + token + ); + assert.equal(redirected.status, 502); + assert.deepEqual(await redirected.json(), { + error: true, + message: 'Unable to update the reply. Try again.', + }); + assert.equal(calls.length, before + 1); + assert.deepEqual(app.logs, [['Unable to update the reply.']]); + let foreignCalls = 0; + const foreign = await startApp(t, { + signedIn: true, + graphBase: 'https://example.invalid/', + api: { + post: () => { + foreignCalls++; + throw new Error('Synthetic foreign request.'); + }, + }, + }); + const foreignRequest = foreign.client(); + const foreignCsrfToken = await csrfFromPage(foreignRequest); + const rejected = await post( + foreignRequest, + '/manage_reply/123?hide=true', + new FormData(), + foreignCsrfToken + ); + assert.equal(rejected.status, 502); + assert.deepEqual(await rejected.json(), { + error: true, + message: 'Unable to update the reply. Try again.', + }); + assert.equal(foreignCalls, 0); }); test('logout is a protected native POST and invalidates the old session token', async (t) => { diff --git a/test/lint-regressions.test.js b/test/lint-regressions.test.js new file mode 100644 index 0000000..0caadef --- /dev/null +++ b/test/lint-regressions.test.js @@ -0,0 +1,154 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const http = require('node:http'); +const https = require('node:https'); +const path = require('node:path'); +const vm = require('node:vm'); +const { createRequire } = require('node:module'); +const { once } = require('node:events'); +const { test } = require('node:test'); + +const entry = path.join(__dirname, '../src/index.js'); +const appRequire = createRequire(entry); + +test('publishing and reply handlers keep response intermediates out of global state', async (t) => { + const writes = []; + const context = { + __dirname: path.dirname(entry), + process: { + env: { + SESSION_SECRET: 'synthetic-lint-secret', + INITIAL_ACCESS_TOKEN: 'synthetic-lint-token', + INITIAL_USER_ID: '456', + }, + }, + console: { log() {}, error() {} }, + require(name) { + if (name === 'axios') + return { + get: async () => ({ + data: { data: { is_valid: true, user_id: '456' } }, + }), + post: async (url, body) => { + writes.push({ url: new URL(url), body }); + return { status: 200, data: { id: '789' } }; + }, + delete: () => assert.fail('Unexpected API deletion.'), + }; + if (name === 'dotenv') return { config() {} }; + if (name === 'fs') return { readFileSync: () => '' }; + if (name === 'https') + return { ...https, createServer: () => ({ listen() {} }) }; + return appRequire(name); + }, + }; + const app = vm.runInNewContext( + fs.readFileSync(entry, 'utf8') + '\napp;', + context, + { filename: entry, timeout: 3000 } + ); + const server = http.createServer(app); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + t.after(() => new Promise((resolve) => server.close(resolve))); + const base = `http://127.0.0.1:${server.address().port}`; + const page = await fetch(`${base}/upload`, { + signal: AbortSignal.timeout(5000), + }); + const cookie = page.headers.get('set-cookie').split(';')[0]; + const html = await page.text(); + const csrf = html.match(/name="csrf-token" content="([^"]+)"/)[1]; + async function post(route, body) { + return fetch(`${base}${route}`, { + method: 'POST', + headers: { + cookie, + 'X-CSRF-Token': csrf, + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams(body), + signal: AbortSignal.timeout(5000), + }); + } + const upload = await post('/upload', { + text: 'A **spoiler**hidden**spoiler** Z', + topicTag: '', + replyControl: 'everyone', + replyToId: '', + linkAttachment: '', + }); + assert.equal(upload.status, 200); + assert.equal((await upload.json()).id, '789'); + assert.equal(writes[0].url.searchParams.get('text'), 'A hidden Z'); + assert.deepEqual( + JSON.parse(writes[0].url.searchParams.get('text_entities')), + [{ entity_type: 'SPOILER', offset: '2', length: '6' }] + ); + const reply = await post('/manage_reply/123?hide=true', {}); + assert.equal(reply.status, 200); + await reply.text(); + assert.equal(writes[1].body.hide, true); + for (const name of [ + 'parsedInput', + 'processedText', + 'textEntites', + 'response', + ]) { + assert.equal( + Object.prototype.hasOwnProperty.call(context, name), + false + ); + } +}); + +test('reply network failures show the existing alert and finish loading without an undeclared variable', async () => { + let ready; + let submit; + let started = 0; + let ended = 0; + const alerts = []; + const logs = []; + const form = { + addEventListener: (_event, handler) => { + submit = handler; + }, + getAttribute: () => '/manage_reply/123?hide=true', + }; + vm.runInNewContext( + fs.readFileSync( + path.join(__dirname, '../public/scripts/hide-reply.js'), + 'utf8' + ), + { + document: { + addEventListener: (_event, handler) => { + ready = handler; + }, + getElementsByClassName: () => [form], + querySelector: () => ({ content: 'synthetic-csrf' }), + }, + FormData: function () {}, + fetch: async () => { + throw new Error('Synthetic network failure.'); + }, + console: { error: (message) => logs.push(message) }, + alert: (message) => alerts.push(message), + onAsyncRequestStarting: () => started++, + onAsyncRequestEnded: () => ended++, + }, + { timeout: 3000 } + ); + await ready(); + await submit({ preventDefault() {}, target: form }); + assert.deepEqual(alerts, ['error while hiding reply']); + assert.deepEqual(logs, ['There was an error while hiding the reply.']); + assert.equal(started, 1); + assert.equal(ended, 1); +}); diff --git a/test/own-post-deletion.test.js b/test/own-post-deletion.test.js index 5c7fb1f..2a44093 100644 --- a/test/own-post-deletion.test.js +++ b/test/own-post-deletion.test.js @@ -430,7 +430,7 @@ test('delete limits block API work and keep independent client IP budgets', asyn /Error: Too many delete requests\. Wait a minute and try again\./ ); assert.match(blockedHtml, /href="\/threads">Back to Your Posts<\/a>/); - assert.doesNotMatch(blockedHtml, /\.\!|action="\/repost"|quotePostId=/); + assert.doesNotMatch(blockedHtml, /\.!|action="\/repost"|quotePostId=/); assert.equal(reads, readCount); assert.equal(deletes, 10); @@ -486,7 +486,7 @@ test('the shared error banner preserves message punctuation and escapes text', ( }); const escaped = message.replaceAll('<', '<').replaceAll('>', '>'); assert.ok(html.includes(`Error: ${escaped}`)); - assert.doesNotMatch(html, /Error Occured|\.\!|