rpassword-7.5.4/.cargo/config.toml000064400000000000000000000003671046102023000152060ustar 00000000000000[target.x86_64-pc-windows-gnu] linker = "x86_64-w64-mingw32-gcc" runner = "wine64" [target.wasm32-unknown-emscripten] runner = "node --experimental-wasm-modules --input-type=module -e 'import(require(\"url\").pathToFileURL(process.argv[1]))' --" rpassword-7.5.4/.cargo_vcs_info.json0000644000000001360000000000100130750ustar { "git": { "sha1": "11515101cf108ce825dcd5ef5bac703a591f36c1" }, "path_in_vcs": "" }rpassword-7.5.4/.envrc000064400000000000000000000000071046102023000130000ustar 00000000000000use nixrpassword-7.5.4/.github/workflows/rust.yaml000064400000000000000000000040261046102023000171450ustar 00000000000000name: Rust on: push: branches: - main pull_request: branches: - main jobs: test: name: Test on ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, windows-latest] steps: - name: Install Emscripten for WASM tests if: matrix.os == 'ubuntu-latest' run: | sudo apt-get update sudo apt-get install -y emscripten - name: Checkout code uses: actions/checkout@v4 - name: Install Rust toolchain if: matrix.os == 'ubuntu-latest' uses: dtolnay/rust-toolchain@1.85 with: targets: wasm32-unknown-emscripten - name: Install Rust toolchain if: matrix.os == 'windows-latest' uses: dtolnay/rust-toolchain@1.85 # Cache cargo dependencies - uses: actions/cache@v4 with: path: | ~/.cargo/bin/ ~/.cargo/registry/index/ ~/.cargo/registry/cache/ ~/.cargo/git/db/ target/ key: ${{ matrix.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} restore-keys: | ${{ matrix.os }}-cargo- - name: Build run: cargo build --verbose - name: Run tests run: cargo test --verbose - name: Build if: matrix.os == 'ubuntu-latest' run: cargo build --verbose --target wasm32-unknown-emscripten - name: Run tests if: matrix.os == 'ubuntu-latest' run: cargo test --verbose --target wasm32-unknown-emscripten - name: Install Rust toolchain for additional cargo tooling if: matrix.os == 'ubuntu-latest' uses: dtolnay/rust-toolchain@stable - name: Check coverage if: matrix.os == 'ubuntu-latest' run: | which cargo-tarpaulin || cargo install cargo-tarpaulin cargo tarpaulin - name: Check licenses if: matrix.os == 'ubuntu-latest' run: | which cargo-deny || cargo install cargo-deny cargo deny check licenses rpassword-7.5.4/.gitignore000064400000000000000000000000411046102023000136500ustar 00000000000000/target/ /Cargo.lock .output.txt rpassword-7.5.4/CONTRIBUTING.md000064400000000000000000000020321046102023000141130ustar 00000000000000# Contributing You are welcome to contribute to this project, following a couple of guidelines. The main principle is that we want to respect each other's time. ## Bug reports Bug reports should include instructions for how to reproduce step-by-step, include useful information such as operating system, version of Rust and Cargo used to compile, screenshots, log output, etc. Bug reports that do not give sufficient information to understand and reproduce the bug will be closed. If you have the necessary skills, you should always attempt to fix the bug yourself. Whenever possible, you should add a unit or integration test so that we don't accidentally reintroduce the bug later. ## New features Before working on a new feature, open an issue to discuss your plans. We'll tell you if we think it falls into the scope of this project, so you only spend time implementing changes we're willing to review and merge. New features should include unit tests and integration tests if applicable, so that future development don't break your code. rpassword-7.5.4/Cargo.lock0000644000000330600000000000100110520ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "anyhow" version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" [[package]] name = "bitflags" version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" [[package]] name = "cfg-if" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", "windows-sys 0.61.2", ] [[package]] name = "fastrand" version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" [[package]] name = "foldhash" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" [[package]] name = "getrandom" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "libc", "r-efi", "wasip2", "wasip3", ] [[package]] name = "hashbrown" version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ "foldhash", ] [[package]] name = "hashbrown" version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "id-arena" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" [[package]] name = "indexmap" version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", "hashbrown 0.17.0", "serde", "serde_core", ] [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "leb128fmt" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" version = "0.2.185" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" [[package]] name = "linux-raw-sys" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "log" version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" [[package]] name = "memchr" version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "prettyplease" version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" dependencies = [ "proc-macro2", "syn", ] [[package]] name = "proc-macro2" version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rpassword" version = "7.5.4" dependencies = [ "libc", "rtoolbox", "tempfile", "windows-sys 0.61.2", ] [[package]] name = "rtoolbox" version = "0.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50a0e551c1e27e1731aba276dbeaeac73f53c7cd34d1bda485d02bd1e0f36844" dependencies = [ "libc", "windows-sys 0.59.0", ] [[package]] name = "rustix" version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys 0.61.2", ] [[package]] name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "serde" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", ] [[package]] name = "serde_core" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" dependencies = [ "itoa", "memchr", "serde", "serde_core", "zmij", ] [[package]] name = "syn" version = "2.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tempfile" version = "3.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", "getrandom", "once_cell", "rustix", "windows-sys 0.61.2", ] [[package]] name = "unicode-ident" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "unicode-xid" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] name = "wasip2" version = "1.0.2+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" dependencies = [ "wit-bindgen", ] [[package]] name = "wasip3" version = "0.4.0+wasi-0.3.0-rc-2026-01-06" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" dependencies = [ "wit-bindgen", ] [[package]] name = "wasm-encoder" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" dependencies = [ "leb128fmt", "wasmparser", ] [[package]] name = "wasm-metadata" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" dependencies = [ "anyhow", "indexmap", "wasm-encoder", "wasmparser", ] [[package]] name = "wasmparser" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ "bitflags", "hashbrown 0.15.5", "indexmap", "semver", ] [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-sys" version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ "windows-link", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "wit-bindgen" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" dependencies = [ "wit-bindgen-rust-macro", ] [[package]] name = "wit-bindgen-core" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" dependencies = [ "anyhow", "heck", "wit-parser", ] [[package]] name = "wit-bindgen-rust" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" dependencies = [ "anyhow", "heck", "indexmap", "prettyplease", "syn", "wasm-metadata", "wit-bindgen-core", "wit-component", ] [[package]] name = "wit-bindgen-rust-macro" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" dependencies = [ "anyhow", "prettyplease", "proc-macro2", "quote", "syn", "wit-bindgen-core", "wit-bindgen-rust", ] [[package]] name = "wit-component" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", "bitflags", "indexmap", "log", "serde", "serde_derive", "serde_json", "wasm-encoder", "wasm-metadata", "wasmparser", "wit-parser", ] [[package]] name = "wit-parser" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" dependencies = [ "anyhow", "id-arena", "indexmap", "log", "semver", "serde", "serde_derive", "serde_json", "unicode-xid", "wasmparser", ] [[package]] name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" rpassword-7.5.4/Cargo.toml0000644000000037530000000000100111030ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2024" rust-version = "1.85" name = "rpassword" version = "7.5.4" authors = ["Conrad Kleinespel "] build = false exclude = ["rpassword.png"] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Read passwords in console applications (unix, windows, macos, wasm)." homepage = "https://github.com/conradkleinespel/rpassword" documentation = "https://docs.rs/rpassword/" readme = "README.md" keywords = [ "read", "password", "security", "pass", "getpass", ] license = "Apache-2.0" repository = "https://github.com/conradkleinespel/rpassword" [lib] name = "rpassword" path = "src/lib.rs" [[example]] name = "discard_output" path = "examples/discard_output.rs" [[example]] name = "prompt_password" path = "examples/prompt_password.rs" [[example]] name = "prompt_password_with_config" path = "examples/prompt_password_with_config.rs" [[example]] name = "read_password" path = "examples/read_password.rs" [[example]] name = "read_password_with_config" path = "examples/read_password_with_config.rs" [[test]] name = "no-terminal" path = "tests/no-terminal.rs" [dependencies.rtoolbox] version = "0.0" [dev-dependencies.tempfile] version = "3" [target."cfg(unix)".dependencies.libc] version = "0.2" [target."cfg(windows)".dependencies.windows-sys] version = "0.61" features = [ "Win32_Foundation", "Win32_System_Console", "Win32_System_IO", "Win32_Storage_FileSystem", "Win32_Security", "Win32_System_SystemServices", ] rpassword-7.5.4/Cargo.toml.orig000064400000000000000000000015431046102023000145570ustar 00000000000000[package] name = "rpassword" version = "7.5.4" authors = ["Conrad Kleinespel "] description = "Read passwords in console applications (unix, windows, macos, wasm)." license = "Apache-2.0" homepage = "https://github.com/conradkleinespel/rpassword" repository = "https://github.com/conradkleinespel/rpassword" documentation = "https://docs.rs/rpassword/" readme = "README.md" keywords = ["read", "password", "security", "pass", "getpass"] edition = "2024" rust-version = "1.85" exclude = ["rpassword.png"] [target.'cfg(unix)'.dependencies] libc = "0.2" [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console", "Win32_System_IO", "Win32_Storage_FileSystem", "Win32_Security", "Win32_System_SystemServices"] } [dependencies] rtoolbox = "0.0" [dev-dependencies] tempfile = "3" rpassword-7.5.4/LICENSE-APACHE000064400000000000000000000236751046102023000136260ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS rpassword-7.5.4/README.md000064400000000000000000000024621046102023000131500ustar 00000000000000# Rustastic Password `rpassword` makes it easy to read passwords from Rust code in console applications on all platforms, Unix, Windows, WASM and more. It's similar to Linux's C function `getpass()` or Python's `getpass` module. ![rpassword logo and headline](rpassword.png) ## Usage Add `rpassword` as a dependency in Cargo.toml: ```toml [dependencies] rpassword = "7.5" ``` Then use it in your code: ```rust use std::io::{Cursor, Write}; use rpassword::{ConfigBuilder}; fn main() { // By default, reads and writes to the console, hides password as it is typed let password = rpassword::prompt_password("Your password: ").unwrap(); println!("Your password is {}", password); // Behavior is customizable to accommodate custom use-cases and testing // See documentation for more details let config = rpassword::ConfigBuilder::new() .input_data("my-password\n") .output_discard() .password_feedback_mask('*') .build(); let password = rpassword::read_password_with_config(config).unwrap(); println!("Your password is {}", password); } ``` See examples and docs at [https://docs.rs/rpassword](https://docs.rs/rpassword). See the upgrade path in [UPGRADE.md](UPGRADE.md). ## License The source code is released under the Apache 2.0 license. rpassword-7.5.4/UPGRADE.md000064400000000000000000000022101046102023000132710ustar 00000000000000# Upgrade Policy for `rpassword` ## Overview This policy outlines the versioning and upgrade path for `rpassword`. Please report any upgrading issues or feedback to the project's issue tracker. ## Versioning Rules ### Patch Versions (`x.y.Z`) - **Definition**: Bug fixes, performance improvements, and minor documentation updates. - **Compatibility**: Fully backward-compatible. No breaking changes. - **User Action**: Safe to upgrade without code modifications. ### Minor Versions (`x.Y.z`) - **Definition**: New features, enhancements, and deprecations. - **Compatibility**: Backward-compatible. Deprecated APIs remain functional but emit warnings. - **User Action**: 1. Upgrade to the latest minor version. 2. Address deprecation warnings to prepare for the next major version. ### Major Versions (`X.y.z`) - **Definition**: Breaking changes, API redesigns, or significant architectural shifts. - **Compatibility**: Not backward-compatible. Deprecated APIs may be removed. - **User Action**: 1. Upgrade to the latest minor version of the current major release. 2. Fix all deprecation warnings. 3. Upgrade to the next major version.rpassword-7.5.4/deny.toml000064400000000000000000000002511046102023000135170ustar 00000000000000[licenses] allow = [ "Apache-2.0", ] [licenses.private] ignore = true [bans] multiple-versions = "warn" [sources] unknown-registry = "warn" unknown-git = "warn" rpassword-7.5.4/examples/discard_output.rs000064400000000000000000000010501046102023000170760ustar 00000000000000use rpassword::ConfigBuilder; fn main() { println!("=== prompt_password_with_config(...) with no output ==="); println!("Note: No prompt will be shown, since the output is discarded."); println!("Just type your password and press Enter."); let config = ConfigBuilder::new() .password_feedback_hide() .output_discard() .build(); match rpassword::prompt_password_with_config("Password: ", config) { Ok(pass) => println!("You entered: '{}'", pass), Err(e) => eprintln!("Error: {}", e), } } rpassword-7.5.4/examples/prompt_password.rs000064400000000000000000000003601046102023000173130ustar 00000000000000use rpassword::prompt_password; fn main() { println!("=== prompt_password() ==="); match prompt_password("Password: ") { Ok(pass) => println!("You entered: '{}'", pass), Err(e) => eprintln!("Error: {}", e), } } rpassword-7.5.4/examples/prompt_password_with_config.rs000064400000000000000000000026401046102023000216760ustar 00000000000000use rpassword::ConfigBuilder; fn main() { println!("=== prompt_password_with_config(...) with Hide mode (default behavior) ==="); let config = ConfigBuilder::new().password_feedback_hide().build(); match rpassword::prompt_password_with_config("Password: ", config) { Ok(pass) => println!("You entered: '{}'", pass), Err(e) => eprintln!("Error: {}", e), } println!("\n=== prompt_password_with_config(...) with Mask('*') mode ==="); let config = ConfigBuilder::new().password_feedback_mask('*').build(); match rpassword::prompt_password_with_config("Password: ", config) { Ok(pass) => println!("You entered: '{}'", pass), Err(e) => eprintln!("Error: {}", e), } println!("\n=== prompt_password_with_config(...) with Mask('#') mode ==="); let config = ConfigBuilder::new().password_feedback_mask('#').build(); match rpassword::prompt_password_with_config("Password: ", config) { Ok(pass) => println!("You entered: '{}'", pass), Err(e) => eprintln!("Error: {}", e), } println!("\n=== prompt_password_with_config(...) with PartialMask('*', 3) mode ==="); let config = ConfigBuilder::new() .password_feedback_partial_mask('*', 3) .build(); match rpassword::prompt_password_with_config("Password: ", config) { Ok(pass) => println!("You entered: '{}'", pass), Err(e) => eprintln!("Error: {}", e), } } rpassword-7.5.4/examples/read_password.rs000064400000000000000000000006241046102023000167100ustar 00000000000000use rpassword::read_password; use std::io::{self, Write}; fn prompt(s: &str) { print!("{}", s); io::stdout().flush().unwrap(); // need to flush because print!() doesn't flush } fn main() { println!("=== read_password() ==="); prompt("Password: "); match read_password() { Ok(pass) => println!("You entered: '{}'", pass), Err(e) => eprintln!("Error: {}", e), } } rpassword-7.5.4/examples/read_password_with_config.rs000064400000000000000000000031341046102023000212670ustar 00000000000000use rpassword::ConfigBuilder; use std::io::{self, Write}; fn prompt(s: &str) { print!("{}", s); io::stdout().flush().unwrap(); // need to flush because print!() doesn't flush } fn main() { println!("=== read_password_with_config(...) with Hide mode (default behavior) ==="); let config = ConfigBuilder::new().password_feedback_hide().build(); prompt("Password: "); match rpassword::read_password_with_config(config) { Ok(pass) => println!("You entered: '{}'", pass), Err(e) => eprintln!("Error: {}", e), } println!("\n=== read_password_with_config(...) with Mask('*') mode ==="); let config = ConfigBuilder::new().password_feedback_mask('*').build(); prompt("Password: "); match rpassword::read_password_with_config(config) { Ok(pass) => println!("You entered: '{}'", pass), Err(e) => eprintln!("Error: {}", e), } println!("\n=== read_password_with_config(...) with Mask('#') mode ==="); let config = ConfigBuilder::new().password_feedback_mask('#').build(); prompt("Password: "); match rpassword::read_password_with_config(config) { Ok(pass) => println!("You entered: '{}'", pass), Err(e) => eprintln!("Error: {}", e), } println!("\n=== read_password_with_config(...) with PartialMask('*', 3) mode ==="); let config = ConfigBuilder::new() .password_feedback_partial_mask('*', 3) .build(); prompt("Password: "); match rpassword::read_password_with_config(config) { Ok(pass) => println!("You entered: '{}'", pass), Err(e) => eprintln!("Error: {}", e), } } rpassword-7.5.4/githooks/pre-commit000075500000000000000000000002431046102023000155150ustar 00000000000000#!/usr/bin/env bash set -xeuo pipefail if [ -n "$GIT_GLOBAL_HOOKS_PATH" -a -x "$GIT_GLOBAL_HOOKS_PATH/pre-commit" ]; then $GIT_GLOBAL_HOOKS_PATH/pre-commit fi rpassword-7.5.4/githooks/pre-push000075500000000000000000000003021046102023000152000ustar 00000000000000#!/usr/bin/env bash set -xeuo pipefail input="$(cat)" if [ -n "$GIT_GLOBAL_HOOKS_PATH" -a -x "$GIT_GLOBAL_HOOKS_PATH/pre-push" ]; then echo -n "$input" | $GIT_GLOBAL_HOOKS_PATH/pre-push fi rpassword-7.5.4/githooks/pre-rebase000075500000000000000000000002431046102023000154660ustar 00000000000000#!/usr/bin/env bash set -xeuo pipefail if [ -n "$GIT_GLOBAL_HOOKS_PATH" -a -x "$GIT_GLOBAL_HOOKS_PATH/pre-rebase" ]; then $GIT_GLOBAL_HOOKS_PATH/pre-rebase fi rpassword-7.5.4/shell.nix000064400000000000000000000010571046102023000135170ustar 00000000000000{pkgs ? import {}}: pkgs.mkShell { nativeBuildInputs = with pkgs; [ rustup #pkgsCross.mingwW64.stdenv.cc wineWowPackages.stable emscripten ]; buildInputs = with pkgs; [ #pkgsCross.mingwW64.windows.pthreads nodejs podman ]; shellHook = '' git config set core.hooksPath githooks rustup install 1.85 rustup default 1.85 rustup component add rust-src rustup target add x86_64-unknown-linux-gnu rustup target add x86_64-pc-windows-gnu rustup target add wasm32-unknown-emscripten ''; } rpassword-7.5.4/src/config.rs000064400000000000000000000137511046102023000142760ustar 00000000000000use crate::DEFAULT_INPUT_PATH; use crate::DEFAULT_OUTPUT_PATH; use std::io::{Cursor, Read, Write}; /// Controls visual feedback when the user types a password. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] #[non_exhaustive] pub(crate) enum PasswordFeedback { /// Show nothing while typing (current default behavior). #[default] Hide, /// Show the given mask char for every character typed. /// e.g. `Mask('*')` shows stars. Mask(char), /// Show the actual character for the first N chars, then the given /// mask char for the rest. /// e.g. `PartialMask('*', 3)` shows first 3 chars in plaintext, then stars. PartialMask(char, usize), } /// Specifies the source for input. pub(crate) enum InputTarget { FilePath(String), Reader(Box), } /// Specifies the destination for output. /// /// This enum defines where input is read from or where output is written to. /// It supports file paths, in-memory cursors, or no input/output at all. pub(crate) enum OutputTarget { FilePath(String), Writer(Box), Void, } /// Configuration for prompting and reading a password. /// /// Obtained from `ConfigBuilder::build()`. pub struct Config { pub(crate) password_feedback: PasswordFeedback, pub(crate) input: InputTarget, pub(crate) output: OutputTarget, } /// A builder for creating a [`Config`]. /// /// This struct provides a convenient way to configure the behavior of password reading, /// such as setting visual feedback, specifying an input path, discarding output, etc. /// /// # Examples /// /// ## Customising how the password is hidden /// ``` /// use rpassword::{ConfigBuilder}; /// /// let config = ConfigBuilder::new() /// .password_feedback_mask('*') /// .password_feedback_partial_mask('*', 3) /// .password_feedback_hide() // this is the default /// .build(); /// ``` /// /// ## Setting custom input file path /// ``` /// use rpassword::{ConfigBuilder}; /// /// let config = ConfigBuilder::new() /// .input_file_path("path/to/file/containing/password") /// .build(); /// ``` /// /// ## Reading from in-memory data /// ``` /// use rpassword::{ConfigBuilder}; /// /// let config = ConfigBuilder::new() /// .input_data("my-password\n") /// .build(); /// ``` /// /// ## Reading from `impl Read` /// ``` /// use std::io::Cursor; /// use rpassword::{ConfigBuilder}; /// /// let config = ConfigBuilder::new() /// .input_reader(Cursor::new("my-password\n")) /// .build(); /// ``` /// /// ## Setting custom output file path /// ``` /// use rpassword::{ConfigBuilder}; /// /// let config = ConfigBuilder::new() /// .output_file_path("path/to/file/for/prompt/output") /// .build(); /// ``` /// /// ## Writing to `impl Write` /// ``` /// use std::io::Cursor; /// use rpassword::{ConfigBuilder}; /// /// let config = ConfigBuilder::new() /// .output_writer(Cursor::new(Vec::::new())) /// .build(); /// ``` /// /// ## Discarding output /// ``` /// use rpassword::{ConfigBuilder}; /// /// let config = ConfigBuilder::new() /// .output_discard() /// .build(); /// ``` pub struct ConfigBuilder { feedback: PasswordFeedback, input: InputTarget, output: OutputTarget, } impl Default for ConfigBuilder { fn default() -> Self { ConfigBuilder { feedback: PasswordFeedback::default(), input: InputTarget::FilePath(DEFAULT_INPUT_PATH.to_string()), output: OutputTarget::FilePath(DEFAULT_OUTPUT_PATH.to_string()), } } } impl ConfigBuilder { pub fn new() -> ConfigBuilder { ConfigBuilder::default() } /// Sets the visual feedback to a mask with the given character. pub fn password_feedback_mask(self, mask: char) -> ConfigBuilder { ConfigBuilder { feedback: PasswordFeedback::Mask(mask), ..self } } /// Sets the visual feedback to a mask with the given character. pub fn password_feedback_partial_mask(self, mask: char, length: usize) -> ConfigBuilder { ConfigBuilder { feedback: PasswordFeedback::PartialMask(mask, length), ..self } } /// Sets the visual feedback none, hides the password entirely. pub fn password_feedback_hide(self) -> ConfigBuilder { ConfigBuilder { feedback: PasswordFeedback::Hide, ..self } } /// Reads the password from the file at the given path. pub fn input_file_path(self, file_path: impl Into) -> ConfigBuilder { ConfigBuilder { input: InputTarget::FilePath(file_path.into()), ..self } } /// Reads the passwords from the data. pub fn input_data(self, data: impl Into>) -> ConfigBuilder { ConfigBuilder { input: InputTarget::Reader(Box::new(Cursor::new(data.into()))), ..self } } /// Reads the passwords from a custom Read implementation. pub fn input_reader(self, reader: impl Read + 'static) -> ConfigBuilder { ConfigBuilder { input: InputTarget::Reader(Box::new(reader)), ..self } } /// Sends the output to the file at the given path. pub fn output_file_path(self, file_path: impl Into) -> ConfigBuilder { ConfigBuilder { output: OutputTarget::FilePath(file_path.into()), ..self } } /// Sends output to a custom Write implementation. pub fn output_writer(self, writer: impl Write + 'static) -> ConfigBuilder { ConfigBuilder { output: OutputTarget::Writer(Box::new(writer)), ..self } } /// Discards any output. pub fn output_discard(self) -> ConfigBuilder { ConfigBuilder { output: OutputTarget::Void, ..self } } /// Builds the final [`Config`]. pub fn build(self) -> Config { Config { password_feedback: self.feedback, input: self.input, output: self.output, } } } rpassword-7.5.4/src/feedback.rs000064400000000000000000000264061046102023000145560ustar 00000000000000use crate::config::PasswordFeedback; use rtoolbox::safe_string::SafeString; use std::cmp::min; pub struct FeedbackState { password: SafeString, needs_terminal_configuration: bool, displayed_count: usize, feedback: PasswordFeedback, } impl FeedbackState { pub fn new(feedback: PasswordFeedback, needs_terminal_configuration: bool) -> Self { FeedbackState { password: SafeString::new(), needs_terminal_configuration, displayed_count: 0, feedback, } } pub fn push_char(&mut self, c: char) -> String { self.password.push(c); if !self.needs_terminal_configuration { return String::new(); } match self.feedback { PasswordFeedback::Hide => String::new(), PasswordFeedback::Mask(mask) => { self.displayed_count += 1; mask.to_string() } PasswordFeedback::PartialMask(mask, n) => { self.displayed_count += 1; if self.displayed_count <= n { c.to_string() } else { mask.to_string() } } } } pub fn pop_char(&mut self) -> String { let last_char = self.password.chars().last(); if let Some(c) = last_char { let new_len = self.password.len() - c.len_utf8(); self.password.truncate(new_len); if !self.needs_terminal_configuration { return String::new(); } if self.displayed_count > 0 { self.displayed_count -= 1; "\x08 \x08".to_string() } else { String::new() } } else { String::new() } } pub fn clear(&mut self) -> String { self.password = SafeString::new(); if !self.needs_terminal_configuration { return String::new(); } let count = self.displayed_count; self.displayed_count = 0; "\x08 \x08".repeat(count).to_string() } pub fn clear_til_last_space(&mut self) -> String { let mut trimmed = self.password.as_str().trim_end(); match trimmed.rfind(' ') { Some(last_space_position) => { trimmed = &trimmed[..=last_space_position]; } None => { trimmed = ""; } } let new_displayed_count = trimmed.chars().count(); let removed_chars = self.password.chars().count() - trimmed.chars().count(); self.password = trimmed.to_string().into(); if !self.needs_terminal_configuration { return String::new(); } let count = self.displayed_count; self.displayed_count = new_displayed_count; "\x08 \x08".repeat(min(removed_chars, count)).to_string() } pub fn abort(&mut self) -> String { self.password = SafeString::new(); if !self.needs_terminal_configuration { return String::new(); } self.displayed_count = 0; '\n'.to_string() } pub fn finish(&mut self) -> String { if !self.needs_terminal_configuration { return String::new(); } '\n'.to_string() } pub fn is_empty(&self) -> bool { self.password.is_empty() } pub fn into_password(self) -> String { self.password.into_inner() } } #[cfg(test)] mod tests { mod with_terminal_configuration { use crate::config::PasswordFeedback; use crate::feedback::FeedbackState; #[test] fn feedback_state_mask_star() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), true); assert_eq!(state.push_char('a'), "*"); assert_eq!(state.push_char('b'), "*"); assert_eq!(state.push_char('🚲'), "*"); assert_eq!(state.push_char('🚲'), "*"); assert_eq!(state.pop_char(), "\x08 \x08"); assert_eq!(state.into_password(), "ab🚲"); } #[test] fn feedback_state_mask_hash() { let mut state = FeedbackState::new(PasswordFeedback::Mask('#'), true); assert_eq!(state.push_char('x'), "#"); assert_eq!(state.push_char('y'), "#"); assert_eq!(state.push_char('🚲'), "#"); assert_eq!(state.push_char('🚲'), "#"); assert_eq!(state.into_password(), "xy🚲🚲"); } #[test] fn feedback_state_hide() { let mut state = FeedbackState::new(PasswordFeedback::Hide, true); assert!(state.push_char('a').is_empty()); assert!(state.push_char('b').is_empty()); assert!(state.push_char('🚲').is_empty()); assert!(state.pop_char().is_empty()); assert_eq!(state.into_password(), "ab"); } #[test] fn feedback_state_partial_mask() { let mut state = FeedbackState::new(PasswordFeedback::PartialMask('*', 3), true); assert_eq!(state.push_char('a'), "a"); assert_eq!(state.push_char('b'), "b"); assert_eq!(state.push_char('c'), "c"); assert_eq!(state.push_char('🚲'), "*"); assert_eq!(state.push_char('🚲'), "*"); assert_eq!(state.into_password(), "abc🚲🚲"); } #[test] fn feedback_state_backspace_empty() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), true); assert!(state.pop_char().is_empty()); } #[test] fn feedback_state_clear() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), true); state.push_char('a'); state.push_char('b'); state.push_char('c'); state.push_char('🚲'); assert_eq!(state.clear(), "\x08 \x08\x08 \x08\x08 \x08\x08 \x08"); assert!(state.is_empty()); } #[test] fn feedback_state_clear_til_last_space() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), true); state.push_char('a'); state.push_char('b'); state.push_char('c'); state.push_char(' '); state.push_char('d'); state.push_char('🚲'); state.push_char(' '); state.push_char(' '); state.push_char(' '); assert_eq!( state.clear_til_last_space(), "\x08 \x08\x08 \x08\x08 \x08\x08 \x08\x08 \x08" ); assert_eq!(state.into_password(), "abc "); } #[test] fn feedback_state_abort() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), true); state.push_char('a'); state.push_char('b'); state.push_char('c'); assert_eq!(state.abort(), "\n"); assert!(state.is_empty()); } #[test] fn feedback_state_finish() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), true); state.push_char('a'); state.push_char('b'); state.push_char('c'); assert_eq!(state.finish(), "\n"); assert_eq!(state.into_password(), "abc"); } #[test] fn feedback_state_partial_mask_zero() { let mut state = FeedbackState::new(PasswordFeedback::PartialMask('*', 0), true); assert_eq!(state.push_char('a'), "*"); assert_eq!(state.push_char('b'), "*"); assert_eq!(state.into_password(), "ab"); } } mod without_terminal_configuration { use crate::config::PasswordFeedback; use crate::feedback::FeedbackState; #[test] fn feedback_state_mask_star() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), false); assert_eq!(state.push_char('a'), ""); assert_eq!(state.push_char('b'), ""); assert_eq!(state.push_char('c'), ""); assert_eq!(state.pop_char(), ""); assert_eq!(state.into_password(), "ab"); } #[test] fn feedback_state_mask_hash() { let mut state = FeedbackState::new(PasswordFeedback::Mask('#'), false); assert_eq!(state.push_char('x'), ""); assert_eq!(state.push_char('y'), ""); assert_eq!(state.into_password(), "xy"); } #[test] fn feedback_state_hide() { let mut state = FeedbackState::new(PasswordFeedback::Hide, false); assert!(state.push_char('a').is_empty()); assert!(state.push_char('b').is_empty()); assert!(state.pop_char().is_empty()); assert_eq!(state.into_password(), "a"); } #[test] fn feedback_state_partial_mask() { let mut state = FeedbackState::new(PasswordFeedback::PartialMask('*', 3), false); assert_eq!(state.push_char('a'), ""); assert_eq!(state.push_char('b'), ""); assert_eq!(state.push_char('c'), ""); assert_eq!(state.push_char('d'), ""); assert_eq!(state.push_char('e'), ""); assert_eq!(state.into_password(), "abcde"); } #[test] fn feedback_state_backspace_empty() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), false); assert!(state.pop_char().is_empty()); } #[test] fn feedback_state_clear() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), false); state.push_char('a'); state.push_char('b'); state.push_char('c'); assert_eq!(state.clear(), ""); assert!(state.is_empty()); } #[test] fn feedback_state_clear_til_last_space() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), false); state.push_char('a'); state.push_char('b'); state.push_char('c'); state.push_char(' '); state.push_char('d'); state.push_char('🚲'); state.push_char(' '); state.push_char(' '); state.push_char(' '); assert_eq!(state.clear_til_last_space(), ""); assert_eq!(state.into_password(), "abc "); } #[test] fn feedback_state_abort() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), false); state.push_char('a'); state.push_char('b'); state.push_char('c'); assert_eq!(state.abort(), ""); assert!(state.is_empty()); } #[test] fn feedback_state_finish() { let mut state = FeedbackState::new(PasswordFeedback::Mask('*'), false); state.push_char('a'); state.push_char('b'); state.push_char('c'); assert_eq!(state.finish(), ""); assert_eq!(state.into_password(), "abc"); } #[test] fn feedback_state_partial_mask_zero() { let mut state = FeedbackState::new(PasswordFeedback::PartialMask('*', 0), false); assert_eq!(state.push_char('a'), ""); assert_eq!(state.push_char('b'), ""); assert_eq!(state.into_password(), "ab"); } } } rpassword-7.5.4/src/lib.rs000064400000000000000000000303051046102023000135710ustar 00000000000000//! This library makes it easy to read passwords in a console application on all platforms, Unix, //! Windows, WASM, etc. //! //! Here's how you can read a password: //! ```no_run //! let password = rpassword::read_password().unwrap(); //! println!("Your password is {}", password); //! ``` //! //! You can also prompt for a password: //! ```no_run //! let password = rpassword::prompt_password("Your password: ").unwrap(); //! println!("Your password is {}", password); //! ``` //! //! For testing or custom use-cases, you can use `read_password_with_config` and `prompt_password_with_config`: //! ``` //! use std::io::{Cursor, Write}; //! //! let config = rpassword::ConfigBuilder::new() //! // Default input is the console, but we can pass any file path or raw data //! .input_data("my-password\n") //! // Default output is the console, but we can also discard it //! .output_discard() //! // Default behavior is to hide the password as it's being typed, but we can change that //! .password_feedback_mask('*') //! .build(); //! //! let password = rpassword::read_password_with_config(config).unwrap(); //! println!("Your password is {}", password); //! ``` use rtoolbox::fix_line_issues::fix_line_issues; use rtoolbox::print_tty::print_writer; use rtoolbox::safe_string::SafeString; use std::fs::OpenOptions; use std::io; use std::io::{BufRead, Cursor, Write}; mod config; mod feedback; #[cfg(all(target_family = "unix", not(target_family = "wasm")))] mod unix; #[cfg(all(target_family = "unix", not(target_family = "wasm")))] use unix::*; #[cfg(target_family = "windows")] mod windows; #[cfg(target_family = "windows")] use windows::*; mod utf8; #[cfg(target_family = "wasm")] mod wasm; #[cfg(target_family = "wasm")] use wasm::*; use crate::config::{OutputTarget, PasswordFeedback}; use crate::feedback::FeedbackState; pub use config::{Config, ConfigBuilder}; const BACKSPACE: char = '\x08'; const DEL: char = '\x7F'; const CTRL_C: char = '\x03'; const CTRL_D: char = '\x04'; const CTRL_U: char = '\x15'; const CTRL_W: char = '\x17'; const ESC: char = '\x1B'; trait RawPasswordInput { fn new(config: Config) -> io::Result; fn needs_terminal_configuration(&self) -> bool; fn apply_terminal_configuration(&mut self) -> io::Result<()>; fn read_char(&mut self) -> std::io::Result; fn write_output(&mut self, output: &str) -> std::io::Result<()>; fn send_signal_sigint(&mut self) -> std::io::Result<()>; /// Reads a password from the console using the given config fn read_password(&mut self, password_feedback: PasswordFeedback) -> std::io::Result { if self.needs_terminal_configuration() { self.apply_terminal_configuration()?; } let mut state = FeedbackState::new(password_feedback, self.needs_terminal_configuration()); loop { let c = match self.read_char() { Ok(c) => c, Err(e) => { if e.kind() == std::io::ErrorKind::UnexpectedEof { break; } return Err(e); } }; match c { // LF / CR (Enter) '\n' | '\r' => { let output = state.finish(); if !output.is_empty() { self.write_output(output.as_str())?; } break; } // Backspace / DEL DEL | BACKSPACE => { let output = state.pop_char(); if !output.is_empty() { self.write_output(output.as_str())?; } } // Ctrl-U: clear line CTRL_U => { let output = state.clear(); if !output.is_empty() { self.write_output(output.as_str())?; } } // Ctrl-W: clear to last space CTRL_W => { let output = state.clear_til_last_space(); if !output.is_empty() { self.write_output(output.as_str())?; } } // Ctrl-C: interrupt CTRL_C => { let output = state.abort(); if !output.is_empty() { self.write_output(output.as_str())?; } self.send_signal_sigint()?; return Err(std::io::Error::new( std::io::ErrorKind::Interrupted, "interrupted", )); } // Ctrl-D: EOF when empty CTRL_D => { if state.is_empty() { return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, "unexpected end of file", )); } } // ESC: consume and discard escape sequence like arrow keys ESC => { let c = match self.read_char() { Ok(c) => c, Err(e) => { if e.kind() == std::io::ErrorKind::UnexpectedEof { break; } return Err(e); } }; if c == '[' || c == 'O' { // CSI (ESC [) or SS3 (ESC O): read until final byte (0x40-0x7E) loop { let c = match self.read_char() { Ok(c) => c, Err(e) => { if e.kind() == std::io::ErrorKind::UnexpectedEof { break; } return Err(e); } }; if ('\x40'..='\x7E').contains(&c) { break; } } } } c if !c.is_control() => { let output = state.push_char(c); if !output.is_empty() { self.write_output(output.as_str())?; } } // Discard unrecognized control characters and invalid input _ => {} } } Ok(state.into_password()) } } /// Reads a password from `impl BufRead`. /// /// **Deprecated**: This method is deprecated. Use `read_password_with_config` with a temporary file instead. /// See the example below for updated usage. /// /// # Example of Updated Usage /// ``` /// use std::io::{Cursor, Write}; /// use rpassword::{read_password_with_config, ConfigBuilder}; /// /// let config = ConfigBuilder::new() /// .input_reader(Cursor::new("my-password\n")) // anything that implements Read is OK here /// .output_discard() /// .build(); /// /// let password = read_password_with_config(config).unwrap(); /// println!("The typed password is: {}", password); /// ``` #[deprecated( since = "7.5.0", note = "Use `read_password_with_config` with `ConfigBuilder::input_reader` instead." )] pub fn read_password_from_bufread(reader: &mut impl BufRead) -> std::io::Result { let mut password = SafeString::new(); reader.read_line(&mut password)?; fix_line_issues(password.into_inner()) } /// Prompts on `impl Write` and then reads a password from `impl BufRead`. /// /// **Deprecated**: This method is deprecated. Use `prompt_password_with_config` with a temporary file instead. /// See the example below for updated usage. /// /// # Example of Updated Usage /// ``` /// use std::io::{Cursor, Write}; /// use rpassword::{prompt_password_with_config, ConfigBuilder}; /// /// let mut input = Cursor::new(b"my-password\n".to_vec()); /// /// let config = ConfigBuilder::new() /// .input_reader(Cursor::new("my-password\n")) // anything that implements Read is OK here /// .output_writer(Cursor::new(Vec::::new())) // anything that implements Write is OK here /// .build(); /// /// let password = prompt_password_with_config("Your password: ", config).unwrap(); /// println!("The typed password is: {}", password); /// ``` #[deprecated( since = "7.5.0", note = "Use `prompt_password_with_config` with `ConfigBuilder::input_reader` and `ConfigBuilder::output_writer()` instead." )] #[allow(deprecated)] pub fn prompt_password_from_bufread( reader: &mut impl BufRead, writer: &mut impl Write, prompt: impl ToString, ) -> std::io::Result { print_writer(writer, prompt.to_string().as_str()) .and_then(|_| read_password_from_bufread(reader)) } /// Reads a password from TTY using the given config pub fn read_password_with_config(config: Config) -> std::io::Result { let password_feedback = config.password_feedback; let mut raw_mode_input = RawModeInput::new(config)?; raw_mode_input.read_password(password_feedback) } /// Reads a password from the TTY pub fn read_password() -> std::io::Result { read_password_with_config(ConfigBuilder::default().build()) } /// Prompts on the TTY and then reads a password from TTY pub fn prompt_password(prompt: impl ToString) -> std::io::Result { prompt_password_with_config(prompt, ConfigBuilder::new().build()) } /// Prompts and then reads a password using the given config pub fn prompt_password_with_config( prompt: impl ToString, mut config: Config, ) -> std::io::Result { { // Create an inner scope to allow using the config without moving it // The mut ref to the config is dropped at the end of the scope let mut output: Box = match &mut config.output { OutputTarget::FilePath(path) => Box::new(OpenOptions::new().write(true).open(path)?), OutputTarget::Writer(writer) => Box::new(writer), OutputTarget::Void => Box::new(Cursor::new(Vec::::new())), // TODO: Should use a SafeVec instead }; output.write_all(prompt.to_string().as_bytes())?; output.flush()?; } read_password_with_config(config) } #[cfg(test)] mod tests { use super::*; use std::io::Cursor; fn mock_input_crlf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\r\nAnother mocked response.\r\n"[..]) } fn mock_input_lf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\nAnother mocked response.\n"[..]) } #[test] #[allow(deprecated)] fn can_read_from_redirected_input_many_times() { let mut reader_crlf = mock_input_crlf(); let response = read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "A mocked response."); let response = read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "Another mocked response."); let mut reader_lf = mock_input_lf(); let response = read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "A mocked response."); let response = read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "Another mocked response."); } #[test] fn test_read_password_with_config_with_input_file() { let mut temp_file = tempfile::NamedTempFile::new().unwrap(); temp_file.write_all(b"password\n").unwrap(); let path = temp_file.path().to_str().unwrap().to_string(); let config = ConfigBuilder::new() .input_file_path(path.as_str()) .output_discard() .build(); let result = read_password_with_config(config); assert_eq!("password", result.unwrap()); } #[test] fn test_read_password_with_config_with_input_cursor() { let config = ConfigBuilder::new() .input_data("hello world\x7F\x7F\x7F\n") .output_discard() .build(); let result = read_password_with_config(config); assert_eq!("hello wo", result.unwrap()); } } rpassword-7.5.4/src/unix.rs000064400000000000000000000131331046102023000140060ustar 00000000000000use crate::RawPasswordInput; use crate::config::{Config, InputTarget, OutputTarget}; use crate::utf8::read_char; use libc::{ECHO, ECHONL, ICANON, ISIG, TCSANOW, VMIN, VTIME, c_int, isatty, tcsetattr, termios}; use std::fs::OpenOptions; use std::io::{self, Cursor, Read, Write}; use std::mem; use std::os::fd::RawFd; use std::os::unix::io::AsRawFd; pub(crate) const DEFAULT_INPUT_PATH: &str = "/dev/tty"; pub(crate) const DEFAULT_OUTPUT_PATH: &str = "/dev/tty"; /// Turns a C function return into an IO Result fn io_result(ret: c_int) -> std::io::Result<()> { match ret { 0 => Ok(()), _ => Err(std::io::Error::last_os_error()), } } fn is_interactive_terminal(fd: c_int) -> bool { unsafe { isatty(fd) != 0 } } fn safe_tcgetattr(fd: c_int) -> std::io::Result { let mut term = mem::MaybeUninit::::uninit(); io_result(unsafe { ::libc::tcgetattr(fd, term.as_mut_ptr()) })?; Ok(unsafe { term.assume_init() }) } fn safe_tcsetattr(fd: c_int, term: &mut termios) -> std::io::Result<()> { io_result(unsafe { tcsetattr(fd, TCSANOW, term) }) } pub(crate) struct RawModeInput { input: Box, input_fd: Option, input_term_orig: Option, input_is_tty: bool, output: Box, output_fd: Option, output_term_orig: Option, output_is_tty: bool, } impl Drop for RawModeInput { fn drop(&mut self) { if let (Some(fd), Some(term_orig)) = (self.input_fd, self.input_term_orig.as_mut()) { unsafe { tcsetattr(fd, TCSANOW, term_orig); } } if let (Some(fd), Some(term_orig)) = (self.output_fd, self.output_term_orig.as_mut()) { unsafe { tcsetattr(fd, TCSANOW, term_orig); } } } } impl RawPasswordInput for RawModeInput { fn new(config: Config) -> io::Result { let mut input_fd: Option = None; let input: Box = match config.input { InputTarget::FilePath(path) => { let file = OpenOptions::new().read(true).open(path)?; input_fd = Some(file.as_raw_fd()); Box::new(file) } InputTarget::Reader(reader) => Box::new(reader), }; let input_is_tty = if let Some(fd) = input_fd { is_interactive_terminal(fd) } else { false }; let input_term_orig = if input_is_tty { if let Some(fd) = input_fd { Some(safe_tcgetattr(fd)?) } else { None } } else { None }; let mut output_fd: Option = None; let output: Box = match config.output { OutputTarget::FilePath(path) => { let file = OpenOptions::new().write(true).open(path)?; output_fd = Some(file.as_raw_fd()); Box::new(file) } OutputTarget::Writer(writer) => Box::new(writer), OutputTarget::Void => Box::new(Cursor::new(Vec::::new())), // TODO: Should use a SafeVec instead }; let output_is_tty = if let Some(fd) = output_fd { is_interactive_terminal(fd) } else { false }; let output_term_orig = if output_is_tty { if let Some(fd) = output_fd { Some(safe_tcgetattr(fd)?) } else { None } } else { None }; Ok(RawModeInput { input, input_fd, input_term_orig, input_is_tty, output, output_fd, output_term_orig, output_is_tty, }) } fn needs_terminal_configuration(&self) -> bool { self.input_is_tty } fn apply_terminal_configuration(&mut self) -> io::Result<()> { if self.input_is_tty { if let Some(fd) = self.input_fd { let mut term = safe_tcgetattr(fd)?; term.c_lflag &= !(ECHO | ICANON | ECHONL | ISIG); term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 0; safe_tcsetattr(fd, &mut term)?; } } if self.output_is_tty { if let Some(fd) = self.output_fd { let mut term = safe_tcgetattr(fd)?; term.c_lflag &= !(ECHO | ICANON | ECHONL | ISIG); term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 0; safe_tcsetattr(fd, &mut term)?; } } Ok(()) } fn read_char(&mut self) -> std::io::Result { read_char(&mut self.input) } fn write_output(&mut self, output: &str) -> std::io::Result<()> { self.output.write_all(output.as_bytes())?; self.output.flush() } fn send_signal_sigint(&mut self) -> io::Result<()> { if unsafe { libc::raise(libc::SIGINT) != 0 } { return Err(std::io::Error::last_os_error()); } Ok(()) } } #[cfg(test)] mod tests { use crate::config::ConfigBuilder; use crate::read_password_with_config; #[test] fn test_read_password_with_config_errors_with_file_not_found() { let config = ConfigBuilder::new() .input_file_path("/does/not/exist") .output_discard() .build(); // This should fail because the file does not exist let result = read_password_with_config(config); assert!(result.is_err()); let err = result.unwrap_err(); assert_eq!(err.raw_os_error(), Some(libc::ENOENT)); } } rpassword-7.5.4/src/utf8.rs000064400000000000000000000024371046102023000137160ustar 00000000000000use std::io::Read; pub fn read_char(reader: &mut impl Read) -> std::io::Result { let mut byte = [0u8; 1]; let n = reader.read(&mut byte)?; if n == 0 { return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, "unexpected end of file", )); } match byte[0] { // ASCII 0x00..=0x7F => Ok(byte[0] as char), // UTF-8 lead byte 0xC2..=0xF4 => { let width = match byte[0] { 0xC2..=0xDF => 2, 0xE0..=0xEF => 3, 0xF0..=0xF4 => 4, _ => { return Ok('\u{FFFD}'); } }; let mut utf8_buf = vec![byte[0]]; for _ in 1..width { let n = reader.read(&mut byte)?; if n == 0 { return Ok('\u{FFFD}'); } utf8_buf.push(byte[0]); } if let Ok(s) = std::str::from_utf8(&utf8_buf) { if let Some(c) = s.chars().next() { Ok(c) } else { Ok('\u{FFFD}') } } else { Ok('\u{FFFD}') } } // Invalid byte _ => Ok('\u{FFFD}'), } } rpassword-7.5.4/src/wasm.rs000064400000000000000000000030351046102023000137720ustar 00000000000000use crate::RawPasswordInput; use crate::config::{Config, InputTarget}; use rtoolbox::fix_line_issues::fix_line_issues; use std::fs::OpenOptions; use std::io::{self, BufRead, BufReader, Read}; pub(crate) const DEFAULT_INPUT_PATH: &str = "/dev/stdin"; pub(crate) const DEFAULT_OUTPUT_PATH: &str = "/dev/stdout"; pub(crate) struct RawModeInput { config: Config, } impl RawPasswordInput for RawModeInput { fn new(config: Config) -> io::Result { Ok(RawModeInput { config }) } fn needs_terminal_configuration(&self) -> bool { false } fn apply_terminal_configuration(&mut self) -> io::Result<()> { Ok(()) } #[allow(unused)] fn read_char(&mut self) -> std::io::Result { unimplemented!() } fn read_password( &mut self, _password_feedback: crate::PasswordFeedback, ) -> std::io::Result { let input: Box = match &mut self.config.input { InputTarget::FilePath(path) => Box::new(OpenOptions::new().read(true).open(path)?), InputTarget::Reader(reader) => Box::new(reader), }; let mut reader = BufReader::new(input); let mut line = String::new(); reader.read_line(&mut line)?; fix_line_issues(line) } fn write_output(&mut self, _output: &str) -> std::io::Result<()> { Ok(()) } fn send_signal_sigint(&mut self) -> io::Result<()> { // Not sure what to do with signals on WASM, so just ignore it for now Ok(()) } } rpassword-7.5.4/src/windows.rs000064400000000000000000000323741046102023000145250ustar 00000000000000use crate::RawPasswordInput; use crate::config::{Config, InputTarget, OutputTarget}; use crate::utf8::read_char; use std::io; use std::io::{Cursor, Read, Write}; use windows_sys::Win32::Foundation::{GENERIC_READ, GENERIC_WRITE, HANDLE, INVALID_HANDLE_VALUE}; use windows_sys::Win32::Storage::FileSystem::{ CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, ReadFile, WriteFile, }; use windows_sys::Win32::System::Console::{ CONSOLE_MODE, CTRL_C_EVENT, ENABLE_PROCESSED_INPUT, GenerateConsoleCtrlEvent, GetConsoleMode, ReadConsoleW, SetConsoleMode, WriteConsoleW, }; pub(crate) const DEFAULT_INPUT_PATH: &str = "CONIN$"; pub(crate) const DEFAULT_OUTPUT_PATH: &str = "CONOUT$"; fn is_interactive_terminal(handle: windows_sys::Win32::Foundation::HANDLE) -> bool { let mut mode: CONSOLE_MODE = 0; unsafe { // Try to get the console mode. If it succeeds, the handle is a console handle. GetConsoleMode(handle, &mut mode) != 0 } } fn get_console_mode(handle: HANDLE) -> io::Result { let mut mode: CONSOLE_MODE = 0; if unsafe { GetConsoleMode(handle, &mut mode as *mut CONSOLE_MODE) } == 0 { return Err(std::io::Error::last_os_error()); } Ok(mode) } fn open_file_or_console(path: &str) -> io::Result { let handle = unsafe { CreateFileW( path.encode_utf16() .chain(std::iter::once(0)) .collect::>() .as_ptr(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, std::ptr::null(), OPEN_EXISTING, 0, INVALID_HANDLE_VALUE, ) }; if handle == INVALID_HANDLE_VALUE { return Err(std::io::Error::last_os_error()); } Ok(handle) } fn read_wchar_from_console(handle: windows_sys::Win32::Foundation::HANDLE) -> io::Result { let mut buf: [u16; 1] = [0]; let mut wchars_read: u32 = 0; if unsafe { ReadConsoleW( handle, buf.as_mut_ptr() as *mut std::ffi::c_void, 1, &mut wchars_read, std::ptr::null(), ) } == 0 { return Err(std::io::Error::last_os_error()); } if wchars_read == 0 { return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, "unexpected end of file", )); } Ok(buf[0]) } fn read_char_from_console(handle: windows_sys::Win32::Foundation::HANDLE) -> io::Result { let wchar1 = read_wchar_from_console(handle)?; // Handle UTF-16 surrogate pairs: characters above U+FFFF (e.g. emoji) // are split across two u16 values — a high surrogate (0xD800..0xDBFF) // followed by a low surrogate. Read the second half before decoding. if (0xD800..=0xDBFF).contains(&wchar1) { let wchar2 = match read_wchar_from_console(handle) { Ok(wchar) => wchar, Err(e) => { if e.kind() == io::ErrorKind::UnexpectedEof { return Ok('\u{FFFD}'); } return Err(e); } }; match char::decode_utf16([wchar1, wchar2]) .next() .and_then(|r| r.ok()) { Some(c) => Ok(c), // Invalid/mismatched surrogate pair; shouldn't happen with // ReadConsoleW, but we skip gracefully rather than panicking. None => Ok('\u{FFFD}'), } } else { match char::from_u32(wchar1 as u32) { Some(c) => Ok(c), // Orphaned surrogate (0xD800-0xDFFF) as a lone u16; defensive // guard since ReadConsoleW shouldn't produce these. None => Ok('\u{FFFD}'), } } } fn read_byte_from_file(handle: windows_sys::Win32::Foundation::HANDLE) -> io::Result { let mut buf_bytes: [u8; 1] = [0]; let mut bytes_read: u32 = 0; unsafe { if ReadFile( handle, buf_bytes.as_mut_ptr(), buf_bytes.len() as u32, &mut bytes_read, std::ptr::null_mut(), ) == 0 { return Err(io::Error::last_os_error()); } } if bytes_read == 0 { return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, "unexpected end of file", )); } Ok(buf_bytes[0]) } // TODO: this is mostly duplicated with utf8::read_char, should be deduplicated fn read_char_from_file(handle: windows_sys::Win32::Foundation::HANDLE) -> io::Result { let byte1 = read_byte_from_file(handle)?; match byte1 { // ASCII 0x00..=0x7F => Ok(byte1 as char), // UTF-8 lead byte 0xC0..=0xF7 => { let width = match byte1 { 0xC0..=0xDF => 2, 0xE0..=0xEF => 3, 0xF0..=0xF7 => 4, _ => unreachable!(), }; let mut utf8_buf = vec![byte1]; for _ in 1..width { match read_byte_from_file(handle) { Ok(next_byte) => { utf8_buf.push(next_byte); } Err(e) => { if e.kind() == io::ErrorKind::UnexpectedEof { return Ok('\u{FFFD}'); } return Err(e); } } } match std::str::from_utf8(&utf8_buf) { Ok(s) => { if let Some(c) = s.chars().next() { Ok(c) } else { Ok('\u{FFFD}') } } _ => Ok('\u{FFFD}'), } } // Invalid byte _ => Ok('\u{FFFD}'), } } fn write_output_to_console( handle: windows_sys::Win32::Foundation::HANDLE, output: &str, ) -> std::io::Result<()> { let output_utf16 = output .encode_utf16() .chain(std::iter::once(0)) .collect::>(); let mut wchars_written: u32 = 0; unsafe { if WriteConsoleW( handle, output_utf16.as_ptr(), output_utf16.len() as u32, &mut wchars_written, std::ptr::null_mut(), ) == 0 { return Err(std::io::Error::last_os_error()); } } Ok(()) } fn write_output_to_file( handle: windows_sys::Win32::Foundation::HANDLE, output: &str, ) -> std::io::Result<()> { let output_bytes = output.as_bytes(); let mut bytes_written: u32 = 0; unsafe { if WriteFile( handle, output_bytes.as_ptr(), output_bytes.len() as u32, &mut bytes_written, std::ptr::null_mut(), ) == 0 { return Err(std::io::Error::last_os_error()); } } Ok(()) } enum WindowsInput { Console(windows_sys::Win32::Foundation::HANDLE), File(windows_sys::Win32::Foundation::HANDLE), Reader(Box), } impl WindowsInput { fn handle(&self) -> Option { match self { WindowsInput::Console(handle) => Some(*handle), WindowsInput::File(handle) => Some(*handle), WindowsInput::Reader(_) => None, } } fn is_console(&self) -> bool { matches!(self, WindowsInput::Console(_)) } } enum WindowsOutput { Console(windows_sys::Win32::Foundation::HANDLE), File(windows_sys::Win32::Foundation::HANDLE), Writer(Box), } impl WindowsOutput { fn handle(&self) -> Option { match self { WindowsOutput::Console(handle) => Some(*handle), WindowsOutput::File(handle) => Some(*handle), WindowsOutput::Writer(_) => None, } } fn is_console(&self) -> bool { matches!(self, WindowsOutput::Console(_)) } } pub(crate) struct RawModeInput { input: WindowsInput, input_mode: u32, output: WindowsOutput, output_mode: u32, } impl Drop for RawModeInput { fn drop(&mut self) { let input_handle = self.input.handle(); if let Some(handle) = input_handle { if handle != INVALID_HANDLE_VALUE { if self.input.is_console() { unsafe { SetConsoleMode(handle, self.input_mode); } } unsafe { windows_sys::Win32::Foundation::CloseHandle(handle); } } } let output_handle = self.output.handle(); if let Some(handle) = output_handle { if output_handle != input_handle && handle != INVALID_HANDLE_VALUE { if self.output.is_console() { unsafe { SetConsoleMode(handle, self.output_mode); } } unsafe { windows_sys::Win32::Foundation::CloseHandle(handle); } } } } } impl RawPasswordInput for RawModeInput { fn new(config: Config) -> io::Result { let input = match config.input { InputTarget::FilePath(path) => { let input_handle = open_file_or_console(path.as_str())?; let is_console = is_interactive_terminal(input_handle); if is_console { WindowsInput::Console(input_handle) } else { WindowsInput::File(input_handle) } } InputTarget::Reader(reader) => WindowsInput::Reader(reader), }; let input_handle = input.handle(); let output = match config.output { OutputTarget::FilePath(path) => { let output_handle = open_file_or_console(path.as_str())?; let is_console = is_interactive_terminal(output_handle); if Some(output_handle) == input_handle { match input { WindowsInput::Console(input_handle) => WindowsOutput::Console(input_handle), WindowsInput::File(input_handle) => WindowsOutput::File(input_handle), _ => { unreachable!() } } } else if is_console { WindowsOutput::Console(output_handle) } else { WindowsOutput::File(output_handle) } } OutputTarget::Writer(writer) => WindowsOutput::Writer(Box::new(writer)), OutputTarget::Void => WindowsOutput::Writer(Box::new(Cursor::new(Vec::::new()))), }; let input_mode = if let (Some(handle), true) = (input.handle(), input.is_console()) { get_console_mode(handle)? } else { 0 }; let output_mode = if let (Some(handle), true) = (output.handle(), output.is_console()) { get_console_mode(handle)? } else { 0 }; Ok(RawModeInput { input, output, input_mode, output_mode, }) } fn needs_terminal_configuration(&self) -> bool { self.input.is_console() } fn apply_terminal_configuration(&mut self) -> io::Result<()> { if self.input.is_console() { if let Some(handle) = self.input.handle() { if unsafe { SetConsoleMode(handle, ENABLE_PROCESSED_INPUT) } == 0 { return Err(std::io::Error::last_os_error()); } } } Ok(()) } fn read_char(&mut self) -> io::Result { match self.input { WindowsInput::Console(handle) => read_char_from_console(handle), WindowsInput::File(handle) => read_char_from_file(handle), WindowsInput::Reader(ref mut reader) => read_char(reader), } } fn write_output(&mut self, output: &str) -> std::io::Result<()> { match self.output { WindowsOutput::Console(handle) => write_output_to_console(handle, output), WindowsOutput::File(handle) => write_output_to_file(handle, output), WindowsOutput::Writer(ref mut writer) => { writer.write_all(output.as_bytes())?; writer.flush() } } } fn send_signal_sigint(&mut self) -> io::Result<()> { if unsafe { GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0) } == 0 { return Err(std::io::Error::last_os_error()); } Ok(()) } } #[cfg(test)] mod tests { use crate::{ConfigBuilder, read_password_with_config}; use windows_sys::Win32::Foundation::ERROR_FILE_NOT_FOUND; #[test] fn test_read_password_with_config_errors_with_file_not_found() { let config = ConfigBuilder::new() .input_file_path("C:\\not-found.txt") .build(); // This should fail because it's not a Console (GetConsoleMode fails on regular files) // But, it proves that read_password_with_config is using our input path. let result = read_password_with_config(config); assert!(result.is_err()); let err = result.unwrap_err(); assert_eq!(err.raw_os_error(), Some(ERROR_FILE_NOT_FOUND as i32)); } } rpassword-7.5.4/tests/no-terminal.rs000064400000000000000000000041411046102023000156220ustar 00000000000000//! This test checks whether or not we can read from a reader when //! stdin is not a terminal. use std::io::Cursor; #[allow(deprecated)] use rpassword::read_password_from_bufread; #[cfg(all(target_family = "unix", not(target_family = "wasm")))] fn close_stdin() { unsafe { libc::close(libc::STDIN_FILENO); } } #[cfg(target_family = "windows")] fn close_stdin() { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Console::{GetStdHandle, STD_INPUT_HANDLE}; unsafe { CloseHandle(GetStdHandle(STD_INPUT_HANDLE)); } } #[cfg(target_family = "wasm")] fn close_stdin() { unimplemented!() } fn mock_input_crlf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\r\nAnother mocked response.\r\n"[..]) } fn mock_input_lf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\nAnother mocked response.\n"[..]) } #[test] #[allow(deprecated)] fn can_read_from_redirected_input_many_times() { close_stdin(); let mut reader_crlf = mock_input_crlf(); let response = crate::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "A mocked response."); let response = crate::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "Another mocked response."); let mut reader_lf = mock_input_lf(); let response = crate::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "A mocked response."); let response = crate::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "Another mocked response."); } #[test] #[allow(deprecated)] fn can_read_from_input_ctrl_u() { close_stdin(); let mut reader_ctrl_u = Cursor::new(&b"A mocked response.Another mocked response.\n"[..]); let response = crate::read_password_from_bufread(&mut reader_ctrl_u).unwrap(); assert_eq!(response, "Another mocked response."); let mut reader_ctrl_u_at_end = Cursor::new(&b"A mocked response.\n"[..]); let response = crate::read_password_from_bufread(&mut reader_ctrl_u_at_end).unwrap(); assert_eq!(response, ""); }