From 93873776235a886373b3b8b3bd0cb44f69bae9bd Mon Sep 17 00:00:00 2001 From: anujs3 Date: Tue, 24 Nov 2026 09:19:36 -0800 Subject: [PATCH] Keep Reply Controls in Sync Update the action and label together after the server confirms a reply change. --- public/scripts/hide-reply.js | 48 ++++++++------- src/index.js | 15 ++--- test/hide-reply.test.js | 104 +++++++++++++++++++++++++++++++++ test/lint-regressions.test.js | 24 +++++++- test/reply-management.test.js | 107 ++++++++++++++++++++++++++++++++++ 5 files changed, 268 insertions(+), 30 deletions(-) create mode 100644 test/hide-reply.test.js create mode 100644 test/reply-management.test.js diff --git a/public/scripts/hide-reply.js b/public/scripts/hide-reply.js index 37e924c..47d9b48 100644 --- a/public/scripts/hide-reply.js +++ b/public/scripts/hide-reply.js @@ -5,17 +5,25 @@ * LICENSE file in the root directory of this source tree. */ -document.addEventListener('DOMContentLoaded', async () => { +document.addEventListener('DOMContentLoaded', () => { const hideForms = document.getElementsByClassName('hide-reply'); - for (let i = 0; i < hideForms.length; i++) { - const hideForm = hideForms[i]; - hideForm.addEventListener('submit', async (e) => { + for (const form of hideForms) { + const submitButton = form.querySelector('input[type="submit"]'); + let busy = false; + form.addEventListener('submit', async (e) => { e.preventDefault(); - onAsyncRequestStarting(); + if (busy) return; - const formData = new FormData(e.target); + busy = true; + submitButton.disabled = true; + onAsyncRequestStarting(); try { - let response = await fetch(e.target.getAttribute('action'), { + const action = new URL( + form.getAttribute('action'), + window.location.href + ); + if (action.origin !== window.location.origin) return; + const response = await fetch(action.href, { method: 'POST', mode: 'same-origin', headers: { @@ -23,22 +31,22 @@ document.addEventListener('DOMContentLoaded', async () => { document.querySelector('meta[name="csrf-token"]') ?.content ?? '', }, - body: formData, + body: new FormData(form), }); - - if (response.ok) { - const submitButton = e.target.querySelector( - 'input[type="submit"]' - ); - submitButton.value = - submitButton.value === 'Hide' ? 'Unhide' : 'Hide'; - } else { - alert('An error occurred while hiding/unhiding the reply.'); + const result = response.ok ? await response.json() : null; + if (result?.success !== true || result.error) { + alert('Unable to update the reply. Try again.'); + return; } - } catch (e) { - console.error('There was an error while hiding the reply.'); - alert('error while hiding reply'); + const hidden = action.searchParams.get('hide') === 'true'; + action.searchParams.set('hide', String(!hidden)); + form.setAttribute('action', action.pathname + action.search); + submitButton.value = hidden ? 'Unhide' : 'Hide'; + } catch { + alert('Unable to update the reply. Try again.'); } finally { + busy = false; + submitButton.disabled = false; onAsyncRequestEnded(); } }); diff --git a/src/index.js b/src/index.js index 1ced1fc..c8d53b7 100644 --- a/src/index.js +++ b/src/index.js @@ -1615,19 +1615,20 @@ app.post('/manage_reply/:replyId', upload.array(), async (req, res) => { req.session.access_token ); } - await axios.post(hideReplyUrl.toString(), params, { + const response = await axios.post(hideReplyUrl.toString(), params, { httpsAgent: agent, maxRedirects: 0, }); + if (response.data?.success === true && !response.data.error) { + return res.json({ success: true }); + } } catch { console.error('Unable to update the reply.'); - return res.status(502).json({ - error: true, - message: 'Unable to update the reply. Try again.', - }); } - - return res.sendStatus(200); + return res.status(502).json({ + error: true, + message: 'Unable to update the reply. Try again.', + }); }); app.get( diff --git a/test/hide-reply.test.js b/test/hide-reply.test.js new file mode 100644 index 0000000..f96effb --- /dev/null +++ b/test/hide-reply.test.js @@ -0,0 +1,104 @@ +/** + * 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 path = require('node:path'); +const vm = require('node:vm'); +const { test } = require('node:test'); + +test('reply controls toggle only after confirmation and ignore duplicate submits', async () => { + let action = '/manage_reply/123?hide=true&username=example'; + let submit; + let finish; + const button = { value: 'Hide', disabled: false }; + const alerts = []; + const calls = []; + let loading = false; + const form = { + querySelector: () => button, + addEventListener: (_event, callback) => { + submit = callback; + }, + getAttribute: () => action, + setAttribute: (_name, value) => { + action = value; + }, + }; + vm.runInNewContext( + fs.readFileSync( + path.join(__dirname, '../public/scripts/hide-reply.js'), + 'utf8' + ), + { + URL, + window: { + location: new URL( + 'https://example.invalid/threads/456/replies' + ), + }, + document: { + addEventListener: (_event, callback) => callback(), + getElementsByClassName: () => [form], + querySelector: () => ({ content: 'synthetic-csrf' }), + }, + FormData: class {}, + alert: (message) => alerts.push(message), + onAsyncRequestStarting: () => { + loading = true; + }, + onAsyncRequestEnded: () => { + loading = false; + }, + fetch: (url, options) => { + calls.push(new URL(url).searchParams.get('hide')); + assert.equal(options.mode, 'same-origin'); + assert.equal(options.headers['X-CSRF-Token'], 'synthetic-csrf'); + return new Promise((resolve, reject) => { + finish = { resolve, reject }; + }); + }, + } + ); + const event = { preventDefault() {} }; + const confirmed = { ok: true, json: async () => ({ success: true }) }; + const pending = submit(event); + assert.ok(button.disabled && loading); + await submit(event); + assert.deepEqual(calls, ['true']); + finish.resolve(confirmed); + await pending; + assert.equal(action, '/manage_reply/123?hide=false&username=example'); + assert.equal(button.value, 'Unhide'); + + for (const fail of [ + () => + finish.resolve({ + ok: true, + json: async () => ({ success: false }), + }), + () => finish.reject(new Error('Synthetic network error.')), + ]) { + const attempt = submit(event); + fail(); + await attempt; + assert.equal(action, '/manage_reply/123?hide=false&username=example'); + assert.equal(button.value, 'Unhide'); + assert.ok(!button.disabled && !loading); + } + const retry = submit(event); + finish.resolve(confirmed); + await retry; + assert.equal(action, '/manage_reply/123?hide=true&username=example'); + assert.equal(button.value, 'Hide'); + assert.ok(!button.disabled && !loading); + assert.deepEqual(calls, ['true', 'false', 'false', 'false']); + assert.deepEqual(alerts, [ + 'Unable to update the reply. Try again.', + 'Unable to update the reply. Try again.', + ]); +}); diff --git a/test/lint-regressions.test.js b/test/lint-regressions.test.js index 0caadef..4384e0c 100644 --- a/test/lint-regressions.test.js +++ b/test/lint-regressions.test.js @@ -38,7 +38,13 @@ test('publishing and reply handlers keep response intermediates out of global st }), post: async (url, body) => { writes.push({ url: new URL(url), body }); - return { status: 200, data: { id: '789' } }; + return { + status: 200, + data: + new URL(url).pathname === '/123/manage_reply' + ? { success: true } + : { id: '789' }, + }; }, delete: () => assert.fail('Unexpected API deletion.'), }; @@ -113,9 +119,12 @@ test('reply network failures show the existing alert and finish loading without let submit; let started = 0; let ended = 0; + let requests = 0; const alerts = []; const logs = []; + const button = { disabled: false }; const form = { + querySelector: () => button, addEventListener: (_event, handler) => { submit = handler; }, @@ -127,6 +136,12 @@ test('reply network failures show the existing alert and finish loading without 'utf8' ), { + URL, + window: { + location: new URL( + 'https://example.invalid/threads/456/replies' + ), + }, document: { addEventListener: (_event, handler) => { ready = handler; @@ -136,6 +151,7 @@ test('reply network failures show the existing alert and finish loading without }, FormData: function () {}, fetch: async () => { + requests++; throw new Error('Synthetic network failure.'); }, console: { error: (message) => logs.push(message) }, @@ -147,8 +163,10 @@ test('reply network failures show the existing alert and finish loading without ); 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.deepEqual(alerts, ['Unable to update the reply. Try again.']); + assert.deepEqual(logs, []); + assert.equal(requests, 1); + assert.equal(button.disabled, false); assert.equal(started, 1); assert.equal(ended, 1); }); diff --git a/test/reply-management.test.js b/test/reply-management.test.js new file mode 100644 index 0000000..ef52733 --- /dev/null +++ b/test/reply-management.test.js @@ -0,0 +1,107 @@ +/** + * 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 { once } = require('node:events'); +const { createRequire } = require('node:module'); +const { test } = require('node:test'); + +const entry = path.join(__dirname, '../src/index.js'); +const appRequire = createRequire(entry); + +async function startApp(t, api) { + const logs = []; + const app = vm.runInNewContext(fs.readFileSync(entry, 'utf8') + '\napp;', { + __dirname: path.dirname(entry), + process: { + env: { + SESSION_SECRET: 'synthetic-secret', + INITIAL_ACCESS_TOKEN: 'synthetic-token', + INITIAL_USER_ID: '456', + }, + }, + console: { log() {}, warn() {}, error: (...args) => logs.push(args) }, + require(name) { + if (name === 'axios') return api; + if (name === 'dotenv') return { config() {} }; + if (name === 'fs') return { readFileSync: () => '' }; + if (name === 'https') + return { ...https, createServer: () => ({ listen() {} }) }; + return appRequire(name); + }, + }); + 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 home = await fetch(base, { + redirect: 'manual', + signal: AbortSignal.timeout(5000), + }); + assert.equal(home.status, 302); + const cookie = home.headers.get('set-cookie').split(';')[0]; + const upload = await fetch(base + '/upload', { + headers: { cookie }, + redirect: 'manual', + signal: AbortSignal.timeout(5000), + }); + assert.equal(upload.status, 200); + const csrf = (await upload.text()).match( + /name="csrf-token" content="([a-f0-9]{64})"/ + )[1]; + return { + logs, + request: (route, body) => + fetch(base + route, { + ...(body && { method: 'POST', body }), + headers: { cookie, 'X-CSRF-Token': csrf }, + redirect: 'manual', + signal: AbortSignal.timeout(5000), + }), + }; +} + +async function checkError(response, status, message) { + assert.equal(response.status, status); + assert.deepEqual(await response.json(), { error: true, message }); +} + +test('reply management only reports confirmed upstream success', async (t) => { + let result = { success: false }; + const { request, logs } = await startApp(t, { + post: async (url, body) => { + assert.equal(new URL(url).pathname, '/123/manage_reply'); + assert.equal(body.hide, false); + if (result instanceof Error) throw result; + return { data: result }; + }, + }); + const route = '/manage_reply/123?hide=false'; + for (const failure of [ + { success: false }, + { success: 'true' }, + new Error('Synthetic upstream detail.'), + ]) { + result = failure; + await checkError( + await request(route, new FormData()), + 502, + 'Unable to update the reply. Try again.' + ); + } + result = { success: true }; + assert.deepEqual(await (await request(route, new FormData())).json(), { + success: true, + }); + assert.deepEqual(logs, [['Unable to update the reply.']]); +});