aboutsummaryrefslogtreecommitdiffstats
path: root/server/main.ts
blob: 7cb21a0d10d5629a6300cc37cfca847e03378319 (plain)
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
import { URL, URLSearchParams } from "url";
import express from "express";
import cors from "cors";
import fetch from "node-fetch";
import cookieParser from "cookie-parser";
import * as cheerio from "cheerio";

import { wrap } from "./async";

const PORT = process.env.PORT ? +process.env.PORT : 3000;
const DISCDAG_URL = process.env.DISCDAG_URL ?? 'http://solipsys.co.uk/cgi-bin/DiscDAG.py';
const PUBLIC_URL = process.env.PUBLIC_URL ?? 'http://localhost:3000';
const DEBUG = process.env.NODE_ENV ? process.env.NODE_ENV !== 'production' : PUBLIC_URL.indexOf('localhost') > -1;

const app = express();

if (DEBUG) {
  app.use(cors({ origin: true, credentials: true }));
  app.use(express.static('../client/dist/'));
} else {
  app.use(express.static('static'));
}
app.use(express.json());
app.use(cookieParser());

type LinkOr<T> = string | T;

type Person = {
  id: string;
  type: 'Person',
  name: string;
};

type Note = {
  type: 'Note';
  published: string;
  attributedTo: LinkOr<Person>;
  inReplyTo: string[];
  replies: string[];
  content: string;
};

type Relationship<S, O> = {
  type: 'Relationship';
  relationship: string;
  subject: S;
  object: O;
};

type Create<O> = {
  type: 'Create';
  actor: LinkOr<Person>;
  object: O;
};

type Delete<O> = {
  type: 'Create';
  actor: LinkOr<Person>;
  object: O;
};

const iri2id = (iri: string) => {
  const parts = iri.split('/');
  return parts[parts.length - 1];
};

const discdag = express()
  .post('/login', wrap(async ($req, $res) => {
    const { username, password } = $req.body;
    if (!username || !password)
      throw new Error("no credentials");

    const res = await fetch(DISCDAG_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams({
        Action: 'Login',
        Username: username,
        Password: password,
      }).toString(),
    });

    if (res.status !== 200)
      throw new Error("bad response");

    const cookiestr = res.headers.get('set-cookie') ?? '';
    const match = cookiestr.match(/digest=([^ ]+);/);
    if (!match || !match[1].length) throw new Error("wrong credentials");

    const doc = cheerio.load(await res.text());
    const name = doc("font b").text().match(/browsing as (.*)$/)![1];
    const user = `${PUBLIC_URL}/discdag/user/${name}`;

    return $res
      .cookie('digest', match[1])
      .json({
        '@context': 'https://www.w3.org/ns/activitystreams',
        id: user,
        type: 'User',
        name,
      });
  }))

  .post('/logout', wrap(async ($req, $res) => $res.cookie('digest', '').json({})))

  .get('/list', wrap(async ($req, $res) => {
    const { digest } = $req.cookies;

    const res = await fetch(DISCDAG_URL + '?Action=ListDiscussions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cookie': `digest=${digest}`,
      },
    });

    const doc = cheerio.load(await res.text());
    const name = doc("font b").text().match(/browsing as (.*)$/)![1];
    const user = `${PUBLIC_URL}/discdag/user/${name}`;

    const discussions = doc("ul > li").map(function(this: any) {
      const writeAccess = this.children[0].data.indexOf('(W)') > -1;
      const href = doc("a", this).attr("href")!;
      const id = href.match(/cgi-bin\/DiscDAG.py\?DiscussionID=(.+)/)![1];

      return {
        id: `${PUBLIC_URL}/discdag/disc/${id}`,
        type: 'Document',
        name: id,
        url: {
          type: 'Link',
          href,
        },
        attributedTo: writeAccess ? user : null,
        audience: user,
      };
    }).toArray();
    
    return $res.json({
      discussions,
      user: {
        id: user,
        type: 'User',
        name,
      },
    });
  }))

  .get('/user/:name', wrap(async ($req, $res) => {
    const { name } = $req.params;

    return $res.json({
      '@context': 'https://www.w3.org/ns/activitystreams',
      id: `${PUBLIC_URL}/discdag/user/${name}`,
      type: 'User',
      name,
    });
  }))

  .get('/disc/:discussion', wrap(async ($req, $res) => {
    const { discussion } = $req.params;
    const { digest } = $req.cookies;

    const res = await fetch(DISCDAG_URL, {
      headers: {
        'Cookie': `DiscussionID=${discussion}; digest=${digest}`,
      }
    });

    if (res.status !== 200)
      throw new Error("bad response");

    const doc = cheerio.load(await res.text());

    if (doc.text().indexOf("Invalid discussion ID:") > -1)
      return $res.status(404).end();

    let first = null;
    const items: Record<string, Note> = {};
    for (const node of doc('g.node', 'svg')) {
      const nodeId = doc('title', node).text();
      const [_, time, author] = nodeId.split('_');

      const id = `${PUBLIC_URL}/discdag/disc/${discussion}/${nodeId}`;
      first = first ?? id;

      const content = doc('g:first text', node)
        .slice(3)
        .map(function(this: any) { return doc(this).text(); })
        .toArray()
        .join(' ').trim();

      items[id] = {
        type: 'Note',
        published: time.replace(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)[a-z]*/, '$1-$2-$3T$4:$5:$6Z'),
        attributedTo: `${PUBLIC_URL}/discdag/user/${author}`,
        inReplyTo: [],
        replies: [],
        content,
      };
    }

    for (const node of doc('g.edge', 'svg')) {
      let [frm, to] = doc('title', node).text().split('->');
      frm = `${PUBLIC_URL}/discdag/disc/${discussion}/${frm}`;
      to = `${PUBLIC_URL}/discdag/disc/${discussion}/${to}`;

      items[frm].replies.push(to);
      items[to].inReplyTo.push(frm);
    }
    
    return $res.json({
      '@context': [
        'https://www.w3.org/ns/activitystreams',
        {
          items: {
            '@id': 'as:items',
            '@container': '@id'
          },
        },
      ],
      id: `${PUBLIC_URL}/discdag/disc/${discussion}`,
      type: 'Document',
      name: discussion,
      first,
      items,
    });
  }))

  .post('/disc/:discussion', wrap(async ($req, $res) => {
    const { discussion } = $req.params;
    const { digest } = $req.cookies;

    if (!digest || !digest.length)
      return $res.status(401).end();

    type Activity =
      | Create<Note>
      | Create<Relationship<string, string>>
      | Delete<Relationship<string, string>>
    ;
    const activity = $req.body as Activity;

    let selection: string[];
    let body: string;
    let method = 'GET';
    if (activity.type === 'Create' && activity.object?.type === 'Note') {
      method = 'POST';
      selection = activity.object.inReplyTo.map(iri2id);
      body = new URLSearchParams({ Action: 'SendReply', ReplyText: activity.object.content }).toString();
    } else if (activity.object?.type === 'Relationship' && activity.object.relationship === 'as:inReplyTo') {
      const frm = iri2id(activity.object.object);
      const to = iri2id(activity.object.subject);
      selection = [frm, to];
      body = new URLSearchParams({
        Action: activity.type === 'Create' ? 'CreateLink' : 'RemoveLink',
        N0: frm,
        N1: to,
      }).toString();
    } else {
      return $res.status(501).end();
    }

    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Cookie': `DiscussionID=${discussion}; digest=${digest}; SelectedNodes=${selection.join(',')}`,
    };

    let res;
    if (method === 'POST') {
      res = await fetch(DISCDAG_URL, { method, headers, body });
    } else {
      res = await fetch(DISCDAG_URL + `?${body}`, { method, headers });
    }

    if (res.status !== 200)
      throw new Error("bad response");

    const doc = cheerio.load(await res.text());

    if (doc.text().indexOf("Invalid discussion ID:") > -1)
      return $res.status(404).end();

    if (doc.text().indexOf("Replying only available if you have write access:") > -1)
      return $res.status(403).end();

    const items: Record<string, Note> = {};
    for (const node of doc('g.node polygon[stroke-width=5]', 'svg').parent()) {
      const nodeId = doc('title', node).text();
      const [_, time, author] = nodeId.split('_');

      const id = `${PUBLIC_URL}/discdag/disc/${discussion}/${nodeId}`;

      const content = doc('g:first text', node)
        .slice(3)
        .map(function(this: any) { return doc(this).text(); })
        .toArray()
        .join(' ').trim();

      items[id] = {
        type: 'Note',
        published: time.replace(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)[a-z]*/, '$1-$2-$3T$4:$5:$6Z'),
        attributedTo: `${PUBLIC_URL}/discdag/user/${author}`,
        inReplyTo: [],
        replies: [],
        content,
      };
    }

    for (const node of doc('g.edge', 'svg')) {
      let [frm, to] = doc('title', node).text().split('->');
      if (frm === 'SELECTED' || to === 'SELECTED') continue;
      frm = `${PUBLIC_URL}/discdag/disc/${discussion}/${frm}`;
      to = `${PUBLIC_URL}/discdag/disc/${discussion}/${to}`;

      items[frm]?.replies.push(to);
      items[to]?.inReplyTo.push(frm);
    }

    return $res.json({
      '@context': [
        'https://www.w3.org/ns/activitystreams',
        {
          items: {
            '@id': 'as:items',
            '@container': '@id'
          },
        },
      ],
      items,
    });
  }))
;

app.use('/discdag', discdag);

app.get(/\/remote\/.*/, wrap(async ($req, $res) => {
  const { origin, referer } = $req.headers;
  const url = $req.url.match('^/remote/(.*)')![1];

  if (!DEBUG) {
    const org = origin ?? new URL(referer!).origin;
    if (org !== PUBLIC_URL) return $res.status(403).end();
  }

  const res = await fetch(url, {
    headers: {
      'Accept': 'application/ld+json, application/json',
      'X-Forwarded-For': $req.ip,
    },
  });

  $res.status(res.status);
  for (const key of [
    'Content-Type',
    'Content-Size',
    'Location',
    'Age',
    'Cache-Control',
    'Expires',
    'Etag',
  ]) {
    const val = res.headers.get(key);
    if (val) $res.setHeader(key, val);
  }

  res.body.pipe($res);

  return $res;
}));

try {
  app.listen(PORT, (): void => {
    console.log(`Connected successfully on port ${PORT}`);
  });
} catch (error) {
  console.error(`Error occured: ${error}`);
}