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
18 changes: 17 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const FIELD__LATITUDE = 'latitude';
const FIELD__LIKES = 'likes';
const FIELD__LONGITUDE = 'longitude';
const FIELD__LINK_ATTACHMENT_URL = 'link_attachment_url';
const FIELD__LOCATION_ID = 'location_id';
const FIELD__TOPIC_TAG = 'topic_tag';
const FIELD__MEDIA_TYPE = 'media_type';
const FIELD__MEDIA_URL = 'media_url';
Expand Down Expand Up @@ -1301,6 +1302,21 @@ app.get(
is_ghost_post,
};
postLoaded = true;
if (/^\d+$/.test(threadId)) {
try {
const locationUrl = buildGraphAPIURL(
threadId,
{ [PARAMS__FIELDS]: FIELD__LOCATION_ID },
req.session.access_token
);
const locationResponse = await axios.get(locationUrl, {
httpsAgent: agent,
});
data.location_id = locationResponse.data?.location_id;
} catch {
data.location_id = undefined;
}
}
} catch (e) {
error = e?.response?.data?.error?.message ?? e.message;
console.error(error);
Expand Down Expand Up @@ -1733,7 +1749,7 @@ app.get(
}

res.render('thread_insights', {
title: 'Thread Insights',
title: 'Media Insights',
threadId,
metrics,
since,
Expand Down
9 changes: 7 additions & 2 deletions test/own-post-deletion.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -276,8 +276,12 @@ test('owned detail shows Delete after Quote and Repost and reuses the existing g
const reads = [];
const readConfigs = [];
api.get = async (url, config) => {
reads.push(new URL(url));
const read = new URL(url);
reads.push(read);
readConfigs.push(config);
if (read.searchParams.get('fields') === 'location_id') {
return { data: {} };
}
return get(url, config);
};
const remove = api.delete;
Expand All @@ -288,9 +292,10 @@ test('owned detail shows Delete after Quote and Repost and reuses the existing g
};
const request = await startApp(t, api);
const html = await (await request('/threads/123')).text();
assert.equal(reads[1].searchParams.get('fields'), 'location_id');
assert.deepEqual(
readConfigs.map((config) => config.maxRedirects),
[undefined, 0, 0, 0]
[undefined, undefined, 0, 0, 0]
);
const quotePosition = html.indexOf('<td>Quote</td>');
const repostPosition = html.indexOf('<td>Repost</td>');
Expand Down
8 changes: 7 additions & 1 deletion test/post-details-rate-limit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,15 @@ test('Post Details rejects excess requests before authentication and API work',
/Too many post detail requests\. Wait a minute and try again\./
);
assert.ok(Number(blocked.headers.get('retry-after')) > 0);
assert.doesNotMatch(
blocked.text,
/action="\/repost"|quotePostId=|\/undefined/
);
assert.deepEqual({ reads, authChecks }, before);
assert.equal(authChecks, 60);
assert.equal(reads, signedIn ? 181 : 0);
// Each signed-in request loads the post, location, and two ownership records.
// The session's token binding is verified once.
assert.equal(reads, signedIn ? 241 : 0);
assert.equal(
(await request('/upload')).status,
signedIn ? 200 : 302,
Expand Down
21 changes: 15 additions & 6 deletions test/post-details-ui.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,14 @@ async function startApp(t, post, owner = '456', probe = {}) {
return {
get: async (url, config) => {
const parsed = new URL(url);
if (
parsed.searchParams.get('fields') ===
'location_id'
) {
reads.push(parsed);
assert.ok(config.httpsAgent);
return { data: {} };
}
const stage =
parsed.pathname === '/debug_token'
? 'token'
Expand Down Expand Up @@ -514,12 +522,13 @@ test('Insights visibility requires verified ownership independently of deletion
);
assert.equal(
reads.length,
scenario.expectedReads ??
(scenario.probe?.failToken ||
scenario.probe?.tokenUserID ||
scenario.probe?.tokenValid === false
? 2
: 4)
1 +
(scenario.expectedReads ??
(scenario.probe?.failToken ||
scenario.probe?.tokenUserID ||
scenario.probe?.tokenValid === false
? 2
: 4))
);
const probeFailed =
scenario.probe?.failOwner ||
Expand Down
169 changes: 169 additions & 0 deletions test/post-location.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/**
* 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);

async function startApp(t, get, signedIn = true) {
const app = vm.runInNewContext(
fs.readFileSync(entry, 'utf8') + '\napp;',
{
__dirname: path.dirname(entry),
process: {
env: {
SESSION_SECRET: 'test-secret',
...(signedIn && {
INITIAL_ACCESS_TOKEN: 'test-token',
INITIAL_USER_ID: '456',
}),
},
},
console: { log() {}, error() {} },
require(name) {
if (name === 'axios') return { get };
if (name === 'dotenv') return { config() {} };
if (name === 'fs') return { readFileSync: () => '' };
if (name === 'https')
return { ...https, createServer: () => ({ listen() {} }) };
return appRequire(name);
},
},
{ filename: entry }
);
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}`;
let cookie;
return async (route) => {
const response = await fetch(new URL(route, base), {
redirect: 'manual',
signal: AbortSignal.timeout(10000),
headers: { ...(cookie && { cookie }) },
});
cookie = response.headers.get('set-cookie')?.split(';')[0] ?? cookie;
return response;
};
}

test('post location IDs link to location details while poll and ghost fields keep working', async (t) => {
const calls = [];
let locationId = '345';
let locationUnavailable = false;
const request = await startApp(t, async (url, options) => {
const apiUrl = new URL(url);
calls.push(apiUrl);
if (apiUrl.pathname === '/123/insights') return { data: { data: [] } };
if (apiUrl.pathname === '/debug_token') {
assert.equal(options.maxRedirects, 0);
return { data: { data: { is_valid: true, user_id: '456' } } };
}
if (apiUrl.pathname === '/456') {
assert.equal(options.maxRedirects, 0);
return { data: { id: '456' } };
}
if (apiUrl.searchParams.get('fields') === 'id,media_type,owner') {
assert.equal(options.maxRedirects, 0);
return { data: { id: '123', owner: { id: '456' } } };
}
if (apiUrl.pathname === '/345')
return { data: { id: '345', name: 'Example Location' } };
if (apiUrl.searchParams.get('fields') === 'location_id') {
if (locationUnavailable)
throw new Error('Optional location field unavailable.');
return { data: { location_id: locationId } };
}
return {
data: {
text: 'Example post',
poll_attachment: { option_a: 'Option A', option_b: 'Option B' },
ghost_post_status: 'ACTIVE',
access_token: 'synthetic-response-token',
},
};
});
const html = await (await request('/threads/123')).text();
assert.equal(calls[0].pathname, '/123');
assert.ok(
!calls[0].searchParams.get('fields').split(',').includes('location_id')
);
assert.equal(calls[1].pathname, '/123');
assert.equal(calls[1].searchParams.get('fields'), 'location_id');
assert.match(
html,
/<td>Location ID<\/td><td><a href="\/locationSearch\?locationId=345">345<\/a>/
);
assert.match(html, /Option A/);
assert.match(html, /<td>Is Ghost Post<\/td><td>true<\/td>/);
assert.doesNotMatch(
html,
/test-token|synthetic-response-token|access_token/
);
const linked = await (
await request('/locationSearch?locationId=345')
).text();
assert.match(linked, /Example Location/);
assert.match(
await (await request('/threads/123/insights')).text(),
/<h1>Media Insights<\/h1>/
);
for (const value of [
undefined,
'',
'0',
'0123',
'<script>invalid</script>',
{ id: '345' },
]) {
locationId = value;
const untagged = await (await request('/threads/123')).text();
assert.match(untagged, /Example post/);
assert.doesNotMatch(
untagged,
/<td>Location ID<|locationId=|<script>invalid/
);
}
locationUnavailable = true;
const compatible = await (await request('/threads/123')).text();
assert.match(compatible, /Example post/);
assert.match(compatible, /Option A/);
assert.doesNotMatch(
compatible,
/locationId=|Optional location field unavailable/
);
});

test('failed primary loads and signed-out requests never perform an optional location probe', async (t) => {
let calls = 0;
const request = await startApp(t, async (url) => {
calls++;
assert.notEqual(new URL(url).searchParams.get('fields'), 'location_id');
throw {
response: { data: { error: { message: 'Post unavailable.' } } },
};
});
const signedOut = await startApp(
t,
() => assert.fail('Unexpected API request'),
false
);
assert.equal((await signedOut('/threads/123')).status, 302);
const html = await (await request('/threads/123')).text();
assert.equal(calls, 1);
assert.doesNotMatch(html, /locationId=/);
});
5 changes: 5 additions & 0 deletions views/thread.pug
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ block content
tr
td Topic Tag
td=topic_tag
if typeof location_id === 'string' && /^[1-9]\d*$/.test(location_id)
tr
td Location ID
td
a(href=`/locationSearch?locationId=${encodeURIComponent(location_id)}`)=location_id
if hasDisplayValue(media_type)
tr
td Media Type
Expand Down