Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added error templates #25

Merged
merged 3 commits into from
Jun 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ node_modules
yarn-error.log
package-lock.json
src/directory.js
src/error.js
.nyc_output
coverage
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"license": "MIT",
"files": [
"src/index.js",
"src/directory.js"
"src/directory.js",
"src/error.js"
],
"devDependencies": {
"@zeit/eslint-config-node": "0.2.13",
Expand All @@ -48,10 +49,12 @@
"nyc": {
"exclude": [
"src/directory.js",
"src/error.js",
"test/*"
]
},
"eslintIgnore": [
"error.js",
"directory.js",
"coverage"
],
Expand Down
119 changes: 119 additions & 0 deletions src/error.jst
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<!DOCTYPE html>

<head>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>

<style>
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
flex-direction: column;
}

main,
aside,
section {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}

main {
height: 100%;
}

aside {
background: #000;
flex-shrink: 1;
padding: 30px 20px;
}

aside p {
margin: 0;
color: #999999;
font-size: 14px;
line-height: 24px;
}

aside a {
color: #fff;
text-decoration: none;
}

section span {
font-size: 24px;
font-weight: 500;
display: block;
border-bottom: 1px solid #EAEAEA;
text-align: center;
padding-bottom: 20px;
width: 100px;
}

section p {
font-size: 14px;
font-weight: 400;
}

section span + p {
margin: 20px 0 0 0;
}

@media (min-width: 768px) {
section {
height: 40px;
flex-direction: row;
}

section span,
section p {
height: 100%;
line-height: 40px;
}

section span {
border-bottom: 0;
border-right: 1px solid #EAEAEA;
padding: 0 20px 0 0;
width: auto;
}

section span + p {
margin: 0;
padding-left: 20px;
}

aside {
padding: 50px 0;
}

aside p {
max-width: 520px;
text-align: center;
}
}
</style>
</head>

<body>
<main>
<section>
<span>{{=it.statusCode}}</span>
<p>{{=it.message}}</p>
</section>
</main>
</body>
171 changes: 91 additions & 80 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ const contentDisposition = require('content-disposition');
const isPathInside = require('path-is-inside');

// Other
const template = require('./directory');
const directoryTemplate = require('./directory');
const errorTemplate = require('./error');

const getHandlers = methods => Object.assign({
stat: promisify(stat),
Expand Down Expand Up @@ -416,26 +417,95 @@ const renderDirectory = async (current, acceptsJSON, handlers, methods, config,
paths: subPaths
};

const output = acceptsJSON ? JSON.stringify(spec) : template(spec);
const output = acceptsJSON ? JSON.stringify(spec) : directoryTemplate(spec);

return {directory: output};
};

const sendError = async (response, acceptsJSON, current, handlers, config, spec) => {
const {err: original, message, code, statusCode} = spec;

if (original) {
console.error(original);
}

response.statusCode = statusCode;

if (acceptsJSON) {
response.setHeader('Content-Type', 'application/json; charset=utf-8');

response.end(JSON.stringify({
error: {
code,
message
}
}));

return;
}

let stats = null;

const errorPage = path.join(current, `${statusCode}.html`);

try {
stats = await handlers.stat(errorPage);
} catch (err) {
if (err.code !== 'ENOENT') {
// eslint-disable-next-line no-use-before-define
return internalError(response, acceptsJSON, current, handlers, config, err);
}
}

if (stats) {
const headers = await getHeaders(config.headers, current, errorPage, stats);
const stream = await handlers.createReadStream(errorPage);

response.writeHead(statusCode, headers);
stream.pipe(response);

return;
}

response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.end(errorTemplate({statusCode, message}));
};

const internalError = async (...args) => {
const lastIndex = args.length - 1;
const err = args[lastIndex];

args[lastIndex] = {
statusCode: 500,
code: 'internal_server_error',
message: 'A server error has occurred',
err
};

return sendError(...args);
};

module.exports = async (request, response, config = {}, methods = {}) => {
const cwd = process.cwd();
const current = config.public ? path.join(cwd, config.public) : cwd;
const handlers = getHandlers(methods);
const relativePath = decodeURIComponent(url.parse(request.url).pathname);

let absolutePath = path.join(current, relativePath);
let acceptsJSON = null;

if (request.headers.accept) {
acceptsJSON = request.headers.accept.includes('application/json');
}

// Prevent path traversal vulnerabilities. We could do this
// by ourselves, but using the package covers all the edge cases.
if (!isPathInside(absolutePath, current)) {
response.statusCode = 400;
response.end('Bad Request');

return;
return sendError(response, acceptsJSON, current, handlers, config, {
statusCode: 400,
code: 'bad_request',
message: 'Bad Request'
});
}

const cleanUrl = applicable(relativePath, config.cleanUrls);
Expand Down Expand Up @@ -469,12 +539,7 @@ module.exports = async (request, response, config = {}, methods = {}) => {
stats = await handlers.stat(absolutePath);
} catch (err) {
if (err.code !== 'ENOENT') {
console.error(err);

response.statusCode = 500;
response.end(err.message);

return;
return internalError(response, acceptsJSON, current, handlers, config, err);
}
}
}
Expand All @@ -490,12 +555,7 @@ module.exports = async (request, response, config = {}, methods = {}) => {
}
} catch (err) {
if (err.code !== 'ENOENT') {
console.error(err);

response.statusCode = 500;
response.end(err.message);

return;
return internalError(response, acceptsJSON, current, handlers, config, err);
}
}
}
Expand All @@ -505,26 +565,11 @@ module.exports = async (request, response, config = {}, methods = {}) => {
stats = await handlers.stat(absolutePath);
} catch (err) {
if (err.code !== 'ENOENT') {
console.error(err);

response.statusCode = 500;
response.end(err.message);

return;
return internalError(response, acceptsJSON, current, handlers, config, err);
}
}
}

let acceptsJSON = null;

if (request.headers.accept) {
acceptsJSON = request.headers.accept.includes('application/json');
}

if (((stats && stats.isDirectory()) || !stats) && acceptsJSON) {
response.setHeader('Content-Type', 'application/json; charset=utf-8');
}

if (stats && stats.isDirectory()) {
let directory = null;
let singleFile = null;
Expand All @@ -541,23 +586,18 @@ module.exports = async (request, response, config = {}, methods = {}) => {
({directory} = related);
}
} catch (err) {
console.error(err);

response.statusCode = 500;
response.end(err.message);

return;
if (err.code !== 'ENOENT') {
return internalError(response, acceptsJSON, current, handlers, config, err);
}
}

if (directory) {
response.statusCode = 200;

// When JSON is accepted, we already set the header before
if (!response.getHeader('Content-Type')) {
response.setHeader('Content-Type', 'text/html; charset=utf-8');
}
const contentType = acceptsJSON ? 'application/json; charset=utf-8' : 'text/html; charset=utf-8';

response.statusCode = 200;
response.setHeader('Content-Type', contentType);
response.end(directory);

return;
}

Expand All @@ -569,40 +609,11 @@ module.exports = async (request, response, config = {}, methods = {}) => {
}

if (!stats) {
response.statusCode = 404;

if (acceptsJSON) {
response.end(JSON.stringify({
error: {
code: 'not_found',
message: 'Not Found'
}
}));

return;
}

const errorPage = path.join(current, '404.html');

try {
stats = await handlers.stat(errorPage);
} catch (err) {
if (err.code !== 'ENOENT') {
console.error(err);

response.statusCode = 500;
response.end(err.message);

return;
}
}

if (!stats) {
response.end('Not Found');
return;
}

absolutePath = errorPage;
return sendError(response, acceptsJSON, current, handlers, config, {
statusCode: 404,
code: 'not_found',
message: 'The requested path could not be found'
});
}

const headers = await getHeaders(config.headers, current, absolutePath, stats);
Expand Down
Loading