mkcert.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  9. var __export = (target, all) => {
  10. for (var name in all)
  11. __defProp(target, name, { get: all[name], enumerable: true });
  12. };
  13. var __copyProps = (to, from, except, desc) => {
  14. if (from && typeof from === "object" || typeof from === "function") {
  15. for (let key of __getOwnPropNames(from))
  16. if (!__hasOwnProp.call(to, key) && key !== except)
  17. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  18. }
  19. return to;
  20. };
  21. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  22. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  23. mod
  24. ));
  25. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  26. var __publicField = (obj, key, value) => {
  27. __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  28. return value;
  29. };
  30. // plugin/index.ts
  31. var plugin_exports = {};
  32. __export(plugin_exports, {
  33. BaseSource: () => BaseSource,
  34. default: () => plugin_default
  35. });
  36. module.exports = __toCommonJS(plugin_exports);
  37. var import_vite = require("vite");
  38. // plugin/lib/constant.ts
  39. var import_os = __toESM(require("os"));
  40. var import_path = __toESM(require("path"));
  41. var PKG_NAME = "vite-plugin-mkcert";
  42. var PLUGIN_NAME = PKG_NAME.replace(/-/g, ":");
  43. var PLUGIN_DATA_DIR = import_path.default.join(import_os.default.homedir(), `.${PKG_NAME}`);
  44. // plugin/lib/util.ts
  45. var import_child_process = __toESM(require("child_process"));
  46. var import_crypto = __toESM(require("crypto"));
  47. var import_fs = __toESM(require("fs"));
  48. var import_os2 = __toESM(require("os"));
  49. var import_path2 = __toESM(require("path"));
  50. var import_util = __toESM(require("util"));
  51. var exists = async (filePath) => {
  52. try {
  53. await import_fs.default.promises.access(filePath);
  54. return true;
  55. } catch (error) {
  56. return false;
  57. }
  58. };
  59. var resolvePath = (fileName) => {
  60. return import_path2.default.resolve(PLUGIN_DATA_DIR, fileName);
  61. };
  62. var mkdir = async (dirname) => {
  63. const isExist = await exists(dirname);
  64. if (!isExist) {
  65. await import_fs.default.promises.mkdir(dirname, { recursive: true });
  66. }
  67. };
  68. var ensureDirExist = async (filePath) => {
  69. const dirname = import_path2.default.dirname(filePath);
  70. await mkdir(dirname);
  71. };
  72. var readFile = async (filePath) => {
  73. const isExist = await exists(filePath);
  74. return isExist ? (await import_fs.default.promises.readFile(filePath)).toString() : void 0;
  75. };
  76. var writeFile = async (filePath, data) => {
  77. await ensureDirExist(filePath);
  78. await import_fs.default.promises.writeFile(filePath, data);
  79. await import_fs.default.promises.chmod(filePath, 511);
  80. };
  81. var exec = async (cmd, options) => {
  82. return await import_util.default.promisify(import_child_process.default.exec)(cmd, options);
  83. };
  84. var isIPV4 = (family) => {
  85. return family === "IPv4" || family === 4;
  86. };
  87. var getLocalV4Ips = () => {
  88. const interfaceDict = import_os2.default.networkInterfaces();
  89. const addresses = [];
  90. for (const key in interfaceDict) {
  91. const interfaces = interfaceDict[key];
  92. if (interfaces) {
  93. for (const item of interfaces) {
  94. if (isIPV4(item.family)) {
  95. addresses.push(item.address);
  96. }
  97. }
  98. }
  99. }
  100. return addresses;
  101. };
  102. var getDefaultHosts = () => {
  103. return ["localhost", ...getLocalV4Ips()];
  104. };
  105. var getHash = async (filePath) => {
  106. const content = await readFile(filePath);
  107. if (content) {
  108. const hash = import_crypto.default.createHash("sha256");
  109. hash.update(content);
  110. return hash.digest("hex");
  111. }
  112. return void 0;
  113. };
  114. var isObj = (obj) => Object.prototype.toString.call(obj) === "[object Object]";
  115. var mergeObj = (target, source) => {
  116. if (!(isObj(target) && isObj(source))) {
  117. return target;
  118. }
  119. for (const key in source) {
  120. if (Object.prototype.hasOwnProperty.call(source, key)) {
  121. const targetValue = target[key];
  122. const sourceValue = source[key];
  123. if (isObj(targetValue) && isObj(sourceValue)) {
  124. mergeObj(targetValue, sourceValue);
  125. } else {
  126. target[key] = sourceValue;
  127. }
  128. }
  129. }
  130. };
  131. var deepMerge = (target, ...source) => {
  132. return source.reduce((a, b) => mergeObj(a, b), target);
  133. };
  134. var prettyLog = (obj) => {
  135. return JSON.stringify(obj, null, 2);
  136. };
  137. var escape = (path3) => {
  138. return `"${path3}"`;
  139. };
  140. // plugin/mkcert/index.ts
  141. var import_fs2 = __toESM(require("fs"));
  142. var import_process = __toESM(require("process"));
  143. var import_picocolors = __toESM(require("picocolors"));
  144. // plugin/lib/logger.ts
  145. var import_debug = __toESM(require("debug"));
  146. var debug = (0, import_debug.default)(PLUGIN_NAME);
  147. // plugin/mkcert/config.ts
  148. var CONFIG_FILE_NAME = "config.json";
  149. var CONFIG_FILE_PATH = resolvePath(CONFIG_FILE_NAME);
  150. var Config = class {
  151. version;
  152. record;
  153. async init() {
  154. const str = await readFile(CONFIG_FILE_PATH);
  155. const options = str ? JSON.parse(str) : void 0;
  156. if (options) {
  157. this.version = options.version;
  158. this.record = options.record;
  159. }
  160. }
  161. async serialize() {
  162. await writeFile(CONFIG_FILE_PATH, prettyLog(this));
  163. }
  164. async merge(obj) {
  165. const currentStr = prettyLog(this);
  166. deepMerge(this, obj);
  167. const nextStr = prettyLog(this);
  168. debug(
  169. `Receive parameter ${prettyLog(
  170. obj
  171. )}, then update config from ${currentStr} to ${nextStr}`
  172. );
  173. await this.serialize();
  174. }
  175. getRecord() {
  176. return this.record;
  177. }
  178. getVersion() {
  179. return this.version;
  180. }
  181. };
  182. var config_default = Config;
  183. // plugin/lib/request.ts
  184. var import_axios = __toESM(require("axios"));
  185. var request = import_axios.default.create();
  186. request.interceptors.response.use(
  187. (res) => {
  188. return res;
  189. },
  190. (error) => {
  191. debug("Request error: %o", error);
  192. return Promise.reject(error);
  193. }
  194. );
  195. var request_default = request;
  196. // plugin/mkcert/downloader.ts
  197. var Downloader = class {
  198. static create() {
  199. return new Downloader();
  200. }
  201. constructor() {
  202. }
  203. async download(downloadUrl, savedPath) {
  204. debug("Downloading the mkcert executable from %s", downloadUrl);
  205. const { data } = await request_default.get(downloadUrl, {
  206. responseType: "arraybuffer"
  207. });
  208. await writeFile(savedPath, data);
  209. debug("The mkcert has been saved to %s", savedPath);
  210. }
  211. };
  212. var downloader_default = Downloader;
  213. // plugin/mkcert/record.ts
  214. var Record = class {
  215. config;
  216. constructor(options) {
  217. this.config = options.config;
  218. }
  219. getHosts() {
  220. return this.config.getRecord()?.hosts;
  221. }
  222. getHash() {
  223. return this.config.getRecord()?.hash;
  224. }
  225. contains(hosts) {
  226. const oldHosts = this.getHosts();
  227. if (!oldHosts) {
  228. return false;
  229. }
  230. for (const host of hosts) {
  231. if (!oldHosts.includes(host)) {
  232. return false;
  233. }
  234. }
  235. return true;
  236. }
  237. tamper(hash) {
  238. const oldHash = this.getHash();
  239. if (!oldHash) {
  240. return false;
  241. }
  242. if (oldHash.key === hash.key && oldHash.cert === hash.cert) {
  243. return false;
  244. }
  245. return true;
  246. }
  247. async update(record) {
  248. await this.config.merge({ record });
  249. }
  250. };
  251. var record_default = Record;
  252. // plugin/mkcert/source.ts
  253. var import_rest = require("@octokit/rest");
  254. var BaseSource = class {
  255. getPlatformIdentifier() {
  256. switch (process.platform) {
  257. case "win32":
  258. return "windows-amd64.exe";
  259. case "linux":
  260. return process.arch === "arm64" ? "linux-arm64" : process.arch === "arm" ? "linux-arm" : "linux-amd64";
  261. case "darwin":
  262. return "darwin-amd64";
  263. default:
  264. throw new Error("Unsupported platform");
  265. }
  266. }
  267. };
  268. var GithubSource = class extends BaseSource {
  269. static create() {
  270. return new GithubSource();
  271. }
  272. constructor() {
  273. super();
  274. }
  275. async getSourceInfo() {
  276. const octokit = new import_rest.Octokit();
  277. const { data } = await octokit.repos.getLatestRelease({
  278. owner: "FiloSottile",
  279. repo: "mkcert"
  280. });
  281. const platformIdentifier = this.getPlatformIdentifier();
  282. const version = data.tag_name;
  283. const downloadUrl = data.assets.find(
  284. (item) => item.name.includes(platformIdentifier)
  285. )?.browser_download_url;
  286. if (!(version && downloadUrl)) {
  287. return void 0;
  288. }
  289. return {
  290. downloadUrl,
  291. version
  292. };
  293. }
  294. };
  295. var _CodingSource = class extends BaseSource {
  296. static create() {
  297. return new _CodingSource();
  298. }
  299. constructor() {
  300. super();
  301. }
  302. async request(data) {
  303. return request_default({
  304. data,
  305. method: "POST",
  306. url: _CodingSource.CODING_API,
  307. headers: {
  308. Authorization: _CodingSource.CODING_AUTHORIZATION
  309. }
  310. });
  311. }
  312. getPackageName() {
  313. return `mkcert-${this.getPlatformIdentifier()}`;
  314. }
  315. async getSourceInfo() {
  316. const { data: VersionData } = await this.request({
  317. Action: "DescribeArtifactVersionList",
  318. ProjectId: _CodingSource.CODING_PROJECT_ID,
  319. Repository: _CodingSource.REPOSITORY,
  320. Package: this.getPackageName(),
  321. PageSize: 1
  322. });
  323. const version = VersionData.Response.Data.InstanceSet[0]?.Version;
  324. if (!version) {
  325. return void 0;
  326. }
  327. const { data: FileData } = await this.request({
  328. Action: "DescribeArtifactFileDownloadUrl",
  329. ProjectId: _CodingSource.CODING_PROJECT_ID,
  330. Repository: _CodingSource.REPOSITORY,
  331. Package: this.getPackageName(),
  332. PackageVersion: version
  333. });
  334. const downloadUrl = FileData.Response.Url;
  335. if (!downloadUrl) {
  336. return void 0;
  337. }
  338. return {
  339. downloadUrl,
  340. version
  341. };
  342. }
  343. };
  344. var CodingSource = _CodingSource;
  345. __publicField(CodingSource, "CODING_API", "https://e.coding.net/open-api");
  346. __publicField(CodingSource, "CODING_AUTHORIZATION", "token 000f7831ec425079439b0f55f55c729c9280d66e");
  347. __publicField(CodingSource, "CODING_PROJECT_ID", 8524617);
  348. __publicField(CodingSource, "REPOSITORY", "mkcert");
  349. // plugin/mkcert/version.ts
  350. var parseVersion = (version) => {
  351. const str = version.trim().replace(/v/i, "");
  352. return str.split(".");
  353. };
  354. var VersionManger = class {
  355. config;
  356. constructor(props) {
  357. this.config = props.config;
  358. }
  359. async update(version) {
  360. try {
  361. await this.config.merge({ version });
  362. } catch (err) {
  363. debug("Failed to record mkcert version info: %o", err);
  364. }
  365. }
  366. compare(version) {
  367. const currentVersion = this.config.getVersion();
  368. if (!currentVersion) {
  369. return {
  370. currentVersion,
  371. nextVersion: version,
  372. breakingChange: false,
  373. shouldUpdate: true
  374. };
  375. }
  376. let breakingChange = false;
  377. let shouldUpdate = false;
  378. const newVersion = parseVersion(version);
  379. const oldVersion = parseVersion(currentVersion);
  380. for (let i = 0; i < newVersion.length; i++) {
  381. if (newVersion[i] > oldVersion[i]) {
  382. shouldUpdate = true;
  383. breakingChange = i === 0;
  384. break;
  385. }
  386. }
  387. return {
  388. breakingChange,
  389. shouldUpdate,
  390. currentVersion,
  391. nextVersion: version
  392. };
  393. }
  394. };
  395. var version_default = VersionManger;
  396. // plugin/mkcert/index.ts
  397. var KEY_FILE_PATH = resolvePath("certs/dev.key");
  398. var CERT_FILE_PATH = resolvePath("certs/dev.pem");
  399. var Mkcert = class {
  400. force;
  401. autoUpgrade;
  402. mkcertLocalPath;
  403. source;
  404. logger;
  405. mkcertSavedPath;
  406. sourceType;
  407. config;
  408. static create(options) {
  409. return new Mkcert(options);
  410. }
  411. constructor(options) {
  412. const { force, autoUpgrade, source, mkcertPath, logger } = options;
  413. this.force = force;
  414. this.logger = logger;
  415. this.autoUpgrade = autoUpgrade;
  416. this.mkcertLocalPath = mkcertPath;
  417. this.sourceType = source || "github";
  418. if (this.sourceType === "github") {
  419. this.source = GithubSource.create();
  420. } else if (this.sourceType === "coding") {
  421. this.source = CodingSource.create();
  422. } else {
  423. this.source = this.sourceType;
  424. }
  425. this.mkcertSavedPath = resolvePath(
  426. import_process.default.platform === "win32" ? "mkcert.exe" : "mkcert"
  427. );
  428. this.config = new config_default();
  429. }
  430. async getMkcertBinnary() {
  431. return await this.checkMkcert() ? this.mkcertLocalPath || this.mkcertSavedPath : void 0;
  432. }
  433. async checkMkcert() {
  434. let exist;
  435. if (this.mkcertLocalPath) {
  436. exist = await exists(this.mkcertLocalPath);
  437. if (!exists) {
  438. this.logger.error(
  439. import_picocolors.default.red(
  440. `${this.mkcertLocalPath} does not exist, please check the mkcertPath paramter`
  441. )
  442. );
  443. }
  444. } else {
  445. exist = await exists(this.mkcertSavedPath);
  446. }
  447. return exist;
  448. }
  449. async getCertificate() {
  450. const key = await import_fs2.default.promises.readFile(KEY_FILE_PATH);
  451. const cert = await import_fs2.default.promises.readFile(CERT_FILE_PATH);
  452. return {
  453. key,
  454. cert
  455. };
  456. }
  457. async createCertificate(hosts) {
  458. const names = hosts.join(" ");
  459. const mkcertBinnary = await this.getMkcertBinnary();
  460. if (!mkcertBinnary) {
  461. debug(
  462. `Mkcert does not exist, unable to generate certificate for ${names}`
  463. );
  464. }
  465. await ensureDirExist(KEY_FILE_PATH);
  466. await ensureDirExist(CERT_FILE_PATH);
  467. const cmd = `${escape(mkcertBinnary)} -install -key-file ${escape(
  468. KEY_FILE_PATH
  469. )} -cert-file ${escape(CERT_FILE_PATH)} ${names}`;
  470. await exec(cmd, {
  471. env: {
  472. ...import_process.default.env,
  473. JAVA_HOME: void 0
  474. }
  475. });
  476. this.logger.info(
  477. `The certificate is saved in:
  478. ${KEY_FILE_PATH}
  479. ${CERT_FILE_PATH}`
  480. );
  481. }
  482. getLatestHash = async () => {
  483. return {
  484. key: await getHash(KEY_FILE_PATH),
  485. cert: await getHash(CERT_FILE_PATH)
  486. };
  487. };
  488. async regenerate(record, hosts) {
  489. await this.createCertificate(hosts);
  490. const hash = await this.getLatestHash();
  491. record.update({ hosts, hash });
  492. }
  493. async init() {
  494. await this.config.init();
  495. const exist = await this.checkMkcert();
  496. if (!exist) {
  497. await this.initMkcert();
  498. } else if (this.autoUpgrade) {
  499. await this.upgradeMkcert();
  500. }
  501. }
  502. async getSourceInfo() {
  503. const sourceInfo = await this.source.getSourceInfo();
  504. if (!sourceInfo) {
  505. if (typeof this.sourceType === "string") {
  506. this.logger.error(
  507. "Failed to request mkcert information, please check your network"
  508. );
  509. if (this.sourceType === "github") {
  510. this.logger.info(
  511. 'If you are a user in china, maybe you should set "source" paramter to "coding"'
  512. );
  513. }
  514. } else {
  515. this.logger.info(
  516. 'Please check your custom "source", it seems to return invalid result'
  517. );
  518. }
  519. return void 0;
  520. }
  521. return sourceInfo;
  522. }
  523. async initMkcert() {
  524. const sourceInfo = await this.getSourceInfo();
  525. debug("The mkcert does not exist, download it now");
  526. if (!sourceInfo) {
  527. this.logger.error(
  528. "Can not obtain download information of mkcert, init skipped"
  529. );
  530. return;
  531. }
  532. await this.downloadMkcert(sourceInfo.downloadUrl, this.mkcertSavedPath);
  533. }
  534. async upgradeMkcert() {
  535. const versionManger = new version_default({ config: this.config });
  536. const sourceInfo = await this.getSourceInfo();
  537. if (!sourceInfo) {
  538. this.logger.error(
  539. "Can not obtain download information of mkcert, update skipped"
  540. );
  541. return;
  542. }
  543. const versionInfo = versionManger.compare(sourceInfo.version);
  544. if (!versionInfo.shouldUpdate) {
  545. debug("Mkcert is kept latest version, update skipped");
  546. return;
  547. }
  548. if (versionInfo.breakingChange) {
  549. debug(
  550. "The current version of mkcert is %s, and the latest version is %s, there may be some breaking changes, update skipped",
  551. versionInfo.currentVersion,
  552. versionInfo.nextVersion
  553. );
  554. return;
  555. }
  556. debug(
  557. "The current version of mkcert is %s, and the latest version is %s, mkcert will be updated",
  558. versionInfo.currentVersion,
  559. versionInfo.nextVersion
  560. );
  561. await this.downloadMkcert(sourceInfo.downloadUrl, this.mkcertSavedPath);
  562. versionManger.update(versionInfo.nextVersion);
  563. }
  564. async downloadMkcert(sourceUrl, distPath) {
  565. const downloader = downloader_default.create();
  566. await downloader.download(sourceUrl, distPath);
  567. }
  568. async renew(hosts) {
  569. const record = new record_default({ config: this.config });
  570. if (this.force) {
  571. debug(`Certificate is forced to regenerate`);
  572. await this.regenerate(record, hosts);
  573. }
  574. if (!record.contains(hosts)) {
  575. debug(
  576. `The hosts changed from [${record.getHosts()}] to [${hosts}], start regenerate certificate`
  577. );
  578. await this.regenerate(record, hosts);
  579. return;
  580. }
  581. const hash = await this.getLatestHash();
  582. if (record.tamper(hash)) {
  583. debug(
  584. `The hash changed from ${prettyLog(record.getHash())} to ${prettyLog(
  585. hash
  586. )}, start regenerate certificate`
  587. );
  588. await this.regenerate(record, hosts);
  589. return;
  590. }
  591. debug("Neither hosts nor hash has changed, skip regenerate certificate");
  592. }
  593. async install(hosts) {
  594. if (hosts.length) {
  595. await this.renew(hosts);
  596. }
  597. return await this.getCertificate();
  598. }
  599. };
  600. var mkcert_default = Mkcert;
  601. // plugin/index.ts
  602. var plugin = (options = {}) => {
  603. return {
  604. name: PLUGIN_NAME,
  605. apply: "serve",
  606. config: async ({ server = {}, logLevel }) => {
  607. if (server.https === false) {
  608. return;
  609. }
  610. const { hosts = [], ...mkcertOptions } = options;
  611. const logger = (0, import_vite.createLogger)(logLevel, {
  612. prefix: PLUGIN_NAME
  613. });
  614. const mkcert = mkcert_default.create({
  615. logger,
  616. ...mkcertOptions
  617. });
  618. await mkcert.init();
  619. const allHosts = [...getDefaultHosts(), ...hosts];
  620. if (typeof server.host === "string") {
  621. allHosts.push(server.host);
  622. }
  623. const uniqueHosts = Array.from(new Set(allHosts)).filter((item) => !!item);
  624. const certificate = await mkcert.install(uniqueHosts);
  625. return {
  626. server: {
  627. https: {
  628. ...certificate
  629. }
  630. },
  631. preview: {
  632. https: {
  633. ...certificate
  634. }
  635. }
  636. };
  637. }
  638. };
  639. };
  640. var plugin_default = plugin;
  641. // Annotate the CommonJS export names for ESM import in node:
  642. 0 && (module.exports = {
  643. BaseSource
  644. });
  645. //# sourceMappingURL=mkcert.js.map