Skip to content

An open-source, self-hosted system for apps built with web technologies.

Select the first available production port

zohayrslileh83b3c23586b0
diff --git a/bun.lock b/bun.lock
index 5ae295d..b00955e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -13,7 +13,6 @@
"@the-link/react": "^0.2.0",
"@the-link/server": "^0.2.0",
"cfonts": "^3.3.1",
- "get-port": "^7.2.0",
"gsap": "^3.15.0",
"hono": "^4.13.2",
"keyv": "^5.6.0",
@@ -374,8 +373,6 @@
"gensync": ["[email protected]", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
- "get-port": ["[email protected]", "", {}, "sha512-afP4W205ONCuMoPBqcR6PSXnzX35KTcJygfJfcp+QY+uwm3p20p1YczWXhlICIzGMCxYBQcySEcOgsJcrkyobg=="],
-
"graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
"gsap": ["[email protected]", "", {}, "sha512-dMW4CWBTUK1AEEDeZc1g4xpPGIrSf9fJF960qbTZmN/QwZIWY5wgliS6JWl9/25fpTGJrMRtSjGtOmPnfjZB+A=="],
diff --git a/package.json b/package.json
index 12e52ad..c73fc51 100644
--- a/package.json
+++ b/package.json
@@ -43,7 +43,6 @@
"@the-link/react": "^0.2.0",
"@the-link/server": "^0.2.0",
"cfonts": "^3.3.1",
- "get-port": "^7.2.0",
"gsap": "^3.15.0",
"hono": "^4.13.2",
"keyv": "^5.6.0",
diff --git a/scripts/contracts/ports.ts b/scripts/contracts/ports.ts
new file mode 100644
index 0000000..bf70e07
--- /dev/null
+++ b/scripts/contracts/ports.ts
@@ -0,0 +1,56 @@
+import { strict as assert } from "node:assert"
+import { createServer } from "node:http"
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { environmentPorts, listenOnPorts, parsePorts, portRange, requestedPorts } from "@server/view/view"
+
+assert.equal(environmentPorts("phreshos", {}), undefined)
+assert.deepEqual(environmentPorts("phreshos", { PHRESHOS_PORT: "4305" }), [4305])
+assert.deepEqual(
+ environmentPorts("phreshos", { PHRESHOS_PORT: "4196,4234,5000-5002,4234" }),
+ [4196, 4234, 5000, 5001, 5002]
+)
+assert.deepEqual(portRange(4300, 4399), Array.from({ length: 100 }, (_, index) => 4300 + index))
+
+for (const value of ["", "0", "65536", "43.12", "port", "4300-", "4301-4300", "4300,,4301"]) {
+
+ assert.throws(() => parsePorts(value, "PHRESHOS_PORT"), /PHRESHOS_PORT must contain ports or inclusive ranges/)
+}
+
+const occupied = createServer()
+const available = createServer()
+
+const occupiedPort = await listenOnPorts(occupied, "127.0.0.1")
+const availablePort = await listenOnPorts(available, "127.0.0.1")
+
+await close(available)
+
+const selected = createServer()
+
+assert.equal(await listenOnPorts(selected, "127.0.0.1", [occupiedPort, availablePort]), availablePort)
+
+await assert.rejects(
+ listenOnPorts(createServer(), "127.0.0.1", [occupiedPort, availablePort]),
+ /No configured System port is available/
+)
+
+await Promise.all([close(occupied), close(selected)])
+
+const temporary = await mkdtemp(join(tmpdir(), "phreshos-port-request-"))
+const request = join(temporary, "next-port")
+
+try {
+
+ await writeFile(request, "4400,4500-4502\n")
+
+ assert.deepEqual(await requestedPorts(["node", "main.js", "--port-request", request]), [4400, 4500, 4501, 4502])
+ await assert.rejects(readFile(request), error => (error as NodeJS.ErrnoException).code === "ENOENT")
+}
+
+finally { await rm(temporary, { recursive: true, force: true }) }
+
+function close(server: ReturnType<typeof createServer>) {
+
+ return new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()))
+}
diff --git a/scripts/dev.ts b/scripts/dev.ts
index 1f8f39b..1c5ab17 100644
--- a/scripts/dev.ts
+++ b/scripts/dev.ts
@@ -1,6 +1,6 @@
import { displayName, name, version } from "@/package.json"
import doors from "@server/view/doors"
-import view, { environmentHome, environmentPort } from "@server/view/view"
+import view, { environmentHome } from "@server/view/view"
import { createServer } from "vite"
import { fileURLToPath } from "node:url"
@@ -8,8 +8,6 @@ const home = environmentHome(name, process.env) ?? fileURLToPath(new URL("../sto
const host = await view({ name, displayName, version, mode: "development", hostname: "localhost", home })
-const port = environmentPort(name, process.env)
-
const client = await createServer({
configFile: "vite.client.ts",
@@ -18,10 +16,6 @@ const client = await createServer({
allowedHosts: true,
- port,
-
- strictPort: port !== undefined,
-
proxy: Object.fromEntries(Object.values(doors).map(door => [door, {
changeOrigin: true,
diff --git a/source/server/main.ts b/source/server/main.ts
index 42aa986..952196d 100644
--- a/source/server/main.ts
+++ b/source/server/main.ts
@@ -1,8 +1,9 @@
import { displayName, name, version } from "@/package.json"
-import view, { defaultHome, environmentHome, environmentPort, requestedHome } from "./view/view"
+import view, { defaultHome, environmentHome, environmentPorts, portRange, requestedHome, requestedPorts } from "./view/view"
import { fileURLToPath } from "node:url"
const requested = await requestedHome(process.argv)
+const requestedPortSelection = await requestedPorts(process.argv)
const home = environmentHome(name, process.env)
?? requested
?? defaultHome(process.argv)
@@ -20,7 +21,7 @@ await view({
home,
- port: environmentPort(name, process.env) ?? 4300,
+ ports: environmentPorts(name, process.env) ?? requestedPortSelection ?? portRange(4300, 4399),
assets: fileURLToPath(new URL("../client", import.meta.url))
})
diff --git a/source/server/view/view.ts b/source/server/view/view.ts
index 09c4e4d..596c07b 100644
--- a/source/server/view/view.ts
+++ b/source/server/view/view.ts
@@ -1,6 +1,6 @@
import Application from "@server/core/application"
import { serveStatic } from "@hono/node-server/serve-static"
-import { serve } from "@hono/node-server"
+import { createAdaptorServer, type ServerType } from "@hono/node-server"
import { WebSocketServer } from "ws"
import doors from "./doors"
import gateway from "./gateway/gateway"
@@ -10,11 +10,10 @@ import proxy from "./proxy"
import storage from "./storage"
import uploads from "./uploads"
import link from "./link"
-import getPort from "get-port"
import cfonts from "cfonts"
import { Hono } from "hono"
import { isAbsolute, normalize, resolve } from "node:path"
-import { readFile, rm } from "node:fs/promises"
+import { readFile, rm, writeFile } from "node:fs/promises"
import { styleText } from "node:util"
import environment from "@libs/environment"
@@ -49,32 +48,26 @@ export default async function (config: Config) {
if (config.assets) server.use("*", serveStatic({ root: config.assets }))
- const port = config.port ?? await getPort()
-
const hostname = config.hostname ?? "localhost"
- await new Promise(function (resolve) {
-
- serve({
+ const listener = createAdaptorServer({
- port,
+ fetch: server.fetch,
- hostname,
+ websocket: {
- fetch: server.fetch,
+ server: new WebSocketServer({ noServer: true })
+ }
+ })
- websocket: {
+ const port = await listenOnPorts(listener, hostname, config.ports)
- server: new WebSocketServer({ noServer: true })
- }
+ const origin = `http://localhost:${port}`
- }, resolve)
- })
+ await writeFile(resolve(application.storage.path, "desktop"), `${origin}\n`, { mode: 0o600 })
const localGateway = await gateway(application, gatewayAddress(application.storage.path))
- const origin = `http://localhost:${port}`
-
if (config.assets) console.log(` ➜ ${styleText("bold", "Desktop:")} ${origin}`)
console.log(` ➜ ${styleText("bold", "Gateway:")} ${localGateway.path}`)
@@ -99,7 +92,136 @@ export interface Config {
hostname?: string
- port?: number
+ /** Ordered public port candidates. Omit to let the operating system assign one. */
+ ports?: readonly number[]
+}
+
+/** Expand one inclusive TCP port range. */
+export function portRange(from: number, to: number) {
+
+ return Array.from({ length: to - from + 1 }, (_, index) => from + index)
+}
+
+/** Read the optional ordered production port selection. */
+export function environmentPorts(name: string, variables: NodeJS.ProcessEnv) {
+
+ const selected = environment(name, "PORT", variables)
+
+ if (selected.value === undefined) return undefined
+
+ return parsePorts(selected.value, selected.key)
+}
+
+/** Parse comma-separated TCP ports and inclusive ranges in declared order. */
+export function parsePorts(value: string, name = "Port selection") {
+
+ const ports: number[] = []
+
+ const included = new Set<number>()
+
+ for (const part of value.split(",")) {
+
+ const match = /^(\d+)(?:-(\d+))?$/.exec(part)
+
+ if (!match) throw portSelectionError(name)
+
+ const from = Number(match[1])
+
+ const to = Number(match[2] ?? match[1])
+
+ if (!validPort(from) || !validPort(to) || from > to) throw portSelectionError(name)
+
+ for (let port = from; port <= to; port++) {
+
+ if (included.has(port)) continue
+
+ included.add(port)
+
+ ports.push(port)
+ }
+ }
+
+ return Object.freeze(ports)
+}
+
+/** Consume the optional one-time port selection supplied through the native service boundary. */
+export async function requestedPorts(arguments_: string[]) {
+
+ const positions = arguments_.flatMap((value, index) => value === "--port-request" ? [index] : [])
+
+ if (positions.length === 0) return undefined
+
+ if (positions.length !== 1) throw new Error("--port-request can be supplied only once")
+
+ const path = arguments_[positions[0]! + 1]
+
+ if (!path || !isAbsolute(path)) throw new Error("--port-request must be followed by an absolute filesystem path")
+
+ let value: string
+
+ try { value = (await readFile(path, "utf8")).trim() }
+
+ catch (error) {
+
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined
+
+ throw error
+ }
+
+ await rm(path, { force: true })
+
+ return parsePorts(value, "The requested PhreshOS port selection")
+}
+
+/** Bind one server to the first available candidate or an assigned port. */
+export async function listenOnPorts(server: ServerType, hostname: string, ports?: readonly number[]) {
+
+ for (const port of ports ?? [0]) {
+
+ const address = await tryListen(server, hostname, port)
+
+ if (address !== null) return address
+ }
+
+ throw new Error("No configured System port is available")
+}
+
+function tryListen(server: ServerType, hostname: string, port: number) {
+
+ return new Promise<number | null>((resolve, reject) => {
+
+ const failed = (error: NodeJS.ErrnoException) => {
+
+ server.off("error", failed)
+
+ if (error.code === "EADDRINUSE" || error.code === "EACCES") resolve(null)
+
+ else reject(error)
+ }
+
+ server.once("error", failed)
+
+ server.listen(port, hostname, () => {
+
+ server.off("error", failed)
+
+ const address = server.address()
+
+ if (!address || typeof address === "string") reject(new Error("The System listener has no TCP address"))
+
+ else resolve(address.port)
+ })
+ })
+}
+
+function validPort(value: number) {
+
+ return Number.isInteger(value) && value >= 1 && value <= 65_535
+}
+
+function portSelectionError(name: string) {
+
+ return new Error(`${name} must contain ports or inclusive ranges from 1 to 65535`)
}
/** Read the stable fallback home supplied by the native service definition. */
@@ -146,23 +268,6 @@ export async function requestedHome(arguments_: string[]) {
}
/** Read the optional public port override named from the application identity. */
-export function environmentPort(name: string, variables: NodeJS.ProcessEnv) {
-
- const selected = environment(name, "PORT", variables)
-
- const value = selected.value
-
- if (value === undefined) return undefined
-
- if (!/^[0-9]+$/.test(value)) throw new Error(`${selected.key} must be an integer from 1 to 65535`)
-
- const port = Number(value)
-
- if (port < 1 || port > 65_535) throw new Error(`${selected.key} must be an integer from 1 to 65535`)
-
- return port
-}
-
/** Read the optional absolute authoritative home selected by Main's environment. */
export function environmentHome(name: string, variables: NodeJS.ProcessEnv) {