Send the server token from the web proxy and limit peer relay addresses
The proxy adds the shared token to every upstream request and drops any client copy. The peer relay accepts only tailnet, LAN, ts.net and discovered hosts, resolves each name once and pins the checked address, and flags ws:// endpoints with insecure_transport.
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
// Which machines the peer relay may reach (docs/notes/security-boundary.md).
|
||||
//
|
||||
// A signed-in browser names other Pipelines machines by URL and this proxy
|
||||
// fetches /login, /files, /artifacts, /updates and /connect from them, so an
|
||||
// unrestricted address would let any signed-in user make this machine request
|
||||
// its own loopback services, link-local cloud metadata or arbitrary hosts.
|
||||
// Allowed by default: tailnet addresses (100.64.0.0/10 and fd7a:115c:a1e0::/48,
|
||||
// minus Tailscale's own 100.100.100.100 service), private LANs (RFC 1918 and
|
||||
// IPv6 unique-local fc00::/7), and public addresses only for *.ts.net names
|
||||
// (Tailscale Funnel) or hosts this machine's own discovery reported. Loopback,
|
||||
// unspecified, link-local, metadata, multicast and reserved addresses are always
|
||||
// refused. PIPELINES_PEER_ALLOW=loopback,public,link-local,metadata (or "any")
|
||||
// widens the policy explicitly.
|
||||
//
|
||||
// A name is resolved once per request and the connection is pinned to the
|
||||
// checked address (the request's `lookup`), so a DNS answer cannot change
|
||||
// between the check and the connect (rebinding).
|
||||
import { lookup as dnsLookup } from "node:dns/promises";
|
||||
import net from "node:net";
|
||||
|
||||
const ALWAYS_REFUSED = new Set(["unspecified", "multicast", "reserved"]);
|
||||
const OPTIONAL = new Set(["loopback", "public", "link-local", "metadata"]);
|
||||
|
||||
// Hosts the local server's LAN discovery returned (proxyDiscovery), bounded.
|
||||
export const discoveredHosts = new Set();
|
||||
export function rememberDiscovered(body) {
|
||||
try {
|
||||
for (const server of JSON.parse(body)?.discovered_servers ?? []) {
|
||||
const host = new URL(server.endpoint).hostname.toLowerCase();
|
||||
if (discoveredHosts.size >= 256) discoveredHosts.delete(discoveredHosts.values().next().value);
|
||||
discoveredHosts.add(host);
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function v4(address) {
|
||||
const parts = address.split(".").map(Number);
|
||||
return ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
|
||||
}
|
||||
const inV4 = (value, base, bits) => bits === 0 || value >>> (32 - bits) === v4(base) >>> (32 - bits);
|
||||
|
||||
function classifyV4(address) {
|
||||
const value = v4(address);
|
||||
if (inV4(value, "0.0.0.0", 8)) return "unspecified";
|
||||
if (inV4(value, "127.0.0.0", 8)) return "loopback";
|
||||
if (value === v4("169.254.169.254") || value === v4("100.100.100.100")) return "metadata";
|
||||
if (inV4(value, "169.254.0.0", 16)) return "link-local";
|
||||
if (inV4(value, "100.64.0.0", 10)) return "tailnet";
|
||||
if (inV4(value, "10.0.0.0", 8) || inV4(value, "172.16.0.0", 12) || inV4(value, "192.168.0.0", 16)) return "private";
|
||||
if (inV4(value, "224.0.0.0", 4)) return "multicast";
|
||||
if (inV4(value, "240.0.0.0", 4)) return "reserved";
|
||||
return "public";
|
||||
}
|
||||
|
||||
// The 8 hextets of an IPv6 literal (already validated by net.isIPv6).
|
||||
function hextets(address) {
|
||||
let text = address.toLowerCase().split("%")[0];
|
||||
const dotted = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
|
||||
if (dotted) {
|
||||
const value = v4(dotted[1]);
|
||||
text = text.slice(0, -dotted[1].length) + `${(value >>> 16).toString(16)}:${(value & 0xffff).toString(16)}`;
|
||||
}
|
||||
const [head, tail] = text.split("::");
|
||||
const left = head ? head.split(":") : [];
|
||||
const right = tail === undefined ? [] : tail ? tail.split(":") : [];
|
||||
const fill = tail === undefined ? [] : Array(8 - left.length - right.length).fill("0");
|
||||
return [...left, ...fill, ...right].map((part) => parseInt(part, 16));
|
||||
}
|
||||
|
||||
function classifyV6(address) {
|
||||
const h = hextets(address);
|
||||
if (h.every((part) => part === 0)) return "unspecified";
|
||||
if (h.slice(0, 7).every((part) => part === 0) && h[7] === 1) return "loopback";
|
||||
if (h.slice(0, 5).every((part) => part === 0) && h[5] === 0xffff)
|
||||
return classifyV4(`${h[6] >> 8}.${h[6] & 255}.${h[7] >> 8}.${h[7] & 255}`);
|
||||
if ((h[0] & 0xffc0) === 0xfe80) return "link-local";
|
||||
if ((h[0] & 0xff00) === 0xff00) return "multicast";
|
||||
if (h[0] === 0xfd7a && h[1] === 0x115c && h[2] === 0xa1e0)
|
||||
return h.slice(3, 7).every((part) => part === 0) && h[7] === 0x53 ? "metadata" : "tailnet";
|
||||
// AWS's IPv6 instance metadata endpoint sits inside the unique-local range.
|
||||
if (h[0] === 0xfd00 && h[1] === 0x0ec2) return "metadata";
|
||||
if ((h[0] & 0xfe00) === 0xfc00) return "private";
|
||||
return "public";
|
||||
}
|
||||
|
||||
export function classify(address) {
|
||||
if (net.isIPv4(address)) return classifyV4(address);
|
||||
if (net.isIPv6(address)) return classifyV6(address);
|
||||
return "reserved";
|
||||
}
|
||||
|
||||
export function allowedCategories(env = process.env) {
|
||||
const extra = String(env.PIPELINES_PEER_ALLOW ?? "")
|
||||
.split(",")
|
||||
.map((value) => value.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
const any = extra.includes("any");
|
||||
return new Set(["tailnet", "private", ...(any ? OPTIONAL : extra.filter((value) => OPTIONAL.has(value)))]);
|
||||
}
|
||||
|
||||
export class PeerAddressError extends Error {}
|
||||
|
||||
export class PeerAddressPolicy {
|
||||
constructor({ env = process.env, lookup = dnsLookup, discovered = discoveredHosts } = {}) {
|
||||
this.allowed = allowedCategories(env);
|
||||
this.lookup = lookup;
|
||||
this.discovered = discovered;
|
||||
}
|
||||
permits(hostname, category) {
|
||||
if (ALWAYS_REFUSED.has(category)) return false;
|
||||
if (this.allowed.has(category)) return true;
|
||||
if (category !== "public") return false;
|
||||
return hostname.endsWith(".ts.net") || this.discovered.has(hostname);
|
||||
}
|
||||
// Resolve once, check every answer, and return a `lookup` that pins the
|
||||
// request's connection to the first checked address.
|
||||
async pin(url) {
|
||||
const hostname = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
||||
const answers = net.isIP(hostname)
|
||||
? [{ address: hostname, family: net.isIP(hostname) }]
|
||||
: await this.lookup(hostname, { all: true, verbatim: true });
|
||||
if (!answers.length) throw new PeerAddressError("Server address did not resolve");
|
||||
for (const { address } of answers) {
|
||||
const category = classify(address);
|
||||
if (!this.permits(hostname, category))
|
||||
throw new PeerAddressError(`Server address is not allowed (${category})`);
|
||||
}
|
||||
const { address, family } = answers[0];
|
||||
return {
|
||||
address,
|
||||
family,
|
||||
lookup: (_name, options, callback) => {
|
||||
const done = typeof options === "function" ? options : callback;
|
||||
if (options?.all) done(null, [{ address, family }]);
|
||||
else done(null, address, family);
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
+32
-1
@@ -1,6 +1,12 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { authenticate, endpoint, json } from "./peerTransport.js";
|
||||
import { sameOriginUpgrade } from "./proxySecurity.js";
|
||||
import { PeerAddressError, PeerAddressPolicy } from "./peerAddress.js";
|
||||
|
||||
// A password or session cookie sent to a ws:// endpoint crosses the network
|
||||
// unencrypted (unless the path is a tailnet's WireGuard tunnel); the response
|
||||
// says so, so the app can warn before the operator types a password.
|
||||
const plaintext = (urls) => urls.some((url) => url.startsWith("ws:"));
|
||||
|
||||
async function body(req) {
|
||||
const chunks = [];
|
||||
@@ -14,8 +20,9 @@ async function body(req) {
|
||||
}
|
||||
|
||||
export class PeerRegistry {
|
||||
constructor(scopeFor) {
|
||||
constructor(scopeFor, policy = new PeerAddressPolicy()) {
|
||||
this.scopeFor = scopeFor;
|
||||
this.policy = policy;
|
||||
this.sessions = new Map();
|
||||
}
|
||||
owner(req) {
|
||||
@@ -82,6 +89,7 @@ export class PeerRegistry {
|
||||
json(res, 200, {
|
||||
connected: Boolean(peer?.connected),
|
||||
needs_password: !peer?.connected,
|
||||
...(peer && plaintext([peer.active]) ? { insecure_transport: true } : {}),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -113,6 +121,24 @@ export class PeerRegistry {
|
||||
urls.every((url) => previous.endpoints.includes(url));
|
||||
const version = (owner.versions.get(id) ?? 0) + 1;
|
||||
owner.versions.set(id, version);
|
||||
// Every address is checked (and its DNS answer pinned) before any
|
||||
// request leaves this machine; a refused address is never contacted.
|
||||
const pins = new Map();
|
||||
const refused = [];
|
||||
await Promise.all(
|
||||
urls.map(async (value) => {
|
||||
try {
|
||||
pins.set(value, await this.policy.pin(new URL(value)));
|
||||
} catch (error) {
|
||||
if (error instanceof PeerAddressError)
|
||||
refused.push({ endpoint: value, error: error.message });
|
||||
}
|
||||
}),
|
||||
);
|
||||
if (refused.length === urls.length) {
|
||||
json(res, 400, { error: refused[0].error, refused_endpoints: refused });
|
||||
return true;
|
||||
}
|
||||
if (previous && !sameEndpoints) {
|
||||
for (const socket of previous.sockets) socket.destroy();
|
||||
owner.peers.delete(id);
|
||||
@@ -127,6 +153,8 @@ export class PeerRegistry {
|
||||
const results = await Promise.all(
|
||||
urls.map(async (value) => {
|
||||
try {
|
||||
const pin = pins.get(value);
|
||||
if (!pin) return { connected: false, needs_password: false };
|
||||
const old = previous?.endpoints.includes(value)
|
||||
? (previous.cookies.get(value) ?? "")
|
||||
: "";
|
||||
@@ -134,6 +162,7 @@ export class PeerRegistry {
|
||||
new URL(value),
|
||||
old,
|
||||
data.password,
|
||||
pin.lookup,
|
||||
);
|
||||
if (status.connected) {
|
||||
peer.cookies.set(value, status.cookie);
|
||||
@@ -163,6 +192,8 @@ export class PeerRegistry {
|
||||
owner.peers.set(id, peer);
|
||||
json(res, 200, {
|
||||
connected_endpoints: [...peer.cookies.keys()],
|
||||
...(plaintext(urls) ? { insecure_transport: true } : {}),
|
||||
...(refused.length ? { refused_endpoints: refused } : {}),
|
||||
connected: peer.connected,
|
||||
needs_password:
|
||||
!peer.connected && results.some((r) => r.needs_password),
|
||||
|
||||
+111
-86
@@ -6,6 +6,8 @@ import {
|
||||
json,
|
||||
} from "./peerTransport.js";
|
||||
import { PeerRegistry } from "./peerRegistry.js";
|
||||
import { withServerToken } from "./serverToken.js";
|
||||
import { rememberDiscovered } from "./peerAddress.js";
|
||||
|
||||
// Peer files are untrusted content, never privileged control-UI documents.
|
||||
// Apply this even for older peers whose /files endpoint has no sandbox header.
|
||||
@@ -39,6 +41,22 @@ export class PeerRelay extends PeerRegistry {
|
||||
throw new Error("Remote origin changed");
|
||||
return { url, cookie: peer.cookies.get(selected), peer };
|
||||
}
|
||||
// Resolve the peer once for this request, check the answer against the
|
||||
// address policy (peerAddress.js) and connect only to that address.
|
||||
pinned(target, reply, send) {
|
||||
this.policy
|
||||
.pin(target.url)
|
||||
.then((pin) => {
|
||||
if (!reply.destroyed) send(pin.lookup);
|
||||
})
|
||||
.catch(() => {
|
||||
if (typeof reply.writeHead !== "function")
|
||||
reply.end("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n");
|
||||
else if (!reply.headersSent)
|
||||
json(reply, 403, { error: "Server address is not allowed" });
|
||||
else reply.destroy();
|
||||
});
|
||||
}
|
||||
http(req, res) {
|
||||
if (!req.url.startsWith("/peers/")) return false;
|
||||
try {
|
||||
@@ -52,59 +70,62 @@ export class PeerRelay extends PeerRegistry {
|
||||
json(res, 404, { error: "Unsupported remote resource" });
|
||||
return true;
|
||||
}
|
||||
const headers = { ...(target.cookie ? { cookie: target.cookie } : {}) };
|
||||
for (const name of [
|
||||
"content-type",
|
||||
"content-length",
|
||||
"range",
|
||||
"x-file-name",
|
||||
"x-upload-name",
|
||||
"x-chat-file-name",
|
||||
"x-pipelines-upload-name",
|
||||
])
|
||||
if (req.headers[name]) headers[name] = req.headers[name];
|
||||
const upstream = remoteRequest(target.url, {
|
||||
method: req.method,
|
||||
headers,
|
||||
});
|
||||
upstream.setTimeout(30000, () => upstream.destroy());
|
||||
upstream.on("response", (response) => {
|
||||
const safe = {};
|
||||
this.pinned(target, res, (lookup) => {
|
||||
const headers = { ...(target.cookie ? { cookie: target.cookie } : {}) };
|
||||
for (const name of [
|
||||
"content-type",
|
||||
"content-length",
|
||||
"content-range",
|
||||
"accept-ranges",
|
||||
"content-disposition",
|
||||
"range",
|
||||
"x-file-name",
|
||||
"x-upload-name",
|
||||
"x-chat-file-name",
|
||||
"x-pipelines-upload-name",
|
||||
])
|
||||
if (response.headers[name]) safe[name] = response.headers[name];
|
||||
res.writeHead(
|
||||
response.statusCode >= 300 && response.statusCode < 400
|
||||
? 502
|
||||
: response.statusCode,
|
||||
{
|
||||
...safe,
|
||||
"Cache-Control": "private, no-store",
|
||||
// Multiple CSP policies intersect: preserve a peer's stricter
|
||||
// restrictions while always imposing the local sandbox boundary.
|
||||
"Content-Security-Policy": response.headers[
|
||||
"content-security-policy"
|
||||
]
|
||||
? [response.headers["content-security-policy"], contentPolicy]
|
||||
: contentPolicy,
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
);
|
||||
response.pipe(res);
|
||||
if (req.headers[name]) headers[name] = req.headers[name];
|
||||
const upstream = remoteRequest(target.url, {
|
||||
method: req.method,
|
||||
lookup,
|
||||
headers,
|
||||
});
|
||||
upstream.setTimeout(30000, () => upstream.destroy());
|
||||
upstream.on("response", (response) => {
|
||||
const safe = {};
|
||||
for (const name of [
|
||||
"content-type",
|
||||
"content-length",
|
||||
"content-range",
|
||||
"accept-ranges",
|
||||
"content-disposition",
|
||||
])
|
||||
if (response.headers[name]) safe[name] = response.headers[name];
|
||||
res.writeHead(
|
||||
response.statusCode >= 300 && response.statusCode < 400
|
||||
? 502
|
||||
: response.statusCode,
|
||||
{
|
||||
...safe,
|
||||
"Cache-Control": "private, no-store",
|
||||
// Multiple CSP policies intersect: preserve a peer's stricter
|
||||
// restrictions while always imposing the local sandbox boundary.
|
||||
"Content-Security-Policy": response.headers[
|
||||
"content-security-policy"
|
||||
]
|
||||
? [response.headers["content-security-policy"], contentPolicy]
|
||||
: contentPolicy,
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
);
|
||||
response.pipe(res);
|
||||
});
|
||||
upstream.on("error", () => {
|
||||
if (!res.headersSent)
|
||||
json(res, 502, { error: "Remote server unavailable" });
|
||||
else res.destroy();
|
||||
});
|
||||
req.on("aborted", () => upstream.destroy());
|
||||
res.on("close", () => upstream.destroy());
|
||||
req.pipe(upstream);
|
||||
});
|
||||
upstream.on("error", () => {
|
||||
if (!res.headersSent)
|
||||
json(res, 502, { error: "Remote server unavailable" });
|
||||
else res.destroy();
|
||||
});
|
||||
req.on("aborted", () => upstream.destroy());
|
||||
res.on("close", () => upstream.destroy());
|
||||
req.pipe(upstream);
|
||||
} catch {
|
||||
json(res, 401, { error: "Sign in to the remote server again" });
|
||||
}
|
||||
@@ -122,47 +143,49 @@ export class PeerRelay extends PeerRegistry {
|
||||
"sec-websocket-version": "13",
|
||||
...(target.cookie ? { cookie: target.cookie } : {}),
|
||||
};
|
||||
const upstream = remoteRequest(target.url, { headers });
|
||||
upstream.setTimeout(10000, () => upstream.destroy());
|
||||
upstream.on("upgrade", (response, remote, remoteHead) => {
|
||||
socket.write(
|
||||
`HTTP/1.1 101 Switching Protocols\r\n${Object.entries(
|
||||
response.headers,
|
||||
)
|
||||
.filter(([k]) =>
|
||||
[
|
||||
"upgrade",
|
||||
"connection",
|
||||
"sec-websocket-accept",
|
||||
"sec-websocket-protocol",
|
||||
].includes(k),
|
||||
this.pinned(target, socket, (lookup) => {
|
||||
const upstream = remoteRequest(target.url, { headers, lookup });
|
||||
upstream.setTimeout(10000, () => upstream.destroy());
|
||||
upstream.on("upgrade", (response, remote, remoteHead) => {
|
||||
socket.write(
|
||||
`HTTP/1.1 101 Switching Protocols\r\n${Object.entries(
|
||||
response.headers,
|
||||
)
|
||||
.map(([k, v]) => `${k}: ${v}`)
|
||||
.join("\r\n")}\r\n\r\n`,
|
||||
);
|
||||
target.peer.sockets.add(socket);
|
||||
remote.setTimeout(0);
|
||||
socket.once("close", () => {
|
||||
target.peer.sockets.delete(socket);
|
||||
remote.destroy();
|
||||
.filter(([k]) =>
|
||||
[
|
||||
"upgrade",
|
||||
"connection",
|
||||
"sec-websocket-accept",
|
||||
"sec-websocket-protocol",
|
||||
].includes(k),
|
||||
)
|
||||
.map(([k, v]) => `${k}: ${v}`)
|
||||
.join("\r\n")}\r\n\r\n`,
|
||||
);
|
||||
target.peer.sockets.add(socket);
|
||||
remote.setTimeout(0);
|
||||
socket.once("close", () => {
|
||||
target.peer.sockets.delete(socket);
|
||||
remote.destroy();
|
||||
});
|
||||
remote.once("close", () => socket.destroy());
|
||||
socket.on("error", () => remote.destroy());
|
||||
remote.on("error", () => socket.destroy());
|
||||
if (head?.length) remote.write(head);
|
||||
if (remoteHead?.length) socket.write(remoteHead);
|
||||
remote.pipe(socket);
|
||||
socket.pipe(remote);
|
||||
});
|
||||
remote.once("close", () => socket.destroy());
|
||||
socket.on("error", () => remote.destroy());
|
||||
remote.on("error", () => socket.destroy());
|
||||
if (head?.length) remote.write(head);
|
||||
if (remoteHead?.length) socket.write(remoteHead);
|
||||
remote.pipe(socket);
|
||||
socket.pipe(remote);
|
||||
upstream.on("response", (response) => {
|
||||
response.resume();
|
||||
socket.end(
|
||||
`HTTP/1.1 ${response.statusCode === 401 ? 401 : 502} Remote Unavailable\r\nContent-Length: 0\r\n\r\n`,
|
||||
);
|
||||
});
|
||||
upstream.on("error", () => socket.destroy());
|
||||
socket.once("close", () => upstream.destroy());
|
||||
upstream.end();
|
||||
});
|
||||
upstream.on("response", (response) => {
|
||||
response.resume();
|
||||
socket.end(
|
||||
`HTTP/1.1 ${response.statusCode === 401 ? 401 : 502} Remote Unavailable\r\nContent-Length: 0\r\n\r\n`,
|
||||
);
|
||||
});
|
||||
upstream.on("error", () => socket.destroy());
|
||||
socket.once("close", () => upstream.destroy());
|
||||
upstream.end();
|
||||
} catch {
|
||||
socket.end("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n");
|
||||
}
|
||||
@@ -176,7 +199,9 @@ export async function proxyDiscovery(req, res, host, port) {
|
||||
new URL(
|
||||
`http://${host.includes(":") ? `[${host}]` : host}:${port}/discovery`,
|
||||
),
|
||||
{ headers: withServerToken({}) },
|
||||
);
|
||||
if (response.status === 200) rememberDiscovered(response.body);
|
||||
res
|
||||
.writeHead(response.status, {
|
||||
"Content-Type": "application/json",
|
||||
|
||||
@@ -28,12 +28,14 @@ export function remoteRequest(url, options = {}) {
|
||||
// Never follows redirects or sends local browser cookies to another machine.
|
||||
export function boundedRequest(
|
||||
url,
|
||||
{ method = "GET", cookie = "", body = "", headers = {} } = {},
|
||||
{ method = "GET", cookie = "", body = "", headers = {}, lookup } = {},
|
||||
) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = remoteRequest(url, {
|
||||
method,
|
||||
headers: { ...headers, ...(cookie ? { Cookie: cookie } : {}) },
|
||||
// A pinned peer address (peerAddress.js) is connected to directly.
|
||||
...(lookup ? { lookup } : {}),
|
||||
});
|
||||
const timer = setTimeout(
|
||||
() => request.destroy(new Error("Server timed out")),
|
||||
@@ -79,7 +81,7 @@ export function sessionCookie(response) {
|
||||
.join("; ");
|
||||
}
|
||||
|
||||
export async function authenticate(url, cookie, password) {
|
||||
export async function authenticate(url, cookie, password, lookup) {
|
||||
const login = new URL("/login", webOrigin(url));
|
||||
let response;
|
||||
if (password !== undefined) {
|
||||
@@ -88,6 +90,7 @@ export async function authenticate(url, cookie, password) {
|
||||
method: "POST",
|
||||
body,
|
||||
cookie,
|
||||
lookup,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Content-Length": Buffer.byteLength(body),
|
||||
@@ -99,7 +102,7 @@ export async function authenticate(url, cookie, password) {
|
||||
return { connected: false, needs_password: true, cookie: "" };
|
||||
}
|
||||
}
|
||||
response = await boundedRequest(login, { cookie });
|
||||
response = await boundedRequest(login, { cookie, lookup });
|
||||
if ([302, 303].includes(response.status))
|
||||
return { connected: true, needs_password: false, cookie };
|
||||
if (
|
||||
@@ -111,7 +114,7 @@ export async function authenticate(url, cookie, password) {
|
||||
if (response.status === 200)
|
||||
return { connected: true, needs_password: false, cookie };
|
||||
if (response.status === 404) {
|
||||
const health = await boundedRequest(new URL("/healthz", webOrigin(url)));
|
||||
const health = await boundedRequest(new URL("/healthz", webOrigin(url)), { lookup });
|
||||
if (health.status === 200 && JSON.parse(health.body)?.healthy === true)
|
||||
return { connected: true, needs_password: false, cookie: "" };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// The shared secret between this proxy and the local Pipelines server
|
||||
// (internal/servertoken, docs/notes/security-boundary.md). The installer writes
|
||||
// it to a private file beside web-auth.json; the server, when configured with
|
||||
// it, refuses any request without it. Only requests to the local upstream carry
|
||||
// it: the peer relay never forwards it to another machine.
|
||||
import { lstatSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const SERVER_TOKEN_HEADER = "x-pipelines-token";
|
||||
|
||||
export function serverTokenPath(env = process.env) {
|
||||
if (env.PIPELINES_SERVER_TOKEN_FILE) return env.PIPELINES_SERVER_TOKEN_FILE;
|
||||
return join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "pipelines", "server-token");
|
||||
}
|
||||
|
||||
let cached = { key: "", token: "" };
|
||||
|
||||
// The token, re-read when the file changes; "" when no file exists. A file
|
||||
// another user could read or replace is refused (same rule as the Go reader).
|
||||
export function serverToken(path = serverTokenPath()) {
|
||||
let info;
|
||||
try {
|
||||
info = lstatSync(path);
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
if (!info.isFile()) throw new Error(`server token ${path} is not a regular file`);
|
||||
if (typeof process.getuid === "function" && (info.uid !== process.getuid() || info.mode & 0o077))
|
||||
throw new Error(`server token ${path} must be owned by this user and private (chmod 600)`);
|
||||
const key = `${path}:${info.ino}:${info.mtimeMs}:${info.size}`;
|
||||
if (cached.key !== key) {
|
||||
const token = readFileSync(path, "utf8").trim();
|
||||
if (token.length < 32 || /\s/.test(token)) throw new Error(`server token ${path} is malformed`);
|
||||
cached = { key, token };
|
||||
}
|
||||
return cached.token;
|
||||
}
|
||||
|
||||
// Headers for the local upstream: any client-supplied token is dropped and the
|
||||
// proxy's own is set, so the browser never chooses what the server sees.
|
||||
export function withServerToken(headers, token = serverToken()) {
|
||||
const result = { ...headers };
|
||||
for (const name of Object.keys(result))
|
||||
if (name.toLowerCase() === SERVER_TOKEN_HEADER) delete result[name];
|
||||
if (token) result[SERVER_TOKEN_HEADER] = token;
|
||||
return result;
|
||||
}
|
||||
Reference in New Issue
Block a user