fix: close APT adversarial runtime gaps

This commit is contained in:
2026-08-19 21:59:19 +00:00
parent 2f492b662d
commit cf75ea9bc2
9 changed files with 688 additions and 233 deletions
+161 -96
View File
@@ -5,10 +5,16 @@ const crypto = require('node:crypto');
const DEFAULT_SECRET_BYTES = 32;
const DEFAULT_MAX_BODY_BYTES = 64 * 1024;
const DEFAULT_BODY_DEADLINE_MS = 2_000;
const DEFAULT_CHALLENGE_TTL_MS = 5_000;
const DEFAULT_MAX_CHALLENGES = 64;
const APT_EXTENSION_ID = 'onbkfpbggekakjddomjjnboippimlmch';
const APT_EXTENSION_ORIGIN = `chrome-extension://${APT_EXTENSION_ID}`;
const SECRET_PATTERN = /^[A-Za-z0-9_-]{43}$/;
const NONCE_PATTERN = SECRET_PATTERN;
const PROOF_PATTERN = SECRET_PATTERN;
const EXTENSION_ORIGIN_PATTERN = /^chrome-extension:\/\/[a-p]{32}$/;
const SERVER_PROOF_DOMAIN = 'apt-server-challenge-v1';
const COOKIE_PROOF_DOMAIN = 'apt-cookie-request-v1';
class BridgeAuthError extends Error {
constructor(code, message, statusCode = 400) {
@@ -22,10 +28,12 @@ class BridgeAuthError extends Error {
function dependencies(overrides = {}) {
return {
randomBytes: overrides.randomBytes || crypto.randomBytes,
scryptSync: overrides.scryptSync || crypto.scryptSync,
timingSafeEqual: overrides.timingSafeEqual || crypto.timingSafeEqual,
createHmac: overrides.createHmac || crypto.createHmac,
createHash: overrides.createHash || crypto.createHash,
setTimeout: overrides.setTimeout || setTimeout,
clearTimeout: overrides.clearTimeout || clearTimeout
clearTimeout: overrides.clearTimeout || clearTimeout,
now: overrides.now || Date.now
};
}
@@ -44,71 +52,98 @@ function assertPairingSecret(secret) {
}
}
function hashPairingSecret(secret, options = {}) {
function canonicalServerProof(clientNonce, serverNonce) {
return JSON.stringify([SERVER_PROOF_DOMAIN, clientNonce, serverNonce]);
}
function canonicalCookieProof({ clientNonce, serverNonce, deploymentUrl, cookieValue } = {}) {
return JSON.stringify([COOKIE_PROOF_DOMAIN, clientNonce, serverNonce, deploymentUrl, cookieValue]);
}
function computeHmac(secret, message, options = {}) {
assertPairingSecret(secret);
const deps = dependencies(options);
const salt = deps.randomBytes(16);
const digest = deps.scryptSync(secret, salt, 32);
return Object.freeze({
version: 1,
algorithm: 'scrypt',
salt: salt.toString('base64url'),
digest: Buffer.from(digest).toString('base64url')
});
return dependencies(options).createHmac('sha256', secret).update(message, 'utf8').digest('base64url');
}
function computeServerProof(secret, clientNonce, serverNonce, options = {}) {
return computeHmac(secret, canonicalServerProof(clientNonce, serverNonce), options);
}
function computeCookieProof(secret, request, options = {}) {
return computeHmac(secret, canonicalCookieProof(request), options);
}
function isValidEnvelope(envelope) {
return Boolean(
envelope &&
envelope.version === 1 &&
envelope.algorithm === 'scrypt' &&
typeof envelope.salt === 'string' &&
/^[A-Za-z0-9_-]{22}$/.test(envelope.salt) &&
envelope.version === 2 &&
envelope.algorithm === 'electron-safe-storage' &&
typeof envelope.ciphertext === 'string' &&
/^[A-Za-z0-9+/]+={0,2}$/.test(envelope.ciphertext) &&
envelope.ciphertext.length >= 16 && envelope.ciphertext.length <= 8192 &&
typeof envelope.digest === 'string' &&
/^[A-Za-z0-9_-]{43}$/.test(envelope.digest)
PROOF_PATTERN.test(envelope.digest)
);
}
function verifyPairingSecret(secret, envelope, options = {}) {
if (!SECRET_PATTERN.test(typeof secret === 'string' ? secret : '') || !isValidEnvelope(envelope)) {
return false;
}
try {
const deps = dependencies(options);
const salt = Buffer.from(envelope.salt, 'base64url');
const expected = Buffer.from(envelope.digest, 'base64url');
const actual = Buffer.from(deps.scryptSync(secret, salt, expected.length));
return actual.length === expected.length && deps.timingSafeEqual(actual, expected);
} catch {
return false;
function assertExtensionOrigin(origin) {
if (typeof origin !== 'string' || !EXTENSION_ORIGIN_PATTERN.test(origin) || origin !== APT_EXTENSION_ORIGIN) {
throw new BridgeAuthError('INVALID_EXTENSION_ORIGIN', 'The bridge only accepts the committed Alta Proxy Tool extension origin.');
}
}
function assertExtensionOrigin(origin) {
if (typeof origin !== 'string' || !EXTENSION_ORIGIN_PATTERN.test(origin)) {
throw new BridgeAuthError(
'INVALID_EXTENSION_ORIGIN',
'Expected an exact stable chrome-extension origin.'
);
}
function safeEqualText(left, right, deps) {
if (typeof left !== 'string' || typeof right !== 'string') return false;
const leftBytes = Buffer.from(left, 'utf8');
const rightBytes = Buffer.from(right, 'utf8');
return leftBytes.length === rightBytes.length && deps.timingSafeEqual(leftBytes, rightBytes);
}
class BridgeAuth {
constructor({ expectedOrigin = APT_EXTENSION_ORIGIN, envelope = null, ...injected } = {}) {
constructor({
expectedOrigin = APT_EXTENSION_ORIGIN,
envelope = null,
protect,
unprotect,
maxChallenges = DEFAULT_MAX_CHALLENGES,
challengeTtlMs = DEFAULT_CHALLENGE_TTL_MS,
...injected
} = {}) {
assertExtensionOrigin(expectedOrigin);
if (expectedOrigin !== APT_EXTENSION_ORIGIN) {
throw new BridgeAuthError(
'INVALID_EXTENSION_ORIGIN',
'The bridge only accepts the committed Alta Proxy Tool extension origin.'
);
if (typeof protect !== 'function' || typeof unprotect !== 'function') {
throw new BridgeAuthError('SECURE_STORAGE_UNAVAILABLE', 'Secure pairing storage is unavailable.', 503);
}
if (!Number.isSafeInteger(maxChallenges) || maxChallenges < 1 || maxChallenges > 1024) {
throw new BridgeAuthError('INVALID_CHALLENGE_LIMIT', 'Challenge limit is invalid.');
}
if (!Number.isSafeInteger(challengeTtlMs) || challengeTtlMs < 1 || challengeTtlMs > 60_000) {
throw new BridgeAuthError('INVALID_CHALLENGE_TTL', 'Challenge lifetime is invalid.');
}
if (envelope !== null && !isValidEnvelope(envelope)) {
throw new BridgeAuthError('INVALID_SECRET_ENVELOPE', 'The persisted pairing envelope is invalid.');
}
this.expectedOrigin = expectedOrigin;
this._envelope = envelope ? Object.freeze({ ...envelope }) : null;
this._protect = protect;
this._unprotect = unprotect;
this._maxChallenges = maxChallenges;
this._challengeTtlMs = challengeTtlMs;
this._dependencies = dependencies(injected);
this._challenges = new Map();
this._secret = null;
this._envelope = envelope ? Object.freeze({ ...envelope }) : null;
if (envelope) {
try {
const secret = unprotect(Buffer.from(envelope.ciphertext, 'base64'));
assertPairingSecret(secret);
const digest = this._dependencies.createHash('sha256').update(secret, 'utf8').digest('base64url');
if (!safeEqualText(digest, envelope.digest, this._dependencies)) throw new Error('digest mismatch');
this._secret = secret;
} catch {
throw new BridgeAuthError('INVALID_SECRET_ENVELOPE', 'The persisted pairing envelope could not be decrypted.');
}
}
}
get envelope() {
@@ -117,24 +152,75 @@ class BridgeAuth {
rotate() {
const secret = generatePairingSecret(this._dependencies);
this._envelope = hashPairingSecret(secret, this._dependencies);
let protectedBytes;
try {
protectedBytes = this._protect(secret);
} catch {
throw new BridgeAuthError('SECURE_STORAGE_UNAVAILABLE', 'Secure pairing storage is unavailable.', 503);
}
if (!Buffer.isBuffer(protectedBytes) || protectedBytes.length === 0 || protectedBytes.length > 6144) {
throw new BridgeAuthError('SECURE_STORAGE_UNAVAILABLE', 'Secure pairing storage returned invalid ciphertext.', 503);
}
this._secret = secret;
this._challenges.clear();
this._envelope = Object.freeze({
version: 2,
algorithm: 'electron-safe-storage',
ciphertext: protectedBytes.toString('base64'),
digest: this._dependencies.createHash('sha256').update(secret, 'utf8').digest('base64url')
});
return { secret, envelope: this.envelope };
}
revoke() {
this._secret = null;
this._envelope = null;
this._challenges.clear();
}
authenticate({ origin, secret } = {}) {
if (origin !== this.expectedOrigin || !this._envelope) return false;
return verifyPairingSecret(secret, this._envelope, this._dependencies);
_purgeExpired(now) {
for (const [nonce, challenge] of this._challenges) {
if (challenge.expiresAt <= now) this._challenges.delete(nonce);
}
}
authenticateRequest(request) {
if (!request || typeof request !== 'object') return false;
const headers = request.headers || {};
const secret = headers['x-apt-pairing'];
return this.authenticate({ origin: headers.origin, secret });
issueChallenge(clientNonce) {
if (!this._secret) throw new BridgeAuthError('PAIRING_UNAVAILABLE', 'Bridge pairing is unavailable.', 503);
if (typeof clientNonce !== 'string' || !NONCE_PATTERN.test(clientNonce)) {
throw new BridgeAuthError('INVALID_NONCE', 'Client nonce is invalid.');
}
const now = this._dependencies.now();
this._purgeExpired(now);
if (this._challenges.size >= this._maxChallenges) {
throw new BridgeAuthError('CHALLENGE_CAPACITY', 'Too many bridge challenges are outstanding.', 429);
}
let serverNonce;
do {
serverNonce = this._dependencies.randomBytes(32).toString('base64url');
} while (this._challenges.has(serverNonce));
const expiresAt = now + this._challengeTtlMs;
this._challenges.set(serverNonce, { clientNonce, expiresAt });
return {
serverNonce,
serverProof: computeServerProof(this._secret, clientNonce, serverNonce, this._dependencies)
};
}
authenticateCookie(request = {}) {
const { clientNonce, serverNonce, deploymentUrl, cookieValue, proof } = request;
if (!this._secret || !NONCE_PATTERN.test(typeof clientNonce === 'string' ? clientNonce : '') ||
!NONCE_PATTERN.test(typeof serverNonce === 'string' ? serverNonce : '') ||
!PROOF_PATTERN.test(typeof proof === 'string' ? proof : '') ||
typeof deploymentUrl !== 'string' || deploymentUrl.length < 1 || deploymentUrl.length > 2048 ||
typeof cookieValue !== 'string' || cookieValue.length < 1 || cookieValue.length > 4096) {
return false;
}
const challenge = this._challenges.get(serverNonce);
if (!challenge) return false;
this._challenges.delete(serverNonce);
if (challenge.expiresAt <= this._dependencies.now() || challenge.clientNonce !== clientNonce) return false;
const expected = computeCookieProof(this._secret, request, this._dependencies);
return safeEqualText(proof, expected, this._dependencies);
}
}
@@ -142,22 +228,14 @@ function readJsonBody(stream, options = {}) {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BODY_BYTES;
const deadlineMs = options.deadlineMs ?? DEFAULT_BODY_DEADLINE_MS;
const deps = dependencies(options);
if (!stream || typeof stream.on !== 'function') {
return Promise.reject(new BridgeAuthError('INVALID_BODY_STREAM', 'A readable request body is required.'));
}
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {
return Promise.reject(new BridgeAuthError('INVALID_BODY_LIMIT', 'Body limit must be a positive integer.'));
}
if (!Number.isSafeInteger(deadlineMs) || deadlineMs < 1) {
return Promise.reject(new BridgeAuthError('INVALID_BODY_DEADLINE', 'Body deadline must be a positive integer.'));
}
if (!stream || typeof stream.on !== 'function') return Promise.reject(new BridgeAuthError('INVALID_BODY_STREAM', 'A readable request body is required.'));
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) return Promise.reject(new BridgeAuthError('INVALID_BODY_LIMIT', 'Body limit must be a positive integer.'));
if (!Number.isSafeInteger(deadlineMs) || deadlineMs < 1) return Promise.reject(new BridgeAuthError('INVALID_BODY_DEADLINE', 'Body deadline must be a positive integer.'));
return new Promise((resolve, reject) => {
const chunks = [];
let total = 0;
let settled = false;
const cleanup = () => {
deps.clearTimeout(timer);
stream.removeListener('data', onData);
@@ -174,10 +252,7 @@ function readJsonBody(stream, options = {}) {
const onData = (chunk) => {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
total += buffer.length;
if (total > maxBytes) {
fail(new BridgeAuthError('BODY_TOO_LARGE', 'Request body exceeds the configured limit.', 413));
return;
}
if (total > maxBytes) return fail(new BridgeAuthError('BODY_TOO_LARGE', 'Request body exceeds the configured limit.', 413));
chunks.push(buffer);
};
const onError = () => fail(new BridgeAuthError('BODY_READ_ERROR', 'Could not read the request body.'));
@@ -186,23 +261,15 @@ function readJsonBody(stream, options = {}) {
settled = true;
cleanup();
let parsed;
try {
parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
} catch {
reject(new BridgeAuthError('MALFORMED_JSON', 'Request body must be valid JSON.'));
return;
}
try { parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
catch { reject(new BridgeAuthError('MALFORMED_JSON', 'Request body must be valid JSON.')); return; }
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
reject(new BridgeAuthError('INVALID_JSON_BODY', 'Request body must be a JSON object.'));
return;
}
resolve(parsed);
};
const timer = deps.setTimeout(
() => fail(new BridgeAuthError('BODY_DEADLINE_EXCEEDED', 'Request body deadline exceeded.', 408)),
deadlineMs
);
const timer = deps.setTimeout(() => fail(new BridgeAuthError('BODY_DEADLINE_EXCEEDED', 'Request body deadline exceeded.', 408)), deadlineMs);
stream.on('data', onData);
stream.on('end', onEnd);
stream.on('error', onError);
@@ -210,25 +277,15 @@ function readJsonBody(stream, options = {}) {
}
function createRequestLimiter({ maxConcurrent = 4 } = {}) {
if (!Number.isSafeInteger(maxConcurrent) || maxConcurrent < 1) {
throw new BridgeAuthError('INVALID_CONCURRENCY_LIMIT', 'Concurrency limit must be a positive integer.');
}
if (!Number.isSafeInteger(maxConcurrent) || maxConcurrent < 1) throw new BridgeAuthError('INVALID_CONCURRENCY_LIMIT', 'Concurrency limit must be a positive integer.');
let active = 0;
return {
get active() { return active; },
async run(work) {
if (typeof work !== 'function') {
throw new BridgeAuthError('INVALID_REQUEST_WORK', 'Request work must be a function.');
}
if (active >= maxConcurrent) {
throw new BridgeAuthError('TOO_MANY_REQUESTS', 'Too many bridge requests are active.', 429);
}
if (typeof work !== 'function') throw new BridgeAuthError('INVALID_REQUEST_WORK', 'Request work must be a function.');
if (active >= maxConcurrent) throw new BridgeAuthError('TOO_MANY_REQUESTS', 'Too many bridge requests are active.', 429);
active += 1;
try {
return await work();
} finally {
active -= 1;
}
try { return await work(); } finally { active -= 1; }
}
};
}
@@ -238,13 +295,21 @@ module.exports = {
APT_EXTENSION_ORIGIN,
BridgeAuth,
BridgeAuthError,
COOKIE_PROOF_DOMAIN,
DEFAULT_BODY_DEADLINE_MS,
DEFAULT_CHALLENGE_TTL_MS,
DEFAULT_MAX_BODY_BYTES,
DEFAULT_MAX_CHALLENGES,
EXTENSION_ORIGIN_PATTERN,
NONCE_PATTERN,
SECRET_PATTERN,
SERVER_PROOF_DOMAIN,
canonicalCookieProof,
canonicalServerProof,
computeCookieProof,
computeServerProof,
createRequestLimiter,
generatePairingSecret,
hashPairingSecret,
readJsonBody,
verifyPairingSecret
isValidEnvelope,
readJsonBody
};
+67 -18
View File
@@ -26,13 +26,13 @@ function safeErrorMessage(error, fallback) {
: fallback;
}
function loadPairingEnvelope(envelopePath) {
function loadPairingEnvelope(envelopePath, { protect, unprotect } = {}) {
if (!fs.existsSync(envelopePath)) return null;
const bytes = fs.readFileSync(envelopePath);
if (bytes.length === 0 || bytes.length > 4096) throw new Error('Invalid pairing envelope file');
const parsed = JSON.parse(bytes.toString('utf8'));
// BridgeAuth performs the authoritative envelope schema validation.
return new BridgeAuth({ envelope: parsed }).envelope;
return new BridgeAuth({ envelope: parsed, protect, unprotect }).envelope;
}
function atomicWritePairingEnvelope(envelopePath, envelope) {
@@ -51,30 +51,38 @@ function atomicWritePairingEnvelope(envelopePath, envelope) {
}
class PairingController {
constructor({ envelopePath, bridgeAuth } = {}) {
constructor({ envelopePath, bridgeAuth, protect, unprotect } = {}) {
if (typeof envelopePath !== 'string' || envelopePath.length === 0) {
throw new TypeError('PairingController requires an envelope path');
}
this.envelopePath = envelopePath;
this.unavailable = false;
if (bridgeAuth) {
this.bridgeAuth = bridgeAuth;
} else if (typeof protect !== 'function' || typeof unprotect !== 'function') {
this.bridgeAuth = null;
this.unavailable = true;
} else {
let envelope = null;
try {
envelope = loadPairingEnvelope(envelopePath);
envelope = loadPairingEnvelope(envelopePath, { protect, unprotect });
} catch {
try { fs.unlinkSync(envelopePath); } catch {}
}
this.bridgeAuth = new BridgeAuth({ envelope });
this.bridgeAuth = new BridgeAuth({ envelope, protect, unprotect });
}
}
initialize() {
if (this.unavailable) return { paired: false, unavailable: true };
if (this.bridgeAuth.envelope) return { paired: true };
return this.rotate();
}
rotate() {
if (this.unavailable || !this.bridgeAuth) {
throw new BridgeAuthError('SECURE_STORAGE_UNAVAILABLE', 'Secure pairing storage is unavailable.', 503);
}
const { secret, envelope } = this.bridgeAuth.rotate();
try {
atomicWritePairingEnvelope(this.envelopePath, envelope);
@@ -86,17 +94,18 @@ class PairingController {
}
revoke() {
this.bridgeAuth.revoke();
if (this.bridgeAuth) this.bridgeAuth.revoke();
try {
fs.unlinkSync(this.envelopePath);
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
return { paired: false };
return this.unavailable ? { paired: false, unavailable: true } : { paired: false };
}
getStatus() {
return { paired: Boolean(this.bridgeAuth.envelope) };
if (this.unavailable) return { paired: false, unavailable: true };
return { paired: Boolean(this.bridgeAuth && this.bridgeAuth.envelope) };
}
}
@@ -118,7 +127,7 @@ function createBridgeHandler({
maxBodyBytes,
deadlineMs,
} = {}) {
if (!bridgeAuth || typeof bridgeAuth.authenticateRequest !== 'function') {
if (!bridgeAuth || typeof bridgeAuth.issueChallenge !== 'function' || typeof bridgeAuth.authenticateCookie !== 'function') {
throw new TypeError('Bridge handler requires bridge authentication');
}
if (!sessionStore || typeof sessionStore.establish !== 'function') {
@@ -135,7 +144,7 @@ function createBridgeHandler({
response.setHeader('Access-Control-Allow-Origin', APT_EXTENSION_ORIGIN);
response.setHeader('Vary', 'Origin');
response.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
response.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-APT-Pairing');
response.setHeader('Access-Control-Allow-Headers', 'Content-Type');
response.setHeader('Access-Control-Max-Age', '600');
if (request.method === 'OPTIONS') {
@@ -143,29 +152,38 @@ function createBridgeHandler({
response.end();
return;
}
if (request.method !== 'POST' || request.url !== '/cookie') {
if (request.method !== 'POST' || (request.url !== '/challenge' && request.url !== '/cookie')) {
writeJson(response, 404, { success: false, message: 'Not found' });
return;
}
if (!bridgeAuth.authenticateRequest(request)) {
writeJson(response, 403, { success: false, message: 'Forbidden' });
return;
}
try {
let payload;
await limiter.run(async () => {
const data = await readJsonBody(request, { maxBytes: maxBodyBytes, deadlineMs });
if (request.url === '/challenge') {
payload = { success: true, ...bridgeAuth.issueChallenge(data.clientNonce) };
return;
}
if (!bridgeAuth.authenticateCookie(data)) {
throw new BridgeAuthError('FORBIDDEN', 'Cookie proof was rejected.', 403);
}
const state = sessionStore.establish(data.deploymentUrl, data.cookieValue);
onConnectionStateChanged({ connected: state.connected, origin: state.origin });
payload = { success: true, message: 'Session received' };
});
writeJson(response, 200, { success: true, message: 'Session received' });
writeJson(response, 200, payload);
} catch (error) {
const statusCode = error instanceof BridgeAuthError
? error.statusCode
: error && error.code === 'INVALID_SESSION_COOKIE'
? 400
: 400;
writeJson(response, statusCode, { success: false, message: statusCode === 429 ? 'Too many requests' : 'Invalid request' });
const message = statusCode === 429 ? 'Too many requests'
: statusCode === 403 ? 'Forbidden'
: statusCode === 503 ? 'Pairing unavailable'
: 'Invalid request';
writeJson(response, statusCode, { success: false, message });
}
};
}
@@ -189,6 +207,22 @@ class AppRuntime {
this.proxyByDevice = new Map();
}
_reconcileProxies() {
const tracked = this.proxyManager && typeof this.proxyManager.listTrackedProxies === 'function'
? this.proxyManager.listTrackedProxies()
: [];
this.proxyByDevice = new Map();
for (const proxy of tracked) {
try {
const deviceId = validateDeviceId(proxy.deviceId);
if (Number.isSafeInteger(proxy.processId) && proxy.processId > 0) {
this.proxyByDevice.set(deviceId, proxy.processId);
}
} catch {}
}
return tracked.filter((proxy) => this.proxyByDevice.get(proxy.deviceId) === proxy.processId);
}
async getDevices() {
try {
const devices = await this.altaClient.getDevices();
@@ -222,6 +256,7 @@ class AppRuntime {
async launchProxy(deviceId) {
try {
const validatedId = validateDeviceId(deviceId);
this._reconcileProxies();
if (!this.allowedDeviceIds.has(validatedId)) {
return { success: false, message: 'Select a device from the current Alta device list.' };
}
@@ -242,6 +277,7 @@ class AppRuntime {
}
async stopProxy(key) {
this._reconcileProxies();
let deviceId = null;
let processId = null;
if (typeof key === 'string') {
@@ -261,12 +297,25 @@ class AppRuntime {
}
disconnect() {
const tracked = this._reconcileProxies();
for (const proxy of tracked) {
try { this.proxyManager.stopProxy(proxy.processId); } catch {}
}
const remaining = this._reconcileProxies();
if (remaining.length > 0) {
return {
success: false,
message: 'Could not stop every active proxy. The Alta session remains connected.',
...this.getConnectionState(),
};
}
this.sessionStore.clear();
this.allowedDeviceIds.clear();
return this.getConnectionState();
return { success: true, ...this.getConnectionState() };
}
getConnectionState() {
this._reconcileProxies();
const state = this.sessionStore.describe();
return {
connected: state.connected,
+26 -5
View File
@@ -140,27 +140,44 @@ function parseRelease(body) {
};
}
function defaultRequest({ url, timeoutMs, maxBodyBytes }) {
function defaultRequest({
url,
timeoutMs,
maxBodyBytes,
httpsGet = https.get,
setTimer = setTimeout,
clearTimer = clearTimeout,
}) {
if (url !== LATEST_RELEASE_URL) {
return Promise.reject(policyError('UNTRUSTED_REQUEST_URL', 'Update checks are restricted to GitPeji'));
}
return new Promise((resolve, reject) => {
let settled = false;
let responseStream = null;
let deadlineTimer = null;
const clearDeadline = () => {
if (deadlineTimer !== null) {
clearTimer(deadlineTimer);
deadlineTimer = null;
}
};
const finishReject = (error) => {
if (!settled) {
settled = true;
clearDeadline();
reject(error);
}
};
const request = https.get(url, {
const request = httpsGet(url, {
headers: {
accept: 'application/json',
'user-agent': 'Alta-Proxy-Tool-update-check',
},
agent: false,
}, (response) => {
responseStream = response;
const chunks = [];
let receivedBytes = 0;
const contentLength = Number(response.headers['content-length']);
@@ -183,6 +200,7 @@ function defaultRequest({ url, timeoutMs, maxBodyBytes }) {
response.on('end', () => {
if (settled) return;
settled = true;
clearDeadline();
resolve({
statusCode: response.statusCode,
headers: response.headers,
@@ -193,9 +211,12 @@ function defaultRequest({ url, timeoutMs, maxBodyBytes }) {
response.on('error', finishReject);
});
request.setTimeout(timeoutMs, () => {
request.destroy(policyError('REQUEST_TIMEOUT', 'Release check timed out'));
});
deadlineTimer = setTimer(() => {
const timeoutError = policyError('REQUEST_TIMEOUT', 'Release check timed out');
if (responseStream && typeof responseStream.destroy === 'function') responseStream.destroy();
request.destroy(timeoutError);
finishReject(timeoutError);
}, timeoutMs);
request.on('error', (error) => {
if (error instanceof UpdatePolicyError) {
finishReject(error);