Author SHA1 Message Date
Andy Dixon 6ac02cdda5 packaging: publish nexusterminal to repo.dixon.cx and Homebrew; install instructions
- packaging/repo.sh: download release assets over HTTPS (no GitHub API),
  show nfpm errors, PKGREL for packaging-only revisions, and declare ALSA
  as a hard dependency (the release binary links libasound.so.2), with
  libasound2t64 preferred so Ubuntu 24.04 doesn't pick the OSS shim.
  Verified by clean installs on Debian 12/13, Ubuntu 22.04/24.04,
  Fedora 42 and Arch.
- README: Install section (Homebrew cask, apt, dnf/zypper, pacman, zips).
2026-10-13 13:57:25 +01:00
Andy Dixon 7671826fdf release: zip Windows artefacts with 7-Zip or PowerShell when zip isn't installed (GitHub's Windows runners have no zip) 2026-10-13 13:16:25 +01:00
Andy Dixon 35ddd1010a fix(test): gate the serial tests' mpsc import on Linux like the tests that use it (macOS clippy) 2026-10-13 12:24:32 +01:00
Andy Dixon ccce883612 ci: install rustfmt and clippy with the pinned toolchain (CI's fmt/clippy steps failed: component not installed) 2026-10-13 11:54:50 +01:00
Andy Dixon 95601525a8 ci: build darwin/amd64 on macos-15-intel (macos-13 runners are retired; the job never started) 2026-10-13 11:37:30 +01:00
Andy Dixon 73c1f77ca3 fix: macOS and Windows test/lint failures; repo.dixon.cx packaging for nexusterminal
CI hadn't run on macOS or Windows for a while (billing); once it did:
- Windows: the RDP shared-drive code and its symlink test are Unix-only
  but were compiled there (and the unused pieces failed clippy). The drive
  type, its impls, imports and test are now cfg(unix); refusing a drive
  request is a free function used everywhere. Other Windows-only warnings
  fixed (serial test import, unused mut, harden_process).
- macOS: the local shell's directory was sampled on the first output
  after Enter, which is the shell echoing the command before a cd runs,
  so restored tabs opened one directory behind. It's now sampled shortly
  after Enter and again once the command has had time to finish.
- packaging/repo.sh publishes the 'nexusterminal' .deb/.rpm/Arch packages
  to repo.dixon.cx from the release's own Linux binaries, verified
  against SHA256SUMS.
- The desktop entry mentions RDP.
2026-10-13 11:36:45 +01:00
Andy Dixon 9805681c2c license: release Nexus Terminal under the GNU AGPL v3
- LICENSE: the GNU Affero General Public License, version 3 (verbatim
  from gnu.org).
- SPDX-License-Identifier: AGPL-3.0-only plus a copyright line on every
  first-party source file (Rust, shell, Python, PHP); vendored crates keep
  their own licenses.
- Cargo manifests carry license/authors/repository; the macOS bundle
  copyright and the About page state the license and link the source.
- Release zips (and the macOS app bundle) include LICENSE.
- README: License section.
2026-10-13 09:46:31 +01:00
Andy Dixon ee7f831d32 release: 3.0.2
Security and robustness fixes from the 2026-10-12 audit
(audits/20261012-2201-securityAudit.md).
2026-10-13 08:32:21 +01:00
Andy Dixon ee1734c316 docs: security audit and next-steps report (2026-10-12 22:01); rebuild guide PDF 2026-10-13 07:06:07 +01:00
Andy Dixon c8ab4d6557 fix: forget saved credentials when a synced/imported profile is retargeted; --answer needs --screenshot
- Saved credentials are keyed by profile id. A sync peer (or a crafted
  import using 'overwrite') could keep an existing profile's id but point
  it at another host, user, GitHub API URL, RD Gateway or jump host, and
  the saved password/token went there on the next connect without a
  prompt. Such a change now forgets that profile's saved credentials
  (audited), so the user is asked again.
- --answer / NEXUS_ANSWERS auto-fill every credential prompt and --answer
  is visible in the process list; they're now refused unless --screenshot
  is given (they exist for screenshot automation).
- Docs: IRC passwords are only sent over TLS/tunnel/loopback; sync's
  retarget behaviour; the --answer restriction.
2026-10-13 06:59:05 +01:00
Andy Dixon 400d11ea4f ci: least-privilege release publishing, no persisted tokens, pinned audit, checksums
- Release Builds: the build/test matrix ran ~1,400 third-party build
  scripts and tests with a contents:write token persisted in .git/config.
  It now runs with contents:read and persist-credentials: false; a
  separate publish job (no project or dependency code) downloads the
  artefacts, writes SHA256SUMS and attaches both to the release. The
  release now waits for every platform instead of publishing partially.
- CI/Fuzz checkouts don't persist credentials; cargo-audit is pinned
  (0.22.2), fails on yanked crates, and also audits fuzz/Cargo.lock;
  fuzz runs set -timeout=10 so slow-input bugs (like the IRC OSC one)
  are reported instead of hiding under libFuzzer's 20-minute default.
- updates/index.php: array-valued query parameters no longer raise
  TypeErrors/warnings; nosniff header.
2026-10-13 06:57:07 +01:00
Andy Dixon 13ca82ab2d fix(storage): transactional migrations, purge legacy plaintext secrets, private DB files, stricter ids and hosts
- Each migration runs in a transaction. Several rebuild the profiles
  table (create, copy, DROP, rename); a crash between the DROP and the
  rename left a database that failed to open on every later launch.
- Migration 009 removes the Go-era proxyPassword/totpSecret keys still
  sitting in old ssh_config JSON, then VACUUMs and checkpoints the WAL so
  the old pages leave the file. secure_delete is on from now on.
- nexus.db (and -wal/-shm) are created and kept 0600.
- Profile ids are limited to [A-Za-z0-9._-]{1,64}: ids name keychain and
  vault entries (profile:<id>:<kind>), so a crafted id containing ':'
  could shadow or purge another profile's credentials on import/sync.
- Hosts reject control characters (NUL got through) and >253 bytes; jump
  hosts and forward destination/bind addresses get the same host check.
2026-10-13 06:55:49 +01:00
Andy Dixon eb8f08a182 fix(rdp): clipboard only on explicit paste, size check before allocation, bounded device I/O
- The local clipboard was offered to the RDP server every time the
  desktop gained focus, so any server could read the last thing copied
  (a password, a token) without a paste. It now goes only on Ctrl/Cmd+V
  or Paste Clipboard.
- The server-chosen desktop size is checked before DecodedImage
  allocates it (65535x65535 is 16 GiB, and allocation failure aborts the
  whole app), at connect and on reactivation.
- Drive reads are clamped to 8 MiB per request (the native backend
  allocated the server's u32 length up front).
- Print jobs get unique files created exclusively (same-second jobs used
  to truncate each other) and at most 4 may be open at once.
2026-10-13 06:49:13 +01:00
Andy Dixon 7f3704e890 fix(irc): linear OSC stripping, bounded joins and CAP state, no cleartext passwords
- ircformat: an unterminated OSC made the stripper advance two bytes and
  rescan the rest, so one hostile 1 MiB line of ESC ] froze the UI thread
  for minutes. It now stops at the first OSC with no terminator (none can
  follow), which is linear.
- Server lines are capped at 64 KiB (512 bytes + 8 KiB of tags is the
  real ceiling) instead of 1 MiB.
- Spoofed self-JOINs can't grow channel state past 500 rooms (they were
  also persisted and auto-joined next time); CAP LS is ignored after
  registration and its gathered list is capped.
- PASS, SASL PLAIN and NickServ IDENTIFY are only sent over TLS, an SSH
  tunnel or a loopback server; otherwise the Server tab says why.
- TcpConn: a local close no longer races the reader into reporting a
  spurious read error (regression from 00f110f, which shut the socket
  down before taking the stream).
2026-10-13 06:46:38 +01:00
Andy Dixon d6f8f3306b fix(ui): hover-panic on non-ASCII links, paste and clipboard spoofing, image budget, links
- is_web_url sliced the string at byte 7/8, panicking (and killing every
  session) when a remote host printed an OSC 8 or plain link with a
  multi-byte character at that offset and the user hovered it. It now
  compares bytes.
- Paste confirmation also triggers on control characters other than tab
  (readline's C-o runs a line with no newline), and the preview shows
  them escaped.
- Remote clipboard toasts escape control characters and state the line
  count, so 'ls\ncurl … | sh' no longer reads as a harmless 'ls'.
- Inline images: dimensions are read from the header first and anything
  over the 32 Mpx per-terminal budget is refused before decoding.
- Toasts: repeats extend the visible toast and at most 8 are kept, so
  trigger or OSC 52 floods can't stall frames.
- The URL regex is compiled once.
- Enable eframe's 'links' feature: without it every 'open in browser'
  (Cmd/Ctrl+click, GitHub repo links, the update link) was a silent
  no-op. Adds webbrowser 1.2.4 to the lockfile.
2026-10-13 06:32:37 +01:00
Andy Dixon 00f110f39b fix: bound VNC zlib inflation, telnet negotiation state, unblockable socket close
- VNC: ZRLE and Tight inflation is capped at what the rectangle can
  legitimately decode to; a ~64 KiB zlib bomb previously expanded to
  gigabytes and the OOM killer took the whole app. Large scratch buffers
  are released after use. Queued input and a local close are now handled
  after every read, so a server that streams without pause can't starve
  keystrokes or keep a closed tab's connection alive.
- Telnet: option replies are sent only when the option's state changes
  (RFC 854), ending DONT/WONT ping-pong and 1:1 reply amplification; NAWS
  doubles 0xFF so 255/511-column windows don't emit a bare IAC.
- Telnet/RAW: writes time out after 10 s and close() shuts the socket via
  a second handle without waiting for the stream lock, so a peer that
  stops reading can no longer wedge the UI thread or the tab's close.
- Local shells skip non-UTF-8 environment entries instead of panicking.
2026-10-13 06:29:22 +01:00
Andy Dixon 0bcfe6470b fix(ssh): linear host-pattern matching, per-hop forwarding gates, loopback remote forwards
- known_hosts: the @cert-authority pattern matcher was recursive and
  backtracking; a pattern of a few hundred thousand stars overflowed the
  connect thread's stack on every handshake and '*a*a*a…b' went
  exponential. It is now the iterative two-pointer match, and patterns
  over 1 KiB are refused on import and in Trust a CA.
- Agent-forward and remote-forward channels are only honoured on the
  final hop: a jump host could previously open auth-agent channels and
  reach remote-forward destinations on the client machine.
- Remote forwards with no bind address listen on the server's loopback
  (as ssh -R does) instead of every interface.
- Keyboard-interactive gives up after 10 rounds; dials through jump hosts
  and run_command have timeouts; the handshake timeout leaves room for
  the host-key prompt so a slow reader isn't timed out mid-decision.
- Known hosts are looked up per key type, so an imported known_hosts with
  ed25519 and RSA rows no longer produces a false 'key changed' warning.
- SFTP download suggests a sanitised base name in the save dialog.
2026-10-13 00:42:17 +01:00
Andy Dixon 76bd664ed1 fix: clip sync timestamps, exclusive temp files, zeroized secret reads
- sync: timestamps and tombstones in the shared file are clipped to the
  local clock, and an edit wins a tie with a deletion, so a forged
  future-dated record can no longer override every later local change
  (or keep deleting a re-created profile) for as long as the forged date.
- write_private: the temp file is created O_EXCL under a random name, so a
  symlink pre-placed in a shared folder can't be followed or overwritten.
- Vault/keychain reads return Zeroizing<String>; has_sync_password is
  cached for a few seconds instead of fetching the real value every frame.
- generate_ssh_key creates a missing ~/.ssh as 0700.
- Honest wording: encrypted exports and the sync file carry login-script
  values; the audit entry, the Settings hint and the docs now say so.
2026-10-13 00:36:06 +01:00
102 changed files with 3392 additions and 208 deletions
+9 -3
View File
@@ -22,6 +22,8 @@ jobs:
working-directory: rust
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
persist-credentials: false
- name: Linux dependencies (GUI libs, and sshd for the SSH integration tests)
if: runner.os == 'Linux'
run: |
@@ -39,6 +41,10 @@ jobs:
working-directory: rust
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- run: cargo install cargo-audit --locked
# Ignored advisories and their reasons live in rust/.cargo/audit.toml.
- run: cargo audit
with:
persist-credentials: false
- run: cargo install cargo-audit --version 0.22.2 --locked
# Ignored advisories and their reasons live in rust/.cargo/audit.toml. Yanked crates
# fail the build; the fuzz workspace has its own lockfile, so it's audited too.
- run: cargo audit --deny yanked
- run: cargo audit --deny yanked --file fuzz/Cargo.lock
+3 -1
View File
@@ -21,10 +21,12 @@ jobs:
working-directory: rust/fuzz
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
persist-credentials: false
- run: sudo apt-get update && sudo apt-get install -y libasound2-dev
- run: rustup toolchain install nightly --profile minimal
- run: cargo +nightly install cargo-fuzz --locked
- run: cargo +nightly fuzz run ${{ matrix.target }} -- -max_total_time=120 -rss_limit_mb=2048
- run: cargo +nightly fuzz run ${{ matrix.target }} -- -max_total_time=120 -rss_limit_mb=2048 -timeout=10
- name: Upload crashing inputs
if: failure()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+26 -5
View File
@@ -6,8 +6,10 @@ on:
- "v*"
workflow_dispatch:
# Building and testing runs every dependency's build scripts and tests, so those jobs only get a
# read token. Publishing is a separate job that never runs project or dependency code.
permissions:
contents: write
contents: read
jobs:
build:
@@ -17,7 +19,7 @@ jobs:
fail-fast: false
matrix:
include:
- { platform: darwin/amd64, runner: macos-13 }
- { platform: darwin/amd64, runner: macos-15-intel }
- { platform: darwin/arm64, runner: macos-14 }
- { platform: linux/amd64, runner: ubuntu-22.04 }
- { platform: linux/arm64, runner: ubuntu-22.04-arm }
@@ -31,6 +33,7 @@ jobs:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
fetch-depth: 0
persist-credentials: false
- name: Rust toolchain (pinned by rust-toolchain.toml)
run: rustup show active-toolchain || rustup toolchain install
@@ -59,8 +62,26 @@ jobs:
build/releases/manifest-*.json
build/releases/version-*.txt
- name: Attach to GitHub Release
publish:
name: Attach to GitHub Release
needs: build
if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2
runs-on: ubuntu-22.04
permissions:
contents: write
steps:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
files: build/releases/*/NexusTerminal-*.zip
path: artefacts
- name: Checksums
run: |
find artefacts -name 'NexusTerminal-*.zip' | while read -r f; do
(cd "$(dirname "$f")" && sha256sum "$(basename "$f")")
done > SHA256SUMS
cat SHA256SUMS
- uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2
with:
files: |
artefacts/*/*/NexusTerminal-*.zip
artefacts/*/NexusTerminal-*.zip
SHA256SUMS
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+52
View File
@@ -17,6 +17,44 @@ Nexus Terminal helps you manage many connections at once, keep terminal work org
- Session recording (asciicast v2) and playback
- Secure credential storage with the OS keychain first and an encrypted vault fallback
## Install
**macOS** (Homebrew):
```sh
brew install --cask andydixon/tap/nexusterminal
```
**Debian, Ubuntu** (22.04 and later):
```sh
sudo install -d -m 0755 /etc/apt/keyrings
curl -fsSL https://repo.dixon.cx/dixon.gpg | sudo tee /etc/apt/keyrings/dixon.gpg >/dev/null
echo "deb [signed-by=/etc/apt/keyrings/dixon.gpg] https://repo.dixon.cx/apt stable main" |
sudo tee /etc/apt/sources.list.d/dixon.list
sudo apt update && sudo apt install nexusterminal
```
**Fedora, RHEL, openSUSE:**
```sh
sudo curl -fsSL -o /etc/yum.repos.d/dixon.repo https://repo.dixon.cx/rpm/dixon.repo
sudo dnf install nexusterminal # or: sudo zypper install nexusterminal
```
**Arch Linux:**
```sh
curl -fsSL https://repo.dixon.cx/dixon.asc | sudo pacman-key --add -
sudo pacman-key --lsign-key C22FF7330668417C62C7A304CBC7951D7F2234D1
printf '\n[dixon]\nServer = https://repo.dixon.cx/arch/$arch\n' | sudo tee -a /etc/pacman.conf
sudo pacman -Sy nexusterminal
```
**Windows**, or any platform by hand: download a zip from
[GitHub Releases](https://github.com/andydixon/nexus/releases) and check it against `SHA256SUMS`.
Builds aren't code-signed yet, so macOS and Windows ask you to confirm the first launch.
## Quick start
1. Launch Nexus Terminal.
@@ -67,3 +105,17 @@ cargo run --release
```
See [docs/build-and-release.md](docs/build-and-release.md) for platform prerequisites, tests and release packaging.
## License
Copyright (C) 2026 Andy Dixon.
Nexus Terminal is free software: you can redistribute it and/or modify it under the terms of the
[GNU Affero General Public License, version 3](LICENSE) as published by the Free Software
Foundation. It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
license for details.
Third-party crates (including the patched copies in `rust/vendor/`) keep their own licenses,
which are listed in each crate.
@@ -0,0 +1,136 @@
# Functionality and Next Steps Report
Nexus Terminal 3.0.1, reviewed alongside `20261012-2201-securityAudit.md`.
## 1. Executive Summary
The product is broad and mostly solid: nine protocols, sync, restore, shell integration, inline images, RDP devices and a 71-page guide. The highest-impact improvements now:
- **Make the UI thread untouchable.** Several remote- or device-driven paths still do blocking or unbounded work on the UI thread:
- serial writes;
- inline image decode;
- find-bar recomputation;
- recording seek;
- the unbounded event queue.
Moving them to workers, or adding budgets, removes a whole class of "one bad peer freezes everything" reports.
- **Finish the trust story for sync.** Timestamps are clipped and retargeted credentials are forgotten. What's still missing:
- a visible "what changed" summary;
- approval for security-relevant fields;
- eventually per-machine signatures.
- **Credentials out of profile data.** Login-script passwords are the last secrets stored as profile data.
- **Signed updates and releases**, as already planned by the owner.
- **One fixed functional break:** link opening never worked, because eframe's `links` feature was missing. It is fixed now, but it shows the UI has no automated coverage for "does the click do something".
## 2. Current Functional Risks
| Risk | Where | Effect |
|---|---|---|
| Find bar recomputes matches over the whole scrollback (≤100k lines) on every output chunk while open | `app/src/terminal.rs` find (≈1035-1075) | A chatty session plus an open find bar pins the UI thread |
| Recording seek re-feeds from byte 0 on every slider frame | `app/src/recordings.rs` `seek` | Dragging the slider on a big recording wedges the UI |
| `.cast` ids: `trim_end_matches(".cast")` strips repeatedly and `trim()` changes names | `core/src/recording.rs` | `a.cast.cast` plays or deletes `a.cast`; names with leading spaces break |
| A failed recording load closes the browser before the error toast | `app/src/recordings.rs` | The user loses their place |
| `Dialog` is a single `Option`; terminal responses and menus overwrite an open dialog | `tabs.rs`, `app.rs` | A pending Delete confirmation can silently disappear |
| A remote forward with `bind_port == 0` can't be stopped (cancel uses port 0) | `core/src/clients/ssh.rs` `shutdown_forward` | Forward stays listed and active on the server |
| `sftp()` session cached forever; a dead subsystem breaks SFTP until reconnect | `core/src/clients/ssh.rs` | "SFTP stopped working" reports |
| SFTP `list()` treats symlinks to directories as files | `core/src/clients/sftp.rs` | Can't navigate into linked directories |
| No SFTP transfer cancellation | `core/src/clients/sftp.rs` | Large accidental downloads can't be stopped |
| ssh-config import keeps only the first `ProxyJump` hop; `Host !foo` becomes a profile; `=` split on the first `=` anywhere | `core/src/sshconfig.rs` | Imported profiles connect differently from `ssh` |
| Jump-host `auth_method`/`secret_mode` ignored (key/agent only) | `core/src/clients/ssh.rs` `via_jumps` | Password-only bastions can't be used |
| IPv6 literals break KDC and gateway host:port parsing | `rdp.rs`, `ironrdp-mstsgu` | `[::1]:443` doesn't work |
| RD Gateway consent message aborts the connection | vendored `ironrdp-mstsgu` | Enterprise gateways with a banner fail |
| Kerberos hostname comes from `$HOSTNAME`, which is rarely exported | `rdp.rs` | Computer name is almost always "nexus" |
| `is_newer` ignores pre-release suffixes | `core/src/updater.rs` | An `-rc` build isn't offered the final release |
| Swallowed errors: tombstone write failure, vault delete failure, `triggers.json` read failure | `service.rs`, `secrets.rs`, `triggers.rs` | Silent data inconsistency |
| `has_sync_password` was a keychain round trip per frame (now cached for 5 s) | `service.rs` | Fixed; included here because macOS keychain prompts were possible |
## 3. Code Quality Improvements
- **One GCM helper.** `secrets::seal/open` and `exportimport::seal/open` duplicate the AES-GCM wrapping with different layouts. Merge them into one helper that takes AAD; that also closes SEC-049 at the next format bump.
- **Writer threads for every byte-stream client.** VNC already has a bounded queue. Telnet/RAW now have a write timeout, but writes still run on the caller's thread, and Serial and local PTY writes block under locks. One pattern for all of them removes a recurring bug class.
- **Dead code:** `Store::import_profiles` (no callers), `TermResponse.title` / `TermEvent::Title` plumbing (never read), the stray doc comment in `updater.rs`, the stale `.gitignore` whitelist for `rust/core/tests/fixtures/**`, and "Alchementary Link" strings left in `migrations/001_initial.sql` and `updates/index.php`.
- **`parse_col`** drops an unreadable config column, and the next save overwrites it with defaults. Keep the raw JSON and merge, so a config written by a newer build survives an older one.
- **Dependency hygiene:** move nexus-core to `rand 0.9`, `argon2 0.6`, `aes-gcm 0.11` and `sha2 0.11` to match the rest of the graph, collapsing duplicate crypto crates.
- **Vendored crates:** commit `.patch` files plus upstream tarball sha256, and add a CI check that the patches still apply cleanly to the pinned upstream versions.
## 4. Frontend Interaction and Error-Handling Improvements
(The UI is native egui. These are its equivalents of the frontend event and error items.)
- **Keep heavy work off the UI thread:**
- decode inline images on a worker;
- debounce find to ≤10 Hz, or restrict it to visible rows plus N;
- seek recordings on `drag_stopped`;
- write serial data on a writer thread.
- **Bound the event queue:** a per-session byte budget, coalescing consecutive `Data` events.
- **Dialogs:** make `Dialog` a small stack, or refuse to replace a confirmation dialog, so destructive confirmations can't vanish.
- **A sync change summary:** after a pull, list the changed profiles and fields (host, user, key policy, scripts, forwards, shared folder), with approve/revert for the security-relevant ones.
- **Explain withheld credentials:** IRC now does this for plaintext servers. Do the same for any future "held back for safety" behaviour, ideally with a one-click fix (enable TLS).
- **Clipboard settings:** consider defaulting "Allow remote clipboard writes" to off, or prompting on multi-line writes. The toast is now honest about line counts.
- **Debug logs:** before a user shares `RUST_LOG=debug` logs, the Diagnostics page should warn that debug output from the RDP libraries can contain authentication blobs and shared-folder data.
## 5. Testing Roadmap
- **Unit:**
- RDPDR read clamp;
- oversized RDP desktop;
- `.cast` id mapping;
- remote forward with port 0 stop;
- `parse_col` with an unknown future field;
- import strategies (skip/overwrite/duplicate, duplicate ids in one batch, size caps).
- **Integration:**
- two-sshd jump chain proving a jump host can't open agent or forwarded-tcpip channels (SEC-008);
- a stalled SSH server proving every phase hits its timeout;
- a fake Telnet peer that floods and never reads, proving `close()` returns quickly.
- **Migration fixtures:** real schema-1 and schema-7 databases opened by the current build, including one with Go-era `proxyPassword` keys.
- **Fuzzing:**
- new targets for `.cast` parsing, `known_hosts::parse`, `exportimport::open` and the JSON profile importer;
- seed the VNC corpus with valid ZRLE/Tight zlib streams;
- keep `-timeout` (now 10 s) so slow-input bugs surface.
- **UI smoke:**
- a headless run per protocol using the existing screenshot automation (`--connect`, `--do`, `--screenshot`) as a CI job, asserting no panic and a non-blank frame;
- "does this click do something" checks (link open, Copy, Paste) would have caught the missing `links` feature.
- **Load:** stream 512 MiB through a RAW session with the UI paused and assert bounded RSS (SEC-044).
## 6. Recommended New Functionality
- **Secret placeholders in login scripts** (`{{password}}`, `{{totp}}`) resolved from the keychain or vault at run time. This removes plaintext secrets from profiles (SEC-020) and improves the feature.
- **Sync change review and per-machine trust:** pair machines once by exchanging ed25519 public keys and sign sync records. Then the sync password is no longer the only key.
- **Signed update checks:** a minisign signature over the manifest, with the public key embedded, and verification in the updater. Pairs with the signing work already planned.
- **RDP NLA memory:** remember that a host did NLA and refuse a TLS-only downgrade later (SEC-019). Show "no NLA" visibly in the toolbar when it is in use.
- **VNC "unauthenticated session" indicator**, shown when the server picks security type None.
- **IRC TLS certificate pinning** for private-CA networks, so users aren't nudged to turn TLS off.
- **SFTP:** transfer cancellation and following symlinked directories.
- **Jump hosts with passwords:** honour the existing `auth_method` and `secret_mode` fields.
## 7. Next-Level Opportunities
- **Observability:** a "Copy debug bundle" action that redacts known-sensitive upstream log targets automatically, instead of relying on the user's `RUST_LOG` choice.
- **Architecture:** a single I/O runtime per session (tokio already runs SSH) for Telnet, RAW, Serial and VNC. That gives consistent cancellation, timeouts and back-pressure, and removes several thread-per-connection blocking patterns.
- **Release engineering:** build provenance attestations, signed tags, and reproducible-build notes. Releases are already split into build (read-only) and publish (write) jobs.
- **Accessibility:** egui AccessKit is enabled. Audit screen-reader labels on the desktop viewers and terminal (password fields are already masked for AccessKit).
- **Performance:** the OSC 8 underline painter issues up to cols/3 `hline` calls per cell per frame, and the RAW hex row cache is bounded by count, not bytes. Both are cheap wins.
## 8. Prioritised Action Plan
| When | Action | Why | Risk |
|---|---|---|---|
| Immediate | Fix the GitHub Actions billing block so CI and the v3.0.1 release builds run | No CI signal and no release artefacts right now | None |
| Short term | Event budget, find debounce, recording seek on drag-stop, serial writer thread | Remove the remaining UI-freeze vectors | Low; contained changes |
| Short term | Sync change summary plus approval for security-relevant fields | Closes SEC-021 | Medium; UX design needed |
| Short term | RDP NLA memory (SEC-019) | Downgrade protection | Low; needs a small known-hosts field |
| Medium | Login-script secret placeholders | Removes the last plaintext secrets | Medium; changes the script editor and migration |
| Medium | Merge the GCM helpers with AAD, bump crypto crates, vendored patch checks | Hygiene and integrity | Low |
| Medium | Fuzz targets and migration fixtures listed in §5 | Regression safety | None |
| Long term | Signed manifests, binaries and tags; per-machine sync signatures | Supply-chain and sync trust | Medium; key management |
## 9. Caveats and Validation Needed
- **Not exercised against real systems:**
- Windows RDP with NLA and Display Control;
- RD Gateway;
- Kerberos;
- macOS/Windows keychains (after the `Zeroizing` API change);
- real plaintext IRC networks (behaviour changed: passwords are now held back there).
- **Release ordering:** the release workflow now publishes only after every platform builds, so one failing platform blocks the release. Confirm that is the preferred trade-off over partial releases.
- **Sync re-prompts:** forgetting credentials on retargeted sync/import means a host edit on one machine makes the others re-prompt once. That is intended, but users should be told (it's in the manual now).
- **Profile ids:** ids are now limited to `[A-Za-z0-9._-]{1,64}`. Every id this app generates is a UUID, but hand-made JSON imports with unusual ids will be refused rather than rewritten. Rewriting them on import is a possible follow-up.
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -76,7 +76,7 @@
\begin{sidequest}[How the screenshots in this guide were made]
Every screenshot here is the real app, driven by \code{docs/guide/tools/screenshots.sh}: it starts throwaway
SSH, IRC, VNC and GitHub-ish servers, fills a demo data folder, and runs Nexus Terminal headless with
\code{--screenshot}, \code{--do} (run a palette command) and \code{--answer} (fill a password prompt). Change the app,
\code{--screenshot}, \code{--do} (run a palette command) and \code{--answer} (fill a password prompt; only accepted together with \code{--screenshot}). Change the app,
rerun the script, rebuild the guide.
\end{sidequest}
+2 -1
View File
@@ -85,7 +85,8 @@ after you change a profile, every ten minutes and whenever you click \ui{Sync No
\begin{checklist}
\item[\color{green}\iCheck] Edited on two machines? The newer change wins, profile by profile.
\item[\color{green}\iCheck] Deleted on one machine? It goes from the others too (unless someone edited it afterwards).
\item[\color{rose}\ph{E4F6}] Passwords, keys and tokens never sync. Each machine keeps its own in its keychain or vault.
\item[\color{rose}\ph{E4F6}] Saved passwords, keys and tokens never sync. Each machine keeps its own in its keychain or vault.
(Anything a login script \emph{sends} is part of the profile, so that does travel.)
\end{checklist}
\crop{settings-security.png}{581}{253}{576}{285}{0.8\linewidth}{Profile sync lives on the Security page, under your stored credentials.}
Binary file not shown.
+1 -1
View File
@@ -35,7 +35,7 @@
\node[inner sep=0pt, draw=white!25!ink, line width=0.6pt, rounded corners=4pt] {\includegraphics[width=166mm]{img/ssh.png}};
\end{tikzpicture}};
\node[anchor=south east, text=white!55!ink, font=\footnotesize, align=right]
at ([xshift=-22mm, yshift=24mm]pg.south east) {Version 3.0.1\\October 2026\\dixon.cx};
at ([xshift=-22mm, yshift=24mm]pg.south east) {Version 3.0.2\\October 2026\\dixon.cx};
}\null
\cleardoublepage
+2
View File
@@ -1,4 +1,6 @@
#!/bin/bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 Andy Dixon
# ForceCommand for the throwaway screenshot sshd: never a login shell (no ~/.profile, no byobu).
DEMO_HOME=$1 SFTP_SERVER=$2
export LC_ALL=C.UTF-8
+2
View File
@@ -1,4 +1,6 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 Andy Dixon
"""Tiny fake servers for the user-guide screenshots: RAW sensor feed (42023), IRC (42667),
GitHub API (42080) and a VNC desktop (42900). Stdlib only. Runs until killed."""
+2
View File
@@ -1,4 +1,6 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 Andy Dixon
# Regenerates docs/guide/img/*.png: a throwaway sshd (ForceCommand, never a login shell),
# fake RAW/IRC/GitHub/VNC servers, a demo data directory, then one headless app run per shot.
# Needs: xvfb-run, sshd, ssh-keygen, python3, ImageMagick. Usage: docs/guide/tools/screenshots.sh [shot...]
+6 -4
View File
@@ -105,7 +105,7 @@ If you connect to a profile that already has a live session, Nexus Terminal asks
- **Key & Passphrase**: choose a key from the suggestions (keys in `~/.ssh`), click **Browse**, or type a full path (`~` is not expanded). The editor checks that the file exists and is a private key.
- **Host Verification**: the host key policy (see section 12).
- **Jump Hosts**: one or more bastions, each with user, host, port and an optional key. Nexus Terminal tunnels through each hop in order.
- **Port Forwarding**: local and remote forwards, each with a bind address and port, destination, label and an **Active** box to start it on connect.
- **Port Forwarding**: local and remote forwards, each with a bind address and port, destination, label and an **Active** box to start it on connect. A remote forward with no bind address listens on the server's loopback only (as `ssh -R` does); set it to `0.0.0.0` to expose it to the server's network, which also needs `GatewayPorts` on the server.
- **Startup**: a startup command and environment variables (`KEY=VALUE`, one per line).
- **Login Script**: expect-style steps (see below).
- **SSH Agent**: agent authentication and **Forward Agent to Remote** (like `ssh -A`).
@@ -175,12 +175,12 @@ Nexus Terminal logs on with Network Level Authentication (CredSSP), so your pass
RDP servers usually present self-signed certificates, so the certificate is pinned like an SSH host key: its SHA-256 fingerprint is shown the first time and stored in **Known Hosts**, and a changed certificate offers Reject, Accept Once or Accept & Update. The check happens before any credentials are sent.
The viewer works like the VNC one: click the desktop to give it keyboard focus, **Ctrl+Alt+Del** sends the key combination, and text is shared through the clipboard both ways: text you copy on the remote desktop arrives on your clipboard (subject to the remote-clipboard setting), and your clipboard is offered to the remote desktop whenever you click into it, press Ctrl+V or use **Paste Clipboard**. Files and images are not shared. With **Resize With Tab**, the remote desktop follows the tab's size on servers that support it (Windows); otherwise the picture is scaled.
The viewer works like the VNC one: click the desktop to give it keyboard focus, **Ctrl+Alt+Del** sends the key combination, and text is shared through the clipboard both ways: text you copy on the remote desktop arrives on your clipboard (subject to the remote-clipboard setting), and your clipboard is sent to the remote desktop only when you paste (Ctrl+V / Cmd+V on the desktop, or **Paste Clipboard**), so a server can't read what you last copied. Files and images are not shared. With **Resize With Tab**, the remote desktop follows the tab's size on servers that support it (Windows); otherwise the picture is scaled.
### IRC
- **IRC**: nick, real name, **Use TLS** (port 6697 for most TLS networks) and an optional server password.
- **SASL**: log in during registration with SASL PLAIN (account defaults to your nick), which most networks now expect; use TLS or an SSH tunnel so the password isn't sent in the clear. If the network doesn't offer SASL or rejects the login, the Server tab says so and the connection carries on.
- **SASL**: log in during registration with SASL PLAIN (account defaults to your nick), which most networks now expect; Nexus Terminal only sends it (or a server or NickServ password) over TLS, an SSH tunnel or to a server on this machine; on a plain connection the Server tab says the password was held back. If the network doesn't offer SASL or rejects the login, the Server tab says so and the connection carries on.
- **NickServ**: identify on connect, with an optional account name and password.
- **Rooms**: rooms to join automatically, one per line or comma-separated. Networks that support IRCv3 server-time stamp messages with the time they were sent, so replayed history shows its real times.
- **SSH Tunnel** and **Reconnection** settings.
@@ -434,7 +434,9 @@ Connections, disconnections, profile changes, credential access, imports and exp
- for a profile changed on both sides, the more recent change wins;
- a profile deleted on one machine is deleted on the others (unless it was edited after the deletion);
- passwords, keys and other credentials are never synced; each machine keeps its own in its keychain or vault.
- saved passwords, keys and tokens are never synced; each machine keeps its own in its keychain or vault. Values that a login script `send`s (including a password typed after a `wait "Password:"`) are part of the profile and do travel, as they do in an export;
- timestamps in the shared file are never trusted beyond the local clock, so a file edited to claim a future date can't override later local changes;
- if a synced (or imported) profile now points at a different host, user, GitHub API URL or RD Gateway, this machine forgets the credentials it had saved for it and asks again, rather than sending them to the new destination.
- **Encrypted export**: **File → Export profiles…**, the sidebar footer, the command palette, or **Export…** on a profile's right-click menu. Choose the profiles, set a password and save a `.nexus` file. Credentials saved in the keychain or vault are not included.
+2
View File
@@ -1,3 +1,5 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 Andy Dixon
# Release builds live with the Rust workspace; see docs/build-and-release.md.
exec "$(dirname "${BASH_SOURCE[0]}")/rust/release.sh" "$@"
+19 -2
View File
@@ -1800,6 +1800,7 @@ dependencies = [
"serde",
"smithay-clipboard",
"web-time",
"webbrowser",
"winit",
]
@@ -3710,7 +3711,7 @@ dependencies = [
[[package]]
name = "nexus"
version = "3.0.1"
version = "3.0.2"
dependencies = [
"alacritty_terminal",
"arboard",
@@ -3735,7 +3736,7 @@ dependencies = [
[[package]]
name = "nexus-core"
version = "3.0.1"
version = "3.0.2"
dependencies = [
"aes-gcm 0.10.3",
"argon2 0.5.3",
@@ -7074,6 +7075,22 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "webbrowser"
version = "1.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62c35be770821a214dbc362fc26908c853e776c0004294d0b10b8a6bad582f94"
dependencies = [
"jni 0.22.4",
"log",
"ndk-context",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"url",
"web-sys",
]
[[package]]
name = "webpki-roots"
version = "1.0.9"
+4 -1
View File
@@ -4,8 +4,11 @@ members = ["core", "app"]
exclude = ["fuzz"]
[workspace.package]
version = "3.0.1"
version = "3.0.2"
edition = "2024"
license = "AGPL-3.0-only"
authors = ["Andy Dixon <andy@dixon.cx>"]
repository = "https://github.com/andydixon/nexus"
[profile.dev.package."*"]
opt-level = 2
+4 -1
View File
@@ -2,6 +2,9 @@
name = "nexus"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
build = "build.rs"
[[bin]]
@@ -10,7 +13,7 @@ path = "src/main.rs"
[dependencies]
nexus-core = { path = "../core" }
eframe = { version = "0.36", default-features = false, features = ["default_fonts", "glow", "wayland", "x11", "accesskit", "persistence"] }
eframe = { version = "0.36", default-features = false, features = ["default_fonts", "glow", "wayland", "x11", "accesskit", "persistence", "links"] }
egui = "0.36"
parking_lot = "0.12"
zeroize = "1"
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Embeds the icon and version info into the Windows executable.
fn main() {
println!("cargo:rerun-if-changed=../packaging/windows/nexus.ico");
+23 -2
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! The main window: title bar, connection sidebar, tab strip and workspace (terminals, split
//! panes, protocol viewers), right dock (SFTP or the profile editor), status bar, command
//! palette, prompts and toasts. Session events from nexus-core are drained here every frame.
@@ -791,10 +794,9 @@ impl App {
/// A remote host (OSC 52 or VNC) wants to set the clipboard: allowed per preference, and always
/// announced so a silent swap can't set up a paste into another shell.
pub fn remote_clipboard(&mut self, text: &str) {
let first: String = text.lines().next().unwrap_or("").chars().take(60).collect();
if self.s.prefs.allow_remote_clipboard {
self.s.ctx.copy_text(text.into());
self.s.info(format!("Remote host set the clipboard: {first}"));
self.s.info(format!("Remote host set the clipboard: {}", clipboard_summary(text)));
} else {
self.s.info("Blocked a remote clipboard write (Settings → General to allow)");
}
@@ -1077,3 +1079,22 @@ impl eframe::App for App {
let _ = ToastKind::Info;
}
}
/// How a remote clipboard write is announced: control characters made visible and the line
/// count stated, so `ls\ncurl … | sh` can't pass for a harmless `ls`.
fn clipboard_summary(text: &str) -> String {
let lines = text.lines().count();
let shown: String = text.chars().take(60).flat_map(|c| if c.is_control() { c.escape_debug().collect::<Vec<_>>() } else { vec![c] }).collect();
let more = if text.chars().count() > 60 { "…" } else { "" };
if lines > 1 { format!("{shown}{more} ({lines} lines)") } else { format!("{shown}{more}") }
}
#[cfg(test)]
mod clipboard_tests {
#[test]
fn remote_clipboard_toast_shows_hidden_lines() {
assert_eq!(super::clipboard_summary("ls"), "ls");
assert_eq!(super::clipboard_summary("ls\ncurl x|sh\n"), "ls\\ncurl x|sh\\n (2 lines)");
assert!(super::clipboard_summary("a\x0fb").contains("\\u{f}"));
}
}
+10 -1
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Window chrome: custom title bar, status bar, command palette, credential and host-key
//! prompts, the main window's modal dialogs, toasts and resize edges.
@@ -931,7 +934,13 @@ pub fn dialogs(app: &mut App, ctx: &egui::Context) {
}
Dialog::ConfirmPaste { session, text } => {
let lines = text.lines().count();
let preview: String = text.lines().take(12).collect::<Vec<_>>().join("\n");
// Control characters other than newline/tab act on their own; show them.
let preview: String = text
.lines()
.take(12)
.map(|l| l.chars().flat_map(|c| if c.is_control() && c != '\t' { c.escape_debug().collect::<Vec<_>>() } else { vec![c] }).collect::<String>())
.collect::<Vec<_>>()
.join("\n");
modal(ctx, "confirm-paste", 480.0, |ui| {
ui.label(RichText::new("Paste multiple lines?").font(theme::semibold(15.0)));
widgets::hint(ui, &format!("{lines} line(s) will run as commands as soon as they are pasted:"));
+6 -9
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Remote desktop viewer for VNC and RDP: the remote framebuffer as a texture, with mouse,
//! keyboard and clipboard input. Input is expressed in X keysyms and VNC pointer masks (VNC's own
//! terms); `Remote` translates them for RDP. Toolbar after the web build's `vnc.js` (status,
@@ -446,15 +449,9 @@ impl DesktopView {
resp.request_focus();
}
let focused = resp.has_focus();
// RDP shares the clipboard both ways: offer the local text whenever the desktop gains focus.
if focused
&& !self.had_focus
&& let Some(Remote::Rdp(c)) = &self.client
&& let Ok(text) = arboard::Clipboard::new().and_then(|mut c| c.get_text())
&& !text.is_empty()
{
c.set_clipboard(text);
}
// The local clipboard goes to the remote desktop only on an explicit paste (Ctrl/Cmd+V or
// Paste Clipboard). Offering it whenever the desktop gained focus let any server read
// whatever was last copied (a password, a token) without the user pasting anything.
if focused {
ui.painter().rect_stroke(img, 0.0, egui::Stroke::new(1.0, Tokens::get(ui.ctx()).accent.gamma_multiply(0.6)), egui::StrokeKind::Outside);
ui.memory_mut(|m| m.set_focus_lock_filter(id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true }));
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Port forwards dialog for a live SSH session: list, stop, add.
use crate::chrome::modal;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! GitHub repository browser: owner groups of repo cards with ZIP download and Visit. Port of
//! `github.js`.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! IRC client view: room tabs, message log, composer and room/user lists. Port of `irc.js`;
//! lines are `ircformat::format_event` spans drawn in the terminal theme's colours.
+9 -4
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Nexus Terminal: SSH, Telnet, RAW TCP, Serial, VNC, IRC, GitHub and local terminals in one
//! native window. `nexus-terminal [--theme pro|midnight|light] [--screenshot out.png] [--size WxH]`.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
@@ -99,8 +102,11 @@ fn main() -> eframe::Result {
// SAFETY: still single-threaded here; no other thread can be reading the environment.
unsafe { std::env::remove_var("NEXUS_ANSWERS") };
}
// They answer every credential prompt in order (and --answer is visible in the process list),
// so they're only honoured for screenshot runs.
if !opts.answers.is_empty() && opts.screenshot.is_none() {
eprintln!("warning: --answer/NEXUS_ANSWERS auto-fill credential prompts; they are meant for screenshot automation only");
eprintln!("--answer/NEXUS_ANSWERS only work together with --screenshot (they auto-fill credential prompts)");
std::process::exit(2);
}
let config = match data_dir {
Some(d) => {
@@ -169,10 +175,8 @@ fn init_logging(data_dir: &std::path::Path) {
/// files, and on Linux the process is non-dumpable (also blocks ptrace attach by other processes
/// of the same user). Debug builds skip this so they can still be debugged.
fn harden_process() {
if cfg!(debug_assertions) {
return;
}
#[cfg(unix)]
if !cfg!(debug_assertions) {
// SAFETY: plain syscalls on this process with valid arguments; failure is harmless.
unsafe {
let none = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
@@ -180,4 +184,5 @@ fn harden_process() {
#[cfg(target_os = "linux")]
libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0);
}
}
}
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Finds the OSC sequences the VT parser ignores but Nexus uses: OSC 133 (shell integration
//! marks: prompt, command, output, finished with exit status) and OSC 7 (the shell's working
//! directory). Sequences may be split across reads, so the scanner keeps state between chunks.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Profile editor (right dock): create and edit every protocol's settings. A port of the
//! `profiles.js` drawer plus the Serial protocol. Switching protocol keeps the common fields
//! (including the group), and list editors keep unsaved edits.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Quick Connect dialog: an ad-hoc session without saving a profile.
use crate::chrome::modal;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! RAW TCP viewer: text / hex / split views of the capture, pause, clear, save, and a send bar.
//! Port of the web build's `raw.js`. Sent data comes back through `Event::RawData` ("send"), so
//! the echo of a sent entry needs no local bookkeeping.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Recordings browser and playback window (port of the RecordingManager in recordings.js).
use crate::state::Shared;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Reopens the previous run's tabs and splits at launch: saved profiles reconnect, local shells
//! start again in the directory they were in. The layout is saved whenever it changes (not only on
//! exit), so it survives a crash. Quick Connect tabs aren't restored (they have no saved profile).
+13 -2
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Settings window: General, Terminal, Security, Known Hosts, Help, About. Also the
//! master-password dialog (strength meter + confirm) used to create or unlock the vault.
@@ -452,7 +455,8 @@ impl Settings {
widgets::hint(
ui,
"Keep connection profiles in step across machines through a folder they share (a cloud drive, a network share, a git checkout). \
Profiles are stored there encrypted with the sync password; passwords and keys are never synced.",
Profiles are stored there encrypted with the sync password. Saved passwords and keys stay in each machine's keychain or vault; \
values a login script sends travel with their profile.",
);
form(ui, "sync-form", |ui| {
field(ui, "Folder");
@@ -780,14 +784,21 @@ impl Settings {
// --- About ----------------------------------------------------------------------------
fn about(&mut self, ui: &mut Ui, s: &mut Shared) {
const SOURCE_URL: &str = "https://github.com/andydixon/nexus";
let t = Tokens::get(ui.ctx());
ui.add_space(8.0);
ui.label(RichText::new("Nexus Terminal").font(theme::semibold(22.0)));
ui.label(RichText::new(format!("Version {}", nexus_core::service::VERSION)).color(t.text_dim));
ui.label(RichText::new("Developed by Andy Dixon - dixon.cx/nexus").color(t.text_faint));
ui.horizontal(|ui| {
ui.label(RichText::new("Free software under the GNU Affero General Public License v3. Source:").color(t.text_faint));
if ui.link("github.com/andydixon/nexus").clicked() {
widgets::open_web_url(ui.ctx(), SOURCE_URL);
}
});
ui.add_space(8.0);
for f in [
"SSH, Telnet, RAW TCP, Serial, VNC, IRC, GitHub and local terminals",
"SSH, Telnet, RAW TCP, Serial, VNC, RDP, IRC, GitHub and local terminals",
"AES-256-GCM encrypted credential vault",
"Platform-native keychain integration",
"SFTP file browser and transfer",
+6 -1
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! SFTP browser (right dock), the file-drop dialog and the remote directory picker.
//! Every SFTP call blocks on the network, so it runs on a worker thread; results come back
//! through `inbox` and are applied on the UI thread at the start of the next frame.
@@ -393,7 +396,9 @@ impl Sftp {
fn download(&mut self, s: &Shared, session: &str, files: Vec<FileEntry>) {
let targets: Vec<(FileEntry, PathBuf)> = if files.len() == 1 {
let Some(p) = rfd::FileDialog::new().set_file_name(&files[0].name).save_file() else {
// The name comes from the server: keep only a safe base name for the dialog's default.
let suggested = safe_sftp_upload_name(&files[0].name).unwrap_or_else(|_| "download".into());
let Some(p) = rfd::FileDialog::new().set_file_name(suggested).save_file() else {
return;
};
vec![(files[0].clone(), p)]
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! The connection sidebar: Local Machine, Favourites, Recent, folders, Ungrouped; fuzzy search;
//! click to connect, Ctrl/Cmd-click to multi-select, double-click to edit; bulk actions.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Snippet library window and the {{variable}} prompt (port of snippets.js).
use crate::state::{Request, Shared};
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Split panes: a binary tree of sessions inside one tab. A new split starts as a placeholder
//! pane offering Local Machine and the saved connections; ✕ on a pane promotes its sibling.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! SSH Key Manager window: key pairs in ~/.ssh — copy public key, delete, generate (in-process, OpenSSH format).
use crate::settings::{Job, poll};
+16 -2
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! State shared by the main window and every feature module: the service, cached profiles and
//! preferences, open tabs, toasts, and a request queue features use to ask the app to act.
@@ -45,6 +48,8 @@ pub enum SettingsTab {
About,
}
const MAX_TOASTS: usize = 8;
pub struct Toast {
pub text: String,
pub kind: ToastKind,
@@ -129,8 +134,17 @@ impl Shared {
}
fn push(&mut self, text: impl Into<String>, kind: ToastKind) {
let secs = if kind == ToastKind::Error { 6.0 } else { 4.0 };
self.toasts.push(Toast { text: text.into(), kind, until: self.now + secs });
let (text, secs) = (text.into(), if kind == ToastKind::Error { 6.0 } else { 4.0 });
// Remote output can raise toasts (triggers, clipboard writes) at line rate: repeats only
// extend the visible one, and at most a handful are kept so a flood can't stall frames.
if let Some(t) = self.toasts.iter_mut().find(|t| t.text == text && t.kind == kind) {
t.until = self.now + secs;
} else {
self.toasts.push(Toast { text, kind, until: self.now + secs });
if self.toasts.len() > MAX_TOASTS {
self.toasts.remove(0);
}
}
self.ctx.request_repaint();
}
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! The tab strip and the workspace under it: the active tab's session (or its split panes),
//! terminal find bar and connection overlays.
+45 -6
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! TermView: an alacritty_terminal grid drawn with egui's painter. Bytes from a session go
//! straight into the VT parser; keystrokes, paste, mouse reports and terminal replies come back
//! out through `TermResponse` for the app to send to the session (and broadcast targets).
@@ -280,11 +283,18 @@ impl TermView {
return;
}
let decoded = (|| {
let mut r = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format().ok()?;
let reader = || image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format().ok();
// Read the header first: refuse anything larger than the per-terminal image budget
// before decoding, since the decoder's own limits don't bound every internal buffer.
let (w, h) = reader()?.into_dimensions().ok()?;
if w as usize * h as usize > MAX_IMAGE_PIXELS {
return None;
}
let mut r = reader()?;
let mut limits = image::Limits::default();
limits.max_image_width = Some(8192);
limits.max_image_height = Some(8192);
limits.max_alloc = Some(256 << 20);
limits.max_alloc = Some((MAX_IMAGE_PIXELS * 4) as u64);
r.limits(limits);
Some(r.decode().ok()?.to_rgba8())
})();
@@ -707,9 +717,11 @@ impl TermView {
}
/// Pastes `text`, or hands it back in `out.confirm_paste` when `confirm_paste` is set and the
/// newlines would run each line immediately (no bracketed paste).
/// paste could act by itself without bracketed paste: newlines run lines, and other control
/// characters do too (readline's C-o runs the line, C-d exits, ESC drives key macros).
pub fn paste(&mut self, text: &str, out: &mut TermResponse) {
if self.confirm_paste && !self.term.mode().contains(TermMode::BRACKETED_PASTE) && text.contains(['\n', '\r']) {
let acts = text.chars().any(|c| c.is_control() && c != '\t');
if self.confirm_paste && !self.term.mode().contains(TermMode::BRACKETED_PASTE) && acts {
out.confirm_paste = Some(text.into());
return;
}
@@ -871,8 +883,8 @@ impl TermView {
return Some(link);
}
let (text, cols) = self.line_text(point.line);
let re = regex::Regex::new(URL_RE).ok()?;
re.find_iter(&text).find_map(|m| {
static RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| regex::Regex::new(URL_RE).expect("URL_RE is valid"));
RE.find_iter(&text).find_map(|m| {
let start = text[..m.start()].chars().count();
let end = start + m.as_str().chars().count() - 1;
(cols.get(start)? <= &point.column.0 && cols.get(end)? >= &point.column.0).then(|| m.as_str().to_string())
@@ -1226,12 +1238,39 @@ mod tests {
let mut out = TermResponse::default();
t.paste("one line", &mut out);
assert_eq!(out.input, b"one line");
// Control characters that act without a newline need the prompt too (C-o runs the line).
let mut out = TermResponse::default();
t.paste("curl x|sh\x0f", &mut out);
assert!(out.input.is_empty() && out.confirm_paste.is_some());
let mut out = TermResponse::default();
t.paste("a\tb", &mut out);
assert_eq!(out.input, b"a\tb", "a tab is fine");
t.feed(b"\x1b[?2004h");
let mut out = TermResponse::default();
t.paste("a\nb", &mut out);
assert!(out.confirm_paste.is_none() && out.input.starts_with(b"\x1b[200~"), "bracketed paste needs no prompt");
}
#[test]
fn oversized_inline_images_are_refused_before_decoding() {
use std::io::Cursor;
let png = |w: u32, h: u32| {
let mut v = Vec::new();
image::RgbaImage::new(w, h).write_to(&mut Cursor::new(&mut v), image::ImageFormat::Png).unwrap();
v
};
let b64 = |d: &[u8]| {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(d)
};
let mut t = TermView::new(1000, 14.0, CursorStyle::Block);
// 8192x8192 is within the decoder's dimension limits but over the 32 Mpx budget.
t.feed(format!("\x1b]1337;File=inline=1:{}\x07", b64(&png(8192, 8192))).as_bytes());
assert!(t.images.is_empty());
t.feed(format!("\x1b]1337;File=inline=1:{}\x07", b64(&png(64, 64))).as_bytes());
assert_eq!(t.images.len(), 1);
}
#[test]
fn shell_integration_marks_survive_a_full_scrollback() {
// Scrollback of 30 lines, so the history fills and rotates during the test.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! The 11 terminal colour schemes, generated from the web build's themes.js.
pub struct TermTheme {
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Design system: colour tokens, radii and typography (Inter for UI, JetBrains Mono for bytes).
//! Widgets read `Tokens::get(ctx)` instead of hard-coding colours, so every theme applies
//! everywhere. Copied from Leviathan Desktop so both apps share one look.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Profile export/import: encrypted `.nexus` and plain JSON.
use crate::settings::{Job, poll};
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Trigger rules: match terminal output lines and notify / highlight / beep (port of triggers.js).
//! Rules live in `triggers.json` in the data directory (the web build's localStorage rules are
//! not migrated).
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! How a session is drawn. Terminal-style protocols share `TermView`; the rest have their own.
use crate::desktop_view::DesktopView;
+22 -3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Shared widgets: section headers, buttons, chips, key/value grids, virtual lists, empty states.
//! Colours always come from `Tokens`.
@@ -129,8 +132,11 @@ pub fn group(n: u64) -> String {
/// GitHub API responses) are only handed to the system opener when they are http(s), so a
/// hostile or spoofed server can't launch `file:`, `ssh:` or custom-scheme handlers.
pub fn is_web_url(url: &str) -> bool {
let u = url.trim();
(u.len() > 8 && u[..8].eq_ignore_ascii_case("https://")) || (u.len() > 7 && u[..7].eq_ignore_ascii_case("http://"))
// Compare bytes: slicing the `str` at 7/8 panics when that offset falls inside a multi-byte
// character, and these strings come from the network (hovering a hostile OSC 8 link).
let u = url.trim().as_bytes();
let starts = |p: &[u8]| u.len() > p.len() && u[..p.len()].eq_ignore_ascii_case(p);
starts(b"https://") || starts(b"http://")
}
/// Opens `url` in the browser if it is a web link; returns false (and opens nothing) otherwise.
@@ -166,7 +172,20 @@ mod tests {
for ok in ["https://dixon.cx/downloads/nexus/", "http://localhost:3000/x", " HTTPS://Example.com "] {
assert!(super::is_web_url(ok), "{ok}");
}
for bad in ["", "https://", "file:///etc/passwd", "ssh://evil", "javascript:alert(1)", "ms-msdt:/id x", "ftp://host/", "//host/path"] {
assert!(super::is_web_url("http://über.example/"));
for bad in [
"",
"https://",
"file:///etc/passwd",
"ssh://evil",
"javascript:alert(1)",
"ms-msdt:/id x",
"ftp://host/",
"//host/path",
"mailto:ü@x",
"http:/üüü",
"ftp://é",
] {
assert!(!super::is_web_url(bad), "{bad}");
}
}
+3
View File
@@ -2,6 +2,9 @@
name = "nexus-core"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
[features]
# Exposes parser entry points for rust/fuzz (cargo-fuzz).
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Fills a data directory with demo profiles, snippets, known hosts, trigger rules and recordings
//! for the user-guide screenshots (docs/guide/screenshots.sh).
//!
@@ -0,0 +1,10 @@
-- Profiles saved by the Go app kept proxyPassword and totpSecret inside ssh_config. They live in
-- the keychain or vault now and are dropped on read, but the old JSON stayed in the column until
-- the profile was next saved. Remove them (the store also VACUUMs after this migration so the
-- old pages don't linger in the file).
UPDATE profiles
SET ssh_config = json_remove(ssh_config, '$.proxyPassword', '$.totpSecret')
WHERE json_valid(ssh_config)
AND (json_extract(ssh_config, '$.proxyPassword') IS NOT NULL OR json_extract(ssh_config, '$.totpSecret') IS NOT NULL);
INSERT INTO schema_version (version, applied_at) VALUES (9, datetime('now'));
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Lightweight GitHub REST client for repository metadata and archive downloads. Works with
//! github.com and GitHub Enterprise via a configurable API base URL.
+72 -6
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! IRC client: registration, PING/PONG, channel/user tracking, CTCP ACTION, NickServ identify,
//! auto-join and the composer's /commands, reporting through typed `Event`s.
//!
@@ -24,7 +27,12 @@ const READ_POLL: Duration = Duration::from_millis(50);
const PING_DELAY: Duration = Duration::from_secs(20);
const PING_TIMEOUT: Duration = Duration::from_secs(60);
const PING_GRACE: Duration = Duration::from_secs(30);
const MAX_LINE_BYTES: usize = 1 << 20;
/// IRC lines are 512 bytes plus up to 8 KiB of IRCv3 tags; anything far longer is hostile.
const MAX_LINE_BYTES: usize = 64 << 10;
/// Channels the client keeps state for; a server can't grow it past this with spoofed self-JOINs.
const MAX_CHANNELS: usize = 500;
/// Capability names gathered from a multi-line CAP LS.
const MAX_CAPS: usize = 1000;
/// Users tracked per channel; a hostile server can't grow the client past this.
const MAX_CHANNEL_USERS: usize = 10_000;
@@ -563,7 +571,7 @@ impl Client {
};
// IRCv3 capability negotiation; servers without it ignore the command and register as usual.
write(&mut stream, "CAP LS 302")?;
if !self.cfg.server_pass.is_empty() {
if !self.cfg.server_pass.is_empty() && self.credentials_allowed("server password") {
write(&mut stream, &encode("PASS", &[&self.cfg.server_pass]))?;
}
write(&mut stream, &encode("NICK", &[&self.cfg.nick]))?;
@@ -720,8 +728,23 @@ impl Client {
}
}
/// Passwords (PASS, SASL PLAIN, NickServ) only go over an encrypted or local connection:
/// TLS, an SSH tunnel, or a loopback server. Otherwise they're held back and the Server tab
/// says why, rather than putting the password on the wire in the clear.
fn credentials_allowed(&self, what: &str) -> bool {
if sends_credentials_safely(&self.cfg) {
return true;
}
self.emit(Event {
kind: "error".into(),
text: format!("{what} not sent: the connection isn't encrypted (turn on TLS or an SSH tunnel)"),
..Default::default()
});
false
}
fn identify_with_nickserv(&self) {
if !self.cfg.nickserv_identify || self.cfg.nickserv_password.is_empty() {
if !self.cfg.nickserv_identify || self.cfg.nickserv_password.is_empty() || !self.credentials_allowed("NickServ identify") {
return;
}
let body = if self.cfg.nickserv_account.is_empty() {
@@ -781,16 +804,22 @@ impl Client {
fn handle_cap(&self, m: &Message) {
let sub = m.param(1).to_ascii_uppercase();
let caps: Vec<&str> = m.last().split_whitespace().map(|c| c.split('=').next().unwrap_or(c)).collect();
let want_sasl = !self.cfg.sasl_account.is_empty();
let want_sasl = !self.cfg.sasl_account.is_empty() && self.credentials_allowed("SASL login");
if self.st().connected && sub == "LS" {
return; // negotiation is over; a late LS can only grow state
}
match sub.as_str() {
// A multi-line LS list ("CAP * LS * :…") continues; act on the last line.
"LS" if m.params.len() >= 4 && m.param(2) == "*" => {
self.st().caps_offered.extend(caps.iter().map(|c| c.to_string()));
let mut st = self.st();
let room = MAX_CAPS.saturating_sub(st.caps_offered.len());
st.caps_offered.extend(caps.iter().take(room).map(|c| c.to_string()));
}
"LS" => {
let offered: Vec<String> = {
let mut st = self.st();
st.caps_offered.extend(caps.iter().map(|c| c.to_string()));
let room = MAX_CAPS.saturating_sub(st.caps_offered.len());
st.caps_offered.extend(caps.iter().take(room).map(|c| c.to_string()));
std::mem::take(&mut st.caps_offered)
};
let mut req = vec![];
@@ -832,6 +861,9 @@ impl Client {
if !me && !self.tracks(&room) {
return;
}
if me && !self.tracks(&room) && self.st().channels.len() >= MAX_CHANNELS {
return;
}
if !from.is_empty() {
let mut st = self.st();
let ch = st.channels.entry(fold(&room)).or_insert_with(|| Channel { name: room.clone(), topic: String::new(), users: Vec::new() });
@@ -1155,9 +1187,43 @@ pub fn fuzz_lines(data: &[u8]) {
}
}
/// See [`Client::credentials_allowed`].
fn sends_credentials_safely(cfg: &Config) -> bool {
let h = cfg.server.trim_start_matches('[').trim_end_matches(']');
cfg.use_tls || cfg.connector.is_some() || h.eq_ignore_ascii_case("localhost") || h.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn credentials_need_tls_a_tunnel_or_loopback() {
let c = |server: &str, use_tls: bool| Config { server: server.into(), use_tls, ..Default::default() };
assert!(!sends_credentials_safely(&c("irc.libera.chat", false)));
assert!(sends_credentials_safely(&c("irc.libera.chat", true)));
assert!(
sends_credentials_safely(&c("127.0.0.1", false)) && sends_credentials_safely(&c("localhost", false)) && sends_credentials_safely(&c("::1", false))
);
let tunnelled = Config { connector: Some(Arc::new(|| Err("unused".into()))), ..c("irc.example", false) };
assert!(sends_credentials_safely(&tunnelled));
}
#[test]
fn spoofed_self_joins_and_cap_floods_are_bounded() {
let client = Client::new(Config::default());
client.st().nick = "me".into();
let feed = |l: &str| client.handle_message(&parse_line(l).unwrap());
for i in 0..(MAX_CHANNELS + 200) {
feed(&format!(":me!u@h JOIN #r{i}"));
}
assert_eq!(client.st().channels.len(), MAX_CHANNELS);
assert_eq!(client.st().room_names.len(), MAX_CHANNELS);
for _ in 0..50 {
feed(&format!(":srv CAP * LS * :{}", "x ".repeat(100)));
}
assert!(client.st().caps_offered.len() <= MAX_CAPS);
}
use std::io::{BufRead, BufReader};
use std::net::TcpListener;
+16 -1
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Local shell in a PTY (forkpty on Unix, ConPTY on Windows), a port of internal/localshell.
use super::Callbacks;
@@ -60,7 +63,8 @@ impl LocalShell {
.map_err(|e| format!("failed to start shell {:?}: {e}", self.shell))?;
let mut cmd = CommandBuilder::new(&self.shell);
cmd.env_clear();
let env = crate::terminalenv::local_shell_env(std::env::vars().map(|(k, v)| format!("{k}={v}")).collect());
// `vars()` panics on a non-UTF-8 entry (a launcher can plant one); skip those instead.
let env = crate::terminalenv::local_shell_env(std::env::vars_os().filter_map(|(k, v)| Some(format!("{}={}", k.to_str()?, v.to_str()?))).collect());
for kv in env {
if let Some((k, v)) = kv.split_once('=') {
cmd.env(k, v);
@@ -167,6 +171,9 @@ impl LocalShell {
}
}
/// macOS has no cheap cwd lookup (it's an `lsof` run), so the directory is sampled after Enter:
/// the first output after Enter is usually the shell echoing the command, before a `cd` has
/// run, so sample shortly afterwards and again once the command has had time to finish.
fn capture_cwd_in_background(self: &Arc<Self>) {
let Some(pid) = self.state.lock().0.as_ref().and_then(|r| r.pid) else { return };
if self.capturing.swap(true, Ordering::SeqCst) {
@@ -174,10 +181,13 @@ impl LocalShell {
}
let me = self.clone();
std::thread::spawn(move || {
for delay in [150, 850] {
std::thread::sleep(std::time::Duration::from_millis(delay));
// A failed lookup (the shell already exited) keeps the last known directory.
if let Some(dir) = process_cwd(pid).filter(|d| d.is_dir()) {
me.state.lock().1 = dir;
}
}
me.capturing.store(false, Ordering::SeqCst);
});
}
@@ -219,6 +229,11 @@ mod tests {
std::thread::sleep(Duration::from_millis(20));
}
sh.resize(100, 30).unwrap();
// macOS samples the directory shortly after a command runs (Linux reads it live).
while sh.working_directory() != std::path::Path::new("/") {
assert!(t.elapsed() < Duration::from_secs(5), "cwd still {:?}", sh.working_directory());
std::thread::sleep(Duration::from_millis(20));
}
sh.write(b"exit\n").unwrap();
while *closed.lock() == 0 {
assert!(t.elapsed() < Duration::from_secs(5));
+21 -2
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Protocol clients. Conventions, shared by every client so the session manager treats them alike:
//! - `connect()` blocks the calling thread (the manager calls it from a worker thread, as Go
//! called it from a goroutine) and returns once the connection is usable.
@@ -105,22 +108,34 @@ pub(crate) fn dial(host: &str, port: i64, timeout_secs: i64) -> (String, std::io
/// reports `read error: …` then closes; `close` is idempotent and fires `on_close` once).
pub(crate) struct TcpConn {
stream: parking_lot::Mutex<Option<std::net::TcpStream>>,
/// A second handle on the socket, so `close` can shut it down without waiting for the
/// stream lock (a write blocked on a peer that stopped reading holds that lock).
shutdown: parking_lot::Mutex<Option<std::net::TcpStream>>,
/// Set before the socket is shut down, so the reader doesn't report our own close as an error.
closing: std::sync::atomic::AtomicBool,
on_error: ErrorFn,
on_close: CloseFn,
}
/// Longest a single write may block on a peer that has stopped reading; the writes happen on
/// the UI thread (keystrokes) and on the reader thread (negotiation replies).
const WRITE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
impl TcpConn {
pub(crate) fn new(on_error: ErrorFn, on_close: CloseFn) -> TcpConn {
TcpConn { stream: parking_lot::Mutex::new(None), on_error, on_close }
TcpConn { stream: parking_lot::Mutex::new(None), shutdown: parking_lot::Mutex::new(None), closing: Default::default(), on_error, on_close }
}
pub(crate) fn connect(self: &Arc<Self>, stream: std::net::TcpStream, mut on_read: impl FnMut(&[u8]) + Send + 'static) -> crate::Result<()> {
let mut reader = stream.try_clone()?;
let _ = stream.set_write_timeout(Some(WRITE_TIMEOUT));
{
let mut guard = self.stream.lock();
if guard.is_some() {
return Err("already connected".into());
}
*self.shutdown.lock() = stream.try_clone().ok();
self.closing.store(false, std::sync::atomic::Ordering::SeqCst);
*guard = Some(stream);
}
let me = self.clone();
@@ -138,7 +153,7 @@ impl TcpConn {
Err(e) => e.to_string(),
};
// A local close also ends the read; Go reported that as an error too, we don't.
if me.is_connected() {
if me.is_connected() && !me.closing.load(std::sync::atomic::Ordering::SeqCst) {
(me.on_error)(format!("read error: {err}"));
me.close();
}
@@ -161,6 +176,10 @@ impl TcpConn {
}
pub(crate) fn close(&self) {
self.closing.store(true, std::sync::atomic::Ordering::SeqCst);
if let Some(s) = self.shutdown.lock().take() {
let _ = s.shutdown(std::net::Shutdown::Both);
}
let taken = self.stream.lock().take();
if let Some(s) = taken {
let _ = s.shutdown(std::net::Shutdown::Both);
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Outbound proxies (SOCKS5, HTTP CONNECT) for the clients that dial TCP themselves: SSH and RDP.
//! Blocking; async callers run it on a blocking thread.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! RAW TCP client (port of Go `internal/rawclient`): binary-safe send/receive, a capped history
//! of sent ("send") and received ("recv") frames, JSON capture, and the hex/escape encoders the
//! RAW view reuses.
+8 -2
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! RDP client on IronRDP: TLS with NLA (CredSSP), the server certificate pinned through the
//! caller's host-key check, any transport the caller dials (direct, SOCKS5/HTTP proxy or an SSH
//! tunnel), and the desktop decoded into the same RGBA framebuffer the VNC client uses. Like the
@@ -202,6 +205,7 @@ impl Client {
}
if self.cfg.shared_folder.is_some() || self.cfg.printer.is_some() {
let mut devices = super::rdp_devices::Devices::default();
#[cfg_attr(not(unix), allow(unused_mut))]
let mut drives = vec![];
#[cfg(unix)]
if let Some((folder, name)) = &self.cfg.shared_folder {
@@ -259,8 +263,10 @@ impl Client {
fn run(&self, mut framed: Framed<Tls>, result: ConnectionResult, rx: Receiver<Input>) -> Result<()> {
framed.get_inner_mut().0.sock.set_read_timeout(Some(POLL))?;
let size = result.desktop_size;
let mut image = DecodedImage::new(PixelFormat::RgbA32, size.width, size.height);
// Check the server-chosen size before DecodedImage allocates it (65535² is 16 GiB, and
// an allocation failure aborts the whole app rather than failing this session).
*self.fb.lock() = Framebuffer::new_checked(size.width, size.height)?;
let mut image = DecodedImage::new(PixelFormat::RgbA32, size.width, size.height);
let factory = result.activation_factory;
let mut stage = ActiveStageBuilder {
static_channels: result.static_channels,
@@ -349,8 +355,8 @@ impl Client {
if let ConnectionActivationState::Finalized { desktop_size, share_id, enable_server_pointer, pointer_software_rendering } =
seq.connection_activation_state()
{
image = DecodedImage::new(PixelFormat::RgbA32, desktop_size.width, desktop_size.height);
*self.fb.lock() = Framebuffer::new_checked(desktop_size.width, desktop_size.height)?;
image = DecodedImage::new(PixelFormat::RgbA32, desktop_size.width, desktop_size.height);
stage.set_fastpath_processor(
fast_path::ProcessorBuilder {
io_channel_id: seq.io_channel_id(),
+66 -30
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! RDP device redirection: a shared folder as a drive, and a virtual printer whose jobs are saved
//! as PostScript files.
//!
@@ -11,9 +14,11 @@ use ironrdp::core::impl_as_any;
use ironrdp::pdu::PduResult;
use ironrdp::rdpdr::RdpdrBackend;
use ironrdp::rdpdr::pdu::RdpdrPdu;
#[cfg(unix)]
use ironrdp::rdpdr::pdu::efs::FileInformationClass;
use ironrdp::rdpdr::pdu::efs::{
ClientDriveQueryDirectoryResponse, ClientDriveSetInformationResponse, DeviceCloseResponse, DeviceControlRequest, DeviceCreateResponse, DeviceIoResponse,
DeviceWriteResponse, FileInformationClass, Information, NtStatus, PrinterIoRequest, ServerDeviceAnnounceResponse, ServerDriveIoRequest,
DeviceWriteResponse, Information, NtStatus, PrinterIoRequest, ServerDeviceAnnounceResponse, ServerDriveIoRequest,
};
use ironrdp::rdpdr::pdu::esc::{ScardCall, ScardIoCtlCode};
use ironrdp::svc::SvcMessage;
@@ -21,10 +26,18 @@ use ironrdp::svc::SvcMessage;
use ironrdp_rdpdr_native::backend::NixRdpdrBackend;
use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::path::Path;
use std::path::PathBuf;
/// A print job may not grow past this (a hostile server could otherwise fill the disk).
const MAX_PRINT_JOB: u64 = 256 << 20;
/// Print jobs open at once; each holds a file descriptor.
const MAX_OPEN_PRINT_JOBS: usize = 4;
/// Largest drive read served in one request. The server picks the length (a u32), and the
/// native backend allocates it before reading; Windows clients never ask for more than ~1 MiB.
#[cfg(unix)]
const MAX_DRIVE_READ: u32 = 8 << 20;
/// Called with the file a finished print job was saved to.
pub type PrintedFn = std::sync::Arc<dyn Fn(PathBuf) + Send + Sync>;
@@ -69,9 +82,16 @@ impl Spool {
fn handle(&mut self, req: PrinterIoRequest) -> PduResult<Vec<SvcMessage>> {
let pdu = match req {
PrinterIoRequest::Create(r) => {
let name = format!("Nexus print {}.ps", chrono::Local::now().format("%Y-%m-%d %H.%M.%S"));
let path = self.dir.join(name);
match std::fs::File::create(&path) {
// A fresh file per job: two jobs in the same second used to share (and truncate)
// one file, and an existing file of that name was overwritten.
let stamp = chrono::Local::now().format("%Y-%m-%d %H.%M.%S");
let path = self.dir.join(format!("Nexus print {stamp} #{}.ps", self.next_id));
let file = if self.jobs.len() >= MAX_OPEN_PRINT_JOBS {
Err(std::io::Error::other("too many print jobs open"))
} else {
std::fs::OpenOptions::new().write(true).create_new(true).open(&path)
};
match file {
Ok(f) => {
let id = self.next_id;
self.next_id += 1;
@@ -136,7 +156,7 @@ impl RdpdrBackend for Devices {
if let Some(d) = &mut self.drive {
return d.handle(req);
}
ConfinedDrive::refuse(req)
refuse_drive_io(req)
}
fn handle_printer_io_request(&mut self, req: PrinterIoRequest) -> PduResult<Vec<SvcMessage>> {
@@ -149,14 +169,35 @@ impl RdpdrBackend for Devices {
}
}
/// Answers a drive request with a refusal (no shared folder, or a path outside it).
fn refuse_drive_io(req: ServerDriveIoRequest) -> PduResult<Vec<SvcMessage>> {
tracing::warn!("RDP server asked for a path outside the shared folder; refused");
let pdu = match req {
ServerDriveIoRequest::ServerCreateDriveRequest(r) => RdpdrPdu::DeviceCreateResponse(DeviceCreateResponse {
device_io_reply: DeviceIoResponse::new(r.device_io_request, NtStatus::ACCESS_DENIED),
file_id: 0,
information: Information::empty(),
}),
ServerDriveIoRequest::ServerDriveQueryDirectoryRequest(r) => RdpdrPdu::ClientDriveQueryDirectoryResponse(ClientDriveQueryDirectoryResponse {
device_io_reply: DeviceIoResponse::new(r.device_io_request, NtStatus::NO_MORE_FILES),
buffer: None,
}),
ServerDriveIoRequest::ServerDriveSetInformationRequest(r) => RdpdrPdu::ClientDriveSetInformationResponse(
ClientDriveSetInformationResponse::new(&r, NtStatus::ACCESS_DENIED).map_err(|e| ironrdp::pdu::encode_err!(e))?,
),
_ => return Ok(vec![]),
};
Ok(vec![SvcMessage::from(pdu)])
}
#[cfg(unix)]
#[derive(Debug)]
struct ConfinedDrive {
#[cfg(unix)]
inner: NixRdpdrBackend,
#[cfg_attr(not(unix), allow(dead_code))]
base: PathBuf,
}
#[cfg(unix)]
impl ConfinedDrive {
pub fn new(folder: &Path) -> std::io::Result<ConfinedDrive> {
let base = folder.canonicalize()?;
@@ -196,31 +237,16 @@ impl ConfinedDrive {
}
}
}
fn refuse(req: ServerDriveIoRequest) -> PduResult<Vec<SvcMessage>> {
tracing::warn!("RDP server asked for a path outside the shared folder; refused");
let pdu = match req {
ServerDriveIoRequest::ServerCreateDriveRequest(r) => RdpdrPdu::DeviceCreateResponse(DeviceCreateResponse {
device_io_reply: DeviceIoResponse::new(r.device_io_request, NtStatus::ACCESS_DENIED),
file_id: 0,
information: Information::empty(),
}),
ServerDriveIoRequest::ServerDriveQueryDirectoryRequest(r) => RdpdrPdu::ClientDriveQueryDirectoryResponse(ClientDriveQueryDirectoryResponse {
device_io_reply: DeviceIoResponse::new(r.device_io_request, NtStatus::NO_MORE_FILES),
buffer: None,
}),
ServerDriveIoRequest::ServerDriveSetInformationRequest(r) => RdpdrPdu::ClientDriveSetInformationResponse(
ClientDriveSetInformationResponse::new(&r, NtStatus::ACCESS_DENIED).map_err(|e| ironrdp::pdu::encode_err!(e))?,
),
_ => return Ok(vec![]),
};
Ok(vec![SvcMessage::from(pdu)])
}
}
#[cfg(unix)]
impl ConfinedDrive {
#[cfg(unix)]
fn handle(&mut self, req: ServerDriveIoRequest) -> PduResult<Vec<SvcMessage>> {
fn handle(&mut self, mut req: ServerDriveIoRequest) -> PduResult<Vec<SvcMessage>> {
if let ServerDriveIoRequest::DeviceReadRequest(r) = &mut req {
// A short read is valid RDPDR; the server asks again for the rest.
r.length = r.length.min(MAX_DRIVE_READ);
}
let ok = match &req {
ServerDriveIoRequest::ServerCreateDriveRequest(r) => self.allowed(&r.path),
ServerDriveIoRequest::ServerDriveQueryDirectoryRequest(r) => r.initial_query == 0 || self.allowed(r.path.trim_end_matches('*')),
@@ -231,7 +257,7 @@ impl ConfinedDrive {
// Everything else names a file by an id that a checked create handed out.
_ => true,
};
if ok { self.inner.handle_drive_io_request(req) } else { Self::refuse(req) }
if ok { self.inner.handle_drive_io_request(req) } else { refuse_drive_io(req) }
}
}
@@ -283,9 +309,19 @@ mod tests {
dev.handle_printer_io_request(write(3, b"x")).unwrap();
assert_eq!(dev.printer.as_ref().unwrap().jobs[&3].2, MAX_PRINT_JOB);
assert_eq!(printed.lock().len(), 1);
dev.handle_printer_io_request(close(3)).unwrap();
// Jobs started in the same second get their own files, and only a few may be open at once.
for _ in 0..(MAX_OPEN_PRINT_JOBS + 3) {
dev.handle_printer_io_request(create()).unwrap();
}
let jobs = &dev.printer.as_ref().unwrap().jobs;
assert_eq!(jobs.len(), MAX_OPEN_PRINT_JOBS);
let paths: std::collections::HashSet<_> = jobs.values().map(|j| j.1.clone()).collect();
assert_eq!(paths.len(), MAX_OPEN_PRINT_JOBS);
std::fs::remove_dir_all(dir).unwrap();
}
#[cfg(unix)]
#[test]
fn server_paths_stay_inside_the_share() {
let root = std::env::temp_dir().join(format!("nexus-drive-{}", std::process::id()));
+4
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Serial client (new protocol, no Go original) on the `serialport` crate. The device path is
//! `Profile::host`, line settings come from `Profile::serial`. Same conventions as the other
//! clients: blocking `connect`, an own reader thread, `on_close` exactly once (unplug included).
@@ -203,6 +206,7 @@ fn open_error(path: &str, e: &serialport::Error) -> crate::Error {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(target_os = "linux")]
use std::sync::mpsc;
#[test]
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! SFTP operations over an SSH session's subsystem (internal/sftpclient). Every call blocks the
//! caller, so the UI runs them on worker threads.
+54 -19
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! SSH client on russh: interactive PTY shell, the profile's auth chain (agent, public key,
//! password, keyboard-interactive with TOTP), jump hosts, SOCKS5/HTTP proxies, local and remote
//! port forwards, agent forwarding and SFTP. A port of internal/sshclient + sftpclient.
@@ -20,6 +23,16 @@ use zeroize::Zeroizing;
const MAX_PRIVATE_KEY_BYTES: u64 = 1 << 20;
/// Bounds what `run_command` buffers, so a hostile server can't stream unlimited output into memory.
const MAX_COMMAND_OUTPUT_BYTES: usize = 1 << 20;
/// How long `run_command` waits for a command to finish.
const COMMAND_TIMEOUT: Duration = Duration::from_secs(30);
/// Keyboard-interactive rounds answered before giving up on the method.
const MAX_KBD_INTERACTIVE_ROUNDS: usize = 10;
/// Extra handshake time allowed for the host-key prompt (see `credentials::host_key_check`).
const HOST_KEY_PROMPT_SECS: u64 = 60;
/// Remote forwards listen on the server's loopback unless told otherwise, as `ssh -R` does; an
/// empty bind host used to mean every interface, exposing the forwarded service to the server's
/// whole network wherever `GatewayPorts` is on.
const REMOTE_BIND_DEFAULT: &str = "localhost";
/// What a host-key decision needs. The manager's checker consults the known-hosts table and,
/// per policy, prompts the user; it returns Err with the reason to reject.
@@ -61,6 +74,9 @@ struct Handler {
port: u16,
check: HostKeyCheck,
shared: Arc<Shared>,
/// Whether this is the final hop. Only the target may open agent-forward and remote-forward
/// channels; a jump host never asked for either and must not get them (as `ssh -J` behaves).
target: bool,
/// Certificate authorities trusted for this host (from `@cert-authority` known-hosts rows).
cas: Vec<PublicKey>,
}
@@ -123,7 +139,7 @@ impl client::Handler for Handler {
_session: &mut client::Session,
) -> std::result::Result<(), Self::Error> {
let dest = self.shared.remote_targets.lock().get(&(connected_address.to_string(), connected_port)).cloned();
let Some((host, port)) = dest else {
let Some((host, port)) = dest.filter(|_| self.target) else {
reply.reject(russh::ChannelOpenFailure::AdministrativelyProhibited).await;
return Ok(());
};
@@ -143,7 +159,7 @@ impl client::Handler for Handler {
reply: client::ChannelOpenHandle,
_session: &mut client::Session,
) -> std::result::Result<(), Self::Error> {
if !self.shared.agent_forwarding.load(std::sync::atomic::Ordering::Relaxed) {
if !self.target || !self.shared.agent_forwarding.load(std::sync::atomic::Ordering::Relaxed) {
reply.reject(russh::ChannelOpenFailure::AdministrativelyProhibited).await;
return Ok(());
}
@@ -348,7 +364,9 @@ async fn authenticate(h: &mut Handle<Handler>, a: Auth<'_>) -> Result<()> {
"keyboard-interactive" => {
let Some(get) = a.password.clone() else { continue };
let mut resp = h.authenticate_keyboard_interactive_start(a.user, None).await?;
loop {
// A server can keep asking forever (harvesting TOTP codes, parking the connect
// thread on prompts); OpenSSH gives up after a handful of rounds too.
for _ in 0..MAX_KBD_INTERACTIVE_ROUNDS {
match resp {
client::KeyboardInteractiveAuthResponse::Success => return Ok(()),
client::KeyboardInteractiveAuthResponse::Failure { .. } => break,
@@ -469,11 +487,14 @@ impl SshClient {
host: &str,
port: u16,
check: &HostKeyCheck,
target: bool,
) -> Result<Handle<Handler>> {
let cas = crate::known_hosts::authorities_for(&self.authorities.lock(), host, port);
let cfg = config(&self.sc(), !cas.is_empty());
let handler = Handler { host: host.into(), port, check: check.clone(), shared: self.shared.clone(), cas };
let timeout = Duration::from_secs(self.profile.connect_timeout.max(1) as u64);
let handler = Handler { host: host.into(), port, check: check.clone(), shared: self.shared.clone(), cas, target };
// The handshake may stop at the host-key prompt (up to 60 s): don't let the connect
// timeout expire underneath the user while they read a fingerprint.
let timeout = Duration::from_secs(self.profile.connect_timeout.max(1) as u64 + HOST_KEY_PROMPT_SECS);
match tokio::time::timeout(timeout, client::connect_stream(cfg, stream, handler)).await {
Err(_) => Err(format!("SSH handshake with {host}:{port} timed out").into()),
Ok(Ok(h)) => Ok(h),
@@ -507,16 +528,16 @@ impl SshClient {
};
let mut handle = if sc.jump_hosts.is_empty() {
let tcp = dial(&sc, &proxy_password, &p.host, port, timeout).await.map_err(|e| format!("SSH connection failed: {e}"))?;
self.handshake(tcp, &p.host, port, &check).await?
self.handshake(tcp, &p.host, port, &check, true).await?
} else {
let (prev, h) = self.via_jumps(&sc, &check, passphrase.clone(), timeout).await?;
let ch = prev
.channel_open_direct_tcpip(p.host.clone(), port as u32, "127.0.0.1", 0)
let ch = tokio::time::timeout(timeout, prev.channel_open_direct_tcpip(p.host.clone(), port as u32, "127.0.0.1", 0))
.await
.map_err(|_| format!("failed to dial target {}:{port} through jump hosts: timeout", p.host))?
.map_err(|e| format!("failed to dial target {}:{port} through jump hosts: {e}", p.host))?;
self.hops.lock().extend(h);
self.hops.lock().push(prev);
self.handshake(ch.into_stream(), &p.host, port, &check).await?
self.handshake(ch.into_stream(), &p.host, port, &check, true).await?
};
let cert = load_user_certificate(&sc.private_key_path);
@@ -600,14 +621,14 @@ impl SshClient {
.await
.map_err(|_| format!("failed to connect to jump host {i} ({host}:{jport}): timeout"))?
.map_err(|e| format!("failed to connect to jump host {i} ({host}:{jport}): {e}"))?;
self.handshake(tcp, host, jport, check).await?
self.handshake(tcp, host, jport, check, false).await?
}
Some(prev) => {
let ch = prev
.channel_open_direct_tcpip(host.clone(), jport as u32, "127.0.0.1", 0)
let ch = tokio::time::timeout(timeout, prev.channel_open_direct_tcpip(host.clone(), jport as u32, "127.0.0.1", 0))
.await
.map_err(|_| format!("failed to dial through jump host {i} ({host}:{jport}): timeout"))?
.map_err(|e| format!("failed to dial through jump host {i} ({host}:{jport}): {e}"))?;
self.handshake(ch.into_stream(), host, jport, check).await?
self.handshake(ch.into_stream(), host, jport, check, false).await?
}
};
authenticate(
@@ -652,11 +673,21 @@ impl SshClient {
Ok(start.elapsed().as_millis() as i64)
}
/// Runs a command on a separate channel and returns trimmed stdout.
/// Runs a command on a separate channel and returns trimmed stdout, giving up after
/// `COMMAND_TIMEOUT` so a server that never answers can't park the caller's thread.
pub fn run_command(&self, command: &str) -> Result<String> {
let h = self.handle()?;
let command = command.to_string();
rt().block_on(async move {
match tokio::time::timeout(COMMAND_TIMEOUT, Self::run_command_inner(h, command)).await {
Ok(r) => r,
Err(_) => Err("command timed out".into()),
}
})
}
async fn run_command_inner(h: Arc<Handle<Handler>>, command: String) -> Result<String> {
{
let mut ch = h.channel_open_session().await.map_err(|e| format!("failed to open SSH session: {e}"))?;
ch.exec(true, command.as_bytes()).await?;
let mut out = vec![];
@@ -673,7 +704,7 @@ impl SshClient {
}
}
Ok(String::from_utf8_lossy(&out).trim().to_string())
})
}
}
pub fn is_connected(&self) -> bool {
@@ -733,7 +764,7 @@ impl SshClient {
tasks.lock().push(task.abort_handle());
}
ForwardDirection::Remote => {
let bind = if rule.bind_host.is_empty() { "0.0.0.0".to_string() } else { rule.bind_host.clone() };
let bind = if rule.bind_host.is_empty() { REMOTE_BIND_DEFAULT.to_string() } else { rule.bind_host.clone() };
let port = rt()
.block_on(h.tcpip_forward(bind.clone(), rule.bind_port as u32))
.map_err(|e| format!("remote forward: server listen on {bind}:{} failed: {e}", rule.bind_port))?;
@@ -756,7 +787,7 @@ impl SshClient {
t.abort();
}
if f.rule.direction == ForwardDirection::Remote {
let bind = if f.rule.bind_host.is_empty() { "0.0.0.0".to_string() } else { f.rule.bind_host.clone() };
let bind = if f.rule.bind_host.is_empty() { REMOTE_BIND_DEFAULT.to_string() } else { f.rule.bind_host.clone() };
self.shared.remote_targets.lock().retain(|(a, p), _| !(a == &bind && *p == f.rule.bind_port as u32));
if let Ok(h) = self.handle() {
let port = f.rule.bind_port as u32;
@@ -840,7 +871,7 @@ pub fn generate_key_pair(dir: &std::path::Path, name: &str, kind: &str, bits: u3
let comment = format!("{name}@nexus-terminal");
let key = russh::keys::PrivateKey::new(data, comment.as_str()).map_err(|e| e.to_string())?;
let key = if passphrase.is_empty() { key } else { key.encrypt(&mut rng, passphrase.as_bytes()).map_err(|e| e.to_string())? };
std::fs::create_dir_all(dir)?;
crate::config::create_private_dir(dir)?;
let path = dir.join(&name);
if path.exists() || path.with_extension("pub").exists() {
return Err(format!("key {name:?} already exists").into());
@@ -904,7 +935,11 @@ mod tests {
let public = std::fs::read_to_string(dir.join("id_test.pub")).unwrap();
assert!(public.starts_with("ssh-ed25519 ") && public.trim_end().ends_with("id_test@nexus-terminal"), "{public}");
#[cfg(unix)]
assert_eq!(std::os::unix::fs::PermissionsExt::mode(&std::fs::metadata(&path).unwrap().permissions()) & 0o777, 0o600);
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700, "a fresh ~/.ssh is private");
}
assert!(crate::keyfiles::is_likely_private_key(&path));
// Encrypted: unreadable without the passphrase, readable with it.
let p = path.to_string_lossy().into_owned();
+68 -8
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Telnet client (port of Go `internal/telnetclient`): RFC 854/855 option negotiation (ECHO, SGA,
//! TTYPE, NAWS; everything else refused), IAC escaping, line-ending conversion, ISO 8859-1 output
//! encoding and BRK. Go read but never acted on `lineMode`, and neither do we.
@@ -48,6 +51,11 @@ struct State {
local_echo: bool,
cols: u16,
rows: u16,
/// Options we have agreed to perform (WILL) and the peer has agreed to (DO), so a request
/// for a state we're already in isn't answered (RFC 854 forbids it; answering unconditionally
/// lets a hostile or naive peer drive an endless DONT/WONT ping-pong at line rate).
us: std::collections::HashSet<u8>,
him: std::collections::HashSet<u8>,
}
impl TelnetClient {
@@ -56,7 +64,7 @@ impl TelnetClient {
pub fn new(profile: &Profile, cb: Callbacks, on_debug: Option<DebugFn>) -> TelnetClient {
let cfg = profile.telnet.clone().unwrap_or_default();
let encoding = if cfg.encoding.is_empty() { "utf-8".to_string() } else { cfg.encoding.clone() };
let state = State { local_echo: cfg.local_echo, cols: 80, rows: 24 };
let state = State { local_echo: cfg.local_echo, cols: 80, rows: 24, us: Default::default(), him: Default::default() };
TelnetClient {
inner: Arc::new(Inner {
conn: Arc::new(TcpConn::new(cb.on_error, cb.on_close)),
@@ -193,32 +201,42 @@ impl Inner {
fn handle_do(&self, opt: u8) {
self.debug(format!("received DO {opt}"));
match opt {
OPT_TERM_TYPE | OPT_SGA => self.negotiate(WILL, opt),
OPT_NAWS => {
OPT_TERM_TYPE | OPT_SGA | OPT_NAWS => {
if !self.state.lock().us.insert(opt) {
return;
}
self.negotiate(WILL, opt);
if opt == OPT_NAWS {
let (cols, rows) = {
let st = self.state.lock();
(st.cols, st.rows)
};
let _ = self.send_naws(cols, rows);
}
}
_ => self.negotiate(WONT, opt),
}
}
fn handle_dont(&self, opt: u8) {
self.debug(format!("received DONT {opt}"));
if self.state.lock().us.remove(&opt) {
self.negotiate(WONT, opt);
}
}
fn handle_will(&self, opt: u8) {
self.debug(format!("received WILL {opt}"));
match opt {
OPT_ECHO => {
OPT_ECHO | OPT_SGA => {
if !self.state.lock().him.insert(opt) {
return;
}
self.negotiate(DO, opt);
if opt == OPT_ECHO {
self.state.lock().local_echo = false;
}
OPT_SGA => self.negotiate(DO, opt),
}
_ => self.negotiate(DONT, opt),
}
}
@@ -228,8 +246,10 @@ impl Inner {
if opt == OPT_ECHO {
self.state.lock().local_echo = true;
}
if self.state.lock().him.remove(&opt) {
self.negotiate(DONT, opt);
}
}
fn process_subnegotiation(&self, payload: &[u8]) {
let Some(&opt) = payload.first() else { return };
@@ -251,9 +271,17 @@ impl Inner {
fn send_naws(&self, cols: u16, rows: u16) -> crate::Result<()> {
self.debug(format!("sending NAWS: {cols}x{rows}"));
let [c0, c1] = cols.to_be_bytes();
let [r0, r1] = rows.to_be_bytes();
self.conn.write(&[IAC, SB, OPT_NAWS, c0, c1, r0, r1, IAC, SE])
// 0xFF inside the subnegotiation must be doubled (RFC 1073), or a 255-column window
// sends a bare IAC the server parses as a command.
let mut msg = vec![IAC, SB, OPT_NAWS];
for b in cols.to_be_bytes().into_iter().chain(rows.to_be_bytes()) {
msg.push(b);
if b == IAC {
msg.push(IAC);
}
}
msg.extend_from_slice(&[IAC, SE]);
self.conn.write(&msg)
}
fn debug(&self, msg: String) {
@@ -346,6 +374,38 @@ mod tests {
}
}
#[test]
fn negotiation_replies_only_on_state_change() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let profile = Profile { host: "127.0.0.1".into(), port: listener.local_addr().unwrap().port() as i64, ..Profile::new(crate::models::Protocol::Telnet) };
let client = TelnetClient::new(&profile, Callbacks::noop(), None);
client.connect().unwrap();
let (mut srv, _) = listener.accept().unwrap();
srv.set_read_timeout(Some(Duration::from_millis(500))).unwrap();
// DONT/WONT for options that are already off, and repeated WILL/DO, get no reply;
// only the first WILL SGA and the first DO SGA are answered.
let mut flood = vec![];
for _ in 0..100 {
flood.extend_from_slice(&[IAC, DONT, 1, IAC, WONT, 1, IAC, WILL, OPT_SGA, IAC, DO, OPT_SGA]);
}
srv.write_all(&flood).unwrap();
let mut got = vec![];
let mut buf = [0u8; 4096];
while let Ok(n) = srv.read(&mut buf) {
if n == 0 {
break;
}
got.extend_from_slice(&buf[..n]);
}
assert_eq!(got, [IAC, DO, OPT_SGA, IAC, WILL, OPT_SGA]);
// A 255-column window doubles the 0xFF inside the NAWS subnegotiation.
srv.write_all(&[IAC, DO, OPT_NAWS]).unwrap();
let _ = read_n(&mut srv, 3 + 9);
client.resize(255, 24).unwrap();
assert_eq!(read_n(&mut srv, 10), [IAC, SB, OPT_NAWS, 0, 255, 255, 0, 24, IAC, SE]);
client.close();
}
#[test]
fn line_endings() {
let cases = [
+77 -14
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Native VNC (RFB 3.3/3.7/3.8) client: None and VNC Authentication, Raw, CopyRect, Hextile, ZRLE
//! and Tight (zlib + JPEG), plus the DesktopSize, ExtendedDesktopSize and LastRect pseudo-encodings.
//!
@@ -461,23 +464,39 @@ impl Conn {
}
}
impl Conn {
/// Writes queued input (keys, pointer, clipboard) and notices a local close. Runs after every
/// read, not only on read timeouts, so a server that streams without pause can't starve
/// our output or keep a closed tab's connection alive.
fn pump_out(&mut self) -> std::io::Result<()> {
let mut wrote = false;
loop {
match self.out_rx.try_recv() {
Ok(msg) => {
self.io.write_all(&msg)?;
wrote = true;
}
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => return Err(std::io::Error::other("closed")),
}
}
if wrote { self.io.flush() } else { Ok(()) }
}
}
impl Read for Conn {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
loop {
match self.io.read(buf) {
Ok(0) => return Err(std::io::Error::new(ErrorKind::UnexpectedEof, "connection closed by server")),
Ok(n) => return Ok(n),
Ok(n) => {
self.pump_out()?;
return Ok(n);
}
Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut | ErrorKind::Interrupted) => {}
Err(e) => return Err(e),
}
loop {
match self.out_rx.try_recv() {
Ok(msg) => self.io.write_all(&msg)?,
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => return Err(std::io::Error::other("closed")),
}
}
self.io.flush()?;
self.pump_out()?;
}
}
}
@@ -523,21 +542,45 @@ impl Default for Decoders {
}
}
/// Inflates one server chunk (which ends at a sync flush) into `out`.
fn inflate(z: &mut Decompress, mut input: &[u8], out: &mut Vec<u8>) -> crate::Result<()> {
/// Inflates one server chunk (which ends at a sync flush) into `out`, refusing to grow past
/// `max_out`: the caller knows how many bytes a rectangle can legitimately need, and a zlib bomb
/// would otherwise expand a few hundred KiB from the wire into gigabytes.
fn inflate(z: &mut Decompress, mut input: &[u8], out: &mut Vec<u8>, max_out: usize) -> crate::Result<()> {
out.clear();
loop {
out.reserve(64 << 10);
if out.len() > max_out {
return Err(format!("compressed rectangle inflates past {max_out} bytes").into());
}
// Never ask for more room than the cap allows (plus one byte to detect overflow).
out.reserve((64 << 10).min(max_out + 1 - out.len()));
let (i0, o0) = (z.total_in(), z.total_out());
z.decompress_vec(input, out, FlushDecompress::Sync).map_err(|e| format!("zlib: {e}"))?;
input = &input[(z.total_in() - i0) as usize..];
let stalled = z.total_in() == i0 && z.total_out() == o0;
if out.len() > max_out {
return Err(format!("compressed rectangle inflates past {max_out} bytes").into());
}
if (input.is_empty() && out.len() < out.capacity()) || stalled {
return Ok(());
}
}
}
/// A rectangle's decoded size can't exceed this, whatever the encoding: raw pixels plus, per
/// 64×64 ZRLE tile, a subencoding byte and a 128-entry palette.
fn max_inflated(w: usize, h: usize) -> usize {
let tiles = w.div_ceil(64) * h.div_ceil(64);
w * h * 4 + tiles * (1 + 128 * 4)
}
/// Returns a decode scratch buffer to a modest size after a big rectangle, so one large update
/// doesn't pin hundreds of MiB for the rest of the session.
fn shrink_scratch(buf: &mut Vec<u8>) {
if buf.capacity() > (8 << 20) {
*buf = Vec::new();
}
}
/// Reads one FramebufferUpdate (after the type byte) into `fb`. Returns the changed row range and
/// whether the desktop was resized.
fn read_update(r: &mut impl Read, fb: &mut Framebuffer, dec: &mut Decoders) -> crate::Result<(usize, usize, bool)> {
@@ -592,8 +635,9 @@ fn read_update(r: &mut impl Read, fb: &mut Framebuffer, dec: &mut Decoders) -> c
return Err(format!("ZRLE rectangle of {len} bytes exceeds {MAX_ZRLE_BYTES}").into());
}
let data = read_n(r, len)?;
inflate(&mut dec.zrle, &data, &mut dec.buf)?;
inflate(&mut dec.zrle, &data, &mut dec.buf, max_inflated(w as usize, ht as usize))?;
zrle(&dec.buf, fb, x, y, w, ht)?;
shrink_scratch(&mut dec.buf);
}
e => return Err(format!("unsupported encoding {e}").into()),
}
@@ -770,7 +814,7 @@ fn tight(r: &mut impl Read, fb: &mut Framebuffer, dec: &mut Decoders, x: u16, y:
} else {
let len = compact_len(r)?;
let compressed = read_n(r, len)?;
inflate(&mut dec.tight[(ctl >> 4 & 3) as usize], &compressed, &mut dec.buf)?;
inflate(&mut dec.tight[(ctl >> 4 & 3) as usize], &compressed, &mut dec.buf, size)?;
std::mem::take(&mut dec.buf)
};
if data.len() < size {
@@ -877,6 +921,25 @@ pub fn fuzz_updates(data: &[u8]) {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn inflate_refuses_zlib_bombs() {
use flate2::{Compress, Compression, FlushCompress};
// 64 MiB of zeros compresses to ~64 KiB; a 4x4 rectangle may only need a few hundred bytes.
let mut z = Compress::new(Compression::best(), true);
let mut wire = Vec::with_capacity(1 << 20);
z.compress_vec(&vec![0u8; 64 << 20], &mut wire, FlushCompress::Sync).unwrap();
let (mut d, mut out) = (Decompress::new(true), Vec::new());
assert!(inflate(&mut d, &wire, &mut out, max_inflated(4, 4)).is_err());
assert!(out.capacity() < 1 << 20, "never grew far past the cap: {}", out.capacity());
// A legitimate rectangle still inflates.
let mut z = Compress::new(Compression::fast(), true);
let mut wire = Vec::with_capacity(4096);
z.compress_vec(&[7u8; 64], &mut wire, FlushCompress::Sync).unwrap();
let (mut d, mut out) = (Decompress::new(true), Vec::new());
inflate(&mut d, &wire, &mut out, max_inflated(4, 4)).unwrap();
assert_eq!(out, [7u8; 64]);
}
use std::net::TcpListener;
#[test]
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Data directories.
use std::path::{Path, PathBuf};
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Password-encrypted profile exports: `[version 1][salt 32][nonce 12][AES-256-GCM ciphertext]`
//! over a JSON bundle, with the vault's Argon2id parameters.
+15 -4
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! mIRC formatting (^B ^] ^^ ^_ ^V ^Q ^O ^C fg,bg ^D hex) to styled spans, the nick colour hash
//! and the IRC event line layout. Ported from the Wails frontend's `irc.js`.
//!
@@ -224,10 +227,10 @@ fn strip_terminal_escapes(value: &str) -> String {
s.push_str(&rest[..pos]);
rest = &body[end..];
}
None => {
s.push_str(&rest[..pos + 2]);
rest = body;
}
// No terminator anywhere after this OSC, so none after any later OSC either:
// keep the rest as is. (Advancing two bytes and searching again was quadratic, and
// one hostile 1 MiB line of "\x1b]" froze the UI for minutes.)
None => break,
}
}
s.push_str(rest);
@@ -425,6 +428,14 @@ mod tests {
assert_eq!(plain_text("\x02bold\x02 \x0304red\x03"), "bold red");
}
#[test]
fn unterminated_osc_runs_are_linear() {
let start = std::time::Instant::now();
let out = plain_text(&"\x1b]".repeat(500_000));
assert!(start.elapsed() < std::time::Duration::from_secs(2), "{:?}", start.elapsed());
assert!(!out.contains('\x1b'));
}
#[test]
fn untrusted_terminal_sequences_are_removed() {
assert_eq!(plain_text("before\x1b[31munsafe\x1b]0;title\x07after"), "beforeunsafeafter");
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! SSH key file helpers that need no SSH crypto: spotting private keys, listing `~/.ssh`, and
//! sanitising key and upload file names.
+55 -6
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! OpenSSH `known_hosts` interchange and SSH certificate authorities.
//!
//! Imported host keys become ordinary known-host rows. `@cert-authority` lines become rows with
@@ -11,6 +14,8 @@ use russh::keys::{HashAlg, PublicKey};
/// `key_type` of a certificate-authority row.
pub const CA_KEY_TYPE: &str = "@cert-authority";
/// Longest host pattern accepted (OpenSSH's own line limit is 8 KiB; real patterns are tiny).
pub const MAX_PATTERN_LEN: usize = 1024;
#[derive(Debug, Default, PartialEq)]
pub struct Parsed {
@@ -35,6 +40,7 @@ pub fn parse(text: &str) -> Parsed {
continue;
};
match marker {
Some("@cert-authority") if hosts.len() > MAX_PATTERN_LEN => out.skipped += 1,
Some("@cert-authority") => out.authorities.push((hosts.to_string(), key)),
Some(_) => out.skipped += 1,
None if hosts.starts_with('|') => out.skipped += 1,
@@ -116,14 +122,34 @@ pub fn pattern_matches(patterns: &str, host: &str, port: u16) -> bool {
matched
}
/// Wildcard match with `*` and `?`, iterative and linear in `|p| + |s|` per star (the classic
/// two-pointer algorithm), so a pattern of a million stars or `*a*a*a…` can't recurse or
/// backtrack exponentially. Patterns come from imported files and typed input.
fn glob(p: &str, s: &str) -> bool {
match (p.chars().next(), s.chars().next()) {
(None, None) => true,
(Some('*'), _) => glob(&p[1..], s) || (!s.is_empty() && glob(p, &s[s.chars().next().unwrap().len_utf8()..])),
(Some('?'), Some(c)) => glob(&p[1..], &s[c.len_utf8()..]),
(Some(a), Some(b)) if a == b => glob(&p[a.len_utf8()..], &s[b.len_utf8()..]),
_ => false,
let (p, s): (Vec<char>, Vec<char>) = (p.chars().collect(), s.chars().collect());
let (mut pi, mut si) = (0, 0);
let mut star: Option<(usize, usize)> = None;
while si < s.len() {
match p.get(pi) {
Some('*') => {
star = Some((pi, si));
pi += 1;
}
Some(&c) if c == '?' || c == s[si] => {
pi += 1;
si += 1;
}
_ => match star {
Some((sp, ss)) => {
pi = sp + 1;
si = ss + 1;
star = Some((sp, ss + 1));
}
None => return false,
},
}
}
p[pi..].iter().all(|&c| c == '*')
}
/// CA keys trusted for `host:port`.
@@ -180,6 +206,29 @@ mod tests {
assert!(!pattern_matches(pats, "corp.example", 22));
}
#[test]
fn hostile_patterns_match_in_linear_time() {
// The old recursive matcher overflowed the stack on a long run of stars and went
// exponential on `*a*a*a…b`; both must now be instant (and run on a small stack).
let t = std::thread::Builder::new()
.stack_size(256 << 10)
.spawn(|| {
let start = std::time::Instant::now();
assert!(pattern_matches(&"*".repeat(200_000), "db.corp", 22));
assert!(!pattern_matches("*a*a*a*a*a*a*a*a*a*a*b", &"a".repeat(253), 22));
assert!(pattern_matches("*a*a*a*b?", &format!("{}bx", "a".repeat(253)), 22));
assert!(!pattern_matches("a*c", "ab", 22) && pattern_matches("a*", "a", 22) && !pattern_matches("a?", "a", 22));
start.elapsed()
})
.unwrap()
.join()
.unwrap();
assert!(t < std::time::Duration::from_millis(500), "{t:?}");
// Over-long CA patterns in an imported file are skipped rather than stored.
let p = parse(&format!("@cert-authority {} {}\n", "*".repeat(MAX_PATTERN_LEN + 1), ed()));
assert!(p.authorities.is_empty() && p.skipped == 1);
}
#[test]
fn exports_what_it_imports() {
let ED = ed();
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! nexus-core: everything in Nexus Terminal that isn't drawing — storage, secrets, protocol
//! clients and the session manager. The egui app is one client of this crate.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Data model shared by storage, the session manager and the UI. Field names are the JSON keys
//! used in the database's config columns and in `.nexus` exports.
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Session recording in asciicast v2 (https://docs.asciinema.org/manual/asciicast/v2/): a JSON
//! header line, then one `[elapsed_secs, type, data]` array per line. Same files as the Go app.
+49 -13
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Credential storage: the OS keychain first, then an Argon2id + AES-256-GCM vault file that is
//! byte-compatible with the Go app's `vault/vault.json`.
@@ -236,12 +239,13 @@ impl Vault {
write_private(&self.path(), &data)
}
pub fn get(&self, key: &str) -> Result<String> {
pub fn get(&self, key: &str) -> Result<Zeroizing<String>> {
let st = self.state.lock();
let u = st.as_ref().ok_or("secrets: vault is locked")?;
let enc = u.vault.secrets.get(key).ok_or_else(|| format!("secrets: key {key:?} not found"))?;
let data = B64.decode(enc).map_err(|e| format!("failed to decode secret: {e}"))?;
Ok(String::from_utf8_lossy(&open(&u.key, &data)?).into_owned())
let plain = Zeroizing::new(open(&u.key, &data)?);
Ok(Zeroizing::new(String::from_utf8_lossy(&plain).into_owned()))
}
pub fn set(&self, key: &str, value: &str) -> Result<()> {
@@ -269,17 +273,26 @@ impl Vault {
/// Writes a file readable only by the owner, atomically: the data goes to a sibling temp file
/// that replaces `path` only once it is fully written and synced, so a crash can't leave a
/// truncated vault or export behind (and an existing file's wider mode is never kept).
/// truncated vault or export behind (and an existing file's wider mode is never kept). The temp
/// file is created exclusively under an unguessable name, so nothing pre-placed in the folder (a
/// symlink in a shared sync folder, say) can be followed or overwritten.
pub fn write_private(path: &std::path::Path, data: &[u8]) -> Result<()> {
use std::io::Write;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let tmp = path.with_file_name(format!(".{name}.tmp-{}", std::process::id()));
let name = path.file_name().ok_or("write_private: path has no file name")?.to_string_lossy().into_owned();
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true);
opts.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o600);
let mut tmp = path.to_path_buf();
let written = (|| {
let mut f = opts.open(&tmp)?;
let mut f = loop {
let r = random_bytes::<8>();
tmp = path.with_file_name(format!(".{name}.tmp-{}", r.iter().map(|b| format!("{b:02x}")).collect::<String>()));
match opts.open(&tmp) {
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
r => break r?,
}
};
f.write_all(data)?;
f.sync_all()?;
std::fs::rename(&tmp, path)
@@ -321,9 +334,9 @@ impl Keychain {
off_runtime(move || matches!(entry(&service, "__nexus_keychain_probe__").and_then(|e| e.get_password()), Ok(_) | Err(keyring::Error::NoEntry)))
}
pub fn get(&self, key: &str) -> Option<String> {
pub fn get(&self, key: &str) -> Option<Zeroizing<String>> {
let (service, key) = (self.service.clone(), key.to_string());
off_runtime(move || entry(&service, &key).and_then(|e| e.get_password())).ok()
off_runtime(move || entry(&service, &key).and_then(|e| e.get_password())).ok().map(Zeroizing::new)
}
pub fn set(&self, key: &str, value: &str) -> Result<()> {
@@ -352,7 +365,7 @@ impl Secrets {
Secrets { vault, keychain, keychain_ok }
}
pub fn get(&self, key: &str) -> Option<String> {
pub fn get(&self, key: &str) -> Option<Zeroizing<String>> {
if self.keychain_ok
&& let Some(v) = self.keychain.get(key).filter(|v| !v.is_empty())
{
@@ -423,7 +436,7 @@ mod tests {
v.lock();
assert!(v.get("a").is_err());
v.unlock("pw").unwrap();
assert_eq!(v.get("a").unwrap(), "1");
assert_eq!(*v.get("a").unwrap(), "1");
std::fs::remove_dir_all(dir).unwrap();
}
@@ -459,7 +472,7 @@ mod tests {
v.lock();
assert!(v.unlock("old").is_err(), "the old password no longer opens it");
v.unlock("new").unwrap();
assert_eq!((v.get("a").unwrap(), v.get("profile:p:password").unwrap()), ("1".to_string(), "hunter2".to_string()));
assert_eq!((v.get("a").unwrap().as_str(), v.get("profile:p:password").unwrap().as_str()), ("1", "hunter2"));
assert_eq!(v.keys(), ["a", "profile:p:password"]);
std::fs::remove_dir_all(dir).unwrap();
}
@@ -496,7 +509,30 @@ mod tests {
s.vault.set("profile:p2:password", "keep").unwrap();
s.delete_profile("p1");
assert!(SecretKind::ALL.iter().all(|k| s.get(&k.key("p1")).is_none()));
assert_eq!(s.get("profile:p2:password").as_deref(), Some("keep"));
assert_eq!(s.get("profile:p2:password").as_deref().map(String::as_str), Some("keep"));
std::fs::remove_dir_all(dir).unwrap();
}
#[cfg(unix)]
#[test]
fn write_private_never_follows_links_or_leaves_temp_files() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("nexus-wp-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let canary = dir.join("canary");
std::fs::write(&canary, b"untouched").unwrap();
// A pre-placed symlink at the destination is replaced, not followed.
let target = dir.join("out");
std::os::unix::fs::symlink(&canary, &target).unwrap();
write_private(&target, b"secret").unwrap();
assert_eq!(std::fs::read(&canary).unwrap(), b"untouched");
assert!(std::fs::symlink_metadata(&target).unwrap().file_type().is_file());
assert_eq!(std::fs::read(&target).unwrap(), b"secret");
assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o600);
// No temp file is left behind, and the temp name isn't the old predictable one.
let names: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
assert!(names.iter().all(|n| !n.contains(".tmp-")), "{names:?}");
std::fs::remove_dir_all(dir).unwrap();
}
}
+55 -5
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! The app-facing API (a port of internal/api.Service minus the Wails plumbing): profiles,
//! sessions, credentials, known hosts, preferences, snippets, import/export, SSH keys, updates.
//! File dialogs live in the UI; methods here take paths.
@@ -43,6 +46,9 @@ pub struct Service {
pub store: Arc<Store>,
pub secrets: Arc<Secrets>,
pub sessions: Arc<Manager>,
/// Whether a sync password is stored, probed at most every few seconds: the Settings page
/// asks every frame, and each probe is a keychain round trip that fetches the real value.
sync_password: parking_lot::Mutex<Option<(std::time::Instant, bool)>>,
}
#[derive(Clone, Debug)]
@@ -58,7 +64,7 @@ impl Service {
let store = Arc::new(Store::open(&config.db_path)?);
let secrets = Arc::new(Secrets::new(Vault::new(config.vault_dir.clone()), Keychain::new(KEYCHAIN_SERVICE)));
let sessions = Manager::new(store.clone(), secrets.clone(), config.recordings_dir.clone());
Ok(Service { config, store, secrets, sessions })
Ok(Service { config, store, secrets, sessions, sync_password: Default::default() })
}
// --- profiles -----------------------------------------------------------------------
@@ -109,12 +115,39 @@ impl Service {
Ok(d)
}
/// Saved credentials are keyed by profile id. When a profile arriving from a sync folder or
/// an import keeps the id but points somewhere else (another host, user, GitHub API or RD
/// Gateway), the saved password/token would be sent there without a prompt; forget them so
/// the user is asked again.
fn forget_credentials_if_retargeted(&self, old: &Profile, new: &Profile, via: &str) {
let target = |p: &Profile| {
(
p.host.trim().to_ascii_lowercase(),
p.port,
p.username.trim().to_string(),
p.github.as_ref().map(|g| g.base_url.trim().to_ascii_lowercase()),
p.rdp.as_ref().map(|r| (r.gateway_host.trim().to_ascii_lowercase(), r.gateway_username.trim().to_string())),
p.ssh.as_ref().map(|s| s.jump_hosts.iter().map(|j| (j.host.trim().to_ascii_lowercase(), j.port, j.username.clone())).collect::<Vec<_>>()),
)
};
if target(old) != target(new) {
self.secrets.delete_profile(&old.id);
self.store.add_audit(
"secret.forget",
&old.id,
"",
&format!("Forgot saved credentials for {:?}: its {via} copy points at a different host or account", old.display_name),
);
}
}
fn sync_tombstones(&self) -> std::collections::BTreeMap<String, Time> {
self.store.setting(SYNC_DELETED).and_then(|j| serde_json::from_str(&j).ok()).unwrap_or_default()
}
/// Sets (or, when empty, forgets) the profile-sync password.
pub fn set_sync_password(&self, password: &str) -> Result<()> {
*self.sync_password.lock() = None;
if password.is_empty() {
self.secrets.delete(SYNC_PASSWORD);
return Ok(());
@@ -140,7 +173,15 @@ impl Service {
}
pub fn has_sync_password(&self) -> bool {
self.secrets.get(SYNC_PASSWORD).is_some()
let mut c = self.sync_password.lock();
if let Some((at, v)) = *c
&& at.elapsed() < std::time::Duration::from_secs(5)
{
return v;
}
let v = self.secrets.get(SYNC_PASSWORD).is_some();
*c = Some((std::time::Instant::now(), v));
v
}
/// Merges profiles with the shared sync file; see [`crate::sync`].
@@ -164,7 +205,13 @@ impl Service {
report.skipped += 1;
continue;
}
let r = if self.store.get_profile(&p.id).is_ok() { self.store.update_profile(&p) } else { self.store.create_profile(&p) };
let r = match self.store.get_profile(&p.id) {
Ok(old) => {
self.forget_credentials_if_retargeted(&old, &p, "sync");
self.store.update_profile(&p)
}
Err(_) => self.store.create_profile(&p),
};
match r {
Ok(()) => report.pulled += 1,
Err(_) => report.skipped += 1,
@@ -312,7 +359,7 @@ impl Service {
/// Trusts an SSH certificate authority for hosts matching `pattern` (OpenSSH syntax).
pub fn add_cert_authority(&self, pattern: &str, public_key: &str) -> Result<()> {
let pattern = pattern.trim();
if pattern.is_empty() || pattern.contains(char::is_whitespace) {
if pattern.is_empty() || pattern.contains(char::is_whitespace) || pattern.len() > crate::known_hosts::MAX_PATTERN_LEN {
return Err("the host pattern must be one word, e.g. *.example.com".into());
}
let key = russh::keys::PublicKey::from_openssh(public_key.trim()).map_err(|e| format!("not an OpenSSH public key: {e}"))?;
@@ -369,6 +416,9 @@ impl Service {
"skip" if exists => continue,
"overwrite" if exists => {
p.updated_at = now();
if let Ok(old) = self.store.get_profile(&p.id) {
self.forget_credentials_if_retargeted(&old, &p, "import");
}
self.store.update_profile(&p).is_ok()
}
"duplicate" => {
@@ -431,7 +481,7 @@ impl Service {
path.as_mut_os_string().push(format!(".{}", exportimport::EXTENSION));
}
exportimport::encrypt_and_export(&ps, password, &path)?;
self.store.add_audit("export", "", "", &format!("Exported {} profile(s) without secrets", ps.len()));
self.store.add_audit("export", "", "", &format!("Exported {} profile(s) (saved credentials not included)", ps.len()));
Ok(path)
}
+5 -2
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Credential resolution (saved, session-only, ask-every-time), prompts and host-key checks.
use super::*;
@@ -62,7 +65,7 @@ impl Manager {
{
st.used.insert(key.clone());
store.add_audit("secret.access", &pid, "", &format!("Accessed {kind} credential"));
return Ok(Zeroizing::new(v));
return Ok(v);
}
}
if mode == SecretMode::SessionOnly
@@ -108,7 +111,7 @@ impl Manager {
pub fn host_key_check(self: &Arc<Self>, session: &str, policy: HostKeyPolicy) -> HostKeyCheck {
let (me, sid) = (self.clone(), session.to_string());
Arc::new(move |k: &HostKeyInfo| {
let stored = me.store.get_known_host(&k.host, k.port as i64).map_err(|e| format!("failed to query known hosts: {e}"))?;
let stored = me.store.get_known_host(&k.host, k.port as i64, &k.key_type).map_err(|e| format!("failed to query known hosts: {e}"))?;
let save = || {
let n = now();
me.store
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Accessors and actions specific to one protocol (RAW, IRC, GitHub, desktops, SSH).
use super::*;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Local shells and login scripts.
use super::*;
+5 -2
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! The session manager: one entry per open tab, each owning a protocol client. A port of
//! internal/sessions — same lifecycle, reconnect backoff, login scripts, recording hooks and
//! credential resolution — reporting to the UI through `Event`s.
@@ -803,7 +806,7 @@ mod tests {
// Typed again and accepted: stored.
resolve(&m, "s1");
m.finish_connect("s1", e, Ok(Client::None), |_| {});
assert_eq!(m.secrets.get(&key).as_deref(), Some("hunter2"));
assert_eq!(m.secrets.get(&key).as_deref().map(String::as_str), Some("hunter2"));
assert_eq!(asked.load(Ordering::SeqCst), 3);
// The saved value is reused; once the server rejects it, the next attempt asks again.
@@ -873,7 +876,7 @@ mod tests {
}
}));
let info = |fp: &str| HostKeyInfo { host: "h".into(), port: 22, key_type: "ssh-ed25519".into(), fingerprint: fp.into(), public_key_b64: "AAAA".into() };
let stored = |m: &Manager| m.store.get_known_host("h", 22).unwrap().map(|k| k.fingerprint);
let stored = |m: &Manager| m.store.get_known_host("h", 22, "ssh-ed25519").unwrap().map(|k| k.fingerprint);
// Unknown key: accept once records nothing; accept & save records it.
let check = m.host_key_check("s", HostKeyPolicy::Ask);
answers.lock().push(HostKeyDecision::AcceptOnce);
+5 -2
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Per-protocol connect: SSH, GitHub, IRC, VNC and RDP, and the SSH tunnels they can use.
use super::*;
@@ -17,7 +20,7 @@ impl Manager {
let passphrase = self.secret_fn(id, &p.id, SecretKind::Passphrase, sc.key_secret_mode, prompt);
let c = SshClient::new(&p, self.terminal_callbacks(id, epoch));
c.set_authorities(self.cert_authorities());
let stored = |k: SecretKind| self.secrets.get(&k.key(&p.id)).unwrap_or_default();
let stored = |k: SecretKind| self.secrets.get(&k.key(&p.id)).map(|v| v.to_string()).unwrap_or_default();
c.set_stored_secrets(stored(SecretKind::Totp), stored(SecretKind::ProxyPassword));
c.connect(self.host_key_check(id, sc.host_key_policy), Some(password), Some(passphrase))?;
for pf in sc.port_forwards.iter().filter(|f| f.enabled) {
@@ -347,7 +350,7 @@ impl Manager {
host: rc.proxy_host.clone(),
port: rc.proxy_port as u16,
username: rc.proxy_username.clone(),
password: self.secrets.get(&SecretKind::ProxyPassword.key(&p.id)).unwrap_or_default(),
password: self.secrets.get(&SecretKind::ProxyPassword.key(&p.id)).map(|v| v.to_string()).unwrap_or_default(),
};
let h = host.clone();
Arc::new(move || proxy.connect(&h, port, timeout))
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Parses OpenSSH `~/.ssh/config` Host blocks into SSH profiles. Supports HostName, Port, User,
//! IdentityFile, ProxyJump (first hop), ForwardAgent and Compression. Match blocks, wildcard-only
//! hosts, Include and `%h`-style tokens are ignored, as in the Go app.
+113 -5
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! SQLite persistence: profiles, known hosts, preferences, audit log, snippets and IRC channel
//! state. The schema and migration files are the Go app's, so existing databases open unchanged.
@@ -17,6 +20,7 @@ const MIGRATIONS: &[(i64, &str)] = &[
(6, include_str!("../migrations/006_irc_channel_state.sql")),
(7, include_str!("../migrations/007_serial_protocol.sql")),
(8, include_str!("../migrations/008_rdp_protocol.sql")),
(9, include_str!("../migrations/009_purge_legacy_secrets.sql")),
];
const PROFILE_COLS: &str = "id, display_name, description, protocol, host, port, username,
@@ -118,23 +122,50 @@ fn scan_snippet(r: &Row) -> rusqlite::Result<Snippet> {
impl Store {
pub fn open(path: &Path) -> Result<Store> {
// Owner-only from the first byte (the data folder is 0700 too, but the file may be copied
// or backed up on its own).
#[cfg(unix)]
if !path.exists() {
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path).map_err(|e| format!("storage: failed to create database: {e}"))?;
}
let db = Connection::open(path).map_err(|e| format!("storage: failed to open database: {e}"))?;
db.busy_timeout(std::time::Duration::from_secs(5))?;
db.pragma_update(None, "journal_mode", "WAL")?;
// Deleted rows (edited profiles, removed audit entries) are zeroed rather than left in
// free pages.
db.pragma_update(None, "secure_delete", "ON")?;
#[cfg(unix)]
for suffix in ["", "-wal", "-shm"] {
let mut p = path.as_os_str().to_owned();
p.push(suffix);
let _ = std::fs::set_permissions(&p, std::os::unix::fs::PermissionsExt::from_mode(0o600));
}
let s = Store { db: Mutex::new(db) };
s.migrate().map_err(|e| format!("storage: migration failed: {e}"))?;
Ok(s)
}
/// Applies pending migrations, each in its own transaction: several rebuild a table
/// (create new, copy, DROP old, rename), and a crash between the DROP and the rename used to
/// leave a database that failed to open on every later launch.
fn migrate(&self) -> Result<()> {
let db = self.db.lock();
let mut db = self.db.lock();
db.execute_batch("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)")?;
let current: i64 = db.query_row("SELECT COALESCE(MAX(version), 0) FROM schema_version", [], |r| r.get(0))?;
for (ver, sql) in MIGRATIONS {
if *ver > current {
db.execute_batch(sql).map_err(|e| format!("failed to apply migration {ver:03}: {e}"))?;
let tx = db.transaction()?;
tx.execute_batch(sql).map_err(|e| format!("failed to apply migration {ver:03}: {e}"))?;
tx.commit()?;
}
}
if current < 9 && current > 0 {
// Migration 009 removed plaintext secrets; rewrite the file so their pages go too.
// In WAL mode the rewrite lands in the WAL; checkpoint it into the main file and
// truncate the WAL so neither keeps the old pages.
let _ = db.execute_batch("VACUUM; PRAGMA wal_checkpoint(TRUNCATE);");
}
Ok(())
}
@@ -273,14 +304,17 @@ impl Store {
Ok(n)
}
pub fn get_known_host(&self, host: &str, port: i64) -> Result<Option<KnownHost>> {
/// The stored key of this type for `host:port`. A host can have one key per type (an
/// imported known_hosts usually brings ed25519, RSA and ECDSA), and comparing the offered
/// key with a row of another type would look like a changed key.
pub fn get_known_host(&self, host: &str, port: i64, key_type: &str) -> Result<Option<KnownHost>> {
Ok(self
.db
.lock()
.query_row(
"SELECT id, host, port, key_type, fingerprint, public_key, first_seen, last_seen, trusted
FROM known_hosts WHERE host = ? AND port = ?",
params![host, port],
FROM known_hosts WHERE host = ? AND port = ? AND key_type = ?",
params![host, port, key_type],
scan_known_host,
)
.optional()?)
@@ -557,4 +591,78 @@ mod tests {
self
}
}
#[test]
fn a_failed_migration_rolls_back_and_legacy_secrets_are_purged() {
let tmp = std::env::temp_dir().join(format!("nexus-mig-{}.db", std::process::id()));
let _ = std::fs::remove_file(&tmp);
let s = Store::open(&tmp).unwrap();
let mut p = Profile::new(crate::models::Protocol::Ssh);
p.id = "legacy".into();
p.display_name = "old".into();
p.host = "h".into();
s.create_profile(&p).unwrap();
{
// Put the database back at version 8 with a Go-era ssh_config carrying secrets.
let db = s.db.lock();
db.execute_batch(
"UPDATE profiles SET ssh_config = json_set(ssh_config, '$.proxyPassword', 'hunter2', '$.totpSecret', 'JBSWY3DP') WHERE id = 'legacy';
DELETE FROM schema_version WHERE version = 9;",
)
.unwrap();
}
drop(s);
let s = Store::open(&tmp).unwrap();
let raw: String = s.db.lock().query_row("SELECT ssh_config FROM profiles WHERE id = 'legacy'", [], |r| r.get(0)).unwrap();
assert!(!raw.contains("hunter2") && !raw.contains("JBSWY3DP"), "{raw}");
for suffix in ["", "-wal"] {
let bytes = std::fs::read(format!("{}{suffix}", tmp.display())).unwrap_or_default();
assert!(!String::from_utf8_lossy(&bytes).contains("hunter2"), "old secret left in nexus.db{suffix}");
}
// A migration that fails part-way leaves nothing behind.
let mut db = s.db.lock();
let tx = db.transaction().unwrap();
assert!(tx.execute_batch("CREATE TABLE half (x); SELECT * FROM no_such_table;").is_err());
drop(tx);
assert!(db.prepare("SELECT * FROM half").is_err(), "rolled back");
drop(db);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(&tmp).unwrap().permissions().mode() & 0o777, 0o600);
}
drop(s);
for suffix in ["", "-wal", "-shm"] {
let _ = std::fs::remove_file(format!("{}{suffix}", tmp.display()));
}
}
#[test]
fn known_hosts_are_looked_up_per_key_type() {
let tmp = std::env::temp_dir().join(format!("nexus-kh-{}.db", std::process::id()));
let _ = std::fs::remove_file(&tmp);
let s = Store::open(&tmp).unwrap();
let n = now();
for (kt, fp) in [("ssh-ed25519", "SHA256:ed"), ("ssh-rsa", "SHA256:rsa")] {
s.save_known_host(&KnownHost {
id: String::new(),
host: "h".into(),
port: 22,
key_type: kt.into(),
fingerprint: fp.into(),
public_key: "AAAA".into(),
first_seen: n,
last_seen: n,
trusted: true,
})
.unwrap();
}
// An imported known_hosts brings several key types per host; the offered key is
// compared with the row of its own type, not whichever row comes first.
assert_eq!(s.get_known_host("h", 22, "ssh-rsa").unwrap().unwrap().fingerprint, "SHA256:rsa");
assert_eq!(s.get_known_host("h", 22, "ssh-ed25519").unwrap().unwrap().fingerprint, "SHA256:ed");
assert!(s.get_known_host("h", 22, "ecdsa-sha2-nistp256").unwrap().is_none());
drop(s);
let _ = std::fs::remove_file(tmp);
}
}
+42 -6
View File
@@ -1,8 +1,16 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Profile sync through a folder the user picks (a cloud drive, a network share, a git checkout):
//! one encrypted file, `nexus-profiles.nexus`, in the export format (Argon2id + AES-256-GCM) under
//! a sync password. Each side merges profile by profile — the newer `updated_at` wins — and
//! deletions travel as dated tombstones, so a profile removed on one machine goes away on the
//! others. Credentials are never synced: they live in each machine's keychain or vault.
//! others. Saved credentials are never synced: they live in each machine's keychain or vault
//! (values a login script sends travel with their profile, as in an export).
//!
//! Timestamps in the shared file are clipped to the merging machine's clock: a record stamped in
//! the future would otherwise win over every later local edit (or keep deleting a profile) for
//! as long as the forged date, and the sync password is shared by every machine.
use crate::Result;
use crate::models::{Profile, Time};
@@ -37,14 +45,23 @@ pub struct Merged {
/// Merges local state with the shared file.
pub fn merge(local: &[Profile], local_deleted: &BTreeMap<String, Time>, remote: &SyncFile, now: Time) -> Merged {
let mut deleted = remote.deleted.clone();
let mut deleted: BTreeMap<String, Time> = remote.deleted.iter().map(|(id, t)| (id.clone(), (*t).min(now))).collect();
for (id, t) in local_deleted {
let e = deleted.entry(id.clone()).or_insert(*t);
*e = (*e).max(*t);
*e = (*e).max(*t).min(now);
}
deleted.retain(|_, t| (now - *t).num_days() < TOMBSTONE_DAYS);
let remote_by: HashMap<&str, &Profile> = remote.profiles.iter().map(|p| (p.id.as_str(), p)).collect();
let remote_profiles: Vec<Profile> = remote
.profiles
.iter()
.map(|p| {
let mut p = p.clone();
p.updated_at = p.updated_at.min(now);
p
})
.collect();
let remote_by: HashMap<&str, &Profile> = remote_profiles.iter().map(|p| (p.id.as_str(), p)).collect();
let local_by: HashMap<&str, &Profile> = local.iter().map(|p| (p.id.as_str(), p)).collect();
let mut out = Merged::default();
let mut ids: Vec<&str> = local_by.keys().chain(remote_by.keys()).copied().collect();
@@ -64,8 +81,8 @@ pub fn merge(local: &[Profile], local_deleted: &BTreeMap<String, Time>, remote:
(None, Some(r)) => *r,
(None, None) => continue,
};
// A deletion newer than the last edit wins; an edit after the deletion brings it back.
if deleted.get(id).is_some_and(|t| *t >= winner.updated_at) {
// A deletion newer than the last edit wins; an edit at or after the deletion brings it back.
if deleted.get(id).is_some_and(|t| *t > winner.updated_at) {
if local_by.contains_key(id) {
out.delete.push(id.to_string());
}
@@ -138,6 +155,25 @@ mod tests {
assert!(merge(&[], &BTreeMap::new(), &remote, at(TOMBSTONE_DAYS * 86_400 + 10)).file.deleted.is_empty());
}
#[test]
fn future_dated_records_cannot_win_forever() {
let now = at(1_000_000);
// A forged remote edit "from the future" is clipped to now, so the user's later local edit
// (also at now) keeps winning, and the rewritten file no longer carries the forged date.
let remote = SyncFile { version: 1, profiles: vec![p("a", "forged", 9_000_000)], deleted: BTreeMap::new() };
let m = merge(&[p("a", "mine", 1_000_000)], &BTreeMap::new(), &remote, now);
assert!(m.upsert.is_empty());
assert_eq!(m.file.profiles[0].host, "mine");
// A brand-new remote profile stamped in the future is accepted, but with a sane time.
let remote = SyncFile { version: 1, profiles: vec![p("b", "new", 9_000_000)], deleted: BTreeMap::new() };
let m = merge(&[], &BTreeMap::new(), &remote, now);
assert_eq!(m.upsert[0].updated_at, now);
// A future-dated tombstone can't keep deleting a profile the user re-creates afterwards.
let remote = SyncFile { version: 1, profiles: vec![], deleted: [("c".to_string(), at(9_000_000))].into() };
let m = merge(&[p("c", "recreated", 1_000_001)], &BTreeMap::new(), &remote, at(1_000_001));
assert!(m.delete.is_empty() && m.file.profiles.len() == 1 && m.file.deleted.is_empty());
}
#[test]
fn file_round_trips_under_the_password() {
let dir = std::env::temp_dir().join(format!("nexus-sync-{}", std::process::id()));
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Environment variables for terminal sessions: TERM and a UTF-8 character locale.
use std::collections::BTreeMap;
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Update checks against a self-hosted manifest. Check-only: nothing is downloaded or installed.
//! The launch-time check honours `AppPreferences::check_for_updates`. Calls block; run them off
//! the UI thread.
+39 -4
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Field-level validation of profiles and their protocol configs. Enum-typed fields (secret modes,
//! host-key policy, line endings, forward direction, protocol) can't hold invalid values in Rust,
//! so the Go checks for those are enforced by the types instead.
@@ -60,6 +63,10 @@ pub fn validate_profile(p: &Profile) -> Result<(), ValidationErrors> {
let mut errs = ValidationErrors::default();
if p.id.trim().is_empty() {
errs.add("id", "profile ID must not be empty");
} else if p.id.len() > 64 || !p.id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) {
// Ids name keychain/vault entries (`profile:<id>:<kind>`): a crafted id containing `:`
// could shadow or purge another profile's credentials.
errs.add("id", "profile ID may only contain letters, digits, '-', '_' and '.'");
}
if p.display_name.trim().is_empty() {
errs.add("displayName", "display name must not be empty");
@@ -155,6 +162,12 @@ pub fn validate_host(host: &str) -> Result<(), ValidationError> {
if h.contains([' ', '\t', '\n', '\r']) {
return err("host", "host must not contain whitespace");
}
if h.chars().any(is_control) {
return err("host", "host must not contain control characters");
}
if h.len() > 253 {
return err("host", "host is too long");
}
if h.contains("://") {
return err("host", "host must not include a URI scheme");
}
@@ -206,8 +219,8 @@ pub fn validate_ssh_config(cfg: &SshConfig) -> Result<(), ValidationErrors> {
}
for (i, jh) in cfg.jump_hosts.iter().enumerate() {
let prefix = format!("ssh.jumpHosts[{i}]");
if jh.host.trim().is_empty() {
errs.add(format!("{prefix}.host"), "jump host address must not be empty");
if let Err(e) = validate_host(&jh.host) {
errs.add(format!("{prefix}.host"), format!("jump host: {}", e.message));
}
if !(1..=65535).contains(&jh.port) {
errs.add(format!("{prefix}.port"), "jump host port must be between 1 and 65535");
@@ -224,8 +237,13 @@ pub fn validate_ssh_config(cfg: &SshConfig) -> Result<(), ValidationErrors> {
if !(1..=65535).contains(&pf.dest_port) {
errs.add(format!("{prefix}.destPort"), "destination port must be between 1 and 65535");
}
if pf.dest_host.trim().is_empty() {
errs.add(format!("{prefix}.destHost"), "destination host must not be empty");
if let Err(e) = validate_host(&pf.dest_host) {
errs.add(format!("{prefix}.destHost"), format!("destination: {}", e.message));
}
if !pf.bind_host.trim().is_empty()
&& let Err(e) = validate_host(&pf.bind_host)
{
errs.add(format!("{prefix}.bindHost"), format!("bind address: {}", e.message));
}
}
errs.into_result()
@@ -626,4 +644,21 @@ mod tests {
assert!(validate_irc_config(&c).is_err(), "{rooms:?}");
}
}
#[test]
fn hosts_and_ids_reject_control_characters_and_separators() {
assert!(validate_host("a\0b").is_err() && validate_host("a\x1bb").is_err());
assert!(validate_host(&"a".repeat(254)).is_err() && validate_host("db.example.com").is_ok() && validate_host("::1").is_ok());
let mut p = Profile::new(Protocol::Ssh);
p.display_name = "x".into();
p.host = "h".into();
p.username = "u".into();
assert!(validate_profile(&p).is_ok(), "a generated id is valid");
for bad in ["victim:password", "../x", "a b", &"a".repeat(65)] {
p.id = bad.into();
assert!(validate_profile(&p).is_err(), "{bad:?}");
}
p.id = "rdp-test_1.a".into();
assert!(validate_profile(&p).is_ok());
}
}
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Session manager end to end: events, writes, host-key prompts, auto-reconnect.
use nexus_core::models::{Profile, Protocol, SessionState};
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! End-to-end SSH tests against a throwaway OpenSSH server run as the current user. Skipped
//! (passing) when `sshd`/`ssh-keygen` aren't installed.
+8
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
//! Profile sync between two "machines" (data directories) sharing one folder.
use nexus_core::config::AppConfig;
@@ -29,6 +32,8 @@ fn profiles_follow_edits_and_deletes_across_machines() {
p.host = "web.example".into();
p.username = "me".into();
let p = a.create_profile(p).unwrap();
let pw_key = nexus_core::secrets::SecretKind::Password.key(&p.id);
a.secrets.set_checked(&pw_key, "hunter2").unwrap();
assert!(a.sync_profiles().unwrap().pushed);
assert_eq!(b.sync_profiles().unwrap().pulled, 1);
assert_eq!(b.profiles()[0].host, "web.example");
@@ -40,6 +45,9 @@ fn profiles_follow_edits_and_deletes_across_machines() {
b.sync_profiles().unwrap();
assert_eq!(a.sync_profiles().unwrap().pulled, 1);
assert_eq!(a.profiles()[0].host, "web2.example");
// A's saved password was for web.example; the synced copy points elsewhere, so it's forgotten
// rather than sent to the new host without asking.
assert!(a.secrets.get(&pw_key).is_none());
a.delete_profile(&p.id).unwrap();
a.sync_profiles().unwrap();
+1
View File
@@ -3,6 +3,7 @@ name = "nexus-fuzz"
version = "0.0.0"
publish = false
edition = "2024"
license = "AGPL-3.0-only"
[package.metadata]
cargo-fuzz = true
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
#![no_main]
libfuzzer_sys::fuzz_target!(|data: &[u8]| nexus_core::clients::irc::fuzz_lines(data));
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
#![no_main]
libfuzzer_sys::fuzz_target!(|data: &[u8]| nexus_core::sshconfig::fuzz_parse(data));
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
#![no_main]
libfuzzer_sys::fuzz_target!(|data: &[u8]| nexus_core::clients::telnet::fuzz_negotiation(data));
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
#![no_main]
libfuzzer_sys::fuzz_target!(|data: &[u8]| nexus_core::updater::fuzz_manifest(data));
+3
View File
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Andy Dixon
#![no_main]
libfuzzer_sys::fuzz_target!(|data: &[u8]| nexus_core::clients::vnc::fuzz_updates(data));
+2
View File
@@ -1,4 +1,6 @@
#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 Andy Dixon
# Install Nexus Terminal for the current user so it appears in the app launcher.
# Usage: rust/packaging/linux/install.sh [path/to/nexus-terminal] (default: target/release/nexus-terminal)
set -eu
+2 -2
View File
@@ -2,10 +2,10 @@
Type=Application
Name=Nexus Terminal
GenericName=Terminal and Remote Connections
Comment=SSH, Telnet, RAW TCP, Serial, VNC, IRC and GitHub sessions in one window
Comment=SSH, Telnet, RAW TCP, Serial, VNC, RDP, IRC and GitHub sessions in one window
Exec=nexus-terminal
Icon=nexus-terminal
Terminal=false
Categories=System;TerminalEmulator;Network;RemoteAccess;
Keywords=ssh;telnet;serial;sftp;vnc;irc;terminal;
Keywords=ssh;telnet;serial;sftp;vnc;rdp;irc;terminal;
StartupWMClass=nexus-terminal
+1 -1
View File
@@ -31,6 +31,6 @@
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>© Andy Dixon</string>
<string>© 2026 Andy Dixon. Licensed under the GNU AGPL v3.</string>
</dict>
</plist>
+3
View File
@@ -1,4 +1,6 @@
#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 Andy Dixon
# Build NexusTerminal.app, a macOS application bundle. Run on a Mac with Xcode command-line tools:
#
# rust/packaging/macos/build-app.sh # universal (Apple Silicon + Intel) if both
@@ -44,6 +46,7 @@ mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cp "$BIN" "$APP/Contents/MacOS/NexusTerminal"
chmod +x "$APP/Contents/MacOS/NexusTerminal"
cp "$HERE/NexusTerminal.icns" "$APP/Contents/Resources/NexusTerminal.icns"
cp "$HERE/../../../LICENSE" "$APP/Contents/Resources/LICENSE"
sed "s/__VERSION__/$VERSION/g" "$HERE/Info.plist" > "$APP/Contents/Info.plist"
printf 'APPL????' > "$APP/Contents/PkgInfo"
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 Andy Dixon
#
# Publish a Nexus Terminal release as the `nexusterminal` package (.deb, .rpm and Arch) in the
# signed apt, dnf and pacman repositories served at https://repo.dixon.cx.
#
# packaging/repo.sh # the newest tag
# packaging/repo.sh v3.0.2 # a given tag
#
# Unlike the command-line tools' copies of this script, nothing is built here: Nexus is a GUI app
# linked against the platform's windowing stack, so the packages wrap the official binaries that
# the Release Builds workflow made for the tag (native glibc builds on amd64 and arm64). They're
# downloaded from the GitHub release and checked against its SHA256SUMS first.
#
# The publish half is the same as in ../../../mapsize/packaging/repo.sh and friends: every index
# is rebuilt over all packages in the repository, so other projects' packages are kept.
#
# Needs: curl, unzip, curl (for the pinned nfpm), docker, gpg, apt-ftparchive, flock.
# REPO_DIR where the repository lives (default below)
# REPO_GNUPGHOME GnuPG home holding the signing key (default below)
# ARCHS package architectures (default: amd64 arm64)
set -euo pipefail
# ---- project ---------------------------------------------------------------
PACKAGE=nexusterminal
SUMMARY="Native desktop client for SSH, SFTP, Telnet, Serial, VNC, RDP, IRC and GitHub"
HOMEPAGE=https://dixon.cx/nexus
GITHUB=andydixon/nexus
LICENSE=AGPL-3.0-only
ARCHS=${ARCHS:-"amd64 arm64"}
# The binaries come from ubuntu-22.04 runners: glibc 2.35. Windowing, GL and audio libraries are
# loaded at run time, so they're recommended rather than hard dependencies (any desktop has them).
# ALSA is linked directly (RDP audio), so it's a hard dependency. libasound2t64 comes first: on
# Ubuntu 24.04 and later plain libasound2 is only a virtual name, which apt may satisfy with the
# OSS shim liboss4-salsa-asound2 (missing real ALSA symbols); older Debian falls through to it.
DEB_DEPENDS='"libc6 (>= 2.35)", "libgcc-s1", "zlib1g", "libasound2t64 | libasound2"'
DEB_RECOMMENDS='"libxkbcommon0", "libwayland-client0", "libx11-6", "libxcursor1", "libxrandr2", "libxi6", "libgl1", "libegl1", "xdg-desktop-portal"'
RPM_DEPENDS='"glibc >= 2.35", "libgcc", "zlib", "alsa-lib"'
RPM_RECOMMENDS='"libxkbcommon", "libwayland-client", "libX11", "libXcursor", "libXrandr", "libXi", "mesa-libGL", "mesa-libEGL", "xdg-desktop-portal"'
ARCH_DEPENDS='"glibc", "gcc-libs", "zlib", "alsa-lib", "libxkbcommon", "libglvnd"'
ARCH_SUGGESTS='"wayland", "libx11", "libxcursor", "libxrandr", "libxi", "xdg-desktop-portal"'
# Package revision: bump to republish the same Nexus version with packaging fixes.
PKGREL=${PKGREL:-1}
# ----------------------------------------------------------------------------
REPO_DIR=${REPO_DIR:-/home/andy/domains/repo.dixon.cx/public_html}
REPO_GNUPGHOME=${REPO_GNUPGHOME:-$HOME/.config/repo.dixon.cx/gnupg}
SUITE=stable
COMPONENT=main
ARCH_REPO=dixon # the pacman repository name: [dixon]
HERE=$(cd "$(dirname "$0")" && pwd)
say() { echo "repo: $*" >&2; }
die() { say "$*"; exit 1; }
for tool in unzip curl docker gpg apt-ftparchive flock sha256sum; do
command -v $tool >/dev/null || die "needs $tool"
done
[[ -d $REPO_DIR ]] || die "$REPO_DIR does not exist"
export GNUPGHOME=$REPO_GNUPGHOME
KEY=$(gpg --list-secret-keys --with-colons 2>/dev/null | awk -F: '/^fpr/{print $10; exit}')
[[ -n $KEY ]] || die "no signing key in $GNUPGHOME"
cd "$(git -C "$HERE" rev-parse --show-toplevel)"
TAG=${1:-$(git describe --tags --abbrev=0)}
VERSION=${TAG#v}
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
gpg --batch --armor --export-secret-keys "$KEY" >"$WORK/signing.asc"
# The pinned nfpm, as in the other projects (checksummed download, cached under target/tools).
NFPM_VERSION=2.41.1
case $(uname -m) in
x86_64) nfpm_arch=x86_64 nfpm_sum=b3cf95aa6dabed836d09ad7f0c190a13c74c5b1304db60846f0f702ee407f430 ;;
aarch64) nfpm_arch=arm64 nfpm_sum=17350a838c8e2c422c6e573ed379b18424565d2de8a2b1cb1b20211976124eb5 ;;
*) die "unsupported host $(uname -m)" ;;
esac
NFPM_DIR=$PWD/rust/target/tools/nfpm-$NFPM_VERSION
if [[ ! -x $NFPM_DIR/nfpm ]]; then
mkdir -p "$NFPM_DIR"
curl -fsSL -o "$NFPM_DIR/nfpm.tar.gz" "https://github.com/goreleaser/nfpm/releases/download/v$NFPM_VERSION/nfpm_${NFPM_VERSION}_Linux_$nfpm_arch.tar.gz"
echo "$nfpm_sum $NFPM_DIR/nfpm.tar.gz" | sha256sum -c --quiet
tar -xzf "$NFPM_DIR/nfpm.tar.gz" -C "$NFPM_DIR" nfpm
rm -f "$NFPM_DIR/nfpm.tar.gz"
fi
NFPM=$NFPM_DIR/nfpm
# ---- fetch and verify the release binaries ---------------------------------
say "fetching $TAG from github.com/$GITHUB"
mkdir -p "$WORK/dl"
base=https://github.com/$GITHUB/releases/download/$TAG
for f in SHA256SUMS $(for arch in $ARCHS; do echo "NexusTerminal-linux-$arch.zip"; done); do
curl -fsSL -o "$WORK/dl/$f" "$base/$f" || die "release $TAG has no $f yet"
done
(cd "$WORK/dl" && grep -E "NexusTerminal-linux-($(tr ' ' '|' <<<"$ARCHS"))\.zip" SHA256SUMS | sha256sum -c --quiet) || die "checksum mismatch"
# ---- package -----------------------------------------------------------------
say "packaging $PACKAGE $VERSION for $ARCHS"
mkdir -p "$WORK/out"
for arch in $ARCHS; do
src=$WORK/src-$arch
mkdir -p "$src"
unzip -q "$WORK/dl/NexusTerminal-linux-$arch.zip" -d "$src"
[[ -x $src/nexus-terminal ]] || die "no nexus-terminal binary in the $arch zip"
cp "$src/nexus-terminal.desktop" "$src/$PACKAGE.desktop"
cat >"$WORK/nfpm-$arch.yaml" <<-EOF
name: $PACKAGE
arch: $arch
platform: linux
version: $VERSION
release: $PKGREL
section: net
maintainer: Andy Dixon <andy@dixon.cx>
description: |
$SUMMARY.
Tabs, split panes, SFTP, port forwards, jump hosts, session recording and an
encrypted credential vault, in one native app written in Rust.
homepage: $HOMEPAGE
license: $LICENSE
contents:
- src: $src/nexus-terminal
dst: /usr/bin/nexus-terminal
file_info: {mode: 0755}
- src: /usr/bin/nexus-terminal
dst: /usr/bin/$PACKAGE
type: symlink
- src: $src/$PACKAGE.desktop
dst: /usr/share/applications/$PACKAGE.desktop
file_info: {mode: 0644}
- src: $src/app/assets/icon/icon-256.png
dst: /usr/share/icons/hicolor/256x256/apps/nexus-terminal.png
file_info: {mode: 0644}
- src: $src/app/assets/icon/icon-512.png
dst: /usr/share/icons/hicolor/512x512/apps/nexus-terminal.png
file_info: {mode: 0644}
- src: $src/LICENSE
dst: /usr/share/licenses/$PACKAGE/LICENSE
file_info: {mode: 0644}
- src: $PWD/README.md
dst: /usr/share/doc/$PACKAGE/README.md
file_info: {mode: 0644}
overrides:
deb:
depends: [$DEB_DEPENDS]
recommends: [$DEB_RECOMMENDS]
rpm:
depends: [$RPM_DEPENDS]
recommends: [$RPM_RECOMMENDS]
archlinux:
depends: [$ARCH_DEPENDS]
suggests: [$ARCH_SUGGESTS]
archlinux:
packager: Andy Dixon <andy@dixon.cx>
rpm:
signature:
key_file: $WORK/signing.asc
EOF
for fmt in deb rpm archlinux; do
"$NFPM" pkg -f "$WORK/nfpm-$arch.yaml" -p $fmt -t "$WORK/out/" >"$WORK/nfpm.log" 2>&1 ||
{ cat "$WORK/nfpm.log" >&2; die "nfpm $fmt for $arch failed"; }
done
done
# ---- publish (shared with the other projects' repo.sh) -----------------------
exec 9>"$REPO_DIR/../.publish.lock"
flock 9
say "publishing to $REPO_DIR"
gpg --batch --armor --export "$KEY" >"$REPO_DIR/dixon.asc"
gpg --batch --export "$KEY" >"$REPO_DIR/dixon.gpg"
sign() { gpg --batch --yes --local-user "$KEY" "$@"; }
pool=$REPO_DIR/apt/pool/$COMPONENT/${PACKAGE:0:1}/$PACKAGE
mkdir -p "$pool"
cp "$WORK"/out/*.deb "$pool/"
(
cd "$REPO_DIR/apt"
dists=dists/.$SUITE.new
rm -rf "$dists"
debarchs=$(find pool -name '*.deb' | sed -E 's/.*_([^_]+)\.deb$/\1/' | sort -u | tr '\n' ' ')
for a in $debarchs; do
d=$dists/$COMPONENT/binary-$a
mkdir -p "$d"
apt-ftparchive --arch "$a" packages pool >"$d/Packages"
gzip -9kn "$d/Packages"
done
apt-ftparchive \
-o APT::FTPArchive::Release::Origin=repo.dixon.cx \
-o APT::FTPArchive::Release::Label=repo.dixon.cx \
-o APT::FTPArchive::Release::Suite=$SUITE \
-o APT::FTPArchive::Release::Codename=$SUITE \
-o APT::FTPArchive::Release::Components=$COMPONENT \
-o "APT::FTPArchive::Release::Architectures=${debarchs% }" \
release "$dists" >"$WORK/Release"
mv "$WORK/Release" "$dists/Release"
sign --clearsign -o "$dists/InRelease" "$dists/Release"
sign --armor --detach-sign -o "$dists/Release.gpg" "$dists/Release"
rm -rf "dists/.$SUITE.old"
[[ -d dists/$SUITE ]] && mv "dists/$SUITE" "dists/.$SUITE.old"
mv "$dists" "dists/$SUITE"
rm -rf "dists/.$SUITE.old"
)
mkdir -p "$REPO_DIR/rpm"
cp "$WORK"/out/*.rpm "$REPO_DIR/rpm/"
docker image inspect repo-tools:fedora >/dev/null 2>&1 ||
docker build -q -t repo-tools:fedora - >/dev/null <<-'EOF'
FROM fedora:42
RUN dnf -y install createrepo_c && dnf clean all
EOF
docker run --rm --user "$(id -u):$(id -g)" -v "$REPO_DIR/rpm:/repo" repo-tools:fedora \
createrepo_c --quiet --update --general-compress-type=gz /repo
sign --armor --detach-sign -o "$REPO_DIR/rpm/repodata/repomd.xml.asc" "$REPO_DIR/rpm/repodata/repomd.xml"
added=
for pkg in "$WORK"/out/*.pkg.tar.zst; do
a=$(basename "$pkg" .pkg.tar.zst)
a=${a##*-}
mkdir -p "$REPO_DIR/arch/$a"
cp "$pkg" "$REPO_DIR/arch/$a/"
sign --detach-sign -o "$REPO_DIR/arch/$a/$(basename "$pkg").sig" "$pkg"
added+=" $a"
done
for a in $(tr ' ' '\n' <<<"$added" | sort -u); do
dir=$REPO_DIR/arch/$a
rm -f "$dir/$ARCH_REPO".{db,files}{,.tar.gz}{,.sig}
docker run --rm --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$dir:/repo" -w /repo archlinux:latest \
sh -c "repo-add --quiet --prevent-downgrade $ARCH_REPO.db.tar.gz *.pkg.tar.zst" 2>&1 |
{ grep -v "newer version\|^$" >&2 || true; }
for db in $ARCH_REPO.db $ARCH_REPO.files; do
sign --detach-sign -o "$dir/$db.tar.gz.sig" "$dir/$db.tar.gz"
ln -sfn "$db.tar.gz.sig" "$dir/$db.sig"
done
rm -f "$dir"/*.old "$dir"/*.old.sig
done
say "published $PACKAGE $VERSION: $(cd "$WORK/out" && ls | wc -l) packages"
+13 -3
View File
@@ -1,4 +1,6 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 Andy Dixon
# release.sh — build and package Nexus Terminal release artefacts with cargo.
#
# Produces, under build/releases/<version>/ (repo root):
@@ -66,18 +68,26 @@ for target in "${TARGETS[@]}"; do
NEXUS_BIN="$bin" packaging/macos/build-app.sh
rm -rf "$OUT/$base.app"
cp -R target/macos/NexusTerminal.app "$OUT/$base.app"
(cd "$OUT" && rm -f "$base.zip" && zip -qry "$base.zip" "$base.app")
(cd "$OUT" && rm -f "$base.zip" && zip -qry "$base.zip" "$base.app" && zip -qj "$base.zip" "$ROOT/LICENSE")
;;
windows)
cp "$bin.exe" "$OUT/$base.exe"
(cd "$OUT" && rm -f "$base.zip" && zip -qj "$base.zip" "$base.exe")
# GitHub's Windows runners have 7-Zip but no zip.
if command -v zip >/dev/null; then
(cd "$OUT" && rm -f "$base.zip" && zip -qj "$base.zip" "$base.exe" "$ROOT/LICENSE")
elif command -v 7z >/dev/null; then
(cd "$OUT" && rm -f "$base.zip" && cp "$ROOT/LICENSE" LICENSE && 7z a -tzip -bso0 -bsp0 "$base.zip" "$base.exe" LICENSE && rm -f LICENSE)
else
(cd "$OUT" && rm -f "$base.zip" && cp "$ROOT/LICENSE" LICENSE &&
powershell -NoProfile -NonInteractive -Command "Compress-Archive -Path '$base.exe','LICENSE' -DestinationPath '$base.zip' -Force" && rm -f LICENSE)
fi
;;
*)
cp "$bin" "$OUT/$base"
strip "$OUT/$base" 2>/dev/null || true
stage="$(mktemp -d)"
cp "$OUT/$base" "$stage/nexus-terminal"
cp packaging/linux/nexus-terminal.desktop packaging/linux/install.sh "$stage/"
cp packaging/linux/nexus-terminal.desktop packaging/linux/install.sh "$ROOT/LICENSE" "$stage/"
mkdir -p "$stage/app/assets/icon" && cp app/assets/icon/icon-256.png app/assets/icon/icon-512.png "$stage/app/assets/icon/"
sed -i 's|\$HERE/../../app|$HERE/app|; s|\$HERE/../../target/release/nexus-terminal|$HERE/nexus-terminal|' "$stage/install.sh"
(cd "$stage" && rm -f "$OUT/$base.zip" && zip -qr "$OUT/$base.zip" .)

Some files were not shown because too many files have changed in this diff Show More