feat: Add first poc

This commit is contained in:
Myzel394 2024-11-05 21:57:37 +01:00
parent b79a7293af
commit 1390ef247c
No known key found for this signature in database
GPG Key ID: ED20A1D1D423AF3F
5 changed files with 93 additions and 4 deletions

BIN
bun.lockb

Binary file not shown.

View File

@ -4,9 +4,12 @@
"dev": "bun run --hot src/index.ts" "dev": "bun run --hot src/index.ts"
}, },
"dependencies": { "dependencies": {
"hono": "^4.6.9" "hono": "^4.6.9",
"id": "^0.0.0",
"zod": "^3.23.8"
}, },
"devDependencies": { "devDependencies": {
"@types/bun": "latest" "@types/bun": "latest",
"@types/ip": "^1.1.3"
} }
} }

View File

@ -1,9 +1,19 @@
import { Hono } from 'hono' import { Hono } from 'hono'
import {getConnInfo} from "hono/bun"
import connectToAddress from './utils/connect-to-address'
const app = new Hono() const app = new Hono()
app.get('/', (c) => { app.get('/:port', async context => {
return c.text('Hello Hono!') const port = Number(context.req.param("port"))
const info = getConnInfo(context)
const ipAddress = info.remote.address!
const result = await connectToAddress(ipAddress, port)
return context.json({
isOpen: result.isOpen
})
}) })
export default app export default app

33
src/routes/port.ts Normal file
View File

@ -0,0 +1,33 @@
import { Hono } from "hono";
import { getConnInfo } from "hono/bun";
import connectToAddress from "../utils/connect-to-address";
import { z } from "zod";
import * as IP from "ip"
export const portRoute = new Hono();
const schema = z.object({
ip: z.string().refine(ip => !IP.isPublic(ip), "This IP address is not valid"),
port: z.coerce.number().min(1).max(2**16 - 1),
});
portRoute.get("/:port", async context => {
const info = getConnInfo(context)
const rawData = {
ip: info.remote.address || "",
port: context.req.param("port"),
};
const parsedData = schema.safeParse(rawData);
if (!parsedData.success) {
return context.json({ error: parsedData.error }, 401);
}
const { ip, port } = parsedData.data;
const result = await connectToAddress(ip, port)
return context.json({
isOpen: result.isOpen
})
});

View File

@ -0,0 +1,43 @@
export interface ConnectionResult {
isOpen: boolean
}
const TIMEOUT = 5
export default function connectToAddress(address: string, port: number): Promise<ConnectionResult> {
return new Promise<ConnectionResult>(async (resolve) => {
const socket = await Bun.connect({
hostname: address,
port: port,
socket: {
open(socket) {
socket.end()
resolve({
isOpen: true
})
},
data() {
},
connectError() {
resolve({
isOpen: false
})
},
error(socket) {
socket.end()
resolve({
isOpen: false
})
},
timeout() {
resolve({
isOpen: false
})
},
}
})
socket.timeout(TIMEOUT)
})
}