Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,173 @@
|
||||
"use strict";
|
||||
|
||||
const http = require("node:http");
|
||||
const https = require("node:https");
|
||||
const { PassThrough } = require("node:stream");
|
||||
const { cancelUpstreamOnClose, destroyStreams } = require("./stream-lifecycle");
|
||||
|
||||
function createRemoteHttpGetters(deps) {
|
||||
const now = deps.now || Date.now;
|
||||
const scheduleTimeout = deps.setTimeout || setTimeout;
|
||||
const cancelTimeout = deps.clearTimeout || clearTimeout;
|
||||
|
||||
function get(urlString, opts, streaming) {
|
||||
const maxBytes = Number.isFinite(opts.maxBytes) ? opts.maxBytes : deps.maxBytes;
|
||||
const timeoutMs = Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : deps.timeoutMs;
|
||||
const maxRedirects = Number.isFinite(opts.maxRedirects) ? opts.maxRedirects : deps.maxRedirects;
|
||||
const redirects = Number.isFinite(opts._redirects) ? opts._redirects : 0;
|
||||
const requireHttps = opts.requireHttps === true;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
let finished = false;
|
||||
let exchange = null;
|
||||
let sink = null;
|
||||
let hardTimer = null;
|
||||
const deadline = now() + timeoutMs;
|
||||
const clearDeadline = () => {
|
||||
cancelTimeout(hardTimer);
|
||||
hardTimer = null;
|
||||
};
|
||||
const fail = (error) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearDeadline();
|
||||
// adpanel:remote-stream-failure - after headers, the stream rather
|
||||
// than the already-resolved getter promise owns transport failures.
|
||||
if (sink) sink.destroy(error);
|
||||
destroyStreams(exchange?.response, exchange?.request);
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
const active = () => {
|
||||
if (finished) return false;
|
||||
if (now() >= deadline) {
|
||||
fail(new Error("Request timeout"));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const finishResolve = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve(value);
|
||||
};
|
||||
const complete = () => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearDeadline();
|
||||
};
|
||||
|
||||
async function visit(currentUrl, redirectCount) {
|
||||
if (!active()) return;
|
||||
const validated = await deps.assertSafeRemoteUrlWithResolvedIp(currentUrl);
|
||||
if (!active()) return;
|
||||
const { url: parsedUrl, resolvedIp, originalHostname } = validated;
|
||||
if (requireHttps && parsedUrl.protocol !== "https:") throw new Error("HTTPS is required for this download");
|
||||
const transport = parsedUrl.protocol === "https:" ? (deps.https || https) : (deps.http || http);
|
||||
const agent = deps.createSsrfSafeAgent(resolvedIp, parsedUrl.protocol, originalHostname);
|
||||
if (!active()) return;
|
||||
const hop = { request: null, response: null, ended: false, discarded: false };
|
||||
exchange = hop;
|
||||
hop.request = transport.request({
|
||||
method: "GET",
|
||||
hostname: resolvedIp,
|
||||
port: parsedUrl.port || (parsedUrl.protocol === "https:" ? 443 : 80),
|
||||
path: parsedUrl.pathname + parsedUrl.search,
|
||||
headers: { "User-Agent": "ADPanel/1.0", "Accept": "*/*", "Host": originalHostname },
|
||||
agent,
|
||||
timeout: Math.max(1, deadline - now()),
|
||||
...(parsedUrl.protocol === "https:" ? { servername: deps.tlsServernameForHost(originalHostname) } : {}),
|
||||
}, (res) => {
|
||||
hop.response = res;
|
||||
res.on("error", (error) => { if (!hop.discarded && !hop.ended) fail(error); });
|
||||
res.on("aborted", () => { if (!hop.discarded && !hop.ended) fail(new Error("Remote response aborted")); });
|
||||
res.on("close", () => { if (!hop.discarded && !hop.ended) fail(new Error("Remote response closed before end")); });
|
||||
if (!active() || hop.discarded) {
|
||||
destroyStreams(res, hop.request);
|
||||
return;
|
||||
}
|
||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
if (redirectCount >= maxRedirects) return fail(new Error("Too many redirects"));
|
||||
let nextUrl;
|
||||
try {
|
||||
nextUrl = new URL(res.headers.location, parsedUrl).toString();
|
||||
} catch (error) {
|
||||
return fail(new Error(`Invalid redirect Location header: ${error?.message || error}`));
|
||||
}
|
||||
hop.discarded = true;
|
||||
destroyStreams(res, hop.request);
|
||||
visit(nextUrl, redirectCount + 1).catch(fail);
|
||||
return;
|
||||
}
|
||||
if (res.statusCode !== 200) return fail(new Error(`HTTP ${res.statusCode}`));
|
||||
|
||||
const chunks = [];
|
||||
if (streaming) {
|
||||
sink = new PassThrough();
|
||||
sink.on("error", () => {});
|
||||
sink.once("end", complete);
|
||||
cancelUpstreamOnClose(sink, res, hop.request, complete);
|
||||
}
|
||||
let total = 0;
|
||||
let upstreamPaused = false;
|
||||
res.on("data", (chunk) => {
|
||||
if (!active()) return;
|
||||
total += chunk.length;
|
||||
if (total > maxBytes) {
|
||||
const error = new Error(streaming ? `Download too large (limit ${maxBytes} bytes)` : "Download too large");
|
||||
if (streaming) error.code = "ADPANEL_REMOTE_MAX_BYTES";
|
||||
fail(error);
|
||||
return;
|
||||
}
|
||||
if (!streaming) {
|
||||
chunks.push(chunk);
|
||||
} else if (!sink.write(chunk) && !upstreamPaused) {
|
||||
upstreamPaused = true;
|
||||
res.pause();
|
||||
sink.once("drain", () => {
|
||||
if (!active() || !upstreamPaused || hop.ended) return;
|
||||
upstreamPaused = false;
|
||||
res.resume();
|
||||
});
|
||||
}
|
||||
});
|
||||
res.on("end", () => {
|
||||
if (!active()) return;
|
||||
hop.ended = true;
|
||||
if (streaming) sink.end();
|
||||
else {
|
||||
complete();
|
||||
finishResolve(Buffer.concat(chunks));
|
||||
}
|
||||
});
|
||||
if (streaming) finishResolve({ stream: sink, contentType: String(res.headers["content-type"] || ""), finalUrl: parsedUrl.toString() });
|
||||
});
|
||||
hop.request.on("error", (error) => { if (!hop.discarded && !hop.ended) fail(error); });
|
||||
hop.request.on("timeout", () => { if (!hop.discarded && !hop.ended) fail(new Error("Request timeout")); });
|
||||
hop.request.on("close", () => {
|
||||
if (!hop.discarded && !hop.response) fail(new Error("Remote request closed before headers"));
|
||||
});
|
||||
if (!active() || hop.discarded) {
|
||||
destroyStreams(hop.response, hop.request);
|
||||
return;
|
||||
}
|
||||
hop.request.end();
|
||||
}
|
||||
|
||||
// adpanel:remote-total-deadline - validation, all redirects and body
|
||||
// consumption share one budget; expired DNS must never start a dial.
|
||||
hardTimer = scheduleTimeout(() => fail(new Error("Request timeout")), timeoutMs);
|
||||
visit(urlString, redirects).catch(fail);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
httpGetRaw: (url, opts = {}) => get(url, opts, false),
|
||||
ssrfPipedHttpGet: (url, opts = {}) => get(url, opts, true),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createRemoteHttpGetters };
|
||||
Reference in new issue
Block a user