import fs from 'fs'; import os from 'os'; import path from 'path'; import { parse } from 'ini'; type NpmConfig = Record; // Mirrors @npmcli/config's env-replace: ${NAME} expands to the variable, an // unset variable is left as-is, ${NAME?} expands to '' when unset, and a // backslash escapes the expression const envExpr = /(? { const val = process.env[name] ?? (modifier === '?' ? '' : `\${${name}}`); if (esc.length % 2) { return orig.slice((esc.length + 1) / 2); } return esc.slice(esc.length / 2) + val; }); } function expandValue(value: unknown): unknown { if (typeof value === 'string') { return expandEnv(value); } if (Array.isArray(value)) { return value.map(expandValue); } return value; } // Config values are strings unless the user's npmrc is malformed (a section // header, say); anything else is treated as not set function asString(value: unknown): string | undefined { return typeof value === 'string' ? value : undefined; } function expandPath(file: string): string { return file.startsWith('~/') ? path.join(os.homedir(), file.slice(2)) : file; } // Node's read errors such as EISDIR carry no path, so a warning built from the // message alone can't say which file to look at function nameFile(err: unknown, file: string): unknown { // Not `instanceof Error`: an error thrown by Node's fs can come from another // realm (under jest, for one) and fail that check const e = err as { message?: unknown }; if (typeof e?.message === 'string' && !e.message.includes(file)) { e.message = `${e.message} (${file})`; } return err; } function readNpmrc(file: string): NpmConfig { let text: string; try { text = fs.readFileSync(file, 'utf8'); } catch (err) { // A missing npmrc is normal; anything else (EACCES, EISDIR) would silently // drop the user's registry and credentials, so let the caller warn if ((err as NodeJS.ErrnoException).code === 'ENOENT') { return {}; } throw nameFile(err, file); } const config: NpmConfig = {}; for (const [key, value] of Object.entries(parse(text))) { config[expandEnv(key)] = expandValue(value); } return config; } // npm_config_ variables, normalized the way npm does: underscores become // dashes and the name is lowercased (nerf-darted keys are left alone) function readEnvConfig(): NpmConfig { const config: NpmConfig = {}; for (const [envKey, value] of Object.entries(process.env)) { if (!/^npm_config_/i.test(envKey) || !value) { continue; } let key = envKey.slice('npm_config_'.length); if (!key.startsWith('//')) { key = key.replace(/(?!^)_/g, '-').toLowerCase(); } config[key] = value; } return config; } // Where npm looks for its global config: /etc/npmrc, with the prefix // derived from the location of the node binary unless configured function getGlobalPrefix(): string { if (process.env.PREFIX) { return process.env.PREFIX; } return process.platform === 'win32' ? path.dirname(process.execPath) : path.dirname(path.dirname(process.execPath)); } /** * Reads npm's configuration the way `npm` would for a command run outside of * any project: environment, then the user config, then the global config. The * project-level .npmrc in the working directory is deliberately never read by * this code, so a stray file in whichever directory `alks` is run from can't * redirect the request or pick which credentials are sent with it. * * That holds when `alks` is run directly. Under `npx alks`, `npm exec` or an * npm script, npm itself exports its resolved non-default config, including a * registry set by the project .npmrc, as `npm_config_registry`, and that * arrives here as environment config. Credentials are unaffected: npm does not * export per-registry token keys, and a token is only sent to the registry * whose `//host/path` key matches the request. */ function readNpmConfig(): NpmConfig { const env = readEnvConfig(); const userFile = asString(env.userconfig) ?? path.join(process.env.HOME || os.homedir(), '.npmrc'); const user = readNpmrc(expandPath(userFile)); const prefix = asString(env.prefix) ?? asString(user.prefix) ?? getGlobalPrefix(); const globalFile = asString(env.globalconfig) ?? asString(user.globalconfig) ?? path.resolve(prefix, 'etc', 'npmrc'); const global = readNpmrc(expandPath(globalFile)); return { ...global, ...user, ...env }; } function readCaFile(file: string): string[] | undefined { let raw: string; const resolved = expandPath(file); try { raw = fs.readFileSync(resolved, 'utf8'); } catch (err) { // npm ignores a cafile that doesn't exist if ((err as NodeJS.ErrnoException).code === 'ENOENT') { return undefined; } throw nameFile(err, resolved); } const delim = '-----END CERTIFICATE-----'; const certs = raw .replace(/\r\n/g, '\n') .split(delim) .filter((section) => section.trim()) .map((section) => section.trimStart() + delim); return certs.length ? certs : undefined; } /** * Options for npm-registry-fetch drawn from the user's npm configuration: * registry, the credentials stored for it, and the TLS and proxy settings. * npm-registry-fetch reads no config files itself (and ignores `cafile`), so * this is what makes it behave like `npm`. When no registry is configured, * `registry` is left unset so npm-registry-fetch applies npm's own default. */ export function getNpmRegistryOptions(): Record { const config = readNpmConfig(); const options: Record = {}; const registry = asString(config.registry); if (registry) { options.registry = registry; } // Credentials are stored per registry under keys such as // //host/path/:_authToken; npm-registry-fetch picks the ones that match for (const [key, value] of Object.entries(config)) { if (key.startsWith('//')) { options[key] = value; } } const strictSsl = config['strict-ssl']; if (strictSsl !== undefined) { options.strictSSL = strictSsl !== false && strictSsl !== 'false'; } const ca = config.ca; if (ca) { options.ca = ca; } if (typeof config.cafile === 'string') { const certs = readCaFile(config.cafile); if (certs) { options.ca = certs; } } if (typeof config.proxy === 'string') { options.proxy = config.proxy; } if (typeof config['https-proxy'] === 'string') { options.httpsProxy = config['https-proxy']; } const noProxy = config.noproxy; if (noProxy) { options.noProxy = Array.isArray(noProxy) ? noProxy.join(',') : noProxy; } return options; }