-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.ts
284 lines (227 loc) · 7.99 KB
/
server.ts
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
import axios from 'axios';
import Koa from 'koa';
import KoaPinoLogger from 'koa-pino-logger';
import KoaRouter from 'koa-router';
import KoaStatic from 'koa-static';
import KoaViews from '@ladjs/koa-views';
import * as path from 'path';
import Pino from 'pino';
import { linkBuilder } from './linkbuilder';
import * as sites from './sites';
import { sitemap } from './sitemap';
import * as templates from './templates';
import * as util from './util';
import * as comparison from './comparison';
type KoaContext = Koa.ParameterizedContext<any, KoaRouter.IRouterParamContext<any, {}>>;
const app = new Koa();
app.proxy = true;
const logger = Pino();
app.use(KoaPinoLogger({ logger: logger }));
app.use( async (ctx, next) => {
ctx.res.setHeader("Referrer-Policy", "unsafe-url");
if (ctx.hostname != 'localhost') {
ctx.res.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
}
ctx.res.setHeader("X-Content-Type-Options", "nosniff");
ctx.res.setHeader("X-Frame-Options", "SAMEORIGIN");
ctx.res.setHeader("X-XSS-Protection", "1; mode=block");
/*
* I already have the max free domains at report-uri
ctx.res.setHeader('Report-To', '{ "group": "default", "max_age": 31536000, "endpoints": [{ "url": "https://fileformat.report-uri.com/a/d/g" }], "include_subdomains": true }');
ctx.res.setHeader('NEL', '{ "report_to": "default", "max_age": 31536000, "include_subdomains": true }');
*/
await next();
});
app.use( async (ctx, next) => {
try {
await next();
const status = ctx.status || 404;
if (status === 404) {
ctx.log.warn( { url: ctx.request.url }, 'File not found');
await ctx.render('404.hbs', { title: 'File not found (404)', url: ctx.request.url });
}
} catch (err) {
ctx.log.error( { err, url: ctx.request.url }, 'Server Error');
await ctx.render('500.hbs', { title: 'Server Error', message: err.message });
}
});
app.use(KoaStatic("public", { maxage: 24 * 60 * 60 * 1000 }));
app.use(KoaViews(path.join(__dirname, '..', 'views'), {
map: { hbs: 'handlebars' },
options: {
helpers: {
'encodeURIComponent': function (a: any) {
return encodeURIComponent(a)
},
'ischecked': function(value:string, checks:string[]) {
return checks && checks.indexOf(value) != -1;
}
},
partials: {
above: path.join(__dirname, '..', 'partials', 'above'),
below: path.join(__dirname, '..', 'partials', 'below')
}
}
}));
const rootRouter = new KoaRouter();
rootRouter.get('/', async (ctx) => {
await ctx.render('index.hbs', {
shareUrl: "https://simpleshare.dev/",
shareText: "Simple script-less share buttons",
shareSummary: "The most awesome-est way to share!!!",
sites: sites.getAll(),
title: 'SimpleShare - simple script-less social sharing',
hideh2: true
});
});
rootRouter.get('/contact.html', async (ctx) => {
await ctx.render('contact.hbs', {
title: 'Contact',
});
});
rootRouter.get('/index.html', async (ctx) => {
await ctx.redirect('/');
});
rootRouter.get("/linkbuilder.html", linkBuilder);
rootRouter.get('/sitemap.xml', sitemap);
rootRouter.get('/status.json', async (ctx) => {
const retVal: {[key:string]: any } = {};
retVal["success"] = true;
retVal["message"] = "OK";
retVal["timestamp"] = new Date().toISOString();
retVal["lastmod"] = process.env.LASTMOD || null;
retVal["commit"] = process.env.COMMIT || null;
retVal["tech"] = "NodeJS " + process.version;
retVal["targetcount"] = sites.getAll().length;
sendJSON(ctx, retVal);
});
function sendJSON(ctx: KoaContext, data: object) {
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Methods', 'POST, GET');
ctx.set('Access-Control-Max-Age', '604800');
const callback = util.getFirst(ctx.request.query['callback']);
if (callback && callback.match(/^[$A-Za-z_][0-9A-Za-z_$]*$/) != null) {
ctx.type = 'text/javascript';
ctx.body = callback + '(' + JSON.stringify(data) + ');';
} else {
ctx.type = 'application/json';
ctx.body = JSON.stringify(data);
}
}
function getVariables(ctx: KoaContext) {
const result:{[key:string]: any} = {};
if ('url' in ctx.request.query == false) {
result["success"] = false;
result["code"] = 400;
result["message"] = "Parameter 'url' is required";
sendJSON(ctx, result);
return null;
}
const targetUrl = util.getFirst(ctx.request.query["url"]) || '';
// LATER: split off just filename?
const text = util.getFirst(ctx.request.query["text"]) || targetUrl;
const summary = util.getFirst(ctx.request.query["summary"]) || '';
const image = util.getFirst(ctx.request.query["image"]) || '';
result["URL"] = encodeURIComponent(targetUrl);
result["TEXT"] = encodeURIComponent(text);
result["SUMMARY"] = encodeURIComponent(summary);
result["IMAGE"] = encodeURIComponent(image);
return result;
}
function getSite(ctx: KoaContext):sites.SiteData|null {
const targetSite = util.getFirst(ctx.request.query["site"]);
if (!targetSite) {
sendJSON(ctx, {
success: false,
code: 400,
message: "Parameter 'site' is required"
});
return null;
}
const site = sites.get(targetSite);
if (site == null) {
sendJSON(ctx, {
success: false,
code: 404,
message: `Site '${ctx.request.query["site"]}' is not supported yet`
});
return null;
}
return site;
}
function guid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
const v = (c == 'x') ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function trackEvent(ctx: KoaContext, ga_id:string | undefined, event:trackingEvent) {
if (!ga_id) {
return;
}
const formData:{[key:string]:string} = {};
formData.v = '1';
formData.tid = ga_id;
formData.cid = guid(); // anonymous client id
formData.t = 'event';
if (event.eventCategory) {
formData.ec = event.eventCategory;
}
if (event.eventAction) {
formData.ea = event.eventAction;
}
if (event.eventLabel) {
formData.el = event.eventLabel.substr(0, 500);
}
if (event.eventValue) {
formData.ev = event.eventValue;
}
formData.ua = ctx.request.get('user-agent') || '(not set)';
formData.uip = ctx.ip || '0.0.0.0';
axios.post("https://www.google-analytics.com/collect", {
form: formData
});
}
type trackingEvent = {
eventCategory?: string,
eventAction?: string,
eventLabel?: string,
eventValue?: string
}
rootRouter.get('/go', function (ctx) {
const site = getSite(ctx);
if (site == null) {
return;
}
const vars = getVariables(ctx);
if (vars == null) {
return;
}
logger.info( { site: site, data: vars }, 'Redirecting');
const loc = site.templateFn(vars);
ctx.set('Referrer-Policy', 'unsafe-url');
ctx.redirect(loc);
const event:trackingEvent = {
eventCategory: 'SHARE',
eventAction: util.getFirst(ctx.request.query["site"]),
eventLabel: util.getFirst(ctx.request.query["url"])
};
//webmaster's tracking
trackEvent(ctx, util.getFirst(ctx.request.query['ga']), event);
//simpleshare tracking
trackEvent(ctx, process.env.GA_ID, event);
});
app.use(rootRouter.routes());
async function main() {
await Promise.all([
sites.initialize(logger),
templates.initialize(logger),
comparison.initialize(logger)
]);
app.use(comparison.comparisonRouter.routes());
const listener = app.listen(process.env.PORT || "4000", function () {
logger.info( { address: listener.address(), ga_id: process.env.GA_ID || '(not set)' }, 'Running');
});
}
main();