Files
pipelines/web/src/peerTransport.js
T

129 lines
3.8 KiB
JavaScript

import http from "node:http";
import https from "node:https";
export function endpoint(value) {
const url = new URL(value);
if (
!["ws:", "wss:"].includes(url.protocol) ||
!url.hostname ||
url.username ||
url.password ||
url.hash ||
url.search ||
url.pathname !== "/connect"
)
throw new Error("Use a ws(s) server address ending in /connect");
return url;
}
export function webOrigin(url) {
const result = new URL(url);
result.protocol = result.protocol === "wss:" ? "https:" : "http:";
result.pathname = "/";
return result;
}
export function remoteRequest(url, options = {}) {
return (url.protocol === "https:" ? https : http).request(url, options);
}
// Never follows redirects or sends local browser cookies to another machine.
export function boundedRequest(
url,
{ method = "GET", cookie = "", body = "", headers = {} } = {},
) {
return new Promise((resolve, reject) => {
const request = remoteRequest(url, {
method,
headers: { ...headers, ...(cookie ? { Cookie: cookie } : {}) },
});
const timer = setTimeout(
() => request.destroy(new Error("Server timed out")),
8000,
);
request.once("error", (error) => {
clearTimeout(timer);
reject(error);
});
request.once("response", (response) => {
const chunks = [];
let bytes = 0;
response.on("data", (chunk) => {
bytes += chunk.length;
if (bytes > 65536) {
response.destroy();
request.destroy(new Error("Server response was too large"));
return;
}
chunks.push(chunk);
});
response.once("error", (error) => {
clearTimeout(timer);
reject(error);
});
response.once("end", () => {
clearTimeout(timer);
resolve({
status: response.statusCode,
headers: response.headers,
body: Buffer.concat(chunks).toString("utf8"),
});
});
});
request.end(body);
});
}
export function sessionCookie(response) {
return (response.headers["set-cookie"] ?? [])
.map((value) => value.split(";")[0])
.filter((value) => value.startsWith("pipelines_session="))
.join("; ");
}
export async function authenticate(url, cookie, password) {
const login = new URL("/login", webOrigin(url));
let response;
if (password !== undefined) {
const body = new URLSearchParams({ password, remember: "on" }).toString();
response = await boundedRequest(login, {
method: "POST",
body,
cookie,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(body),
},
});
if ([302, 303].includes(response.status)) {
cookie = sessionCookie(response) || cookie;
} else if (response.status === 401 || response.status === 429) {
return { connected: false, needs_password: true, cookie: "" };
}
}
response = await boundedRequest(login, { cookie });
if ([302, 303].includes(response.status))
return { connected: true, needs_password: false, cookie };
if (
response.status === 401 ||
(response.status === 200 && /name=["']password["']/.test(response.body))
) {
return { connected: false, needs_password: true, cookie: "" };
}
if (response.status === 200)
return { connected: true, needs_password: false, cookie };
if (response.status === 404) {
const health = await boundedRequest(new URL("/healthz", webOrigin(url)));
if (health.status === 200 && JSON.parse(health.body)?.healthy === true)
return { connected: true, needs_password: false, cookie: "" };
}
throw new Error("Server could not be reached");
}
export function json(res, status, value) {
res
.writeHead(status, {
"Content-Type": "application/json",
"Cache-Control": "no-store",
})
.end(JSON.stringify(value));
}