-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
server.ts
134 lines (129 loc) · 5.62 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
import { IncomingMessage, ServerResponse } from 'http';
import { parse } from 'url';
import { mimeType, cacheControl } from './util/backend/lookup';
import { renderPage } from './pages/_document';
import { pages, versionUnknown } from './util/constants';
import { getPkgDetails } from './page-props/common';
import { getApiResponseSize, getBadgeSvg } from './util/badge';
import { parsePackageString } from './util/npm-parser';
import semver from 'semver';
import { fetchManifest } from './util/npm-api';
import { NotFoundError } from './util/not-found-error';
import type { ApiResponseV1, ApiResponseV2, PackageJson } from './types';
const { TMPDIR = '/tmp', GA_ID = '', NODE_ENV } = process.env;
process.env.HOME = TMPDIR;
delete process.env.AWS_ACCESS_KEY_ID;
delete process.env.AWS_SECRET_KEY;
delete process.env.AWS_SECRET_ACCESS_KEY;
delete process.env.AWS_SESSION_TOKEN;
const isProd = NODE_ENV === 'production';
console.log('NODE_ENV: ' + NODE_ENV);
console.log('isProd: ', isProd);
console.log('TMPDIR: ', TMPDIR);
console.log('HOME: ', process.env.HOME);
console.log('AWS_SECRET_ACCESS_KEY: ', process.env.AWS_SECRET_ACCESS_KEY);
let botCount = 0;
export async function handler(req: IncomingMessage, res: ServerResponse) {
let { method, url, headers } = req;
const userAgent = headers['user-agent'] || '';
console.log(`${method} ${headers.host}${url}`);
console.log(`user-agent: ${userAgent}`);
if (
!userAgent ||
userAgent.startsWith('node') ||
userAgent.startsWith('axios') ||
userAgent.startsWith('got')
) {
botCount++;
if (botCount % 2 === 0) {
res.statusCode = 429;
res.end(
'Too many requests from unknown user-agent. See https://github.com/styfle/packagephobia/blob/main/API.md',
);
return;
}
}
let { pathname = '/', query = {} } = parse(url || '', true);
if (!pathname || pathname === '/') {
pathname = pages.index;
}
const force = query.force === '1';
try {
if (pathname === pages.badge) {
const parsed = parsePackageString(query.p as string);
let manifest;
try {
manifest = await fetchManifest(parsed.name);
} catch (err) {
if (err instanceof NotFoundError) manifest = null;
else throw err;
}
const { pkgSize, cacheResult } = await getPkgDetails(
manifest,
parsed.name,
parsed.version,
force,
TMPDIR,
);
res.setHeader('Content-Type', mimeType('*.svg'));
res.setHeader('Cache-Control', cacheControl(isProd, cacheResult ? 31 : 0));
res.end(getBadgeSvg(pkgSize));
} else if (pathname === pages.apiv1 || pathname === pages.apiv2) {
const parsed = parsePackageString(query.p as string);
const manifest = await fetchManifest(parsed.name);
const { pkgSize, cacheResult } = await getPkgDetails(
manifest,
parsed.name,
parsed.version,
force,
TMPDIR,
);
const { publishSize, installSize, name, version, publishFiles, installFiles } = pkgSize;
let result: ApiResponseV1 | ApiResponseV2;
if (pathname === pages.apiv1) {
result = { publishSize, installSize };
} else {
const publish = getApiResponseSize(publishSize, publishFiles);
const install = getApiResponseSize(installSize, installFiles);
result = { name, version, publish, install };
}
res.statusCode = version === versionUnknown ? 404 : 200;
res.setHeader('Content-Type', mimeType(pathname));
res.setHeader('Cache-Control', cacheControl(isProd, cacheResult ? 31 : 0));
res.end(JSON.stringify(result));
} else if (pathname === pages.scanResults) {
let data: Buffer[] = [];
req.on('data', chunk => data.push(chunk));
req.on('end', () => {
try {
const [packageString = '{}'] = data.toString().match(/{[\s\S]+}/) || [];
const packageData: PackageJson = JSON.parse(packageString);
const queryString = Object.entries(packageData.dependencies)
.map(([name, version]) => {
const exactVersion = semver.coerce(version);
return exactVersion ? `${name}@${exactVersion}` : name;
})
.join(',');
res.writeHead(307, { Location: `/result?p=${queryString}` });
return res.end();
} catch (e) {
res.setHeader('Content-Type', mimeType('*.html'));
return renderPage(res, pages.parseFailure, query, TMPDIR, GA_ID);
}
});
} else {
const isIndex = pathname === pages.index;
const hasVersion =
typeof query.p === 'string' && parsePackageString(query.p).version !== null;
res.setHeader('Content-Type', mimeType('*.html'));
res.setHeader('Cache-Control', cacheControl(isProd, isIndex || hasVersion ? 31 : 0));
renderPage(res, pathname, query, TMPDIR, GA_ID);
}
} catch (e) {
console.error(e);
res.setHeader('Content-Type', mimeType('500.txt'));
res.setHeader('Cache-Control', cacheControl(isProd, 0));
res.statusCode = 500;
res.end('500 Internal Error');
}
}