-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathclient.js
More file actions
768 lines (704 loc) · 27.9 KB
/
Copy pathclient.js
File metadata and controls
768 lines (704 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
const bodyParser = require('body-parser'),
crypto = require('crypto'),
{ URL } = require('url'),
express = require('express'),
morgan = require('morgan'),
config = require('./config'),
{ createSessionStore } = require('./lib/session-store'),
{ createGuardedFetch } = require('./lib/guarded-fetch'),
{ describeActionError } = require('./lib/egress-error'),
{ createSessionSockets } = require('./session-sockets'),
{
createRssCloudClient,
createWebSubClient,
readVerification,
buildNotifyResponse,
renderCloudFeed,
discoverFeed
} = require('./lib'),
textParser = bodyParser.text({ type: '*/xml' }),
// Content distribution arrives with the origin feed's Content-Type relayed
// verbatim, so the callback parses any media type as a raw string to log it.
rawTextParser = bodyParser.text({ type: () => true }),
urlencodedParser = bodyParser.urlencoded({ extended: false }),
jsonParser = bodyParser.json();
// The hub's WebSub front door, advertised in feeds via <atom:link rel="hub">.
const hubUrl = `${config.hubServerUrl}/websub`;
// The hub's origin, decomposed for the <cloud> element's domain/port — its
// XML-RPC front door is always /RPC2, the rssCloud convention.
const hubOrigin = new URL(config.hubServerUrl);
const hubPort =
Number(hubOrigin.port) || (hubOrigin.protocol === 'https:' ? 443 : 80);
// This session's callback URL the hub notifies for WebSub content
// distribution and intent verification.
function webSubCallbackUrl(sessionId) {
return `http://${config.domain}:${config.port}/s/${sessionId}/websub-callback`;
}
// Build the feed URL an action targets: the caller's own external feedUrl
// when given (subscriber mode), else this session's own test feed.
function resolveFeedUrl(sessionId, { feedUrl, feedName }) {
return feedUrl || `http://${config.domain}:${config.port}/s/${sessionId}/${feedName || 'rss-01.xml'}`;
}
// Pull the topic URL out of a delivery's Link header (`<url>; rel="self"`).
function selfLink(link) {
const match = /<([^>]+)>\s*;\s*rel="self"/.exec(link || '');
return match ? match[1] : undefined;
}
// Verify a relayed X-Hub-Signature (`<algo>=<hex>`) against the body using the
// secret this session subscribed with. Returns a human-readable verdict for
// the log.
function checkSignature(session, topicUrl, signature, body) {
const secret = session.webSubSecrets[topicUrl];
if (!secret) {
return 'no stored secret — not verified';
}
const [algo, digest] = String(signature).split('=');
if (!algo || !digest) {
return 'malformed header';
}
let expected;
try {
expected = crypto.createHmac(algo, secret).update(body).digest('hex');
} catch {
return `unsupported algorithm: ${algo}`;
}
return expected === digest ? 'valid ✓' : 'INVALID ✗';
}
// Helper function to escape HTML entities
function escapeHtml(text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// Render the unified control box + live traffic log for a session.
// `hubServerUrl`/`hubUrl` prefill the server/hub override field with this
// harness's own defaults; the Discover action overwrites it client-side.
function renderPage(sessionId, wsUrl) {
return `<!DOCTYPE html>
<html>
<head>
<title>rssCloud Test Client</title>
<link href="/css/style.css" rel="stylesheet" />
<style>
/* Client-specific additions layered on the shared server stylesheet. */
select {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 15px;
font-size: 16px;
background: white;
}
.controls {
background: #f8f9fa;
padding: 20px;
border-radius: 5px;
margin: 20px 0;
}
.controls fieldset {
border: none;
padding: 0;
margin: 0 0 20px;
}
.controls fieldset:last-of-type {
margin-bottom: 0;
}
.controls legend {
font-weight: bold;
color: #2c3e50;
padding: 0;
margin-bottom: 10px;
}
.form-row {
display: flex;
gap: 20px;
flex-wrap: wrap;
}
.form-row > label {
flex: 1;
min-width: 220px;
}
.input-with-button {
display: flex;
gap: 10px;
align-items: flex-start;
}
.input-with-button input {
flex: 1;
margin-bottom: 0;
}
.actions {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
</style>
</head>
<body data-session-id="${escapeHtml(sessionId)}">
<h1>rssCloud Test Client</h1>
<div class="controls">
<fieldset>
<legend>Target</legend>
<div class="form-row">
<label for="protocol">
Protocol
<select id="protocol">
<option value="rsscloud-rest">rssCloud REST</option>
<option value="rsscloud-xml-rpc">rssCloud XML-RPC</option>
<option value="websub">WebSub</option>
</select>
</label>
<label for="serverOverride">
Server/hub override
<input type="text" id="serverOverride" placeholder="${escapeHtml(config.hubServerUrl)}">
</label>
</div>
</fieldset>
<fieldset>
<legend>Feed</legend>
<label for="feedUrl">
Feed URL (external — leave blank to use this harness's own test feed)
</label>
<div class="input-with-button">
<input type="text" id="feedUrl" placeholder="https://example.com/feed.xml">
<button type="button" id="discoverButton">Discover</button>
</div>
<label for="feedName">
Feed name (own test feed)
<input type="text" id="feedName" value="rss-01.xml">
</label>
</fieldset>
<fieldset class="websub-only">
<legend>WebSub options</legend>
<div class="form-row">
<label for="leaseSeconds">
lease_seconds
<input type="text" id="leaseSeconds" placeholder="optional">
</label>
<label for="secret">
secret
<input type="text" id="secret" placeholder="optional">
</label>
</div>
</fieldset>
<div class="actions">
<button type="button" id="subscribeButton">Subscribe</button>
<button type="button" id="unsubscribeButton" class="websub-only">Unsubscribe</button>
<button type="button" id="pingButton" class="rsscloud-only">Ping</button>
<button type="button" id="publishButton" class="websub-only">Publish</button>
</div>
</div>
<div id="actionError" class="action-error" role="alert" hidden></div>
<h2>Traffic Log</h2>
<p class="feed-url">Log stream: <code>${escapeHtml(wsUrl)}</code></p>
<script type="module">
import 'https://esm.sh/@andrewshell/socklog';
const viewer = document.getElementById('viewer');
const controls = document.getElementById('controls');
controls.store = viewer.getStore();
</script>
<div class="log-panel">
<socklog-controls id="controls"></socklog-controls>
<socklog-viewer id="viewer" url="${escapeHtml(wsUrl)}"></socklog-viewer>
</div>
<script type="module" src="/app.js"></script>
</body>
</html>`;
}
// Build the Express app. `fetch` is injected into the rssCloud/WebSub clients
// (defaults to the global fetch); `sessionStore` defaults to a fresh
// in-memory store (defaults let tests inject fakes without touching real
// process state).
function createApp({
fetch = createGuardedFetch({
allowCidrs: config.clientFetchAllowCidrs,
timeoutMs: config.requestTimeout
}),
sessionStore = createSessionStore(),
sessionCallbackIdleMs = config.sessionCallbackIdleMs
} = {}) {
const { attach, broadcast } = createSessionSockets({ sessionStore });
// Every outbound action broadcasts its request as it's about to fire;
// routing that broadcast through here keeps the session's idle clock
// (lastOutgoingAt) in sync with actual activity, so requireLiveSession
// doesn't treat a session mid-use as abandoned.
function broadcastOutgoingRequest(sessionId, entry) {
sessionStore.touchOutgoing(sessionId);
broadcast(sessionId, {
...entry,
direction: 'outgoing',
phase: 'request'
});
}
// UI/action routes create a session on demand.
function ensureSession(req, res, next) {
req.session = sessionStore.getOrCreate(req.params.sessionId);
next();
}
// Machine-to-machine callback/feed routes never create a session, and go
// dark (404) once it's idle past sessionCallbackIdleMs — a hub that never
// stops probing a long-abandoned subscription shouldn't get a response.
// A connected socklog socket overrides this (see session-store.js's
// isIdle) — a tab left open overnight watching an external feed is
// itself a sign of active use, not abandonment.
function requireLiveSession(req, res, next) {
if (sessionStore.isIdle(req.params.sessionId, sessionCallbackIdleMs)) {
res.status(404).send('Not found');
return;
}
next();
}
const app = express();
morgan.format('mydate', () => {
return new Date()
.toLocaleTimeString('en-US', {
hour12: false,
fractionalSecondDigits: 3
})
.replace(/:/g, ':');
});
app.use(
morgan(
'[:mydate] :method :url :status :res[content-length] - :remote-addr - :response-time ms'
)
);
// Handle static files in public directory
app.use(
express.static('public', {
dotfiles: 'ignore',
maxAge: '1d'
})
);
// Route: mint a session id and hand the browser off to it.
app.get('/', (req, res) => {
res.redirect(302, `/s/${crypto.randomUUID()}`);
});
const sessionRouter = express.Router({ mergeParams: true });
// Attach this request's session state, if it exists — never creates one
// (ensureSession does that for UI/action routes). May leave req.session
// undefined for a callback/feed route on an unknown id; requireLiveSession
// gates those routes before their handler or the logging middleware below
// ever reads it.
sessionRouter.use((req, res, next) => {
req.session = sessionStore.get(req.params.sessionId);
next();
});
// Request logging middleware - captures all incoming requests
sessionRouter.use((req, res, next) => {
res.on('finish', () => {
// No session (unknown/idle id on a callback route, already 404'd
// by requireLiveSession) — nothing to log against.
if (!req.session) {
return;
}
// Don't log client UI requests to keep log clean
if (req.path === '/' && req.method === 'GET') {
return;
}
// The browser's own action-trigger POSTs are outbound; the real
// hub-bound request/response they cause is already logged
// explicitly (with direction: 'outgoing') by the handler itself.
if (req.path.startsWith('/actions/')) {
return;
}
if (req.path.startsWith('/.well-known/')) {
return;
}
// Surface the WebSub delivery headers so the hub/self links and
// the signature (with our verdict) are visible in the log.
const headers = {};
if (req.headers.link) {
headers.Link = req.headers.link;
}
if (req.headers['x-hub-signature']) {
const topic = selfLink(req.headers.link);
headers['X-Hub-Signature'] =
`${req.headers['x-hub-signature']} (${checkSignature(
req.session,
topic,
req.headers['x-hub-signature'],
req.body
)})`;
}
broadcast(req.params.sessionId, {
id: crypto.randomUUID(),
direction: 'incoming',
timestamp: new Date().toISOString(),
method: req.method,
url: req.originalUrl,
headers: Object.keys(headers).length ? headers : null,
body: req.body || null
});
});
next();
});
// Route: Home page with UI
sessionRouter.get('/', ensureSession, (req, res) => {
const wsProtocol = req.protocol === 'https' ? 'wss' : 'ws';
const wsUrl = `${wsProtocol}://${req.get('host')}/s/${req.params.sessionId}/logs`;
res.type('html').send(renderPage(req.params.sessionId, wsUrl));
});
// Route: parse an arbitrary feed URL for rssCloud/WebSub support. Feeds
// this outbound fetch through the same SSRF-guarded fetch as every other
// action, since the URL is user-supplied.
sessionRouter.post('/actions/discover', ensureSession, jsonParser, async(req, res) => {
const sessionId = req.params.sessionId;
const { feedUrl } = req.body;
const logId = crypto.randomUUID();
broadcastOutgoingRequest(sessionId, {
id: logId,
timestamp: new Date().toISOString(),
method: 'GET',
url: feedUrl,
body: { action: 'discover', feedUrl }
});
try {
const result = await discoverFeed({ url: feedUrl, fetch });
broadcast(sessionId, {
id: logId,
direction: 'outgoing',
phase: 'response',
timestamp: new Date().toISOString(),
body: result
});
res.json(result);
} catch (error) {
const message = describeActionError(error);
broadcast(sessionId, {
id: logId,
direction: 'outgoing',
phase: 'response',
timestamp: new Date().toISOString(),
error: message
});
res.json({ rssCloud: null, webSub: null, error: message });
}
});
// Route: unified Subscribe action — branches by the selected protocol.
// `server` optionally overrides the target: for rssCloud this is the hub
// origin (pleaseNotify/RPC2 base); for WebSub it's the full hub front-door
// URL (path defaults to '' so it isn't double-appended).
sessionRouter.post('/actions/subscribe', ensureSession, jsonParser, async(req, res) => {
const sessionId = req.params.sessionId;
const { protocol, server: serverOverride, leaseSeconds, secret } =
req.body;
const feedUrl = resolveFeedUrl(sessionId, req.body);
const logId = crypto.randomUUID();
// `onSuccess`, when given, runs only once `call()` resolves without
// throwing — session state (e.g. the WebSub secret) must never be
// mutated on the strength of a request that might still fail.
async function logAndRespond(action, targetUrl, requestBody, call, onSuccess) {
broadcastOutgoingRequest(sessionId, {
id: logId,
timestamp: new Date().toISOString(),
method: 'POST',
url: targetUrl,
body: { action, ...requestBody }
});
try {
const result = await call();
onSuccess?.(result);
broadcast(sessionId, {
id: logId,
direction: 'outgoing',
phase: 'response',
timestamp: new Date().toISOString(),
...result
});
res.json(result);
} catch (error) {
// An egress-guard refusal carries an actionable hint (set
// CLIENT_FETCH_ALLOW_CIDRS) so the failure isn't mistaken for a
// success in both the traffic log and the browser banner.
const message = describeActionError(error);
broadcast(sessionId, {
id: logId,
direction: 'outgoing',
phase: 'response',
timestamp: new Date().toISOString(),
error: message
});
res.json({ error: message });
}
}
if (protocol === 'websub') {
const hub = createWebSubClient({
serverUrl: serverOverride || config.hubServerUrl,
path: serverOverride ? '' : undefined,
fetch
});
await logAndRespond(
'websub-subscribe',
serverOverride || hubUrl,
// Redact the secret in the logged/broadcast copy — it's still
// sent verbatim to the hub below, just never echoed into the
// traffic log or session.requestLog.
{ topicUrl: feedUrl, leaseSeconds, secret: secret ? '(redacted)' : undefined },
() => hub.subscribe({
callbackUrl: webSubCallbackUrl(sessionId),
topicUrl: feedUrl,
leaseSeconds,
secret
}),
() => {
if (secret) {
req.session.webSubSecrets[feedUrl] = secret;
} else {
delete req.session.webSubSecrets[feedUrl];
}
}
);
return;
}
const useXmlRpc = protocol === 'rsscloud-xml-rpc';
const rssCloudClient = createRssCloudClient({
serverUrl: serverOverride || config.hubServerUrl,
fetch
});
const subscribeParams = {
protocol: useXmlRpc ? 'xml-rpc' : 'http-post',
callback: {
domain: config.domain,
port: config.port,
path: useXmlRpc
? `/s/${sessionId}/RPC2`
: `/s/${sessionId}/notify`
},
feedUrl
};
await logAndRespond(
'pleaseNotify',
serverOverride || config.hubServerUrl,
subscribeParams,
() => rssCloudClient.pleaseNotify(subscribeParams)
);
});
// Route: unified Unsubscribe action (WebSub only).
sessionRouter.post('/actions/unsubscribe', ensureSession, jsonParser, async(req, res) => {
const sessionId = req.params.sessionId;
const { server: serverOverride } = req.body;
const feedUrl = resolveFeedUrl(sessionId, req.body);
const logId = crypto.randomUUID();
const hub = createWebSubClient({
serverUrl: serverOverride || config.hubServerUrl,
path: serverOverride ? '' : undefined,
fetch
});
broadcastOutgoingRequest(sessionId, {
id: logId,
timestamp: new Date().toISOString(),
method: 'POST',
url: serverOverride || hubUrl,
body: { action: 'websub-unsubscribe', topicUrl: feedUrl }
});
try {
const result = await hub.unsubscribe({
callbackUrl: webSubCallbackUrl(sessionId),
topicUrl: feedUrl
});
// Only drop the stored secret once the hub has actually
// acknowledged the unsubscribe — a failed call shouldn't lose it.
delete req.session.webSubSecrets[feedUrl];
broadcast(sessionId, {
id: logId,
direction: 'outgoing',
phase: 'response',
timestamp: new Date().toISOString(),
...result
});
res.json(result);
} catch (error) {
const message = describeActionError(error);
broadcast(sessionId, {
id: logId,
direction: 'outgoing',
phase: 'response',
timestamp: new Date().toISOString(),
error: message
});
res.json({ error: message });
}
});
// Route: unified Publish action (WebSub only). Deliberately accepts only
// `feedName` — see the comment on /actions/ping for why.
sessionRouter.post('/actions/publish', ensureSession, jsonParser, async(req, res) => {
const sessionId = req.params.sessionId;
const { feedName = 'rss-01.xml', server: serverOverride } = req.body;
const feedUrl = `http://${config.domain}:${config.port}/s/${sessionId}/${feedName}`;
const logId = crypto.randomUUID();
if (!req.session.feedItems[feedName]) {
req.session.feedItems[feedName] = [
{ title: 'initialized', timestamp: new Date() }
];
}
const now = new Date();
req.session.feedItems[feedName].unshift({
title: `Update at ${now.toISOString()}`,
timestamp: now
});
const hub = createWebSubClient({
serverUrl: serverOverride || config.hubServerUrl,
path: serverOverride ? '' : undefined,
fetch
});
broadcastOutgoingRequest(sessionId, {
id: logId,
timestamp: new Date().toISOString(),
method: 'POST',
url: serverOverride || hubUrl,
body: { action: 'websub-publish', topicUrl: feedUrl }
});
try {
const result = await hub.publish({ topicUrl: feedUrl });
broadcast(sessionId, {
id: logId,
direction: 'outgoing',
phase: 'response',
timestamp: new Date().toISOString(),
...result
});
res.json(result);
} catch (error) {
const message = describeActionError(error);
broadcast(sessionId, {
id: logId,
direction: 'outgoing',
phase: 'response',
timestamp: new Date().toISOString(),
error: message
});
res.json({ error: message });
}
});
// Route: unified Ping action. Deliberately accepts only `feedName` (never
// an arbitrary feedUrl) — this session can only ever ping/publish a feed
// it itself serves, never someone else's; that's the actual enforcement
// point for "don't ping/publish someone else's feed" (the UI hiding
// these controls in subscriber mode is a client-side mirror of this).
sessionRouter.post('/actions/ping', ensureSession, jsonParser, async(req, res) => {
const sessionId = req.params.sessionId;
const { protocol, feedName = 'rss-01.xml', server: serverOverride } =
req.body;
const feedUrl = `http://${config.domain}:${config.port}/s/${sessionId}/${feedName}`;
const logId = crypto.randomUUID();
if (!req.session.feedItems[feedName]) {
req.session.feedItems[feedName] = [
{ title: 'initialized', timestamp: new Date() }
];
}
const now = new Date();
req.session.feedItems[feedName].unshift({
title: `Update at ${now.toISOString()}`,
timestamp: now
});
const rssCloudClient = createRssCloudClient({
serverUrl: serverOverride || config.hubServerUrl,
fetch
});
const pingParams = {
feedUrl,
transport: protocol === 'rsscloud-xml-rpc' ? 'xml-rpc' : 'rest'
};
broadcastOutgoingRequest(sessionId, {
id: logId,
timestamp: new Date().toISOString(),
method: 'POST',
url: serverOverride || config.hubServerUrl,
body: { action: 'ping', ...pingParams }
});
try {
const result = await rssCloudClient.ping(pingParams);
broadcast(sessionId, {
id: logId,
direction: 'outgoing',
phase: 'response',
timestamp: new Date().toISOString(),
...result
});
res.json(result);
} catch (error) {
const message = describeActionError(error);
broadcast(sessionId, {
id: logId,
direction: 'outgoing',
phase: 'response',
timestamp: new Date().toISOString(),
error: message
});
res.json({ error: message });
}
});
// Route: WebSub intent verification — the hub GETs the callback with a
// hub.challenge the subscriber must echo verbatim to confirm the subscription.
sessionRouter.get('/websub-callback', requireLiveSession, (req, res) => {
const verification = readVerification(req.query);
if (verification) {
res.send(verification.challenge);
return;
}
res.status(404).send('Not a WebSub verification');
});
// Route: WebSub content distribution — the hub POSTs the full feed body
// here. The request-logging middleware records the body, the hub/self
// Link header, and the signature verdict; we just acknowledge with a 2xx.
sessionRouter.post('/websub-callback', requireLiveSession, rawTextParser, (req, res) => {
res.status(204).end();
});
// Route: Handle challenge verification for http-post subscriptions
sessionRouter.get('/notify', requireLiveSession, (req, res) => {
const challenge = req.query.challenge || '';
res.send(challenge);
});
// Route: Handle HTTP-POST notifications
sessionRouter.post('/notify', requireLiveSession, urlencodedParser, (req, res) => {
// Body is already logged by middleware
res.send('');
});
// Route: Handle XML-RPC notifications
sessionRouter.post('/RPC2', requireLiveSession, textParser, (req, res) => {
// Body is already logged by middleware; acknowledge with the boolean reply.
res.type('text/xml').send(buildNotifyResponse());
});
// Route: Serve RSS feeds (must be after specific routes)
sessionRouter.get('/:feedName', requireLiveSession, (req, res) => {
const sessionId = req.params.sessionId;
const feedName = req.params.feedName;
// Only serve .xml files as RSS feeds
if (!feedName.endsWith('.xml')) {
res.status(404).send('Not found');
return;
}
const items = req.session.feedItems[feedName] || [
{ title: 'initialized', timestamp: new Date() }
];
const feedUrl = `http://${config.domain}:${config.port}/s/${sessionId}/${feedName}`;
const rssXml = renderCloudFeed({
title: `Test Feed: ${feedName}`,
link: feedUrl,
description: 'Test feed for rssCloud',
cloud: {
domain: hubOrigin.hostname,
port: hubPort,
path: '/RPC2',
registerProcedure: 'rssCloud.pleaseNotify',
protocol: 'xml-rpc'
},
hub: hubUrl,
items: items.map((item, index) => ({
title: item.title,
description: `Feed item: ${item.title}`,
pubDate: item.timestamp,
guid: `${feedName}-${index}`
}))
});
res.type('application/rss+xml').send(rssXml);
});
app.use('/s/:sessionId', sessionRouter);
app.locals.attachSessionSockets = attach;
return app;
}
module.exports = { createApp };