Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
OlliV committed Apr 7, 2020
1 parent f9f303d commit b941a50
Show file tree
Hide file tree
Showing 8 changed files with 74 additions and 63 deletions.
33 changes: 0 additions & 33 deletions src/allow-methods.ts

This file was deleted.

41 changes: 41 additions & 0 deletions src/allowed-method.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { IncomingMessage, ServerResponse } from 'micri';
import { sendError } from './error';

// These methods are allowd for static resources: files and folder listings.
const ALLOW_METHODS = ['GET', 'HEAD', 'OPTIONS'];
const ALLOW_METHODS_STR = ALLOW_METHODS.join(', ');

const ALLOW_ORIGIN = '*';
const ALLOW_REQ_HEADERS = 'Accept, Accept-Encoding, Range';
const EXPOSE_RES_HEADERS =
'Accept-Ranges, Content-Range, Content-Length, Content-Type, Content-Encoding, Content-Disposition, Date, ETag, Transfer-Encoding, Server';

/**
* Check that the request method is one of the allowed types for static resources.
*/
export default function allowedMethod(req: IncomingMessage, res: ServerResponse): boolean {
if (!ALLOW_METHODS.includes(req.method || '')) {
res.setHeader('Allow', ALLOW_METHODS_STR);
sendError(req, res, 405, {
code: 'method_not_allowed',
message: 'Method not allowed',
});

return false;
}

if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Access-Control-Allow-Origin': ALLOW_ORIGIN,
'Access-Control-Allow-Methods': ALLOW_METHODS_STR,
'Access-Control-Allow-Headers': ALLOW_REQ_HEADERS,
'Access-Control-Expose-Headers': EXPOSE_RES_HEADERS,
'Access-Control-Max-Age': '86400',
});
res.end();

return false;
}

return true;
}
26 changes: 13 additions & 13 deletions src/fetch-graph-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ type OauthToken = {
access_token: string;
};

class GraphApiError extends Error {
method: string;
path: string;
responseBody: string;

constructor(path: string, opts: FetchOptions, res: Response, body: string, message: string) {
super(`${message} (${res.statusText})`);
this.method = opts.method || 'GET';
this.path = path;
this.responseBody = body;
}
}

const RESOURCE = 'https://graph.microsoft.com/';
const [TENANT_ID, CLIENT_ID, CLIENT_SECRET] = getEnv('TENANT_ID', 'CLIENT_ID', 'CLIENT_SECRET');
let tokenPromise: Promise<OauthToken> | null;
Expand All @@ -28,19 +41,6 @@ async function getToken(): Promise<OauthToken> {
return res.json();
}

class GraphApiError extends Error {
method: string;
path: string;
responseBody: string;

constructor(path: string, opts: FetchOptions, res: Response, body: string, message: string) {
super(`${message} (${res.statusText})`);
this.method = opts.method || 'GET';
this.path = path;
this.responseBody = body;
}
}

export default async function fetchAPI(path: string, opts: FetchOptions = {}) {
if (!tokenPromise) {
tokenPromise = getToken();
Expand Down
3 changes: 3 additions & 0 deletions src/get-site-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import { DirectoryListing, File, Folder } from './graph-api-types';

const [ROOT] = getEnv('ROOT');

/**
* SiteConfig can be set per each domain.
*/
export type SiteConfig = {
/**
* Custom error page file paths.
Expand Down
15 changes: 6 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,30 @@ import serveUri from './serve-uri';
import { sendError } from './error';

const [ROOT] = getEnv('ROOT');
const HOSTNAME_RE = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/;

const server = micri(async (req: IncomingMessage, res: ServerResponse) => {
accesslog(req, res);

const url = parse(req.url || '/', true);
const pathname = parse(req.url || '/', true).pathname || '';
const host = req.headers.host?.split(':')[0] || '';

if (
host === '' ||
!/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/.test(
host
)
) {
if (host === '' || !HOSTNAME_RE.test(host)) {
return sendError(req, res, 400, {
code: 'invalid_host',
message: 'Invalid Host',
});
}

const siteConfig = await getSiteConfig(host);
return serveUri(req, res, host, url.pathname || '', siteConfig);
return serveUri(req, res, host, pathname, siteConfig);
});

server.listen(process.env.PORT || 3000);

// Start authentication on startup to minimize the effect to serving traffic.
apiFetch(`${ROOT}:`)
.then(() => console.log(`Authenticated`)) // eslint-disable-line no-console
.then(() => console.log('Authenticated')) // eslint-disable-line no-console
.catch((err: Error) => {
console.error(err); // eslint-disable-line no-console
process.exit(1);
Expand Down
11 changes: 7 additions & 4 deletions src/send-file-list.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { send, IncomingMessage, ServerResponse } from 'micri';
import { parseAll } from '@hapi/accept';
import allowMethods from './allow-methods';
import allowedMethod from './allowed-method';
import setVary from './set-vary';
import { File, Folder } from './graph-api-types';

function getParent(path: string) {
/**
* Get path to the parent folder of path.
*/
function getParent(path: string): string {
const prev = path.split('/').slice(0, -1).join('/');

return prev.length === 0 ? '/' : prev;
Expand Down Expand Up @@ -42,12 +45,12 @@ export default function sendFileList(
res: ServerResponse,
pathname: string,
files: Array<File | Folder>
) {
): void {
let types = ['*/*'];

// Some methods are not allowed here and some will need special
// handling.
if (!allowMethods(req, res)) {
if (!allowedMethod(req, res)) {
return;
}

Expand Down
6 changes: 3 additions & 3 deletions src/send-file.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createHash } from 'crypto';
import { IncomingMessage, ServerResponse, send } from 'micri';
import allowMethods from './allow-methods';
import allowedMethod from './allowed-method';
import fetch from './fetch';
import setVary from './set-vary';
import { CACHE_CONTROL } from './config';
Expand All @@ -22,10 +22,10 @@ function makeReqHeaders(req: IncomingMessage) {
return headers;
}

export default async function sendFile(req: IncomingMessage, res: ServerResponse, file: File) {
export default async function sendFile(req: IncomingMessage, res: ServerResponse, file: File): Promise<void> {
// Some methods are not allowed here and some will need special
// handling.
if (!allowMethods(req, res)) {
if (!allowedMethod(req, res)) {
return;
}

Expand Down
2 changes: 1 addition & 1 deletion src/set-vary.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { ServerResponse } from 'micri';

export default (res: ServerResponse) => res.setHeader('Vary', 'Accept, Accept-Encoding, Range');
export default (res: ServerResponse): void => res.setHeader('Vary', 'Accept, Accept-Encoding, Range');

0 comments on commit b941a50

Please sign in to comment.