mihawk
Version:
A tiny & simple mock server tool, support json,js,cjs,ts(typescript).
38 lines (37 loc) • 1.72 kB
JavaScript
;
import { resolve } from 'path';
import { createReadStream, readFileSync } from 'fs-extra';
import { PKG_NAME } from '../consts';
import { ASSET_TPL_HTML_404_PATH, ASSET_DIR_PATH } from '../root';
const CA_ROOT_PATH = resolve(ASSET_DIR_PATH, './.cert/');
export default function certAuthFileDownload() {
const html = readFileSync(ASSET_TPL_HTML_404_PATH, 'utf-8');
return async function (ctx, next) {
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', 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 = createReadStream(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 <a href="/.cert/ca.crt">/.cert/ca.crt</a> ?`);
}
}
else {
return next();
}
};
}