first commit
This commit is contained in:
commit
b6256abbfb
397 files changed
+537630
No files matched your search
@@ -0,0 +1,161 @@
|
||||
import { LocoSocket } from "./net/index.js";
|
||||
import type {
|
||||
LocoClientConfig,
|
||||
LoginCredentials,
|
||||
LocoPacketHeader,
|
||||
DEFAULT_CONFIG,
|
||||
} from "./types/index.ts";
|
||||
|
||||
export interface ChatMessage {
|
||||
chatId: number;
|
||||
msgId: number;
|
||||
message: string;
|
||||
type: number;
|
||||
sender?: number;
|
||||
}
|
||||
|
||||
export class LocoClient {
|
||||
private socket: LocoSocket;
|
||||
private config: LocoClientConfig;
|
||||
private credentials: LoginCredentials;
|
||||
|
||||
/** Callback for incoming messages */
|
||||
onMessage?: (msg: ChatMessage) => void;
|
||||
|
||||
/** Callback for any incoming packet (for debugging/analysis) */
|
||||
onPacket?: (header: LocoPacketHeader, body: Record<string, unknown>) => void;
|
||||
|
||||
constructor(config: LocoClientConfig, credentials: LoginCredentials) {
|
||||
this.config = config;
|
||||
this.credentials = credentials;
|
||||
this.socket = new LocoSocket(config);
|
||||
|
||||
this.socket.on("packet", (header, body) => {
|
||||
this.onPacket?.(header, body);
|
||||
if (header.command === "MSG") {
|
||||
this.handleMsg(body);
|
||||
}
|
||||
});
|
||||
|
||||
this.socket.on("error", (err) => {
|
||||
console.error("[LocoClient] Socket error:", err.message);
|
||||
});
|
||||
|
||||
this.socket.on("close", () => {
|
||||
console.log("[LocoClient] Connection closed.");
|
||||
});
|
||||
}
|
||||
|
||||
/** Full login sequence: connect → RSA handshake → CHECKIN → LOGINLIST → SETST → GETTOKEN */
|
||||
async login(): Promise<Record<string, unknown>> {
|
||||
console.log(
|
||||
`[LocoClient] Connecting to ${this.config.host}:${this.config.port}...`,
|
||||
);
|
||||
await this.socket.connect();
|
||||
console.log("[LocoClient] Handshake complete.");
|
||||
|
||||
// Step 1: CHECKIN
|
||||
console.log("[LocoClient] Sending CHECKIN...");
|
||||
const checkinResp = await this.socket.request("CHECKIN", {
|
||||
userId: this.credentials.userId,
|
||||
os: "android",
|
||||
ntype: 0,
|
||||
appVer: this.credentials.appVer,
|
||||
lang: this.credentials.lang,
|
||||
MCCMNC: this.credentials.mccmnc,
|
||||
});
|
||||
console.log(
|
||||
"[LocoClient] CHECKIN response:",
|
||||
JSON.stringify(checkinResp.body, null, 2),
|
||||
);
|
||||
|
||||
// Step 2: LOGINLIST
|
||||
console.log("[LocoClient] Sending LOGINLIST...");
|
||||
const loginResp = await this.socket.request("LOGINLIST", {
|
||||
appVer: this.credentials.appVer,
|
||||
prtVer: "1",
|
||||
os: "android",
|
||||
lang: this.credentials.lang,
|
||||
duuid: this.credentials.duuid,
|
||||
ntype: 0,
|
||||
MCCMNC: this.credentials.mccmnc,
|
||||
revision: 0,
|
||||
chatIds: [],
|
||||
maxIds: [],
|
||||
lastTokenId: 0,
|
||||
lbk: 0,
|
||||
bg: true,
|
||||
oauthToken: this.credentials.oauthToken,
|
||||
rp: Buffer.from([0x01, 0x00, 0xff, 0xff, 0x01, 0x00]),
|
||||
});
|
||||
console.log(
|
||||
"[LocoClient] LOGINLIST response status:",
|
||||
loginResp.header.statusCode,
|
||||
);
|
||||
|
||||
// Step 3: SETST (set status = 2, "away/background")
|
||||
console.log("[LocoClient] Sending SETST (st=2)...");
|
||||
await this.socket.request("SETST", { st: 2 });
|
||||
|
||||
// Step 4: GETTOKEN
|
||||
console.log("[LocoClient] Sending GETTOKEN...");
|
||||
await this.socket.request("GETTOKEN", {
|
||||
ts: [2, 3, 11, 12, 4, 9, 10, 18, 19],
|
||||
});
|
||||
|
||||
// Step 5: SETST (set status = 1, "online/foreground")
|
||||
console.log("[LocoClient] Sending SETST (st=1)...");
|
||||
await this.socket.request("SETST", { st: 1 });
|
||||
|
||||
return loginResp.body;
|
||||
}
|
||||
|
||||
/** Send a text message to a chat room. */
|
||||
async sendMessage(chatId: number, text: string): Promise<void> {
|
||||
await this.socket.request("WRITE", {
|
||||
msg: text,
|
||||
c: chatId,
|
||||
t: 1,
|
||||
});
|
||||
}
|
||||
|
||||
/** Request message sync for a chat room. */
|
||||
async syncMessages(
|
||||
chatId: number,
|
||||
count: number = 20,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const resp = await this.socket.request("SYNCMSG", {
|
||||
chatId,
|
||||
cnt: count,
|
||||
cur: 0,
|
||||
max: 0,
|
||||
});
|
||||
return resp.body;
|
||||
}
|
||||
|
||||
/** Listen for packets (keeps the connection alive). */
|
||||
listen(): void {
|
||||
console.log("[LocoClient] Listening for incoming packets...");
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
this.socket.disconnect();
|
||||
}
|
||||
|
||||
// -- private --
|
||||
|
||||
private handleMsg(body: Record<string, unknown>): void {
|
||||
const chatLog = body["chatLog"] as Record<string, unknown> | undefined;
|
||||
if (!chatLog) return;
|
||||
|
||||
const msg: ChatMessage = {
|
||||
chatId: body["chatId"] as number,
|
||||
msgId: chatLog["msgId"] as number,
|
||||
message: chatLog["message"] as string,
|
||||
type: chatLog["type"] as number,
|
||||
sender: chatLog["authorId"] as number,
|
||||
};
|
||||
|
||||
this.onMessage?.(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
randomBytes,
|
||||
} from "node:crypto";
|
||||
|
||||
const GCM_ALGORITHM = "aes-128-gcm";
|
||||
|
||||
/** GCM nonce size in bytes */
|
||||
export const NONCE_SIZE = 12;
|
||||
|
||||
/** GCM authentication tag size in bytes */
|
||||
export const TAG_SIZE = 16;
|
||||
|
||||
/**
|
||||
* Encrypt with AES-128-GCM.
|
||||
* Returns ciphertext + 16-byte auth tag appended.
|
||||
*/
|
||||
export function aesEncryptGCM(
|
||||
plaintext: Buffer,
|
||||
key: Buffer,
|
||||
nonce: Buffer,
|
||||
): Buffer {
|
||||
const cipher = createCipheriv(GCM_ALGORITHM, key, nonce);
|
||||
const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return Buffer.concat([encrypted, tag]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt AES-128-GCM. Input is ciphertext with 16-byte auth tag appended.
|
||||
*/
|
||||
export function aesDecryptGCM(
|
||||
ciphertextWithTag: Buffer,
|
||||
key: Buffer,
|
||||
nonce: Buffer,
|
||||
): Buffer {
|
||||
const ciphertext = ciphertextWithTag.subarray(
|
||||
0,
|
||||
ciphertextWithTag.length - TAG_SIZE,
|
||||
);
|
||||
const tag = ciphertextWithTag.subarray(ciphertextWithTag.length - TAG_SIZE);
|
||||
|
||||
const decipher = createDecipheriv(GCM_ALGORITHM, key, nonce);
|
||||
decipher.setAuthTag(tag);
|
||||
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||
}
|
||||
|
||||
export function generateAESKey(): Buffer {
|
||||
return randomBytes(16);
|
||||
}
|
||||
|
||||
export function generateNonce(): Buffer {
|
||||
return randomBytes(NONCE_SIZE);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export {
|
||||
aesEncryptGCM,
|
||||
aesDecryptGCM,
|
||||
generateAESKey,
|
||||
generateNonce,
|
||||
NONCE_SIZE,
|
||||
TAG_SIZE,
|
||||
} from "./aes.js";
|
||||
export { rsaEncryptOAEP, toPem } from "./rsa.js";
|
||||
@@ -0,0 +1,30 @@
|
||||
import { publicEncrypt, constants } from "node:crypto";
|
||||
|
||||
/**
|
||||
* RSA-OAEP encrypt with SHA1 (matches KakaoTalk's RSA/NONE/OAEPWithSHA1AndMGF1Padding).
|
||||
* Used during handshake to send the AES session key to the server.
|
||||
*/
|
||||
export function rsaEncryptOAEP(
|
||||
plaintext: Buffer,
|
||||
publicKeyPem: string,
|
||||
): Buffer {
|
||||
return publicEncrypt(
|
||||
{
|
||||
key: publicKeyPem,
|
||||
padding: constants.RSA_PKCS1_OAEP_PADDING,
|
||||
oaepHash: "sha1",
|
||||
},
|
||||
plaintext,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a raw base64 public key (no PEM headers) into PEM format.
|
||||
*/
|
||||
export function toPem(base64Key: string): string {
|
||||
const lines: string[] = [];
|
||||
for (let i = 0; i < base64Key.length; i += 64) {
|
||||
lines.push(base64Key.slice(i, i + 64));
|
||||
}
|
||||
return `-----BEGIN PUBLIC KEY-----\n${lines.join("\n")}\n-----END PUBLIC KEY-----\n`;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import "dotenv/config";
|
||||
export { LocoClient, type ChatMessage } from "./client.js";
|
||||
export {
|
||||
LocoSocket,
|
||||
fetchBookingServer,
|
||||
resolveCheckinServer,
|
||||
} from "./net/index.js";
|
||||
export {
|
||||
buildLocoPacket,
|
||||
parseLocoPacket,
|
||||
buildEncryptedPacket,
|
||||
parseEncryptedPacket,
|
||||
buildHandshakePacket,
|
||||
PacketReader,
|
||||
} from "./protocol/index.js";
|
||||
export {
|
||||
aesEncryptGCM,
|
||||
aesDecryptGCM,
|
||||
generateAESKey,
|
||||
generateNonce,
|
||||
rsaEncryptOAEP,
|
||||
toPem,
|
||||
} from "./crypto/index.js";
|
||||
export type * from "./types/index.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Example: run directly with `node --experimental-strip-types src/index.ts`
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const isMain = process.argv[1]?.endsWith("index.js");
|
||||
|
||||
if (isMain) {
|
||||
const { LocoClient } = await import("./client.js");
|
||||
const { toPem } = await import("./crypto/rsa.js");
|
||||
const { resolveCheckinServer } = await import("./net/booking.js");
|
||||
|
||||
const pubkeyHex = process.env["LOCO_SERVER_PUBKEY_HEX"] ?? "";
|
||||
const serverPublicKey = pubkeyHex
|
||||
? toPem(Buffer.from(pubkeyHex, "hex").toString("base64"))
|
||||
: "";
|
||||
|
||||
const credentials = {
|
||||
oauthToken: process.env["LOCO_OAUTH_TOKEN"] ?? "",
|
||||
duuid: process.env["LOCO_DUUID"] ?? "",
|
||||
userId: Number(process.env["LOCO_USER_ID"] ?? "0"),
|
||||
appVer: process.env["LOCO_APP_VER"] ?? "26.1.2",
|
||||
lang: "ko",
|
||||
mccmnc: "45005",
|
||||
};
|
||||
|
||||
if (!serverPublicKey || !credentials.oauthToken) {
|
||||
console.error(
|
||||
"Missing environment variables. Required:\n" +
|
||||
" LOCO_SERVER_PUBKEY_HEX - Server RSA public key (DER hex)\n" +
|
||||
" LOCO_OAUTH_TOKEN - OAuth token from Frida capture\n" +
|
||||
" LOCO_DUUID - Device UUID\n" +
|
||||
" LOCO_USER_ID - KakaoTalk user ID\n" +
|
||||
" LOCO_APP_VER - App version (default: 26.1.2)\n",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Step 1: Booking — discover LOCO server via LOCO protocol
|
||||
console.log("[Booking] Resolving LOCO server from booking-loco.kakao.com...");
|
||||
const locoServer = await resolveCheckinServer(serverPublicKey, {
|
||||
os: "android",
|
||||
MCCMNC: credentials.mccmnc,
|
||||
model: "",
|
||||
});
|
||||
console.log(`[Booking] LOCO server: ${locoServer.host}:${locoServer.port}`);
|
||||
|
||||
// Step 2: Connect to LOCO server (raw TCP + RSA handshake + AES-GCM)
|
||||
// CHECKIN + LOGINLIST + all commands happen on this single encrypted connection
|
||||
const config = {
|
||||
host: locoServer.host,
|
||||
port: locoServer.port,
|
||||
useTLS: false,
|
||||
serverPublicKey,
|
||||
};
|
||||
|
||||
const client = new LocoClient(config, credentials);
|
||||
|
||||
// Log every raw packet for protocol analysis
|
||||
client.onPacket = (header, body) => {
|
||||
console.log(
|
||||
`[${header.command}] id=${header.id} status=${header.statusCode}`,
|
||||
);
|
||||
console.log(JSON.stringify(body, null, 2));
|
||||
console.log("---");
|
||||
};
|
||||
|
||||
// Log decoded messages
|
||||
client.onMessage = (msg) => {
|
||||
console.log(
|
||||
`\n[Chat ${msg.chatId}] sender=${msg.sender}: ${msg.message}\n`,
|
||||
);
|
||||
};
|
||||
|
||||
try {
|
||||
const loginData = await client.login();
|
||||
console.log("[LocoClient] Login successful. Chat data received.");
|
||||
client.listen();
|
||||
} catch (err) {
|
||||
console.error("[LocoClient] Failed:", err);
|
||||
client.disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* LOCO Booking — connects to booking-loco.kakao.com:443 over TLS,
|
||||
* performs LOCO RSA handshake, sends GETCONF, and returns checkin server info.
|
||||
*
|
||||
* Flow (based on kiwitalk reference):
|
||||
* 1. TLS connect to booking-loco.kakao.com:443
|
||||
* 2. LOCO RSA handshake (encrypt AES session key)
|
||||
* 3. Send GETCONF command → receive checkin server list
|
||||
* 4. Disconnect
|
||||
*/
|
||||
|
||||
import { LocoSocket } from "./socket.js";
|
||||
import type { LocoClientConfig } from "../types/index.js";
|
||||
|
||||
export interface GetConfRequest {
|
||||
os: string;
|
||||
MCCMNC: string;
|
||||
model: string;
|
||||
}
|
||||
|
||||
export interface GetConfResponse {
|
||||
/** Checkin host list (v2sl) */
|
||||
checkinHosts: string[];
|
||||
/** Checkin host list (lsl - preferred) */
|
||||
checkinHostsLsl: string[];
|
||||
/** Available ports */
|
||||
ports: number[];
|
||||
/** Full raw response for debugging */
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const BOOKING_HOST = "booking-loco.kakao.com";
|
||||
const BOOKING_PORT = 443;
|
||||
|
||||
/**
|
||||
* Connect to the booking server via TLS + LOCO protocol,
|
||||
* send GETCONF, and return checkin server information.
|
||||
*/
|
||||
export async function fetchBookingServer(
|
||||
serverPublicKey: string,
|
||||
req: GetConfRequest,
|
||||
): Promise<GetConfResponse> {
|
||||
const config: LocoClientConfig = {
|
||||
host: BOOKING_HOST,
|
||||
port: BOOKING_PORT,
|
||||
useTLS: true,
|
||||
serverPublicKey,
|
||||
};
|
||||
|
||||
const socket = new LocoSocket(config, { plaintext: true });
|
||||
|
||||
try {
|
||||
await socket.connect();
|
||||
console.log("[Booking] Connected to booking-loco.kakao.com:443");
|
||||
|
||||
const resp = await socket.request("GETCONF", {
|
||||
MCCMNC: req.MCCMNC,
|
||||
os: req.os,
|
||||
model: req.model,
|
||||
});
|
||||
|
||||
console.log("[Booking] GETCONF response received");
|
||||
if (process.env["LOCO_DEBUG"]) {
|
||||
console.log(
|
||||
"[Booking] Full GETCONF body:",
|
||||
JSON.stringify(resp.body, null, 2),
|
||||
);
|
||||
}
|
||||
|
||||
const body = resp.body;
|
||||
|
||||
// Extract checkin hosts from ticket.lsl or ticket.v2sl
|
||||
const ticket = (body["ticket"] as Record<string, unknown>) ?? {};
|
||||
const lsl = (ticket["lsl"] as string[]) ?? [];
|
||||
const v2sl = (ticket["v2sl"] as string[]) ?? [];
|
||||
|
||||
// Extract ports from wifi config
|
||||
const wifi = (body["wifi"] as Record<string, unknown>) ?? {};
|
||||
const ports = (wifi["ports"] as number[]) ?? [9282];
|
||||
|
||||
return {
|
||||
checkinHosts: v2sl,
|
||||
checkinHostsLsl: lsl,
|
||||
ports,
|
||||
raw: body,
|
||||
};
|
||||
} finally {
|
||||
socket.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience function: booking → pick first checkin host + port.
|
||||
* Returns { host, port } ready for checkin connection.
|
||||
*/
|
||||
export async function resolveCheckinServer(
|
||||
serverPublicKey: string,
|
||||
req: GetConfRequest,
|
||||
fallbackHost = "121.53.93.55",
|
||||
fallbackPort = 9282,
|
||||
): Promise<{ host: string; port: number }> {
|
||||
try {
|
||||
const conf = await fetchBookingServer(serverPublicKey, req);
|
||||
const hosts =
|
||||
conf.checkinHostsLsl.length > 0
|
||||
? conf.checkinHostsLsl
|
||||
: conf.checkinHosts;
|
||||
|
||||
// Prefer an IP address over hostname for direct connection
|
||||
const host = hosts.find((h) => /^\d/.test(h)) ?? hosts[0] ?? fallbackHost;
|
||||
// Prefer port 9282 (standard LOCO raw TCP) if available
|
||||
const port = conf.ports.includes(9282)
|
||||
? 9282
|
||||
: (conf.ports[0] ?? fallbackPort);
|
||||
return { host, port };
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"[Booking] Failed:",
|
||||
(err as Error).message,
|
||||
"— using fallback",
|
||||
);
|
||||
return { host: fallbackHost, port: fallbackPort };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* LOCO Checkin — connects to the checkin server (e.g. ticket-loco.kakao.com:5242)
|
||||
* over TLS with plaintext LOCO (same as booking), sends CHECKIN, and returns
|
||||
* the LOCO session server host:port for the encrypted connection.
|
||||
*/
|
||||
|
||||
import { LocoSocket } from "./socket.js";
|
||||
import type { LocoClientConfig, LoginCredentials } from "../types/index.js";
|
||||
|
||||
export interface CheckinRequest {
|
||||
userId: number;
|
||||
os: string;
|
||||
ntype: number;
|
||||
appVer: string;
|
||||
lang: string;
|
||||
MCCMNC: string;
|
||||
}
|
||||
|
||||
export interface CheckinResponse {
|
||||
/** LOCO session server host */
|
||||
host: string;
|
||||
/** LOCO session server port */
|
||||
port: number;
|
||||
/** Full raw response for debugging */
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to the checkin server via TLS + plaintext LOCO,
|
||||
* send CHECKIN, and return the LOCO session server address.
|
||||
*/
|
||||
export async function fetchCheckinServer(
|
||||
checkinHost: string,
|
||||
checkinPort: number,
|
||||
serverPublicKey: string,
|
||||
req: CheckinRequest,
|
||||
): Promise<CheckinResponse> {
|
||||
const config: LocoClientConfig = {
|
||||
host: checkinHost,
|
||||
port: checkinPort,
|
||||
useTLS: true,
|
||||
serverPublicKey,
|
||||
};
|
||||
|
||||
const socket = new LocoSocket(config, { plaintext: true });
|
||||
|
||||
try {
|
||||
await socket.connect();
|
||||
console.log(`[Checkin] Connected to ${checkinHost}:${checkinPort}`);
|
||||
|
||||
const resp = await socket.request("CHECKIN", {
|
||||
userId: req.userId,
|
||||
os: req.os,
|
||||
ntype: req.ntype,
|
||||
appVer: req.appVer,
|
||||
lang: req.lang,
|
||||
MCCMNC: req.MCCMNC,
|
||||
});
|
||||
|
||||
console.log("[Checkin] CHECKIN response received");
|
||||
|
||||
const body = resp.body;
|
||||
const host = (body["host"] as string) ?? "";
|
||||
const port = (body["port"] as number) ?? 0;
|
||||
|
||||
return { host, port, raw: body };
|
||||
} finally {
|
||||
socket.disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export { LocoSocket } from "./socket.js";
|
||||
export {
|
||||
fetchBookingServer,
|
||||
resolveCheckinServer,
|
||||
type GetConfRequest,
|
||||
type GetConfResponse,
|
||||
} from "./booking.js";
|
||||
export {
|
||||
fetchCheckinServer,
|
||||
type CheckinRequest,
|
||||
type CheckinResponse,
|
||||
} from "./checkin.js";
|
||||
@@ -0,0 +1,182 @@
|
||||
import { connect as tlsConnect, type TLSSocket } from "node:tls";
|
||||
import { connect as netConnect, type Socket } from "node:net";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { generateAESKey } from "../crypto/index.js";
|
||||
import {
|
||||
buildHandshakePacket,
|
||||
buildEncryptedPacket,
|
||||
buildPlainPacket,
|
||||
buildLocoPacket,
|
||||
PacketReader,
|
||||
PlainPacketReader,
|
||||
} from "../protocol/index.js";
|
||||
import type {
|
||||
LocoClientConfig,
|
||||
LocoCommand,
|
||||
LocoPacketHeader,
|
||||
} from "../types/index.js";
|
||||
|
||||
export interface LocoSocketEvents {
|
||||
packet: [header: LocoPacketHeader, body: Record<string, unknown>];
|
||||
error: [error: Error];
|
||||
close: [];
|
||||
connected: [];
|
||||
}
|
||||
|
||||
export interface LocoSocketOptions {
|
||||
/**
|
||||
* When true, packets are sent/received as plain LOCO over TLS
|
||||
* (no RSA handshake, no AES encryption). Used for booking server.
|
||||
*/
|
||||
plaintext?: boolean;
|
||||
}
|
||||
|
||||
export class LocoSocket extends EventEmitter<LocoSocketEvents> {
|
||||
private socket: TLSSocket | Socket | null = null;
|
||||
private aesKey: Buffer;
|
||||
private encryptedReader: PacketReader;
|
||||
private plainReader: PlainPacketReader;
|
||||
private packetId = 1000;
|
||||
private config: LocoClientConfig;
|
||||
private plaintext: boolean;
|
||||
|
||||
/** Map of pending request id -> resolve callback */
|
||||
private pending = new Map<
|
||||
number,
|
||||
(result: {
|
||||
header: LocoPacketHeader;
|
||||
body: Record<string, unknown>;
|
||||
}) => void
|
||||
>();
|
||||
|
||||
constructor(config: LocoClientConfig, options?: LocoSocketOptions) {
|
||||
super();
|
||||
this.config = config;
|
||||
this.plaintext = options?.plaintext ?? false;
|
||||
this.aesKey = generateAESKey();
|
||||
this.encryptedReader = new PacketReader(this.aesKey);
|
||||
this.plainReader = new PlainPacketReader();
|
||||
}
|
||||
|
||||
/** Connect to the LOCO server. Performs RSA handshake unless in plaintext mode. */
|
||||
async connect(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onConnect = () => {
|
||||
if (this.plaintext) {
|
||||
// No handshake needed — TLS provides encryption
|
||||
this.emit("connected");
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
// Send handshake: RSA-encrypted AES key
|
||||
const handshake = buildHandshakePacket(
|
||||
this.aesKey,
|
||||
this.config.serverPublicKey,
|
||||
);
|
||||
if (process.env["LOCO_DEBUG"]) {
|
||||
console.log(
|
||||
`[Socket] handshake ${handshake.length} bytes: ${handshake.subarray(0, Math.min(64, handshake.length)).toString("hex")}`,
|
||||
);
|
||||
console.log(`[Socket] AES key: ${this.aesKey.toString("hex")}`);
|
||||
}
|
||||
this.socket!.write(handshake, (err) => {
|
||||
if (err) return reject(err);
|
||||
this.emit("connected");
|
||||
resolve();
|
||||
});
|
||||
};
|
||||
|
||||
if (this.config.useTLS) {
|
||||
this.socket = tlsConnect(
|
||||
{
|
||||
host: this.config.host,
|
||||
port: this.config.port,
|
||||
rejectUnauthorized: true,
|
||||
},
|
||||
onConnect,
|
||||
);
|
||||
} else {
|
||||
this.socket = netConnect(
|
||||
{ host: this.config.host, port: this.config.port },
|
||||
onConnect,
|
||||
);
|
||||
}
|
||||
|
||||
this.socket.on("data", (chunk: Buffer) => {
|
||||
if (process.env["LOCO_DEBUG"]) {
|
||||
console.log(
|
||||
`[Socket] recv ${chunk.length} bytes: ${chunk.subarray(0, Math.min(64, chunk.length)).toString("hex")}`,
|
||||
);
|
||||
}
|
||||
const reader = this.plaintext ? this.plainReader : this.encryptedReader;
|
||||
const packets = reader.feed(chunk);
|
||||
for (const pkt of packets) {
|
||||
// Resolve pending request if matched
|
||||
const resolver = this.pending.get(pkt.header.id);
|
||||
if (resolver) {
|
||||
this.pending.delete(pkt.header.id);
|
||||
resolver(pkt);
|
||||
}
|
||||
this.emit("packet", pkt.header, pkt.body);
|
||||
}
|
||||
});
|
||||
|
||||
this.socket.on("error", (err) => {
|
||||
this.emit("error", err);
|
||||
reject(err);
|
||||
});
|
||||
|
||||
this.socket.on("close", () => {
|
||||
this.emit("close");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Send a LOCO command and return a promise that resolves with the server's response. */
|
||||
async request(
|
||||
command: LocoCommand,
|
||||
body: Record<string, unknown>,
|
||||
): Promise<{ header: LocoPacketHeader; body: Record<string, unknown> }> {
|
||||
const id = ++this.packetId;
|
||||
const inner = buildLocoPacket(id, command, 0, body);
|
||||
const packet = this.plaintext
|
||||
? buildPlainPacket(inner)
|
||||
: buildEncryptedPacket(inner, this.aesKey);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
if (process.env["LOCO_DEBUG"]) {
|
||||
console.log(
|
||||
`[Socket] send ${command} id=${id} ${packet.length} bytes: ${packet.subarray(0, Math.min(64, packet.length)).toString("hex")}`,
|
||||
);
|
||||
}
|
||||
this.pending.set(id, resolve);
|
||||
this.socket!.write(packet, (err) => {
|
||||
if (err) {
|
||||
this.pending.delete(id);
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Send a LOCO command without waiting for a specific response. */
|
||||
send(command: LocoCommand, body: Record<string, unknown>): number {
|
||||
const id = ++this.packetId;
|
||||
const inner = buildLocoPacket(id, command, 0, body);
|
||||
const packet = this.plaintext
|
||||
? buildPlainPacket(inner)
|
||||
: buildEncryptedPacket(inner, this.aesKey);
|
||||
this.socket!.write(packet);
|
||||
return id;
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
this.socket?.destroy();
|
||||
this.socket = null;
|
||||
}
|
||||
|
||||
get sessionKey(): Buffer {
|
||||
return this.aesKey;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export {
|
||||
buildLocoPacket,
|
||||
parseLocoPacket,
|
||||
buildEncryptedPacket,
|
||||
parseEncryptedPacket,
|
||||
buildPlainPacket,
|
||||
buildHandshakePacket,
|
||||
isHandshakePacket,
|
||||
PacketReader,
|
||||
PlainPacketReader,
|
||||
} from "./packet.js";
|
||||
@@ -0,0 +1,222 @@
|
||||
import { BSON } from "bson";
|
||||
import {
|
||||
LOCO_HEADER_SIZE,
|
||||
ENCRYPTED_HEADER_SIZE,
|
||||
HANDSHAKE_LENGTH,
|
||||
type LocoPacketHeader,
|
||||
type LocoCommand,
|
||||
type LocoHandshakeData,
|
||||
} from "../types/index.js";
|
||||
import {
|
||||
aesEncryptGCM,
|
||||
aesDecryptGCM,
|
||||
generateNonce,
|
||||
NONCE_SIZE,
|
||||
rsaEncryptOAEP,
|
||||
} from "../crypto/index.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// LOCO inner packet (plaintext layer)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function buildLocoPacket(
|
||||
id: number,
|
||||
command: LocoCommand,
|
||||
statusCode: number,
|
||||
body: Record<string, unknown>,
|
||||
): Buffer {
|
||||
const bsonBody = Buffer.from(BSON.serialize(body));
|
||||
const buf = Buffer.alloc(LOCO_HEADER_SIZE + bsonBody.length);
|
||||
|
||||
buf.writeUInt32LE(id, 0);
|
||||
buf.writeUInt16LE(statusCode, 4);
|
||||
|
||||
// command: 11 bytes, null-padded
|
||||
const cmdBuf = Buffer.alloc(11, 0);
|
||||
cmdBuf.write(command, "utf-8");
|
||||
cmdBuf.copy(buf, 6);
|
||||
|
||||
buf.writeInt8(0, 17); // bodyType = 0 (BSON)
|
||||
buf.writeInt32LE(bsonBody.length, 18);
|
||||
bsonBody.copy(buf, LOCO_HEADER_SIZE);
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
export function parseLocoPacket(
|
||||
data: Buffer,
|
||||
): { header: LocoPacketHeader; body: Record<string, unknown> } | null {
|
||||
if (data.length < LOCO_HEADER_SIZE) return null;
|
||||
|
||||
const id = data.readUInt32LE(0);
|
||||
const statusCode = data.readUInt16LE(4);
|
||||
const command = data
|
||||
.subarray(6, 17)
|
||||
.toString("utf-8")
|
||||
.replace(/\0/g, "") as LocoCommand;
|
||||
const bodyType = data.readInt8(17);
|
||||
const bodyLength = data.readInt32LE(18);
|
||||
|
||||
const header: LocoPacketHeader = {
|
||||
id,
|
||||
statusCode,
|
||||
command,
|
||||
bodyType,
|
||||
bodyLength,
|
||||
};
|
||||
|
||||
let body: Record<string, unknown> = {};
|
||||
if (bodyLength > 0 && data.length >= LOCO_HEADER_SIZE + bodyLength) {
|
||||
try {
|
||||
body = BSON.deserialize(
|
||||
data.subarray(LOCO_HEADER_SIZE, LOCO_HEADER_SIZE + bodyLength),
|
||||
) as Record<string, unknown>;
|
||||
} catch {
|
||||
// body stays empty if BSON parsing fails
|
||||
}
|
||||
}
|
||||
|
||||
return { header, body };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Encrypted LOCO packet (network layer)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function buildEncryptedPacket(
|
||||
locoPacket: Buffer,
|
||||
aesKey: Buffer,
|
||||
): Buffer {
|
||||
const nonce = generateNonce();
|
||||
const encrypted = aesEncryptGCM(locoPacket, aesKey, nonce);
|
||||
|
||||
// [length:4][nonce:12][ciphertext+tag]
|
||||
const buf = Buffer.alloc(4 + NONCE_SIZE + encrypted.length);
|
||||
buf.writeUInt32LE(NONCE_SIZE + encrypted.length, 0);
|
||||
nonce.copy(buf, 4);
|
||||
encrypted.copy(buf, 4 + NONCE_SIZE);
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
export function parseEncryptedPacket(
|
||||
data: Buffer,
|
||||
aesKey: Buffer,
|
||||
): { decrypted: Buffer; consumed: number } | null {
|
||||
if (data.length < ENCRYPTED_HEADER_SIZE + 1) return null;
|
||||
|
||||
const length = data.readUInt32LE(0);
|
||||
const totalSize = 4 + length;
|
||||
|
||||
if (data.length < totalSize) return null; // fragmented
|
||||
|
||||
const nonce = data.subarray(4, 4 + NONCE_SIZE);
|
||||
const payload = data.subarray(4 + NONCE_SIZE, totalSize);
|
||||
const decrypted = aesDecryptGCM(payload, aesKey, nonce);
|
||||
|
||||
return { decrypted, consumed: totalSize };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Handshake packet
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function buildHandshakePacket(
|
||||
aesKey: Buffer,
|
||||
serverPublicKeyPem: string,
|
||||
): Buffer {
|
||||
const encryptedKey = rsaEncryptOAEP(aesKey, serverPublicKeyPem);
|
||||
|
||||
// [keyLen:4][encType:4][blockMode:4][encKey:keyLen]
|
||||
const buf = Buffer.alloc(4 + 4 + 4 + encryptedKey.length);
|
||||
buf.writeUInt32LE(encryptedKey.length, 0); // RSA ciphertext length (256)
|
||||
buf.writeUInt32LE(15, 4); // encryption type (RSA-OAEP-SHA1)
|
||||
buf.writeUInt32LE(4, 8); // block cipher mode (AES/GCM)
|
||||
encryptedKey.copy(buf, 12);
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
export function isHandshakePacket(data: Buffer): boolean {
|
||||
if (data.length < 4) return false;
|
||||
return data.readUInt32LE(0) === HANDSHAKE_LENGTH;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plain (unencrypted) packet framing — used over TLS (booking, checkin)
|
||||
// [length:4 LE][loco_packet:length]
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* In plaintext mode (over TLS), LOCO packets are sent raw — no length prefix.
|
||||
* The packet itself contains bodyLength at offset 18, so we can frame it.
|
||||
*/
|
||||
export function buildPlainPacket(locoPacket: Buffer): Buffer {
|
||||
return locoPacket; // no wrapping needed
|
||||
}
|
||||
|
||||
export class PlainPacketReader {
|
||||
private buffer: Buffer = Buffer.alloc(0);
|
||||
|
||||
/** Append incoming data and yield all complete parsed packets.
|
||||
* Framing: read LOCO header (22 bytes), then bodyLength bytes. */
|
||||
feed(
|
||||
chunk: Buffer,
|
||||
): Array<{ header: LocoPacketHeader; body: Record<string, unknown> }> {
|
||||
this.buffer = Buffer.concat([this.buffer, chunk]);
|
||||
const results: Array<{
|
||||
header: LocoPacketHeader;
|
||||
body: Record<string, unknown>;
|
||||
}> = [];
|
||||
|
||||
while (this.buffer.length >= LOCO_HEADER_SIZE) {
|
||||
const bodyLength = this.buffer.readInt32LE(18);
|
||||
const totalSize = LOCO_HEADER_SIZE + bodyLength;
|
||||
if (this.buffer.length < totalSize) break;
|
||||
|
||||
const payload = this.buffer.subarray(0, totalSize);
|
||||
const loco = parseLocoPacket(payload);
|
||||
if (loco) results.push(loco);
|
||||
|
||||
this.buffer = this.buffer.subarray(totalSize);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Encrypted stream reassembly helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export class PacketReader {
|
||||
private buffer: Buffer = Buffer.alloc(0);
|
||||
private aesKey: Buffer;
|
||||
|
||||
constructor(aesKey: Buffer) {
|
||||
this.aesKey = aesKey;
|
||||
}
|
||||
|
||||
/** Append incoming data and yield all complete parsed packets. */
|
||||
feed(
|
||||
chunk: Buffer,
|
||||
): Array<{ header: LocoPacketHeader; body: Record<string, unknown> }> {
|
||||
this.buffer = Buffer.concat([this.buffer, chunk]);
|
||||
const results: Array<{
|
||||
header: LocoPacketHeader;
|
||||
body: Record<string, unknown>;
|
||||
}> = [];
|
||||
|
||||
while (this.buffer.length >= ENCRYPTED_HEADER_SIZE + 1) {
|
||||
const parsed = parseEncryptedPacket(this.buffer, this.aesKey);
|
||||
if (!parsed) break; // incomplete packet, wait for more data
|
||||
|
||||
const loco = parseLocoPacket(parsed.decrypted);
|
||||
if (loco) results.push(loco);
|
||||
|
||||
this.buffer = this.buffer.subarray(parsed.consumed);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./loco.js";
|
||||
@@ -0,0 +1,85 @@
|
||||
/** Known LOCO commands */
|
||||
export type LocoCommand =
|
||||
| "GETTOKEN"
|
||||
| "CHECKIN"
|
||||
| "LOGINLIST"
|
||||
| "WRITE"
|
||||
| "MSG"
|
||||
| "SYNCMSG"
|
||||
| "GETCONF"
|
||||
| "GETPK"
|
||||
| "GETLPK"
|
||||
| "SETPK"
|
||||
| "SETSK"
|
||||
| "SETST"
|
||||
| "SCREATE"
|
||||
| "SWRITE"
|
||||
| "CHATONROOM"
|
||||
| "ACTION"
|
||||
| "GETMEM"
|
||||
| "BLSYNC"
|
||||
| (string & {});
|
||||
|
||||
export interface LocoPacketHeader {
|
||||
/** Packet identifier (auto-incrementing, starts at 1000 / 0x3E8) */
|
||||
id: number;
|
||||
/** Status code (0 = request from client, response status from server) */
|
||||
statusCode: number;
|
||||
/** LOCO command name, max 11 bytes null-padded */
|
||||
command: LocoCommand;
|
||||
/** Body type (0 = BSON) */
|
||||
bodyType: number;
|
||||
/** Body payload length in bytes */
|
||||
bodyLength: number;
|
||||
}
|
||||
|
||||
/** LOCO header is always 22 bytes */
|
||||
export const LOCO_HEADER_SIZE = 22;
|
||||
|
||||
/** Encrypted packet: [length:4][nonce:12][ciphertext+tag] */
|
||||
export const ENCRYPTED_HEADER_SIZE = 16; // 4 (length) + 12 (nonce)
|
||||
|
||||
/** Handshake packet length field value */
|
||||
export const HANDSHAKE_LENGTH = 256;
|
||||
|
||||
export interface LocoHandshakeData {
|
||||
/** Encryption type (15 = RSA-OAEP-SHA1) */
|
||||
type: number;
|
||||
/** Block cipher mode (4 = AES/GCM/NoPadding) */
|
||||
blockCipherMode: number;
|
||||
/** RSA-encrypted AES key */
|
||||
payload: Buffer;
|
||||
}
|
||||
|
||||
export interface LocoClientConfig {
|
||||
/** LOCO server host */
|
||||
host: string;
|
||||
/** LOCO server port */
|
||||
port: number;
|
||||
/** RSA public key of the server (PEM or base64) */
|
||||
serverPublicKey: string;
|
||||
/** Whether to use TLS for the initial TCP connection */
|
||||
useTLS: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_CONFIG: LocoClientConfig = {
|
||||
host: "211.249.240.122",
|
||||
port: 9282,
|
||||
useTLS: false,
|
||||
serverPublicKey: "",
|
||||
};
|
||||
|
||||
export interface LoginCredentials {
|
||||
/** OAuth token obtained from KakaoTalk auth */
|
||||
oauthToken: string;
|
||||
/** Device UUID */
|
||||
duuid: string;
|
||||
/** User ID */
|
||||
userId: number;
|
||||
/** App version string */
|
||||
appVer: string;
|
||||
/** Language code */
|
||||
lang: string;
|
||||
/** Mobile Country Code + Mobile Network Code */
|
||||
mccmnc: string;
|
||||
}
|
||||
Reference in new issue
Block a user