Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

feat(desktop): install NectarLink in a folder of your choice (#102)

Bee96d6eaa21765
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a79e492..a86565b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -176,9 +176,13 @@ has a Stop button. Choosing another
or folders in Nemo (Cinnamon) or Thunar (XFCE) as well as GNOME Files,
Dolphin and Caja, and folders now work in all of them
([#49](https://github.com/thtbee/nectarlink/issues/49)).
-- **Setup on Windows asks about the desktop shortcut.** Untick **Add a
- desktop shortcut** to skip it. Updates leave it as you had it, so one
- you deleted no longer comes back
+- **Setup on Windows asks about the desktop shortcut and the folder.**
+ Untick **Add a desktop shortcut** to skip it. Updates leave it as you
+ had it, so one you deleted no longer comes back. **Change** next to
+ **Installs in** puts NectarLink on another drive or folder instead of
+ Program Files, and updates go there too. Setup locks the folder like
+ Program Files. If a folder above it can be changed without
+ administrator rights, updates there ask for your permission each time
([#102](https://github.com/thtbee/nectarlink/issues/102)).
- **Files received on Windows are marked as from another device,** the way
a browser marks a download, so Windows checks a program with SmartScreen
diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.toml
index ec737ef..9e4dddd 100644
--- a/desktop/app/Cargo.toml
+++ b/desktop/app/Cargo.toml
@@ -80,6 +80,7 @@ windows = { workspace = true, features = [
"Win32_System_IO",
"Win32_System_LibraryLoader",
"Win32_Security",
+ "Win32_Security_Authorization",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
"Win32_System_DataExchange",
diff --git a/desktop/app/i18n/rust_strings.h b/desktop/app/i18n/rust_strings.h
index c722782..21b675f 100644
--- a/desktop/app/i18n/rust_strings.h
+++ b/desktop/app/i18n/rust_strings.h
@@ -439,12 +439,20 @@ static const char *const nectarlink_rust_strings[] = {
QT_TRANSLATE_NOOP("SendTo", "Sent to %1"), // desktop/app/src/send_to.rs
QT_TRANSLATE_NOOP("SendTo", "The transfer didn't go through."), // desktop/app/src/send_to.rs
QT_TRANSLATE_NOOP("SendTo", "Waiting for %1…"), // desktop/app/src/send_to.rs
+ QT_TRANSLATE_NOOP("Setup", "Choose a folder on a drive inside this PC, not a USB or network drive."), // desktop/app/src/win/install_dir.rs
+ QT_TRANSLATE_NOOP("Setup", "Choose a folder on one of this PC's drives."), // desktop/app/src/win/install_dir.rs
QT_TRANSLATE_NOOP("Setup", "Couldn't start setup: %1"), // desktop/app/src/setup.rs
QT_TRANSLATE_NOOP("Setup", "Couldn't uninstall NectarLink: %1"), // desktop/app/src/setup.rs
+ QT_TRANSLATE_NOOP("Setup", "Setup can't use that folder. Choose another one."), // desktop/app/src/win/install_dir.rs
QT_TRANSLATE_NOOP("Setup", "Setup is taking too long. Try again after restarting the PC."), // desktop/app/src/setup.rs
QT_TRANSLATE_NOOP("Setup", "Setup stopped with code %1."), // desktop/app/src/setup.rs
+ QT_TRANSLATE_NOOP("Setup", "That drive can't keep the app's files safe (it isn't NTFS). Choose another drive."), // desktop/app/src/win/install_dir.rs
+ QT_TRANSLATE_NOOP("Setup", "That folder's path is too long. Choose one closer to the top of a drive."), // desktop/app/src/win/install_dir.rs
QT_TRANSLATE_NOOP("Setup", "The uninstaller is missing. Reinstall NectarLink, then uninstall it."), // desktop/app/src/setup.rs
+ QT_TRANSLATE_NOOP("Setup", "There's a file named %1 there. Choose another place."), // desktop/app/src/win/install_dir.rs
+ QT_TRANSLATE_NOOP("Setup", "There's already a %1 folder there with files in it. Choose another place."), // desktop/app/src/win/install_dir.rs
QT_TRANSLATE_NOOP("Setup", "Uninstall stopped with code %1."), // desktop/app/src/setup.rs
+ QT_TRANSLATE_NOOP("Setup", "Updates here will ask for your permission each time."), // desktop/app/src/bridge/setup.rs
QT_TRANSLATE_NOOP("Storage", "%1's files aren't shared with this PC"), // desktop/app/src/storage.rs
QT_TRANSLATE_NOOP("Storage", "On the phone, allow All files access for NectarLink."), // desktop/app/src/storage.rs
QT_TRANSLATE_NOOP("Storage", "On the phone, turn on Browse this phone's storage in File Explorer in NectarLink."), // desktop/app/src/storage.rs
diff --git a/desktop/app/qml/setup/SetupWindow.qml b/desktop/app/qml/setup/SetupWindow.qml
index b39bcb0..0bc7966 100644
--- a/desktop/app/qml/setup/SetupWindow.qml
+++ b/desktop/app/qml/setup/SetupWindow.qml
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import QtQuick
+import QtQuick.Dialogs
import QtQuick.Shapes
import app.nectarlink
@@ -61,6 +62,12 @@ NativeWindow {
Qt.quit()
}
+ FolderDialog {
+ id: dirPicker
+ title: qsTr("Install NectarLink in")
+ onAccepted: Setup.chooseDir(selectedFolder.toString())
+ }
+
function primary() {
if (window.phase === "welcome" || window.phase === "failed")
Setup.start()
@@ -366,6 +373,57 @@ NativeWindow {
}
}
+ // Where it goes (Windows; #102). A first install can pick another folder.
+ Item { width: 1; height: placeRow.visible ? 12 : 0 }
+ Row {
+ id: placeRow
+ visible: window.phase === "welcome" && !window.removing && Setup.installDir.length > 0
+ anchors.horizontalCenter: parent.horizontalCenter
+ spacing: 8
+ Text {
+ width: Math.min(implicitWidth, main.width - (changeDir.visible ? changeDir.implicitWidth + 8 : 0))
+ elide: Text.ElideMiddle
+ font.family: "Figtree"
+ font.pixelSize: 13
+ color: window.muted
+ text: qsTr("Installs in %1").arg(Setup.installDir)
+ }
+ Text {
+ id: changeDir
+ visible: Setup.canChooseDir
+ font.family: "Figtree"
+ font.pixelSize: 13
+ font.underline: changeArea.containsMouse || activeFocus
+ color: window.honey
+ text: qsTr("Change")
+ activeFocusOnTab: visible
+ Accessible.role: Accessible.Link
+ Accessible.name: qsTr("Change the install folder")
+ Accessible.onPressAction: dirPicker.open()
+ Keys.onSpacePressed: dirPicker.open()
+ Keys.onReturnPressed: dirPicker.open()
+ MouseArea {
+ id: changeArea
+ anchors.fill: parent
+ anchors.margins: -6
+ hoverEnabled: true
+ cursorShape: Qt.PointingHandCursor
+ onClicked: dirPicker.open()
+ }
+ }
+ }
+ Text {
+ visible: placeRow.visible && Setup.dirNote.length > 0
+ width: parent.width
+ topPadding: 4
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.WordWrap
+ font.family: "Figtree"
+ font.pixelSize: 12
+ color: Setup.dirRefused ? window.danger : window.muted
+ text: Setup.dirNote
+ }
+
Item { width: 1; height: shortcutChoice.visible ? 14 : 18 }
Text {
id: details
@@ -530,9 +588,9 @@ NativeWindow {
font.pixelSize: 14
color: window.muted
textFormat: Text.StyledText
- text: qsTr("NectarLink goes into Program Files for everyone on this PC. Setup also:")
+ text: qsTr("NectarLink goes into Program Files, or the folder you choose, for everyone on this PC. Setup also:")
+ "<br>&#8226; " + qsTr("allows it through Windows Firewall on private networks, so your phone can connect")
- + "<br>&#8226; " + qsTr("adds a task that installs updates without an administrator prompt")
+ + "<br>&#8226; " + qsTr("adds a task that installs updates without an administrator prompt, where only administrators can change the folder")
+ "<br>&#8226; " + qsTr("adds a Start menu shortcut, and a desktop one if you leave that ticked, and starts it with Windows (turn this off in Settings)")
+ "<br>&#8226; " + qsTr("adds it to the Windows Share sheet")
+ "<br><br>" + qsTr("It checks GitHub for updates once a day, which you can turn off in Settings. Otherwise your phone and PC only talk to each other.")
diff --git a/desktop/app/src/bridge/setup.rs b/desktop/app/src/bridge/setup.rs
index e11e765..c681b96 100644
--- a/desktop/app/src/bridge/setup.rs
+++ b/desktop/app/src/bridge/setup.rs
@@ -42,6 +42,14 @@ pub mod qobject {
#[qproperty(QString, android_url, cxx_name = "androidUrl")]
/// Windows: whether setup adds a desktop shortcut.
#[qproperty(bool, desktop_shortcut, cxx_name = "desktopShortcut")]
+ /// Windows, first installs: whether the user can pick the folder.
+ #[qproperty(bool, can_choose_dir, cxx_name = "canChooseDir")]
+ /// Where the app goes.
+ #[qproperty(QString, install_dir, cxx_name = "installDir")]
+ /// About the folder picked: that updates will ask, or why it can't be used.
+ #[qproperty(QString, dir_note, cxx_name = "dirNote")]
+ /// Whether `dir_note` says the folder can't be used.
+ #[qproperty(bool, dir_refused, cxx_name = "dirRefused")]
type Setup = super::SetupRust;
}
@@ -52,6 +60,10 @@ pub mod qobject {
/// Install, or remove, depending on the mode.
#[qinvokable]
fn start(self: Pin<&mut Setup>);
+ /// Checks a folder the user picked (a `file:` URL) and uses it if it's fine.
+ #[qinvokable]
+ #[cxx_name = "chooseDir"]
+ fn choose_dir(self: Pin<&mut Setup>, url: &QString);
#[qinvokable]
#[cxx_name = "openApp"]
fn open_app(self: &Setup);
@@ -80,11 +92,17 @@ pub struct SetupRust {
qr_url: QString,
android_url: QString,
desktop_shortcut: bool,
+ can_choose_dir: bool,
+ install_dir: QString,
+ dir_note: QString,
+ dir_refused: bool,
}
static MODE: OnceLock<Mode> = OnceLock::new();
/// Where the app ended up, for Open NectarLink.
static INSTALLED_DIR: Mutex<Option<PathBuf>> = Mutex::new(None);
+/// The folder the user picked, when not Program Files.
+static PLACEMENT: Mutex<Option<setup::Placement>> = Mutex::new(None);
/// Sets what the window is for, before QML loads.
pub fn set_mode(mode: Mode) {
@@ -124,6 +142,15 @@ impl cxx_qt::Initialize for qobject::Setup {
self.as_mut().set_kind(QString::from(kind));
// A first install adds it; otherwise it stays as the user left it.
self.as_mut().set_desktop_shortcut(kind == "fresh" || setup::has_desktop_shortcut());
+ // An installed copy is updated where it is.
+ #[cfg(windows)]
+ {
+ let dir = installed
+ .as_ref()
+ .map_or_else(crate::win::install_dir::default_dir, |i| i.dir.clone());
+ self.as_mut().set_install_dir(QString::from(&dir.display().to_string()));
+ self.as_mut().set_can_choose_dir(kind == "fresh");
+ }
self.as_mut().set_mode(QString::from("install"));
}
}
@@ -135,6 +162,7 @@ impl cxx_qt::Initialize for qobject::Setup {
self.as_mut().set_dark(theme == "dark");
}
if let Ok(kind) = std::env::var("NECTARLINK_SETUP_KIND") {
+ self.as_mut().set_can_choose_dir(cfg!(windows) && kind == "fresh");
self.as_mut().set_kind(QString::from(&kind));
self.as_mut().set_installed_version(QString::from("0.1.0"));
}
@@ -168,6 +196,7 @@ impl qobject::Setup {
self.as_mut().set_progress(0.02);
let removing = matches!(mode, Mode::Remove { .. });
let desktop_shortcut = *self.desktop_shortcut();
+ let placement = PLACEMENT.lock().unwrap_or_else(|e| e.into_inner()).clone();
self.as_mut().set_step(QString::from("Waiting for permission"));
let qt = self.qt_thread();
std::thread::spawn(move || {
@@ -181,7 +210,9 @@ impl qobject::Setup {
}
};
let outcome = match &mode {
- Mode::Install { installer } => setup::install(installer, desktop_shortcut, report),
+ Mode::Install { installer } => {
+ setup::install(installer, desktop_shortcut, placement.as_ref(), report)
+ }
Mode::Remove { installed } => setup::remove(installed, report),
};
if outcome == Outcome::Done && !removing {
@@ -209,6 +240,49 @@ impl qobject::Setup {
});
}
+ pub fn choose_dir(mut self: Pin<&mut Self>, url: &QString) {
+ if !*self.can_choose_dir() {
+ return;
+ }
+ let Some(chosen) = cxx_qt_lib::QUrl::from(url).to_local_file().map(|p| String::from(&p)) else {
+ return;
+ };
+ #[cfg(windows)]
+ {
+ use crate::win::install_dir;
+ let chosen = PathBuf::from(chosen.replace('/', "\\"));
+ let default = install_dir::default_dir();
+ // Program Files: back to the installer's own default.
+ let result = if install_dir::target_dir(&chosen).as_os_str().eq_ignore_ascii_case(&default) {
+ Ok(None)
+ } else {
+ install_dir::check(&chosen).map(Some)
+ };
+ match result {
+ Ok(placement) => {
+ let dir = placement.as_ref().map_or(&default, |p| &p.dir);
+ self.as_mut().set_install_dir(QString::from(&dir.display().to_string()));
+ self.as_mut().set_dir_refused(false);
+ self.as_mut().set_dir_note(if placement.as_ref().is_none_or(|p| p.admin_only) {
+ QString::default()
+ } else {
+ QString::from(&crate::i18n::tr!(
+ "Setup",
+ "Updates here will ask for your permission each time."
+ ))
+ });
+ *PLACEMENT.lock().unwrap_or_else(|e| e.into_inner()) = placement;
+ }
+ Err(reason) => {
+ self.as_mut().set_dir_refused(true);
+ self.as_mut().set_dir_note(QString::from(&reason));
+ }
+ }
+ }
+ #[cfg(not(windows))]
+ let _ = (self.as_mut(), chosen);
+ }
+
pub fn open_app(&self) {
let dir = INSTALLED_DIR.lock().unwrap_or_else(|e| e.into_inner()).clone();
if let Some(dir) = dir
diff --git a/desktop/app/src/setup.rs b/desktop/app/src/setup.rs
index b029ba8..a8a1fb6 100644
--- a/desktop/app/src/setup.rs
+++ b/desktop/app/src/setup.rs
@@ -237,6 +237,15 @@ pub fn parse_event(line: &str) -> Option<Event> {
Some(Event::Step(step))
}
+/// Where setup puts the app, when the user picks a folder (Windows, #102).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Placement {
+ pub dir: PathBuf,
+ /// Only administrators can change any folder on the way to `dir`, so
+ /// updates can run without asking.
+ pub admin_only: bool,
+}
+
/// How a run ended.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Outcome {
@@ -258,16 +267,41 @@ pub fn has_desktop_shortcut() -> bool {
false
}
-/// Installs from `installer` with administrator rights, reporting each step.
+/// Installs from `installer` with administrator rights, reporting each step:
+/// into Program Files, or where `placement` says.
#[cfg(windows)]
-pub fn install(installer: &Path, desktop_shortcut: bool, on_event: impl FnMut(Event)) -> Outcome {
+pub fn install(
+ installer: &Path,
+ desktop_shortcut: bool,
+ placement: Option<&Placement>,
+ on_event: impl FnMut(Event),
+) -> Outcome {
let progress = progress_file("install");
- let params = format!("/S /DESKTOP={} /PROGRESS={}", u8::from(desktop_shortcut), progress.display());
+ let params = install_params(desktop_shortcut, placement, &progress);
run_tracked(installer, &params, &progress, Duration::from_secs(600), true, on_event)
}
+/// The installer's switches. NSIS takes `/D=` last and unquoted, spaces and all.
+#[cfg(any(windows, test))]
+fn install_params(desktop_shortcut: bool, placement: Option<&Placement>, progress: &Path) -> String {
+ let mut params = format!("/S /DESKTOP={} /PROGRESS={}", u8::from(desktop_shortcut), progress.display());
+ if let Some(placement) = placement {
+ params.push_str(&format!(
+ " /ADMINONLY={} /D={}",
+ u8::from(placement.admin_only),
+ placement.dir.display()
+ ));
+ }
+ params
+}
+
#[cfg(target_os = "linux")]
-pub fn install(installer: &Path, _desktop_shortcut: bool, mut on_event: impl FnMut(Event)) -> Outcome {
+pub fn install(
+ installer: &Path,
+ _desktop_shortcut: bool,
+ _placement: Option<&Placement>,
+ mut on_event: impl FnMut(Event),
+) -> Outcome {
let name = installer.file_name().and_then(|s| s.to_str()).unwrap_or_default();
if name.ends_with(".deb") {
on_event(Event::Step(Step::Closing));
@@ -318,7 +352,12 @@ pub fn install(installer: &Path, _desktop_shortcut: bool, mut on_event: impl FnM
/// The app installs from a disk image on macOS, not through this setup.
#[cfg(not(any(windows, target_os = "linux")))]
-pub fn install(installer: &Path, _desktop_shortcut: bool, _on_event: impl FnMut(Event)) -> Outcome {
+pub fn install(
+ installer: &Path,
+ _desktop_shortcut: bool,
+ _placement: Option<&Placement>,
+ _on_event: impl FnMut(Event),
+) -> Outcome {
Outcome::Failed(tr!("Setup", "Couldn't start setup: %1", installer.display()))
}
@@ -690,6 +729,17 @@ pub fn icon_url(size: usize) -> String {
mod tests {
use super::*;
+ #[test]
+ fn a_chosen_folder_goes_last_for_nsis() {
+ let progress = Path::new("p.txt");
+ assert_eq!(install_params(true, None, progress), "/S /DESKTOP=1 /PROGRESS=p.txt");
+ let placement = Placement { dir: PathBuf::from(r"D:\My Apps\Nectarlink"), admin_only: false };
+ assert_eq!(
+ install_params(false, Some(&placement), progress),
+ r"/S /DESKTOP=0 /PROGRESS=p.txt /ADMINONLY=0 /D=D:\My Apps\Nectarlink"
+ );
+ }
+
#[test]
fn progress_lines_parse() {
assert_eq!(parse_event("step files"), Some(Event::Step(Step::Files)));
diff --git a/desktop/app/src/win/autostart.rs b/desktop/app/src/win/autostart.rs
index 9d26a5c..2c9ca0f 100644
--- a/desktop/app/src/win/autostart.rs
+++ b/desktop/app/src/win/autostart.rs
@@ -55,14 +55,26 @@ pub fn set(enabled: bool, exe: &Path) -> windows::core::Result<()> {
result
}
-/// Whether an executable is an installed copy (under Program Files), as
-/// opposed to a build being run from its folder.
+/// Whether an executable is an installed copy (under Program Files, or in
+/// the folder setup installed it to), as opposed to a build being run from
+/// its folder.
pub fn is_installed(exe: &Path) -> bool {
+ let installed_to = super::reg_string(
+ windows::Win32::System::Registry::HKEY_LOCAL_MACHINE,
+ r"Software\Nectarlink",
+ "InstallDir",
+ );
+ is_installed_in(exe, installed_to.as_deref())
+}
+
+fn is_installed_in(exe: &Path, installed_to: Option<&str>) -> bool {
let exe = exe.to_string_lossy().to_lowercase();
+ let under = |dir: &str| exe.starts_with(&format!("{}\\", dir.to_lowercase().trim_end_matches('\\')));
["ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"]
.iter()
.filter_map(|var| std::env::var(var).ok())
- .any(|dir| exe.starts_with(&format!("{}\\", dir.to_lowercase().trim_end_matches('\\'))))
+ .any(|dir| under(&dir))
+ || installed_to.is_some_and(|dir| !dir.trim().is_empty() && under(dir))
}
#[cfg(test)]
@@ -86,4 +98,14 @@ mod tests {
assert!(is_installed(&Path::new(&dir).join("Nectarlink").join("nectarlink-desktop.exe")));
}
}
+
+ #[test]
+ fn a_copy_in_the_folder_setup_chose_is_installed() {
+ let exe = Path::new(r"D:\Apps\Nectarlink\nectarlink-desktop.exe");
+ assert!(is_installed_in(exe, Some(r"d:\apps\nectarlink")));
+ assert!(is_installed_in(exe, Some(r"D:\Apps\Nectarlink\")));
+ assert!(!is_installed_in(exe, Some(r"D:\Apps\Nectar")));
+ assert!(!is_installed_in(exe, Some("")));
+ assert!(!is_installed_in(exe, None));
+ }
}
diff --git a/desktop/app/src/win/install_dir.rs b/desktop/app/src/win/install_dir.rs
new file mode 100644
index 0000000..b5ad388
--- /dev/null
+++ b/desktop/app/src/win/install_dir.rs
@@ -0,0 +1,302 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Where setup installs the app (#102): Program Files by default, or a
+//! folder the user picks.
+//!
+//! Updates run a task as SYSTEM that starts `nectarlink-desktop.exe` from the
+//! install folder, and the installer runs it with administrator rights to
+//! close the old copy. That's only safe where nobody but administrators can
+//! change what's at that path. The installer locks the install folder (and
+//! any folder it creates on the way) the way Program Files is locked, but a
+//! folder above it that a normal user can rename lets them put their own
+//! folder of the same name in its place. So setup checks every folder above
+//! the install folder: when all of them are admin-only, updates stay silent;
+//! otherwise there's no update task and updates ask for permission.
+
+use std::path::{Component, Path, PathBuf, Prefix};
+
+use windows::{
+ Win32::{
+ Foundation::{ERROR_SUCCESS, HLOCAL, LocalFree},
+ Security::{
+ ACCESS_ALLOWED_ACE, ACE_HEADER, ACL,
+ Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
+ DACL_SECURITY_INFORMATION, GetAce, OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID,
+ },
+ Storage::FileSystem::{GetDriveTypeW, GetVolumeInformationW},
+ },
+ core::{HSTRING, PWSTR},
+};
+
+use crate::{i18n::tr, setup::Placement};
+
+/// The folder the app goes into inside the one the user picks.
+pub const FOLDER_NAME: &str = "Nectarlink";
+
+/// Longest install folder accepted: the app's deepest file adds about 90
+/// characters, and it has to stay under Windows' 260.
+const MAX_LEN: usize = 150;
+
+/// SYSTEM, Administrators and TrustedInstaller: the only owners, and the only
+/// ones allowed to delete, rename or re-permission a folder above the app.
+const TRUSTED: [&str; 3] =
+ ["S-1-5-18", "S-1-5-32-544", "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"];
+
+/// DELETE, WRITE_DAC, WRITE_OWNER, FILE_DELETE_CHILD and GENERIC_ALL: what
+/// lets someone remove or rename a folder, or its children, or give
+/// themselves that right.
+const TAKES_OVER: u32 = 0x0001_0000 | 0x0004_0000 | 0x0008_0000 | 0x0000_0040 | 0x1000_0000;
+
+const ACCESS_ALLOWED_ACE_TYPE: u8 = 0;
+const ACCESS_DENIED_ACE_TYPE: u8 = 1;
+const INHERIT_ONLY_ACE: u8 = 0x08;
+const DRIVE_FIXED: u32 = 3;
+
+/// Program Files, where the app goes unless the user picks somewhere else.
+pub fn default_dir() -> PathBuf {
+ let program_files = std::env::var_os("ProgramW6432")
+ .or_else(|| std::env::var_os("ProgramFiles"))
+ .map_or_else(|| PathBuf::from(r"C:\Program Files"), PathBuf::from);
+ program_files.join(FOLDER_NAME)
+}
+
+/// The install folder for a folder the user picked: a `Nectarlink` folder in
+/// it, unless they picked one with that name.
+pub fn target_dir(chosen: &Path) -> PathBuf {
+ let named = chosen.file_name().is_some_and(|name| name.eq_ignore_ascii_case(FOLDER_NAME));
+ if named { chosen.to_path_buf() } else { chosen.join(FOLDER_NAME) }
+}
+
+/// Checks a folder the user picked and says where the app would go, or, in
+/// words for the user, why it can't go there.
+pub fn check(chosen: &Path) -> Result<Placement, String> {
+ let dir = target_dir(chosen);
+ let Some(letter) = drive_letter(&dir) else {
+ return Err(tr!("Setup", "Choose a folder on one of this PC's drives."));
+ };
+ if dir.as_os_str().len() > MAX_LEN {
+ return Err(tr!("Setup", "That folder's path is too long. Choose one closer to the top of a drive."));
+ }
+ let root = format!("{letter}:\\");
+ // SAFETY: a null-terminated path to a drive's root.
+ if unsafe { GetDriveTypeW(&HSTRING::from(&root)) } != DRIVE_FIXED {
+ return Err(tr!("Setup", "Choose a folder on a drive inside this PC, not a USB or network drive."));
+ }
+ let mut fs = [0u16; 32];
+ // SAFETY: the buffer outlives the call, which writes at most its length.
+ let named =
+ unsafe { GetVolumeInformationW(&HSTRING::from(&root), None, None, None, None, Some(&mut fs)) };
+ let fs = String::from_utf16_lossy(&fs[..fs.iter().position(|&c| c == 0).unwrap_or(fs.len())]);
+ if named.is_err() || !(fs.eq_ignore_ascii_case("NTFS") || fs.eq_ignore_ascii_case("ReFS")) {
+ return Err(tr!(
+ "Setup",
+ "That drive can't keep the app's files safe (it isn't NTFS). Choose another drive."
+ ));
+ }
+ match std::fs::read_dir(&dir).map(|mut entries| entries.next().is_none()) {
+ Ok(false) => {
+ return Err(tr!(
+ "Setup",
+ "There's already a %1 folder there with files in it. Choose another place.",
+ FOLDER_NAME
+ ));
+ }
+ Ok(true) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(_) if dir.is_file() => {
+ return Err(tr!("Setup", "There's a file named %1 there. Choose another place.", FOLDER_NAME));
+ }
+ Err(_) => return Err(tr!("Setup", "Setup can't use that folder. Choose another one.")),
+ }
+ Ok(Placement { admin_only: path_is_admin_only(&dir), dir })
+}
+
+/// The drive letter of an absolute `X:\...` path; `None` for anything else
+/// (network shares, `\\?\` paths, relative paths).
+fn drive_letter(path: &Path) -> Option<char> {
+ let mut parts = path.components();
+ let Some(Component::Prefix(prefix)) = parts.next() else { return None };
+ let Prefix::Disk(letter) = prefix.kind() else { return None };
+ matches!(parts.next(), Some(Component::RootDir)).then_some(char::from(letter).to_ascii_uppercase())
+}
+
+/// Whether only administrators can delete, rename or re-permission each
+/// folder above `dir` that already exists (setup creates and locks the
+/// missing ones itself), up to the drive's root.
+fn path_is_admin_only(dir: &Path) -> bool {
+ dir.ancestors().skip(1).filter(|folder| folder.exists()).all(|folder| match security(folder) {
+ Some((owner, aces)) => admin_only(&owner, &aces),
+ None => false,
+ })
+}
+
+/// One entry of a folder's permissions.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct Ace {
+ pub kind: u8,
+ pub flags: u8,
+ pub sid: String,
+ pub mask: u32,
+}
+
+/// Whether a folder with this owner and these permissions can only be taken
+/// over by administrators. Deny entries are ignored (an allow could still be
+/// reached another way), and any entry this doesn't understand counts against.
+pub(crate) fn admin_only(owner: &str, aces: &[Ace]) -> bool {
+ TRUSTED.contains(&owner)
+ && aces.iter().all(|ace| match ace.kind {
+ ACCESS_DENIED_ACE_TYPE => true,
+ _ if ace.flags & INHERIT_ONLY_ACE != 0 => true,
+ ACCESS_ALLOWED_ACE_TYPE => TRUSTED.contains(&ace.sid.as_str()) || ace.mask & TAKES_OVER == 0,
+ _ => false,
+ })
+}
+
+/// A folder's owner and permissions, as SID strings. `None` when they can't
+/// be read, or when there are no permissions at all (a null DACL lets
+/// everyone do everything).
+fn security(folder: &Path) -> Option<(String, Vec<Ace>)> {
+ let mut owner = PSID::default();
+ let mut dacl: *mut ACL = std::ptr::null_mut();
+ let mut sd = PSECURITY_DESCRIPTOR::default();
+ // SAFETY: the out-pointers live across the call; `sd` owns what the
+ // others point into and is freed below.
+ let status = unsafe {
+ GetNamedSecurityInfoW(
+ &HSTRING::from(folder.as_os_str()),
+ SE_FILE_OBJECT,
+ OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
+ Some(&mut owner),
+ None,
+ Some(&mut dacl),
+ None,
+ &mut sd,
+ )
+ };
+ if status != ERROR_SUCCESS {
+ return None;
+ }
+ let result = (|| {
+ if dacl.is_null() {
+ return None;
+ }
+ let owner = sid_string(owner)?;
+ // SAFETY: `dacl` points to a valid ACL inside `sd`.
+ let count = unsafe { (*dacl).AceCount };
+ let mut aces = Vec::with_capacity(usize::from(count));
+ for index in 0..u32::from(count) {
+ let mut raw = std::ptr::null_mut();
+ // SAFETY: `index` is below the ACL's count; `raw` points into `sd`.
+ unsafe { GetAce(dacl, index, &mut raw) }.ok()?;
+ // SAFETY: every ACE starts with a header.
+ let header = unsafe { *(raw as *const ACE_HEADER) };
+ let ace = if matches!(header.AceType, ACCESS_ALLOWED_ACE_TYPE | ACCESS_DENIED_ACE_TYPE) {
+ // Allowed and denied entries share this layout: the SID
+ // starts at `SidStart`.
+ let entry = raw as *const ACCESS_ALLOWED_ACE;
+ // SAFETY: the type says it has this layout.
+ let (mask, sid) =
+ unsafe { ((*entry).Mask, PSID(std::ptr::addr_of!((*entry).SidStart) as *mut _)) };
+ Ace { kind: header.AceType, flags: header.AceFlags, sid: sid_string(sid)?, mask }
+ } else {
+ Ace { kind: header.AceType, flags: header.AceFlags, sid: String::new(), mask: 0 }
+ };
+ aces.push(ace);
+ }
+ Some((owner, aces))
+ })();
+ // SAFETY: `sd` came from GetNamedSecurityInfoW, which allocates with LocalAlloc.
+ unsafe {
+ let _ = LocalFree(Some(HLOCAL(sd.0)));
+ }
+ result
+}
+
+fn sid_string(sid: PSID) -> Option<String> {
+ let mut text = PWSTR::null();
+ // SAFETY: `sid` is a valid SID; the string is freed below.
+ unsafe { ConvertSidToStringSidW(sid, &mut text) }.ok()?;
+ // SAFETY: the call returned a null-terminated string.
+ let out = unsafe { text.to_string() }.ok();
+ // SAFETY: allocated by ConvertSidToStringSidW with LocalAlloc.
+ unsafe {
+ let _ = LocalFree(Some(HLOCAL(text.0.cast())));
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const USERS: &str = "S-1-5-32-545";
+ const AUTHENTICATED: &str = "S-1-5-11";
+ const SYSTEM: &str = "S-1-5-18";
+ const ADMINS: &str = "S-1-5-32-544";
+ const SOMEONE: &str = "S-1-5-21-1-2-3-1001";
+
+ fn allow(sid: &str, mask: u32) -> Ace {
+ Ace { kind: ACCESS_ALLOWED_ACE_TYPE, flags: 0, sid: sid.into(), mask }
+ }
+
+ #[test]
+ fn the_app_goes_in_its_own_folder() {
+ assert_eq!(target_dir(Path::new(r"D:\")), Path::new(r"D:\Nectarlink"));
+ assert_eq!(target_dir(Path::new(r"D:\Apps")), Path::new(r"D:\Apps\Nectarlink"));
+ assert_eq!(target_dir(Path::new(r"D:\Apps\nectarlink")), Path::new(r"D:\Apps\nectarlink"));
+ assert!(default_dir().ends_with(FOLDER_NAME));
+ }
+
+ #[test]
+ fn only_local_drive_paths_have_a_letter() {
+ assert_eq!(drive_letter(Path::new(r"d:\Apps\Nectarlink")), Some('D'));
+ assert_eq!(drive_letter(Path::new(r"\\server\share\Nectarlink")), None);
+ assert_eq!(drive_letter(Path::new(r"\\?\D:\Nectarlink")), None);
+ assert_eq!(drive_letter(Path::new(r"D:Nectarlink")), None);
+ assert_eq!(drive_letter(Path::new(r"Apps\Nectarlink")), None);
+ }
+
+ #[test]
+ fn a_drive_root_and_program_files_are_admin_only() {
+ // A fresh NTFS drive's root: everyone can add folders, nobody else can
+ // remove them; the modify entry only applies to what's inside.
+ let root = [
+ allow(SYSTEM, 0x1F01FF),
+ allow(ADMINS, 0x1F01FF),
+ allow(USERS, 0x1200A9),
+ allow(AUTHENTICATED, 0x0004),
+ Ace { kind: ACCESS_ALLOWED_ACE_TYPE, flags: 0x0B, sid: AUTHENTICATED.into(), mask: 0x1301BF },
+ Ace { kind: ACCESS_ALLOWED_ACE_TYPE, flags: 0x0B, sid: "S-1-3-0".into(), mask: 0x1000_0000 },
+ ];
+ assert!(admin_only(SYSTEM, &root));
+ assert!(admin_only(TRUSTED[2], &[allow(TRUSTED[2], 0x1F01FF), allow(USERS, 0x1200A9)]));
+ }
+
+ #[test]
+ fn a_folder_users_can_change_or_own_is_not() {
+ // A folder made on a drive's root inherits modify (with delete) for
+ // every signed-in user.
+ assert!(!admin_only(ADMINS, &[allow(ADMINS, 0x1F01FF), allow(AUTHENTICATED, 0x1301BF)]));
+ // One a user made is theirs, so they can change its permissions.
+ assert!(!admin_only(SOMEONE, &[allow(ADMINS, 0x1F01FF)]));
+ // Delete-child on a parent lets them rename the folder below it.
+ assert!(!admin_only(SYSTEM, &[allow(USERS, 0x40)]));
+ assert!(!admin_only(SYSTEM, &[allow(SOMEONE, 0x1000_0000)]));
+ // An entry of a kind this doesn't read counts against.
+ assert!(!admin_only(SYSTEM, &[Ace { kind: 9, flags: 0, sid: String::new(), mask: 0 }]));
+ // A deny entry doesn't make it unsafe.
+ assert!(admin_only(
+ SYSTEM,
+ &[Ace { kind: ACCESS_DENIED_ACE_TYPE, flags: 0, sid: USERS.into(), mask: 0x10000 }]
+ ));
+ }
+
+ #[test]
+ fn program_files_on_this_pc_is_admin_only() {
+ // The real thing, read from this PC: Program Files must pass, and a
+ // folder in the user's profile (theirs to change) must not.
+ assert!(path_is_admin_only(&default_dir()));
+ if let Some(home) = dirs::home_dir() {
+ assert!(!path_is_admin_only(&home.join("Apps").join(FOLDER_NAME)));
+ }
+ }
+}
diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rs
index 70996a2..cdded1b 100644
--- a/desktop/app/src/win/mod.rs
+++ b/desktop/app/src/win/mod.rs
@@ -19,6 +19,7 @@ pub mod http;
pub mod icon;
pub mod image;
pub mod input;
+pub mod install_dir;
pub mod jumplist;
pub mod media_sessions;
pub mod mp4;
diff --git a/desktop/installer/nectarlink.nsi b/desktop/installer/nectarlink.nsi
index 2d51cea..45b71ec 100644
--- a/desktop/installer/nectarlink.nsi
+++ b/desktop/installer/nectarlink.nsi
@@ -13,6 +13,15 @@
; step to the file; /RUN opens the app afterwards. Without administrator
; rights it asks for them (UAC) and carries on elevated.
;
+; The setup window can pick another folder (#102): /D=<folder> (last, as
+; NSIS wants) and /ADMINONLY=1 when only administrators can change the
+; folders above it. Updates go to the folder of the last install. The app's
+; update task runs it as SYSTEM, and installing runs the old copy to close
+; it, so that only happens where nobody else can swap the files: Program
+; Files, or a folder above which only administrators can change anything.
+; Elsewhere updates ask for permission instead. Folders setup creates
+; outside Program Files are locked like Program Files.
+;
; Installing for everyone lets it allow the app through Windows Firewall:
; otherwise Windows asks on first use, and people often say no.
;
@@ -68,6 +77,8 @@ Var ProgressFile
Var AppDir
; Where an earlier copy was installed, if there is one.
Var PreviousDir
+; 1 when only administrators can change $INSTDIR and the folders above it.
+Var AdminOnly
!macro Progress line
${If} $ProgressFile != ""
@@ -105,12 +116,21 @@ Function .onInit
${If} ${Silent}
StrCpy $Interactive 0
+ ; Without /D (an update): where the last install went. InstallDirRegKey
+ ; can't say, as it reads the 32-bit registry before SetRegView.
+ ${If} $INSTDIR == "$PROGRAMFILES64\${APP}"
+ ReadRegStr $0 HKLM "Software\${APP}" "InstallDir"
+ ${If} $0 != ""
+ StrCpy $INSTDIR $0
+ ${EndIf}
+ ${EndIf}
; Installing needs administrator rights: ask, and let the elevated copy
; do it. (The app's own updater runs as SYSTEM and has them already.)
+ ; NSIS takes /D off the command line, so it's passed on again.
UserInfo::GetAccountType
Pop $0
${If} $0 != "Admin"
- ExecShell "runas" '"$EXEPATH"' "$R0" SW_HIDE
+ ExecShell "runas" '"$EXEPATH"' "$R0 /D=$INSTDIR" SW_HIDE
SetErrorLevel 0
Quit
${EndIf}
@@ -124,6 +144,9 @@ FunctionEnd
Function un.onInit
SetRegView 64
SetShellVarContext all
+ ; The uninstaller came from the app's folder, so running the app from
+ ; there trusts nothing more than running the uninstaller did.
+ StrCpy $AdminOnly 1
${un.GetParameters} $R0
ClearErrors
${un.GetOptions} $R0 "/PROGRESS=" $ProgressFile
@@ -136,7 +159,10 @@ FunctionEnd
; for it, so its files can be replaced or removed. The setup and uninstall
; windows run under other names, so they're left alone.
!macro QuitRunningApp
- ${If} ${FileExists} "$INSTDIR\${EXE}"
+ ; Only where nobody else can have replaced it: this runs with
+ ; administrator rights.
+ ${If} $AdminOnly == 1
+ ${AndIf} ${FileExists} "$INSTDIR\${EXE}"
ExecWait '"$INSTDIR\${EXE}" --quit'
${EndIf}
StrCpy $R0 0
@@ -157,6 +183,81 @@ FunctionEnd
${Loop}
!macroend
+; Locks folder $R1 the way Program Files is: owned by administrators, which
+; SYSTEM and administrators may change and everyone else only read. Anything
+; in it before then could have been put there by someone else, so it must be
+; empty. Sets the error flag when it can't.
+Function LockFolder
+ nsExec::Exec 'icacls "$R1" /setowner *S-1-5-32-544'
+ Pop $0
+ ${If} $0 == 0
+ nsExec::Exec 'icacls "$R1" /reset'
+ Pop $0
+ ${EndIf}
+ ${If} $0 == 0
+ nsExec::Exec 'icacls "$R1" /inheritance:r /grant:r *S-1-5-18:(OI)(CI)F *S-1-5-32-544:(OI)(CI)F *S-1-5-32-545:(OI)(CI)RX *S-1-15-2-1:(OI)(CI)RX'
+ Pop $0
+ ${EndIf}
+ StrCpy $4 0
+ ${If} $0 == 0
+ FindFirst $2 $3 "$R1\*.*"
+ ${DoWhile} $3 != ""
+ ${If} $3 != "."
+ ${AndIf} $3 != ".."
+ StrCpy $4 1
+ ${Break}
+ ${EndIf}
+ FindNext $2 $3
+ ${Loop}
+ FindClose $2
+ ${EndIf}
+ ClearErrors
+ ${If} $0 != 0
+ ${OrIf} $4 == 1
+ SetErrors
+ ${EndIf}
+FunctionEnd
+
+; Creates $INSTDIR outside Program Files one folder at a time from the
+; first one that exists, locking each (LockFolder) before going in, so
+; nobody else can put anything on the way. Sets the error flag when it can't.
+Function CreateLockedInstallDir
+ StrCpy $R0 "$INSTDIR"
+ StrCpy $R2 0
+ ${Do}
+ ${If} ${FileExists} "$R0\*.*"
+ ${Break}
+ ${EndIf}
+ Push $R0
+ IntOp $R2 $R2 + 1
+ ${GetParent} "$R0" $R0
+ ${If} $R0 == ""
+ ${Break}
+ ${EndIf}
+ ${Loop}
+ ; The folder itself already there (empty, setup checked): lock it too.
+ ${If} $R2 == 0
+ Push "$INSTDIR"
+ StrCpy $R2 1
+ ${EndIf}
+ StrCpy $R3 0
+ ${DoWhile} $R2 > 0
+ Pop $R1
+ IntOp $R2 $R2 - 1
+ ${If} $R3 == 0
+ CreateDirectory "$R1"
+ Call LockFolder
+ ${If} ${Errors}
+ StrCpy $R3 1
+ ${EndIf}
+ ${EndIf}
+ ${Loop}
+ ClearErrors
+ ${If} $R3 == 1
+ SetErrors
+ ${EndIf}
+FunctionEnd
+
Function OpenApp
; Through Explorer, so the app runs as the user and not elevated.
Exec '"$WINDIR\explorer.exe" "$INSTDIR\${EXE}"'
@@ -168,6 +269,39 @@ Section "Install"
StrCpy $AppDir "$PLUGINSDIR\app"
${Else}
ReadRegStr $PreviousDir HKLM "Software\${APP}" "InstallDir"
+ ; Program Files is admin-only. Elsewhere: the setup window's check
+ ; (/ADMINONLY), or, for an update, what the last install found.
+ StrCpy $AdminOnly 0
+ StrLen $0 "$PROGRAMFILES64\"
+ StrCpy $1 "$INSTDIR" $0
+ StrLen $0 "$PROGRAMFILES\"
+ StrCpy $2 "$INSTDIR" $0
+ ${If} $1 == "$PROGRAMFILES64\"
+ ${OrIf} $2 == "$PROGRAMFILES\"
+ StrCpy $AdminOnly 1
+ ${Else}
+ ${GetParameters} $R0
+ ClearErrors
+ ${GetOptions} $R0 "/ADMINONLY=" $R1
+ ${If} ${Errors}
+ ${If} $INSTDIR == $PreviousDir
+ ReadRegDWORD $AdminOnly HKLM "Software\${APP}" "AdminOnlyFolder"
+ ${EndIf}
+ ${ElseIf} $R1 == 1
+ StrCpy $AdminOnly 1
+ ${EndIf}
+ ${If} $AdminOnly != 1
+ StrCpy $AdminOnly 0
+ ${EndIf}
+ ${If} $INSTDIR != $PreviousDir
+ Call CreateLockedInstallDir
+ ${If} ${Errors}
+ !insertmacro Progress "error Setup couldn't make that folder safe for NectarLink. Choose another folder."
+ SetErrorLevel 2
+ Quit
+ ${EndIf}
+ ${EndIf}
+ ${EndIf}
!insertmacro Progress "step closing"
!insertmacro QuitRunningApp
!insertmacro Progress "step files"
@@ -204,6 +338,11 @@ Section "Install"
; PowerShell, which security software can hold up without a word, leaving
; setup stuck at this step.
!insertmacro Progress "step updates"
+ ${If} $AdminOnly != 1
+ ; Updates ask for permission in this folder (see the top of this file).
+ nsExec::Exec 'schtasks /Delete /TN "Nectarlink Update" /F'
+ Goto updates_done
+ ${EndIf}
InitPluginsDir
FileOpen $0 "$PLUGINSDIR\update-task.xml" w
FileWriteUTF16LE /BOM $0 '<?xml version="1.0" encoding="UTF-16"?>$\r$\n'
@@ -229,6 +368,7 @@ Section "Install"
FileWriteUTF16LE $0 '</Task>$\r$\n'
FileClose $0
nsExec::Exec 'schtasks /Create /TN "Nectarlink Update" /XML "$PLUGINSDIR\update-task.xml" /F'
+ updates_done:
!insertmacro Progress "step shortcuts"
CreateShortCut "$SMPROGRAMS\${DISPLAY}.lnk" "$INSTDIR\${EXE}" "" "$INSTDIR\${EXE}" 0 "" "" "Your phone, on your PC"
@@ -258,6 +398,7 @@ Section "Install"
nsExec::Exec 'powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "try { Add-AppxPackage -Register \"$INSTDIR\AppxManifest.xml\" -ExternalLocation \"$INSTDIR\" -ErrorAction Stop } catch { $$_ | Out-File -Encoding utf8 \"$INSTDIR\sparse-package.log\" }"'
WriteRegStr HKLM "Software\${APP}" "InstallDir" "$INSTDIR"
+ WriteRegDWORD HKLM "Software\${APP}" "AdminOnlyFolder" $AdminOnly
WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayName" "${DISPLAY}"
WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayVersion" "${DISPLAY_VERSION}"
WriteRegStr HKLM "${UNINSTALL_KEY}" "Publisher" "The NectarLink contributors"
diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md
index 50e0704..c3c98a4 100644
--- a/docs/guide/getting-started.md
+++ b/docs/guide/getting-started.md
@@ -17,7 +17,7 @@ This guide walks you through installing NectarLink on Windows, Linux and Android
1. Download the latest Windows installer (`Nectarlink-<version>-x64-setup.exe` for Intel/AMD PCs or `Nectarlink-<version>-arm64-setup.exe` for Snapdragon/ARM64 PCs) from the project's GitHub Releases page.
2. Run the installer. The installer isn't code-signed yet, so Windows SmartScreen may show **Windows protected your PC**: choose **More info**, then **Run anyway**.
-3. Click **Install** and allow the administrator prompt. Setup installs NectarLink, registers the required Windows Firewall rule for local QUIC discovery and connections, adds a Start Menu shortcut (and a desktop one, unless you untick **Add a desktop shortcut**), and sets NectarLink to start in the system tray when you sign in (turn this off with **Start with Windows** in **Settings › General**). **What this installs** on the first screen lists everything it adds.
+3. Click **Install** and allow the administrator prompt. Setup installs NectarLink in Program Files; to put it somewhere else, such as another drive, click **Change** next to **Installs in** first. It goes into a new `Nectarlink` folder inside the one you pick, on a drive inside the PC (not USB or network). Updates install without asking in Program Files or at the top of a drive. In a folder that people without administrator rights can change, such as one you made yourself, updates ask for your permission instead, so nothing else can slip in its own files to run with full rights. Setup also registers the required Windows Firewall rule for local QUIC discovery and connections, adds a Start Menu shortcut (and a desktop one, unless you untick **Add a desktop shortcut**), and sets NectarLink to start in the system tray when you sign in (turn this off with **Start with Windows** in **Settings › General**). **What this installs** on the first screen lists everything it adds.
4. The last screen shows a QR code for the Android app's download page. Scan it with your phone's camera, then click **Open NectarLink**.
### On Linux
diff --git a/docs/technical/security-model.md b/docs/technical/security-model.md
index 622d6ba..38ab45f 100644
--- a/docs/technical/security-model.md
+++ b/docs/technical/security-model.md
@@ -122,6 +122,7 @@ Implemented in `desktop/app/src/updater.rs` (`win/http.rs`), `desktop/installer/
- **Endpoint**: Both apps query `https://api.github.com/repos/thtbee/nectarlink/releases/latest` over HTTPS with the OS TLS stack (`WinHTTP`, `HttpURLConnection`). Only `https://` URLs are fetched, redirects stay on HTTPS, and responses are size-capped while they are read. No device identifiers or telemetry are sent.
- **What is accepted**: a published release (not a draft or pre-release) whose version is newer than the running one, with an installer named `Nectarlink-*-x64-setup.exe` (Windows, a plain file name) or `*-android.apk`, and a `SHA256SUMS.txt` that lists it. The download is rejected unless its SHA-256 matches. Android additionally refuses an APK not signed with the app's own key.
- **Windows, installing without a prompt**: the app is installed per machine, so installing needs administrator rights. The installer registers the scheduled task **Nectarlink Update**, which runs `nectarlink-desktop.exe --update-service` as SYSTEM. Its security descriptor gives SYSTEM and Administrators full control and authenticated users read and execute only, so a signed-in user can start it but not change what it runs. The task takes no arguments or input from the user: it fetches the latest release itself and applies the checks above. When the user clicks **Update**, the app first downloads the installer itself (resumable, with progress) into `%ProgramData%\Nectarlink\updates` and checks it against the sums. The task copies that file into a new randomly named folder in `C:\Windows\SystemTemp` (writable only by SYSTEM and administrators) and checks the copy against the sums it fetched itself, so a file planted in the shared folder can only ever be the official installer. When there is no matching file, it downloads the installer into that folder itself. It then runs the installer with `/S` and logs to `update.log` in the install folder. The worst a user can do by starting it is install the latest official release early.
+- **Windows, a folder outside Program Files** (`win/install_dir.rs`): the task, and the installer closing the old copy, run `nectarlink-desktop.exe` from the install folder with full rights, so they only do so where nobody else can swap it. Setup creates the install folder, and any folder above it that's missing, one level at a time, and locks each like Program Files (owner Administrators; SYSTEM and Administrators full control, Users and app packages read and execute; refused unless empty after locking, so nothing planted before stays). A folder above that a normal user can rename would still let them put a folder of the same name in its place, so the setup window reads the owner and permissions of every existing folder up to the drive's root. When none can be deleted, renamed or re-permissioned by anyone but SYSTEM, Administrators or TrustedInstaller, the installer gets `/ADMINONLY=1` and registers the task; otherwise there's no task, the installer doesn't run the old copy (it ends it with `taskkill`), and updates use the UAC prompt. The result is kept in `HKLM\Software\Nectarlink\AdminOnlyFolder` for later updates. Only USB, network and non-NTFS/ReFS drives are refused outright.
- **Windows, when**: with **Install updates automatically** on, the app starts the task once nobody has used the PC for 10 minutes and nothing would be interrupted (mirroring, an app window, a transfer, a call, screen sharing, the webcam). It first starts a hidden relauncher, which reopens the app once the new version's `DisplayVersion` is in the uninstall key and the installer has exited, then quits. Without the task (copies installed before it existed) **Update** runs the installer with the usual UAC prompt.
- **Android**: with **Install updates automatically** on, the connection service checks in the background at most once a day and installs through `PackageInstaller` with `USER_ACTION_NOT_REQUIRED` (Android 12+, `UPDATE_PACKAGES_WITHOUT_USER_ACTION`). Android skips the prompt only when NectarLink installed the current version itself; otherwise the user confirms from a notification.
- **Opt-out**: **Check for updates** and **Install updates automatically** in Settings on both apps. With checks off, nothing is fetched.
diff --git a/scripts/smoke-installer.ps1 b/scripts/smoke-installer.ps1
index efc74c7..891d799 100644
--- a/scripts/smoke-installer.ps1
+++ b/scripts/smoke-installer.ps1
@@ -115,6 +115,57 @@ Check "the Start menu shortcut is gone" (-not (Test-Path $shortcut))
Check "the desktop shortcut is gone" (-not (Test-Path $desktopShortcut))
Check "the firewall rule is gone" (-not (FirewallRule))
Check "the update task is gone" ($null -eq (UpdateTask))
+
+# A folder the user picked (#102), with a space in it, as the setup window
+# passes it: /D last and unquoted. Its parent doesn't exist, so setup
+# creates both and locks them like Program Files.
+$top = 'C:\nl smoke'
+$custom = Join-Path $top 'Apps\Nectarlink'
+$customExe = Join-Path $custom 'nectarlink-desktop.exe'
+$reg = 'HKLM:\Software\Nectarlink'
+function Test-Locked($path) {
+ $acl = Get-Acl $path
+ $sd = New-Object System.Security.AccessControl.RawSecurityDescriptor $acl.Sddl
+ $acl.Owner -eq 'BUILTIN\Administrators' -and -not (Test-OthersMayWrite $sd)
+}
+Write-Host "Installing into $custom"
+Start-Process $Setup -ArgumentList "/S /ADMINONLY=1 /D=$custom" -Wait
+Check "the app is installed in the chosen folder" (Test-Path $customExe)
+Check "nothing went into Program Files" (-not (Test-Path $dir))
+Check "the chosen folder is locked like Program Files" (Test-Locked $custom)
+Check "the folder setup created above it is locked too" (Test-Locked $top)
+Check "an admin-only folder gets the update task" (
+ $null -ne ($task = UpdateTask) -and $task.Definition.Actions.Item(1).Path.Trim('"') -eq $customExe)
+Check "the chosen folder is remembered" ((Get-ItemProperty $reg).InstallDir -eq $custom -and (Get-ItemProperty $reg).AdminOnlyFolder -eq 1)
+Start-Process $Setup -ArgumentList '/S' -Wait
+Check "an update goes to the chosen folder" ((Test-Path $customExe) -and -not (Test-Path $dir))
+Check "an update keeps the update task" ($null -ne (UpdateTask))
+Start-Process (Join-Path $custom 'uninstall.exe') -ArgumentList '/S' -Wait
+$deadline = (Get-Date).AddSeconds(60)
+while ((Test-Path $custom) -and (Get-Date) -lt $deadline) { Start-Sleep 1 }
+Check "uninstalling removes the chosen folder" (-not (Test-Path $custom))
+Check "uninstalling removes the update task" ($null -eq (UpdateTask))
+
+# Where folders above it aren't admin-only: no task running it as SYSTEM.
+Start-Process $Setup -ArgumentList "/S /ADMINONLY=0 /D=$custom" -Wait
+Check "the app is installed there" (Test-Path $customExe)
+Check "a folder others could swap gets no update task" ($null -eq (UpdateTask))
+Check "updates there will ask" ((Get-ItemProperty $reg).AdminOnlyFolder -eq 0)
+Start-Process $Setup -ArgumentList '/S' -Wait
+Check "an update there still adds no update task" ($null -eq (UpdateTask))
+Start-Process (Join-Path $custom 'uninstall.exe') -ArgumentList '/S' -Wait
+$deadline = (Get-Date).AddSeconds(60)
+while ((Test-Path $custom) -and (Get-Date) -lt $deadline) { Start-Sleep 1 }
+Check "it uninstalls from there" (-not (Test-Path $custom))
+
+# A folder that already has files in it is refused.
+$busy = Join-Path $top 'Busy\Nectarlink'
+New-Item -ItemType Directory -Force $busy | Out-Null
+Set-Content (Join-Path $busy 'someone-elses.txt') 'x'
+$run = Start-Process $Setup -ArgumentList "/S /ADMINONLY=1 /D=$busy" -Wait -PassThru
+Check "a folder with files in it is refused" ($run.ExitCode -ne 0 -and -not (Test-Path (Join-Path $busy 'nectarlink-desktop.exe')))
+Check "a refused folder leaves no update task" ($null -eq (UpdateTask))
+Remove-Item -Recurse -Force $top
Write-Host "Installer smoke test passed."
# netsh reports "no rules match" with a failing exit code; that was the point.
exit 0