lixnet 1.0.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/.gitattributes ADDED
@@ -0,0 +1,2 @@
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
package/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # lixnet
2
+
3
+ To install dependencies:
4
+
5
+ ```bash
6
+ bun install
7
+ ```
8
+
9
+ To run:
10
+
11
+ ```bash
12
+ bun run index.ts
13
+ ```
14
+
15
+ This project was created using `bun init` in bun v1.2.18. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
@@ -0,0 +1,4 @@
1
+ import LixnetServer from "./lib/server";
2
+ import LixnetClient from "./lib/client";
3
+ import LixnetPeer from "./lib/peer";
4
+ export { LixnetServer, LixnetClient, LixnetPeer };
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.LixnetPeer = exports.LixnetClient = exports.LixnetServer = void 0;
7
+ const server_1 = __importDefault(require("./lib/server"));
8
+ exports.LixnetServer = server_1.default;
9
+ const client_1 = __importDefault(require("./lib/client"));
10
+ exports.LixnetClient = client_1.default;
11
+ const peer_1 = __importDefault(require("./lib/peer"));
12
+ exports.LixnetPeer = peer_1.default;
@@ -0,0 +1,14 @@
1
+ import type { EventCollection, CallableEvent } from "./types";
2
+ export default class LixnetClientConstructor<TEvents extends EventCollection> {
3
+ private baseUrl;
4
+ private events;
5
+ constructor({ events, baseUrl, }: {
6
+ events: TEvents;
7
+ baseUrl: string;
8
+ });
9
+ getClient(): {
10
+ [K in keyof TEvents]: TEvents[K] extends {
11
+ handler: (input: infer TInput) => Promise<infer TOutput>;
12
+ } ? CallableEvent<Omit<TInput, "request">, TOutput> : never;
13
+ };
14
+ }
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ class LixnetClientConstructor {
13
+ constructor({ events, baseUrl, }) {
14
+ this.baseUrl = baseUrl;
15
+ this.events = events;
16
+ }
17
+ getClient() {
18
+ const client = {};
19
+ Object.keys(this.events).forEach((key) => {
20
+ client[key] = (input) => __awaiter(this, void 0, void 0, function* () {
21
+ const response = yield fetch(this.baseUrl, {
22
+ method: "POST",
23
+ body: JSON.stringify({ event: key, input }),
24
+ });
25
+ try {
26
+ const json = (yield response.json());
27
+ if (json.error) {
28
+ throw new Error(json.error);
29
+ }
30
+ return json.data;
31
+ }
32
+ catch (error) {
33
+ console.error(error);
34
+ return null;
35
+ }
36
+ });
37
+ });
38
+ return client;
39
+ }
40
+ }
41
+ exports.default = LixnetClientConstructor;
@@ -0,0 +1,39 @@
1
+ export type PeerEventInput<T> = T extends (input: infer TInput) => any ? TInput : never;
2
+ type Caller<ThisToThereEvents extends Record<string, any>> = <K extends keyof ThisToThereEvents>(name: K, input: PeerEventInput<ThisToThereEvents[K]>, options?: {
3
+ callback: ((data: Awaited<ReturnType<ThisToThereEvents[K]>>) => any) | null;
4
+ }) => Promise<void>;
5
+ export default class LixnetPeer<ThisToThereEvents extends Record<string, any>, ThereToThisEvents extends Record<string, any>, SocketType extends WebSocket = WebSocket> {
6
+ socket: SocketType | null;
7
+ rb: {
8
+ [key: string]: {
9
+ method: keyof ThisToThereEvents;
10
+ callback: (data: Awaited<ReturnType<ThisToThereEvents[keyof ThisToThereEvents]>>) => any;
11
+ };
12
+ };
13
+ transmissionLimit: number;
14
+ transmissionChunksLimit: number;
15
+ setTransmissionChunksLimit(limit: number): void;
16
+ call: Caller<ThisToThereEvents>;
17
+ private getChunkLimits;
18
+ private eventHandlers;
19
+ setSocket(socket: SocketType): void;
20
+ setTransmissionLimit(limit: number): void;
21
+ on<K extends keyof ThereToThisEvents>(event: K, handler: (input: PeerEventInput<ThereToThisEvents[K]> & {
22
+ socket: SocketType;
23
+ }) => ReturnType<ThereToThisEvents[K]>): void;
24
+ transmissions: Record<string, {
25
+ chunks: Record<number, string>;
26
+ chunkTimes: Record<number, number>;
27
+ chunkCount: number;
28
+ event: keyof ThereToThisEvents;
29
+ rf: string | null;
30
+ }>;
31
+ outgoingTransmissions: Record<string, Record<number, string>>;
32
+ private transmissionSecurityCheck;
33
+ handle({ data, socket }: {
34
+ data: any;
35
+ socket: SocketType;
36
+ }): void;
37
+ private handleEvent;
38
+ }
39
+ export {};
@@ -0,0 +1,257 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ function createLixnetId() {
13
+ return "LX-" + Math.random().toString(36).substring(2, 15);
14
+ }
15
+ class LixnetPeer {
16
+ constructor() {
17
+ this.socket = null;
18
+ this.rb = {};
19
+ this.transmissionLimit = -1;
20
+ this.transmissionChunksLimit = 20;
21
+ this.call = (event_1, data_1, ...args_1) => __awaiter(this, [event_1, data_1, ...args_1], void 0, function* (event, data, { callback } = { callback: null }) {
22
+ if (!this.socket)
23
+ throw new Error("LIXNET - Socket not set");
24
+ let rf = null;
25
+ if (typeof callback === "function") {
26
+ rf = createLixnetId();
27
+ this.rb[rf] = {
28
+ method: event,
29
+ callback: callback,
30
+ };
31
+ }
32
+ let dataToSend = {
33
+ event,
34
+ data,
35
+ };
36
+ if (rf)
37
+ dataToSend.rf = rf;
38
+ dataToSend = JSON.stringify(dataToSend);
39
+ // No callback needed, just send
40
+ if (this.transmissionLimit !== -1 &&
41
+ dataToSend.length > this.transmissionLimit - 50) {
42
+ // Send in chunks
43
+ let dataString = JSON.stringify(data);
44
+ const tId = createLixnetId();
45
+ const limits = this.getChunkLimits({
46
+ tId,
47
+ dataLength: dataString.length,
48
+ });
49
+ // Send transmission id and rf
50
+ const sendData = {
51
+ tId,
52
+ event,
53
+ chunkCount: limits.length,
54
+ };
55
+ if (rf)
56
+ sendData.rf = rf;
57
+ this.socket.send(JSON.stringify(sendData));
58
+ const chunks = {};
59
+ for (let i = 0; i < limits.length; i++) {
60
+ chunks[i] = `${tId}.${i}.${dataString.slice(0, limits[i])}`;
61
+ dataString = dataString.slice(limits[i]);
62
+ }
63
+ this.outgoingTransmissions[tId] = chunks;
64
+ // Chunks sent. Complete.
65
+ return;
66
+ }
67
+ this.socket.send(dataToSend);
68
+ });
69
+ this.eventHandlers = {};
70
+ this.transmissions = {};
71
+ this.outgoingTransmissions = {};
72
+ }
73
+ setTransmissionChunksLimit(limit) {
74
+ this.transmissionChunksLimit = limit;
75
+ }
76
+ getChunkLimits({ tId, dataLength, }) {
77
+ const limits = [];
78
+ let chunkIndex = 0;
79
+ while (dataLength > 0) {
80
+ const overheadLength = `${tId}.${chunkIndex}.`.length;
81
+ const requiredSize = this.transmissionLimit - overheadLength - 50;
82
+ const chunkSize = Math.min(requiredSize, dataLength);
83
+ limits.push(chunkSize);
84
+ if (chunkSize < dataLength) {
85
+ chunkIndex++;
86
+ dataLength -= chunkSize;
87
+ }
88
+ else {
89
+ dataLength = 0;
90
+ }
91
+ }
92
+ return limits;
93
+ }
94
+ setSocket(socket) {
95
+ this.socket = socket;
96
+ }
97
+ setTransmissionLimit(limit) {
98
+ this.transmissionLimit = limit;
99
+ }
100
+ on(event, handler) {
101
+ this.eventHandlers[event] = handler;
102
+ }
103
+ transmissionSecurityCheck(tId) {
104
+ const transmission = this.transmissions[tId];
105
+ if (!transmission)
106
+ return;
107
+ const receivedChunks = Object.keys(transmission.chunks).length;
108
+ const expectedChunks = transmission.chunkCount;
109
+ // If transmission is complete, no security concern
110
+ if (receivedChunks >= expectedChunks) {
111
+ delete this.transmissions[tId];
112
+ return;
113
+ }
114
+ // Check if transmission is likely abandoned
115
+ const now = Date.now();
116
+ const chunkTimes = Object.values(transmission.chunkTimes);
117
+ const lastChunkTime = Math.max(...chunkTimes, 0);
118
+ const timeSinceLastChunk = now - lastChunkTime;
119
+ // If no chunks received or last chunk was more than 30 seconds ago, likely abandoned
120
+ if (receivedChunks === 0 || timeSinceLastChunk > 30000) {
121
+ delete this.transmissions[tId];
122
+ return;
123
+ }
124
+ // Check for suspicious patterns - if chunks are coming too slowly
125
+ if (chunkTimes.length > 1) {
126
+ const timeIntervals = [];
127
+ const sortedTimes = chunkTimes.sort((a, b) => a - b);
128
+ for (let i = 1; i < sortedTimes.length; i++) {
129
+ const current = sortedTimes[i];
130
+ const previous = sortedTimes[i - 1];
131
+ if (current !== undefined && previous !== undefined) {
132
+ timeIntervals.push(current - previous);
133
+ }
134
+ }
135
+ const avgInterval = timeIntervals.reduce((a, b) => a + b, 0) / timeIntervals.length;
136
+ const remainingChunks = expectedChunks - receivedChunks;
137
+ const estimatedTimeToComplete = avgInterval * remainingChunks;
138
+ // If estimated completion time is unreasonable (>5 minutes), likely abuse
139
+ if (estimatedTimeToComplete > 300000) {
140
+ delete this.transmissions[tId];
141
+ return;
142
+ }
143
+ }
144
+ // Schedule next check in 10 seconds
145
+ setTimeout(() => {
146
+ this.transmissionSecurityCheck(tId);
147
+ }, 10000);
148
+ }
149
+ handle({ data, socket }) {
150
+ if (data.startsWith("LX-")) {
151
+ // Transmission chunk
152
+ const splits = data.split(".");
153
+ const tId = splits[0];
154
+ const chunkIndex = parseInt(splits[1]);
155
+ const chunk = splits.slice(2).join(".");
156
+ if (!this.transmissions[tId]) {
157
+ // No transmission found
158
+ return;
159
+ }
160
+ this.transmissions[tId].chunks[chunkIndex] = chunk;
161
+ this.transmissions[tId].chunkTimes[chunkIndex] = Date.now();
162
+ if (this.transmissions[tId].chunkCount ==
163
+ Object.keys(this.transmissions[tId].chunks).length) {
164
+ // Transmission complete
165
+ const transmission = this.transmissions[tId];
166
+ if (!transmission)
167
+ return;
168
+ let assembledData = new Array(transmission.chunkCount)
169
+ .fill("")
170
+ .map((_, i) => transmission.chunks[i])
171
+ .join("");
172
+ try {
173
+ this.handleEvent({
174
+ eventName: this.transmissions[tId].event,
175
+ data: JSON.parse(assembledData),
176
+ rf: this.transmissions[tId].rf,
177
+ socket,
178
+ });
179
+ }
180
+ catch (e) {
181
+ console.error(e);
182
+ }
183
+ delete this.transmissions[tId];
184
+ }
185
+ return;
186
+ }
187
+ try {
188
+ data = JSON.parse(data);
189
+ }
190
+ catch (e) {
191
+ // Not a JSON string
192
+ return;
193
+ }
194
+ if (data.launch) {
195
+ const outgoingChunks = this.outgoingTransmissions[data.tId];
196
+ if (outgoingChunks) {
197
+ // Launch the outgoing transmission
198
+ const chunks = structuredClone(outgoingChunks);
199
+ delete this.outgoingTransmissions[data.tId];
200
+ Object.values(chunks).forEach((chunk) => {
201
+ socket.send(chunk);
202
+ });
203
+ }
204
+ return;
205
+ }
206
+ // Normal event, not a transmission chunk
207
+ if (data.tId) {
208
+ // Starting transmission, allow the client to start sending chunks
209
+ this.transmissions[data.tId] = {
210
+ chunks: {},
211
+ chunkTimes: {},
212
+ chunkCount: data.chunkCount,
213
+ event: data.event,
214
+ rf: data.rf,
215
+ };
216
+ setTimeout(() => {
217
+ this.transmissionSecurityCheck(data.tId);
218
+ }, 30000);
219
+ socket.send(JSON.stringify({
220
+ launch: true,
221
+ tId: data.tId,
222
+ }));
223
+ return;
224
+ }
225
+ if (data.rb) {
226
+ // Receied callback
227
+ const callback = this.rb[data.rb];
228
+ if (callback) {
229
+ callback.callback(data.data);
230
+ delete this.rb[data.rb];
231
+ }
232
+ return;
233
+ }
234
+ // Not transmission starter or chunk, handle event
235
+ this.handleEvent({
236
+ eventName: data.event,
237
+ data: data.data,
238
+ rf: data.rf,
239
+ socket,
240
+ });
241
+ }
242
+ handleEvent(_a) {
243
+ return __awaiter(this, arguments, void 0, function* ({ eventName, data, rf, socket, }) {
244
+ const eventHandler = this.eventHandlers[eventName];
245
+ if (!eventHandler)
246
+ return;
247
+ const result = yield eventHandler(Object.assign(Object.assign({}, (typeof data === "object" ? data : {})), { socket }));
248
+ if (rf) {
249
+ socket.send(JSON.stringify({
250
+ rb: rf,
251
+ data: result,
252
+ }));
253
+ }
254
+ });
255
+ }
256
+ }
257
+ exports.default = LixnetPeer;
@@ -0,0 +1,11 @@
1
+ import type { EventCollection, ToEventTypes, LixnetServerInit } from "./types";
2
+ export default class LixnetServer<TEvents extends EventCollection> {
3
+ private eventCollection;
4
+ private logger;
5
+ private debugLog;
6
+ private jsonResponseMaker;
7
+ constructor({ debugLog, logger, jsonResponseMaker, events, }: LixnetServerInit<TEvents>);
8
+ handleRequest(request: Request): Promise<Response>;
9
+ getEventTypes(): ToEventTypes<TEvents>;
10
+ getEventCollection(): TEvents;
11
+ }
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const zod_1 = require("zod");
16
+ const log_1 = __importDefault(require("./util/log"));
17
+ class LixnetServer {
18
+ constructor({ debugLog = false, logger, jsonResponseMaker = Response.json, events, }) {
19
+ this.logger = log_1.default;
20
+ this.debugLog = false;
21
+ this.debugLog = debugLog;
22
+ logger ? (this.logger = logger) : "";
23
+ this.jsonResponseMaker = jsonResponseMaker;
24
+ this.eventCollection = events;
25
+ }
26
+ handleRequest(request) {
27
+ return __awaiter(this, void 0, void 0, function* () {
28
+ let jsonData;
29
+ try {
30
+ jsonData = (yield request.json());
31
+ }
32
+ catch (error) {
33
+ this.debugLog
34
+ ? this.logger({
35
+ error: true,
36
+ message: "Invalid JSON",
37
+ })
38
+ : "";
39
+ return this.jsonResponseMaker({
40
+ error: "Invalid JSON",
41
+ }, { status: 400 });
42
+ }
43
+ if (!jsonData.action) {
44
+ return this.jsonResponseMaker({ error: "Action not found" }, { status: 400 });
45
+ }
46
+ if (!jsonData.input) {
47
+ return this.jsonResponseMaker({ error: "Input not found" }, { status: 400 });
48
+ }
49
+ const event = this.eventCollection[jsonData.event];
50
+ if (!event) {
51
+ return this.jsonResponseMaker({
52
+ error: "Action not found",
53
+ }, { status: 404 });
54
+ }
55
+ try {
56
+ const validatedInput = event.schema
57
+ ? event.schema.parse(jsonData.input)
58
+ : jsonData.input;
59
+ const result = yield event.handler(validatedInput);
60
+ return this.jsonResponseMaker({ data: result });
61
+ }
62
+ catch (error) {
63
+ if (error instanceof zod_1.z.ZodError) {
64
+ return this.jsonResponseMaker({
65
+ error: "Invalid input",
66
+ details: error.issues,
67
+ }, { status: 400 });
68
+ }
69
+ throw error;
70
+ }
71
+ });
72
+ }
73
+ // Returns dummy functions that match the type signatures
74
+ getEventTypes() {
75
+ const eventTypes = {};
76
+ Object.entries(this.eventCollection).forEach(([key, event]) => {
77
+ // Create a dummy function that matches the type signature
78
+ eventTypes[key] = {
79
+ input: (() => { }), // Dummy function for input type
80
+ output: (() => { }), // Dummy function for output type
81
+ };
82
+ });
83
+ return eventTypes;
84
+ }
85
+ // Keep this for internal use only
86
+ getEventCollection() {
87
+ return this.eventCollection;
88
+ }
89
+ }
90
+ exports.default = LixnetServer;
@@ -0,0 +1,34 @@
1
+ import { z } from "zod";
2
+ export type DebugLogger = ({ error, message, }: {
3
+ error?: boolean;
4
+ message: string;
5
+ }) => void;
6
+ export type Event<TInput = any, TOutput = any> = {
7
+ handler: (input: TInput & {
8
+ request: Request;
9
+ }) => Promise<TOutput>;
10
+ schema?: z.ZodSchema<TInput>;
11
+ };
12
+ export type EventType<TInput = any, TOutput = any> = {
13
+ input: TInput;
14
+ output: TOutput;
15
+ };
16
+ export type EventCollection = Record<string, Event>;
17
+ export type EventTypeCollection = Record<string, EventType>;
18
+ export type LixnetServerInit<TEvents extends EventCollection> = {
19
+ debugLog?: boolean;
20
+ logger?: DebugLogger;
21
+ jsonResponseMaker?: (data: any, init?: ResponseInit) => Response;
22
+ events: TEvents;
23
+ };
24
+ export type LixnetClientInit<TEventTypes extends EventTypeCollection> = {
25
+ eventTypes: TEventTypes;
26
+ baseUrl: string;
27
+ };
28
+ export type CallableEvent<TInput = any, TOutput = any> = (input: TInput) => Promise<TOutput>;
29
+ export type ToEventTypes<TEvents extends EventCollection> = {
30
+ [K in keyof TEvents]: TEvents[K] extends Event<infer TInput, infer TOutput> ? EventType<TInput, TOutput> : never;
31
+ };
32
+ export type ClientEvents<TEventTypes extends EventTypeCollection> = {
33
+ [K in keyof TEventTypes]: TEventTypes[K] extends EventType<infer TInput, infer TOutput> ? CallableEvent<TInput, TOutput> : never;
34
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ export default function ({ error, message, }: {
2
+ error?: boolean;
3
+ message: string;
4
+ }): void;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = default_1;
4
+ function default_1({ error = false, message, }) {
5
+ if (error) {
6
+ return console.error(`[LIXNET]`, message);
7
+ }
8
+ return console.log(`[LIXNET]`, message);
9
+ }
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "lixnet",
3
+ "version": "1.0.0",
4
+ "author": "Nitlix",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/Nitlix/Lixnet"
9
+ },
10
+ "homepage": "https://github.com/Nitlix/lixnet",
11
+ "description": "RPC over HTTP and WebSockets, simplified.",
12
+ "module": "src/exports.ts",
13
+ "type": "module",
14
+ "devDependencies": {
15
+ "@types/bun": "latest"
16
+ },
17
+ "peerDependencies": {
18
+ "typescript": "^5"
19
+ },
20
+ "dependencies": {
21
+ "zod": "^4.0.8"
22
+ }
23
+ }