@cldmv/droidsock 2.1.0 → 2.2.1

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.
Files changed (98) hide show
  1. package/README.md +42 -25
  2. package/dist/api/auth.mjs +2 -17
  3. package/dist/api/config.mjs +2 -17
  4. package/dist/api/connection.mjs +2 -17
  5. package/dist/api/device.mjs +2 -17
  6. package/dist/api/devices.mjs +2 -17
  7. package/dist/api/discover.mjs +2 -17
  8. package/dist/api/files.mjs +2 -17
  9. package/dist/api/forward.mjs +2 -17
  10. package/dist/api/install.mjs +2 -17
  11. package/dist/api/log.mjs +2 -17
  12. package/dist/api/pairing.mjs +2 -17
  13. package/dist/api/reboot.mjs +2 -17
  14. package/dist/api/reverse.mjs +2 -17
  15. package/dist/api/shell.mjs +2 -17
  16. package/dist/api/stream.mjs +2 -17
  17. package/dist/api/utils.mjs +5 -17
  18. package/dist/droidsock.mjs +2 -17
  19. package/dist/index.cjs +50 -0
  20. package/dist/index.mjs +2 -0
  21. package/dist/main.mjs +2 -0
  22. package/package.json +61 -44
  23. package/types/src/api/auth.d.mts +34 -0
  24. package/types/src/api/auth.d.mts.map +1 -0
  25. package/types/src/api/config.d.mts +50 -0
  26. package/types/src/api/config.d.mts.map +1 -0
  27. package/types/src/api/connection.d.mts +16 -0
  28. package/types/src/api/connection.d.mts.map +1 -0
  29. package/types/src/api/device.d.mts +41 -0
  30. package/types/src/api/device.d.mts.map +1 -0
  31. package/types/src/api/devices.d.mts +41 -0
  32. package/types/src/api/devices.d.mts.map +1 -0
  33. package/types/src/api/discover.d.mts +65 -0
  34. package/types/src/api/discover.d.mts.map +1 -0
  35. package/types/src/api/files.d.mts +228 -0
  36. package/types/src/api/files.d.mts.map +1 -0
  37. package/types/src/api/forward.d.mts +27 -0
  38. package/types/src/api/forward.d.mts.map +1 -0
  39. package/types/src/api/install.d.mts +54 -0
  40. package/types/src/api/install.d.mts.map +1 -0
  41. package/types/src/api/log.d.mts +37 -0
  42. package/types/src/api/log.d.mts.map +1 -0
  43. package/types/src/api/pairing.d.mts +30 -0
  44. package/types/src/api/pairing.d.mts.map +1 -0
  45. package/types/src/api/reboot.d.mts +33 -0
  46. package/types/src/api/reboot.d.mts.map +1 -0
  47. package/types/src/api/reverse.d.mts +26 -0
  48. package/types/src/api/reverse.d.mts.map +1 -0
  49. package/types/src/api/shell.d.mts +63 -0
  50. package/types/src/api/shell.d.mts.map +1 -0
  51. package/types/src/api/stream.d.mts +7 -0
  52. package/types/src/api/stream.d.mts.map +1 -0
  53. package/types/src/api/utils.d.mts +161 -0
  54. package/types/src/api/utils.d.mts.map +1 -0
  55. package/types/src/droidsock.d.mts +14 -0
  56. package/types/src/droidsock.d.mts.map +1 -0
  57. package/types/src/index.d.mts +2 -0
  58. package/types/src/index.d.mts.map +1 -0
  59. package/types/src/main.d.mts +3 -0
  60. package/types/src/main.d.mts.map +1 -0
  61. package/index.cjs +0 -46
  62. package/index.mjs +0 -44
  63. package/types/dist/api/auth.d.mts +0 -14
  64. package/types/dist/api/auth.d.mts.map +0 -1
  65. package/types/dist/api/config.d.mts +0 -52
  66. package/types/dist/api/config.d.mts.map +0 -1
  67. package/types/dist/api/connection.d.mts +0 -2
  68. package/types/dist/api/connection.d.mts.map +0 -1
  69. package/types/dist/api/device.d.mts +0 -4
  70. package/types/dist/api/device.d.mts.map +0 -1
  71. package/types/dist/api/devices.d.mts +0 -5
  72. package/types/dist/api/devices.d.mts.map +0 -1
  73. package/types/dist/api/discover.d.mts +0 -6
  74. package/types/dist/api/discover.d.mts.map +0 -1
  75. package/types/dist/api/files.d.mts +0 -85
  76. package/types/dist/api/files.d.mts.map +0 -1
  77. package/types/dist/api/forward.d.mts +0 -5
  78. package/types/dist/api/forward.d.mts.map +0 -1
  79. package/types/dist/api/install.d.mts +0 -3
  80. package/types/dist/api/install.d.mts.map +0 -1
  81. package/types/dist/api/log.d.mts +0 -21
  82. package/types/dist/api/log.d.mts.map +0 -1
  83. package/types/dist/api/pairing.d.mts +0 -2
  84. package/types/dist/api/pairing.d.mts.map +0 -1
  85. package/types/dist/api/reboot.d.mts +0 -2
  86. package/types/dist/api/reboot.d.mts.map +0 -1
  87. package/types/dist/api/reverse.d.mts +0 -6
  88. package/types/dist/api/reverse.d.mts.map +0 -1
  89. package/types/dist/api/shell.d.mts +0 -29
  90. package/types/dist/api/shell.d.mts.map +0 -1
  91. package/types/dist/api/stream.d.mts +0 -11
  92. package/types/dist/api/stream.d.mts.map +0 -1
  93. package/types/dist/api/utils.d.mts +0 -32
  94. package/types/dist/api/utils.d.mts.map +0 -1
  95. package/types/dist/droidsock.d.mts +0 -3
  96. package/types/dist/droidsock.d.mts.map +0 -1
  97. package/types/index.d.mts +0 -11
  98. package/types/index.d.mts.map +0 -1
package/README.md CHANGED
@@ -15,9 +15,9 @@ It talks to devices directly over TCP, with no `adb` binary or ADB server in bet
15
15
  > [!NOTE]
16
16
  > **Current status:**
17
17
  >
18
- > - **Shell + streaming**: Stable - command execution, interactive shells, and log/process streaming all work over the real ADB protocol.
18
+ > - **Shell + streaming**: Stable - command execution, interactive shells, and log / process streaming all work over the real ADB protocol.
19
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.
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).
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).
21
21
 
22
22
  [![Contributors]][contributors_url] [![Sponsor shinrai]][sponsor_url]
23
23
 
@@ -25,18 +25,18 @@ It talks to devices directly over TCP, with no `adb` binary or ADB server in bet
25
25
 
26
26
  ## ✨ What's New
27
27
 
28
- ### Latest: v2.1.0 (October 2026)
28
+ ### Latest: v2.2.1 (November 2026)
29
29
 
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)
30
+ - **`@cldmv/slothlet` kept below 3.24.0** - slothlet 3.24.0 hands sockets back as proxies, so `device.connect()` threw `TypeError: Illegal invocation` on any install that resolved it ([slothlet#708](https://github.com/CLDMV/slothlet/issues/708)). The range is now `>=3.22.1 <3.24.0`; no droidsock code changed ([#112](https://github.com/CLDMV/droidsock/pull/112)).
31
+ - **Suite runs against the build** - `npm run test:dist` runs the Vitest suite against `dist/`, and `npm test` includes it ([#107](https://github.com/CLDMV/droidsock/pull/107)).
32
+ - [View full v2.2.1 Changelog](https://github.com/CLDMV/droidsock/blob/master/docs/changelog/v2/v2.2.1.md)
33
33
 
34
34
  ### Recent Releases
35
35
 
36
+ - **v2.2.0** (November 2026) - CLDMV library layout (`src/index.mjs` / `src/index.cjs` entries, tsup-built `dist/`); `@cldmv/droidsock/main` is a deprecated alias of the root ([Changelog](https://github.com/CLDMV/droidsock/blob/master/docs/changelog/v2/v2.2.0.md))
37
+ - **v2.1.0** (October 2026) - device lifecycle events, opt-in auto-reconnect with backoff, TCP keepalive and an optional heartbeat; `engines.node` rose to `>=22.15.0` ([Changelog](https://github.com/CLDMV/droidsock/blob/master/docs/changelog/v2/v2.1.0.md))
36
38
  - **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
39
  - **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))
40
40
 
41
41
  📚 **For complete version history and detailed release notes, see the [docs/changelog/](https://github.com/CLDMV/droidsock/tree/master/docs/changelog/) folder.**
42
42
 
@@ -44,12 +44,12 @@ It talks to devices directly over TCP, with no `adb` binary or ADB server in bet
44
44
 
45
45
  ## 🚀 Key Features
46
46
 
47
- - ✅ **Complete ADB Protocol**: TCP connection, CNXN/AUTH handshake, and stream multiplexing implemented from scratch
48
- - ✅ **RSA Authentication**: Automatic key generation and ADB-specific signature/public-key formatting
47
+ - ✅ **Complete ADB Protocol**: TCP connection, CNXN / AUTH handshake, and stream multiplexing implemented from scratch
48
+ - ✅ **RSA Authentication**: Automatic key generation and ADB-specific signature / public-key formatting
49
49
  - ✅ **Stream Multiplexing**: Multiple concurrent operations over a single connection
50
50
  - ✅ **Shell Commands**: Execute commands, stream output, interactive sessions
51
51
  - ✅ **File Operations**: Shell-based `mkdir` / `remove` / `move` / `copy` / `chmod` / `diskUsage` / `find`, plus binary-safe SYNC-based `list`, and experimental `push` / `pull` (legacy 32-bit) / `pushV2` / `pullV2` / `listV2` / `statV2` (64-bit)
52
- - ✅ **Reboot** (experimental): Real `reboot:` service, including bootloader/recovery/sideload modes
52
+ - ✅ **Reboot** (experimental): Real `reboot:` service, including bootloader / recovery / sideload modes
53
53
  - ✅ **Port Forwarding** (experimental): `adb forward`/`adb reverse`-equivalent TCP tunneling, both directions
54
54
  - ✅ **APK Install** (experimental): `adb install`-equivalent local APK installation - classic push-then-install and modern streaming (`exec:cmd package install`) paths
55
55
  - ✅ **Wi-Fi Pairing** (experimental): `adb pair`-equivalent PIN-based pairing (SPAKE2-over-Ed25519 + TLS 1.3) for Android 11+ wireless debugging
@@ -62,8 +62,9 @@ It talks to devices directly over TCP, with no `adb` binary or ADB server in bet
62
62
 
63
63
  ### Requirements
64
64
 
65
- - **Node.js v22.15.0 or higher** (the package's `engines.node` floor)
65
+ - **Node.js v22.15.0 or higher** (the package's `engines.node` floor, set by its `@cldmv/slothlet` dependency)
66
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
+ - Developing this package needs Node.js 22.22.0 or later (`devEngines`).
67
68
 
68
69
  ### Install
69
70
 
@@ -103,6 +104,8 @@ await device.disconnect();
103
104
 
104
105
  CommonJS works the same way: `const droidsock = require("@cldmv/droidsock")` (also available as `createDroidSock`).
105
106
 
107
+ `@cldmv/droidsock/main` is a deprecated alias of `@cldmv/droidsock`: it exports the same functions and prints a `DeprecationWarning` (code `CLDMV_DROIDSOCK_MAIN`) once per process. Import `@cldmv/droidsock` instead; the alias is removed in the next major version.
108
+
106
109
  ---
107
110
 
108
111
  ## ⚙️ Device Configuration
@@ -131,9 +134,9 @@ The example scripts read device addresses from `references/devices.json`. The fo
131
134
 
132
135
  ## 📘 API Reference
133
136
 
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.
137
+ `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.
135
138
 
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`.
139
+ 📚 **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
140
 
138
141
  ---
139
142
 
@@ -143,34 +146,36 @@ The example scripts read device addresses from `references/devices.json`. The fo
143
146
 
144
147
  ```bash
145
148
  # Run basic example with default device
146
- node examples/basic-usage.mjs
149
+ node --conditions=droidsock-dev examples/basic-usage.mjs
147
150
 
148
151
  # Run with specific device
149
- node examples/basic-usage.mjs livingroom
152
+ node --conditions=droidsock-dev examples/basic-usage.mjs livingroom
150
153
  ```
151
154
 
155
+ The examples import `@cldmv/droidsock` by name. `--conditions=droidsock-dev` runs them against `src/`; without it they load the build in `dist/` (run `npm run build` first). See [Development](#-development).
156
+
152
157
  ### Streaming Commands
153
158
 
154
159
  ```bash
155
160
  # Stream logcat
156
- node examples/streaming-example.mjs logcat
161
+ node --conditions=droidsock-dev examples/streaming-example.mjs logcat
157
162
 
158
163
  # Stream top command
159
- node examples/streaming-example.mjs top
164
+ node --conditions=droidsock-dev examples/streaming-example.mjs top
160
165
 
161
166
  # File transfer demo
162
- node examples/streaming-example.mjs files
167
+ node --conditions=droidsock-dev examples/streaming-example.mjs files
163
168
  ```
164
169
 
165
170
  ---
166
171
 
167
172
  ## 🏗️ Architecture
168
173
 
169
- `src/droidsock.mjs` composes the layers below into a single api tree via [`@cldmv/slothlet`](https://github.com/CLDMV/slothlet):
174
+ `src/index.mjs` is the package entry (`src/index.cjs` is the CommonJS entry, which loads it through `require(esm)`) and re-exports the factory from `src/droidsock.mjs`, which composes the layers below into a single api tree via [`@cldmv/slothlet`](https://github.com/CLDMV/slothlet):
170
175
 
171
- 1. **Connection Layer** (`src/api/connection.mjs`): TCP socket + CNXN/AUTH handshake
172
- 2. **Authentication Layer** (`src/api/auth.mjs`): RSA key management and ADB signature/public-key formatting
173
- 3. **Stream Layer** (`src/api/stream.mjs`): ADB stream multiplexing (OPEN/WRTE/OKAY/CLSE)
176
+ 1. **Connection Layer** (`src/api/connection.mjs`): TCP socket + CNXN / AUTH handshake
177
+ 2. **Authentication Layer** (`src/api/auth.mjs`): RSA key management and ADB signature / public-key formatting
178
+ 3. **Stream Layer** (`src/api/stream.mjs`): ADB stream multiplexing (OPEN / WRTE / OKAY / CLSE)
174
179
  4. **Shell Layer** (`src/api/shell.mjs`): Command execution, streaming, and interactive shell APIs
175
180
  5. **Files Layer** (`src/api/files.mjs`): Shell-based file operations, a binary-safe SYNC `LIST` implementation with automatic shell fallback, and an experimental ADB SYNC sub-protocol implementation for real binary transfer (`push` / `pull`) - not yet validated against a real device
176
181
  6. **Reboot Layer** (`src/api/reboot.mjs`): Real ADB `reboot:` service
@@ -181,7 +186,7 @@ node examples/streaming-example.mjs files
181
186
  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
182
187
  12. **Config / Log Layers** (`src/api/config.mjs`, `src/api/log.mjs`): Shared configuration and logging
183
188
 
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).
189
+ 📚 **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).
185
190
 
186
191
  ---
187
192
 
@@ -210,7 +215,19 @@ node examples/streaming-example.mjs files
210
215
 
211
216
  ## 🧪 Development
212
217
 
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).
218
+ 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).
219
+
220
+ The source lives in `src/`: `src/index.mjs` is the ESM entry and `src/index.cjs` the CommonJS entry. `npm run build` (tsup) writes `dist/`, which mirrors `src/` file by file because slothlet scans `dist/api/` at runtime; `dist/index.cjs` is a verbatim copy of `src/index.cjs`. Only `dist/` and `types/` are published.
221
+
222
+ In a checkout, `@cldmv/droidsock` resolves to `dist/` by default. The `droidsock-dev` export condition switches it to `src/`:
223
+
224
+ | Run | Resolves to |
225
+ | ------------------------------------------------ | --------------------------------------------------------------- |
226
+ | `node app.mjs` | `dist/index.mjs` (`ERR_MODULE_NOT_FOUND` until `npm run build`) |
227
+ | `node --conditions=droidsock-dev app.mjs` | `src/index.mjs` |
228
+ | `require("@cldmv/droidsock")` with the condition | `src/index.cjs` → `src/index.mjs` |
229
+
230
+ Set it once per shell with `export NODE_OPTIONS=--conditions=droidsock-dev`. `npm test` runs the Vitest suite against `src/` (the Vitest config passes the condition) and then `npm run test:cjs`, which builds `dist/` and checks it with `node --test`, and `npm run test:dist` builds `dist/` and runs the Vitest suite against it (`npm test` includes both).
214
231
 
215
232
  ---
216
233
 
package/dist/api/auth.mjs CHANGED
@@ -1,17 +1,2 @@
1
- /*
2
- Copyright 2026 CLDMV/Shinrai
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
16
-
17
- import{self}from"@cldmv/slothlet/runtime";import crypto from"node:crypto";import fs from"node:fs";import path from"node:path";import os from"node:os";function getKeys(keyDir){const adbDir=keyDir||path.join(os.homedir(),".adb");const privateKeyPath=path.join(adbDir,"adbkey");const publicKeyPath=path.join(adbDir,"adbkey.pub");if(!fs.existsSync(adbDir)){fs.mkdirSync(adbDir,{recursive:true})}if(fs.existsSync(privateKeyPath)&&fs.existsSync(publicKeyPath)){const privateKey=fs.readFileSync(privateKeyPath,"utf8");const adbPublicKey=fs.readFileSync(publicKeyPath,"utf8").trim();const keyObject=crypto.createPrivateKey(privateKey);const publicKey=crypto.createPublicKey(keyObject).export({type:"spki",format:"pem"});return{privateKey,publicKey,adbPublicKey}}return generateKeys(2048,adbDir)}function generateKeys(keySize=2048,saveDir=null){const{publicKey,privateKey}=crypto.generateKeyPairSync("rsa",{modulusLength:keySize,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});const adbPublicKey=formatAdbPublicKey(publicKey);if(saveDir){if(!fs.existsSync(saveDir)){fs.mkdirSync(saveDir,{recursive:true})}const privateKeyPath=path.join(saveDir,"adbkey");const publicKeyPath=path.join(saveDir,"adbkey.pub");fs.writeFileSync(privateKeyPath,privateKey);fs.writeFileSync(publicKeyPath,adbPublicKey)}return{privateKey,publicKey,adbPublicKey}}function sign(token,privateKey){self.log.debug("[DEBUG] AOSP-STYLE ADB SIGNATURE (token as digest):");self.log.debug("[DEBUG] Token:",token.toString("hex"),`(${token.length} bytes)`);if(!Buffer.isBuffer(token)){token=Buffer.from(token)}if(token.length!==20){throw new Error(`Token must be 20 bytes, got ${token.length}`)}const DIGESTINFO_SHA1_PREFIX=Buffer.from([48,33,48,9,6,5,43,14,3,2,26,5,0,4,20]);const digestInfo=Buffer.concat([DIGESTINFO_SHA1_PREFIX,token]);self.log.debug("[DEBUG] DigestInfo:",digestInfo.toString("hex"));const keyObject=crypto.createPrivateKey(privateKey);let keySize=keyObject.asymmetricKeySize;if(keySize===void 0){const keyDetails=keyObject.asymmetricKeyDetails||{};if(keyDetails.modulusLength){keySize=Math.ceil(keyDetails.modulusLength/8)}else{keySize=getKeySizeFromPem(privateKey)}}self.log.debug("[DEBUG] Key size:",keySize,"bytes");const paddedBlock=buildPkcs1v15Block(digestInfo,keySize);self.log.debug("[DEBUG] PKCS#1 v1.5 block length:",paddedBlock.length,"bytes");self.log.debug("[DEBUG] Block starts:",paddedBlock.slice(0,16).toString("hex")+"...");self.log.debug("[DEBUG] Block ends: ..."+paddedBlock.slice(-16).toString("hex"));const signature=crypto.privateEncrypt({key:keyObject,padding:crypto.constants.RSA_NO_PADDING},paddedBlock);self.log.debug("[DEBUG] Signature length:",signature.length,"bytes");self.log.debug("[DEBUG] Signature starts with:",signature.slice(0,8).toString("hex"));return signature}function buildPkcs1v15Block(data,keySize){self.log.debug("[DEBUG] buildPkcs1v15Block - data length:",data.length,"keySize:",keySize,"keySize type:",typeof keySize);if(isNaN(keySize)||keySize<=0){throw new Error(`Invalid key size: ${keySize}`)}const paddingLength=keySize-data.length-3;self.log.debug("[DEBUG] Padding length:",paddingLength);if(paddingLength<8){throw new Error(`Key too small for data - keySize: ${keySize}, dataLength: ${data.length}, paddingLength: ${paddingLength}`)}const padding=Buffer.alloc(paddingLength,255);return Buffer.concat([Buffer.from([0,1]),padding,Buffer.from([0]),data])}function validateAuth(token,privateKey){try{if(!Buffer.isBuffer(token)||token.length!==20){return false}if(typeof privateKey!=="string"||!privateKey.includes("-----BEGIN PRIVATE KEY-----")){return false}sign(token,privateKey);return true}catch{return false}}function formatAdbPublicKey(publicKey){self.log.debug("[DEBUG] Creating ADB public key format...");const pubKey=crypto.createPublicKey(publicKey);const jwk=pubKey.export({format:"jwk"});const n=base64UrlToBuf(jwk.n);const e=base64UrlToBuf(jwk.e);self.log.debug("[DEBUG] Exponent length:",e.length,"bytes, first byte: 0x"+e[0].toString(16).padStart(2,"0"));self.log.debug("[DEBUG] Modulus length:",n.length,"bytes, first byte: 0x"+n[0].toString(16).padStart(2,"0"));const eStripped=e[0]===0?e.slice(1):e;const nStripped=n[0]===0?n.slice(1):n;self.log.debug("[DEBUG] After stripping - Exponent:",eStripped.length,"bytes, Modulus:",nStripped.length,"bytes");const parts=[];writeSshString(parts,Buffer.from("ssh-rsa"));writeSshString(parts,eStripped);writeSshString(parts,nStripped);const sshBlob=Buffer.concat(parts);const base64Key=sshBlob.toString("base64");self.log.debug("[DEBUG] SSH blob length:",sshBlob.length,"bytes");self.log.debug("[DEBUG] Base64 length:",base64Key.length,"chars");self.log.debug("[DEBUG] Base64 preview:",base64Key.substring(0,50)+"...");const hostname=os.hostname()||"unknown";const username=os.userInfo().username||"user";const comment=`${username}@${hostname}`;const result=`${base64Key} ${comment}\0`;self.log.debug("[DEBUG] Final ADB key length:",result.length,"chars");return result}function base64UrlToBuf(b64url){const b64=b64url.replace(/-/g,"+").replace(/_/g,"/");const pad=b64.length%4;const padded=pad?b64+"=".repeat(4-pad):b64;return Buffer.from(padded,"base64")}function writeSshString(bufs,data){const len=Buffer.alloc(4);len.writeUInt32BE(data.length,0);bufs.push(len,data)}function getKeySizeFromPem(privateKey){try{const base64=privateKey.replace(/-----BEGIN PRIVATE KEY-----/,"").replace(/-----END PRIVATE KEY-----/,"").replace(/\s/g,"");const derBuffer=Buffer.from(base64,"base64");if(derBuffer.length>1e3){return 512}else{return 256}}catch(error){self.log.debug("[DEBUG] Failed to parse key size from PEM, defaulting to 256 bytes:",error.message);return 256}}export{formatAdbPublicKey,generateKeys,getKeys,sign,validateAuth};
1
+ var x=Object.defineProperty;var u=(t,e)=>x(t,"name",{value:e,configurable:!0});import{self as r}from"@cldmv/slothlet/runtime";import f from"node:crypto";import g from"node:fs";import b from"node:path";import y from"node:os";function v(t){const e=t||b.join(y.homedir(),".adb"),n=b.join(e,"adbkey"),o=b.join(e,"adbkey.pub");if(g.existsSync(e)||g.mkdirSync(e,{recursive:!0}),g.existsSync(n)&&g.existsSync(o)){const s=g.readFileSync(n,"utf8"),i=g.readFileSync(o,"utf8").trim(),c=f.createPrivateKey(s),l=f.createPublicKey(c).export({type:"spki",format:"pem"});return{privateKey:s,publicKey:l,adbPublicKey:i}}return S(2048,e)}u(v,"getKeys");function S(t=2048,e=null){const{publicKey:n,privateKey:o}=f.generateKeyPairSync("rsa",{modulusLength:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}),s=G(n);if(e){g.existsSync(e)||g.mkdirSync(e,{recursive:!0});const i=b.join(e,"adbkey"),c=b.join(e,"adbkey.pub");g.writeFileSync(i,o),g.writeFileSync(c,s)}return{privateKey:o,publicKey:n,adbPublicKey:s}}u(S,"generateKeys");function K(t,e){if(r.log.debug("[DEBUG] AOSP-STYLE ADB SIGNATURE (token as digest):"),r.log.debug("[DEBUG] Token:",t.toString("hex"),`(${t.length} bytes)`),Buffer.isBuffer(t)||(t=Buffer.from(t)),t.length!==20)throw new Error(`Token must be 20 bytes, got ${t.length}`);const n=Buffer.from([48,33,48,9,6,5,43,14,3,2,26,5,0,4,20]),o=Buffer.concat([n,t]);r.log.debug("[DEBUG] DigestInfo:",o.toString("hex"));const s=f.createPrivateKey(e);let i=s.asymmetricKeySize;if(i===void 0){const a=s.asymmetricKeyDetails||{};a.modulusLength?i=Math.ceil(a.modulusLength/8):i=P(e)}r.log.debug("[DEBUG] Key size:",i,"bytes");const c=D(o,i);r.log.debug("[DEBUG] PKCS#1 v1.5 block length:",c.length,"bytes"),r.log.debug("[DEBUG] Block starts:",c.slice(0,16).toString("hex")+"..."),r.log.debug("[DEBUG] Block ends: ..."+c.slice(-16).toString("hex"));const l=f.privateEncrypt({key:s,padding:f.constants.RSA_NO_PADDING},c);return r.log.debug("[DEBUG] Signature length:",l.length,"bytes"),r.log.debug("[DEBUG] Signature starts with:",l.slice(0,8).toString("hex")),l}u(K,"sign");function D(t,e){if(r.log.debug("[DEBUG] buildPkcs1v15Block - data length:",t.length,"keySize:",e,"keySize type:",typeof e),isNaN(e)||e<=0)throw new Error(`Invalid key size: ${e}`);const n=e-t.length-3;if(r.log.debug("[DEBUG] Padding length:",n),n<8)throw new Error(`Key too small for data - keySize: ${e}, dataLength: ${t.length}, paddingLength: ${n}`);const o=Buffer.alloc(n,255);return Buffer.concat([Buffer.from([0,1]),o,Buffer.from([0]),t])}u(D,"buildPkcs1v15Block");function F(t,e){try{return!Buffer.isBuffer(t)||t.length!==20||typeof e!="string"||!e.includes("-----BEGIN PRIVATE KEY-----")?!1:(K(t,e),!0)}catch{return!1}}u(F,"validateAuth");function G(t){r.log.debug("[DEBUG] Creating ADB public key format...");const n=f.createPublicKey(t).export({format:"jwk"}),o=B(n.n),s=B(n.e);r.log.debug("[DEBUG] Exponent length:",s.length,"bytes, first byte: 0x"+s[0].toString(16).padStart(2,"0")),r.log.debug("[DEBUG] Modulus length:",o.length,"bytes, first byte: 0x"+o[0].toString(16).padStart(2,"0"));const i=s[0]===0?s.slice(1):s,c=o[0]===0?o.slice(1):o;r.log.debug("[DEBUG] After stripping - Exponent:",i.length,"bytes, Modulus:",c.length,"bytes");const l=[];p(l,Buffer.from("ssh-rsa")),p(l,i),p(l,c);const a=Buffer.concat(l),d=a.toString("base64");r.log.debug("[DEBUG] SSH blob length:",a.length,"bytes"),r.log.debug("[DEBUG] Base64 length:",d.length,"chars"),r.log.debug("[DEBUG] Base64 preview:",d.substring(0,50)+"...");const m=y.hostname()||"unknown",E=`${y.userInfo().username||"user"}@${m}`,h=`${d} ${E}\0`;return r.log.debug("[DEBUG] Final ADB key length:",h.length,"chars"),h}u(G,"formatAdbPublicKey");function B(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4,o=n?e+"=".repeat(4-n):e;return Buffer.from(o,"base64")}u(B,"base64UrlToBuf");function p(t,e){const n=Buffer.alloc(4);n.writeUInt32BE(e.length,0),t.push(n,e)}u(p,"writeSshString");function P(t){try{const e=t.replace(/-----BEGIN PRIVATE KEY-----/,"").replace(/-----END PRIVATE KEY-----/,"").replace(/\s/g,"");return Buffer.from(e,"base64").length>1e3?512:256}catch(e){return r.log.debug("[DEBUG] Failed to parse key size from PEM, defaulting to 256 bytes:",e.message),256}}u(P,"getKeySizeFromPem");export{G as formatAdbPublicKey,S as generateKeys,v as getKeys,K as sign,F as validateAuth};
2
+ //# sourceMappingURL=auth.mjs.map
@@ -1,17 +1,2 @@
1
- /*
2
- Copyright 2026 CLDMV/Shinrai
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
16
-
17
- const DEFAULT_CONFIG={host:"127.0.0.1",port:5555,timeout:1e4,retryAttempts:3,retryDelay:1e3,keyDir:null,autoGenerateKeys:true,keySize:2048,debug:false,verbose:false,silent:false,debugArrowSent:">>>>",debugArrowReceived:"<<<<",streamTimeout:3e4,maxStreams:10,shellTimeout:3e4,shellEncoding:"utf8",fileTimeout:6e4,chunkSize:65536,emitEvents:true,eventPrefix:"adb",bufferSize:1024*1024,keepAlive:true,keepAliveInterval:3e4};let configInstance=null;function init(options={}){if(!configInstance){configInstance={...DEFAULT_CONFIG,...options}}return getApi()}function get(key,defaultValue=void 0){if(!configInstance){init()}const keys=key.split(".");let value=configInstance;for(const k of keys){if(value&&typeof value==="object"&&k in value){value=value[k]}else{return defaultValue}}return value}function set(key,value){if(!configInstance){init()}const keys=key.split(".");let obj=configInstance;for(let i=0;i<keys.length-1;i++){const k=keys[i];if(!(k in obj)||typeof obj[k]!=="object"){obj[k]={}}obj=obj[k]}obj[keys[keys.length-1]]=value}function merge(options){if(!configInstance){init()}const mergeRecursive=(target,source,path="")=>{for(const[key,value]of Object.entries(source)){const fullPath=path?`${path}.${key}`:key;if(typeof value==="object"&&value!==null&&!Array.isArray(value)){if(!(key in target)||typeof target[key]!=="object"){target[key]={}}mergeRecursive(target[key],value,fullPath)}else{target[key]=value}}};mergeRecursive(configInstance,options)}function reset(){configInstance={...DEFAULT_CONFIG}}function all(){return configInstance?{...configInstance}:{...DEFAULT_CONFIG}}function getApi(){return{init,get,set,merge,reset,all}}function getDefaults(){return{...DEFAULT_CONFIG}}function validateConfig(config){const errors=[];if(config.port&&(typeof config.port!=="number"||config.port<1||config.port>65535)){errors.push("port must be a number between 1 and 65535")}if(config.timeout&&(typeof config.timeout!=="number"||config.timeout<0)){errors.push("timeout must be a non-negative number")}const timeouts=["streamTimeout","shellTimeout","fileTimeout"];for(const timeout of timeouts){if(config[timeout]&&(typeof config[timeout]!=="number"||config[timeout]<0)){errors.push(`${timeout} must be a non-negative number`)}}const bufferSizes=["bufferSize","chunkSize"];for(const size of bufferSizes){if(config[size]&&(typeof config[size]!=="number"||config[size]<1024)){errors.push(`${size} must be a number >= 1024`)}}return{valid:errors.length===0,errors}}export{all,get,getApi,getDefaults,init,merge,reset,set,validateConfig};
1
+ var b=Object.defineProperty;var i=(e,o)=>b(e,"name",{value:o,configurable:!0});const l={host:"127.0.0.1",port:5555,timeout:1e4,retryAttempts:3,retryDelay:1e3,keyDir:null,autoGenerateKeys:!0,keySize:2048,debug:!1,verbose:!1,silent:!1,debugArrowSent:">>>>",debugArrowReceived:"<<<<",streamTimeout:3e4,maxStreams:10,shellTimeout:3e4,shellEncoding:"utf8",fileTimeout:6e4,chunkSize:65536,emitEvents:!0,eventPrefix:"adb",bufferSize:1048576,keepAlive:!0,keepAliveInterval:3e4};let s=null;function m(e={}){return s||(s={...l,...e}),d()}i(m,"init");function a(e,o=void 0){s||m();const n=e.split(".");let r=s;for(const t of n)if(r&&typeof r=="object"&&t in r)r=r[t];else return o;return r}i(a,"get");function c(e,o){s||m();const n=e.split(".");let r=s;for(let t=0;t<n.length-1;t++){const u=n[t];(!(u in r)||typeof r[u]!="object")&&(r[u]={}),r=r[u]}r[n[n.length-1]]=o}i(c,"set");function y(e){s||m();const o=i((n,r,t="")=>{for(const[u,f]of Object.entries(r)){const p=t?`${t}.${u}`:u;typeof f=="object"&&f!==null&&!Array.isArray(f)?((!(u in n)||typeof n[u]!="object")&&(n[u]={}),o(n[u],f,p)):n[u]=f}},"mergeRecursive");o(s,e)}i(y,"merge");function v(){s={...l}}i(v,"reset");function h(){return s?{...s}:{...l}}i(h,"all");function d(){return{init:m,get:a,set:c,merge:y,reset:v,all:h}}i(d,"getApi");function x(){return{...l}}i(x,"getDefaults");function A(e){const o=[];e.port&&(typeof e.port!="number"||e.port<1||e.port>65535)&&o.push("port must be a number between 1 and 65535"),e.timeout&&(typeof e.timeout!="number"||e.timeout<0)&&o.push("timeout must be a non-negative number");const n=["streamTimeout","shellTimeout","fileTimeout"];for(const t of n)e[t]&&(typeof e[t]!="number"||e[t]<0)&&o.push(`${t} must be a non-negative number`);const r=["bufferSize","chunkSize"];for(const t of r)e[t]&&(typeof e[t]!="number"||e[t]<1024)&&o.push(`${t} must be a number >= 1024`);return{valid:o.length===0,errors:o}}i(A,"validateConfig");export{h as all,a as get,d as getApi,x as getDefaults,m as init,y as merge,v as reset,c as set,A as validateConfig};
2
+ //# sourceMappingURL=config.mjs.map
@@ -1,17 +1,2 @@
1
- /*
2
- Copyright 2026 CLDMV/Shinrai
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
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);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};
1
+ var L=Object.defineProperty;var u=(c,o)=>L(c,"name",{value:o,configurable:!0});import{self as n}from"@cldmv/slothlet/runtime";import N from"node:net";const I=16777216,_=4096,A=1314410051,S=1213486401,p=1497451343,C=["shell_v2","cmd","stat_v2","ls_v2","sendrecv_v2","sendrecv_v2_brotli"];async function D(c){const{host:o,port:r,privateKey:l,adbPublicKey:a}=c,e=new N.Socket,t={socket:e,host:o,port:r,authorized:!1,connected:!1,onUnhandledPacket:null,disconnect:u(()=>{e&&!e.destroyed&&(n.log.debug(`Disconnecting from ${o}:${r}`),e.destroy()),t.connected=!1,t.authorized=!1},"disconnect")};return new Promise((w,d)=>{const s=setTimeout(()=>{e.destroy(),d(new Error("Connection timeout"))},1e4);e.connect(r,o,async()=>{try{n.log.debug(`Connected to ${o}:${r}, sending CNXN message...`);const i=`device::features=${C.join(",")}`,b=Buffer.from(i);await U(e,A,I,_,b),n.log.debug(`${n.config.get("debugArrowSent")} CNXN message sent, waiting for AUTH response...`);const f=await $(e);if(n.log.debug(`${n.config.get("debugArrowReceived")} Received AUTH message, command:`,f.command.toString(16)),f.command!==S)throw new Error(`Expected AUTH message (0x${S.toString(16)}), got 0x${f.command.toString(16)}`);n.log.debug(`${n.config.get("debugArrowReceived")} AUTH message received, token length:`,f.data.length);const v=f.data,h=await n.auth.sign(v,l);await U(e,S,2,0,h);const E=Buffer.from(a);await U(e,S,3,0,E);const g=await $(e);if(n.log.debug(`${n.config.get("debugArrowReceived")} After auth, received command:`,g.command.toString(16)),n.log.debug("Expected CNXN:",A.toString(16),"or OKAY:",p.toString(16)),g.command===A){const m=g.data.toString().replace(/\0/g,"");n.log.debug(`${n.config.get("debugArrowReceived")} Device sent CNXN response - authentication successful!`),n.log.debug(`${n.config.get("debugArrowReceived")} CNXN payload:`,m);const y=m.match(/features=([^;]+)/);t.deviceFeatures=y?y[1].split(","):[],t.authorized=!0,t.connected=!0,n.log.debug("Authentication successful!")}else if(g.command===p)n.log.debug(`${n.config.get("debugArrowReceived")} Device sent OKAY response - authentication successful!`),t.authorized=!0,t.connected=!0;else throw new Error(`Authentication failed - expected CNXN (${A.toString(16)}) or OKAY (${p.toString(16)}), got ${g.command.toString(16)}`);clearTimeout(s),e.on("data",m=>{t.onUnhandledPacket&&t.onUnhandledPacket(m)}),w(t)}catch(i){clearTimeout(s),n.log.debug("Connection error:",i.message),e.destroy(),d(i)}}),e.on("error",i=>{clearTimeout(s),n.log.debug("Socket error:",i.message),d(i)})})}u(D,"create");async function U(c,o,r,l,a=Buffer.alloc(0)){const e=Buffer.alloc(24);let t=0;e.writeUInt32LE(o,t),t+=4,e.writeUInt32LE(r,t),t+=4,e.writeUInt32LE(l,t),t+=4,e.writeUInt32LE(a.length,t),t+=4,e.writeUInt32LE(x(a),t),t+=4,e.writeUInt32LE((o^4294967295)>>>0,t),c.write(e),a.length>0&&c.write(a)}u(U,"sendMessage");function $(c){return new Promise((o,r)=>{let l=!1,a=0,e=null,t=Buffer.alloc(0);const w=u(d=>{if(l)t=Buffer.concat([t,d]);else if(d.length>=24){e=d.slice(0,24),n.log.debug("Header bytes:",Array.from(e).map(s=>s.toString(16).padStart(2,"0")).join(" "));try{a=e.readUInt32LE(12),n.log.debug("Raw data length from header:",a)}catch(s){r(new Error(`Failed to read data length from header: ${s.message}`));return}if(isNaN(a)||a<0||a>1024*1024){r(new Error(`Invalid data length: ${a} (header: ${e.toString("hex")})`));return}l=!0,d.length>24&&(t=Buffer.concat([t,d.slice(24)]))}if(l&&t.length>=a){c.removeListener("data",w);try{const s=e.readUInt32LE(0),i=e.readUInt32LE(4),b=e.readUInt32LE(8),f=e.readUInt32LE(12),v=e.readUInt32LE(16),h=e.readUInt32LE(20);n.log.debug("Parsed header - command:",s.toString(16),"arg0:",i,"arg1:",b,"length:",f,"checksum:",v,"magic:",h.toString(16));const E=(s^4294967295)>>>0;h!==E&&n.log.debug("Magic mismatch - expected:",E.toString(16),"got:",h.toString(16));const g=t.slice(0,a);if(g.length>0){const m=x(g);n.log.debug("Data checksum - expected:",v,"calculated:",m)}o({command:s,arg0:i,arg1:b,data:g})}catch(s){r(new Error(`Failed to parse message header: ${s.message}`))}}},"onData");c.on("data",w),c.on("error",r)})}u($,"receiveMessage");function x(c){let o=0;for(let r=0;r<c.length;r++)o=o+c[r]>>>0;return o}u(x,"checksum");export{D as create};
2
+ //# sourceMappingURL=connection.mjs.map
@@ -1,17 +1,2 @@
1
- /*
2
- Copyright 2026 CLDMV/Shinrai
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
16
-
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};
1
+ var V=Object.defineProperty;var n=(o,l)=>V(o,"name",{value:l,configurable:!0});import{EventEmitter as F}from"node:events";import{self as a}from"@cldmv/slothlet/runtime";import{quoteShellArg as v,sanitizeKey as M}from"./utils.mjs";const I={maxAttempts:1/0,maxDelay:3e4,factor:2,jitter:.2};function P(o){if(!o)return null;const l=typeof o=="object"?o:{};return{...I,initialDelay:a.config.get("retryDelay",1e3),...l}}n(P,"resolveReconnectPolicy");function R(o,l){const u=Math.min(o.maxDelay,o.initialDelay*o.factor**(l-1)),s=u*o.jitter;return Math.max(0,Math.round(u-s+Math.random()*s*2))}n(R,"backoffDelay");function T(o){return o?{interval:15e3,timeout:5e3,...typeof o=="object"?o:{}}:null}n(T,"resolveHeartbeatPolicy");function K(o){return/^Authentication failed/.test(o?.message||"")}n(K,"isFatalConnectError");async function j(o,l,u){const s=await a.auth.getKeys(u.keyDir),d=await a.connection.create({host:o,port:l,publicKey:s.publicKey,privateKey:s.privateKey,adbPublicKey:s.adbPublicKey}),t=await a.stream.create(d.socket);return d.onUnhandledPacket=g=>t.handlePacket(g),{connection:d,streamManager:t}}n(j,"openSession");function z(o,l,u,s,d){const t={connection:null,streamManager:null},g=new F,b=new WeakSet,$=new WeakMap;let h=null,w=null,p=null;function y(e,r={}){if(a.config.get("emitEvents",!0)&&!(e==="error"&&g.listenerCount("error")===0))try{g.emit(e,{deviceId:u,host:o,port:l,...r})}catch(c){a.log.error(`Listener for "${e}" on ${u} threw:`,c)}}n(y,"emit");function x(){w&&clearInterval(w),w=null}n(x,"stopHeartbeat");function A(e){x();const r=T(i.options.heartbeat);if(!r)return;let c=!1;w=setInterval(async()=>{if(!(c||t.connection!==e||!i.isConnected())){c=!0;try{await a.shell.execute(e.socket,t.streamManager,"echo",{timeout:r.timeout,deviceFeatures:e.deviceFeatures||[]})}catch(m){t.connection===e&&($.set(e,"heartbeat"),y("error",{error:m}),e.disconnect())}finally{c=!1}}},r.interval)}n(A,"startHeartbeat");function S(){h&&clearTimeout(h),h=null}n(S,"cancelReconnect");function D(e="connect"){return p||(p=(async()=>{y("connecting",{phase:e});const{connection:r,streamManager:c}=await j(o,l,i.options);t.connection=r,t.streamManager=c,a.devices[s].connection=r,a.devices[s].streamManager=c,C(r),A(r),y("connected",{phase:e})})().finally(()=>{p=null}),p)}n(D,"establish");function C(e){const r=e.socket;a.config.get("keepAlive",!0)&&r.setKeepAlive(!0,a.config.get("keepAliveInterval",3e4)),r.once("close",c=>{if(t.connection!==e)return;e.connected=!1,x();const m=b.has(e);y("disconnected",{intentional:m,hadError:c,reason:$.get(e)??(m?"requested":"closed")}),m||E(1)})}n(C,"watchConnection");function E(e,r){const c=P(i.options.autoReconnect);if(!c)return;if(e>c.maxAttempts){y("gave-up",{reason:"max-attempts",attempts:e-1,error:r});return}const m=R(c,e);y("reconnecting",{attempt:e,delay:m,error:r}),h=setTimeout(async()=>{h=null;try{await D("reconnect"),y("reconnected",{attempt:e})}catch(k){y("error",{error:k,attempt:e}),K(k)?y("gave-up",{reason:"auth",attempts:e,error:k}):E(e+1,k)}},m)}n(E,"scheduleReconnect");function f(){if(!i.isConnected())throw new Error("Device not connected");if(!t.connection.authorized)throw new Error("Device not authorized. Please accept authorization dialog.")}n(f,"assertReady");const i={host:o,port:l,deviceId:u,options:d,connection:null,streamManager:null,isConnected:n(()=>!!(t.connection&&t.connection.connected&&t.connection.socket&&!t.connection.socket.destroyed),"isConnected"),disconnect:n(()=>{S(),t.connection&&(b.add(t.connection),t.connection.disconnect())},"disconnect"),on:n((e,r)=>(g.on(e,r),a.devices[s]),"on"),once:n((e,r)=>(g.once(e,r),a.devices[s]),"once"),off:n((e,r)=>(g.off(e,r),a.devices[s]),"off"),reconnect:n(async(e={})=>(i.options={...i.options,...e},i.isConnected()?a.devices[s]:(S(),await D(),a.devices[s])),"reconnect"),remove:n(async()=>{i.disconnect(),await a.slothlet.api.remove(`devices.${s}`).catch(()=>{})},"remove"),shell:n(async(e,r={})=>(f(),await a.shell.execute(t.connection.socket,t.streamManager,e,{...r,deviceFeatures:t.connection.deviceFeatures||[]})),"shell"),startStreamingShell:n((e,r={})=>(f(),a.shell.startStreaming(t.connection.socket,t.streamManager,e,r)),"startStreamingShell"),startInteractiveShell:n((e,r={})=>(f(),a.shell.startInteractive(t.connection.socket,t.streamManager,e,r)),"startInteractiveShell"),push:n(async(e,r,c={})=>(f(),await a.files.push(t.connection.socket,t.streamManager,e,r,c)),"push"),pull:n(async(e,r,c={})=>(f(),await a.files.pull(t.connection.socket,t.streamManager,e,r,c)),"pull"),pushV2:n(async(e,r,c={})=>(f(),await a.files.pushV2(t.connection.socket,t.streamManager,e,r,c)),"pushV2"),pullV2:n(async(e,r,c={})=>(f(),await a.files.pullV2(t.connection.socket,t.streamManager,e,r,c)),"pullV2"),list:n(async e=>(f(),await a.files.list(t.connection.socket,t.streamManager,e)),"list"),stat:n(async e=>(f(),await a.files.stat(t.connection.socket,t.streamManager,e)),"stat"),listV2:n(async e=>(f(),await a.files.listV2(t.connection.socket,t.streamManager,e)),"listV2"),statV2:n(async e=>(f(),await a.files.statV2(t.connection.socket,t.streamManager,e)),"statV2"),reboot:n(async(e="")=>(f(),await a.reboot.execute(t.connection.socket,t.streamManager,e)),"reboot"),forward:n(async(e,r={})=>(f(),await a.forward.start(t.connection.socket,t.streamManager,e,r)),"forward"),reverse:n(async(e,r,c={})=>(f(),await a.reverse.start(t.connection.socket,t.streamManager,e,r,c)),"reverse"),install:n(async(e,r={})=>{if(f(),(t.connection.deviceFeatures||[]).includes("cmd"))try{return await a.install.streaming(t.connection.socket,t.streamManager,e,r)}catch(c){try{return await a.install.classic(t.connection.socket,t.streamManager,e,r)}catch(m){throw new Error(`Streaming install failed (${c.message}), and the classic fallback also failed: ${m.message}`,{cause:m})}}return await a.install.classic(t.connection.socket,t.streamManager,e,r)},"install"),ls:n((e=".")=>i.shell(`ls -la ${v(e)}`),"ls"),pwd:n(()=>i.shell("pwd"),"pwd"),getprop:n((e=null)=>i.shell(e?`getprop ${v(e)}`:"getprop"),"getprop"),getModel:n(()=>i.shell("getprop ro.product.model"),"getModel"),getAndroidVersion:n(()=>i.shell("getprop ro.build.version.release"),"getAndroidVersion"),getBattery:n(()=>i.shell("dumpsys battery"),"getBattery"),screenshot:n((e="/sdcard/screenshot.png")=>i.shell(`screencap -p ${v(e)}`),"screenshot"),logcat:n((e={})=>i.startStreamingShell("logcat",e),"logcat"),top:n((e={})=>i.startStreamingShell("top -m 10",e),"top"),keypress:n(e=>i.shell(`input keyevent ${v(e)}`),"keypress"),launchApp:n((e,r="")=>{const c=r?`${e}/${r}`:e;return i.shell(`am start -n ${v(c)}`)},"launchApp"),rebootBootloader:n(()=>i.reboot("bootloader"),"rebootBootloader"),rebootRecovery:n(()=>i.reboot("recovery"),"rebootRecovery"),rebootSideload:n(()=>i.reboot("sideload"),"rebootSideload")};return i}n(z,"buildDeviceLeaf");async function q(o,l=5555,u={}){const s=`${o}:${l}`,d=M(s),t=a.devices&&a.devices[d];if(t)return await t.reconnect(u);const g=z(o,l,s,d,u);return await a.slothlet.api.add(`devices.${d}`,g,{moduleID:`device:${s}`}),await a.devices[d].reconnect(u),a.devices[d]}n(q,"connect");function W(o,l=5555){const u=M(`${o}:${l}`),s=a.devices&&a.devices[u];return s?(s.disconnect(),!0):!1}n(W,"disconnect");async function _(o,l=5555){const u=M(`${o}:${l}`),s=a.devices&&a.devices[u];return s?(await s.remove(),!0):!1}n(_,"remove");export{q as connect,W as disconnect,_ as remove};
2
+ //# sourceMappingURL=device.mjs.map
@@ -1,17 +1,2 @@
1
- /*
2
- Copyright 2026 CLDMV/Shinrai
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
16
-
17
- import{self}from"@cldmv/slothlet/runtime";import{parseHostPort,sanitizeKey}from"./utils.mjs";function deviceEntries(){const registry=self.devices||{};return Object.keys(registry).map(key=>registry[key]).filter(entry=>entry&&typeof entry==="object"&&typeof entry.isConnected==="function")}function list(){return deviceEntries().filter(entry=>entry.isConnected())}function get(idOrLeaf){let host,port;if(idOrLeaf&&typeof idOrLeaf==="object"){({host,port}=idOrLeaf)}else{({host,port}=parseHostPort(String(idOrLeaf)))}const key=sanitizeKey(`${host}:${port}`);return self.devices&&self.devices[key]||void 0}function disconnect(){if(arguments.length>0){throw new Error("devices.disconnect() takes no arguments - it disconnects ALL devices. Use device.disconnect(host, port) for one.")}let count=0;for(const entry of deviceEntries()){if(!entry.isConnected())continue;entry.disconnect();count++}return count}async function remove(){if(arguments.length>0){throw new Error("devices.remove() takes no arguments - it removes ALL devices. Use device.remove(host, port) for one.")}const entries=deviceEntries();let count=0;for(const entry of entries){await entry.remove();count++}return count}export{disconnect,get,list,remove};
1
+ var i=Object.defineProperty;var o=(t,e)=>i(t,"name",{value:e,configurable:!0});import{self as r}from"@cldmv/slothlet/runtime";import{parseHostPort as f,sanitizeKey as u}from"./utils.mjs";function s(){const t=r.devices||{};return Object.keys(t).map(e=>t[e]).filter(e=>e&&typeof e=="object"&&typeof e.isConnected=="function")}o(s,"deviceEntries");function p(){return s().filter(t=>t.isConnected())}o(p,"list");function l(t){let e,n;t&&typeof t=="object"?{host:e,port:n}=t:{host:e,port:n}=f(String(t));const c=u(`${e}:${n}`);return r.devices&&r.devices[c]||void 0}o(l,"get");function a(){if(arguments.length>0)throw new Error("devices.disconnect() takes no arguments - it disconnects ALL devices. Use device.disconnect(host, port) for one.");let t=0;for(const e of s())e.isConnected()&&(e.disconnect(),t++);return t}o(a,"disconnect");async function g(){if(arguments.length>0)throw new Error("devices.remove() takes no arguments - it removes ALL devices. Use device.remove(host, port) for one.");const t=s();let e=0;for(const n of t)await n.remove(),e++;return e}o(g,"remove");export{a as disconnect,l as get,p as list,g as remove};
2
+ //# sourceMappingURL=devices.mjs.map
@@ -1,17 +1,2 @@
1
- /*
2
- Copyright 2026 CLDMV/Shinrai
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
16
-
17
- import{self}from"@cldmv/slothlet/runtime";import net from"node:net";import dgram from"node:dgram";import{isValidPort,ipv6ToBigInt,bigIntToIpv6}from"./utils.mjs";const DNS_TYPE_A=1;const DNS_TYPE_PTR=12;const DNS_TYPE_TXT=16;const DNS_TYPE_AAAA=28;const DNS_TYPE_SRV=33;const DNS_CLASS_IN=1;function ipv4ToBigInt(ip){return ip.split(".").reduce((acc,octet)=>acc<<8n|BigInt(octet),0n)}function bigIntToIpv4(value){return[24n,16n,8n,0n].map(shift=>Number(value>>shift&0xffn)).join(".")}function parseCidr(cidr){const parts=String(cidr).split("/");const family=parts.length===2?net.isIP(parts[0]):0;if(family===0||!/^\d+$/.test(parts[1])){throw new Error(`Invalid CIDR: ${cidr}`)}const[address,prefixStr]=parts;const addressBits=family===6?128:32;const prefix=Number(prefixStr);if(prefix>addressBits){throw new Error(`Invalid CIDR prefix (must be 0-${addressBits}): ${cidr}`)}const format=family===6?bigIntToIpv6:bigIntToIpv4;const base=family===6?ipv6ToBigInt(address):ipv4ToBigInt(address);const hostBits=BigInt(addressBits-prefix);const size=1n<<hostBits;const network=base>>hostBits<<hostBits;const lastAddress=network+size-1n;if(family===6||hostBits<=1n){return{family,firstHost:network,lastHost:lastAddress,sweepCount:size,format}}return{family,firstHost:network+1n,lastHost:lastAddress-1n,sweepCount:size-2n,format}}function attemptConnect(host,port,timeoutMs){return new Promise(resolve=>{const socket=new net.Socket;let settled=false;const finish=reachable=>{if(settled)return;settled=true;socket.removeAllListeners();socket.destroy();resolve(reachable)};socket.setTimeout(timeoutMs);socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false));socket.once("timeout",()=>finish(false));socket.connect(port,host)})}async function sweepPool(hosts,port,{timeoutMs,concurrency}){const reachable=[];let nextIndex=0;async function worker(){for(;;){const i=nextIndex++;if(i>=hosts.length)return;const host=hosts[i];if(await attemptConnect(host,port,timeoutMs)){reachable.push({index:i,host,port})}}}const workers=Array.from({length:Math.min(concurrency,hosts.length)},()=>worker());await Promise.all(workers);return reachable.sort((a,b)=>a.index-b.index).map(({host,port:p})=>({host,port:p}))}async function subnet(cidr,port=5555,options={}){const{timeoutMs=500,concurrency=32,maxHosts=1024}=options;if(!isValidPort(port)){throw new Error(`Invalid port: ${port}`)}if(!Number.isInteger(timeoutMs)||timeoutMs<=0){throw new Error(`Invalid timeoutMs: ${timeoutMs} (must be a positive integer)`)}if(!Number.isInteger(concurrency)||concurrency<=0){throw new Error(`Invalid concurrency: ${concurrency} (must be a positive integer)`)}if(!Number.isInteger(maxHosts)||maxHosts<=0){throw new Error(`Invalid maxHosts: ${maxHosts} (must be a positive integer)`)}const range=parseCidr(cidr);if(range.sweepCount>maxHosts){throw new Error(`CIDR ${cidr} has ${range.sweepCount} sweepable host(s), exceeding maxHosts (${maxHosts}). Use a narrower CIDR or raise maxHosts.`)}const hosts=[];for(let value=range.firstHost;value<=range.lastHost;value++){hosts.push(range.format(value))}self.log.debug(`discover.subnet: sweeping ${hosts.length} host(s) in ${cidr} on port ${port}`);return await sweepPool(hosts,port,{timeoutMs,concurrency})}function encodeDnsName(name){const labels=name.replace(/\.$/,"").split(".").filter(Boolean);const parts=labels.map(label=>{const labelBuf=Buffer.from(label,"utf8");if(labelBuf.length>63){throw new Error(`DNS label too long (max 63 bytes): "${label}"`)}return Buffer.concat([Buffer.from([labelBuf.length]),labelBuf])});const encoded=Buffer.concat([...parts,Buffer.from([0])]);if(encoded.length>255){throw new Error(`DNS name too long (max 255 bytes): "${name}"`)}return encoded}function decodeDnsName(buffer,offset){const labels=[];let pos=offset;let next=-1;let guard=0;for(;;){if(guard++>128)throw new Error("DNS name decoding exceeded compression-pointer guard");const len=buffer.readUInt8(pos);if(len===0){pos+=1;if(next===-1)next=pos;break}if((len&192)===192){const pointer=(len&63)<<8|buffer.readUInt8(pos+1);if(next===-1)next=pos+2;pos=pointer;continue}labels.push(buffer.toString("utf8",pos+1,pos+1+len));pos+=1+len}return{name:labels.join("."),next}}function readDnsRecord(buffer,offset){const{name,next:afterName}=decodeDnsName(buffer,offset);let pos=afterName;const type=buffer.readUInt16BE(pos);pos+=2;pos+=2;const ttl=buffer.readUInt32BE(pos);pos+=4;const rdlength=buffer.readUInt16BE(pos);pos+=2;const rdataStart=pos;const rdataEnd=pos+rdlength;let data;switch(type){case DNS_TYPE_PTR:{const ptr=decodeDnsName(buffer,rdataStart);data=ptr.next<=rdataEnd?{target:ptr.name}:null;break}case DNS_TYPE_SRV:{if(rdlength<6){data=null;break}const srv=decodeDnsName(buffer,rdataStart+6);data=srv.next<=rdataEnd?{priority:buffer.readUInt16BE(rdataStart),weight:buffer.readUInt16BE(rdataStart+2),port:buffer.readUInt16BE(rdataStart+4),target:srv.name}:null;break}case DNS_TYPE_TXT:{const txt=Object.create(null);let p=rdataStart;while(p<rdataEnd){const len=buffer.readUInt8(p);p+=1;if(len===0)continue;if(p+len>rdataEnd)break;const entry=buffer.toString("utf8",p,p+len);p+=len;const eq=entry.indexOf("=");if(eq===-1)txt[entry]=true;else txt[entry.slice(0,eq)]=entry.slice(eq+1)}data=txt;break}case DNS_TYPE_A:data=Array.from(buffer.subarray(rdataStart,rdataEnd)).join(".");break;case DNS_TYPE_AAAA:data=rdlength===16?bigIntToIpv6(buffer.readBigUInt64BE(rdataStart)<<64n|buffer.readBigUInt64BE(rdataStart+8)):null;break;default:data=buffer.subarray(rdataStart,rdataEnd)}return{name,type,ttl,data,next:rdataEnd}}function parseDnsMessage(buffer){const qdcount=buffer.readUInt16BE(4);const ancount=buffer.readUInt16BE(6);const nscount=buffer.readUInt16BE(8);const arcount=buffer.readUInt16BE(10);let offset=12;for(let i=0;i<qdcount;i++){const{next}=decodeDnsName(buffer,offset);offset=next+4}const records=[];for(let i=0;i<ancount+nscount+arcount;i++){const record=readDnsRecord(buffer,offset);records.push(record);offset=record.next}return records}function buildPtrQuery(serviceType){const header=Buffer.alloc(12);header.writeUInt16BE(1,4);const question=Buffer.alloc(4);question.writeUInt16BE(DNS_TYPE_PTR,0);question.writeUInt16BE(DNS_CLASS_IN,2);return Buffer.concat([header,encodeDnsName(serviceType),question])}function isMulticastAddress(address){const bare=address.split("%",1)[0];if(net.isIPv6(bare)){return ipv6ToBigInt(bare)>>120n===0xffn}const firstOctet=Number(bare.split(".",1)[0]);return Number.isInteger(firstOctet)&&firstOctet>=224&&firstOctet<=239}function addressRank(address,queryFamily){const isSix=net.isIPv6(address);const isLinkLocal=isSix?/^fe[89ab]/i.test(address):address.startsWith("169.254.");if(isLinkLocal)return 1;return(isSix?6:4)===queryFamily?3:2}function ingestDnsRecords(records,results,addresses,queryFamily){for(const record of records){if(record.type!==DNS_TYPE_A&&record.type!==DNS_TYPE_AAAA||typeof record.data!=="string"||net.isIP(record.data)===0){continue}const existing=addresses.get(record.name);if(!existing||addressRank(record.data,queryFamily)>=addressRank(existing,queryFamily)){addresses.set(record.name,record.data)}}for(const record of records){if(record.type!==DNS_TYPE_PTR||!record.data)continue;const instanceName=record.data.target;if(!results.has(instanceName)){results.set(instanceName,{name:instanceName,txt:Object.create(null)})}}for(const record of records){if(record.type===DNS_TYPE_SRV){if(!record.data)continue;const entry=results.get(record.name);if(!entry)continue;entry.port=record.data.port;entry._target=record.data.target;entry.host=addresses.get(record.data.target)||entry.host}else if(record.type===DNS_TYPE_TXT){const entry=results.get(record.name);if(!entry)continue;Object.assign(entry.txt,record.data)}}for(const entry of results.values()){if(!entry.host&&entry._target&&addresses.has(entry._target)){entry.host=addresses.get(entry._target)}}}async function mdns(options={}){const{serviceType="_adb-tls-connect._tcp.local",address,family,port=5353,timeoutMs=3e3,multicastInterface}=options;if(family!==void 0&&family!==4&&family!==6){throw new Error(`Invalid family: ${family} (must be 4 or 6)`)}if(!isValidPort(port)){throw new Error(`Invalid port: ${port}`)}if(!Number.isInteger(timeoutMs)||timeoutMs<=0){throw new Error(`Invalid timeoutMs: ${timeoutMs} (must be a positive integer)`)}if(address!==void 0&&typeof address!=="string"){throw new Error(`Invalid address: ${address} (must be a string)`)}if(multicastInterface!==void 0&&typeof multicastInterface!=="string"){throw new Error(`Invalid multicastInterface: ${multicastInterface} (must be a string)`)}const detectedFamily=typeof address==="string"?net.isIP(address):0;if(family!==void 0&&detectedFamily!==0&&detectedFamily!==family){throw new Error(`Invalid address: ${address} (not an IPv${family} address)`)}const queryFamily=family??(detectedFamily===6?6:4);const target=address??(queryFamily===6?"ff02::fb":"224.0.0.251");const query=buildPtrQuery(serviceType);const isMulticast=isMulticastAddress(target);const socket=dgram.createSocket({type:queryFamily===6?"udp6":"udp4",reuseAddr:true});const results=new Map;const addresses=new Map;let settled=false;return new Promise((resolve,reject)=>{const finish=(fn,value)=>{if(settled)return;settled=true;clearTimeout(timer);socket.removeAllListeners();socket.close();fn(value)};socket.on("error",error=>finish(reject,error));socket.on("message",message=>{try{ingestDnsRecords(parseDnsMessage(message),results,addresses,queryFamily)}catch(error){self.log.debug(`discover.mdns: ignoring unparseable response - ${error.message}`)}});const timer=setTimeout(()=>{finish(resolve,Array.from(results.values()).filter(entry=>entry.host&&entry.port).map(entry=>({name:entry.name,host:entry.host,port:entry.port,txt:entry.txt})))},timeoutMs);socket.bind(isMulticast?port:0,()=>{if(isMulticast){try{if(multicastInterface)socket.setMulticastInterface(multicastInterface);socket.addMembership(target,multicastInterface)}catch(error){self.log.debug(`discover.mdns: couldn't join multicast group ${target} - ${error.message}`)}}try{socket.setMulticastTTL(255)}catch(error){self.log.debug(`discover.mdns: couldn't set multicast TTL - ${error.message}`)}self.log.debug(`discover.mdns: querying ${serviceType} via ${target}:${port}`);socket.send(query,port,target,error=>{if(error)finish(reject,error)})})})}export{mdns,subnet};
1
+ var M=Object.defineProperty;var f=(e,o)=>M(e,"name",{value:o,configurable:!0});import{self as x}from"@cldmv/slothlet/runtime";import h from"node:net";import C from"node:dgram";import{isValidPort as $,ipv6ToBigInt as N,bigIntToIpv6 as S}from"./utils.mjs";const T=1,b=12,U=16,k=28,D=33,H=1;function L(e){return e.split(".").reduce((o,n)=>o<<8n|BigInt(n),0n)}f(L,"ipv4ToBigInt");function R(e){return[24n,16n,8n,0n].map(o=>Number(e>>o&0xffn)).join(".")}f(R,"bigIntToIpv4");function j(e){const o=String(e).split("/"),n=o.length===2?h.isIP(o[0]):0;if(n===0||!/^\d+$/.test(o[1]))throw new Error(`Invalid CIDR: ${e}`);const[s,t]=o,r=n===6?128:32,a=Number(t);if(a>r)throw new Error(`Invalid CIDR prefix (must be 0-${r}): ${e}`);const c=n===6?S:R,i=n===6?N(s):L(s),l=BigInt(r-a),g=1n<<l,m=i>>l<<l,u=m+g-1n;return n===6||l<=1n?{family:n,firstHost:m,lastHost:u,sweepCount:g,format:c}:{family:n,firstHost:m+1n,lastHost:u-1n,sweepCount:g-2n,format:c}}f(j,"parseCidr");function q(e,o,n){return new Promise(s=>{const t=new h.Socket;let r=!1;const a=f(c=>{r||(r=!0,t.removeAllListeners(),t.destroy(),s(c))},"finish");t.setTimeout(n),t.once("connect",()=>a(!0)),t.once("error",()=>a(!1)),t.once("timeout",()=>a(!1)),t.connect(o,e)})}f(q,"attemptConnect");async function O(e,o,{timeoutMs:n,concurrency:s}){const t=[];let r=0;async function a(){for(;;){const i=r++;if(i>=e.length)return;const l=e[i];await q(l,o,n)&&t.push({index:i,host:l,port:o})}}f(a,"worker");const c=Array.from({length:Math.min(s,e.length)},()=>a());return await Promise.all(c),t.sort((i,l)=>i.index-l.index).map(({host:i,port:l})=>({host:i,port:l}))}f(O,"sweepPool");async function tt(e,o=5555,n={}){const{timeoutMs:s=500,concurrency:t=32,maxHosts:r=1024}=n;if(!$(o))throw new Error(`Invalid port: ${o}`);if(!Number.isInteger(s)||s<=0)throw new Error(`Invalid timeoutMs: ${s} (must be a positive integer)`);if(!Number.isInteger(t)||t<=0)throw new Error(`Invalid concurrency: ${t} (must be a positive integer)`);if(!Number.isInteger(r)||r<=0)throw new Error(`Invalid maxHosts: ${r} (must be a positive integer)`);const a=j(e);if(a.sweepCount>r)throw new Error(`CIDR ${e} has ${a.sweepCount} sweepable host(s), exceeding maxHosts (${r}). Use a narrower CIDR or raise maxHosts.`);const c=[];for(let i=a.firstHost;i<=a.lastHost;i++)c.push(a.format(i));return x.log.debug(`discover.subnet: sweeping ${c.length} host(s) in ${e} on port ${o}`),await O(c,o,{timeoutMs:s,concurrency:t})}f(tt,"subnet");function Y(e){const n=e.replace(/\.$/,"").split(".").filter(Boolean).map(t=>{const r=Buffer.from(t,"utf8");if(r.length>63)throw new Error(`DNS label too long (max 63 bytes): "${t}"`);return Buffer.concat([Buffer.from([r.length]),r])}),s=Buffer.concat([...n,Buffer.from([0])]);if(s.length>255)throw new Error(`DNS name too long (max 255 bytes): "${e}"`);return s}f(Y,"encodeDnsName");function y(e,o){const n=[];let s=o,t=-1,r=0;for(;;){if(r++>128)throw new Error("DNS name decoding exceeded compression-pointer guard");const a=e.readUInt8(s);if(a===0){s+=1,t===-1&&(t=s);break}if((a&192)===192){const c=(a&63)<<8|e.readUInt8(s+1);t===-1&&(t=s+2),s=c;continue}n.push(e.toString("utf8",s+1,s+1+a)),s+=1+a}return{name:n.join("."),next:t}}f(y,"decodeDnsName");function V(e,o){const{name:n,next:s}=y(e,o);let t=s;const r=e.readUInt16BE(t);t+=2,t+=2;const a=e.readUInt32BE(t);t+=4;const c=e.readUInt16BE(t);t+=2;const i=t,l=t+c;let g;switch(r){case b:{const m=y(e,i);g=m.next<=l?{target:m.name}:null;break}case D:{if(c<6){g=null;break}const m=y(e,i+6);g=m.next<=l?{priority:e.readUInt16BE(i),weight:e.readUInt16BE(i+2),port:e.readUInt16BE(i+4),target:m.name}:null;break}case U:{const m=Object.create(null);let u=i;for(;u<l;){const p=e.readUInt8(u);if(u+=1,p===0)continue;if(u+p>l)break;const I=e.toString("utf8",u,u+p);u+=p;const w=I.indexOf("=");w===-1?m[I]=!0:m[I.slice(0,w)]=I.slice(w+1)}g=m;break}case T:g=Array.from(e.subarray(i,l)).join(".");break;case k:g=c===16?S(e.readBigUInt64BE(i)<<64n|e.readBigUInt64BE(i+8)):null;break;default:g=e.subarray(i,l)}return{name:n,type:r,ttl:a,data:g,next:l}}f(V,"readDnsRecord");function z(e){const o=e.readUInt16BE(4),n=e.readUInt16BE(6),s=e.readUInt16BE(8),t=e.readUInt16BE(10);let r=12;for(let c=0;c<o;c++){const{next:i}=y(e,r);r=i+4}const a=[];for(let c=0;c<n+s+t;c++){const i=V(e,r);a.push(i),r=i.next}return a}f(z,"parseDnsMessage");function F(e){const o=Buffer.alloc(12);o.writeUInt16BE(1,4);const n=Buffer.alloc(4);return n.writeUInt16BE(b,0),n.writeUInt16BE(H,2),Buffer.concat([o,Y(e),n])}f(F,"buildPtrQuery");function Q(e){const o=e.split("%",1)[0];if(h.isIPv6(o))return N(o)>>120n===0xffn;const n=Number(o.split(".",1)[0]);return Number.isInteger(n)&&n>=224&&n<=239}f(Q,"isMulticastAddress");function P(e,o){const n=h.isIPv6(e);return(n?/^fe[89ab]/i.test(e):e.startsWith("169.254."))?1:(n?6:4)===o?3:2}f(P,"addressRank");function W(e,o,n,s){for(const t of e){if(t.type!==T&&t.type!==k||typeof t.data!="string"||h.isIP(t.data)===0)continue;const r=n.get(t.name);(!r||P(t.data,s)>=P(r,s))&&n.set(t.name,t.data)}for(const t of e){if(t.type!==b||!t.data)continue;const r=t.data.target;o.has(r)||o.set(r,{name:r,txt:Object.create(null)})}for(const t of e)if(t.type===D){if(!t.data)continue;const r=o.get(t.name);if(!r)continue;r.port=t.data.port,r._target=t.data.target,r.host=n.get(t.data.target)||r.host}else if(t.type===U){const r=o.get(t.name);if(!r)continue;Object.assign(r.txt,t.data)}for(const t of o.values())!t.host&&t._target&&n.has(t._target)&&(t.host=n.get(t._target))}f(W,"ingestDnsRecords");async function et(e={}){const{serviceType:o="_adb-tls-connect._tcp.local",address:n,family:s,port:t=5353,timeoutMs:r=3e3,multicastInterface:a}=e;if(s!==void 0&&s!==4&&s!==6)throw new Error(`Invalid family: ${s} (must be 4 or 6)`);if(!$(t))throw new Error(`Invalid port: ${t}`);if(!Number.isInteger(r)||r<=0)throw new Error(`Invalid timeoutMs: ${r} (must be a positive integer)`);if(n!==void 0&&typeof n!="string")throw new Error(`Invalid address: ${n} (must be a string)`);if(a!==void 0&&typeof a!="string")throw new Error(`Invalid multicastInterface: ${a} (must be a string)`);const c=typeof n=="string"?h.isIP(n):0;if(s!==void 0&&c!==0&&c!==s)throw new Error(`Invalid address: ${n} (not an IPv${s} address)`);const i=s??(c===6?6:4),l=n??(i===6?"ff02::fb":"224.0.0.251"),g=F(o),m=Q(l),u=C.createSocket({type:i===6?"udp6":"udp4",reuseAddr:!0}),p=new Map,I=new Map;let w=!1;return new Promise((_,B)=>{const E=f((d,v)=>{w||(w=!0,clearTimeout(A),u.removeAllListeners(),u.close(),d(v))},"finish");u.on("error",d=>E(B,d)),u.on("message",d=>{try{W(z(d),p,I,i)}catch(v){x.log.debug(`discover.mdns: ignoring unparseable response - ${v.message}`)}});const A=setTimeout(()=>{E(_,Array.from(p.values()).filter(d=>d.host&&d.port).map(d=>({name:d.name,host:d.host,port:d.port,txt:d.txt})))},r);u.bind(m?t:0,()=>{if(m)try{a&&u.setMulticastInterface(a),u.addMembership(l,a)}catch(d){x.log.debug(`discover.mdns: couldn't join multicast group ${l} - ${d.message}`)}try{u.setMulticastTTL(255)}catch(d){x.log.debug(`discover.mdns: couldn't set multicast TTL - ${d.message}`)}x.log.debug(`discover.mdns: querying ${o} via ${l}:${t}`),u.send(g,t,l,d=>{d&&E(B,d)})})})}f(et,"mdns");export{et as mdns,tt as subnet};
2
+ //# sourceMappingURL=discover.mjs.map
@@ -1,17 +1,2 @@
1
- /*
2
- Copyright 2026 CLDMV/Shinrai
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
16
-
17
- import{self}from"@cldmv/slothlet/runtime";import{parseListing,quoteShellArg}from"./utils.mjs";import{readFile,writeFile,open,rename,unlink}from"node:fs/promises";import{brotliCompress,brotliDecompress}from"node:zlib";import{promisify}from"node:util";import path from"node:path";import{randomUUID}from"node:crypto";const brotliCompressAsync=promisify(brotliCompress);const brotliDecompressAsync=promisify(brotliDecompress);function assertValidMode(mode){if(!Number.isInteger(mode)||mode<0||mode>4095){throw new Error(`Invalid mode: ${mode} (must be an integer between 0 and 0o7777)`)}return mode}const SYNC_ID_SEND="SEND";const SYNC_ID_RECV="RECV";const SYNC_ID_LIST="LIST";const SYNC_ID_DENT="DENT";const SYNC_ID_DATA="DATA";const SYNC_ID_DONE="DONE";const SYNC_ID_OKAY="OKAY";const SYNC_ID_FAIL="FAIL";const SYNC_ID_QUIT="QUIT";const SYNC_DATA_MAX=64*1024;const SYNC_DENT_HEADER_SIZE=20;const SYNC_ID_SEND_V2="SND2";const SYNC_ID_RECV_V2="RCV2";const SYNC_ID_STAT_V2="STA2";const SYNC_ID_LIST_V2="LIS2";const SYNC_ID_DENT_V2="DNT2";const SYNC_FLAG_NONE=0;const SYNC_FLAG_BROTLI=1;const SYNC_BROTLI_INPUT_MAX=48*1024;const SYNC_SEND_V2_SETUP_SIZE=12;const SYNC_RECV_V2_SETUP_SIZE=8;const SYNC_STAT_V2_SIZE=72;const SYNC_DENT_V2_TAIL_SIZE=72;const SYNC_MAX_NAME_LEN=4096;const SYNC_BROTLI_OUTPUT_MAX=SYNC_DATA_MAX;const S_IFMT=61440;const S_IFDIR=16384;const S_IFREG=32768;const S_IFLNK=40960;function buildSyncFrame(id,valueOrPayload){const payload=Buffer.isBuffer(valueOrPayload)?valueOrPayload:Buffer.alloc(0);const value=Buffer.isBuffer(valueOrPayload)?valueOrPayload.length:valueOrPayload;const header=Buffer.alloc(8);header.write(id,0,4,"ascii");header.writeUInt32LE(value>>>0,4);return Buffer.concat([header,payload])}function createSyncFrameReader(stream){let buffer=Buffer.alloc(0);const pending=[];let waiter=null;let endError=null;function drain(){while(buffer.length>=8){const id=buffer.toString("ascii",0,4);const value=buffer.readUInt32LE(4);if(buffer.length<8+value)return;const payload=Buffer.from(buffer.subarray(8,8+value));buffer=buffer.subarray(8+value);pending.push({id,value,payload})}if(pending.length>0&&waiter){const resolve=waiter.resolve;waiter=null;resolve()}}function endWith(error){if(endError)return;endError=error||new Error("Sync stream ended before a terminal frame arrived");if(waiter){const reject=waiter.reject;waiter=null;reject(endError)}}stream.on("data",chunk=>{buffer=Buffer.concat([buffer,Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk)]);drain()});stream.on("close",()=>endWith());stream.on("error",error=>endWith(error));return{async next(){while(pending.length===0){if(endError)throw endError;await new Promise((resolve,reject)=>{waiter={resolve,reject}})}return pending.shift()}}}function createListFrameReader(stream){let buffer=Buffer.alloc(0);const pending=[];let waiter=null;let endError=null;function drain(){for(;;){if(buffer.length<4)break;const id=buffer.toString("ascii",0,4);if(id===SYNC_ID_DENT){if(buffer.length<SYNC_DENT_HEADER_SIZE)break;const mode=buffer.readUInt32LE(4);const size=buffer.readUInt32LE(8);const mtime=buffer.readUInt32LE(12);const namelen=buffer.readUInt32LE(16);if(buffer.length<SYNC_DENT_HEADER_SIZE+namelen)break;const name=buffer.toString("utf8",SYNC_DENT_HEADER_SIZE,SYNC_DENT_HEADER_SIZE+namelen);buffer=buffer.subarray(SYNC_DENT_HEADER_SIZE+namelen);pending.push({id,mode,size,mtime,name});continue}if(buffer.length<8)break;const value=buffer.readUInt32LE(4);if(buffer.length<8+value)break;const payload=Buffer.from(buffer.subarray(8,8+value));buffer=buffer.subarray(8+value);pending.push({id,value,payload})}if(pending.length>0&&waiter){const resolve=waiter.resolve;waiter=null;resolve()}}function endWith(error){if(endError)return;endError=error||new Error("Sync stream ended before a DONE/FAIL frame arrived");if(waiter){const reject=waiter.reject;waiter=null;reject(endError)}}stream.on("data",chunk=>{buffer=Buffer.concat([buffer,Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk)]);drain()});stream.on("close",()=>endWith());stream.on("error",error=>endWith(error));return{async next(){while(pending.length===0){if(endError)throw endError;await new Promise((resolve,reject)=>{waiter={resolve,reject}})}return pending.shift()}}}function createRawByteReader(stream){let buffer=Buffer.alloc(0);const waiters=[];let endError=null;function drain(){while(waiters.length>0&&buffer.length>=waiters[0].size){const{size,resolve}=waiters.shift();resolve(Buffer.from(buffer.subarray(0,size)));buffer=buffer.subarray(size)}}function endWith(error){if(endError)return;endError=error||new Error("Sync stream ended before enough bytes arrived");while(waiters.length>0){waiters.shift().reject(endError)}}stream.on("data",chunk=>{buffer=Buffer.concat([buffer,Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk)]);drain()});stream.on("close",()=>endWith());stream.on("error",error=>endWith(error));return{readBytes(size){if(endError&&buffer.length<size)return Promise.reject(endError);return new Promise((resolve,reject)=>{waiters.push({size,resolve,reject});drain()})}}}function parseStatV2Record(buf){return{id:buf.toString("ascii",0,4),error:buf.readUInt32LE(4),dev:buf.readBigUInt64LE(8),ino:buf.readBigUInt64LE(16),mode:buf.readUInt32LE(24),nlink:buf.readUInt32LE(28),uid:buf.readUInt32LE(32),gid:buf.readUInt32LE(36),size:buf.readBigUInt64LE(40),atime:buf.readBigInt64LE(48),mtime:buf.readBigInt64LE(56),ctime:buf.readBigInt64LE(64)}}function parseDentV2Tail(buf){return{error:buf.readUInt32LE(0),dev:buf.readBigUInt64LE(4),ino:buf.readBigUInt64LE(12),mode:buf.readUInt32LE(20),nlink:buf.readUInt32LE(24),uid:buf.readUInt32LE(28),gid:buf.readUInt32LE(32),size:buf.readBigUInt64LE(36),atime:buf.readBigInt64LE(44),mtime:buf.readBigInt64LE(52),ctime:buf.readBigInt64LE(60),namelen:buf.readUInt32LE(68)}}function createListV2FrameReader(stream){const raw=createRawByteReader(stream);return{async next(){const idBuf=await raw.readBytes(4);const id=idBuf.toString("ascii");if(id===SYNC_ID_DENT_V2){const tail=parseDentV2Tail(await raw.readBytes(SYNC_DENT_V2_TAIL_SIZE));if(tail.namelen>SYNC_MAX_NAME_LEN){throw new Error(`list_v2 entry name length ${tail.namelen} exceeds the maximum of ${SYNC_MAX_NAME_LEN}`)}const name=(await raw.readBytes(tail.namelen)).toString("utf8");return{id,...tail,name}}if(id===SYNC_ID_DONE){await raw.readBytes(4);return{id}}if(id===SYNC_ID_FAIL){const value=(await raw.readBytes(4)).readUInt32LE(0);if(value>SYNC_DATA_MAX){throw new Error(`list_v2 FAIL payload length ${value} exceeds the maximum of ${SYNC_DATA_MAX}`)}const payload=await raw.readBytes(value);return{id,payload}}throw new Error(`Unexpected SYNC frame during list_v2: ${id}`)}}}async function quitSyncStream(stream){try{await stream.write(buildSyncFrame(SYNC_ID_QUIT,Buffer.alloc(0)))}catch{}stream.close()}async function writeFully(fileHandle,buffer){let offset=0;while(offset<buffer.length){const{bytesWritten}=await fileHandle.write(buffer,offset,buffer.length-offset);if(bytesWritten===0){throw new Error("fileHandle.write() returned 0 bytes written - refusing to loop forever")}offset+=bytesWritten}}async function push(___socket,streamManager,localPath,remotePath,options={}){const{onProgress,mode=420}=options;const data=await readFile(localPath);const stream=await streamManager.openStream("sync:");const reader=createSyncFrameReader(stream);try{const pathAndMode=Buffer.from(`${remotePath},${mode.toString(10)}`,"utf8");await stream.write(buildSyncFrame(SYNC_ID_SEND,pathAndMode));let offset=0;while(offset<data.length){const chunk=data.subarray(offset,Math.min(offset+SYNC_DATA_MAX,data.length));await stream.write(buildSyncFrame(SYNC_ID_DATA,chunk));offset+=chunk.length;if(onProgress)onProgress({bytesTransferred:offset,totalBytes:data.length})}await stream.write(buildSyncFrame(SYNC_ID_DONE,Math.floor(Date.now()/1e3)));const frame=await reader.next();if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC push failed: ${frame.payload.toString("utf8")}`)}if(frame.id!==SYNC_ID_OKAY){throw new Error(`Unexpected SYNC frame during push: ${frame.id}`)}}finally{await quitSyncStream(stream)}}async function pushV2(___socket,streamManager,localPath,remotePath,options={}){const{onProgress,mode=420,compression="none"}=options;assertValidMode(mode);if(compression!=="none"&&compression!=="brotli"){throw new Error(`Invalid compression: ${compression} (must be "none" or "brotli")`)}const flag=compression==="brotli"?SYNC_FLAG_BROTLI:SYNC_FLAG_NONE;const fileHandle=await open(localPath,"r");try{const{size:totalBytes}=await fileHandle.stat();const stream=await streamManager.openStream("sync:");const reader=createSyncFrameReader(stream);try{await stream.write(buildSyncFrame(SYNC_ID_SEND_V2,Buffer.from(remotePath,"utf8")));const setup=Buffer.alloc(SYNC_SEND_V2_SETUP_SIZE);setup.write(SYNC_ID_SEND_V2,0,4,"ascii");setup.writeUInt32LE(mode>>>0,4);setup.writeUInt32LE(flag,8);await stream.write(setup);const inputChunkMax=flag===SYNC_FLAG_BROTLI?SYNC_BROTLI_INPUT_MAX:SYNC_DATA_MAX;let bytesTransferred=0;for(;;){const buffer=Buffer.alloc(inputChunkMax);const{bytesRead}=await fileHandle.read(buffer,0,inputChunkMax,null);if(bytesRead===0)break;const chunk=bytesRead===inputChunkMax?buffer:buffer.subarray(0,bytesRead);const wireChunk=flag===SYNC_FLAG_BROTLI?await brotliCompressAsync(chunk):chunk;if(wireChunk.length>SYNC_DATA_MAX){throw new Error(`Compressed SYNC DATA chunk exceeds the protocol ceiling: ${wireChunk.length} bytes (max ${SYNC_DATA_MAX})`)}await stream.write(buildSyncFrame(SYNC_ID_DATA,wireChunk));bytesTransferred+=bytesRead;if(onProgress)onProgress({bytesTransferred,totalBytes})}await stream.write(buildSyncFrame(SYNC_ID_DONE,Math.floor(Date.now()/1e3)));const frame=await reader.next();if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC send_v2 failed: ${frame.payload.toString("utf8")}`)}if(frame.id!==SYNC_ID_OKAY){throw new Error(`Unexpected SYNC frame during send_v2: ${frame.id}`)}}finally{await quitSyncStream(stream)}}finally{await fileHandle.close()}}async function pull(___socket,streamManager,remotePath,localPath,options={}){const{onProgress}=options;const stream=await streamManager.openStream("sync:");const reader=createSyncFrameReader(stream);try{await stream.write(buildSyncFrame(SYNC_ID_RECV,Buffer.from(remotePath,"utf8")));const chunks=[];let totalBytes=0;for(;;){const frame=await reader.next();if(frame.id===SYNC_ID_DATA){chunks.push(frame.payload);totalBytes+=frame.payload.length;if(onProgress)onProgress({bytesTransferred:totalBytes})}else if(frame.id===SYNC_ID_DONE){break}else if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC pull failed: ${frame.payload.toString("utf8")}`)}else{throw new Error(`Unexpected SYNC frame during pull: ${frame.id}`)}}await writeFile(localPath,Buffer.concat(chunks))}finally{await quitSyncStream(stream)}}async function pullV2(___socket,streamManager,remotePath,localPath,options={}){const{onProgress,compression="none"}=options;if(compression!=="none"&&compression!=="brotli"){throw new Error(`Invalid compression: ${compression} (must be "none" or "brotli")`)}const flag=compression==="brotli"?SYNC_FLAG_BROTLI:SYNC_FLAG_NONE;const stream=await streamManager.openStream("sync:");const reader=createSyncFrameReader(stream);try{await stream.write(buildSyncFrame(SYNC_ID_RECV_V2,Buffer.from(remotePath,"utf8")));const setup=Buffer.alloc(SYNC_RECV_V2_SETUP_SIZE);setup.write(SYNC_ID_RECV_V2,0,4,"ascii");setup.writeUInt32LE(flag,4);await stream.write(setup);const tempPath=path.join(path.dirname(localPath),`.${path.basename(localPath)}.${randomUUID()}.part`);try{const fileHandle=await open(tempPath,"w");try{let bytesTransferred=0;for(;;){const frame=await reader.next();if(frame.id===SYNC_ID_DATA){let chunk=frame.payload;if(flag===SYNC_FLAG_BROTLI){try{chunk=await brotliDecompressAsync(frame.payload,{maxOutputLength:SYNC_BROTLI_OUTPUT_MAX})}catch(decompressError){if(decompressError.code==="ERR_BUFFER_TOO_LARGE"){throw new Error(`recv_v2 brotli chunk decompressed past the ${SYNC_BROTLI_OUTPUT_MAX}-byte cap - rejecting as a likely decompression bomb`,{cause:decompressError})}throw decompressError}}await writeFully(fileHandle,chunk);bytesTransferred+=frame.payload.length;if(onProgress)onProgress({bytesTransferred})}else if(frame.id===SYNC_ID_DONE){break}else if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC recv_v2 failed: ${frame.payload.toString("utf8")}`)}else{throw new Error(`Unexpected SYNC frame during recv_v2: ${frame.id}`)}}}finally{await fileHandle.close()}await rename(tempPath,localPath)}catch(error){await unlink(tempPath).catch(()=>{});throw error}}finally{await quitSyncStream(stream)}}async function listOverStream(stream,remotePath){const reader=createListFrameReader(stream);try{await stream.write(buildSyncFrame(SYNC_ID_LIST,Buffer.from(remotePath,"utf8")));const entries=[];for(;;){const frame=await reader.next();if(frame.id===SYNC_ID_DENT){entries.push({name:frame.name,size:frame.size,mtime:frame.mtime,mode:frame.mode,isDirectory:(frame.mode&S_IFMT)===S_IFDIR,isFile:(frame.mode&S_IFMT)===S_IFREG,isSymlink:(frame.mode&S_IFMT)===S_IFLNK})}else if(frame.id===SYNC_ID_DONE){break}else if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC list failed: ${frame.payload.toString("utf8")}`)}else{throw new Error(`Unexpected SYNC frame during list: ${frame.id}`)}}return entries}finally{await quitSyncStream(stream)}}async function listSync(___socket,streamManager,remotePath){const stream=await streamManager.openStream("sync:");return await listOverStream(stream,remotePath)}async function listV2(___socket,streamManager,remotePath){const stream=await streamManager.openStream("sync:");const reader=createListV2FrameReader(stream);try{await stream.write(buildSyncFrame(SYNC_ID_LIST_V2,Buffer.from(remotePath,"utf8")));const entries=[];for(;;){const frame=await reader.next();if(frame.id===SYNC_ID_DENT_V2){entries.push({name:frame.name,mode:frame.mode,size:frame.size,atime:frame.atime,mtime:frame.mtime,ctime:frame.ctime,uid:frame.uid,gid:frame.gid,nlink:frame.nlink,dev:frame.dev,ino:frame.ino,isDirectory:(frame.mode&S_IFMT)===S_IFDIR,isFile:(frame.mode&S_IFMT)===S_IFREG,isSymlink:(frame.mode&S_IFMT)===S_IFLNK})}else if(frame.id===SYNC_ID_DONE){break}else if(frame.id===SYNC_ID_FAIL){throw new Error(`SYNC list_v2 failed: ${frame.payload.toString("utf8")}`)}}return entries}finally{await quitSyncStream(stream)}}async function listShell(socket,streamManager,remotePath){const output=await self.shell.execute(socket,streamManager,`ls -la ${quoteShellArg(remotePath)}`);return parseListing(output)}async function list(socket,streamManager,remotePath){let stream;try{stream=await streamManager.openStream("sync:")}catch{return await listShell(socket,streamManager,remotePath)}return await listOverStream(stream,remotePath)}async function stat(socket,streamManager,remotePath){return await self.shell.execute(socket,streamManager,`stat ${quoteShellArg(remotePath)}`)}async function statV2(___socket,streamManager,remotePath){const stream=await streamManager.openStream("sync:");const raw=createRawByteReader(stream);try{await stream.write(buildSyncFrame(SYNC_ID_STAT_V2,Buffer.from(remotePath,"utf8")));const record=parseStatV2Record(await raw.readBytes(SYNC_STAT_V2_SIZE));if(record.id!==SYNC_ID_STAT_V2){throw new Error(`Unexpected SYNC frame during stat_v2: ${record.id}`)}if(record.error!==0){throw new Error(`SYNC stat_v2 failed for ${remotePath}: errno ${record.error}`)}return{mode:record.mode,size:record.size,atime:record.atime,mtime:record.mtime,ctime:record.ctime,uid:record.uid,gid:record.gid,nlink:record.nlink,dev:record.dev,ino:record.ino,isDirectory:(record.mode&S_IFMT)===S_IFDIR,isFile:(record.mode&S_IFMT)===S_IFREG,isSymlink:(record.mode&S_IFMT)===S_IFLNK}}finally{await quitSyncStream(stream)}}async function mkdir(socket,streamManager,remotePath,mode=493){assertValidMode(mode);const command=`mkdir -p ${quoteShellArg(remotePath)} && chmod ${mode.toString(8)} ${quoteShellArg(remotePath)}`;return await self.shell.execute(socket,streamManager,command)}async function remove(socket,streamManager,remotePath,recursive=false){const flag=recursive?"-rf":"-f";const command=`rm ${flag} ${quoteShellArg(remotePath)}`;return await self.shell.execute(socket,streamManager,command)}async function move(socket,streamManager,sourcePath,destPath){const command=`mv ${quoteShellArg(sourcePath)} ${quoteShellArg(destPath)}`;return await self.shell.execute(socket,streamManager,command)}async function copy(socket,streamManager,sourcePath,destPath,recursive=false){const flag=recursive?"-r":"";const command=`cp ${flag} ${quoteShellArg(sourcePath)} ${quoteShellArg(destPath)}`;return await self.shell.execute(socket,streamManager,command)}async function chmod(socket,streamManager,remotePath,mode,recursive=false){assertValidMode(mode);const flag=recursive?"-R":"";const command=`chmod ${flag} ${mode.toString(8)} ${quoteShellArg(remotePath)}`;return await self.shell.execute(socket,streamManager,command)}async function diskUsage(socket,streamManager,path2="/"){const command=`df -h ${quoteShellArg(path2)}`;return await self.shell.execute(socket,streamManager,command)}async function find(socket,streamManager,path2,pattern,options={}){let command=`find ${quoteShellArg(path2)}`;if(options.maxDepth!==void 0){if(!Number.isInteger(options.maxDepth)||options.maxDepth<0){throw new Error(`Invalid maxDepth: ${options.maxDepth} (must be a non-negative integer)`)}command+=` -maxdepth ${options.maxDepth}`}if(options.type!==void 0){if(!/^[bcdpfls]$/.test(options.type)){throw new Error(`Invalid type: ${options.type} (must be one of b, c, d, p, f, l, s)`)}command+=` -type ${options.type}`}command+=` -name ${quoteShellArg(pattern)}`;return await self.shell.execute(socket,streamManager,command)}export{chmod,copy,diskUsage,find,list,listShell,listSync,listV2,mkdir,move,pull,pullV2,push,pushV2,remove,stat,statV2};
1
+ var Q=Object.defineProperty;var f=(t,e)=>Q(t,"name",{value:e,configurable:!0});import{self as _}from"@cldmv/slothlet/runtime";import{parseListing as J,quoteShellArg as h}from"./utils.mjs";import{readFile as ee,writeFile as te,open as V,rename as re,unlink as ne}from"node:fs/promises";import{brotliCompress as ie,brotliDecompress as ae}from"node:zlib";import{promisify as z}from"node:util";import b from"node:path";import{randomUUID as oe}from"node:crypto";const se=z(ie),ce=z(ae);function T(t){if(!Number.isInteger(t)||t<0||t>4095)throw new Error(`Invalid mode: ${t} (must be an integer between 0 and 0o7777)`);return t}f(T,"assertValidMode");const fe="SEND",le="RECV",de="LIST",M="DENT",D="DATA",g="DONE",O="OKAY",I="FAIL",ue="QUIT",B=64*1024,L=20,j="SND2",Z="RCV2",G="STA2",me="LIS2",H="DNT2",P=0,$=1,we=48*1024,ye=12,he=8,pe=72,_e=72,W=4096,X=B,S=61440,k=16384,A=32768,R=40960;function p(t,e){const i=Buffer.isBuffer(e)?e:Buffer.alloc(0),r=Buffer.isBuffer(e)?e.length:e,n=Buffer.alloc(8);return n.write(t,0,4,"ascii"),n.writeUInt32LE(r>>>0,4),Buffer.concat([n,i])}f(p,"buildSyncFrame");function U(t){let e=Buffer.alloc(0);const i=[];let r=null,n=null;function o(){for(;e.length>=8;){const s=e.toString("ascii",0,4),c=e.readUInt32LE(4);if(e.length<8+c)return;const u=Buffer.from(e.subarray(8,8+c));e=e.subarray(8+c),i.push({id:s,value:c,payload:u})}if(i.length>0&&r){const s=r.resolve;r=null,s()}}f(o,"drain");function a(s){if(!n&&(n=s||new Error("Sync stream ended before a terminal frame arrived"),r)){const c=r.reject;r=null,c(n)}}return f(a,"endWith"),t.on("data",s=>{e=Buffer.concat([e,Buffer.isBuffer(s)?s:Buffer.from(s)]),o()}),t.on("close",()=>a()),t.on("error",s=>a(s)),{async next(){for(;i.length===0;){if(n)throw n;await new Promise((s,c)=>{r={resolve:s,reject:c}})}return i.shift()}}}f(U,"createSyncFrameReader");function Se(t){let e=Buffer.alloc(0);const i=[];let r=null,n=null;function o(){for(;!(e.length<4);){const s=e.toString("ascii",0,4);if(s===M){if(e.length<L)break;const d=e.readUInt32LE(4),l=e.readUInt32LE(8),y=e.readUInt32LE(12),m=e.readUInt32LE(16);if(e.length<L+m)break;const w=e.toString("utf8",L,L+m);e=e.subarray(L+m),i.push({id:s,mode:d,size:l,mtime:y,name:w});continue}if(e.length<8)break;const c=e.readUInt32LE(4);if(e.length<8+c)break;const u=Buffer.from(e.subarray(8,8+c));e=e.subarray(8+c),i.push({id:s,value:c,payload:u})}if(i.length>0&&r){const s=r.resolve;r=null,s()}}f(o,"drain");function a(s){if(!n&&(n=s||new Error("Sync stream ended before a DONE/FAIL frame arrived"),r)){const c=r.reject;r=null,c(n)}}return f(a,"endWith"),t.on("data",s=>{e=Buffer.concat([e,Buffer.isBuffer(s)?s:Buffer.from(s)]),o()}),t.on("close",()=>a()),t.on("error",s=>a(s)),{async next(){for(;i.length===0;){if(n)throw n;await new Promise((s,c)=>{r={resolve:s,reject:c}})}return i.shift()}}}f(Se,"createListFrameReader");function K(t){let e=Buffer.alloc(0);const i=[];let r=null;function n(){for(;i.length>0&&e.length>=i[0].size;){const{size:a,resolve:s}=i.shift();s(Buffer.from(e.subarray(0,a))),e=e.subarray(a)}}f(n,"drain");function o(a){if(!r)for(r=a||new Error("Sync stream ended before enough bytes arrived");i.length>0;)i.shift().reject(r)}return f(o,"endWith"),t.on("data",a=>{e=Buffer.concat([e,Buffer.isBuffer(a)?a:Buffer.from(a)]),n()}),t.on("close",()=>o()),t.on("error",a=>o(a)),{readBytes(a){return r&&e.length<a?Promise.reject(r):new Promise((s,c)=>{i.push({size:a,resolve:s,reject:c}),n()})}}}f(K,"createRawByteReader");function Ee(t){return{id:t.toString("ascii",0,4),error:t.readUInt32LE(4),dev:t.readBigUInt64LE(8),ino:t.readBigUInt64LE(16),mode:t.readUInt32LE(24),nlink:t.readUInt32LE(28),uid:t.readUInt32LE(32),gid:t.readUInt32LE(36),size:t.readBigUInt64LE(40),atime:t.readBigInt64LE(48),mtime:t.readBigInt64LE(56),ctime:t.readBigInt64LE(64)}}f(Ee,"parseStatV2Record");function ge(t){return{error:t.readUInt32LE(0),dev:t.readBigUInt64LE(4),ino:t.readBigUInt64LE(12),mode:t.readUInt32LE(20),nlink:t.readUInt32LE(24),uid:t.readUInt32LE(28),gid:t.readUInt32LE(32),size:t.readBigUInt64LE(36),atime:t.readBigInt64LE(44),mtime:t.readBigInt64LE(52),ctime:t.readBigInt64LE(60),namelen:t.readUInt32LE(68)}}f(ge,"parseDentV2Tail");function Ie(t){const e=K(t);return{async next(){const r=(await e.readBytes(4)).toString("ascii");if(r===H){const n=ge(await e.readBytes(_e));if(n.namelen>W)throw new Error(`list_v2 entry name length ${n.namelen} exceeds the maximum of ${W}`);const o=(await e.readBytes(n.namelen)).toString("utf8");return{id:r,...n,name:o}}if(r===g)return await e.readBytes(4),{id:r};if(r===I){const n=(await e.readBytes(4)).readUInt32LE(0);if(n>B)throw new Error(`list_v2 FAIL payload length ${n} exceeds the maximum of ${B}`);const o=await e.readBytes(n);return{id:r,payload:o}}throw new Error(`Unexpected SYNC frame during list_v2: ${r}`)}}}f(Ie,"createListV2FrameReader");async function N(t){try{await t.write(p(ue,Buffer.alloc(0)))}catch{}t.close()}f(N,"quitSyncStream");async function Be(t,e){let i=0;for(;i<e.length;){const{bytesWritten:r}=await t.write(e,i,e.length-i);if(r===0)throw new Error("fileHandle.write() returned 0 bytes written - refusing to loop forever");i+=r}}f(Be,"writeFully");async function be(t,e,i,r,n={}){const{onProgress:o,mode:a=420}=n,s=await ee(i),c=await e.openStream("sync:"),u=U(c);try{const d=Buffer.from(`${r},${a.toString(10)}`,"utf8");await c.write(p(fe,d));let l=0;for(;l<s.length;){const m=s.subarray(l,Math.min(l+B,s.length));await c.write(p(D,m)),l+=m.length,o&&o({bytesTransferred:l,totalBytes:s.length})}await c.write(p(g,Math.floor(Date.now()/1e3)));const y=await u.next();if(y.id===I)throw new Error(`SYNC push failed: ${y.payload.toString("utf8")}`);if(y.id!==O)throw new Error(`Unexpected SYNC frame during push: ${y.id}`)}finally{await N(c)}}f(be,"push");async function Te(t,e,i,r,n={}){const{onProgress:o,mode:a=420,compression:s="none"}=n;if(T(a),s!=="none"&&s!=="brotli")throw new Error(`Invalid compression: ${s} (must be "none" or "brotli")`);const c=s==="brotli"?$:P,u=await V(i,"r");try{const{size:d}=await u.stat(),l=await e.openStream("sync:"),y=U(l);try{await l.write(p(j,Buffer.from(r,"utf8")));const m=Buffer.alloc(ye);m.write(j,0,4,"ascii"),m.writeUInt32LE(a>>>0,4),m.writeUInt32LE(c,8),await l.write(m);const w=c===$?we:B;let x=0;for(;;){const Y=Buffer.alloc(w),{bytesRead:C}=await u.read(Y,0,w,null);if(C===0)break;const F=C===w?Y:Y.subarray(0,C),v=c===$?await se(F):F;if(v.length>B)throw new Error(`Compressed SYNC DATA chunk exceeds the protocol ceiling: ${v.length} bytes (max ${B})`);await l.write(p(D,v)),x+=C,o&&o({bytesTransferred:x,totalBytes:d})}await l.write(p(g,Math.floor(Date.now()/1e3)));const E=await y.next();if(E.id===I)throw new Error(`SYNC send_v2 failed: ${E.payload.toString("utf8")}`);if(E.id!==O)throw new Error(`Unexpected SYNC frame during send_v2: ${E.id}`)}finally{await N(l)}}finally{await u.close()}}f(Te,"pushV2");async function ke(t,e,i,r,n={}){const{onProgress:o}=n,a=await e.openStream("sync:"),s=U(a);try{await a.write(p(le,Buffer.from(i,"utf8")));const c=[];let u=0;for(;;){const d=await s.next();if(d.id===D)c.push(d.payload),u+=d.payload.length,o&&o({bytesTransferred:u});else{if(d.id===g)break;throw d.id===I?new Error(`SYNC pull failed: ${d.payload.toString("utf8")}`):new Error(`Unexpected SYNC frame during pull: ${d.id}`)}}await te(r,Buffer.concat(c))}finally{await N(a)}}f(ke,"pull");async function Ae(t,e,i,r,n={}){const{onProgress:o,compression:a="none"}=n;if(a!=="none"&&a!=="brotli")throw new Error(`Invalid compression: ${a} (must be "none" or "brotli")`);const s=a==="brotli"?$:P,c=await e.openStream("sync:"),u=U(c);try{await c.write(p(Z,Buffer.from(i,"utf8")));const d=Buffer.alloc(he);d.write(Z,0,4,"ascii"),d.writeUInt32LE(s,4),await c.write(d);const l=b.join(b.dirname(r),`.${b.basename(r)}.${oe()}.part`);try{const y=await V(l,"w");try{let m=0;for(;;){const w=await u.next();if(w.id===D){let x=w.payload;if(s===$)try{x=await ce(w.payload,{maxOutputLength:X})}catch(E){throw E.code==="ERR_BUFFER_TOO_LARGE"?new Error(`recv_v2 brotli chunk decompressed past the ${X}-byte cap - rejecting as a likely decompression bomb`,{cause:E}):E}await Be(y,x),m+=w.payload.length,o&&o({bytesTransferred:m})}else{if(w.id===g)break;throw w.id===I?new Error(`SYNC recv_v2 failed: ${w.payload.toString("utf8")}`):new Error(`Unexpected SYNC frame during recv_v2: ${w.id}`)}}}finally{await y.close()}await re(l,r)}catch(y){throw await ne(l).catch(()=>{}),y}}finally{await N(c)}}f(Ae,"pullV2");async function q(t,e){const i=Se(t);try{await t.write(p(de,Buffer.from(e,"utf8")));const r=[];for(;;){const n=await i.next();if(n.id===M)r.push({name:n.name,size:n.size,mtime:n.mtime,mode:n.mode,isDirectory:(n.mode&S)===k,isFile:(n.mode&S)===A,isSymlink:(n.mode&S)===R});else{if(n.id===g)break;throw n.id===I?new Error(`SYNC list failed: ${n.payload.toString("utf8")}`):new Error(`Unexpected SYNC frame during list: ${n.id}`)}}return r}finally{await N(t)}}f(q,"listOverStream");async function Re(t,e,i){const r=await e.openStream("sync:");return await q(r,i)}f(Re,"listSync");async function Fe(t,e,i){const r=await e.openStream("sync:"),n=Ie(r);try{await r.write(p(me,Buffer.from(i,"utf8")));const o=[];for(;;){const a=await n.next();if(a.id===H)o.push({name:a.name,mode:a.mode,size:a.size,atime:a.atime,mtime:a.mtime,ctime:a.ctime,uid:a.uid,gid:a.gid,nlink:a.nlink,dev:a.dev,ino:a.ino,isDirectory:(a.mode&S)===k,isFile:(a.mode&S)===A,isSymlink:(a.mode&S)===R});else{if(a.id===g)break;if(a.id===I)throw new Error(`SYNC list_v2 failed: ${a.payload.toString("utf8")}`)}}return o}finally{await N(r)}}f(Fe,"listV2");async function Ne(t,e,i){const r=await _.shell.execute(t,e,`ls -la ${h(i)}`);return J(r)}f(Ne,"listShell");async function Ve(t,e,i){let r;try{r=await e.openStream("sync:")}catch{return await Ne(t,e,i)}return await q(r,i)}f(Ve,"list");async function ze(t,e,i){return await _.shell.execute(t,e,`stat ${h(i)}`)}f(ze,"stat");async function Me(t,e,i){const r=await e.openStream("sync:"),n=K(r);try{await r.write(p(G,Buffer.from(i,"utf8")));const o=Ee(await n.readBytes(pe));if(o.id!==G)throw new Error(`Unexpected SYNC frame during stat_v2: ${o.id}`);if(o.error!==0)throw new Error(`SYNC stat_v2 failed for ${i}: errno ${o.error}`);return{mode:o.mode,size:o.size,atime:o.atime,mtime:o.mtime,ctime:o.ctime,uid:o.uid,gid:o.gid,nlink:o.nlink,dev:o.dev,ino:o.ino,isDirectory:(o.mode&S)===k,isFile:(o.mode&S)===A,isSymlink:(o.mode&S)===R}}finally{await N(r)}}f(Me,"statV2");async function Oe(t,e,i,r=493){T(r);const n=`mkdir -p ${h(i)} && chmod ${r.toString(8)} ${h(i)}`;return await _.shell.execute(t,e,n)}f(Oe,"mkdir");async function je(t,e,i,r=!1){const o=`rm ${r?"-rf":"-f"} ${h(i)}`;return await _.shell.execute(t,e,o)}f(je,"remove");async function Ze(t,e,i,r){const n=`mv ${h(i)} ${h(r)}`;return await _.shell.execute(t,e,n)}f(Ze,"move");async function Ge(t,e,i,r,n=!1){const a=`cp ${n?"-r":""} ${h(i)} ${h(r)}`;return await _.shell.execute(t,e,a)}f(Ge,"copy");async function He(t,e,i,r,n=!1){T(r);const a=`chmod ${n?"-R":""} ${r.toString(8)} ${h(i)}`;return await _.shell.execute(t,e,a)}f(He,"chmod");async function Pe(t,e,i="/"){const r=`df -h ${h(i)}`;return await _.shell.execute(t,e,r)}f(Pe,"diskUsage");async function We(t,e,i,r,n={}){let o=`find ${h(i)}`;if(n.maxDepth!==void 0){if(!Number.isInteger(n.maxDepth)||n.maxDepth<0)throw new Error(`Invalid maxDepth: ${n.maxDepth} (must be a non-negative integer)`);o+=` -maxdepth ${n.maxDepth}`}if(n.type!==void 0){if(!/^[bcdpfls]$/.test(n.type))throw new Error(`Invalid type: ${n.type} (must be one of b, c, d, p, f, l, s)`);o+=` -type ${n.type}`}return o+=` -name ${h(r)}`,await _.shell.execute(t,e,o)}f(We,"find");export{He as chmod,Ge as copy,Pe as diskUsage,We as find,Ve as list,Ne as listShell,Re as listSync,Fe as listV2,Oe as mkdir,Ze as move,ke as pull,Ae as pullV2,be as push,Te as pushV2,je as remove,ze as stat,Me as statV2};
2
+ //# sourceMappingURL=files.mjs.map
@@ -1,17 +1,2 @@
1
- /*
2
- Copyright 2026 CLDMV/Shinrai
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
16
-
17
- import net from"node:net";async function start(___socket,streamManager,devicePort,options={}){const{localPort=0,host="127.0.0.1",onError}=options;const server=net.createServer(localSocket=>{let stream;let localSocketFailed=false;localSocket.on("error",error=>{localSocketFailed=true;if(stream)stream.close();if(onError)onError(error,localSocket)});(async()=>{try{stream=await streamManager.openStream(`tcp:${devicePort}`)}catch(error){localSocket.destroy();if(onError)onError(error,localSocket);return}if(localSocketFailed||localSocket.destroyed){stream.close();return}stream.on("data",data=>localSocket.write(data));stream.on("close",()=>localSocket.end());stream.on("error",error=>{stream.close();localSocket.destroy();if(onError)onError(error,localSocket)});localSocket.on("data",data=>{stream.write(data).catch(error=>{stream.close();localSocket.destroy();if(onError)onError(error,localSocket)})});localSocket.on("close",()=>stream.close())})()});await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(localPort,host,()=>{server.removeListener("error",reject);resolve()})});return{localPort:server.address().port,close(){return new Promise(resolve=>server.close(()=>resolve()))}}}export{start};
1
+ var p=Object.defineProperty;var a=(i,o)=>p(i,"name",{value:o,configurable:!0});import P from"node:net";async function _(i,o,f,m={}){const{localPort:y=0,host:u="127.0.0.1",onError:t}=m,n=P.createServer(r=>{let e,d=!1;r.on("error",s=>{d=!0,e&&e.close(),t&&t(s,r)}),(async()=>{try{e=await o.openStream(`tcp:${f}`)}catch(s){r.destroy(),t&&t(s,r);return}if(d||r.destroyed){e.close();return}e.on("data",s=>r.write(s)),e.on("close",()=>r.end()),e.on("error",s=>{e.close(),r.destroy(),t&&t(s,r)}),r.on("data",s=>{e.write(s).catch(w=>{e.close(),r.destroy(),t&&t(w,r)})}),r.on("close",()=>e.close())})()});return await new Promise((r,e)=>{n.once("error",e),n.listen(y,u,()=>{n.removeListener("error",e),r()})}),{localPort:n.address().port,close(){return new Promise(r=>n.close(()=>r()))}}}a(_,"start");export{_ as start};
2
+ //# sourceMappingURL=forward.mjs.map
@@ -1,17 +1,2 @@
1
- /*
2
- Copyright 2026 CLDMV/Shinrai
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
16
-
17
- import{self}from"@cldmv/slothlet/runtime";import path from"node:path";import{open}from"node:fs/promises";import{assertValidFlags}from"./utils.mjs";const EXEC_WRITE_CHUNK=64*1024;async function classic(socket,streamManager,localPath,options={}){const{flags=[],remoteDir="/data/local/tmp",onProgress}=options;const remotePath=path.posix.join(remoteDir,path.basename(localPath));try{await self.files.push(socket,streamManager,localPath,remotePath,{onProgress});return await self.shell.commands.installApk(socket,streamManager,remotePath,flags)}finally{await self.files.remove(socket,streamManager,remotePath).catch(()=>{})}}async function streaming(___socket,streamManager,localPath,options={}){const{flags=[],onProgress}=options;assertValidFlags(flags);const fileHandle=await open(localPath,"r");try{const{size:totalBytes}=await fileHandle.stat();const flagsStr=flags.length>0?` ${flags.join(" ")}`:"";const destination=`exec:cmd package install -S ${totalBytes}${flagsStr}`;const stream=await streamManager.openStream(destination);try{const outputChunks=[];let stopped=false;const closed=new Promise((resolve,reject)=>{stream.on("data",chunk=>{outputChunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk))});stream.once("close",()=>{stopped=true;resolve()});stream.once("error",error=>{stopped=true;reject(error)})});closed.catch(()=>{});let bytesTransferred=0;while(!stopped){const buffer=Buffer.alloc(EXEC_WRITE_CHUNK);const{bytesRead}=await fileHandle.read(buffer,0,EXEC_WRITE_CHUNK,null);if(bytesRead===0)break;if(stopped)break;await stream.write(bytesRead===EXEC_WRITE_CHUNK?buffer:buffer.subarray(0,bytesRead));bytesTransferred+=bytesRead;if(onProgress)onProgress({bytesTransferred,totalBytes})}await closed;if(bytesTransferred<totalBytes){throw new Error(`Exec stream closed before the full APK was sent (${bytesTransferred} of ${totalBytes} bytes transferred)`)}return Buffer.concat(outputChunks).toString("utf8")}finally{stream.close()}}finally{await fileHandle.close()}}export{classic,streaming};
1
+ var E=Object.defineProperty;var w=(a,e)=>E(a,"name",{value:e,configurable:!0});import{self as d}from"@cldmv/slothlet/runtime";import g from"node:path";import{open as _}from"node:fs/promises";import{assertValidFlags as $}from"./utils.mjs";const y=64*1024;async function A(a,e,l,p={}){const{flags:o=[],remoteDir:c="/data/local/tmp",onProgress:r}=p,t=g.posix.join(c,g.basename(l));try{return await d.files.push(a,e,l,t,{onProgress:r}),await d.shell.commands.installApk(a,e,t,o)}finally{await d.files.remove(a,e,t).catch(()=>{})}}w(A,"classic");async function H(a,e,l,p={}){const{flags:o=[],onProgress:c}=p;$(o);const r=await _(l,"r");try{const{size:t}=await r.stat(),B=o.length>0?` ${o.join(" ")}`:"",x=`exec:cmd package install -S ${t}${B}`,n=await e.openStream(x);try{const b=[];let m=!1;const h=new Promise((i,s)=>{n.on("data",f=>{b.push(Buffer.isBuffer(f)?f:Buffer.from(f))}),n.once("close",()=>{m=!0,i()}),n.once("error",f=>{m=!0,s(f)})});h.catch(()=>{});let u=0;for(;!m;){const i=Buffer.alloc(y),{bytesRead:s}=await r.read(i,0,y,null);if(s===0||m)break;await n.write(s===y?i:i.subarray(0,s)),u+=s,c&&c({bytesTransferred:u,totalBytes:t})}if(await h,u<t)throw new Error(`Exec stream closed before the full APK was sent (${u} of ${t} bytes transferred)`);return Buffer.concat(b).toString("utf8")}finally{n.close()}}finally{await r.close()}}w(H,"streaming");export{A as classic,H as streaming};
2
+ //# sourceMappingURL=install.mjs.map