@cldmv/droidsock 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -24
- package/dist/api/auth.mjs +2 -17
- package/dist/api/config.mjs +2 -17
- package/dist/api/connection.mjs +2 -17
- package/dist/api/device.mjs +2 -17
- package/dist/api/devices.mjs +2 -17
- package/dist/api/discover.mjs +2 -17
- package/dist/api/files.mjs +2 -17
- package/dist/api/forward.mjs +2 -17
- package/dist/api/install.mjs +2 -17
- package/dist/api/log.mjs +2 -17
- package/dist/api/pairing.mjs +2 -17
- package/dist/api/reboot.mjs +2 -17
- package/dist/api/reverse.mjs +2 -17
- package/dist/api/shell.mjs +2 -17
- package/dist/api/stream.mjs +2 -17
- package/dist/api/utils.mjs +5 -17
- package/dist/droidsock.mjs +2 -17
- package/dist/index.cjs +50 -0
- package/dist/index.mjs +2 -0
- package/dist/main.mjs +2 -0
- package/package.json +58 -42
- package/types/src/api/auth.d.mts +34 -0
- package/types/src/api/auth.d.mts.map +1 -0
- package/types/src/api/config.d.mts +50 -0
- package/types/src/api/config.d.mts.map +1 -0
- package/types/src/api/connection.d.mts +16 -0
- package/types/src/api/connection.d.mts.map +1 -0
- package/types/src/api/device.d.mts +41 -0
- package/types/src/api/device.d.mts.map +1 -0
- package/types/src/api/devices.d.mts +41 -0
- package/types/src/api/devices.d.mts.map +1 -0
- package/types/src/api/discover.d.mts +65 -0
- package/types/src/api/discover.d.mts.map +1 -0
- package/types/src/api/files.d.mts +228 -0
- package/types/src/api/files.d.mts.map +1 -0
- package/types/src/api/forward.d.mts +27 -0
- package/types/src/api/forward.d.mts.map +1 -0
- package/types/src/api/install.d.mts +54 -0
- package/types/src/api/install.d.mts.map +1 -0
- package/types/src/api/log.d.mts +37 -0
- package/types/src/api/log.d.mts.map +1 -0
- package/types/src/api/pairing.d.mts +30 -0
- package/types/src/api/pairing.d.mts.map +1 -0
- package/types/src/api/reboot.d.mts +33 -0
- package/types/src/api/reboot.d.mts.map +1 -0
- package/types/src/api/reverse.d.mts +26 -0
- package/types/src/api/reverse.d.mts.map +1 -0
- package/types/src/api/shell.d.mts +63 -0
- package/types/src/api/shell.d.mts.map +1 -0
- package/types/src/api/stream.d.mts +7 -0
- package/types/src/api/stream.d.mts.map +1 -0
- package/types/src/api/utils.d.mts +161 -0
- package/types/src/api/utils.d.mts.map +1 -0
- package/types/src/droidsock.d.mts +14 -0
- package/types/src/droidsock.d.mts.map +1 -0
- package/types/src/index.d.mts +2 -0
- package/types/src/index.d.mts.map +1 -0
- package/types/src/main.d.mts +3 -0
- package/types/src/main.d.mts.map +1 -0
- package/index.cjs +0 -46
- package/index.mjs +0 -44
- package/types/dist/api/auth.d.mts +0 -14
- package/types/dist/api/auth.d.mts.map +0 -1
- package/types/dist/api/config.d.mts +0 -52
- package/types/dist/api/config.d.mts.map +0 -1
- package/types/dist/api/connection.d.mts +0 -2
- package/types/dist/api/connection.d.mts.map +0 -1
- package/types/dist/api/device.d.mts +0 -4
- package/types/dist/api/device.d.mts.map +0 -1
- package/types/dist/api/devices.d.mts +0 -5
- package/types/dist/api/devices.d.mts.map +0 -1
- package/types/dist/api/discover.d.mts +0 -6
- package/types/dist/api/discover.d.mts.map +0 -1
- package/types/dist/api/files.d.mts +0 -85
- package/types/dist/api/files.d.mts.map +0 -1
- package/types/dist/api/forward.d.mts +0 -5
- package/types/dist/api/forward.d.mts.map +0 -1
- package/types/dist/api/install.d.mts +0 -3
- package/types/dist/api/install.d.mts.map +0 -1
- package/types/dist/api/log.d.mts +0 -21
- package/types/dist/api/log.d.mts.map +0 -1
- package/types/dist/api/pairing.d.mts +0 -2
- package/types/dist/api/pairing.d.mts.map +0 -1
- package/types/dist/api/reboot.d.mts +0 -2
- package/types/dist/api/reboot.d.mts.map +0 -1
- package/types/dist/api/reverse.d.mts +0 -6
- package/types/dist/api/reverse.d.mts.map +0 -1
- package/types/dist/api/shell.d.mts +0 -29
- package/types/dist/api/shell.d.mts.map +0 -1
- package/types/dist/api/stream.d.mts +0 -11
- package/types/dist/api/stream.d.mts.map +0 -1
- package/types/dist/api/utils.d.mts +0 -32
- package/types/dist/api/utils.d.mts.map +0 -1
- package/types/dist/droidsock.d.mts +0 -3
- package/types/dist/droidsock.d.mts.map +0 -1
- package/types/index.d.mts +0 -11
- package/types/index.d.mts.map +0 -1
package/dist/api/log.mjs
CHANGED
|
@@ -1,17 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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";function getConfig(){return self.config}function getPrefix(){return getConfig().get("eventPrefix","adb")}function debug(...args){if(getConfig().get("silent"))return;if(!getConfig().get("debug"))return;console.log(`[${getPrefix()}][DEBUG]`,...args)}function verbose(...args){if(getConfig().get("silent"))return;if(!getConfig().get("verbose")&&!getConfig().get("debug"))return;console.log(`[${getPrefix()}][VERBOSE]`,...args)}function info(...args){if(getConfig().get("silent"))return;console.log(`[${getPrefix()}][INFO]`,...args)}function warn(...args){if(getConfig().get("silent"))return;console.warn(`[${getPrefix()}][WARN]`,...args)}function error(...args){if(getConfig().get("silent"))return;console.error(`[${getPrefix()}][ERROR]`,...args)}function child(context){const childPrefix=`[${getPrefix()}][${context}]`;const cfg=getConfig();return{debug:(...args)=>{if(cfg.get("silent"))return;if(!cfg.get("debug"))return;console.log(`${childPrefix}[DEBUG]`,...args)},verbose:(...args)=>{if(cfg.get("silent"))return;if(!cfg.get("verbose")&&!cfg.get("debug"))return;console.log(`${childPrefix}[VERBOSE]`,...args)},info:(...args)=>{if(cfg.get("silent"))return;console.log(`${childPrefix}[INFO]`,...args)},warn:(...args)=>{if(cfg.get("silent"))return;console.warn(`${childPrefix}[WARN]`,...args)},error:(...args)=>{if(cfg.get("silent"))return;console.error(`${childPrefix}[ERROR]`,...args)}}}function getApi(){return{debug,verbose,info,warn,error,child}}export{child,debug,error,getApi,info,verbose,warn};
|
|
1
|
+
var f=Object.defineProperty;var e=(r,i)=>f(r,"name",{value:i,configurable:!0});import{self as u}from"@cldmv/slothlet/runtime";function t(){return u.config}e(t,"getConfig");function g(){return t().get("eventPrefix","adb")}e(g,"getPrefix");function l(...r){t().get("silent")||t().get("debug")&&console.log(`[${g()}][DEBUG]`,...r)}e(l,"debug");function s(...r){t().get("silent")||!t().get("verbose")&&!t().get("debug")||console.log(`[${g()}][VERBOSE]`,...r)}e(s,"verbose");function c(...r){t().get("silent")||console.log(`[${g()}][INFO]`,...r)}e(c,"info");function $(...r){t().get("silent")||console.warn(`[${g()}][WARN]`,...r)}e($,"warn");function b(...r){t().get("silent")||console.error(`[${g()}][ERROR]`,...r)}e(b,"error");function x(r){const i=`[${g()}][${r}]`,o=t();return{debug:e((...n)=>{o.get("silent")||o.get("debug")&&console.log(`${i}[DEBUG]`,...n)},"debug"),verbose:e((...n)=>{o.get("silent")||!o.get("verbose")&&!o.get("debug")||console.log(`${i}[VERBOSE]`,...n)},"verbose"),info:e((...n)=>{o.get("silent")||console.log(`${i}[INFO]`,...n)},"info"),warn:e((...n)=>{o.get("silent")||console.warn(`${i}[WARN]`,...n)},"warn"),error:e((...n)=>{o.get("silent")||console.error(`${i}[ERROR]`,...n)},"error")}}e(x,"child");function p(){return{debug:l,verbose:s,info:c,warn:$,error:b,child:x}}e(p,"getApi");export{x as child,l as debug,b as error,p as getApi,c as info,s as verbose,$ as warn};
|
|
2
|
+
//# sourceMappingURL=log.mjs.map
|
package/dist/api/pairing.mjs
CHANGED
|
@@ -1,17 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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 tls from"node:tls";import crypto from"node:crypto";import fs from"node:fs";import path from"node:path";import os from"node:os";import{self}from"@cldmv/slothlet/runtime";import{ed25519}from"@noble/curves/ed25519.js";import selfsigned from"selfsigned";const Point=ed25519.Point;const Fn=Point.Fn;const M_POINT=Point.fromHex("5ada7e4bf6ddd9adb6626d32131c6b5c51a1e347a3478f53cfcf441b88eed12e");const N_POINT=Point.fromHex("10e3df0ae37d8e7a99b5fe74b44672103dbddcbd06af680d71329a11693bc778");const CLIENT_NAME=Buffer.from("adb pair client","utf8");const SERVER_NAME=Buffer.from("adb pair server","utf8");function randomScalar(){return Fn.create(bytesToBigIntLE(crypto.randomBytes(64)))}function bytesToBigIntLE(bytes){let result=0n;for(let i=bytes.length-1;i>=0;i--){result=result<<8n|BigInt(bytes[i])}return result}function hashPassword(password){return crypto.createHash("sha512").update(password).digest()}function passwordToScalar(passwordHash){return Fn.create(bytesToBigIntLE(passwordHash))}function generateSpakeMessage(ephemeralScalar,passwordScalar){const ephemeralPublic=Point.BASE.multiply(ephemeralScalar);const mask=M_POINT.multiply(passwordScalar);return Buffer.from(ephemeralPublic.add(mask).toBytes())}function computeSharedSecret(ephemeralScalar,passwordScalar,theirMessage){const theirMasked=Point.fromBytes(theirMessage);const theirMask=N_POINT.multiply(passwordScalar);const theirEphemeralPublic=theirMasked.subtract(theirMask);const shared=theirEphemeralPublic.multiply(ephemeralScalar);return Buffer.from(shared.toBytes())}function updateLengthPrefixed(hash,value){const len=Buffer.alloc(8);len.writeBigUInt64LE(BigInt(value.length));hash.update(len);hash.update(value)}function deriveSessionKey({clientMsg,serverMsg,dhShared,passwordHash},keyLength){const hash=crypto.createHash("sha512");updateLengthPrefixed(hash,CLIENT_NAME);updateLengthPrefixed(hash,SERVER_NAME);updateLengthPrefixed(hash,clientMsg);updateLengthPrefixed(hash,serverMsg);updateLengthPrefixed(hash,dhShared);updateLengthPrefixed(hash,passwordHash);return hash.digest().subarray(0,keyLength)}const PAIRING_PACKET_VERSION=1;const PACKET_TYPE_SPAKE2_MSG=0;const PACKET_TYPE_PEER_INFO=1;function encodePairingPacket(type,payload){const header=Buffer.alloc(6);header.writeUInt8(PAIRING_PACKET_VERSION,0);header.writeUInt8(type,1);header.writeUInt32BE(payload.length,2);return Buffer.concat([header,payload])}const MAX_PACKET_PAYLOAD=16*1024;function createPacketReader(){let buffered=Buffer.alloc(0);return{push(chunk){buffered=Buffer.concat([buffered,chunk]);const packets=[];for(;;){if(buffered.length<6)break;const version=buffered.readUInt8(0);if(version!==PAIRING_PACKET_VERSION){throw new Error(`Unsupported pairing packet version: ${version} (expected ${PAIRING_PACKET_VERSION})`)}const payloadLength=buffered.readUInt32BE(2);if(payloadLength>MAX_PACKET_PAYLOAD){throw new Error(`Pairing packet payload too large: ${payloadLength} bytes (max ${MAX_PACKET_PAYLOAD})`)}if(buffered.length<6+payloadLength)break;packets.push({version,type:buffered.readUInt8(1),payload:buffered.subarray(6,6+payloadLength)});buffered=buffered.subarray(6+payloadLength)}return packets}}}const PEER_INFO_TYPE_RSA_PUB_KEY=0;function encodePeerInfo(type,data){return Buffer.concat([Buffer.from([type]),data])}function decodePeerInfo(buf){if(buf.length<1){throw new Error("PeerInfo payload is empty (expected at least a 1-byte type)")}return{type:buf.readUInt8(0),data:buf.subarray(1)}}const AES_KEY_INFO=Buffer.from("adb pairing_auth aes-128-gcm key","utf8");function deriveAesKey(keyMaterial){return Buffer.from(crypto.hkdfSync("sha256",keyMaterial,Buffer.alloc(0),AES_KEY_INFO,16))}function createMessageCipher(keyMaterial){const key=deriveAesKey(keyMaterial);let encSequence=0n;let decSequence=0n;const nonceFor=sequence=>{const nonce=Buffer.alloc(12);nonce.writeBigUInt64LE(sequence,0);return nonce};return{encrypt(plaintext){const nonce=nonceFor(encSequence++);const cipher=crypto.createCipheriv("aes-128-gcm",key,nonce);const ciphertext=Buffer.concat([cipher.update(plaintext),cipher.final()]);return Buffer.concat([ciphertext,cipher.getAuthTag()])},decrypt(ciphertextAndTag){if(ciphertextAndTag.length<16){throw new Error(`Encrypted PeerInfo payload is too short to contain a 16-byte GCM tag: ${ciphertextAndTag.length} bytes`)}const nonce=nonceFor(decSequence++);const tag=ciphertextAndTag.subarray(ciphertextAndTag.length-16);const ciphertext=ciphertextAndTag.subarray(0,ciphertextAndTag.length-16);const decipher=crypto.createDecipheriv("aes-128-gcm",key,nonce);decipher.setAuthTag(tag);return Buffer.concat([decipher.update(ciphertext),decipher.final()])}}}function certMatchesKey(certPem,publicKeyPem){const certPublicKey=new crypto.X509Certificate(certPem).publicKey;const currentPublicKey=crypto.createPublicKey(publicKeyPem);return certPublicKey.export({type:"pkcs1",format:"der"}).equals(currentPublicKey.export({type:"pkcs1",format:"der"}))}async function getOrCreatePairingCert(keys,certPath){let cert;try{cert=fs.readFileSync(certPath,"utf8")}catch(error){if(error.code!=="ENOENT")throw error}if(cert!==void 0){let matches=false;try{matches=certMatchesKey(cert,keys.publicKey)}catch{}if(matches){return{cert,key:keys.privateKey}}}const pems=await selfsigned.generate(null,{keyPair:{publicKey:keys.publicKey,privateKey:keys.privateKey},days:3650});fs.writeFileSync(certPath,pems.cert);return{cert:pems.cert,key:keys.privateKey}}async function pair(host,port,pairingCode,options={}){const{keyDir,timeoutMs=1e4}=options;if(!Number.isInteger(timeoutMs)||timeoutMs<=0){throw new Error(`Invalid timeoutMs: ${timeoutMs} (must be a positive integer)`)}if(typeof pairingCode!=="string"||pairingCode.length===0){throw new Error("pairingCode must be a non-empty string")}const adbDir=keyDir||path.join(os.homedir(),".adb");const keys=self.auth.getKeys(adbDir);const certPath=path.join(adbDir,"adbkey.cert.pem");const{cert,key}=await getOrCreatePairingCert(keys,certPath);return new Promise((resolve,reject)=>{let settled=false;let socket;const finish=(fn,value)=>{if(settled)return;settled=true;clearTimeout(timer);if(socket){socket.removeAllListeners();socket.destroy()}fn(value)};const timer=setTimeout(()=>finish(reject,new Error("Pairing timed out")),timeoutMs);try{socket=tls.connect({host,port,cert,key,minVersion:"TLSv1.3",maxVersion:"TLSv1.3",rejectUnauthorized:false})}catch(error){finish(reject,error);return}const reader=createPacketReader();let stage="spake2";let ephemeralScalar;let passwordScalar;let passwordHash;let clientMsg;let cipher;socket.on("error",error=>finish(reject,error));socket.on("secureConnect",()=>{const exportedKeyMaterial=Buffer.from(socket.exportKeyingMaterial(64,"adb-label\0"));const password=Buffer.concat([Buffer.from(pairingCode,"utf8"),exportedKeyMaterial]);passwordHash=hashPassword(password);passwordScalar=passwordToScalar(passwordHash);ephemeralScalar=randomScalar();clientMsg=generateSpakeMessage(ephemeralScalar,passwordScalar);socket.write(encodePairingPacket(PACKET_TYPE_SPAKE2_MSG,clientMsg))});socket.on("data",chunk=>{try{for(const packet of reader.push(chunk)){if(stage==="spake2"){if(packet.type!==PACKET_TYPE_SPAKE2_MSG){throw new Error(`Expected SPAKE2_MSG, got packet type ${packet.type}`)}const serverMsg=packet.payload;const dhShared=computeSharedSecret(ephemeralScalar,passwordScalar,serverMsg);const keyMaterial=deriveSessionKey({clientMsg,serverMsg,dhShared,passwordHash},64);cipher=createMessageCipher(keyMaterial);const peerInfo=encodePeerInfo(PEER_INFO_TYPE_RSA_PUB_KEY,Buffer.from(keys.adbPublicKey,"utf8"));socket.write(encodePairingPacket(PACKET_TYPE_PEER_INFO,cipher.encrypt(peerInfo)));stage="peerInfo"}else if(stage==="peerInfo"){if(packet.type!==PACKET_TYPE_PEER_INFO){throw new Error(`Expected PEER_INFO, got packet type ${packet.type}`)}decodePeerInfo(cipher.decrypt(packet.payload));finish(resolve,{success:true})}}}catch(error){finish(reject,error)}})})}export{pair};
|
|
1
|
+
var D=Object.defineProperty;var a=(e,r)=>D(e,"name",{value:r,configurable:!0});import G from"node:tls";import l from"node:crypto";import M from"node:fs";import v from"node:path";import V from"node:os";import{self as q}from"@cldmv/slothlet/runtime";import{ed25519 as X}from"@noble/curves/ed25519.js";import z from"selfsigned";const g=X.Point,N=g.Fn,j=g.fromHex("5ada7e4bf6ddd9adb6626d32131c6b5c51a1e347a3478f53cfcf441b88eed12e"),J=g.fromHex("10e3df0ae37d8e7a99b5fe74b44672103dbddcbd06af680d71329a11693bc778"),Q=Buffer.from("adb pair client","utf8"),W=Buffer.from("adb pair server","utf8");function Z(){return N.create(A(l.randomBytes(64)))}a(Z,"randomScalar");function A(e){let r=0n;for(let t=e.length-1;t>=0;t--)r=r<<8n|BigInt(e[t]);return r}a(A,"bytesToBigIntLE");function ee(e){return l.createHash("sha512").update(e).digest()}a(ee,"hashPassword");function te(e){return N.create(A(e))}a(te,"passwordToScalar");function re(e,r){const t=g.BASE.multiply(e),c=j.multiply(r);return Buffer.from(t.add(c).toBytes())}a(re,"generateSpakeMessage");function ne(e,r,t){const c=g.fromBytes(t),o=J.multiply(r),i=c.subtract(o).multiply(e);return Buffer.from(i.toBytes())}a(ne,"computeSharedSecret");function d(e,r){const t=Buffer.alloc(8);t.writeBigUInt64LE(BigInt(r.length)),e.update(t),e.update(r)}a(d,"updateLengthPrefixed");function oe({clientMsg:e,serverMsg:r,dhShared:t,passwordHash:c},o){const n=l.createHash("sha512");return d(n,Q),d(n,W),d(n,e),d(n,r),d(n,t),d(n,c),n.digest().subarray(0,o)}a(oe,"deriveSessionKey");const K=1,T=0,U=1;function x(e,r){const t=Buffer.alloc(6);return t.writeUInt8(K,0),t.writeUInt8(e,1),t.writeUInt32BE(r.length,2),Buffer.concat([t,r])}a(x,"encodePairingPacket");const C=16*1024;function ae(){let e=Buffer.alloc(0);return{push(r){e=Buffer.concat([e,r]);const t=[];for(;!(e.length<6);){const c=e.readUInt8(0);if(c!==K)throw new Error(`Unsupported pairing packet version: ${c} (expected ${K})`);const o=e.readUInt32BE(2);if(o>C)throw new Error(`Pairing packet payload too large: ${o} bytes (max ${C})`);if(e.length<6+o)break;t.push({version:c,type:e.readUInt8(1),payload:e.subarray(6,6+o)}),e=e.subarray(6+o)}return t}}}a(ae,"createPacketReader");const ce=0;function se(e,r){return Buffer.concat([Buffer.from([e]),r])}a(se,"encodePeerInfo");function ie(e){if(e.length<1)throw new Error("PeerInfo payload is empty (expected at least a 1-byte type)");return{type:e.readUInt8(0),data:e.subarray(1)}}a(ie,"decodePeerInfo");const fe=Buffer.from("adb pairing_auth aes-128-gcm key","utf8");function ue(e){return Buffer.from(l.hkdfSync("sha256",e,Buffer.alloc(0),fe,16))}a(ue,"deriveAesKey");function pe(e){const r=ue(e);let t=0n,c=0n;const o=a(n=>{const i=Buffer.alloc(12);return i.writeBigUInt64LE(n,0),i},"nonceFor");return{encrypt(n){const i=o(t++),p=l.createCipheriv("aes-128-gcm",r,i),y=Buffer.concat([p.update(n),p.final()]);return Buffer.concat([y,p.getAuthTag()])},decrypt(n){if(n.length<16)throw new Error(`Encrypted PeerInfo payload is too short to contain a 16-byte GCM tag: ${n.length} bytes`);const i=o(c++),p=n.subarray(n.length-16),y=n.subarray(0,n.length-16),m=l.createDecipheriv("aes-128-gcm",r,i);return m.setAuthTag(p),Buffer.concat([m.update(y),m.final()])}}}a(pe,"createMessageCipher");function le(e,r){const t=new l.X509Certificate(e).publicKey,c=l.createPublicKey(r);return t.export({type:"pkcs1",format:"der"}).equals(c.export({type:"pkcs1",format:"der"}))}a(le,"certMatchesKey");async function de(e,r){let t;try{t=M.readFileSync(r,"utf8")}catch(o){if(o.code!=="ENOENT")throw o}if(t!==void 0){let o=!1;try{o=le(t,e.publicKey)}catch{}if(o)return{cert:t,key:e.privateKey}}const c=await z.generate(null,{keyPair:{publicKey:e.publicKey,privateKey:e.privateKey},days:3650});return M.writeFileSync(r,c.cert),{cert:c.cert,key:e.privateKey}}a(de,"getOrCreatePairingCert");async function Ie(e,r,t,c={}){const{keyDir:o,timeoutMs:n=1e4}=c;if(!Number.isInteger(n)||n<=0)throw new Error(`Invalid timeoutMs: ${n} (must be a positive integer)`);if(typeof t!="string"||t.length===0)throw new Error("pairingCode must be a non-empty string");const i=o||v.join(V.homedir(),".adb"),p=q.auth.getKeys(i),y=v.join(i,"adbkey.cert.pem"),{cert:m,key:L}=await de(p,y);return new Promise((O,E)=>{let S=!1,f;const h=a((u,s)=>{S||(S=!0,clearTimeout(F),f&&(f.removeAllListeners(),f.destroy()),u(s))},"finish"),F=setTimeout(()=>h(E,new Error("Pairing timed out")),n);try{f=G.connect({host:e,port:r,cert:m,key:L,minVersion:"TLSv1.3",maxVersion:"TLSv1.3",rejectUnauthorized:!1})}catch(u){h(E,u);return}const R=ae();let b="spake2",P,w,B,I,k;f.on("error",u=>h(E,u)),f.on("secureConnect",()=>{const u=Buffer.from(f.exportKeyingMaterial(64,"adb-label\0")),s=Buffer.concat([Buffer.from(t,"utf8"),u]);B=ee(s),w=te(B),P=Z(),I=re(P,w),f.write(x(T,I))}),f.on("data",u=>{try{for(const s of R.push(u))if(b==="spake2"){if(s.type!==T)throw new Error(`Expected SPAKE2_MSG, got packet type ${s.type}`);const _=s.payload,$=ne(P,w,_),Y=oe({clientMsg:I,serverMsg:_,dhShared:$,passwordHash:B},64);k=pe(Y);const H=se(ce,Buffer.from(p.adbPublicKey,"utf8"));f.write(x(U,k.encrypt(H))),b="peerInfo"}else if(b==="peerInfo"){if(s.type!==U)throw new Error(`Expected PEER_INFO, got packet type ${s.type}`);ie(k.decrypt(s.payload)),h(O,{success:!0})}}catch(s){h(E,s)}})})}a(Ie,"pair");export{Ie as pair};
|
|
2
|
+
//# sourceMappingURL=pairing.mjs.map
|
package/dist/api/reboot.mjs
CHANGED
|
@@ -1,17 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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
|
-
async function execute(___socket,streamManager,mode=""){const stream=await streamManager.openStream(`reboot:${mode}`);try{streamManager.closeStream(stream.localId)}catch{}}export{execute};
|
|
1
|
+
var n=Object.defineProperty;var e=(c,t)=>n(c,"name",{value:t,configurable:!0});async function s(c,t,o=""){const a=await t.openStream(`reboot:${o}`);try{t.closeStream(a.localId)}catch{}}e(s,"execute");export{s as execute};
|
|
2
|
+
//# sourceMappingURL=reboot.mjs.map
|
package/dist/api/reverse.mjs
CHANGED
|
@@ -1,17 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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";const MAX_PENDING_DEVICE_DATA=1024*1024;function assertOkayAck(ack,action){const id=ack.toString("ascii",0,4);if(id==="OKAY")return;if(id==="FAIL"){const lengthField=ack.toString("ascii",4,8);if(!/^[0-9a-fA-F]{4}$/.test(lengthField)){throw new Error(`Unexpected response to ${action}: ${ack.toString("utf8")}`)}const messageLength=parseInt(lengthField,16);const message=ack.subarray(8,8+messageLength).toString("utf8");throw new Error(`Failed to ${action}: ${message}`)}throw new Error(`Unexpected response to ${action}: ${ack.toString("utf8")}`)}async function start(___socket,streamManager,devicePort,hostPort,options={}){const{host="127.0.0.1",onError}=options;const destination=`tcp:${hostPort}`;const onRemoteOpen=(deviceStream,streamDestination)=>{if(streamDestination!==destination)return;const localSocket=net.connect(hostPort,host);let localSocketFailed=false;let localSocketConnected=false;const pendingDeviceData=[];let pendingDeviceDataBytes=0;const closeDeviceStream=()=>streamManager.closeStream(deviceStream.localId);deviceStream.on("data",data=>{if(localSocketFailed)return;if(localSocketConnected){localSocket.write(data);return}pendingDeviceDataBytes+=data.length;if(pendingDeviceDataBytes>MAX_PENDING_DEVICE_DATA){const error=new Error(`Local connect for reverse bridge tcp:${devicePort} -> tcp:${hostPort} stalled while buffering ${pendingDeviceDataBytes} bytes of device data (max ${MAX_PENDING_DEVICE_DATA})`);localSocketFailed=true;localSocket.destroy();closeDeviceStream();if(onError)onError(error,deviceStream);return}pendingDeviceData.push(data)});deviceStream.on("close",()=>{closeDeviceStream();if(localSocketConnected)localSocket.end();else localSocket.destroy()});deviceStream.on("error",error=>{closeDeviceStream();localSocket.destroy();if(onError)onError(error,deviceStream)});localSocket.on("error",error=>{localSocketFailed=true;localSocket.destroy();closeDeviceStream();if(onError)onError(error,deviceStream)});localSocket.on("connect",()=>{if(localSocketFailed||deviceStream.closed){localSocket.destroy();return}localSocketConnected=true;for(const data of pendingDeviceData)localSocket.write(data);pendingDeviceData.length=0;localSocket.on("data",data=>{deviceStream.write(data).catch(error=>{closeDeviceStream();localSocket.destroy();if(onError)onError(error,deviceStream)})});localSocket.on("close",()=>closeDeviceStream())})};streamManager.on("remoteOpen",onRemoteOpen);let registerStream;try{registerStream=await streamManager.openStream(`reverse:forward:tcp:${devicePort};tcp:${hostPort}`);const ack=await new Promise((resolve,reject)=>{registerStream.once("data",resolve);registerStream.once("error",reject);registerStream.once("close",()=>reject(new Error("reverse registration stream closed with no ack")))});assertOkayAck(ack,`register reverse tunnel tcp:${devicePort} -> tcp:${hostPort}`)}catch(error){streamManager.off("remoteOpen",onRemoteOpen);throw error}finally{if(registerStream)streamManager.closeStream(registerStream.localId)}return{devicePort,hostPort,async close(){streamManager.off("remoteOpen",onRemoteOpen);let killStream;try{killStream=await streamManager.openStream(`reverse:killforward:tcp:${devicePort}`);const ack=await new Promise((resolve,reject)=>{killStream.once("data",resolve);killStream.once("error",reject);killStream.once("close",()=>reject(new Error("reverse killforward stream closed with no ack")))});assertOkayAck(ack,`unregister reverse tunnel tcp:${devicePort}`)}catch{}finally{if(killStream)streamManager.closeStream(killStream.localId)}}}}export{start};
|
|
1
|
+
var I=Object.defineProperty;var w=(c,o)=>I(c,"name",{value:o,configurable:!0});import S from"node:net";const k=1024*1024;function D(c,o){const n=c.toString("ascii",0,4);if(n!=="OKAY"){if(n==="FAIL"){const s=c.toString("ascii",4,8);if(!/^[0-9a-fA-F]{4}$/.test(s))throw new Error(`Unexpected response to ${o}: ${c.toString("utf8")}`);const u=parseInt(s,16),d=c.subarray(8,8+u).toString("utf8");throw new Error(`Failed to ${o}: ${d}`)}throw new Error(`Unexpected response to ${o}: ${c.toString("utf8")}`)}}w(D,"assertOkayAck");async function m(c,o,n,s,u={}){const{host:d="127.0.0.1",onError:l}=u,A=`tcp:${s}`,$=w((e,p)=>{if(p!==A)return;const t=S.connect(s,d);let i=!1,y=!1;const g=[];let h=0;const a=w(()=>o.closeStream(e.localId),"closeDeviceStream");e.on("data",r=>{if(!i){if(y){t.write(r);return}if(h+=r.length,h>k){const E=new Error(`Local connect for reverse bridge tcp:${n} -> tcp:${s} stalled while buffering ${h} bytes of device data (max ${k})`);i=!0,t.destroy(),a(),l&&l(E,e);return}g.push(r)}}),e.on("close",()=>{a(),y?t.end():t.destroy()}),e.on("error",r=>{a(),t.destroy(),l&&l(r,e)}),t.on("error",r=>{i=!0,t.destroy(),a(),l&&l(r,e)}),t.on("connect",()=>{if(i||e.closed){t.destroy();return}y=!0;for(const r of g)t.write(r);g.length=0,t.on("data",r=>{e.write(r).catch(E=>{a(),t.destroy(),l&&l(E,e)})}),t.on("close",()=>a())})},"onRemoteOpen");o.on("remoteOpen",$);let f;try{f=await o.openStream(`reverse:forward:tcp:${n};tcp:${s}`);const e=await new Promise((p,t)=>{f.once("data",p),f.once("error",t),f.once("close",()=>t(new Error("reverse registration stream closed with no ack")))});D(e,`register reverse tunnel tcp:${n} -> tcp:${s}`)}catch(e){throw o.off("remoteOpen",$),e}finally{f&&o.closeStream(f.localId)}return{devicePort:n,hostPort:s,async close(){o.off("remoteOpen",$);let e;try{e=await o.openStream(`reverse:killforward:tcp:${n}`);const p=await new Promise((t,i)=>{e.once("data",t),e.once("error",i),e.once("close",()=>i(new Error("reverse killforward stream closed with no ack")))});D(p,`unregister reverse tunnel tcp:${n}`)}catch{}finally{e&&o.closeStream(e.localId)}}}}w(m,"start");export{m as start};
|
|
2
|
+
//# sourceMappingURL=reverse.mjs.map
|
package/dist/api/shell.mjs
CHANGED
|
@@ -1,17 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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{quoteShellArg,assertValidFlags}from"./utils.mjs";async function execute(socket,streamManager,command,options={}){const{timeout=3e4,encoding="utf8",deviceFeatures=[]}=options;return new Promise((resolve,reject)=>{try{let output=Buffer.alloc(0);let streamId=null;let commandTimeout;let commandCompleted=false;let protocolUsed;const supportsShellV2=deviceFeatures.includes("shell_v2");if(supportsShellV2){protocolUsed=`shell,v2:${command}`}else{protocolUsed=`shell:${command}`}if(self.config.get("debug")){self.log.debug(`Executing shell command: ${protocolUsed}`)}const destBuffer=Buffer.from(protocolUsed);const openPacket=Buffer.alloc(24+destBuffer.length);openPacket.writeUInt32LE(1313165391,0);openPacket.writeUInt32LE(12345,4);openPacket.writeUInt32LE(0,8);openPacket.writeUInt32LE(destBuffer.length,12);let checksum=0;for(let i=0;i<destBuffer.length;i++){checksum+=destBuffer[i]}openPacket.writeUInt32LE(checksum&4294967295,16);openPacket.writeUInt32LE(~1313165391>>>0,20);destBuffer.copy(openPacket,24);socket.write(openPacket);commandTimeout=setTimeout(()=>{if(!commandCompleted){commandCompleted=true;socket.removeAllListeners("data");reject(new Error(`Command timeout: ${command}`))}},timeout);let responseBuffer=Buffer.alloc(0);let originalHandlers=[];const existingHandlers=socket.listeners("data");existingHandlers.forEach(handler=>{socket.removeListener("data",handler);originalHandlers.push(handler)});const dataHandler=chunk=>{if(commandCompleted)return;responseBuffer=Buffer.concat([responseBuffer,chunk]);while(responseBuffer.length>=24){const cmd=responseBuffer.readUInt32LE(0);const arg0=responseBuffer.readUInt32LE(4);const arg1=responseBuffer.readUInt32LE(8);const dataLength=responseBuffer.readUInt32LE(12);if(responseBuffer.length<24+dataLength)break;const packetData=dataLength>0?responseBuffer.slice(24,24+dataLength):null;responseBuffer=responseBuffer.slice(24+dataLength);if(self.config.get("debug")){const commandName=cmd===1497451343?"OKAY":cmd===1163154007?"WRTE":cmd===1163086915?"CLSE":`0x${cmd.toString(16)}`;self.log.debug(`${self.config.get("debugArrowReceived")} ${commandName} arg0:${arg0} arg1:${arg1} len:${dataLength}`)}if(cmd===1497451343&&!streamId){streamId=arg1;if(self.config.get("debug")){self.log.debug(`Shell stream opened with ID: ${streamId}`)}}else if(cmd===1163154007&&arg1===12345){if(packetData){output=Buffer.concat([output,packetData]);if(self.config.get("debug")){self.log.debug(`Received ${packetData.length} bytes of output`)}}}else if(cmd===1163086915&&arg1===12345){if(self.config.get("debug")){self.log.debug("Shell stream closed by device")}commandCompleted=true;clearTimeout(commandTimeout);socket.removeListener("data",dataHandler);originalHandlers.forEach(handler=>{socket.on("data",handler)});resolve(output.toString(encoding));return}}};socket.on("data",dataHandler)}catch(error){reject(error)}})}function startStreaming(socket,streamManager,command,options={}){const{onData,onError,onEnd}=options;let stream=null;const control={stop(){if(stream){stream.close();stream=null}}};(async()=>{try{stream=await streamManager.openStream(`shell:${command}`);stream.on("data",data=>{if(onData)onData(data.toString())});stream.on("close",()=>{if(onEnd)onEnd()});stream.on("error",error=>{if(onError)onError(error)})}catch(error){if(onError)onError(error)}})();return control}function startInteractive(socket,streamManager,command,options={}){const{onData,onError,onEnd}=options;let stream=null;const control={async sendInput(input){if(stream){await stream.write(input)}},stop(){if(stream){stream.close();stream=null}}};(async()=>{try{stream=await streamManager.openStream(`shell:${command}`);stream.on("data",data=>{if(onData)onData(data.toString())});stream.on("close",()=>{if(onEnd)onEnd()});stream.on("error",error=>{if(onError)onError(error)})}catch(error){if(onError)onError(error)}})();return control}const commands={ls:async(socket,streamManager,path=".")=>{return await execute(socket,streamManager,`ls -la ${quoteShellArg(path)}`)},pwd:async(socket,streamManager)=>{return await execute(socket,streamManager,"pwd")},getprop:async(socket,streamManager,prop=null)=>{const cmd=prop?`getprop ${quoteShellArg(prop)}`:"getprop";return await execute(socket,streamManager,cmd)},getModel:async(socket,streamManager)=>{return await execute(socket,streamManager,"getprop ro.product.model")},getAndroidVersion:async(socket,streamManager)=>{return await execute(socket,streamManager,"getprop ro.build.version.release")},getBattery:async(socket,streamManager)=>{return await execute(socket,streamManager,"dumpsys battery")},screenshot:async(socket,streamManager,filename="/sdcard/screenshot.png")=>{return await execute(socket,streamManager,`screencap -p ${quoteShellArg(filename)}`)},logcat:(socket,streamManager,options={})=>{return startStreaming(socket,streamManager,"logcat",options)},top:(socket,streamManager,options={})=>{return startStreaming(socket,streamManager,"top -m 10",options)},keypress:async(socket,streamManager,key)=>{return await execute(socket,streamManager,`input keyevent ${quoteShellArg(key)}`)},launchApp:async(socket,streamManager,packageName,activity="")=>{const target=activity?`${packageName}/${activity}`:packageName;return await execute(socket,streamManager,`am start -n ${quoteShellArg(target)}`)},killApp:async(socket,streamManager,packageName)=>{return await execute(socket,streamManager,`am force-stop ${quoteShellArg(packageName)}`)},installApk:async(socket,streamManager,apkPath,flags=[])=>{assertValidFlags(flags);const flagsStr=flags.length>0?` ${flags.map(quoteShellArg).join(" ")}`:"";return await execute(socket,streamManager,`pm install${flagsStr} ${quoteShellArg(apkPath)}`)},uninstallApp:async(socket,streamManager,packageName)=>{return await execute(socket,streamManager,`pm uninstall ${quoteShellArg(packageName)}`)}};export{commands,execute,startInteractive,startStreaming};
|
|
1
|
+
var T=Object.defineProperty;var a=(e,t)=>T(e,"name",{value:t,configurable:!0});import{self as f}from"@cldmv/slothlet/runtime";import{quoteShellArg as g,assertValidFlags as V}from"./utils.mjs";async function s(e,t,r,l={}){const{timeout:i=3e4,encoding:c="utf8",deviceFeatures:m=[]}=l;return new Promise((n,w)=>{try{let o=Buffer.alloc(0),L=null,v,E=!1,b;m.includes("shell_v2")?b=`shell,v2:${r}`:b=`shell:${r}`,f.config.get("debug")&&f.log.debug(`Executing shell command: ${b}`);const y=Buffer.from(b),d=Buffer.alloc(24+y.length);d.writeUInt32LE(1313165391,0),d.writeUInt32LE(12345,4),d.writeUInt32LE(0,8),d.writeUInt32LE(y.length,12);let U=0;for(let p=0;p<y.length;p++)U+=y[p];d.writeUInt32LE(U&4294967295,16),d.writeUInt32LE(2981801904,20),y.copy(d,24),e.write(d),v=setTimeout(()=>{E||(E=!0,e.removeAllListeners("data"),w(new Error(`Command timeout: ${r}`)))},i);let u=Buffer.alloc(0),A=[];e.listeners("data").forEach(p=>{e.removeListener("data",p),A.push(p)});const B=a(p=>{if(!E)for(u=Buffer.concat([u,p]);u.length>=24;){const h=u.readUInt32LE(0),H=u.readUInt32LE(4),x=u.readUInt32LE(8),$=u.readUInt32LE(12);if(u.length<24+$)break;const I=$>0?u.slice(24,24+$):null;if(u=u.slice(24+$),f.config.get("debug")){const S=h===1497451343?"OKAY":h===1163154007?"WRTE":h===1163086915?"CLSE":`0x${h.toString(16)}`;f.log.debug(`${f.config.get("debugArrowReceived")} ${S} arg0:${H} arg1:${x} len:${$}`)}if(h===1497451343&&!L)L=x,f.config.get("debug")&&f.log.debug(`Shell stream opened with ID: ${L}`);else if(h===1163154007&&x===12345)I&&(o=Buffer.concat([o,I]),f.config.get("debug")&&f.log.debug(`Received ${I.length} bytes of output`));else if(h===1163086915&&x===12345){f.config.get("debug")&&f.log.debug("Shell stream closed by device"),E=!0,clearTimeout(v),e.removeListener("data",B),A.forEach(S=>{e.on("data",S)}),n(o.toString(c));return}}},"dataHandler");e.on("data",B)}catch(o){w(o)}})}a(s,"execute");function D(e,t,r,l={}){const{onData:i,onError:c,onEnd:m}=l;let n=null;const w={stop(){n&&(n.close(),n=null)}};return(async()=>{try{n=await t.openStream(`shell:${r}`),n.on("data",o=>{i&&i(o.toString())}),n.on("close",()=>{m&&m()}),n.on("error",o=>{c&&c(o)})}catch(o){c&&c(o)}})(),w}a(D,"startStreaming");function P(e,t,r,l={}){const{onData:i,onError:c,onEnd:m}=l;let n=null;const w={async sendInput(o){n&&await n.write(o)},stop(){n&&(n.close(),n=null)}};return(async()=>{try{n=await t.openStream(`shell:${r}`),n.on("data",o=>{i&&i(o.toString())}),n.on("close",()=>{m&&m()}),n.on("error",o=>{c&&c(o)})}catch(o){c&&c(o)}})(),w}a(P,"startInteractive");const q={ls:a(async(e,t,r=".")=>await s(e,t,`ls -la ${g(r)}`),"ls"),pwd:a(async(e,t)=>await s(e,t,"pwd"),"pwd"),getprop:a(async(e,t,r=null)=>{const l=r?`getprop ${g(r)}`:"getprop";return await s(e,t,l)},"getprop"),getModel:a(async(e,t)=>await s(e,t,"getprop ro.product.model"),"getModel"),getAndroidVersion:a(async(e,t)=>await s(e,t,"getprop ro.build.version.release"),"getAndroidVersion"),getBattery:a(async(e,t)=>await s(e,t,"dumpsys battery"),"getBattery"),screenshot:a(async(e,t,r="/sdcard/screenshot.png")=>await s(e,t,`screencap -p ${g(r)}`),"screenshot"),logcat:a((e,t,r={})=>D(e,t,"logcat",r),"logcat"),top:a((e,t,r={})=>D(e,t,"top -m 10",r),"top"),keypress:a(async(e,t,r)=>await s(e,t,`input keyevent ${g(r)}`),"keypress"),launchApp:a(async(e,t,r,l="")=>{const i=l?`${r}/${l}`:r;return await s(e,t,`am start -n ${g(i)}`)},"launchApp"),killApp:a(async(e,t,r)=>await s(e,t,`am force-stop ${g(r)}`),"killApp"),installApk:a(async(e,t,r,l=[])=>{V(l);const i=l.length>0?` ${l.map(g).join(" ")}`:"";return await s(e,t,`pm install${i} ${g(r)}`)},"installApk"),uninstallApp:a(async(e,t,r)=>await s(e,t,`pm uninstall ${g(r)}`),"uninstallApp")};export{q as commands,s as execute,P as startInteractive,D as startStreaming};
|
|
2
|
+
//# sourceMappingURL=shell.mjs.map
|
package/dist/api/stream.mjs
CHANGED
|
@@ -1,17 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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{EventEmitter}from"node:events";const MSG_OPEN=1313165391;const MSG_WRTE=1163154007;const MSG_CLSE=1163086915;const MSG_OKAY=1497451343;function getCommandName(command){switch(command){case MSG_OPEN:return"OPEN";case MSG_WRTE:return"WRTE";case MSG_CLSE:return"CLSE";case MSG_OKAY:return"OKAY";default:return`0x${command.toString(16).toUpperCase()}`}}function create(socket){const streams=new Map;let nextStreamId=1;const emitter=new EventEmitter;const manager={socket,streams,on:(...args)=>emitter.on(...args),once:(...args)=>emitter.once(...args),off:(...args)=>emitter.off(...args),async openStream(destination){const localId=nextStreamId++;const stream=new AdbStream(localId,0,socket,manager);streams.set(localId,stream);const destBuffer=Buffer.from(destination);await sendMessage(socket,MSG_OPEN,localId,0,destBuffer);return new Promise((resolve,reject)=>{stream.once("ready",()=>resolve(stream));stream.once("error",reject);setTimeout(()=>{if(!stream.ready){streams.delete(localId);reject(new Error("Stream open timeout"))}},5e3)})},handlePacket(data){let offset=0;while(offset<data.length){if(data.length-offset<24)break;const command=data.readUInt32LE(offset);const arg0=data.readUInt32LE(offset+4);const arg1=data.readUInt32LE(offset+8);const dataLength=data.readUInt32LE(offset+12);if(data.length-offset<24+dataLength)break;const packetData=data.slice(offset+24,offset+24+dataLength);offset+=24+dataLength;const commandName=getCommandName(command);if(self.config.get("debug")){self.log.debug(`${self.config.get("debugArrowReceived")} ${commandName} arg0:${arg0} arg1:${arg1} len:${dataLength}`)}if(command===MSG_OPEN&&arg1===0){const remoteId=arg0;const destination=packetData.toString("utf8").replace(/\0/g,"");const localId=nextStreamId++;const stream2=new AdbStream(localId,remoteId,socket,manager);stream2.ready=true;streams.set(localId,stream2);sendMessage(socket,MSG_OKAY,localId,remoteId);emitter.emit("remoteOpen",stream2,destination);continue}const stream=streams.get(arg1);if(stream){stream.handleMessage(command,arg0,arg1,packetData)}}},closeStream(streamId){const stream=streams.get(streamId);if(stream){try{stream.close()}finally{streams.delete(streamId)}}}};return manager}class AdbStream extends EventEmitter{constructor(localId,remoteId,socket,manager){super();this.localId=localId;this.remoteId=remoteId;this.socket=socket;this.manager=manager;this.ready=false;this.closed=false}handleMessage(command,arg0,arg1,data){switch(command){case MSG_OKAY:if(!this.ready){this.remoteId=arg0;this.ready=true;this.emit("ready")}else{this.emit("ack")}break;case MSG_WRTE:this.emit("data",data);sendMessage(this.socket,MSG_OKAY,this.localId,this.remoteId);break;case MSG_CLSE:this.closed=true;this.emit("close");break}}async write(data){if(this.closed||!this.ready){throw new Error("Stream not ready or closed")}const buffer=Buffer.isBuffer(data)?data:Buffer.from(data);await sendMessage(this.socket,MSG_WRTE,this.remoteId,this.localId,buffer)}close(){if(!this.closed){this.closed=true;sendMessage(this.socket,MSG_CLSE,this.remoteId,this.localId);this.emit("close")}}}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);const commandName=getCommandName(command);if(self.config.get("debug")){self.log.debug(`${self.config.get("debugArrowSent")} ${commandName} arg0:${arg0} arg1:${arg1} len:${data.length}`)}socket.write(header);if(data.length>0){socket.write(data)}}function checksum(data){let sum=0;for(let i=0;i<data.length;i++){sum+=data[i]}return sum&4294967295}export{create};
|
|
1
|
+
var M=Object.defineProperty;var f=(s,r)=>M(s,"name",{value:r,configurable:!0});import{self as h}from"@cldmv/slothlet/runtime";import{EventEmitter as p}from"node:events";const I=1313165391,E=1163154007,S=1163086915,d=1497451343;function U(s){switch(s){case I:return"OPEN";case E:return"WRTE";case S:return"CLSE";case d:return"OKAY";default:return`0x${s.toString(16).toUpperCase()}`}}f(U,"getCommandName");function C(s){const r=new Map;let n=1;const c=new p,o={socket:s,streams:r,on:f((...t)=>c.on(...t),"on"),once:f((...t)=>c.once(...t),"once"),off:f((...t)=>c.off(...t),"off"),async openStream(t){const e=n++,i=new $(e,0,s,o);r.set(e,i);const m=Buffer.from(t);return await g(s,I,e,0,m),new Promise((l,a)=>{i.once("ready",()=>l(i)),i.once("error",a),setTimeout(()=>{i.ready||(r.delete(e),a(new Error("Stream open timeout")))},5e3)})},handlePacket(t){let e=0;for(;e<t.length&&!(t.length-e<24);){const i=t.readUInt32LE(e),m=t.readUInt32LE(e+4),l=t.readUInt32LE(e+8),a=t.readUInt32LE(e+12);if(t.length-e<24+a)break;const b=t.slice(e+24,e+24+a);e+=24+a;const x=U(i);if(h.config.get("debug")&&h.log.debug(`${h.config.get("debugArrowReceived")} ${x} arg0:${m} arg1:${l} len:${a}`),i===I&&l===0){const L=m,k=b.toString("utf8").replace(/\0/g,""),u=n++,w=new $(u,L,s,o);w.ready=!0,r.set(u,w),g(s,d,u,L),c.emit("remoteOpen",w,k);continue}const y=r.get(l);y&&y.handleMessage(i,m,l,b)}},closeStream(t){const e=r.get(t);if(e)try{e.close()}finally{r.delete(t)}}};return o}f(C,"create");class $ extends p{static{f(this,"AdbStream")}constructor(r,n,c,o){super(),this.localId=r,this.remoteId=n,this.socket=c,this.manager=o,this.ready=!1,this.closed=!1}handleMessage(r,n,c,o){switch(r){case d:this.ready?this.emit("ack"):(this.remoteId=n,this.ready=!0,this.emit("ready"));break;case E:this.emit("data",o),g(this.socket,d,this.localId,this.remoteId);break;case S:this.closed=!0,this.emit("close");break}}async write(r){if(this.closed||!this.ready)throw new Error("Stream not ready or closed");const n=Buffer.isBuffer(r)?r:Buffer.from(r);await g(this.socket,E,this.remoteId,this.localId,n)}close(){this.closed||(this.closed=!0,g(this.socket,S,this.remoteId,this.localId),this.emit("close"))}}async function g(s,r,n,c,o=Buffer.alloc(0)){const t=Buffer.alloc(24);let e=0;t.writeUInt32LE(r,e),e+=4,t.writeUInt32LE(n,e),e+=4,t.writeUInt32LE(c,e),e+=4,t.writeUInt32LE(o.length,e),e+=4,t.writeUInt32LE(B(o),e),e+=4,t.writeUInt32LE((r^4294967295)>>>0,e);const i=U(r);h.config.get("debug")&&h.log.debug(`${h.config.get("debugArrowSent")} ${i} arg0:${n} arg1:${c} len:${o.length}`),s.write(t),o.length>0&&s.write(o)}f(g,"sendMessage");function B(s){let r=0;for(let n=0;n<s.length;n++)r+=s[n];return r&4294967295}f(B,"checksum");export{C as create};
|
|
2
|
+
//# sourceMappingURL=stream.mjs.map
|
package/dist/api/utils.mjs
CHANGED
|
@@ -1,17 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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";function parseProperties(propOutput){const props={};const lines=propOutput.split("\n");for(const line of lines){const match=line.match(/^\[([^\]]+)\]:\s*\[([^\]]*)\]$/);if(match){const[,key,value]=match;props[key]=value}}return props}function parseListing(lsOutput){const entries=[];const lines=lsOutput.split("\n").filter(line=>line.trim());const startIdx=lines[0]?.startsWith("total")?1:0;for(let i=startIdx;i<lines.length;i++){const line=lines[i];const match=line.match(/^([drwx-]+)\s+(\d+)\s+(\w+)\s+(\w+)\s+(\d+)\s+(.+?)\s+(.+)$/);if(match){const[,permissions,links,owner,group,size,dateTime,name]=match;entries.push({name,permissions,links:parseInt(links),owner,group,size:parseInt(size),dateTime,isDirectory:permissions.startsWith("d"),isFile:permissions.startsWith("-"),isSymlink:permissions.startsWith("l")})}}return entries}function parseBattery(batteryOutput){const battery={};const lines=batteryOutput.split("\n");for(const line of lines){const match=line.match(/^\s*([^:]+):\s*(.+)$/);if(match){let[,key,value]=match;key=key.trim();value=value.trim();if(/^\d+$/.test(value)){value=parseInt(value)}battery[key]=value}}return battery}function formatBytes(bytes,decimals=2){if(bytes===0)return"0 Bytes";const k=1024;const dm=decimals<0?0:decimals;const sizes=["Bytes","KB","MB","GB","TB"];const i=Math.floor(Math.log(bytes)/Math.log(k));return parseFloat((bytes/Math.pow(k,i)).toFixed(dm))+" "+sizes[i]}function delay(ms){return new Promise(resolve=>setTimeout(resolve,ms))}async function retry(fn,options={}){const{baseDelay=1e3,maxDelay=1e4,shouldRetry=()=>true}=options;let{maxRetries=3}=options;if(maxRetries<0){console.warn(`retry: maxRetries must be >= 0, got ${maxRetries} - clamping to 0`);maxRetries=0}let lastError;for(let attempt=0;attempt<=maxRetries;attempt++){try{return await fn()}catch(error){lastError=error;if(attempt===maxRetries||!shouldRetry(error)){throw error}const delayMs=Math.min(baseDelay*Math.pow(2,attempt),maxDelay);await delay(delayMs)}}throw lastError}function isValidIP(ip){const parts=ip.split(".");if(parts.length!==4)return false;return parts.every(part=>{const num=parseInt(part,10);return num>=0&&num<=255&&part===num.toString()})}function isValidPort(port){return Number.isInteger(port)&&port>=1&&port<=65535}function parseHostPort(hostPort,defaultPort=5555){const str=String(hostPort);if(str.startsWith("[")){const closeIdx=str.indexOf("]");if(closeIdx===-1){throw new Error(`Invalid host:port (unterminated '[': ${hostPort})`)}const host2=str.slice(1,closeIdx);if(!net.isIPv6(host2)){throw new Error(`Invalid host:port (bracketed host is not a valid IPv6 address: ${hostPort})`)}const rest=str.slice(closeIdx+1);if(rest===""){return{host:host2,port:defaultPort}}if(!rest.startsWith(":")){throw new Error(`Invalid host:port (expected ':' after ']': ${hostPort})`)}const portStr2=rest.slice(1);const port2=parseInt(portStr2,10);if(!isValidPort(port2)){throw new Error(`Invalid port: ${portStr2}`)}return{host:host2,port:port2}}const colonCount=(str.match(/:/g)||[]).length;if(colonCount>1){if(net.isIPv6(str)){return{host:str,port:defaultPort}}throw new Error(`Invalid host:port - bracket an IPv6 address with a port: [${str}]:<port> (got: ${hostPort})`)}const colonIndex=str.lastIndexOf(":");if(colonIndex===-1){return{host:str,port:defaultPort}}const host=str.substring(0,colonIndex);const portStr=str.substring(colonIndex+1);const port=parseInt(portStr,10);if(!isValidPort(port)){throw new Error(`Invalid port: ${portStr}`)}return{host,port}}function sanitizeKey(deviceId){return deviceId.replace(/\./g,"_").replace(/:/g,"__")}function escapeShell(str){return str.replace(/[\\$`"]/g,"\\$&")}function quoteShellArg(str){return`'${String(str).replace(/'/g,`'\\''`)}'`}function assertValidFlags(flags){if(!Array.isArray(flags)||!flags.every(flag=>typeof flag==="string"&&flag.length>0&&!/\s/.test(flag))){let described;try{described=JSON.stringify(flags)}catch{described=String(flags)}throw new Error(`Invalid flags: ${described} (must be an array of non-empty, whitespace-free strings)`)}return flags}const MAX_IPV6=(1n<<128n)-1n;function ipv6ToBigInt(address){if(typeof address!=="string"||!net.isIPv6(address)||address.includes("%")){throw new Error(`Invalid IPv6 address: ${String(address)}`)}let text=address;const lastColon=text.lastIndexOf(":");if(text.indexOf(".",lastColon)!==-1){const tail2=text.slice(lastColon+1);if(!net.isIPv4(tail2)){throw new Error(`Invalid IPv6 address: ${address}`)}const octets=tail2.split(".").map(Number);const high=(octets[0]<<8|octets[1]).toString(16);const low=(octets[2]<<8|octets[3]).toString(16);text=`${text.slice(0,lastColon+1)}${high}:${low}`}const halves=text.split("::");if(halves.length>2){throw new Error(`Invalid IPv6 address: ${address}`)}const head=halves[0]?halves[0].split(":"):[];const tail=halves.length===2?halves[1]?halves[1].split(":"):[]:null;const fillCount=tail===null?0:8-head.length-tail.length;if(tail===null?head.length!==8:fillCount<0){throw new Error(`Invalid IPv6 address: ${address}`)}const groups=tail===null?head:[...head,...Array(fillCount).fill("0"),...tail];let value=0n;for(const group of groups){if(!/^[0-9a-fA-F]{1,4}$/.test(group)){throw new Error(`Invalid IPv6 address: ${address}`)}value=value<<16n|BigInt(parseInt(group,16))}return value}function bigIntToIpv6(value){if(typeof value!=="bigint"||value<0n||value>MAX_IPV6){throw new Error(`Invalid IPv6 value: ${String(value)} (must be a BigInt in 0..2**128-1)`)}const groups=[];for(let i=7n;i>=0n;i--){groups.push(Number(value>>i*16n&0xffffn))}let bestStart=-1;let bestLen=0;let curStart=-1;let curLen=0;for(let i=0;i<8;i++){if(groups[i]!==0){curStart=-1;curLen=0;continue}if(curStart===-1)curStart=i;curLen++;if(curLen>bestLen){bestLen=curLen;bestStart=curStart}}const hex=groups.map(group=>group.toString(16));if(bestLen<2){return hex.join(":")}return`${hex.slice(0,bestStart).join(":")}::${hex.slice(bestStart+bestLen).join(":")}`}function timeout(ms,message="Operation timed out"){return new Promise((_,reject)=>{setTimeout(()=>reject(new Error(message)),ms)})}function withTimeout(promise,ms,message){return Promise.race([promise,timeout(ms,message)])}export{assertValidFlags,bigIntToIpv6,delay,escapeShell,formatBytes,ipv6ToBigInt,isValidIP,isValidPort,parseBattery,parseHostPort,parseListing,parseProperties,quoteShellArg,retry,sanitizeKey,timeout,withTimeout};
|
|
1
|
+
var m=Object.defineProperty;var c=(t,r)=>m(t,"name",{value:r,configurable:!0});import I from"node:net";function S(t){const r={},n=t.split(`
|
|
2
|
+
`);for(const o of n){const e=o.match(/^\[([^\]]+)\]:\s*\[([^\]]*)\]$/);if(e){const[,i,l]=e;r[i]=l}}return r}c(S,"parseProperties");function b(t){const r=[],n=t.split(`
|
|
3
|
+
`).filter(e=>e.trim()),o=n[0]?.startsWith("total")?1:0;for(let e=o;e<n.length;e++){const l=n[e].match(/^([drwx-]+)\s+(\d+)\s+(\w+)\s+(\w+)\s+(\d+)\s+(.+?)\s+(.+)$/);if(l){const[,s,a,p,u,f,h,g]=l;r.push({name:g,permissions:s,links:parseInt(a),owner:p,group:u,size:parseInt(f),dateTime:h,isDirectory:s.startsWith("d"),isFile:s.startsWith("-"),isSymlink:s.startsWith("l")})}}return r}c(b,"parseListing");function E(t){const r={},n=t.split(`
|
|
4
|
+
`);for(const o of n){const e=o.match(/^\s*([^:]+):\s*(.+)$/);if(e){let[,i,l]=e;i=i.trim(),l=l.trim(),/^\d+$/.test(l)&&(l=parseInt(l)),r[i]=l}}return r}c(E,"parseBattery");function P(t,r=2){if(t===0)return"0 Bytes";const n=1024,o=r<0?0:r,e=["Bytes","KB","MB","GB","TB"],i=Math.floor(Math.log(t)/Math.log(n));return parseFloat((t/Math.pow(n,i)).toFixed(o))+" "+e[i]}c(P,"formatBytes");function d(t){return new Promise(r=>setTimeout(r,t))}c(d,"delay");async function B(t,r={}){const{baseDelay:n=1e3,maxDelay:o=1e4,shouldRetry:e=c(()=>!0,"shouldRetry")}=r;let{maxRetries:i=3}=r;i<0&&(console.warn(`retry: maxRetries must be >= 0, got ${i} - clamping to 0`),i=0);let l;for(let s=0;s<=i;s++)try{return await t()}catch(a){if(l=a,s===i||!e(a))throw a;const p=Math.min(n*Math.pow(2,s),o);await d(p)}throw l}c(B,"retry");function M(t){const r=t.split(".");return r.length!==4?!1:r.every(n=>{const o=parseInt(n,10);return o>=0&&o<=255&&n===o.toString()})}c(M,"isValidIP");function w(t){return Number.isInteger(t)&&t>=1&&t<=65535}c(w,"isValidPort");function k(t,r=5555){const n=String(t);if(n.startsWith("[")){const a=n.indexOf("]");if(a===-1)throw new Error(`Invalid host:port (unterminated '[': ${t})`);const p=n.slice(1,a);if(!I.isIPv6(p))throw new Error(`Invalid host:port (bracketed host is not a valid IPv6 address: ${t})`);const u=n.slice(a+1);if(u==="")return{host:p,port:r};if(!u.startsWith(":"))throw new Error(`Invalid host:port (expected ':' after ']': ${t})`);const f=u.slice(1),h=parseInt(f,10);if(!w(h))throw new Error(`Invalid port: ${f}`);return{host:p,port:h}}if((n.match(/:/g)||[]).length>1){if(I.isIPv6(n))return{host:n,port:r};throw new Error(`Invalid host:port - bracket an IPv6 address with a port: [${n}]:<port> (got: ${t})`)}const e=n.lastIndexOf(":");if(e===-1)return{host:n,port:r};const i=n.substring(0,e),l=n.substring(e+1),s=parseInt(l,10);if(!w(s))throw new Error(`Invalid port: ${l}`);return{host:i,port:s}}c(k,"parseHostPort");function T(t){return t.replace(/\./g,"_").replace(/:/g,"__")}c(T,"sanitizeKey");function A(t){return t.replace(/[\\$`"]/g,"\\$&")}c(A,"escapeShell");function O(t){return`'${String(t).replace(/'/g,"'\\''")}'`}c(O,"quoteShellArg");function W(t){if(!Array.isArray(t)||!t.every(r=>typeof r=="string"&&r.length>0&&!/\s/.test(r))){let r;try{r=JSON.stringify(t)}catch{r=String(t)}throw new Error(`Invalid flags: ${r} (must be an array of non-empty, whitespace-free strings)`)}return t}c(W,"assertValidFlags");const x=(1n<<128n)-1n;function F(t){if(typeof t!="string"||!I.isIPv6(t)||t.includes("%"))throw new Error(`Invalid IPv6 address: ${String(t)}`);let r=t;const n=r.lastIndexOf(":");if(r.indexOf(".",n)!==-1){const p=r.slice(n+1);if(!I.isIPv4(p))throw new Error(`Invalid IPv6 address: ${t}`);const u=p.split(".").map(Number),f=(u[0]<<8|u[1]).toString(16),h=(u[2]<<8|u[3]).toString(16);r=`${r.slice(0,n+1)}${f}:${h}`}const o=r.split("::");if(o.length>2)throw new Error(`Invalid IPv6 address: ${t}`);const e=o[0]?o[0].split(":"):[],i=o.length===2?o[1]?o[1].split(":"):[]:null,l=i===null?0:8-e.length-i.length;if(i===null?e.length!==8:l<0)throw new Error(`Invalid IPv6 address: ${t}`);const s=i===null?e:[...e,...Array(l).fill("0"),...i];let a=0n;for(const p of s){if(!/^[0-9a-fA-F]{1,4}$/.test(p))throw new Error(`Invalid IPv6 address: ${t}`);a=a<<16n|BigInt(parseInt(p,16))}return a}c(F,"ipv6ToBigInt");function _(t){if(typeof t!="bigint"||t<0n||t>x)throw new Error(`Invalid IPv6 value: ${String(t)} (must be a BigInt in 0..2**128-1)`);const r=[];for(let s=7n;s>=0n;s--)r.push(Number(t>>s*16n&0xffffn));let n=-1,o=0,e=-1,i=0;for(let s=0;s<8;s++){if(r[s]!==0){e=-1,i=0;continue}e===-1&&(e=s),i++,i>o&&(o=i,n=e)}const l=r.map(s=>s.toString(16));return o<2?l.join(":"):`${l.slice(0,n).join(":")}::${l.slice(n+o).join(":")}`}c(_,"bigIntToIpv6");function v(t,r="Operation timed out"){return new Promise((n,o)=>{setTimeout(()=>o(new Error(r)),t)})}c(v,"timeout");function z(t,r,n){return Promise.race([t,v(r,n)])}c(z,"withTimeout");export{W as assertValidFlags,_ as bigIntToIpv6,d as delay,A as escapeShell,P as formatBytes,F as ipv6ToBigInt,M as isValidIP,w as isValidPort,E as parseBattery,k as parseHostPort,b as parseListing,S as parseProperties,O as quoteShellArg,B as retry,T as sanitizeKey,v as timeout,z as withTimeout};
|
|
5
|
+
//# sourceMappingURL=utils.mjs.map
|
package/dist/droidsock.mjs
CHANGED
|
@@ -1,17 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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 slothlet from"@cldmv/slothlet";import path from"node:path";import{fileURLToPath}from"node:url";const __filename=fileURLToPath(import.meta.url);const __dirname=path.dirname(__filename);async function createDroidSock(options={}){const{mode="eager",context={},config={},...slothletOptions}=options;const api=await slothlet({base:path.join(__dirname,"api"),mode,runtime:"async",context:{...context},debug:false,sanitize:{lowerFirst:false,rules:{leave:["ADB","TCP","USB","Auth","Sync"],upper:["adb*","tcp*","usb*"]}},...slothletOptions});if(Object.keys(config).length>0){api.config.init(config)}return api}export{createDroidSock as default};
|
|
1
|
+
var c=Object.defineProperty;var n=(t,e)=>c(t,"name",{value:e,configurable:!0});import l from"@cldmv/slothlet";import a from"node:path";import{fileURLToPath as m}from"node:url";const f=m(import.meta.url),p=a.dirname(f);async function u(t={}){const{mode:e="eager",context:r={},config:o={},...s}=t,i=await l({base:a.join(p,"api"),mode:e,runtime:"async",context:{...r},debug:!1,sanitize:{lowerFirst:!1,rules:{leave:["ADB","TCP","USB","Auth","Sync"],upper:["adb*","tcp*","usb*"]}},...s});return Object.keys(o).length>0&&i.config.init(o),i}n(u,"createDroidSock");export{u as default};
|
|
2
|
+
//# sourceMappingURL=droidsock.mjs.map
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
*
|
|
3
|
+
* @Project: @cldmv/droidsock
|
|
4
|
+
* @Filename: /src/index.cjs
|
|
5
|
+
* @Date: 2025-11-21T15:41:06-08:00 (1763768466)
|
|
6
|
+
* @Author: Nate Corcoran <CLDMV>
|
|
7
|
+
* @Email: <Shinrai@users.noreply.github.com>
|
|
8
|
+
* -----
|
|
9
|
+
* @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
|
|
10
|
+
* @Last modified time: 2026-11-01T16:38:35-08:00 (1793579915)
|
|
11
|
+
* -----
|
|
12
|
+
* @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
|
|
13
|
+
*
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* CommonJS entry point: a thin, synchronous re-export of the ESM entry.
|
|
18
|
+
*
|
|
19
|
+
* Node's `require()` loads an ES module synchronously as long as its module graph has no
|
|
20
|
+
* top-level await, so this file re-exports ./index.mjs instead of a second, CommonJS build
|
|
21
|
+
* of the library. tsup.config.mjs copies it verbatim to dist/index.cjs; `./index.mjs`
|
|
22
|
+
* resolves to the sibling src/index.mjs in a checkout and to the build in dist/.
|
|
23
|
+
*
|
|
24
|
+
* The CommonJS shape is the factory itself (`module.exports = createDroidSock`), with the
|
|
25
|
+
* named aliases as properties on it.
|
|
26
|
+
*
|
|
27
|
+
* @module droidsock
|
|
28
|
+
*/
|
|
29
|
+
"use strict";
|
|
30
|
+
|
|
31
|
+
// Node.js versions without require(esm) (before 20.19 / 22.12) would fail with a bare
|
|
32
|
+
// ERR_REQUIRE_ESM, so fail early with a message that says what to do instead.
|
|
33
|
+
if (!process.features?.require_module) {
|
|
34
|
+
const error = new Error(
|
|
35
|
+
`@cldmv/droidsock: require() needs Node.js >=22.15.0 (this is ${process.version}). On older Node.js, load the package with import() instead.`
|
|
36
|
+
);
|
|
37
|
+
error.code = "ERR_REQUIRE_ESM";
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const { default: droidsock } = require("./index.mjs");
|
|
42
|
+
|
|
43
|
+
// Export main function - the quick path, also callable with options
|
|
44
|
+
module.exports = droidsock; // Default export
|
|
45
|
+
module.exports.createDroidSock = droidsock;
|
|
46
|
+
|
|
47
|
+
// Common DroidSock aliases
|
|
48
|
+
module.exports.DroidSock = droidsock;
|
|
49
|
+
module.exports.ADB = droidsock;
|
|
50
|
+
module.exports.AndroidDebugBridge = droidsock;
|
package/dist/index.mjs
ADDED
package/dist/main.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e='"@cldmv/droidsock/main" is deprecated; import "@cldmv/droidsock" instead.';typeof process<"u"&&typeof process.emitWarning=="function"?process.emitWarning(e,{type:"DeprecationWarning",code:"CLDMV_DROIDSOCK_MAIN"}):console.warn(`DeprecationWarning: ${e}`);export*from"./index.mjs";import{default as i}from"./index.mjs";export{i as default};
|
|
2
|
+
//# sourceMappingURL=main.mjs.map
|
package/package.json
CHANGED
|
@@ -1,35 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cldmv/droidsock",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "Complete Node.js implementation of the Android Debug Bridge (ADB) protocol",
|
|
5
|
-
"main": "./index.cjs",
|
|
6
|
-
"module": "./index.mjs",
|
|
7
|
-
"types": "./types/index.d.mts",
|
|
5
|
+
"main": "./dist/index.cjs",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./types/src/index.d.mts",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": {
|
|
10
|
-
"
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
"droidsock-dev": {
|
|
11
|
+
"types": "./types/src/index.d.mts",
|
|
12
|
+
"import": "./src/index.mjs",
|
|
13
|
+
"require": "./src/index.cjs"
|
|
14
|
+
},
|
|
15
|
+
"types": "./types/src/index.d.mts",
|
|
16
|
+
"import": "./dist/index.mjs",
|
|
17
|
+
"require": "./dist/index.cjs"
|
|
13
18
|
},
|
|
14
19
|
"./main": {
|
|
15
20
|
"droidsock-dev": {
|
|
16
|
-
"types": "./types/src/
|
|
17
|
-
"import": "./src/
|
|
21
|
+
"types": "./types/src/index.d.mts",
|
|
22
|
+
"import": "./src/main.mjs"
|
|
18
23
|
},
|
|
19
|
-
"types": "./types/
|
|
20
|
-
"import": "./dist/
|
|
21
|
-
}
|
|
24
|
+
"types": "./types/src/index.d.mts",
|
|
25
|
+
"import": "./dist/main.mjs"
|
|
26
|
+
},
|
|
27
|
+
"./package.json": "./package.json"
|
|
22
28
|
},
|
|
23
29
|
"type": "module",
|
|
24
30
|
"engines": {
|
|
25
31
|
"node": ">=22.15.0"
|
|
26
32
|
},
|
|
33
|
+
"devEngines": {
|
|
34
|
+
"runtime": {
|
|
35
|
+
"name": "node",
|
|
36
|
+
"version": ">=22.22.0",
|
|
37
|
+
"onFail": "error"
|
|
38
|
+
}
|
|
39
|
+
},
|
|
27
40
|
"scripts": {
|
|
28
|
-
"build": "
|
|
29
|
-
"build
|
|
30
|
-
"build:ci": "npm run
|
|
41
|
+
"build": "tsup",
|
|
42
|
+
"types:build": "tsc --project .configs/tsconfig.dts.jsonc",
|
|
43
|
+
"build:ci": "npm run lint && npm run format:check && npm run types:build && npm run build",
|
|
44
|
+
"prepack": "npm run build",
|
|
31
45
|
"test": "node tests/run-vitest.mjs && npm run test:cjs",
|
|
32
|
-
"test:cjs": "
|
|
46
|
+
"test:cjs": "npm run build && node --conditions=droidsock-dev --test tests/cjs/entry.test.cjs",
|
|
33
47
|
"test:watch": "vitest --config .configs/vitest.config.mjs",
|
|
34
48
|
"test:types": "tsc --noEmit --project .configs/tsconfig.dts.jsonc",
|
|
35
49
|
"coverage": "node tests/run-vitest.mjs --coverage-quiet && npm run test:cjs",
|
|
@@ -41,7 +55,7 @@
|
|
|
41
55
|
"fix:headers": "fix-headers --config .configs/fix-headers.json",
|
|
42
56
|
"prepare": "node -e \"import('./.githooks/install.mjs').catch(()=>{})\"",
|
|
43
57
|
"precommit:local": "npm run test:types",
|
|
44
|
-
"precommit": "npm run build
|
|
58
|
+
"precommit": "npm run build:ci && npm run test:types && npm run test"
|
|
45
59
|
},
|
|
46
60
|
"keywords": [
|
|
47
61
|
"adb",
|
|
@@ -89,39 +103,41 @@
|
|
|
89
103
|
"access": "public"
|
|
90
104
|
},
|
|
91
105
|
"files": [
|
|
92
|
-
"
|
|
93
|
-
"
|
|
94
|
-
"
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
"
|
|
98
|
-
"
|
|
99
|
-
"dist/"
|
|
106
|
+
"dist/",
|
|
107
|
+
"!dist/**/*.map",
|
|
108
|
+
"types/"
|
|
109
|
+
],
|
|
110
|
+
"sideEffects": [
|
|
111
|
+
"./src/main.mjs",
|
|
112
|
+
"./dist/main.mjs"
|
|
100
113
|
],
|
|
101
|
-
"sideEffects": false,
|
|
102
114
|
"devDependencies": {
|
|
103
|
-
"@cldmv/configs": "^1.
|
|
104
|
-
"@cldmv/eslint-plugin-jsonv": "^1.0.
|
|
105
|
-
"@cldmv/fix-headers": "^2.2.
|
|
106
|
-
"@cldmv/jsonv": "^1.
|
|
107
|
-
"@cldmv/prettier-plugin-jsonv": "^1.
|
|
108
|
-
"@cldmv/vitest-runner": "^1.
|
|
109
|
-
"@eslint/css": "^2.0.
|
|
115
|
+
"@cldmv/configs": "^1.3.0",
|
|
116
|
+
"@cldmv/eslint-plugin-jsonv": "^1.0.17",
|
|
117
|
+
"@cldmv/fix-headers": "^2.2.4",
|
|
118
|
+
"@cldmv/jsonv": "^1.1.5",
|
|
119
|
+
"@cldmv/prettier-plugin-jsonv": "^1.1.4",
|
|
120
|
+
"@cldmv/vitest-runner": "^1.5.6",
|
|
121
|
+
"@eslint/css": "^2.0.1",
|
|
110
122
|
"@eslint/js": "^10.0.1",
|
|
111
|
-
"@eslint/json": "^2.
|
|
123
|
+
"@eslint/json": "^2.1.1",
|
|
112
124
|
"@eslint/markdown": "^8.0.3",
|
|
113
|
-
"@types/node": "^26.
|
|
114
|
-
"@vitest/coverage-v8": "^5.0.
|
|
115
|
-
"
|
|
116
|
-
"
|
|
117
|
-
"
|
|
118
|
-
"
|
|
125
|
+
"@types/node": "^26.6.6",
|
|
126
|
+
"@vitest/coverage-v8": "^5.0.5",
|
|
127
|
+
"eslint": "^10.14.0",
|
|
128
|
+
"globals": "^17.14.0",
|
|
129
|
+
"prettier": "^3.9.10",
|
|
130
|
+
"tsup": "^9.0.0",
|
|
119
131
|
"typescript": "^6.0.3",
|
|
120
|
-
"vitest": "^5.0.
|
|
132
|
+
"vitest": "^5.0.5"
|
|
121
133
|
},
|
|
122
134
|
"dependencies": {
|
|
123
|
-
"@cldmv/slothlet": "^3.
|
|
135
|
+
"@cldmv/slothlet": "^3.22.1",
|
|
124
136
|
"@noble/curves": "^2.4.0",
|
|
125
137
|
"selfsigned": "^5.5.0"
|
|
138
|
+
},
|
|
139
|
+
"overrides": {
|
|
140
|
+
"katex": ">=0.19.1 <1.0.0",
|
|
141
|
+
"minimatch": "^11.0.3"
|
|
126
142
|
}
|
|
127
143
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gets or creates RSA key pair for ADB authentication
|
|
3
|
+
* @param {string} [keyDir] - Directory to store keys (default: ~/.adb)
|
|
4
|
+
* @returns {Object} Key pair object with publicKey, privateKey, and adbPublicKey
|
|
5
|
+
*/
|
|
6
|
+
export function getKeys(keyDir?: string): Object;
|
|
7
|
+
/**
|
|
8
|
+
* Generates a new RSA key pair for ADB authentication
|
|
9
|
+
* @param {number} [keySize=2048] - Key size in bits
|
|
10
|
+
* @param {string} [saveDir] - Directory to save keys
|
|
11
|
+
* @returns {Object} Key pair object with publicKey, privateKey, and adbPublicKey
|
|
12
|
+
*/
|
|
13
|
+
export function generateKeys(keySize?: number, saveDir?: string): Object;
|
|
14
|
+
/**
|
|
15
|
+
* Signs an ADB authentication token using AOSP-style signature
|
|
16
|
+
* @param {Buffer} token - Token to sign (20-byte SHA1 hash)
|
|
17
|
+
* @param {string} privateKey - Private key in PEM format
|
|
18
|
+
* @returns {Buffer} Signature bytes
|
|
19
|
+
*/
|
|
20
|
+
export function sign(token: Buffer, privateKey: string): Buffer;
|
|
21
|
+
/**
|
|
22
|
+
* Validates a token and private key for signing
|
|
23
|
+
* @param {Buffer} token - Token to validate
|
|
24
|
+
* @param {string} privateKey - Private key to validate
|
|
25
|
+
* @returns {boolean} True if valid
|
|
26
|
+
*/
|
|
27
|
+
export function validateAuth(token: Buffer, privateKey: string): boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Creates ADB-compatible public key format from RSA public key using SSH wire format
|
|
30
|
+
* @param {string} publicKey - Public key in PEM format
|
|
31
|
+
* @returns {string} ADB-compatible public key string with null terminator
|
|
32
|
+
*/
|
|
33
|
+
export function formatAdbPublicKey(publicKey: string): string;
|
|
34
|
+
//# sourceMappingURL=auth.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.d.mts","sourceRoot":"","sources":["../../../src/api/auth.mjs"],"names":[],"mappings":"AAyBA;;;;GAIG;AACH,iCAHW,MAAM,GACJ,MAAM,CA6BlB;AAED;;;;;GAKG;AACH,uCAJW,MAAM,YACN,MAAM,GACJ,MAAM,CAgClB;AAED;;;;;GAKG;AACH,4BAJW,MAAM,cACN,MAAM,GACJ,MAAM,CA4DlB;AAwCD;;;;;GAKG;AACH,oCAJW,MAAM,cACN,MAAM,GACJ,OAAO,CAgBnB;AAED;;;;GAIG;AACH,8CAHW,MAAM,GACJ,MAAM,CA2ClB"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Initialize or get the configuration instance
|
|
3
|
+
* @param {Object} options - Initial configuration options
|
|
4
|
+
* @returns {Object} Configuration API
|
|
5
|
+
*/
|
|
6
|
+
export function init(options?: Object): Object;
|
|
7
|
+
/**
|
|
8
|
+
* Get configuration value
|
|
9
|
+
* @param {string} key - Configuration key (dot notation supported)
|
|
10
|
+
* @param {*} defaultValue - Default value if key not found
|
|
11
|
+
* @returns {*} Configuration value
|
|
12
|
+
*/
|
|
13
|
+
export function get(key: string, defaultValue?: any): any;
|
|
14
|
+
/**
|
|
15
|
+
* Set a configuration value
|
|
16
|
+
* @param {string} key - Configuration key (dot notation supported)
|
|
17
|
+
* @param {*} value - Value to set
|
|
18
|
+
*/
|
|
19
|
+
export function set(key: string, value: any): void;
|
|
20
|
+
/**
|
|
21
|
+
* Merge configuration options
|
|
22
|
+
* @param {Object} options - Options to merge
|
|
23
|
+
*/
|
|
24
|
+
export function merge(options: Object): void;
|
|
25
|
+
/**
|
|
26
|
+
* Reset configuration to defaults
|
|
27
|
+
*/
|
|
28
|
+
export function reset(): void;
|
|
29
|
+
/**
|
|
30
|
+
* Get all configuration as plain object
|
|
31
|
+
* @returns {Object} Configuration object
|
|
32
|
+
*/
|
|
33
|
+
export function all(): Object;
|
|
34
|
+
/**
|
|
35
|
+
* Get the configuration API
|
|
36
|
+
* @returns {Object} Configuration API
|
|
37
|
+
*/
|
|
38
|
+
export function getApi(): Object;
|
|
39
|
+
/**
|
|
40
|
+
* Get default configuration
|
|
41
|
+
* @returns {Object} Default configuration object
|
|
42
|
+
*/
|
|
43
|
+
export function getDefaults(): Object;
|
|
44
|
+
/**
|
|
45
|
+
* Validate configuration object
|
|
46
|
+
* @param {Object} config - Configuration to validate
|
|
47
|
+
* @returns {Object} Validation result with errors array
|
|
48
|
+
*/
|
|
49
|
+
export function validateConfig(config: Object): Object;
|
|
50
|
+
//# sourceMappingURL=config.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.d.mts","sourceRoot":"","sources":["../../../src/api/config.mjs"],"names":[],"mappings":"AAoEA;;;;GAIG;AACH,+BAHW,MAAM,GACJ,MAAM,CAOlB;AAED;;;;;GAKG;AACH,yBAJW,MAAM,iBACN,GAAC,GACC,GAAC,CAmBb;AAED;;;;GAIG;AACH,yBAHW,MAAM,SACN,GAAC,QAmBX;AAED;;;GAGG;AACH,+BAFW,MAAM,QAuBhB;AAED;;GAEG;AACH,8BAEC;AAED;;;GAGG;AACH,uBAFa,MAAM,CAIlB;AAED;;;GAGG;AACH,0BAFa,MAAM,CAWlB;AAED;;;GAGG;AACH,+BAFa,MAAM,CAIlB;AAED;;;;GAIG;AACH,uCAHW,MAAM,GACJ,MAAM,CAkClB"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates an ADB connection to a device
|
|
3
|
+
* @param {Object} options - Connection options
|
|
4
|
+
* @param {string} options.host - Device host/IP
|
|
5
|
+
* @param {number} options.port - Device port
|
|
6
|
+
* @param {string} options.privateKey - RSA private key
|
|
7
|
+
* @param {string} options.adbPublicKey - ADB-formatted public key
|
|
8
|
+
* @returns {Promise<Object>} Connection object
|
|
9
|
+
*/
|
|
10
|
+
export function create(options: {
|
|
11
|
+
host: string;
|
|
12
|
+
port: number;
|
|
13
|
+
privateKey: string;
|
|
14
|
+
adbPublicKey: string;
|
|
15
|
+
}): Promise<Object>;
|
|
16
|
+
//# sourceMappingURL=connection.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connection.d.mts","sourceRoot":"","sources":["../../../src/api/connection.mjs"],"names":[],"mappings":"AA0CA;;;;;;;;GAQG;AACH,gCANG;IAAwB,IAAI,EAApB,MAAM;IACU,IAAI,EAApB,MAAM;IACU,UAAU,EAA1B,MAAM;IACU,YAAY,EAA5B,MAAM;CACd,GAAU,OAAO,CAAC,MAAM,CAAC,CAsH3B"}
|