Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 28 additions & 20 deletions public/scripts/hide-reply.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,40 +5,48 @@
* 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: {
'X-CSRF-Token':
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();
}
});
Expand Down
15 changes: 8 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
104 changes: 104 additions & 0 deletions test/hide-reply.test.js
Original file line number Diff line number Diff line change
@@ -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.',
]);
});
24 changes: 21 additions & 3 deletions test/lint-regressions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.'),
};
Expand Down Expand Up @@ -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;
},
Expand All @@ -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;
Expand All @@ -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) },
Expand All @@ -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);
});
107 changes: 107 additions & 0 deletions test/reply-management.test.js
Original file line number Diff line number Diff line change
@@ -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.']]);
});