import { white, blue, green, yellow } from 'cli-color'; import fetch from 'npm-registry-fetch'; import { gt } from 'semver'; import { version, name } from '../../package.json'; import path from 'path'; import fs from 'fs'; import { URL } from 'url'; import { log } from './log'; import { getNpmRegistryOptions } from './getNpmRegistryOptions'; import { showBorderedMessage } from './showBorderedMessage'; import { getLastVersion, setLastVersion } from './state/lastVersion'; function getChangeLog() { const file = path.join(__dirname, '../../', 'changelog.txt'); return fs.readFileSync(file, 'utf8'); } // TLS verification failures typically caused by a TLS-inspecting proxy (such as // Zscaler) whose root certificate Node doesn't trust const certErrorCodes = new Set([ 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY', 'SELF_SIGNED_CERT_IN_CHAIN', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', ]); const certErrorHint = '\nBehind a TLS-inspecting proxy such as Zscaler? Set NODE_EXTRA_CA_CERTS to the proxy root certificate (see the release notes).'; // Longest the update check may add to a command const updateCheckTimeoutMs = 3000; // Errors raised when a request outlives the timeout: from the fetch library // itself or from the agent underneath it const timeoutErrorCodes = new Set([ 'ETIMEDOUT', 'ECONNECTIONTIMEOUT', 'EIDLETIMEOUT', 'ERESPONSETIMEOUT', 'ETRANSFERTIMEOUT', ]); function isTimeoutError(err: Error): boolean { const { code, type } = err as NodeJS.ErrnoException & { type?: string }; return ( type === 'request-timeout' || (code !== undefined && timeoutErrorCodes.has(code)) ); } // The registry answered 401 or 403 to the credentials from the user's npm // configuration. Not a certificate problem, so it gets no certificate hint. class RegistryLoginRejectedError extends Error {} function describeRegistry(registry: string): string { try { const url = new URL(registry); // A scheme-less user:pass@host/ parses with "user:" as the protocol and the // credential left in the path, so only http(s) URLs are safe to strip by parsing if (url.protocol !== 'http:' && url.protocol !== 'https:') { throw new Error('not an http(s) URL'); } url.username = ''; url.password = ''; return url.href; } catch { // Not parseable as a URL (a protocol-relative //user:pass@host/ is one, and // a scheme-less user:pass@host/ parses as an opaque URL), so strip any // credential from the text instead // The input is a bare registry string, not free text, so everything up to // the last @ is dropped; that also covers a raw / inside the password return registry.replace(/^(\/\/)?.*@/, '$1'); } } // Strips user:pass@ from any URL in a message so a credential in the user's npm // configuration never reaches the terminal or alks.log. The userinfo runs to the // last @ before the path, so a password holding a raw @ is removed whole. function redactUserinfo(message: string): string { return message.replace(/(\/\/)[^/\s]*@/g, '$1'); } export async function checkForUpdate() { // A failed update check must never fail the command that called it, so the // error is captured as a value. Capturing it also keeps a failure that lands // after the timeout from surfacing once the race has already been decided. let timer: NodeJS.Timeout | undefined; const result = await Promise.race([ checkForUpdateInternal().then( () => 'done' as const, (err: unknown) => (err instanceof Error ? err : new Error(String(err))) ), new Promise<'timeout'>((resolve) => { timer = setTimeout(resolve.bind(null, 'timeout'), updateCheckTimeoutMs); }), ]); // A pending timer would keep the process alive for up to the timeout after // a fast check has finished if (timer) { clearTimeout(timer); } if ( result === 'timeout' || (result instanceof Error && isTimeoutError(result)) ) { log('check for update timed out. Skipping...'); } else if (result instanceof Error) { // Persist the reason to alks.log for support; verbose: false keeps -v from // printing it a second time next to the warning log('check for update failed: ' + result.message, { verbose: false }); const code = (result as NodeJS.ErrnoException).code; const hint = code && certErrorCodes.has(code) ? certErrorHint : ''; console.error( yellow(`WARNING: update check failed: ${result.message}${hint}`) ); } } async function checkForUpdateInternal() { log('checking for update...'); const currentVersion = version; const app = name; // Ask the registry the user's own npm configuration points at, as npm would. // With none configured npm-registry-fetch falls back to npm's default. const options = getNpmRegistryOptions(); const registry = fetch.pickRegistry(app, options); log('checking for update via ' + describeRegistry(registry)); let data; try { // npm-registry-fetch throws on a non-2xx response data = await fetch.json(`/${app}/latest`, { ...options, timeout: updateCheckTimeoutMs, retry: { retries: 0 }, }); } catch (err) { const status = (err as { statusCode?: number }).statusCode; if (status === 401 || status === 403) { throw new RegistryLoginRejectedError( `${describeRegistry( registry )} rejected the login from your npm configuration (HTTP ${status}). Check the credentials for it in your .npmrc.` ); } // Any other failure surfaces the fetch library's message, which embeds the // request URL (and proxy URL) verbatim, userinfo included if (err instanceof Error) { err.message = redactUserinfo(err.message); } throw err; } const latestVersion = data.version as string; const needsUpdate = gt(latestVersion, currentVersion); log('needs update? ' + (needsUpdate ? 'yes' : 'no')); if (needsUpdate) { const msg = [ white('Update available '), blue(currentVersion), white(' → '), green(latestVersion + '\n'), white('Run: '), green('npm i -g ' + app), white(' to update'), ].join(''); showBorderedMessage(40, msg); } else { const lastVersion = await getLastVersion(); // check if they just updated if (gt(currentVersion, lastVersion)) { log('user updated, updating db with version'); // give them release notes showBorderedMessage(110, white(getChangeLog())); // update the state to reflect that the last version run is the current version log('db'); await setLastVersion(currentVersion); } } }