UNPKG

mihawk

Version:

A tiny & simple mock server tool, support json,js,cjs,ts(typescript).

51 lines (50 loc) 2.69 kB
'use strict'; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const path_1 = require("path"); const fs_extra_1 = require("fs-extra"); const consts_1 = require("../consts"); const root_1 = require("../root"); const CA_ROOT_PATH = (0, path_1.resolve)(root_1.ASSET_DIR_PATH, './.cert/'); function certAuthFileDownload() { const html = (0, fs_extra_1.readFileSync)(root_1.ASSET_TPL_HTML_404_PATH, 'utf-8'); return function (ctx, next) { return __awaiter(this, void 0, void 0, function* () { const { path, method } = ctx || {}; if (path.startsWith('/.cert/') || path === '/.cert') { ctx.skipDefaultMock = true; if (['/.cert/ca.crt', '/.cert/localhost.crt'].some(p => p === path)) { if (!['GET', 'HEAD'].includes(method)) { ctx.status = 'OPTIONS' == method ? 200 : 405; ctx.set('Allow', 'GET, HEAD, OPTIONS'); } else { const fileName = path.replace(/^(\/.cert\/)/, '').trim(); ctx.set('X-Powered-By', consts_1.PKG_NAME); ctx.set('Cache-Control', `public, max-age=${(86400000 / 1000) | 0}`); ctx.set('Content-Disposition', `attachment; filename=${fileName}`); ctx.type = 'application/x-x509-ca-cert'; ctx.body = (0, fs_extra_1.createReadStream)((0, path_1.resolve)(CA_ROOT_PATH, fileName)); } } else { ctx.set('Content-Type', 'text/html'); ctx.status = 404; ctx.body = html.replace('<%= detailMsg %>', `The uri(${path}) is not found! Do you mean &nbsp;<a href="/.cert/ca.crt">/.cert/ca.crt</a>&nbsp;?`); } } else { return next(); } }); }; } exports.default = certAuthFileDownload;