@cldmv/droidsock 2.0.2 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -38
- package/dist/api/connection.mjs +1 -1
- package/dist/api/device.mjs +1 -1
- package/index.cjs +12 -3
- package/package.json +7 -12
- package/types/dist/api/connection.d.mts.map +1 -1
- package/types/dist/api/device.d.mts.map +1 -1
- package/devcheck.mjs +0 -64
- package/types/devcheck.d.mts +0 -2
package/README.md
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cldmv/droidsock
|
|
2
2
|
|
|
3
3
|
<div align="center">
|
|
4
4
|
<img src="https://github.com/CLDMV/droidsock/raw/HEAD/images/droidsock-banner.jpg" alt="DroidSock Banner">
|
|
5
5
|
</div>
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
**DroidSock** is a complete, from-scratch implementation of the Android Debug Bridge (ADB) protocol in Node.js. This library provides full ADB functionality including device connection, RSA authentication, shell command execution, and file transfers - eliminating clicking sounds on Android TV devices!
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
It talks to devices directly over TCP, with no `adb` binary or ADB server in between, and composes its protocol layers into a single API tree with [`@cldmv/slothlet`](https://github.com/CLDMV/slothlet), so every connected device becomes its own persistent API leaf.
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
> _ADB over the wire, in pure Node.js - no adb binary required._
|
|
12
|
+
|
|
13
|
+
[![npm version]][npm_version_url] [![npm downloads]][npm_downloads_url] [![GitHub downloads]][github_downloads_url] [![Last commit]][last_commit_url] [![npm last update]][npm_last_update_url] [![coverage]][coverage_url]
|
|
12
14
|
|
|
13
15
|
> [!NOTE]
|
|
14
16
|
> **Current status:**
|
|
@@ -17,30 +19,26 @@ A complete, from-scratch implementation of the Android Debug Bridge (ADB) protoc
|
|
|
17
19
|
> - **File transfer**: `mkdir` / `remove` / `move` / `copy` / `chmod` / `diskUsage` / `find` / `stat` work today via shell commands. `list` prefers a binary-safe SYNC-based implementation with automatic shell fallback.
|
|
18
20
|
> - **Experimental**: `push` / `pull` / `pushV2` / `pullV2` / `listSync` / `listV2` / `statV2` (real ADB SYNC sub-protocol usage, both the legacy 32-bit and newer 64-bit variants), `device.reboot()`, `device.forward()` / `device.reverse()`, `device.install()` (both the classic push-then-install and modern streaming install paths), and `pairing.pair()` (Wi-Fi pairing) are all implemented - built from the ADB protocol spec and covered by unit tests (several exercised against real loopback TCP/TLS servers, not purely mocks) - but **none of them have been run against a real device yet**. See [#1](https://github.com/CLDMV/droidsock/issues/1).
|
|
19
21
|
|
|
22
|
+
[![Contributors]][contributors_url] [![Sponsor shinrai]][sponsor_url]
|
|
23
|
+
|
|
20
24
|
---
|
|
21
25
|
|
|
22
26
|
## ✨ What's New
|
|
23
27
|
|
|
24
|
-
### Latest: v2.
|
|
28
|
+
### Latest: v2.1.0 (October 2026)
|
|
25
29
|
|
|
26
|
-
-
|
|
27
|
-
- **
|
|
28
|
-
-
|
|
29
|
-
- **`device.reverse()`** (experimental) - completes port forwarding with the device → host direction.
|
|
30
|
-
- **`pairing.pair()`** (experimental) - Wi-Fi pairing (SPAKE2-over-Ed25519 + TLS 1.3) for Android 11+ wireless debugging.
|
|
31
|
-
- **Streaming APK install** (experimental) - `device.install()` now tries `exec:cmd`-based streaming install first, falling back to the classic push-then-install flow.
|
|
32
|
-
- **SYNC V2 (64-bit)** - `pushV2` / `pullV2` / `statV2` / `listV2` lift the legacy 32-bit size ceiling, with optional brotli compression.
|
|
33
|
-
- **Hardening** - closed a shell-injection gap in `devices.mjs`'s and `shell.mjs`'s convenience shortcuts, capped several unbounded device-controlled memory allocations in the SYNC V2 paths, and fixed a handful of mid-transfer disconnect/failure edge cases.
|
|
34
|
-
- [View full v2.0.0 Changelog](./docs/changelog/v2/v2.0.0.md)
|
|
30
|
+
- **Device lifecycle events and opt-in auto-reconnect** - each device emits `connecting`, `connected`, `disconnected`, `reconnecting`, `reconnected`, `error` and `gave-up`, and `device.connect(host, port, { autoReconnect })` redials after an unexpected drop with exponential backoff and jitter. An explicit `disconnect()` or `remove()` never triggers it, and a device that rejects authentication is not retried ([#75](https://github.com/CLDMV/droidsock/pull/75)).
|
|
31
|
+
- **Keepalive, heartbeat and a leak fix** - the `keepAlive` config now enables TCP keepalive, an optional `heartbeat` option probes the device with a trivial shell command to catch a hung `adbd`, and a failed handshake no longer leaves its socket open. `engines.node` rises to `>=22.15.0` to match `@cldmv/slothlet` 3.22 ([#74](https://github.com/CLDMV/droidsock/pull/74)).
|
|
32
|
+
- [View full v2.1.0 Changelog](https://github.com/CLDMV/droidsock/blob/master/docs/changelog/v2/v2.1.0.md)
|
|
35
33
|
|
|
36
34
|
### Recent Releases
|
|
37
35
|
|
|
38
|
-
- **
|
|
39
|
-
- **
|
|
40
|
-
- **
|
|
41
|
-
- **
|
|
36
|
+
- **v2.0.3** (October 2026) - `index.cjs` loads the ESM entry with a plain `require()` and fails clearly without `require(esm)`; `@cldmv/droidsock/devcheck` is no longer exported or published ([Changelog](https://github.com/CLDMV/droidsock/blob/master/docs/changelog/v2/v2.0.3.md))
|
|
37
|
+
- **v2.0.2** (October 2026) - Dev tooling only: shared CLDMV fix-headers config and a required PR check that never reports as skipped, no runtime change ([Changelog](https://github.com/CLDMV/droidsock/blob/master/docs/changelog/v2/v2.0.2.md))
|
|
38
|
+
- **v2.0.1** (October 2026) - No runtime change, but `engines.node` rose to `>=22.12.0` (from `>=20.19.0`) to match the vitest 5 toolchain; also syncs the v4 workflows with the v4.29.2 templates ([Changelog](https://github.com/CLDMV/droidsock/blob/master/docs/changelog/v2/v2.0.1.md))
|
|
39
|
+
- **v2.0.0** (September 2026) - Breaking: the `device` module splits into `device` and `devices`, device leaves persist across a disconnect, plus IPv6, `devices.get()`, and experimental `device.reverse()`, Wi-Fi pairing, streaming install and SYNC V2 ([Changelog](https://github.com/CLDMV/droidsock/blob/master/docs/changelog/v2/v2.0.0.md))
|
|
42
40
|
|
|
43
|
-
📚 **For complete version history and detailed release notes, see [docs/changelog/](
|
|
41
|
+
📚 **For complete version history and detailed release notes, see the [docs/changelog/](https://github.com/CLDMV/droidsock/tree/master/docs/changelog/) folder.**
|
|
44
42
|
|
|
45
43
|
---
|
|
46
44
|
|
|
@@ -55,16 +53,27 @@ A complete, from-scratch implementation of the Android Debug Bridge (ADB) protoc
|
|
|
55
53
|
- ✅ **Port Forwarding** (experimental): `adb forward`/`adb reverse`-equivalent TCP tunneling, both directions
|
|
56
54
|
- ✅ **APK Install** (experimental): `adb install`-equivalent local APK installation - classic push-then-install and modern streaming (`exec:cmd package install`) paths
|
|
57
55
|
- ✅ **Wi-Fi Pairing** (experimental): `adb pair`-equivalent PIN-based pairing (SPAKE2-over-Ed25519 + TLS 1.3) for Android 11+ wireless debugging
|
|
58
|
-
- ✅ **Device Discovery
|
|
56
|
+
- ✅ **Device Discovery** (experimental): `discover.subnet()` CIDR sweep and `discover.mdns()` for devices advertising wireless debugging, plus support for multiple devices via configuration
|
|
59
57
|
- ✅ **Error Handling**: Robust error handling and connection recovery
|
|
60
58
|
|
|
61
|
-
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## 📦 Installation
|
|
62
|
+
|
|
63
|
+
### Requirements
|
|
64
|
+
|
|
65
|
+
- **Node.js v22.15.0 or higher** (the package's `engines.node` floor)
|
|
66
|
+
- Both `import` and `require()` are supported. `require()` loads the ESM entry through Node's synchronous `require(esm)`, which every supported Node.js version (22.15+) provides; on older versions, load the package with `import()` instead.
|
|
67
|
+
|
|
68
|
+
### Install
|
|
62
69
|
|
|
63
70
|
```bash
|
|
64
71
|
npm install @cldmv/droidsock
|
|
65
72
|
```
|
|
66
73
|
|
|
67
|
-
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## 🚀 Quick Start
|
|
68
77
|
|
|
69
78
|
```javascript
|
|
70
79
|
import droidsock from "@cldmv/droidsock";
|
|
@@ -92,9 +101,13 @@ const logcat = device.logcat({
|
|
|
92
101
|
await device.disconnect();
|
|
93
102
|
```
|
|
94
103
|
|
|
95
|
-
|
|
104
|
+
CommonJS works the same way: `const droidsock = require("@cldmv/droidsock")` (also available as `createDroidSock`).
|
|
96
105
|
|
|
97
|
-
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## ⚙️ Device Configuration
|
|
109
|
+
|
|
110
|
+
The example scripts read device addresses from `references/devices.json`. The folder is git-ignored, so create the file yourself:
|
|
98
111
|
|
|
99
112
|
```json
|
|
100
113
|
{
|
|
@@ -114,13 +127,17 @@ Use the `references/devices.json` file to configure your devices:
|
|
|
114
127
|
}
|
|
115
128
|
```
|
|
116
129
|
|
|
117
|
-
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
## 📘 API Reference
|
|
118
133
|
|
|
119
134
|
`droidsock(options)` (also `createDroidSock`) creates the API instance; `api.device.connect(host, port, options)` connects to a device (IPv4 or IPv6) and returns its live leaf - also reachable afterward at `api.devices["<host>_<port>"]` (a `.` becomes `_`, a `:` becomes `__`) - exposing connection state, shell execution/streaming, file operations (`push` / `pull` / `list` / `stat`), reboot, port forwarding, and APK install. `api.device.disconnect(host, port)` tears down one device's connection without forgetting it - reconnect later with `connect()` on the same host:port, no need to re-supply options; `api.device.remove(host, port)` forgets it entirely. `api.devices.list()` / `disconnect()` (all) / `remove()` (all) / `get(idOrLeaf)` manage the set of known devices as a whole.
|
|
120
135
|
|
|
121
|
-
📚 **See [docs/API.md](
|
|
136
|
+
📚 **See [docs/API.md](https://github.com/CLDMV/droidsock/blob/master/docs/API.md) for the full method reference**, including every option and the experimental/scope caveats on `push` / `pull` / `list` / `forward` / `reverse` / `install`.
|
|
137
|
+
|
|
138
|
+
---
|
|
122
139
|
|
|
123
|
-
## Examples
|
|
140
|
+
## 💡 Examples
|
|
124
141
|
|
|
125
142
|
### Basic Usage
|
|
126
143
|
|
|
@@ -145,7 +162,9 @@ node examples/streaming-example.mjs top
|
|
|
145
162
|
node examples/streaming-example.mjs files
|
|
146
163
|
```
|
|
147
164
|
|
|
148
|
-
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
## 🏗️ Architecture
|
|
149
168
|
|
|
150
169
|
`src/droidsock.mjs` composes the layers below into a single api tree via [`@cldmv/slothlet`](https://github.com/CLDMV/slothlet):
|
|
151
170
|
|
|
@@ -162,9 +181,11 @@ node examples/streaming-example.mjs files
|
|
|
162
181
|
11. **Device / Devices Layers** (`src/api/device.mjs`, `src/api/devices.mjs`): High-level per-device API composing the layers above, split by single-target (`device.connect`/`disconnect`/`remove`) vs. collection-wide (`devices.list`/`disconnect`/`remove`/`get`) operations. Each device is a real, persistent slothlet leaf at `api.devices.<sanitized host_port>`, assigned there by `connect()` rather than held in a private module variable, so its methods keep working `self`/context access exactly like any other leaf - the leaf outlives any one connection, and only `remove()` unmounts it
|
|
163
182
|
12. **Config / Log Layers** (`src/api/config.mjs`, `src/api/log.mjs`): Shared configuration and logging
|
|
164
183
|
|
|
165
|
-
📚 **See [docs/PROTOCOL.md](
|
|
184
|
+
📚 **See [docs/PROTOCOL.md](https://github.com/CLDMV/droidsock/blob/master/docs/PROTOCOL.md) for wire-level protocol details** (packet structure, auth flow, SYNC sub-protocol framing, reboot/forward service usage).
|
|
166
185
|
|
|
167
|
-
|
|
186
|
+
---
|
|
187
|
+
|
|
188
|
+
## 🛠 Troubleshooting
|
|
168
189
|
|
|
169
190
|
### Connection Issues
|
|
170
191
|
|
|
@@ -185,28 +206,71 @@ node examples/streaming-example.mjs files
|
|
|
185
206
|
- "Stream not open": Ensure connection is established
|
|
186
207
|
- "File not found": Check paths and permissions
|
|
187
208
|
|
|
188
|
-
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
## 🧪 Development
|
|
189
212
|
|
|
190
213
|
The implementation is built directly from the public ADB protocol documentation (AOSP `SYNC.TXT` and the wire-protocol references), cross-checked against Google's own reference client (`google/python-adb`) where the public docs are ambiguous, and covered by a mocked Vitest suite. The core connection/shell/stream-multiplexing path has real device usage behind it; the newer SYNC-protocol and service additions (`push` / `pull` / `listSync` / `reboot` / `forward` / `install`) have not yet been run against a real device - see the status note at the top of this README and [#1](https://github.com/CLDMV/droidsock/issues/1).
|
|
191
214
|
|
|
192
|
-
|
|
215
|
+
---
|
|
216
|
+
|
|
217
|
+
## 📚 Documentation
|
|
193
218
|
|
|
194
|
-
|
|
219
|
+
- **[API Reference](https://github.com/CLDMV/droidsock/blob/master/docs/API.md)** - every method and option, with the experimental and scope caveats
|
|
220
|
+
- **[Protocol Details](https://github.com/CLDMV/droidsock/blob/master/docs/PROTOCOL.md)** - packet structure, auth flow, SYNC sub-protocol framing, reboot / forward service usage
|
|
221
|
+
- **[Changelog](https://github.com/CLDMV/droidsock/tree/master/docs/changelog/)** - per-version release notes
|
|
195
222
|
|
|
196
|
-
|
|
223
|
+
[![CodeFactor]][codefactor_url] [![OpenSSF Scorecard]][ossf_scorecard_url] [![npms.io score]][npms_url] [![npm unpacked size]][npm_size_url] [![Repo size]][repo_size_url]
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## 🤝 Contributing
|
|
197
228
|
|
|
198
229
|
This is a complete implementation of the ADB protocol. For improvements or bug fixes, please submit issues or pull requests.
|
|
199
230
|
|
|
231
|
+
[![Contributors]][contributors_url] [![Sponsor shinrai]][sponsor_url]
|
|
232
|
+
|
|
233
|
+
---
|
|
234
|
+
|
|
235
|
+
## 🔗 Links
|
|
236
|
+
|
|
237
|
+
- **npm**: [@cldmv/droidsock](https://www.npmjs.com/package/@cldmv/droidsock)
|
|
238
|
+
- **GitHub**: [CLDMV/droidsock](https://github.com/CLDMV/droidsock)
|
|
239
|
+
- **Issues**: [GitHub Issues](https://github.com/CLDMV/droidsock/issues)
|
|
240
|
+
- **Changelog**: [docs/changelog/](https://github.com/CLDMV/droidsock/tree/master/docs/changelog/)
|
|
241
|
+
|
|
242
|
+
---
|
|
243
|
+
|
|
244
|
+
## 📄 License
|
|
245
|
+
|
|
246
|
+
[![GitHub license]][github_license_url] [![npm license]][npm_license_url]
|
|
247
|
+
|
|
248
|
+
Apache-2.0 - see [LICENSE](https://github.com/CLDMV/droidsock/blob/HEAD/LICENSE) for details.
|
|
249
|
+
|
|
200
250
|
[npm version]: https://img.shields.io/npm/v/%40cldmv%2Fdroidsock.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
|
|
201
251
|
[npm_version_url]: https://www.npmjs.com/package/@cldmv/droidsock
|
|
202
|
-
[npm downloads]: https://img.shields.io/npm/dm/%40cldmv%2Fdroidsock.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
|
|
203
|
-
[npm_downloads_url]: https://www.npmjs.com/package/@cldmv/droidsock
|
|
204
|
-
[github downloads]: https://img.shields.io/github/downloads/CLDMV/droidsock/total?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
|
|
205
|
-
[github_downloads_url]: https://github.com/CLDMV/droidsock/releases
|
|
206
252
|
[last commit]: https://img.shields.io/github/last-commit/CLDMV/droidsock?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
|
|
207
253
|
[last_commit_url]: https://github.com/CLDMV/droidsock/commits
|
|
208
254
|
[npm last update]: https://img.shields.io/npm/last-update/%40cldmv%2Fdroidsock?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
|
|
209
255
|
[npm_last_update_url]: https://www.npmjs.com/package/@cldmv/droidsock
|
|
256
|
+
[codefactor]: https://img.shields.io/codefactor/grade/github/CLDMV/droidsock?style=for-the-badge&logo=codefactor&logoColor=white&labelColor=F44A6A
|
|
257
|
+
[codefactor_url]: https://www.codefactor.io/repository/github/cldmv/droidsock
|
|
258
|
+
[openssf scorecard]: https://img.shields.io/ossf-scorecard/github.com/CLDMV/droidsock?style=for-the-badge&label=OpenSSF%20Scorecard
|
|
259
|
+
[ossf_scorecard_url]: https://scorecard.dev/viewer/?uri=github.com/CLDMV/droidsock
|
|
260
|
+
[npms.io score]: https://img.shields.io/npms-io/final-score/%40cldmv%2Fdroidsock?style=for-the-badge&logo=npms&logoColor=white&labelColor=0B5D57
|
|
261
|
+
[npms_url]: https://npms.io/search?q=%40cldmv%2Fdroidsock
|
|
262
|
+
[npm downloads]: https://img.shields.io/npm/dm/%40cldmv%2Fdroidsock.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
|
|
263
|
+
[npm_downloads_url]: https://www.npmjs.com/package/@cldmv/droidsock
|
|
264
|
+
[github downloads]: https://img.shields.io/github/downloads/CLDMV/droidsock/total?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
|
|
265
|
+
[github_downloads_url]: https://github.com/CLDMV/droidsock/releases
|
|
266
|
+
[npm unpacked size]: https://img.shields.io/npm/unpacked-size/%40cldmv%2Fdroidsock.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
|
|
267
|
+
[npm_size_url]: https://www.npmjs.com/package/@cldmv/droidsock
|
|
268
|
+
[repo size]: https://img.shields.io/github/repo-size/CLDMV/droidsock?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
|
|
269
|
+
[repo_size_url]: https://github.com/CLDMV/droidsock
|
|
270
|
+
[github license]: https://img.shields.io/github/license/CLDMV/droidsock.svg?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
|
|
271
|
+
[github_license_url]: https://github.com/CLDMV/droidsock/blob/HEAD/LICENSE
|
|
272
|
+
[npm license]: https://img.shields.io/npm/l/%40cldmv%2Fdroidsock.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
|
|
273
|
+
[npm_license_url]: https://www.npmjs.com/package/@cldmv/droidsock
|
|
210
274
|
[coverage]: https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2FCLDMV%2Fdroidsock%2Fbadges%2Fcoverage.json&style=for-the-badge&logo=vitest&logoColor=white
|
|
211
275
|
[coverage_url]: https://github.com/CLDMV/droidsock/blob/badges/coverage.json
|
|
212
276
|
[contributors]: https://img.shields.io/github/contributors/CLDMV/droidsock.svg?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
|
package/dist/api/connection.mjs
CHANGED
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{self}from"@cldmv/slothlet/runtime";import net from"node:net";const ADB_PROTOCOL_VERSION=16777216;const ADB_MAX_PAYLOAD=4096;const MSG_CNXN=1314410051;const MSG_AUTH=1213486401;const MSG_OKAY=1497451343;const SUPPORTED_FEATURES=["shell_v2","cmd","stat_v2","ls_v2","sendrecv_v2","sendrecv_v2_brotli"];async function create(options){const{host,port,privateKey,adbPublicKey}=options;const socket=new net.Socket;const connection={socket,host,port,authorized:false,connected:false,onUnhandledPacket:null,disconnect:()=>{if(socket&&!socket.destroyed){self.log.debug(`Disconnecting from ${host}:${port}`);socket.destroy()}connection.connected=false;connection.authorized=false}};return new Promise((resolve,reject)=>{const timeout=setTimeout(()=>{socket.destroy();reject(new Error("Connection timeout"))},1e4);socket.connect(port,host,async()=>{try{self.log.debug(`Connected to ${host}:${port}, sending CNXN message...`);const systemIdentity=`device::features=${SUPPORTED_FEATURES.join(",")}`;const cnxnPayload=Buffer.from(systemIdentity);await sendMessage(socket,MSG_CNXN,ADB_PROTOCOL_VERSION,ADB_MAX_PAYLOAD,cnxnPayload);self.log.debug(`${self.config.get("debugArrowSent")} CNXN message sent, waiting for AUTH response...`);const authMessage=await receiveMessage(socket);self.log.debug(`${self.config.get("debugArrowReceived")} Received AUTH message, command:`,authMessage.command.toString(16));if(authMessage.command!==MSG_AUTH){throw new Error(`Expected AUTH message (0x${MSG_AUTH.toString(16)}), got 0x${authMessage.command.toString(16)}`)}self.log.debug(`${self.config.get("debugArrowReceived")} AUTH message received, token length:`,authMessage.data.length);const token=authMessage.data;const signature=await self.auth.sign(token,privateKey);await sendMessage(socket,MSG_AUTH,2,0,signature);const pubKeyBuffer=Buffer.from(adbPublicKey);await sendMessage(socket,MSG_AUTH,3,0,pubKeyBuffer);const okayMessage=await receiveMessage(socket);self.log.debug(`${self.config.get("debugArrowReceived")} After auth, received command:`,okayMessage.command.toString(16));self.log.debug("Expected CNXN:",MSG_CNXN.toString(16),"or OKAY:",MSG_OKAY.toString(16));if(okayMessage.command===MSG_CNXN){const cnxnPayload2=okayMessage.data.toString().replace(/\0/g,"");self.log.debug(`${self.config.get("debugArrowReceived")} Device sent CNXN response - authentication successful!`);self.log.debug(`${self.config.get("debugArrowReceived")} CNXN payload:`,cnxnPayload2);const featuresMatch=cnxnPayload2.match(/features=([^;]+)/);connection.deviceFeatures=featuresMatch?featuresMatch[1].split(","):[];connection.authorized=true;connection.connected=true;self.log.debug("Authentication successful!")}else if(okayMessage.command===MSG_OKAY){self.log.debug(`${self.config.get("debugArrowReceived")} Device sent OKAY response - authentication successful!`);connection.authorized=true;connection.connected=true}else{throw new Error(`Authentication failed - expected CNXN (${MSG_CNXN.toString(16)}) or OKAY (${MSG_OKAY.toString(16)}), got ${okayMessage.command.toString(16)}`)}clearTimeout(timeout);socket.on("data",data=>{if(connection.onUnhandledPacket){connection.onUnhandledPacket(data)}});resolve(connection)}catch(error){clearTimeout(timeout);self.log.debug("Connection error:",error.message);reject(error)}});socket.on("error",error=>{clearTimeout(timeout);self.log.debug("Socket error:",error.message);reject(error)})})}async function sendMessage(socket,command,arg0,arg1,data=Buffer.alloc(0)){const header=Buffer.alloc(24);let offset=0;header.writeUInt32LE(command,offset);offset+=4;header.writeUInt32LE(arg0,offset);offset+=4;header.writeUInt32LE(arg1,offset);offset+=4;header.writeUInt32LE(data.length,offset);offset+=4;header.writeUInt32LE(checksum(data),offset);offset+=4;header.writeUInt32LE((command^4294967295)>>>0,offset);socket.write(header);if(data.length>0){socket.write(data)}}function receiveMessage(socket){return new Promise((resolve,reject)=>{let headerReceived=false;let expectedDataLength=0;let receivedHeader=null;let receivedData=Buffer.alloc(0);const onData=chunk=>{if(!headerReceived){if(chunk.length>=24){receivedHeader=chunk.slice(0,24);self.log.debug("Header bytes:",Array.from(receivedHeader).map(b=>b.toString(16).padStart(2,"0")).join(" "));try{expectedDataLength=receivedHeader.readUInt32LE(12);self.log.debug("Raw data length from header:",expectedDataLength)}catch(readError){reject(new Error(`Failed to read data length from header: ${readError.message}`));return}if(isNaN(expectedDataLength)||expectedDataLength<0||expectedDataLength>1024*1024){reject(new Error(`Invalid data length: ${expectedDataLength} (header: ${receivedHeader.toString("hex")})`));return}headerReceived=true;if(chunk.length>24){receivedData=Buffer.concat([receivedData,chunk.slice(24)])}}}else{receivedData=Buffer.concat([receivedData,chunk])}if(headerReceived&&receivedData.length>=expectedDataLength){socket.removeListener("data",onData);try{const command=receivedHeader.readUInt32LE(0);const arg0=receivedHeader.readUInt32LE(4);const arg1=receivedHeader.readUInt32LE(8);const dataLength=receivedHeader.readUInt32LE(12);const headerChecksum=receivedHeader.readUInt32LE(16);const magic=receivedHeader.readUInt32LE(20);self.log.debug("Parsed header - command:",command.toString(16),"arg0:",arg0,"arg1:",arg1,"length:",dataLength,"checksum:",headerChecksum,"magic:",magic.toString(16));const expectedMagic=(command^4294967295)>>>0;if(magic!==expectedMagic){self.log.debug("Magic mismatch - expected:",expectedMagic.toString(16),"got:",magic.toString(16))}const data=receivedData.slice(0,expectedDataLength);if(data.length>0){const calculatedChecksum=checksum(data);self.log.debug("Data checksum - expected:",headerChecksum,"calculated:",calculatedChecksum)}resolve({command,arg0,arg1,data})}catch(parseError){reject(new Error(`Failed to parse message header: ${parseError.message}`))}}};socket.on("data",onData);socket.on("error",reject)})}function checksum(data){let sum=0;for(let i=0;i<data.length;i++){sum=sum+data[i]>>>0}return sum}export{create};
|
|
17
|
+
import{self}from"@cldmv/slothlet/runtime";import net from"node:net";const ADB_PROTOCOL_VERSION=16777216;const ADB_MAX_PAYLOAD=4096;const MSG_CNXN=1314410051;const MSG_AUTH=1213486401;const MSG_OKAY=1497451343;const SUPPORTED_FEATURES=["shell_v2","cmd","stat_v2","ls_v2","sendrecv_v2","sendrecv_v2_brotli"];async function create(options){const{host,port,privateKey,adbPublicKey}=options;const socket=new net.Socket;const connection={socket,host,port,authorized:false,connected:false,onUnhandledPacket:null,disconnect:()=>{if(socket&&!socket.destroyed){self.log.debug(`Disconnecting from ${host}:${port}`);socket.destroy()}connection.connected=false;connection.authorized=false}};return new Promise((resolve,reject)=>{const timeout=setTimeout(()=>{socket.destroy();reject(new Error("Connection timeout"))},1e4);socket.connect(port,host,async()=>{try{self.log.debug(`Connected to ${host}:${port}, sending CNXN message...`);const systemIdentity=`device::features=${SUPPORTED_FEATURES.join(",")}`;const cnxnPayload=Buffer.from(systemIdentity);await sendMessage(socket,MSG_CNXN,ADB_PROTOCOL_VERSION,ADB_MAX_PAYLOAD,cnxnPayload);self.log.debug(`${self.config.get("debugArrowSent")} CNXN message sent, waiting for AUTH response...`);const authMessage=await receiveMessage(socket);self.log.debug(`${self.config.get("debugArrowReceived")} Received AUTH message, command:`,authMessage.command.toString(16));if(authMessage.command!==MSG_AUTH){throw new Error(`Expected AUTH message (0x${MSG_AUTH.toString(16)}), got 0x${authMessage.command.toString(16)}`)}self.log.debug(`${self.config.get("debugArrowReceived")} AUTH message received, token length:`,authMessage.data.length);const token=authMessage.data;const signature=await self.auth.sign(token,privateKey);await sendMessage(socket,MSG_AUTH,2,0,signature);const pubKeyBuffer=Buffer.from(adbPublicKey);await sendMessage(socket,MSG_AUTH,3,0,pubKeyBuffer);const okayMessage=await receiveMessage(socket);self.log.debug(`${self.config.get("debugArrowReceived")} After auth, received command:`,okayMessage.command.toString(16));self.log.debug("Expected CNXN:",MSG_CNXN.toString(16),"or OKAY:",MSG_OKAY.toString(16));if(okayMessage.command===MSG_CNXN){const cnxnPayload2=okayMessage.data.toString().replace(/\0/g,"");self.log.debug(`${self.config.get("debugArrowReceived")} Device sent CNXN response - authentication successful!`);self.log.debug(`${self.config.get("debugArrowReceived")} CNXN payload:`,cnxnPayload2);const featuresMatch=cnxnPayload2.match(/features=([^;]+)/);connection.deviceFeatures=featuresMatch?featuresMatch[1].split(","):[];connection.authorized=true;connection.connected=true;self.log.debug("Authentication successful!")}else if(okayMessage.command===MSG_OKAY){self.log.debug(`${self.config.get("debugArrowReceived")} Device sent OKAY response - authentication successful!`);connection.authorized=true;connection.connected=true}else{throw new Error(`Authentication failed - expected CNXN (${MSG_CNXN.toString(16)}) or OKAY (${MSG_OKAY.toString(16)}), got ${okayMessage.command.toString(16)}`)}clearTimeout(timeout);socket.on("data",data=>{if(connection.onUnhandledPacket){connection.onUnhandledPacket(data)}});resolve(connection)}catch(error){clearTimeout(timeout);self.log.debug("Connection error:",error.message);socket.destroy();reject(error)}});socket.on("error",error=>{clearTimeout(timeout);self.log.debug("Socket error:",error.message);reject(error)})})}async function sendMessage(socket,command,arg0,arg1,data=Buffer.alloc(0)){const header=Buffer.alloc(24);let offset=0;header.writeUInt32LE(command,offset);offset+=4;header.writeUInt32LE(arg0,offset);offset+=4;header.writeUInt32LE(arg1,offset);offset+=4;header.writeUInt32LE(data.length,offset);offset+=4;header.writeUInt32LE(checksum(data),offset);offset+=4;header.writeUInt32LE((command^4294967295)>>>0,offset);socket.write(header);if(data.length>0){socket.write(data)}}function receiveMessage(socket){return new Promise((resolve,reject)=>{let headerReceived=false;let expectedDataLength=0;let receivedHeader=null;let receivedData=Buffer.alloc(0);const onData=chunk=>{if(!headerReceived){if(chunk.length>=24){receivedHeader=chunk.slice(0,24);self.log.debug("Header bytes:",Array.from(receivedHeader).map(b=>b.toString(16).padStart(2,"0")).join(" "));try{expectedDataLength=receivedHeader.readUInt32LE(12);self.log.debug("Raw data length from header:",expectedDataLength)}catch(readError){reject(new Error(`Failed to read data length from header: ${readError.message}`));return}if(isNaN(expectedDataLength)||expectedDataLength<0||expectedDataLength>1024*1024){reject(new Error(`Invalid data length: ${expectedDataLength} (header: ${receivedHeader.toString("hex")})`));return}headerReceived=true;if(chunk.length>24){receivedData=Buffer.concat([receivedData,chunk.slice(24)])}}}else{receivedData=Buffer.concat([receivedData,chunk])}if(headerReceived&&receivedData.length>=expectedDataLength){socket.removeListener("data",onData);try{const command=receivedHeader.readUInt32LE(0);const arg0=receivedHeader.readUInt32LE(4);const arg1=receivedHeader.readUInt32LE(8);const dataLength=receivedHeader.readUInt32LE(12);const headerChecksum=receivedHeader.readUInt32LE(16);const magic=receivedHeader.readUInt32LE(20);self.log.debug("Parsed header - command:",command.toString(16),"arg0:",arg0,"arg1:",arg1,"length:",dataLength,"checksum:",headerChecksum,"magic:",magic.toString(16));const expectedMagic=(command^4294967295)>>>0;if(magic!==expectedMagic){self.log.debug("Magic mismatch - expected:",expectedMagic.toString(16),"got:",magic.toString(16))}const data=receivedData.slice(0,expectedDataLength);if(data.length>0){const calculatedChecksum=checksum(data);self.log.debug("Data checksum - expected:",headerChecksum,"calculated:",calculatedChecksum)}resolve({command,arg0,arg1,data})}catch(parseError){reject(new Error(`Failed to parse message header: ${parseError.message}`))}}};socket.on("data",onData);socket.on("error",reject)})}function checksum(data){let sum=0;for(let i=0;i<data.length;i++){sum=sum+data[i]>>>0}return sum}export{create};
|
package/dist/api/device.mjs
CHANGED
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{self}from"@cldmv/slothlet/runtime";import{quoteShellArg,sanitizeKey}from"./utils.mjs";async function openSession(host,port,options){const keys=await self.auth.getKeys(options.keyDir);const connection=await self.connection.create({host,port,publicKey:keys.publicKey,privateKey:keys.privateKey,adbPublicKey:keys.adbPublicKey});const streamManager=await self.stream.create(connection.socket);connection.onUnhandledPacket=packet=>streamManager.handlePacket(packet);return{connection,streamManager}}function buildDeviceLeaf(host,port,deviceId,deviceKey,options){const session={connection:null,streamManager:null};function assertReady(){if(!leaf.isConnected()){throw new Error("Device not connected")}if(!session.connection.authorized){throw new Error("Device not authorized. Please accept authorization dialog.")}}const leaf={host,port,deviceId,options,connection:null,streamManager:null,isConnected:()=>Boolean(session.connection&&session.connection.connected&&session.connection.socket&&!session.connection.socket.destroyed),disconnect:()=>{if(session.connection)session.connection.disconnect()},reconnect:async(reconnectOptions={})=>{leaf.options={...leaf.options,...reconnectOptions};if(leaf.isConnected())return self.devices[deviceKey];const{connection,streamManager}=await openSession(host,port,leaf.options);session.connection=connection;session.streamManager=streamManager;self.devices[deviceKey].connection=connection;self.devices[deviceKey].streamManager=streamManager;return self.devices[deviceKey]},remove:async()=>{leaf.disconnect();await self.slothlet.api.remove(`devices.${deviceKey}`).catch(()=>{})},shell:async(command,shellOptions={})=>{assertReady();return await self.shell.execute(session.connection.socket,session.streamManager,command,{...shellOptions,deviceFeatures:session.connection.deviceFeatures||[]})},startStreamingShell:(command,shellOptions={})=>{assertReady();return self.shell.startStreaming(session.connection.socket,session.streamManager,command,shellOptions)},startInteractiveShell:(command,shellOptions={})=>{assertReady();return self.shell.startInteractive(session.connection.socket,session.streamManager,command,shellOptions)},push:async(localPath,remotePath,transferOptions={})=>{assertReady();return await self.files.push(session.connection.socket,session.streamManager,localPath,remotePath,transferOptions)},pull:async(remotePath,localPath,transferOptions={})=>{assertReady();return await self.files.pull(session.connection.socket,session.streamManager,remotePath,localPath,transferOptions)},pushV2:async(localPath,remotePath,transferOptions={})=>{assertReady();return await self.files.pushV2(session.connection.socket,session.streamManager,localPath,remotePath,transferOptions)},pullV2:async(remotePath,localPath,transferOptions={})=>{assertReady();return await self.files.pullV2(session.connection.socket,session.streamManager,remotePath,localPath,transferOptions)},list:async remotePath=>{assertReady();return await self.files.list(session.connection.socket,session.streamManager,remotePath)},stat:async remotePath=>{assertReady();return await self.files.stat(session.connection.socket,session.streamManager,remotePath)},listV2:async remotePath=>{assertReady();return await self.files.listV2(session.connection.socket,session.streamManager,remotePath)},statV2:async remotePath=>{assertReady();return await self.files.statV2(session.connection.socket,session.streamManager,remotePath)},reboot:async(mode="")=>{assertReady();return await self.reboot.execute(session.connection.socket,session.streamManager,mode)},forward:async(devicePort,forwardOptions={})=>{assertReady();return await self.forward.start(session.connection.socket,session.streamManager,devicePort,forwardOptions)},reverse:async(devicePort,hostPort,reverseOptions={})=>{assertReady();return await self.reverse.start(session.connection.socket,session.streamManager,devicePort,hostPort,reverseOptions)},install:async(localPath,installOptions={})=>{assertReady();if((session.connection.deviceFeatures||[]).includes("cmd")){try{return await self.install.streaming(session.connection.socket,session.streamManager,localPath,installOptions)}catch(streamingError){try{return await self.install.classic(session.connection.socket,session.streamManager,localPath,installOptions)}catch(classicError){throw new Error(`Streaming install failed (${streamingError.message}), and the classic fallback also failed: ${classicError.message}`,{cause:classicError})}}}return await self.install.classic(session.connection.socket,session.streamManager,localPath,installOptions)},ls:(path=".")=>leaf.shell(`ls -la ${quoteShellArg(path)}`),pwd:()=>leaf.shell("pwd"),getprop:(prop=null)=>leaf.shell(prop?`getprop ${quoteShellArg(prop)}`:"getprop"),getModel:()=>leaf.shell("getprop ro.product.model"),getAndroidVersion:()=>leaf.shell("getprop ro.build.version.release"),getBattery:()=>leaf.shell("dumpsys battery"),screenshot:(filename="/sdcard/screenshot.png")=>leaf.shell(`screencap -p ${quoteShellArg(filename)}`),logcat:(logOptions={})=>leaf.startStreamingShell("logcat",logOptions),top:(topOptions={})=>leaf.startStreamingShell("top -m 10",topOptions),keypress:key=>leaf.shell(`input keyevent ${quoteShellArg(key)}`),launchApp:(packageName,activity="")=>{const target=activity?`${packageName}/${activity}`:packageName;return leaf.shell(`am start -n ${quoteShellArg(target)}`)},rebootBootloader:()=>leaf.reboot("bootloader"),rebootRecovery:()=>leaf.reboot("recovery"),rebootSideload:()=>leaf.reboot("sideload")};return leaf}async function connect(host,port=5555,options={}){const deviceId=`${host}:${port}`;const deviceKey=sanitizeKey(deviceId);const existing=self.devices&&self.devices[deviceKey];if(existing){return await existing.reconnect(options)}const leaf=buildDeviceLeaf(host,port,deviceId,deviceKey,options);await self.slothlet.api.add(`devices.${deviceKey}`,leaf,{moduleID:`device:${deviceId}`});await self.devices[deviceKey].reconnect(options);return self.devices[deviceKey]}function disconnect(host,port=5555){const deviceKey=sanitizeKey(`${host}:${port}`);const entry=self.devices&&self.devices[deviceKey];if(!entry){return false}entry.disconnect();return true}async function remove(host,port=5555){const deviceKey=sanitizeKey(`${host}:${port}`);const entry=self.devices&&self.devices[deviceKey];if(!entry){return false}await entry.remove();return true}export{connect,disconnect,remove};
|
|
17
|
+
import{EventEmitter}from"node:events";import{self}from"@cldmv/slothlet/runtime";import{quoteShellArg,sanitizeKey}from"./utils.mjs";const DEFAULT_RECONNECT_POLICY={maxAttempts:Infinity,maxDelay:3e4,factor:2,jitter:.2};function resolveReconnectPolicy(autoReconnect){if(!autoReconnect)return null;const custom=typeof autoReconnect==="object"?autoReconnect:{};return{...DEFAULT_RECONNECT_POLICY,initialDelay:self.config.get("retryDelay",1e3),...custom}}function backoffDelay(policy,attempt){const base=Math.min(policy.maxDelay,policy.initialDelay*policy.factor**(attempt-1));const spread=base*policy.jitter;return Math.max(0,Math.round(base-spread+Math.random()*spread*2))}function resolveHeartbeatPolicy(heartbeat){if(!heartbeat)return null;return{interval:15e3,timeout:5e3,...typeof heartbeat==="object"?heartbeat:{}}}function isFatalConnectError(error){return/^Authentication failed/.test(error?.message||"")}async function openSession(host,port,options){const keys=await self.auth.getKeys(options.keyDir);const connection=await self.connection.create({host,port,publicKey:keys.publicKey,privateKey:keys.privateKey,adbPublicKey:keys.adbPublicKey});const streamManager=await self.stream.create(connection.socket);connection.onUnhandledPacket=packet=>streamManager.handlePacket(packet);return{connection,streamManager}}function buildDeviceLeaf(host,port,deviceId,deviceKey,options){const session={connection:null,streamManager:null};const emitter=new EventEmitter;const closedByUs=new WeakSet;const closeReasons=new WeakMap;let reconnectTimer=null;let heartbeatTimer=null;let inflight=null;function emit(event,detail={}){if(!self.config.get("emitEvents",true))return;if(event==="error"&&emitter.listenerCount("error")===0)return;try{emitter.emit(event,{deviceId,host,port,...detail})}catch(listenerError){self.log.error(`Listener for "${event}" on ${deviceId} threw:`,listenerError)}}function stopHeartbeat(){if(heartbeatTimer)clearInterval(heartbeatTimer);heartbeatTimer=null}function startHeartbeat(connection){stopHeartbeat();const policy=resolveHeartbeatPolicy(leaf.options.heartbeat);if(!policy)return;let probing=false;heartbeatTimer=setInterval(async()=>{if(probing||session.connection!==connection||!leaf.isConnected())return;probing=true;try{await self.shell.execute(connection.socket,session.streamManager,"echo",{timeout:policy.timeout,deviceFeatures:connection.deviceFeatures||[]})}catch(error){if(session.connection===connection){closeReasons.set(connection,"heartbeat");emit("error",{error});connection.disconnect()}}finally{probing=false}},policy.interval)}function cancelReconnect(){if(reconnectTimer)clearTimeout(reconnectTimer);reconnectTimer=null}function establish(phase="connect"){if(inflight)return inflight;inflight=(async()=>{emit("connecting",{phase});const{connection,streamManager}=await openSession(host,port,leaf.options);session.connection=connection;session.streamManager=streamManager;self.devices[deviceKey].connection=connection;self.devices[deviceKey].streamManager=streamManager;watchConnection(connection);startHeartbeat(connection);emit("connected",{phase})})().finally(()=>{inflight=null});return inflight}function watchConnection(connection){const socket=connection.socket;if(self.config.get("keepAlive",true))socket.setKeepAlive(true,self.config.get("keepAliveInterval",3e4));socket.once("close",hadError=>{if(session.connection!==connection)return;connection.connected=false;stopHeartbeat();const intentional=closedByUs.has(connection);emit("disconnected",{intentional,hadError,reason:closeReasons.get(connection)??(intentional?"requested":"closed")});if(!intentional)scheduleReconnect(1)})}function scheduleReconnect(attempt,lastError){const policy=resolveReconnectPolicy(leaf.options.autoReconnect);if(!policy)return;if(attempt>policy.maxAttempts){emit("gave-up",{reason:"max-attempts",attempts:attempt-1,error:lastError});return}const delay=backoffDelay(policy,attempt);emit("reconnecting",{attempt,delay,error:lastError});reconnectTimer=setTimeout(async()=>{reconnectTimer=null;try{await establish("reconnect");emit("reconnected",{attempt})}catch(error){emit("error",{error,attempt});if(isFatalConnectError(error))emit("gave-up",{reason:"auth",attempts:attempt,error});else scheduleReconnect(attempt+1,error)}},delay)}function assertReady(){if(!leaf.isConnected()){throw new Error("Device not connected")}if(!session.connection.authorized){throw new Error("Device not authorized. Please accept authorization dialog.")}}const leaf={host,port,deviceId,options,connection:null,streamManager:null,isConnected:()=>Boolean(session.connection&&session.connection.connected&&session.connection.socket&&!session.connection.socket.destroyed),disconnect:()=>{cancelReconnect();if(session.connection){closedByUs.add(session.connection);session.connection.disconnect()}},on:(event,listener)=>{emitter.on(event,listener);return self.devices[deviceKey]},once:(event,listener)=>{emitter.once(event,listener);return self.devices[deviceKey]},off:(event,listener)=>{emitter.off(event,listener);return self.devices[deviceKey]},reconnect:async(reconnectOptions={})=>{leaf.options={...leaf.options,...reconnectOptions};if(leaf.isConnected())return self.devices[deviceKey];cancelReconnect();await establish();return self.devices[deviceKey]},remove:async()=>{leaf.disconnect();await self.slothlet.api.remove(`devices.${deviceKey}`).catch(()=>{})},shell:async(command,shellOptions={})=>{assertReady();return await self.shell.execute(session.connection.socket,session.streamManager,command,{...shellOptions,deviceFeatures:session.connection.deviceFeatures||[]})},startStreamingShell:(command,shellOptions={})=>{assertReady();return self.shell.startStreaming(session.connection.socket,session.streamManager,command,shellOptions)},startInteractiveShell:(command,shellOptions={})=>{assertReady();return self.shell.startInteractive(session.connection.socket,session.streamManager,command,shellOptions)},push:async(localPath,remotePath,transferOptions={})=>{assertReady();return await self.files.push(session.connection.socket,session.streamManager,localPath,remotePath,transferOptions)},pull:async(remotePath,localPath,transferOptions={})=>{assertReady();return await self.files.pull(session.connection.socket,session.streamManager,remotePath,localPath,transferOptions)},pushV2:async(localPath,remotePath,transferOptions={})=>{assertReady();return await self.files.pushV2(session.connection.socket,session.streamManager,localPath,remotePath,transferOptions)},pullV2:async(remotePath,localPath,transferOptions={})=>{assertReady();return await self.files.pullV2(session.connection.socket,session.streamManager,remotePath,localPath,transferOptions)},list:async remotePath=>{assertReady();return await self.files.list(session.connection.socket,session.streamManager,remotePath)},stat:async remotePath=>{assertReady();return await self.files.stat(session.connection.socket,session.streamManager,remotePath)},listV2:async remotePath=>{assertReady();return await self.files.listV2(session.connection.socket,session.streamManager,remotePath)},statV2:async remotePath=>{assertReady();return await self.files.statV2(session.connection.socket,session.streamManager,remotePath)},reboot:async(mode="")=>{assertReady();return await self.reboot.execute(session.connection.socket,session.streamManager,mode)},forward:async(devicePort,forwardOptions={})=>{assertReady();return await self.forward.start(session.connection.socket,session.streamManager,devicePort,forwardOptions)},reverse:async(devicePort,hostPort,reverseOptions={})=>{assertReady();return await self.reverse.start(session.connection.socket,session.streamManager,devicePort,hostPort,reverseOptions)},install:async(localPath,installOptions={})=>{assertReady();if((session.connection.deviceFeatures||[]).includes("cmd")){try{return await self.install.streaming(session.connection.socket,session.streamManager,localPath,installOptions)}catch(streamingError){try{return await self.install.classic(session.connection.socket,session.streamManager,localPath,installOptions)}catch(classicError){throw new Error(`Streaming install failed (${streamingError.message}), and the classic fallback also failed: ${classicError.message}`,{cause:classicError})}}}return await self.install.classic(session.connection.socket,session.streamManager,localPath,installOptions)},ls:(path=".")=>leaf.shell(`ls -la ${quoteShellArg(path)}`),pwd:()=>leaf.shell("pwd"),getprop:(prop=null)=>leaf.shell(prop?`getprop ${quoteShellArg(prop)}`:"getprop"),getModel:()=>leaf.shell("getprop ro.product.model"),getAndroidVersion:()=>leaf.shell("getprop ro.build.version.release"),getBattery:()=>leaf.shell("dumpsys battery"),screenshot:(filename="/sdcard/screenshot.png")=>leaf.shell(`screencap -p ${quoteShellArg(filename)}`),logcat:(logOptions={})=>leaf.startStreamingShell("logcat",logOptions),top:(topOptions={})=>leaf.startStreamingShell("top -m 10",topOptions),keypress:key=>leaf.shell(`input keyevent ${quoteShellArg(key)}`),launchApp:(packageName,activity="")=>{const target=activity?`${packageName}/${activity}`:packageName;return leaf.shell(`am start -n ${quoteShellArg(target)}`)},rebootBootloader:()=>leaf.reboot("bootloader"),rebootRecovery:()=>leaf.reboot("recovery"),rebootSideload:()=>leaf.reboot("sideload")};return leaf}async function connect(host,port=5555,options={}){const deviceId=`${host}:${port}`;const deviceKey=sanitizeKey(deviceId);const existing=self.devices&&self.devices[deviceKey];if(existing){return await existing.reconnect(options)}const leaf=buildDeviceLeaf(host,port,deviceId,deviceKey,options);await self.slothlet.api.add(`devices.${deviceKey}`,leaf,{moduleID:`device:${deviceId}`});await self.devices[deviceKey].reconnect(options);return self.devices[deviceKey]}function disconnect(host,port=5555){const deviceKey=sanitizeKey(`${host}:${port}`);const entry=self.devices&&self.devices[deviceKey];if(!entry){return false}entry.disconnect();return true}async function remove(host,port=5555){const deviceKey=sanitizeKey(`${host}:${port}`);const entry=self.devices&&self.devices[deviceKey];if(!entry){return false}await entry.remove();return true}export{connect,disconnect,remove};
|
package/index.cjs
CHANGED
|
@@ -21,11 +21,20 @@
|
|
|
21
21
|
*
|
|
22
22
|
* @module droidsock
|
|
23
23
|
*/
|
|
24
|
+
"use strict";
|
|
24
25
|
|
|
25
|
-
|
|
26
|
-
|
|
26
|
+
// index.cjs is a thin wrapper: it loads index.mjs through Node's synchronous require(esm).
|
|
27
|
+
// Node.js versions without require(esm) would fail with a bare ERR_REQUIRE_ESM, so fail
|
|
28
|
+
// early with a message that says what to do instead.
|
|
29
|
+
if (!process.features?.require_module) {
|
|
30
|
+
const error = new Error(
|
|
31
|
+
`@cldmv/droidsock: require() needs Node.js ^20.19.0 or >=22.12.0 (this is ${process.version}). On older Node.js, load the package with import() instead.`
|
|
32
|
+
);
|
|
33
|
+
error.code = "ERR_REQUIRE_ESM";
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
27
36
|
|
|
28
|
-
const { default: droidsock } =
|
|
37
|
+
const { default: droidsock } = require("./index.mjs");
|
|
29
38
|
|
|
30
39
|
// Export main function - the quick path, also callable with options
|
|
31
40
|
module.exports = droidsock; // Default export
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cldmv/droidsock",
|
|
3
|
-
"version": "2.0
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "Complete Node.js implementation of the Android Debug Bridge (ADB) protocol",
|
|
5
5
|
"main": "./index.cjs",
|
|
6
6
|
"module": "./index.mjs",
|
|
@@ -11,10 +11,6 @@
|
|
|
11
11
|
"import": "./index.mjs",
|
|
12
12
|
"require": "./index.cjs"
|
|
13
13
|
},
|
|
14
|
-
"./devcheck": {
|
|
15
|
-
"types": "./types/devcheck.d.mts",
|
|
16
|
-
"import": "./devcheck.mjs"
|
|
17
|
-
},
|
|
18
14
|
"./main": {
|
|
19
15
|
"droidsock-dev": {
|
|
20
16
|
"types": "./types/src/droidsock.d.mts",
|
|
@@ -26,16 +22,17 @@
|
|
|
26
22
|
},
|
|
27
23
|
"type": "module",
|
|
28
24
|
"engines": {
|
|
29
|
-
"node": ">=22.
|
|
25
|
+
"node": ">=22.15.0"
|
|
30
26
|
},
|
|
31
27
|
"scripts": {
|
|
32
28
|
"build": "node build.mjs",
|
|
33
29
|
"build:types": "tsc --project .configs/tsconfig.dts.jsonc",
|
|
34
30
|
"build:ci": "npm run build && npm run build:types && npm run test:types",
|
|
35
|
-
"test": "node tests/run-vitest.mjs",
|
|
31
|
+
"test": "node tests/run-vitest.mjs && npm run test:cjs",
|
|
32
|
+
"test:cjs": "CI=1 node --test tests/cjs/entry.test.cjs",
|
|
36
33
|
"test:watch": "vitest --config .configs/vitest.config.mjs",
|
|
37
34
|
"test:types": "tsc --noEmit --project .configs/tsconfig.dts.jsonc",
|
|
38
|
-
"coverage": "node tests/run-vitest.mjs --coverage-quiet",
|
|
35
|
+
"coverage": "node tests/run-vitest.mjs --coverage-quiet && npm run test:cjs",
|
|
39
36
|
"ci:coverage": "npm run coverage",
|
|
40
37
|
"lint": "eslint --config .configs/eslint.config.mjs .",
|
|
41
38
|
"lint:fix": "eslint --config .configs/eslint.config.mjs . --fix",
|
|
@@ -94,20 +91,18 @@
|
|
|
94
91
|
"files": [
|
|
95
92
|
"index.mjs",
|
|
96
93
|
"index.cjs",
|
|
97
|
-
"devcheck.mjs",
|
|
98
94
|
"README.md",
|
|
99
95
|
"LICENSE",
|
|
100
96
|
"types/dist/",
|
|
101
97
|
"types/index.d.mts",
|
|
102
98
|
"types/index.d.mts.map",
|
|
103
|
-
"types/devcheck.d.mts",
|
|
104
99
|
"dist/"
|
|
105
100
|
],
|
|
106
101
|
"sideEffects": false,
|
|
107
102
|
"devDependencies": {
|
|
108
|
-
"@cldmv/configs": "^1.2.
|
|
103
|
+
"@cldmv/configs": "^1.2.4",
|
|
109
104
|
"@cldmv/eslint-plugin-jsonv": "^1.0.3",
|
|
110
|
-
"@cldmv/fix-headers": "^2.
|
|
105
|
+
"@cldmv/fix-headers": "^2.2.0",
|
|
111
106
|
"@cldmv/jsonv": "^1.0.2",
|
|
112
107
|
"@cldmv/prettier-plugin-jsonv": "^1.0.1",
|
|
113
108
|
"@cldmv/vitest-runner": "^1.2.0",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connection.d.mts","sourceRoot":"","sources":["../../../dist/api/connection.mjs"],"names":[],"mappings":"AAgBkT,
|
|
1
|
+
{"version":3,"file":"connection.d.mts","sourceRoot":"","sources":["../../../dist/api/connection.mjs"],"names":[],"mappings":"AAgBkT,mDAAyiG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"device.d.mts","sourceRoot":"","sources":["../../../dist/api/device.mjs"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"device.d.mts","sourceRoot":"","sources":["../../../dist/api/device.mjs"],"names":[],"mappings":"AAgB2iS,8EAA8c;AAAA,8DAA4L;AAAA,mEAAgM"}
|
package/devcheck.mjs
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
* @Project: @cldmv/droidsock
|
|
4
|
-
* @Filename: /devcheck.mjs
|
|
5
|
-
* @Date: 2025-11-08T22:18:57-08:00 (1762669137)
|
|
6
|
-
* @Author: Nate Corcoran <CLDMV>
|
|
7
|
-
* @Email: <Shinrai@users.noreply.github.com>
|
|
8
|
-
* -----
|
|
9
|
-
* @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
|
|
10
|
-
* @Last modified time: 2026-10-02T15:29:45-07:00 (1790980185)
|
|
11
|
-
* -----
|
|
12
|
-
* @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
|
|
13
|
-
*
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import { existsSync } from "node:fs";
|
|
17
|
-
import { fileURLToPath } from "node:url";
|
|
18
|
-
import path from "node:path";
|
|
19
|
-
|
|
20
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
21
|
-
const __dirname = path.dirname(__filename);
|
|
22
|
-
const srcPath = path.join(__dirname, "src");
|
|
23
|
-
// const distPath = path.join(__dirname, "dist");
|
|
24
|
-
|
|
25
|
-
// Detect if we're running in a CI environment
|
|
26
|
-
const isCI = !!(
|
|
27
|
-
process.env.CI || // Generic CI flag
|
|
28
|
-
process.env.GITHUB_ACTIONS || // GitHub Actions
|
|
29
|
-
process.env.TRAVIS || // Travis CI
|
|
30
|
-
process.env.CIRCLECI || // CircleCI
|
|
31
|
-
process.env.GITLAB_CI || // GitLab CI
|
|
32
|
-
process.env.BUILDKITE || // Buildkite
|
|
33
|
-
process.env.JENKINS_URL || // Jenkins
|
|
34
|
-
process.env.TF_BUILD // Azure DevOps
|
|
35
|
-
);
|
|
36
|
-
|
|
37
|
-
if (existsSync(srcPath) && !isCI) {
|
|
38
|
-
// if (existsSync(srcPath) && !existsSync(distPath)) {
|
|
39
|
-
// NODE_ENV plays no part in Node's conditional-exports resolution - only the
|
|
40
|
-
// "--conditions=droidsock-dev" condition (via NODE_OPTIONS) actually routes
|
|
41
|
-
// exports["./main"] to src/ instead of dist/. NODE_ENV=development alone
|
|
42
|
-
// would previously pass this check while still resolving to dist/.
|
|
43
|
-
const hasNodeOptions = process.env.NODE_OPTIONS?.includes("--conditions=droidsock-dev");
|
|
44
|
-
|
|
45
|
-
if (!hasNodeOptions) {
|
|
46
|
-
console.error("❌ Development environment not properly configured!");
|
|
47
|
-
console.error("📁 Source folder detected but NODE_OPTIONS is not set for development.");
|
|
48
|
-
console.error("");
|
|
49
|
-
console.error("🔧 To fix this, run one of these commands:");
|
|
50
|
-
console.error(" Windows (cmd):");
|
|
51
|
-
console.error(" set NODE_OPTIONS=--conditions=droidsock-dev");
|
|
52
|
-
console.error("");
|
|
53
|
-
console.error(" Windows (PowerShell):");
|
|
54
|
-
console.error(" $env:NODE_OPTIONS='--conditions=droidsock-dev'");
|
|
55
|
-
console.error("");
|
|
56
|
-
console.error(" Unix/Linux/macOS:");
|
|
57
|
-
console.error(" export NODE_OPTIONS=--conditions=droidsock-dev");
|
|
58
|
-
console.error("");
|
|
59
|
-
console.error("💡 This ensures this module loads from src/ instead of dist/ for development.");
|
|
60
|
-
console.error(" (NODE_ENV is not checked here - it has no effect on this resolution.)");
|
|
61
|
-
console.error("🚀 CI environments automatically skip this check.");
|
|
62
|
-
process.exit(1);
|
|
63
|
-
}
|
|
64
|
-
}
|
package/types/devcheck.d.mts
DELETED