mirror of
https://github.com/itsKaynine/electron-injector.git
synced 2025-12-16 15:37:42 +01:00
initial commit
This commit is contained in:
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
/target
|
||||||
|
/tmp
|
||||||
1500
Cargo.lock
generated
Normal file
1500
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
30
Cargo.toml
Normal file
30
Cargo.toml
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
[package]
|
||||||
|
name = "electron-injector"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
description = """
|
||||||
|
electron-injector is an open source command-line tool written in Rust that
|
||||||
|
enables you to inject JavaScript code into Electron apps at runtime. It is
|
||||||
|
inspired by the Python project electron-inject and offers similar functionality.
|
||||||
|
"""
|
||||||
|
keywords = ["electron", "js", "inject", "debug"]
|
||||||
|
categories = ["command-line-utilities", "debugging"]
|
||||||
|
repository = "https://github.com/itsKaynine/electron-injector"
|
||||||
|
documentation = "https://github.com/itsKaynine/electron-injector"
|
||||||
|
authors = ["Punnawut Khowkittipaiboon <me@itskaynine.com>"]
|
||||||
|
readme = "README.md"
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
autotests = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1.0"
|
||||||
|
clap = { version = "4.1.8", features = ["derive"] }
|
||||||
|
log = "0.4"
|
||||||
|
portpicker = "0.1.1"
|
||||||
|
pretty_env_logger = "0.4"
|
||||||
|
reqwest = { version = "0.11", features = ["blocking", "json"] }
|
||||||
|
rust-embed = "6.6.0"
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
tungstenite = "0.18.0"
|
||||||
|
url = "2.3"
|
||||||
201
LICENSE-APACHE-2.0
Normal file
201
LICENSE-APACHE-2.0
Normal file
@@ -0,0 +1,201 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright 2023 Punnawut Khowkittipaiboon
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
21
LICENSE-MIT
Normal file
21
LICENSE-MIT
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2023 Punnawut Khowkittipaiboon
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
53
README.md
Normal file
53
README.md
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
# electron-injector
|
||||||
|
|
||||||
|
`electron-injector` is an open source command-line tool written in Rust that enables you to inject JavaScript code into Electron apps at runtime. It is inspired by the Python project [electron-inject](https://github.com/tintinweb/electron-inject/) and offers similar functionality.
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
You can download pre-compiled binaries from the [releases](https://github.com/itsKaynine/electron-injector/releases) page and add the binary to your `PATH` environment variable.
|
||||||
|
|
||||||
|
Alternatively, you can install electron-injector using Cargo, Rust's package manager.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ cargo install electron-injector
|
||||||
|
```
|
||||||
|
|
||||||
|
### Usage
|
||||||
|
|
||||||
|
To use electron-injector, simply specify the path to the Electron app and the JavaScript file that you want to inject.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ electron-injector --script=/path/to/script.js /path/to/electron/app
|
||||||
|
```
|
||||||
|
|
||||||
|
### Options
|
||||||
|
|
||||||
|
```
|
||||||
|
-a, --arg <ARG> Additional arg for the electron app
|
||||||
|
-s, --script <SCRIPT> Path to the javascript file to be injected
|
||||||
|
--host <HOST> The remote debugging host [default: 127.0.0.1]
|
||||||
|
-p, --port <PORT> The remote debugging port [default: 8315]
|
||||||
|
-t, --timeout <TIMEOUT> Timeout in ms for injecting scripts [default: 10000]
|
||||||
|
-d, --delay <DELAY> Delay in ms to wait after spawning the process [default: 10000]
|
||||||
|
--prelude Enable prelude script
|
||||||
|
-h, --help Print help
|
||||||
|
-V, --version Print version
|
||||||
|
```
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
We welcome contributions from the community. To contribute to `electron-injector`, please follow these steps:
|
||||||
|
|
||||||
|
### Fork the repository
|
||||||
|
|
||||||
|
1. Create a new branch for your changes
|
||||||
|
2. Make your changes and commit them
|
||||||
|
3. Push your changes to your forked repository
|
||||||
|
4. Submit a pull request
|
||||||
|
5. Please ensure that your code adheres to the Rust [coding style guidelines](https://www.rust-lang.org/policies/code-of-conduct#coding-style) and is properly formatted using [rustfmt](https://github.com/rust-lang/rustfmt).
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
electron-injector is dual licensed under the [MIT License](https://opensource.org/licenses/MIT) and [Apache-2.0 License](https://opensource.org/licenses/Apache-2.0). See the LICENSE-MIT and LICENSE-APACHE-2.0 files for more information.
|
||||||
1
assets/js/prelude.js
Normal file
1
assets/js/prelude.js
Normal file
@@ -0,0 +1 @@
|
|||||||
|
// NOTE: This will be empty for now
|
||||||
5
src/assets.rs
Normal file
5
src/assets.rs
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
use rust_embed::RustEmbed;
|
||||||
|
|
||||||
|
#[derive(RustEmbed)]
|
||||||
|
#[folder = "assets/js/"]
|
||||||
|
pub struct JS;
|
||||||
62
src/config.rs
Normal file
62
src/config.rs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
use std::ops::RangeInclusive;
|
||||||
|
|
||||||
|
use clap::Parser;
|
||||||
|
|
||||||
|
const PORT_RANGE: RangeInclusive<usize> = 1..=65535;
|
||||||
|
|
||||||
|
fn validate_port(s: &str) -> Result<u16, String> {
|
||||||
|
let port: usize = s
|
||||||
|
.parse()
|
||||||
|
.map_err(|_| format!("`{s}` isn't a port number"))?;
|
||||||
|
if PORT_RANGE.contains(&port) {
|
||||||
|
Ok(port as u16)
|
||||||
|
} else {
|
||||||
|
Err(format!(
|
||||||
|
"port not in range {}-{}",
|
||||||
|
PORT_RANGE.start(),
|
||||||
|
PORT_RANGE.end()
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Parser)]
|
||||||
|
#[command(author, version, about, long_about = None)]
|
||||||
|
pub struct Config {
|
||||||
|
/// Path to the electron app
|
||||||
|
#[arg()]
|
||||||
|
pub app: String,
|
||||||
|
|
||||||
|
/// Additional arg for the electron app
|
||||||
|
#[arg(short, long)]
|
||||||
|
pub arg: Vec<String>,
|
||||||
|
|
||||||
|
/// Path to the javascript file to be injected
|
||||||
|
#[arg(short, long)]
|
||||||
|
pub script: Vec<String>,
|
||||||
|
|
||||||
|
/// The remote debugging host
|
||||||
|
#[arg(long, default_value_t = String::from("127.0.0.1"))]
|
||||||
|
pub host: String,
|
||||||
|
|
||||||
|
/// The remote debugging port
|
||||||
|
#[arg(short, long, default_value_t = 8315, value_parser = validate_port)]
|
||||||
|
pub port: u16,
|
||||||
|
|
||||||
|
/// Timeout in ms for injecting scripts
|
||||||
|
#[arg(short, long, default_value_t = 10_000)]
|
||||||
|
pub timeout: u64,
|
||||||
|
|
||||||
|
/// Delay in ms to wait after spawning the process
|
||||||
|
#[arg(short, long, default_value_t = 10_000)]
|
||||||
|
pub delay: u64,
|
||||||
|
|
||||||
|
/// Enable prelude script
|
||||||
|
#[arg(long)]
|
||||||
|
pub prelude: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
pub fn parse_auto() -> Config {
|
||||||
|
Config::parse()
|
||||||
|
}
|
||||||
|
}
|
||||||
271
src/injector.rs
Normal file
271
src/injector.rs
Normal file
@@ -0,0 +1,271 @@
|
|||||||
|
use std::process::{Child, Command};
|
||||||
|
use std::{fs, thread, time};
|
||||||
|
|
||||||
|
use anyhow::{bail, Result};
|
||||||
|
use log::{debug, info, warn};
|
||||||
|
use portpicker;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use crate::assets;
|
||||||
|
use crate::config::Config;
|
||||||
|
use crate::protocol::{DevtoolPage, EvaluateResponse};
|
||||||
|
use crate::websocket::WebSocket;
|
||||||
|
|
||||||
|
struct UserScript {
|
||||||
|
file_path: String,
|
||||||
|
content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Injector {
|
||||||
|
config: Config,
|
||||||
|
port: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Injector {
|
||||||
|
pub(crate) const INJECT_LOOP_SLEEP_MS: u64 = 1000;
|
||||||
|
pub(crate) const WAIT_DEBUGGING_PORT_TIMEOUT_MS: u64 = 30_000;
|
||||||
|
|
||||||
|
fn get_available_port(config: &Config) -> u16 {
|
||||||
|
if portpicker::is_free_tcp(config.port) {
|
||||||
|
info!("Using port: {}", config.port);
|
||||||
|
return config.port;
|
||||||
|
}
|
||||||
|
|
||||||
|
info!(
|
||||||
|
"Port {} is not available, finding another port",
|
||||||
|
config.port
|
||||||
|
);
|
||||||
|
|
||||||
|
let port = portpicker::pick_unused_port().expect("Port should be available");
|
||||||
|
info!("Found available port: {}", port);
|
||||||
|
|
||||||
|
port
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new() -> Self {
|
||||||
|
// Parse CLI args
|
||||||
|
let config = Config::parse_auto();
|
||||||
|
|
||||||
|
// Get port
|
||||||
|
let port = Injector::get_available_port(&config);
|
||||||
|
|
||||||
|
Injector { config, port }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(&self) -> Result<()> {
|
||||||
|
info!("Running injector");
|
||||||
|
debug!("{:#?}", self.config);
|
||||||
|
|
||||||
|
// Spawn child process
|
||||||
|
_ = self.spawn_process()?;
|
||||||
|
|
||||||
|
// Prepare prelude script
|
||||||
|
let prelude_script = self.get_prelude_script().unwrap_or(String::new());
|
||||||
|
|
||||||
|
// Prepare user scripts
|
||||||
|
let user_scripts = self.get_user_scripts();
|
||||||
|
|
||||||
|
// Create timeout duration
|
||||||
|
let timeout_duration = time::Duration::from_millis(self.config.timeout);
|
||||||
|
|
||||||
|
// Declare a vec to store found page ids
|
||||||
|
let mut found_page_ids: Vec<String> = Vec::new();
|
||||||
|
|
||||||
|
// Inject loop
|
||||||
|
let start_time = time::Instant::now();
|
||||||
|
loop {
|
||||||
|
// Refresh devtool pages
|
||||||
|
let devtool_pages = self
|
||||||
|
.get_devtool_pages()
|
||||||
|
.expect("Should be able to get devtool pages");
|
||||||
|
|
||||||
|
debug!("{:#?}", devtool_pages);
|
||||||
|
|
||||||
|
// Loop through pages
|
||||||
|
for page in devtool_pages {
|
||||||
|
if found_page_ids.contains(&page.id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create WebSocket
|
||||||
|
let mut ws = WebSocket::connect(&page.web_socket_debugger_url)
|
||||||
|
.expect("To connect to websocket");
|
||||||
|
|
||||||
|
// Inject prelude
|
||||||
|
if self.config.prelude {
|
||||||
|
info!("Injecting prelude script (id: {})", page.id);
|
||||||
|
_ = self
|
||||||
|
.evaluate(&mut ws, &prelude_script)
|
||||||
|
.expect("Should be able to evaluate JS");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inject scripts
|
||||||
|
for user_script in user_scripts.iter() {
|
||||||
|
// Inject using evaluate
|
||||||
|
info!("Injecting script: {}", user_script.file_path);
|
||||||
|
_ = self
|
||||||
|
.evaluate(&mut ws, &user_script.content)
|
||||||
|
.expect("Should be able to evaluate JS");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save page id
|
||||||
|
found_page_ids.push(page.id.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check devtool pages again
|
||||||
|
let updated_devtool_pages = self
|
||||||
|
.get_devtool_pages()
|
||||||
|
.expect("Should be able to get devtool pages");
|
||||||
|
|
||||||
|
// Stop if already found all pages
|
||||||
|
if found_page_ids.len() == updated_devtool_pages.len() {
|
||||||
|
info!("Stopping injection loop");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Timed out
|
||||||
|
if start_time.elapsed() >= timeout_duration {
|
||||||
|
bail!("Injection loop timed out");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sleep before next loop iteration
|
||||||
|
thread::sleep(time::Duration::from_millis(Self::INJECT_LOOP_SLEEP_MS));
|
||||||
|
}
|
||||||
|
|
||||||
|
info!("Injection success");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_devtool_pages(&self) -> Result<Vec<DevtoolPage>, reqwest::Error> {
|
||||||
|
let url = format!("http://{}:{}/json/list", &self.config.host, &self.port);
|
||||||
|
|
||||||
|
let client = reqwest::blocking::Client::new();
|
||||||
|
let response = client.get(url).send()?.error_for_status()?;
|
||||||
|
|
||||||
|
let pages_response = response.json::<Vec<DevtoolPage>>()?;
|
||||||
|
Ok(pages_response)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_prelude_script(&self) -> Option<String> {
|
||||||
|
// No need to load if not enabled anyways
|
||||||
|
if !self.config.prelude {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load from embedded file
|
||||||
|
let file = assets::JS::get("prelude.js").unwrap();
|
||||||
|
let script =
|
||||||
|
std::str::from_utf8(file.data.as_ref()).expect("Script should be a valid UTF-8 file");
|
||||||
|
|
||||||
|
Some(String::from(script))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_user_scripts(&self) -> Vec<UserScript> {
|
||||||
|
let scripts: Vec<UserScript> = self
|
||||||
|
.config
|
||||||
|
.script
|
||||||
|
.iter()
|
||||||
|
.map(|s| {
|
||||||
|
let content =
|
||||||
|
fs::read_to_string(s).expect("Should have been able to read the file");
|
||||||
|
|
||||||
|
UserScript {
|
||||||
|
file_path: s.to_string(),
|
||||||
|
content,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
return scripts;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_process(&self) -> Result<Child> {
|
||||||
|
// Prepare args
|
||||||
|
let mut args = vec![format!("--remote-debugging-port={}", &self.port)];
|
||||||
|
args.extend(self.config.arg.iter().map(|a| a.clone()));
|
||||||
|
|
||||||
|
// Spawn child process
|
||||||
|
debug!(
|
||||||
|
"Spawning electron app: {} (args: {:#?})",
|
||||||
|
&self.config.app, args
|
||||||
|
);
|
||||||
|
let child = Command::new(&self.config.app).args(args).spawn()?;
|
||||||
|
|
||||||
|
// Wait for process
|
||||||
|
info!("Waiting for {}ms", self.config.delay);
|
||||||
|
thread::sleep(time::Duration::from_millis(self.config.delay));
|
||||||
|
|
||||||
|
// Create timeout duration
|
||||||
|
let timeout_duration = time::Duration::from_millis(Self::WAIT_DEBUGGING_PORT_TIMEOUT_MS);
|
||||||
|
|
||||||
|
// Wait until remote debugging port is available
|
||||||
|
info!("Waiting for remote debugging port");
|
||||||
|
let start_time = time::Instant::now();
|
||||||
|
loop {
|
||||||
|
// Connected
|
||||||
|
if self.get_devtool_pages().is_ok() {
|
||||||
|
info!("Connected to remote debugging port");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Timed out
|
||||||
|
if start_time.elapsed() >= timeout_duration {
|
||||||
|
bail!("Unable to connect to remote debugging port");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(child)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn evaluate(&self, ws: &mut WebSocket, expression: &str) -> Result<()> {
|
||||||
|
// Create payload
|
||||||
|
// https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#method-evaluate
|
||||||
|
let payload = json!({
|
||||||
|
"id": 1,
|
||||||
|
"method": "Runtime.evaluate",
|
||||||
|
"params": {
|
||||||
|
"expression": expression,
|
||||||
|
"objectGroup": "inject",
|
||||||
|
"includeCommandLineAPI": true,
|
||||||
|
"silent": true,
|
||||||
|
"userGesture": true,
|
||||||
|
"awaitPromise": true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Serialize payload to JSON
|
||||||
|
let payload_json = serde_json::to_string(&payload)?;
|
||||||
|
|
||||||
|
// Send message and get the result
|
||||||
|
let result_msg = ws.send_and_receive(&payload_json)?;
|
||||||
|
debug!("[Runtime.evaluate] Raw message: {:#?}", result_msg);
|
||||||
|
|
||||||
|
// Ignore if not a text
|
||||||
|
if !result_msg.is_text() {
|
||||||
|
warn!(
|
||||||
|
"[Runtime.evaluate] Unexpected result from WebSocket: {:#?}",
|
||||||
|
result_msg
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert message to text
|
||||||
|
let result_json = result_msg.to_text()?;
|
||||||
|
|
||||||
|
// Parse response
|
||||||
|
let response: EvaluateResponse = serde_json::from_str(result_json)?;
|
||||||
|
|
||||||
|
debug!("[Runtime.evaluate] Parsed response: {:#?}", response);
|
||||||
|
|
||||||
|
// Handle exception
|
||||||
|
if let Some(_) = response.result.exception_details {
|
||||||
|
warn!(
|
||||||
|
"[Runtime.evaluate] Caught exception while evaluating script: {:#?}",
|
||||||
|
response
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
5
src/lib.rs
Normal file
5
src/lib.rs
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
pub mod assets;
|
||||||
|
pub mod config;
|
||||||
|
pub mod injector;
|
||||||
|
mod protocol;
|
||||||
|
mod websocket;
|
||||||
10
src/main.rs
Normal file
10
src/main.rs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
use electron_injector::injector::Injector;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// Setup logging
|
||||||
|
pretty_env_logger::init();
|
||||||
|
|
||||||
|
// Run the injector
|
||||||
|
let injector = Injector::new();
|
||||||
|
injector.run().unwrap();
|
||||||
|
}
|
||||||
36
src/protocol.rs
Normal file
36
src/protocol.rs
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct DevtoolPage {
|
||||||
|
#[serde(rename = "description")]
|
||||||
|
pub description: String,
|
||||||
|
#[serde(rename = "devtoolsFrontendUrl")]
|
||||||
|
pub devtools_frontend_url: String,
|
||||||
|
#[serde(rename = "id")]
|
||||||
|
pub id: String,
|
||||||
|
#[serde(rename = "title")]
|
||||||
|
pub title: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub r#type: String,
|
||||||
|
#[serde(rename = "url")]
|
||||||
|
pub url: String,
|
||||||
|
#[serde(rename = "webSocketDebuggerUrl")]
|
||||||
|
pub web_socket_debugger_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct EvaluateResponse {
|
||||||
|
#[serde(rename = "id")]
|
||||||
|
pub id: i32,
|
||||||
|
#[serde(rename = "result")]
|
||||||
|
pub result: EvaluateResult,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct EvaluateResult {
|
||||||
|
#[serde(rename = "result")]
|
||||||
|
pub result: Value,
|
||||||
|
#[serde(rename = "exceptionDetails")]
|
||||||
|
pub exception_details: Option<Value>,
|
||||||
|
}
|
||||||
54
src/websocket.rs
Normal file
54
src/websocket.rs
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
use std::net::TcpStream;
|
||||||
|
|
||||||
|
use log::{debug, info};
|
||||||
|
use tungstenite::{stream::MaybeTlsStream, Message};
|
||||||
|
|
||||||
|
pub struct WebSocket {
|
||||||
|
address: String,
|
||||||
|
socket: tungstenite::WebSocket<MaybeTlsStream<TcpStream>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WebSocket {
|
||||||
|
pub fn connect(address: &str) -> Result<Self, tungstenite::Error> {
|
||||||
|
let url = url::Url::parse(&address).expect("Should be a valid address");
|
||||||
|
|
||||||
|
let (socket, response) = tungstenite::connect(url)?;
|
||||||
|
info!("WebSocket connected (status: {})", response.status());
|
||||||
|
|
||||||
|
debug!("Response headers: {:#?}", response.headers());
|
||||||
|
|
||||||
|
Ok(WebSocket {
|
||||||
|
address: String::from(address),
|
||||||
|
socket,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send(&mut self, msg: &str) -> Result<(), tungstenite::Error> {
|
||||||
|
self.socket
|
||||||
|
.write_message(Message::Text(String::from(msg)))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn receive(&mut self) -> Result<Message, tungstenite::Error> {
|
||||||
|
let msg = self.socket.read_message()?;
|
||||||
|
|
||||||
|
Ok(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_and_receive(&mut self, msg: &str) -> Result<Message, tungstenite::Error> {
|
||||||
|
self.send(msg)?;
|
||||||
|
self.receive()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn close(&mut self) -> Result<(), tungstenite::Error> {
|
||||||
|
self.socket.close(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for WebSocket {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
debug!("Closing WebSocket (address: {:?})", self.address);
|
||||||
|
_ = self.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user