Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions src/bootstrap/activation.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,22 +128,23 @@ func ensureActivationLink(mode, dataRoot, installRoot, shimDir, activeVersion st
}

nodejsPath := filepath.Join(dataRoot, ".nodejs")
requireSymlinks := settings.Global().RequireActivationSymlinks

switch mode {
case "shim":
if activationLinkMatches(nodejsPath, shimDir) {
if activationLinkOK(nodejsPath, shimDir, requireSymlinks) {
return nil
}
if err := link.Link(shimDir, nodejsPath); err != nil {
return fmt.Errorf("failed to ensure .nodejs junction: %w", err)
return fmt.Errorf("failed to ensure .nodejs activation link: %w", err)
}
return nil

case "link":
linkNodePath := filepath.Join(dataRoot, ".link", "nodejs")
if version := strings.TrimSpace(activeVersion); version != "" {
versionDir := filepath.Join(installRoot, "v"+version)
if !activationLinkMatches(linkNodePath, versionDir) {
if !activationLinkOK(linkNodePath, versionDir, requireSymlinks) {
if err := ValidateVersionActivation(versionDir); err != nil {
return err
}
Expand All @@ -153,11 +154,11 @@ func ensureActivationLink(mode, dataRoot, installRoot, shimDir, activeVersion st
}
}

if activationLinkMatches(nodejsPath, linkNodePath) {
if activationLinkOK(nodejsPath, linkNodePath, requireSymlinks) {
return nil
}
if err := link.Link(linkNodePath, nodejsPath); err != nil {
return fmt.Errorf("failed to ensure .nodejs junction: %w", err)
return fmt.Errorf("failed to ensure .nodejs activation link: %w", err)
}
return nil

Expand All @@ -166,6 +167,18 @@ func ensureActivationLink(mode, dataRoot, installRoot, shimDir, activeVersion st
}
}

// activationLinkOK is true when the link points at expectedTarget and, when
// RequireActivationSymlinks is set, is not still a mount-point junction.
func activationLinkOK(linkPath, expectedTarget string, requireSymlinks bool) bool {
if !activationLinkMatches(linkPath, expectedTarget) {
return false
}
if requireSymlinks && link.IsMountPointJunction(linkPath) {
return false
}
return true
}

func activationLinkMatches(linkPath, expectedTarget string) bool {
linkPath = filepath.Clean(linkPath)
expectedTarget = filepath.Clean(expectedTarget)
Expand Down
43 changes: 43 additions & 0 deletions src/bootstrap/activation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
package bootstrap

import (
"common/settings"
"errors"
"nvm/link"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -91,3 +93,44 @@ func stubActivationBlockedLog(t *testing.T, replacement func(string, string, str
logActivationBlocked = replacement
t.Cleanup(func() { logActivationBlocked = original })
}

func TestEnsureActivationLinkMigratesJunctionWhenRequireSymlinks(t *testing.T) {
root := t.TempDir()
shimDir := filepath.Join(root, ".shim")
if err := os.MkdirAll(shimDir, 0755); err != nil {
t.Fatalf("MkdirAll(.shim) error = %v", err)
}
if err := os.WriteFile(filepath.Join(shimDir, "node.exe"), []byte("shim"), 0644); err != nil {
t.Fatalf("WriteFile(.shim\\node.exe) error = %v", err)
}
nodejsPath := filepath.Join(root, ".nodejs")
if err := link.NewJunction(shimDir, nodejsPath); err != nil {
t.Fatalf("NewJunction(.nodejs) error = %v", err)
}
if !link.IsMountPointJunction(nodejsPath) {
t.Fatal("precondition: .nodejs should be a junction")
}

if err := settings.Put("require_activation_symlinks", true); err != nil {
t.Fatalf("Put(require_activation_symlinks) error = %v", err)
}
settings.Load(true)
t.Cleanup(func() {
_ = settings.Put("require_activation_symlinks", false)
settings.Load(true)
})

if err := ensureActivationLink("shim", root, filepath.Join(root, "installs"), shimDir, ""); err != nil {
t.Fatalf("ensureActivationLink() error = %v", err)
}
if link.IsMountPointJunction(nodejsPath) {
t.Fatal(".nodejs should have been recreated as a symlink")
}
info, err := os.Lstat(nodejsPath)
if err != nil {
t.Fatalf("Lstat(.nodejs) error = %v", err)
}
if info.Mode()&os.ModeSymlink == 0 {
t.Fatalf(".nodejs mode = %v, want symlink", info.Mode())
}
}
88 changes: 68 additions & 20 deletions src/link/link.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,29 +39,36 @@ func hideNodejsLink(path string) {
_ = windows.SetFileAttributes(ptr, attrs|windows.FILE_ATTRIBUTE_HIDDEN)
}

// Link attempts to create an NTFS junction, falling back to
// a symlink if junction creation fails (e.g. on non-NTFS volumes/UNC paths).
func Link(source, symlink string) error {
// Remove whatever already exists at the symlink path (previous junction, symlink, or empty dir).
if _, err := os.Lstat(symlink); err == nil {
if err := os.Remove(symlink); err != nil {
err = fmt.Errorf("failed to remove existing link %s: %w", symlink, err)
// Link creates an activation link at symlink pointing at source.
// By default it tries an NTFS junction, then falls back to a symlink.
// When settings.RequireActivationSymlinks is true (certified OpenSSH /
// Redirection Guard), only a symlink is created.
func Link(source, symlinkPath string) error {
// Remove whatever already exists at the path (previous junction, symlink, or empty dir).
if _, err := os.Lstat(symlinkPath); err == nil {
if err := os.Remove(symlinkPath); err != nil {
err = fmt.Errorf("failed to remove existing link %s: %w", symlinkPath, err)
log.Error(err)
return err
}
}

// Attempt NTFS junction creation
if err := NewJunction(source, symlink); err == nil {
hideNodejsLink(symlink)
return nil
requireSymlink := settings.Global().RequireActivationSymlinks
if !requireSymlink {
if err := NewJunction(source, symlinkPath); err == nil {
hideNodejsLink(symlinkPath)
return nil
}
}

// Fallback to symlink (requires Developer Mode).
if err := os.Symlink(source, symlink); err != nil {
val, _, err := registry.Get("HKLM/SOFTWARE/Microsoft/Windows/CurrentVersion/AppModelUnlock/AllowDevelopmentWithoutDevLicense")
if err != nil {
err = fmt.Errorf("failed to get developer mode setting: %w", err)
return createSymlink(source, symlinkPath)
}

func createSymlink(source, symlinkPath string) error {
if err := os.Symlink(source, symlinkPath); err != nil {
val, _, getErr := registry.Get("HKLM/SOFTWARE/Microsoft/Windows/CurrentVersion/AppModelUnlock/AllowDevelopmentWithoutDevLicense")
if getErr != nil {
err = fmt.Errorf("failed to get developer mode setting: %w", getErr)
log.Error(err)
return err
}
Expand All @@ -79,23 +86,64 @@ func Link(source, symlink string) error {
}

if no_devmode {
// Trigger a notification to open settings to enable developer mode
// Critical setup toast: no collection (reserved nvm.setup).
notify.Send(settings.AppId, "Help Enabling Symlinks", "Developer Mode is required to use symlinks.",
notify.Action{Label: "Open Developer Settings", URL: "ms-settings:developers"},
)
}

log.Errorf("permission denied creating symlink (developer mode %v): %v", val, err)

return fmt.Errorf("permission denied")
}

hideNodejsLink(symlink)

hideNodejsLink(symlinkPath)
return nil
}

// IsMountPointJunction reports whether path is an NTFS mount-point junction
// (IO_REPARSE_TAG_MOUNT_POINT), not a symlink.
func IsMountPointJunction(path string) bool {
ptr, err := windows.UTF16PtrFromString(path)
if err != nil {
return false
}
attrs, err := windows.GetFileAttributes(ptr)
if err != nil {
return false
}
if attrs&windows.FILE_ATTRIBUTE_REPARSE_POINT == 0 {
return false
}

handle, err := windows.CreateFile(
ptr,
windows.GENERIC_READ,
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,
nil,
windows.OPEN_EXISTING,
windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OPEN_REPARSE_POINT,
0,
)
if err != nil {
return false
}
defer windows.CloseHandle(handle)

// Microsoft reparse buffer: first DWORD is ReparseTag.
buf := make([]byte, 16*1024)
var n uint32
const fsctlGetReparsePoint = 0x000900A8
if err := windows.DeviceIoControl(handle, fsctlGetReparsePoint, nil, 0, &buf[0], uint32(len(buf)), &n, nil); err != nil {
return false
}
if n < 4 {
return false
}
tag := binary.LittleEndian.Uint32(buf[0:])
const ioReparseTagMountPoint = 0xA0000003
return tag == ioReparseTagMountPoint
}

func Unlink(target string) error {
return os.Remove(target)
}
Expand Down
77 changes: 77 additions & 0 deletions src/link/link_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package link

import (
"os"
"path/filepath"
"testing"

prefs "common/preferences"
"common/settings"
)

const linkTestRegistryRoot = "HKCU/Software/NVMTest/link_require_symlink"

func TestMain(m *testing.M) {
prefs.ROOT = linkTestRegistryRoot
prefs.ROOTS = []string{prefs.ROOT}
code := m.Run()
os.Exit(code)
}

func setRequireActivationSymlinks(t *testing.T, value bool) {
t.Helper()
if err := settings.Put("require_activation_symlinks", value); err != nil {
t.Fatalf("Put(require_activation_symlinks) error = %v", err)
}
settings.Load(true)
}

func TestLinkRequireActivationSymlinksCreatesSymlink(t *testing.T) {
setRequireActivationSymlinks(t, true)
t.Cleanup(func() { setRequireActivationSymlinks(t, false) })

root := t.TempDir()
source := filepath.Join(root, "target")
if err := os.MkdirAll(source, 0755); err != nil {
t.Fatalf("MkdirAll(source) error = %v", err)
}
if err := os.WriteFile(filepath.Join(source, "node.exe"), []byte("x"), 0644); err != nil {
t.Fatalf("WriteFile(node.exe) error = %v", err)
}
dest := filepath.Join(root, ".nodejs")

if err := Link(source, dest); err != nil {
t.Fatalf("Link() error = %v", err)
}
if IsMountPointJunction(dest) {
t.Fatal("expected symlink, got mount-point junction")
}
info, err := os.Lstat(dest)
if err != nil {
t.Fatalf("Lstat(dest) error = %v", err)
}
if info.Mode()&os.ModeSymlink == 0 {
t.Fatalf("dest mode = %v, want symlink", info.Mode())
}
}

func TestLinkDefaultCreatesJunctionWhenPossible(t *testing.T) {
setRequireActivationSymlinks(t, false)

root := t.TempDir()
source := filepath.Join(root, "target")
if err := os.MkdirAll(source, 0755); err != nil {
t.Fatalf("MkdirAll(source) error = %v", err)
}
if err := os.WriteFile(filepath.Join(source, "node.exe"), []byte("x"), 0644); err != nil {
t.Fatalf("WriteFile(node.exe) error = %v", err)
}
dest := filepath.Join(root, ".nodejs")

if err := Link(source, dest); err != nil {
t.Fatalf("Link() error = %v", err)
}
if !IsMountPointJunction(dest) {
t.Fatal("expected mount-point junction when RequireActivationSymlinks is false")
}
}
Loading