feat(wp): XML-RPC connectivity probe (system.listMethods)
Node tests / test (push) Has been cancelled
Node tests / test (push) Has been cancelled
Add xmlrpc-client with serializer/parser (fast-xml-parser), local stub tests, and npm run wp:probe-xmlrpc for each configured site wp_url. Reuses WP retry env and exports wpRetryOpts from wordpress.js. Optional OPS_CHECK_XMLRPC=1 in ops-check.sh after wp:test. Publish path remains REST-only; probe validates BIT-353 XML-RPC surface for hosts that disable or restrict REST. Made-with: Cursor
This commit is contained in:
1 parent
3daaf43088
commit
495143690f
8 files changed
+389
-2
No files matched your search
+1
-1
@@ -13,7 +13,7 @@ ANTHROPIC_API_KEY=
|
||||
WP_URL=https://wp.newsproject.bitreport.pt
|
||||
WP_USER=
|
||||
WP_PASSWORD=
|
||||
# Retries for WP REST GET/POST (publish, tags, wp:test users/me)
|
||||
# Retries for WP REST GET/POST (publish, tags, wp:test users/me) and XML-RPC probe posts
|
||||
WP_HTTP_MAX_ATTEMPTS=3
|
||||
WP_RETRY_BASE_MS=500
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ node src/index.js write "FC Porto match result"
|
||||
| `npm run deploy:lxc` | Server deploy: `git pull --ff-only`, `npm ci --omit=dev`, `pm2 startOrReload ecosystem.config.cjs --update-env`; append `-- --with-ops-check` for smoke tests |
|
||||
| `npm run verify:deploy -- <url>` | Smoke-test `GET /health` (expects `listen` mode); needs `curl` + `node` |
|
||||
| `npm run wp:test` | `GET /wp-json/wp/v2/users/me` — validates **every** `config/sites/*.json` (excl. example), or `WP_*` env if no site files |
|
||||
| `npm run wp:probe-xmlrpc` | POST `xmlrpc.php` with `system.listMethods` — confirms XML-RPC is enabled (no credentials); same site selection as `wp:test` for `wp_url` |
|
||||
| `npm run rss:test` | Probe each RSS URL in `config/sources.json` (transient HTTP retries via `RSS_HTTP_MAX_ATTEMPTS` / `RSS_RETRY_BASE_MS`); stdout `{ "ok", "feeds" }`; exit 1 if any feed fails |
|
||||
| `npm run x:test` | X API v2 **recent search** for each `x.queries[]` in `config/social.json`; needs `TWITTER_BEARER_TOKEN` |
|
||||
| `npm run ops:check` | **`npm test`** first, then **`rss:test` always**; **`wp:test` only** if `config/sites/*.json` (≠ example) or `WP_URL`+`WP_USER`+`WP_PASSWORD` |
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
"pm2:start": "pm2 start ecosystem.config.cjs",
|
||||
"verify:deploy": "bash tools/verify-deploy.sh",
|
||||
"wp:test": "node src/index.js wp:test",
|
||||
"wp:probe-xmlrpc": "node src/index.js wp:probe-xmlrpc",
|
||||
"rss:test": "node src/index.js rss:test",
|
||||
"x:test": "node src/index.js x:test",
|
||||
"ops:check": "bash tools/ops-check.sh",
|
||||
|
||||
@@ -11,6 +11,7 @@ const { fetchMergedSourceArticles } = require('./crawler/merge-sources');
|
||||
const { scrapeArticle } = require('./crawler/scraper');
|
||||
const { generateArticle, detectTopics } = require('./writer/ai');
|
||||
const { publishToWordPress, testConnection } = require('./publisher/wordpress');
|
||||
const { probeWordPressXmlRpc } = require('./publisher/xmlrpc-client');
|
||||
const { startRSSListener } = require('./listener/rss-listener');
|
||||
const { startStatusServer } = require('./http/status-server');
|
||||
const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadSocialConfig } = require('./config/loader');
|
||||
@@ -193,6 +194,58 @@ async function runWpTest() {
|
||||
process.exit(all_ok ? 0 : 1);
|
||||
}
|
||||
|
||||
async function runWpProbeXmlRpc() {
|
||||
const site_configs = loadSiteConfigs();
|
||||
let to_test = [];
|
||||
|
||||
if (site_configs.length === 0) {
|
||||
const site = loadDefaultSiteConfig();
|
||||
if (!site.wp_url) {
|
||||
logger.error(
|
||||
'wp:probe-xmlrpc — missing wp_url (add config/sites/<site>.json or set WP_URL)'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
to_test = [site];
|
||||
} else {
|
||||
for (const site of site_configs) {
|
||||
if (!site.wp_url) {
|
||||
logger.error(`wp:probe-xmlrpc — site "${site.name || 'unnamed'}" has no wp_url`);
|
||||
process.exit(1);
|
||||
}
|
||||
to_test.push(site);
|
||||
}
|
||||
}
|
||||
|
||||
const sites_out = [];
|
||||
for (const site of to_test) {
|
||||
const result = await probeWordPressXmlRpc(site);
|
||||
if (result.ok) {
|
||||
logger.info(
|
||||
`WordPress XML-RPC OK: ${site.wp_url} (${site.name || 'site'}) methods=${result.method_count}`
|
||||
);
|
||||
sites_out.push({
|
||||
ok: true,
|
||||
wp_url: site.wp_url,
|
||||
site_name: site.name || 'default',
|
||||
method_count: result.method_count,
|
||||
});
|
||||
} else {
|
||||
logger.error(`wp:probe-xmlrpc failed for "${site.name || site.wp_url}": ${result.error}`);
|
||||
sites_out.push({
|
||||
ok: false,
|
||||
wp_url: site.wp_url,
|
||||
site_name: site.name || 'default',
|
||||
error: result.error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const all_ok = sites_out.every((s) => s.ok);
|
||||
console.log(JSON.stringify({ ok: all_ok, sites: sites_out }));
|
||||
process.exit(all_ok ? 0 : 1);
|
||||
}
|
||||
|
||||
async function runAutoMode() {
|
||||
logger.info('Auto mode starting — RSS listener active');
|
||||
|
||||
@@ -291,6 +344,9 @@ async function main() {
|
||||
} else if (command === 'wp:test') {
|
||||
await runWpTest();
|
||||
process.exit(0);
|
||||
} else if (command === 'wp:probe-xmlrpc') {
|
||||
await runWpProbeXmlRpc();
|
||||
process.exit(0);
|
||||
} else if (command === 'rss:test') {
|
||||
await runRssTest();
|
||||
process.exit(0);
|
||||
@@ -302,6 +358,7 @@ async function main() {
|
||||
console.log(' node src/index.js write [topic] — write one article (exits)');
|
||||
console.log(' node src/index.js listen — RSS listener + HTTP on HOST:PORT (/, /health)');
|
||||
console.log(' node src/index.js wp:test — verify WP REST + application password (exits)');
|
||||
console.log(' node src/index.js wp:probe-xmlrpc — verify WP xmlrpc.php (system.listMethods; no auth)');
|
||||
console.log(' node src/index.js rss:test — probe all RSS feeds in sources.json (exits)');
|
||||
console.log(' node src/index.js x:test — probe X API v2 recent search (needs social.json + TWITTER_BEARER_TOKEN)');
|
||||
process.exit(1);
|
||||
|
||||
@@ -154,4 +154,4 @@ async function testConnection(site_config) {
|
||||
return { ok: true, user_info: response.data };
|
||||
}
|
||||
|
||||
module.exports = { publishToWordPress, testConnection };
|
||||
module.exports = { publishToWordPress, testConnection, wpRetryOpts };
|
||||
@@ -0,0 +1,211 @@
|
||||
'use strict';
|
||||
|
||||
const { XMLParser } = require('fast-xml-parser');
|
||||
const { axiosPostWithRetry } = require('../util/http-retry');
|
||||
const { wpRetryOpts } = require('./wordpress');
|
||||
|
||||
/**
|
||||
* @param {string} s
|
||||
* @returns {string}
|
||||
*/
|
||||
function escapeXml(s) {
|
||||
return String(s)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize a JS value to XML-RPC <value>…</value> (recursive).
|
||||
*
|
||||
* @param {unknown} v
|
||||
* @returns {string}
|
||||
*/
|
||||
function serializeValue(v) {
|
||||
if (v === null || v === undefined) {
|
||||
return '<value><string></string></value>';
|
||||
}
|
||||
if (typeof v === 'boolean') {
|
||||
return `<value><boolean>${v ? 1 : 0}</boolean></value>`;
|
||||
}
|
||||
if (typeof v === 'number' && Number.isInteger(v)) {
|
||||
return `<value><int>${v}</int></value>`;
|
||||
}
|
||||
if (typeof v === 'number') {
|
||||
return `<value><double>${v}</double></value>`;
|
||||
}
|
||||
if (typeof v === 'string') {
|
||||
return `<value><string>${escapeXml(v)}</string></value>`;
|
||||
}
|
||||
if (Array.isArray(v)) {
|
||||
const inner = v.map((x) => serializeValue(x)).join('');
|
||||
return `<value><array><data>${inner}</data></array></value>`;
|
||||
}
|
||||
if (typeof v === 'object') {
|
||||
const members = Object.entries(v)
|
||||
.map(([k, val]) => `<member><name>${escapeXml(k)}</name>${serializeValue(val)}</member>`)
|
||||
.join('');
|
||||
return `<value><struct>${members}</struct></value>`;
|
||||
}
|
||||
throw new Error(`xmlrpc: unsupported value type ${typeof v}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} methodName
|
||||
* @param {unknown[]} params
|
||||
* @returns {string}
|
||||
*/
|
||||
function buildMethodCall(methodName, params) {
|
||||
const paramXml = (params || []).map((p) => `<param>${serializeValue(p)}</param>`).join('');
|
||||
return (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>' +
|
||||
`<methodCall><methodName>${escapeXml(methodName)}</methodName><params>${paramXml}</params></methodCall>`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} wp_url
|
||||
* @returns {string}
|
||||
*/
|
||||
function xmlrpcEndpointUrl(wp_url) {
|
||||
const base = String(wp_url || '').replace(/\/$/, '');
|
||||
if (!base) {
|
||||
throw new Error('xmlrpc: wp_url is empty');
|
||||
}
|
||||
return `${base}/xmlrpc.php`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize fast-xml-parser output: single child → array of one.
|
||||
*
|
||||
* @template T
|
||||
* @param {T | T[] | undefined} x
|
||||
* @returns {T[]}
|
||||
*/
|
||||
function asArray(x) {
|
||||
if (x === undefined || x === null) {
|
||||
return [];
|
||||
}
|
||||
return Array.isArray(x) ? x : [x];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} parsed
|
||||
* @returns {string | null}
|
||||
*/
|
||||
function extractFaultString(parsed) {
|
||||
const fault = parsed?.methodResponse?.fault;
|
||||
if (!fault) {
|
||||
return null;
|
||||
}
|
||||
const members = asArray(fault.value?.struct?.member);
|
||||
for (const m of members) {
|
||||
if (m?.name === 'faultString') {
|
||||
const v = m.value;
|
||||
if (v && typeof v === 'object' && v.string !== undefined) {
|
||||
return String(v.string);
|
||||
}
|
||||
return String(v);
|
||||
}
|
||||
}
|
||||
return 'XML-RPC fault';
|
||||
}
|
||||
|
||||
/**
|
||||
* Count methods returned by system.listMethods (best-effort on parser shape).
|
||||
*
|
||||
* @param {object} parsed
|
||||
* @returns {number}
|
||||
*/
|
||||
function countListMethodsEntries(parsed) {
|
||||
const param = parsed?.methodResponse?.params?.param;
|
||||
if (!param) {
|
||||
return 0;
|
||||
}
|
||||
const value = param.value ?? param;
|
||||
const data = value?.array?.data?.value;
|
||||
if (data === undefined || data === null) {
|
||||
return 0;
|
||||
}
|
||||
return Array.isArray(data) ? data.length : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST an XML-RPC call to WordPress xmlrpc.php.
|
||||
*
|
||||
* @param {string} endpoint
|
||||
* @param {string} methodName
|
||||
* @param {unknown[]} params
|
||||
* @returns {Promise<{ raw: string, parsed: object }>}
|
||||
*/
|
||||
async function postXmlRpc(endpoint, methodName, params) {
|
||||
const body = buildMethodCall(methodName, params);
|
||||
const response = await axiosPostWithRetry(
|
||||
endpoint,
|
||||
body,
|
||||
{
|
||||
headers: { 'Content-Type': 'text/xml; charset=utf-8' },
|
||||
timeout: 15000,
|
||||
responseType: 'text',
|
||||
transformResponse: [(d) => d],
|
||||
},
|
||||
{ ...wpRetryOpts(), urlHint: `xmlrpc ${methodName}` }
|
||||
);
|
||||
const raw = typeof response.data === 'string' ? response.data : String(response.data);
|
||||
const parser = new XMLParser({
|
||||
ignoreAttributes: true,
|
||||
trimValues: true,
|
||||
parseTagValue: false,
|
||||
});
|
||||
const parsed = parser.parse(raw);
|
||||
return { raw, parsed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe WordPress XML-RPC (no auth). Calls system.listMethods.
|
||||
*
|
||||
* @param {{ wp_url: string }} site_config
|
||||
* @returns {Promise<{ ok: true, method_count: number } | { ok: false, error: string }>}
|
||||
*/
|
||||
async function probeWordPressXmlRpc(site_config) {
|
||||
const wp_url = site_config?.wp_url;
|
||||
if (!wp_url || typeof wp_url !== 'string') {
|
||||
return { ok: false, error: 'missing wp_url' };
|
||||
}
|
||||
let endpoint;
|
||||
try {
|
||||
endpoint = xmlrpcEndpointUrl(wp_url);
|
||||
} catch (err) {
|
||||
return { ok: false, error: err.message };
|
||||
}
|
||||
|
||||
try {
|
||||
const { parsed } = await postXmlRpc(endpoint, 'system.listMethods', []);
|
||||
const fault = extractFaultString(parsed);
|
||||
if (fault) {
|
||||
return { ok: false, error: fault };
|
||||
}
|
||||
const method_count = countListMethodsEntries(parsed);
|
||||
if (method_count < 1) {
|
||||
return { ok: false, error: 'unexpected XML-RPC response (no methods list)' };
|
||||
}
|
||||
return { ok: true, method_count };
|
||||
} catch (err) {
|
||||
const status = err.response?.status;
|
||||
const message = err.response?.data || err.message;
|
||||
return { ok: false, error: status ? `HTTP ${status}: ${message}` : String(message) };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
escapeXml,
|
||||
serializeValue,
|
||||
buildMethodCall,
|
||||
xmlrpcEndpointUrl,
|
||||
probeWordPressXmlRpc,
|
||||
postXmlRpc,
|
||||
extractFaultString,
|
||||
countListMethodsEntries,
|
||||
};
|
||||
@@ -0,0 +1,112 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const http = require('node:http');
|
||||
const test = require('node:test');
|
||||
const {
|
||||
escapeXml,
|
||||
buildMethodCall,
|
||||
extractFaultString,
|
||||
countListMethodsEntries,
|
||||
xmlrpcEndpointUrl,
|
||||
probeWordPressXmlRpc,
|
||||
} = require('./xmlrpc-client');
|
||||
const { XMLParser } = require('fast-xml-parser');
|
||||
|
||||
test('escapeXml escapes special characters', () => {
|
||||
assert.equal(escapeXml('a&b<c>'), 'a&b<c>');
|
||||
assert.equal(escapeXml('"x"'), '"x"');
|
||||
});
|
||||
|
||||
test('buildMethodCall — system.listMethods empty params', () => {
|
||||
const xml = buildMethodCall('system.listMethods', []);
|
||||
assert.match(xml, /<methodName>system\.listMethods<\/methodName>/);
|
||||
assert.match(xml, /<params><\/params>|<params\s*\/>/);
|
||||
});
|
||||
|
||||
test('buildMethodCall — encodes struct for future wp.newPost-style calls', () => {
|
||||
const xml = buildMethodCall('demo.echo', [{ hello: 'world' }]);
|
||||
assert.match(xml, /<struct>/);
|
||||
assert.match(xml, /<name>hello<\/name>/);
|
||||
assert.match(xml, /<string>world<\/string>/);
|
||||
});
|
||||
|
||||
test('extractFaultString and countListMethodsEntries', () => {
|
||||
const parser = new XMLParser({ ignoreAttributes: true, trimValues: true, parseTagValue: false });
|
||||
const okXml = `<?xml version="1.0"?><methodResponse><params><param><value><array><data>
|
||||
<value><string>a</string></value>
|
||||
<value><string>b</string></value>
|
||||
</data></array></value></param></params></methodResponse>`;
|
||||
const okParsed = parser.parse(okXml);
|
||||
assert.equal(extractFaultString(okParsed), null);
|
||||
assert.equal(countListMethodsEntries(okParsed), 2);
|
||||
|
||||
const faultXml = `<?xml version="1.0"?><methodResponse><fault><value><struct>
|
||||
<member><name>faultCode</name><value><int>403</int></value></member>
|
||||
<member><name>faultString</name><value><string>disabled</string></value></member>
|
||||
</struct></value></fault></methodResponse>`;
|
||||
const faultParsed = parser.parse(faultXml);
|
||||
assert.equal(extractFaultString(faultParsed), 'disabled');
|
||||
assert.equal(countListMethodsEntries(faultParsed), 0);
|
||||
});
|
||||
|
||||
test('xmlrpcEndpointUrl', () => {
|
||||
assert.equal(xmlrpcEndpointUrl('https://ex.com'), 'https://ex.com/xmlrpc.php');
|
||||
assert.equal(xmlrpcEndpointUrl('https://ex.com/'), 'https://ex.com/xmlrpc.php');
|
||||
assert.equal(xmlrpcEndpointUrl('https://ex.com/blog'), 'https://ex.com/blog/xmlrpc.php');
|
||||
});
|
||||
|
||||
test('probeWordPressXmlRpc — happy path against local stub', async () => {
|
||||
const listMethodsResponse = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<methodResponse><params><param><value><array><data>
|
||||
<value><string>system.listMethods</string></value>
|
||||
<value><string>wp.getUsersBlogs</string></value>
|
||||
</data></array></value></param></params></methodResponse>`;
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
let buf = '';
|
||||
req.on('data', (c) => {
|
||||
buf += c;
|
||||
});
|
||||
req.on('end', () => {
|
||||
assert.equal(req.url, '/xmlrpc.php');
|
||||
assert.match(buf, /system\.listMethods/);
|
||||
res.writeHead(200, { 'Content-Type': 'text/xml' });
|
||||
res.end(listMethodsResponse);
|
||||
});
|
||||
});
|
||||
|
||||
await new Promise((resolve) => server.listen(0, resolve));
|
||||
const { port } = server.address();
|
||||
|
||||
try {
|
||||
const result = await probeWordPressXmlRpc({ wp_url: `http://127.0.0.1:${port}` });
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.method_count, 2);
|
||||
} finally {
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
});
|
||||
|
||||
test('probeWordPressXmlRpc — XML-RPC fault body', async () => {
|
||||
const faultBody = `<?xml version="1.0"?><methodResponse><fault><value><struct>
|
||||
<member><name>faultCode</name><value><int>405</int></value></member>
|
||||
<member><name>faultString</name><value><string>Not allowed</string></value></member>
|
||||
</struct></value></fault></methodResponse>`;
|
||||
|
||||
const server = http.createServer((_req, res) => {
|
||||
res.writeHead(200, { 'Content-Type': 'text/xml' });
|
||||
res.end(faultBody);
|
||||
});
|
||||
|
||||
await new Promise((resolve) => server.listen(0, resolve));
|
||||
const { port } = server.address();
|
||||
|
||||
try {
|
||||
const result = await probeWordPressXmlRpc({ wp_url: `http://127.0.0.1:${port}` });
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.error, /Not allowed/);
|
||||
} finally {
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
});
|
||||
@@ -30,6 +30,11 @@ if [[ "${_should_wp_test}" -eq 1 ]]; then
|
||||
echo ""
|
||||
echo "=== ops-check: WordPress REST ==="
|
||||
npm run wp:test --silent
|
||||
if [[ "${OPS_CHECK_XMLRPC:-}" == "1" ]]; then
|
||||
echo ""
|
||||
echo "=== ops-check: WordPress XML-RPC (OPS_CHECK_XMLRPC=1) ==="
|
||||
npm run wp:probe-xmlrpc --silent
|
||||
fi
|
||||
else
|
||||
echo ""
|
||||
echo "=== ops-check: wp:test skipped (no config/sites/*.json besides example, WP_* not set) ==="
|
||||
|
||||
Reference in new issue
Block a user