aoc-copilot
Version:
Advent of Code automatic runner for examples and inputs
135 lines (129 loc) • 5.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.errExpiredSessionCookie = exports.cookieSteps = void 0;
exports.request = request;
const node_https_1 = require("node:https");
const cookieSteps = `
In Chromium-based browsers like Chrome and Edge you can obtain your cookie by
visiting the site, logging in, opening developer tools (F12), and clicking
Application then expanding Cookies under the Storage section, locating the
adventofcode.com cookie, and copying the session value.
Then, add the following line to a .env file in the root of your project:
AOC_SESSION_COOKIE="<your session cookie value>"
NOTE: Protect your session ID! For example, add .env to your .gitignore file.
`;
exports.cookieSteps = cookieSteps;
const errExpiredSessionCookie = `
Expired Session Cookie
Your session cookie seems to have expired or is no longer valid. Please
retrieve a new session ID and update your .env file.
` + cookieSteps;
exports.errExpiredSessionCookie = errExpiredSessionCookie;
const errSelfSignedCertInChain = `
This error occurs on networks that uses a self-signed certificate to inspect
encrypted traffic, which is common in coporate environments, but could also
indicate a man-in-the-middle attack.
If you need to override the trusted CA certificates, you can add them with
CERTIFICATE="<your certificate(s)>" in your .env file.
See options.ca at https://nodejs.org/api/tls.html#tlscreatesecurecontextoptions
`;
const errUnableToGetIssuerCertLocally = `
This error may occur when you've added CERTIFICATE="<your certificate(s)>" in
your .env file but are not on a network that uses self-signed certificates.
Try connecting to the network that uses self-signed certificates -- commonly a
corporate network -- or removing the certificate from your .env file.
`;
function legacyRequest(method, path, cookie, ca, formData) {
return new Promise((resolve, reject) => {
const options = {
hostname: "adventofcode.com",
path,
method,
ca,
headers: {
cookie,
"user-agent": "github.com/jasonmuzzy/aoc-copilot by aoc-copilot@outlook.com"
},
};
if (method === 'POST' && !!formData)
options.headers["Content-Type"] = "application/x-www-form-urlencoded";
const req = (0, node_https_1.request)(options, res => {
let body = "";
res.on("data", chunk => body += chunk);
res.on("end", () => resolve(body));
});
req.on('error', error => {
if (error?.code === 'SELF_SIGNED_CERT_IN_CHAIN') { // https://www.reddit.com/r/typescript/comments/11yilc1/how_the_hell_do_you_handle_exceptions_in/
reject(new Error(`HTTP ${error?.code}\n${errSelfSignedCertInChain}`));
}
else if (error?.code === 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY') {
reject(new Error(`HTTP ${error?.code}\n${errUnableToGetIssuerCertLocally}`));
}
else
reject(error);
});
req.on('response', res => {
if (res.statusCode !== undefined && res.statusCode > 299) {
const isRedirect = (statusCode) => statusCode >= 300 && statusCode <= 399;
const msg = isRedirect(res.statusCode)
? errExpiredSessionCookie
: res.statusMessage;
reject(new Error(`HTTP ${res.statusCode}\n${msg}`));
}
});
if (method === 'POST' && !!formData)
req.write(formData);
req.end();
});
}
async function request(method, path, cookie, ca, formData) {
// Check for NO_HTTP environment variable (e.g. in case of automated tests running in GitHub)
const no_http = process.env.NO_HTTP?.toLowerCase() ?? 'false';
if (['1', 'true'].includes(no_http)) {
throw new Error(`process.env.NO_HTTP = "${no_http}"; no HTTP requests allowed`);
}
// Common error to forget the "session=" at the beginning of the cookie value in .env
if (!cookie.startsWith('session=')) {
cookie = 'session=' + cookie;
}
if (!!ca) {
// we can't set a cert chain with `fetch()`, can only disable cert
// validation: https://github.com/orgs/nodejs/discussions/44038
// so instead of doing that, use the previous version
return legacyRequest(method, path, cookie, ca, formData);
}
const headers = new Headers();
headers.set('agent', 'github.com/jasonmuzzy/aoc-copilot by aoc-copilot@outlook.com');
headers.set('cookie', cookie);
const url = new URL(path, 'https://adventofcode.com');
const options = {
method,
headers,
redirect: 'manual'
};
if (method === 'POST' && !!formData) {
options.body = formData;
headers.set('content-type', 'application/x-www-form-urlencoded');
}
else if (!!formData) {
url.search = formData;
}
try {
const response = await fetch(url, options);
if (response.redirected) {
throw new Error(`HTTP ${response.status}\n${errExpiredSessionCookie}`);
}
if (!response.ok) {
throw new Error(`HTTP ${response.status} - ${response.statusText}\nFetch Error`);
}
const body = await response.text();
return body;
}
catch (error) {
if (error.code === 'SELF_SIGNED_CERT_IN_CHAIN') {
throw new Error(`HTTP ${error.code}\n${errSelfSignedCertInChain}`);
}
throw error;
}
}
//# sourceMappingURL=httpsPromisfied.js.map