Fix access is denied issue when install on Windows
This commit fixes -install options resulting in ERROR: add cert: failed adding cert: Access is denied even on a privileged Windows command prompt.
How does it works
The fix calls CertOpenStore instead of CertOpenSystemStoreW Win32 API for adding certs. The constants are extracted from here. Thanks 池边树下 for providing the solution at StackOverflow.
The story
I was using vite-plugin-mkcert which is a wrapper of mkcert for providing self-assigned CA for SSL purpose in a frontend project. The yarn serve command resulting in the following mkcert error:
PS $Env:DEBUG="vite:plugin:mkcert"
PS yarn serve
yarn run v1.22.11
$ npm run dev
> [email protected] dev
> vite
vite:plugin:mkcert The hosts changed from [undefined] to [localhost,<out_ip>,127.0.0.1], start regenerate certificate +0ms
ERROR error when starting dev server: 14:25:28
Error: Command failed: "C:\Users\<user>\.vite-plugin-mkcert\mkcert.exe" -install -key-file "C:\Users\<user>\.vite-plugin-mkcert\certs\dev.key" -cert-file "C:\Users\<user>\.vite-plugin-mkcert\certs\dev.pem" localhost <out_ip> 127.0.0.1
ERROR: add cert: failed adding cert: Access is denied.
at ChildProcess.exithandler (node:child_process:397:12)
at ChildProcess.emit (node:events:390:28)
at maybeClose (node:internal/child_process:1064:16)
at Socket.<anonymous> (node:internal/child_process:450:11)
at Socket.emit (node:events:390:28)
at Pipe.<anonymous> (node:net:687:12)
I found that -install option will cause this issue even on a privileged Windows command prompt, and there are already issues reported on that (#231, #395). So after searching for hours I've ported the solution here. Now the -install option will works on a privileged Windows command prompt.
PS .\mkcert.exe -install -key-file "C:\Users\<user>\.vite-plugin-mkcert\certs\dev.key" -cert-file "C:\Users\<user>\.vite-plugin-mkcert\certs\dev.pem" localhost <out_ip> 127.0.0.1
The local CA is already installed in the system trust store! 👍
The local CA is already installed in Java's trust store! 👍
Created a new certificate valid for the following names 📜
- "localhost"
- "<out_ip>"
- "127.0.0.1"
The certificate is at "C:\Users\<user>\.vite-plugin-mkcert\certs\dev.pem" and the key at "C:\Users\<user>\.vite-plugin-mkcert\certs\dev.key" ✅
It will expire on 20 September 2024 🗓
Note
The mkcert.exe with the fix is flagged as Trojan:Win32/Wacatac.B!ml by Windows Defender.
Until this is merged I created a PowerShell script a while back that'll install the RootCA certs for you and replace it if the thumbprints are different/tell you if its already installed. Feel free to use if it if its to your liking.