All files / estuary-rpc-server middleware.ts

84.84% Statements 56/66
72.72% Branches 48/66
82.35% Functions 14/17
85% Lines 51/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  2x 2x   2x   2x             2x                                                               2x 29x               2x   61x 61x   61x     2x   4x     4x 3x   1x 1x               2x             6x 6x 6x   2x   2x         2x 2x 2x         2x 2x 2x   2x   2x   4x 4x 4x       4x                                 2x               1x 44x 26x 26x 26x     19x   20x     6x 6x       6x   6x 6x               6x               2x     1x              
import { IncomingMessage, ServerResponse } from "http";
import { extname, resolve, sep } from "path";
import { createReadStream, promises as fs } from "fs";
 
import { SimpleMeta, HTTP_STATUS_CODES } from "estuary-rpc";
 
import {
  errorResponse,
  DEFAULT_NOT_FOUND,
  DEFAULT_INTERNAL_SERVER_ERROR,
} from "./errors";
import { ServerOpts, StaticFileOpts } from "./types";
 
const MIME_TYPES = {
  ".html": "text/html",
  ".htm": "text/html",
  ".js": "text/javascript",
  ".css": "text/css",
  ".json": "application/json",
  ".png": "image/png",
  ".mjs": "text/javascript",
  ".map": "application/json",
  ".webmanifest": "application/manifest+json",
  ".txt": "text/plain",
  ".ico": "image/x-icon",
  ".webp": "image/webp",
  ".avif": "image/avif",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".woff2": "font/woff2",
  ".gif": "image/gif",
  ".svg": "image/svg+xml",
  ".wav": "audio/wav",
  ".mp4": "video/mp4",
  ".woff": "application/font-woff",
  ".ttf": "application/font-ttf",
  ".eot": "application/vnd.ms-fontobject",
  ".otf": "application/font-otf",
  ".wasm": "application/wasm",
};
 
/**
 * Defines a unique string ID for all endpoints
 * @group Server
 */
export function methodId(meta: { method?: string; url?: string }) {
  return `${meta.method}:${meta.url}`;
}
 
/**
 * Parses the IncomingMessage into the URL object, useful for queryString parsing
 * @param req
 * @group Server
 */
export function getUrl(req: IncomingMessage): URL | undefined {
  let url: URL | undefined;
  try {
    url = new URL(req.url ?? "", `http://${req.headers.host ?? ""}`);
  } catch {}
  return url;
}
 
const contentCache: Record<string, Buffer | null> = {};
async function cachedDefaultContent(path?: string) {
  Iif (path === undefined || contentCache[path] === null) {
    return null;
  }
  if (contentCache[path]) {
    return contentCache[path];
  }
  contentCache[path] = await fs.readFile(path).catch(() => null);
  return contentCache[path];
}
/**
 * Method for serving the static file at filePath to a client, streamed; if there's none, the file at defaultPath
 * with defaultCode, else a 404.
 *
 * @group Server
 */
export const serveStatic = async (
  _: IncomingMessage,
  res: ServerResponse,
  filePath: string,
  defaultPath?: string,
  defaultCode?: number,
  headers: StaticFileOpts["headers"] = () => ({})
) => {
  const stat = await fs.stat(filePath).catch(() => undefined);
  if (stat?.isFile()) {
    const contentType =
      MIME_TYPES[String(extname(filePath)).toLowerCase()] ??
      "application/octet-stream";
    res.writeHead(200, {
      "Content-Type": contentType,
      "Content-Length": stat.size,
      ...headers(filePath),
    });
    await new Promise<void>((done) => {
      const stream = createReadStream(filePath);
      stream.on("error", (error) => {
        console.error(error);
        res.destroy();
        done();
      });
      res.on("close", () => {
        stream.destroy();
        done();
      });
      stream.pipe(res);
    });
    return;
  }
  const defaultContent = await cachedDefaultContent(defaultPath);
  try {
    res.writeHead(defaultCode ?? HTTP_STATUS_CODES.NOT_FOUND, {
      "Content-Type": defaultContent ? "text/html" : "application/json",
      ...(defaultContent && defaultPath ? headers(defaultPath) : {}),
    });
    res.end(defaultContent ?? errorResponse(DEFAULT_NOT_FOUND));
  } catch (error) {
    console.error(error);
    res.writeHead(500, { "Content-Type": "application/json" });
    res.end(errorResponse(DEFAULT_INTERNAL_SERVER_ERROR));
  }
};
 
/**
 * Creates a middleware object for serving static files. See {@link StaticFileOpts} for more detailed information
 * Can't really imagine needing to use this directly, instead you should just define the staticFiles field in the
 * {@link createApiServer}. Only GET and HEAD requests are served, and only files under fileRoot.
 * @param staticFileOpts
 * @returns Static File Middles
 *
 * @group Server
 */
export const staticFileMiddleware = ({
  defaultFile = "404.html",
  apiPrefixes = [],
  defaultCode = HTTP_STATUS_CODES.NOT_FOUND,
  fileRoot = "./static",
  urlRoot = "",
  headers,
}: StaticFileOpts) => {
  const root = resolve(fileRoot);
  const prefix = (path: string) => (path.startsWith("/") ? path : `/${path}`);
  return async (req: IncomingMessage, res: ServerResponse) => {
    const pathname = getUrl(req)?.pathname ?? "/";
    if (
      (req.method !== "GET" && req.method !== "HEAD") ||
      !pathname.startsWith(prefix(urlRoot)) ||
      apiPrefixes.some((api) => pathname.startsWith(prefix(api)))
    ) {
      return true;
    }
    let relative: string;
    try {
      relative = decodeURIComponent(pathname.slice(prefix(urlRoot).length));
    } catch {
      relative = "";
    }
    const filePath = resolve(root, `.${sep}${relative}`);
    // Never anything outside fileRoot (`/../`, encoded or not).
    const inside = filePath === root || filePath.startsWith(root + sep);
    await serveStatic(
      req,
      res,
      inside && !relative.includes("\0") ? filePath : root,
      resolve(root, defaultFile),
      defaultCode,
      headers
    );
    return false;
  };
};
 
/**
 * Gets the list of middlewares given serverOpts
 * @group Server
 */
export function automaticMiddleware<Meta extends SimpleMeta>(
  serverOpts: ServerOpts<Meta>
) {
  return [
    ...(serverOpts.staticFiles
      ? [staticFileMiddleware(serverOpts.staticFiles)]
      : []),
    ...(serverOpts.restMiddleware || []),
  ];
}