vite-plugin-mkcert
Advanced tools
Comparing version 1.3.2 to 1.4.0
{ | ||
"name": "vite-plugin-mkcert", | ||
"version": "1.3.2", | ||
"version": "1.4.0", | ||
"description": "Provide certificates for vite's https dev service", | ||
@@ -21,3 +21,3 @@ "repository": { | ||
"homepage": "https://github.com/liuweiGL/vite-plugin-mkcert#readme", | ||
"main": "dist/src/index", | ||
"main": "dist/index", | ||
"scripts": { | ||
@@ -34,4 +34,5 @@ "dev": "tsc -w", | ||
"devDependencies": { | ||
"rimraf": "^3.0.2" | ||
"rimraf": "^3.0.2", | ||
"typescript": "^4.3.5" | ||
} | ||
} |
import { createLogger, Plugin } from 'vite' | ||
import { PLUGIN_NAME } from './lib/constant' | ||
import { getLocalV4Ips } from './lib/util' | ||
import { getDefaultHosts } from './lib/util' | ||
import Mkcert, { MkcertOptions } from './mkcert' | ||
export type ViteCertificateOptions = MkcertOptions | ||
export type ViteCertificateOptions = MkcertOptions & { | ||
/** | ||
* The hosts that needs to generate the certificate. | ||
* | ||
* @default ["localhost","local ip addrs"] | ||
*/ | ||
hosts?: string[] | ||
} | ||
const plugin = (options?: ViteCertificateOptions): Plugin => { | ||
const plugin = (options: ViteCertificateOptions = {}): Plugin => { | ||
return { | ||
@@ -18,2 +25,4 @@ name: PLUGIN_NAME, | ||
const { hosts = getDefaultHosts(), ...mkcertOptions } = options | ||
const { logLevel } = config | ||
@@ -23,6 +32,5 @@ const logger = createLogger(logLevel, { | ||
}) | ||
const ips = getLocalV4Ips() | ||
const mkcert = Mkcert.create({ | ||
logger, | ||
...options | ||
...mkcertOptions | ||
}) | ||
@@ -32,3 +40,4 @@ | ||
const certificate = await mkcert.install(['localhost', ...ips]) | ||
const uniqueHosts = Array.from(new Set(hosts)) | ||
const certificate = await mkcert.install(uniqueHosts) | ||
@@ -35,0 +44,0 @@ return { |
import os from 'os' | ||
import path from 'path' | ||
import pkg from '../../package.json' | ||
export const PKG_NAME = pkg.name | ||
export const PKG_NAME ='vite-plugin-mkcert' | ||
@@ -8,0 +7,0 @@ export const PLUGIN_NAME = PKG_NAME.replace(/-/g, ':') |
@@ -6,2 +6,3 @@ import child_process from 'child_process' | ||
import util from 'util' | ||
import crypto from 'crypto' | ||
@@ -49,3 +50,4 @@ import { PLUGIN_DATA_DIR } from './constant' | ||
export const readFile = async (filePath: string) => { | ||
return (await fs.promises.readFile(filePath)).toString() | ||
const isExist = await exists(filePath) | ||
return isExist ? (await fs.promises.readFile(filePath)).toString() : undefined | ||
} | ||
@@ -82,1 +84,46 @@ | ||
} | ||
export const getDefaultHosts = () => { | ||
return ['localhost', ...getLocalV4Ips()] | ||
} | ||
export const getHash = async (filePath: string) => { | ||
const content = await readFile(filePath) | ||
if (content) { | ||
const hash = crypto.createHash('sha256') | ||
hash.update(content) | ||
return hash.digest('hex') | ||
} | ||
return undefined | ||
} | ||
const isObj = (obj: any) => | ||
Object.prototype.toString.call(obj) === '[object Object]' | ||
const mergeObj = (target: any, source: any) => { | ||
if (!(isObj(target) && isObj(source))) { | ||
return target | ||
} | ||
for (const key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
const targetValue = target[key] | ||
const sourceValue = source[key] | ||
if (isObj(targetValue) && isObj(sourceValue)) { | ||
mergeObj(targetValue, sourceValue) | ||
} else { | ||
target[key] = sourceValue | ||
} | ||
} | ||
} | ||
} | ||
export const deepMerge = (target: any, ...source: any[]) => { | ||
return source.reduce((a, b) => mergeObj(a, b), target) | ||
} | ||
export const prettyLog = (obj?: Record<string, any>) => { | ||
return obj ? JSON.stringify(obj, null, 2) : obj | ||
} |
@@ -7,7 +7,16 @@ import fs from 'fs' | ||
import { debug } from '../lib/logger' | ||
import { ensureDirExist, exec, exists, resolvePath } from '../lib/util' | ||
import { | ||
ensureDirExist, | ||
exec, | ||
exists, | ||
getHash, | ||
prettyLog, | ||
resolvePath | ||
} from '../lib/util' | ||
import Downloader from './downloader' | ||
import { BaseSource, GithubSource, CodingSource } from './Source' | ||
import { BaseSource, GithubSource, CodingSource } from './source' | ||
import VersionManger from './version' | ||
import Config from './config' | ||
import Record from './record' | ||
@@ -44,2 +53,4 @@ export type SourceType = 'github' | 'coding' | BaseSource | ||
const KEY_FILE_PATH = resolvePath('certs/dev.key') | ||
const CERT_FILE_PATH = resolvePath('certs/dev.pem') | ||
class Mkcert { | ||
@@ -54,2 +65,4 @@ private autoUpgrade?: boolean | ||
private config: Config | ||
public static create(options: MkcertProps) { | ||
@@ -76,14 +89,8 @@ return new Mkcert(options) | ||
this.mkcertSavedPath = resolvePath( | ||
process.platform === 'win32' ? `mkcert.exe` : 'mkcert' | ||
process.platform === 'win32' ? 'mkcert.exe' : 'mkcert' | ||
) | ||
} | ||
private getKeyPath() { | ||
return resolvePath(`certs/dev.key`) | ||
this.config = new Config() | ||
} | ||
private getCertPath() { | ||
return resolvePath(`certs/dev.pem`) | ||
} | ||
private async getMkcertBinnary() { | ||
@@ -114,4 +121,4 @@ return (await this.checkMkcert()) | ||
private async getCertificate() { | ||
const key = await fs.promises.readFile(this.getKeyPath()) | ||
const cert = await fs.promises.readFile(this.getCertPath()) | ||
const key = await fs.promises.readFile(KEY_FILE_PATH) | ||
const cert = await fs.promises.readFile(CERT_FILE_PATH) | ||
@@ -134,16 +141,32 @@ return { | ||
const keyFile = this.getKeyPath() | ||
const certFile = this.getCertPath() | ||
await ensureDirExist(KEY_FILE_PATH) | ||
await ensureDirExist(CERT_FILE_PATH) | ||
await ensureDirExist(keyFile) | ||
await ensureDirExist(certFile) | ||
const cmd = `${mkcertBinnary} -install -key-file ${KEY_FILE_PATH} -cert-file ${CERT_FILE_PATH} ${hostlist}` | ||
const cmd = `${mkcertBinnary} -install -key-file ${keyFile} -cert-file ${certFile} ${hostlist}` | ||
await exec(cmd) | ||
this.logger.info(`The certificate is saved in:\n${keyFile}\n${certFile}`) | ||
this.logger.info( | ||
`The certificate is saved in:\n${KEY_FILE_PATH}\n${CERT_FILE_PATH}` | ||
) | ||
} | ||
private getLatestHash = async () => { | ||
return { | ||
key: await getHash(KEY_FILE_PATH), | ||
cert: await getHash(CERT_FILE_PATH) | ||
} | ||
} | ||
private async regenerate(record: Record, hosts: string[]) { | ||
await this.createCertificate(hosts) | ||
const hash = await this.getLatestHash() | ||
record.update({ hosts, hash }) | ||
} | ||
public async init() { | ||
await this.config.init() | ||
if (this.autoUpgrade || !(await this.checkMkcert())) { | ||
@@ -155,3 +178,3 @@ await this.updateMkcert() | ||
public async updateMkcert() { | ||
const versionManger = VersionManger.create() | ||
const versionManger = new VersionManger({ config: this.config }) | ||
const sourceInfo = await this.source.getSourceInfo() | ||
@@ -161,6 +184,6 @@ | ||
if (typeof this.sourceType === 'string') { | ||
debug(`Failed to request mkcert information, please check your network`) | ||
debug('Failed to request mkcert information, please check your network') | ||
if (this.sourceType === 'github') { | ||
debug( | ||
`If you are a user in china, maybe you should set "source" paramter to "coding"` | ||
'If you are a user in china, maybe you should set "source" paramter to "coding"' | ||
) | ||
@@ -170,6 +193,6 @@ } | ||
debug( | ||
`Please check your custom "source", it seems to return invalid result` | ||
'Please check your custom "source", it seems to return invalid result' | ||
) | ||
} | ||
debug(`Can not get mkcert information, update skipped`) | ||
debug('Can not get mkcert information, update skipped') | ||
return | ||
@@ -187,3 +210,3 @@ } | ||
debug( | ||
`The current version of mkcert is %s, and the latest version is %s, there may be some breaking changes, update skipped`, | ||
'The current version of mkcert is %s, and the latest version is %s, there may be some breaking changes, update skipped', | ||
versionInfo.currentVersion, | ||
@@ -196,3 +219,3 @@ versionInfo.nextVersion | ||
debug( | ||
`The current version of mkcert is %s, and the latest version is %s, mkcert is be updated`, | ||
'The current version of mkcert is %s, and the latest version is %s, mkcert will be updated', | ||
versionInfo.currentVersion, | ||
@@ -202,2 +225,4 @@ versionInfo.nextVersion | ||
versionManger.update(versionInfo.nextVersion) | ||
const downloader = Downloader.create() | ||
@@ -208,4 +233,28 @@ | ||
public async renew(hostnames: string[]) { | ||
await this.createCertificate(hostnames) | ||
public async renew(hosts: string[]) { | ||
const record = new Record({ config: this.config }) | ||
if (!record.contains(hosts)) { | ||
this.logger.info( | ||
`The hosts changed from [${record.getHosts()}] to [${hosts}], start regenerate certificate` | ||
) | ||
await this.regenerate(record, hosts) | ||
return | ||
} | ||
const hash = await this.getLatestHash() | ||
if (record.tamper(hash)) { | ||
this.logger.info( | ||
`The hash changed from ${prettyLog( | ||
record.getHash() | ||
)} to ${prettyLog(hash)}, start regenerate certificate` | ||
) | ||
await this.regenerate(record, hosts) | ||
return | ||
} | ||
debug('Neither hosts nor hash has changed, skip regenerate certificate') | ||
} | ||
@@ -216,8 +265,8 @@ | ||
* | ||
* @param hostnames hostname collection | ||
* @param hosts host collection | ||
* @returns cretificates | ||
*/ | ||
public async install(hostnames: string[]) { | ||
if (hostnames.length) { | ||
await this.renew(hostnames) | ||
public async install(hosts: string[]) { | ||
if (hosts.length) { | ||
await this.renew(hosts) | ||
} | ||
@@ -224,0 +273,0 @@ |
import { debug } from '../lib/logger' | ||
import { readFile, resolvePath, writeFile } from '../lib/util' | ||
import Config from './config' | ||
const VERSION_FILE_NAME = 'version.txt' | ||
const VERSION_FILE_PATH = resolvePath(VERSION_FILE_NAME) | ||
export type VersionMangerProps = { | ||
config: Config | ||
} | ||
@@ -14,19 +15,11 @@ const parseVersion = (version: string) => { | ||
class VersionManger { | ||
public static create() { | ||
return new VersionManger() | ||
} | ||
private config: Config | ||
private constructor() {} | ||
private async getVersion() { | ||
try { | ||
return await readFile(VERSION_FILE_PATH) | ||
} catch (e) { | ||
return undefined | ||
} | ||
public constructor(props: VersionMangerProps) { | ||
this.config = props.config | ||
} | ||
public async updateVersion(version: string) { | ||
public async update(version: string) { | ||
try { | ||
await writeFile(VERSION_FILE_PATH, version) | ||
await this.config.merge({ version }) | ||
} catch (err) { | ||
@@ -37,4 +30,4 @@ debug('Failed to record mkcert version info: %o', err) | ||
public async compare(version: string) { | ||
const currentVersion = await this.getVersion() | ||
public compare(version: string) { | ||
const currentVersion = this.config.getVersion() | ||
@@ -41,0 +34,0 @@ if (!currentVersion) { |
{ | ||
"compilerOptions": { | ||
/* Visit https://aka.ms/tsconfig.json to read more about this file */ | ||
/* Basic Options */ | ||
"incremental": true, /* Enable incremental compilation */ | ||
"target": "ES6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, | ||
"module": "CommonJS" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, | ||
// "lib": [], /* Specify library files to be included in the compilation. */ | ||
// "allowJs": true, /* Allow javascript files to be compiled. */ | ||
// "checkJs": true, /* Report errors in .js files. */ | ||
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ | ||
"declaration": true, /* Generates corresponding '.d.ts' file. */ | ||
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ | ||
"sourceMap": true, /* Generates corresponding '.map' file. */ | ||
// "outFile": "./", /* Concatenate and emit output to single file. */ | ||
"outDir": "./dist", /* Redirect output structure to the directory. */ | ||
"rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ | ||
// "composite": true, /* Enable project compilation */ | ||
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ | ||
// "removeComments": true, /* Do not emit comments to output. */ | ||
// "noEmit": true, /* Do not emit outputs. */ | ||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */ | ||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ | ||
"isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ | ||
/* Strict Type-Checking Options */ | ||
"strict": true /* Enable all strict type-checking options. */, | ||
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ | ||
// "strictNullChecks": true, /* Enable strict null checks. */ | ||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */ | ||
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ | ||
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ | ||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ | ||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ | ||
/* Additional Checks */ | ||
// "noUnusedLocals": true, /* Report errors on unused locals. */ | ||
// "noUnusedParameters": true, /* Report errors on unused parameters. */ | ||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ | ||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ | ||
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ | ||
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ | ||
/* Module Resolution Options */ | ||
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ | ||
"resolveJsonModule": true, | ||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ | ||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ | ||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ | ||
// "typeRoots": [], /* List of folders to include type definitions from. */ | ||
// "types": [], /* Type declaration files to be included in compilation. */ | ||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ | ||
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, | ||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ | ||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ | ||
/* Source Map Options */ | ||
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ | ||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ | ||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ | ||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ | ||
/* Experimental Options */ | ||
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ | ||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ | ||
/* Advanced Options */ | ||
"skipLibCheck": true /* Skip type checking of declaration files. */, | ||
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ | ||
"target": "ES6", | ||
"module": "commonjs", | ||
"declaration": true, | ||
"sourceMap": true, | ||
"outDir": "./dist", | ||
"baseUrl": ".", | ||
"isolatedModules": true, | ||
"strict": true, | ||
"moduleResolution": "node", | ||
"esModuleInterop": true, | ||
"skipLibCheck": true, | ||
"forceConsistentCasingInFileNames": true | ||
}, | ||
"include": ["src"] | ||
"include": ["src/**/*.ts"] | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
47
1657
75521
2
2