|
| 1 | +const { log } = require('proc-log') |
| 2 | +const npmFetch = require('npm-registry-fetch') |
| 3 | +const ciInfo = require('ci-info') |
| 4 | +const fetch = require('make-fetch-happen') |
| 5 | +const npa = require('npm-package-arg') |
| 6 | + |
| 7 | +/** |
| 8 | + * Handles OpenID Connect (OIDC) token retrieval and exchange for CI environments. |
| 9 | + * |
| 10 | + * This function is designed to work in Continuous Integration (CI) environments such as GitHub Actions |
| 11 | + * and GitLab. It retrieves an OIDC token from the CI environment, exchanges it for an npm token, and |
| 12 | + * sets the token in the provided configuration for authentication with the npm registry. |
| 13 | + * |
| 14 | + * This function is intended to never throw, as it mutates the state of the `opts` and `config` objects on success. |
| 15 | + * OIDC is always an optional feature, and the function should not throw if OIDC is not configured by the registry. |
| 16 | + * |
| 17 | + * @see https://github.com/watson/ci-info for CI environment detection. |
| 18 | + * @see https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect for GitHub Actions OIDC. |
| 19 | + */ |
| 20 | +async function oidc ({ packageName, registry, opts, config }) { |
| 21 | + /* |
| 22 | + * This code should never run when people try to publish locally on their machines. |
| 23 | + * It is designed to execute only in Continuous Integration (CI) environments. |
| 24 | + */ |
| 25 | + |
| 26 | + try { |
| 27 | + if (!( |
| 28 | + /** @see https://github.com/watson/ci-info/blob/v4.2.0/vendors.json#L152 */ |
| 29 | + ciInfo.GITHUB_ACTIONS || |
| 30 | + /** @see https://github.com/watson/ci-info/blob/v4.2.0/vendors.json#L161C13-L161C22 */ |
| 31 | + ciInfo.GITLAB |
| 32 | + )) { |
| 33 | + return undefined |
| 34 | + } |
| 35 | + |
| 36 | + log.silly('oidc', 'Determining if npm should use OIDC publishing') |
| 37 | + |
| 38 | + /** |
| 39 | + * Check if the environment variable `NPM_ID_TOKEN` is set. |
| 40 | + * In GitLab CI, the ID token is provided via an environment variable, |
| 41 | + * with `NPM_ID_TOKEN` serving as a predefined default. For consistency, |
| 42 | + * all supported CI environments are expected to support this variable. |
| 43 | + * In contrast, GitHub Actions uses a request-based approach to retrieve the ID token. |
| 44 | + * The presence of this token within GitHub Actions will override the request-based approach. |
| 45 | + * This variable follows the prefix/suffix convention from sigstore (e.g., `SIGSTORE_ID_TOKEN`). |
| 46 | + * @see https://docs.sigstore.dev/cosign/signing/overview/ |
| 47 | + */ |
| 48 | + let idToken = process.env.NPM_ID_TOKEN |
| 49 | + |
| 50 | + if (idToken) { |
| 51 | + log.silly('oidc', 'NPM_ID_TOKEN present') |
| 52 | + } else { |
| 53 | + log.silly('oidc', 'NPM_ID_TOKEN not present, checking for GITHUB_ACTIONS') |
| 54 | + if (ciInfo.GITHUB_ACTIONS) { |
| 55 | + /** |
| 56 | + * GitHub Actions provides these environment variables: |
| 57 | + * - `ACTIONS_ID_TOKEN_REQUEST_URL`: The URL to request the ID token. |
| 58 | + * - `ACTIONS_ID_TOKEN_REQUEST_TOKEN`: The token to authenticate the request. |
| 59 | + * Only when a workflow has the following permissions: |
| 60 | + * ``` |
| 61 | + * permissions: |
| 62 | + * id-token: write |
| 63 | + * ``` |
| 64 | + * @see https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-cloud-providers#adding-permissions-settings |
| 65 | + */ |
| 66 | + if ( |
| 67 | + process.env.ACTIONS_ID_TOKEN_REQUEST_URL && |
| 68 | + process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN |
| 69 | + ) { |
| 70 | + log.silly('oidc', '"GITHUB_ACTIONS" detected with "ACTIONS_ID_" envs, fetching id_token') |
| 71 | + |
| 72 | + /** |
| 73 | + * The specification for an audience is `npm:registry.npmjs.org`, |
| 74 | + * where "registry.npmjs.org" can be any supported registry. |
| 75 | + */ |
| 76 | + const audience = `npm:${new URL(registry).hostname}` |
| 77 | + log.silly('oidc', `Using audience: ${audience}`) |
| 78 | + const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL) |
| 79 | + url.searchParams.append('audience', audience) |
| 80 | + const startTime = Date.now() |
| 81 | + const response = await fetch(url.href, { |
| 82 | + retry: opts.retry, |
| 83 | + headers: { |
| 84 | + Accept: 'application/json', |
| 85 | + Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}`, |
| 86 | + }, |
| 87 | + }) |
| 88 | + |
| 89 | + const elapsedTime = Date.now() - startTime |
| 90 | + |
| 91 | + log.http( |
| 92 | + 'fetch', |
| 93 | + `GET ${url.href} ${response.status} ${elapsedTime}ms` |
| 94 | + ) |
| 95 | + |
| 96 | + const json = await response.json() |
| 97 | + |
| 98 | + if (!response.ok) { |
| 99 | + throw new Error(`Failed to fetch id_token from GitHub: received an invalid response`) |
| 100 | + } |
| 101 | + |
| 102 | + if (!json.value) { |
| 103 | + throw new Error(`Failed to fetch id_token from GitHub: missing value`) |
| 104 | + } |
| 105 | + |
| 106 | + log.silly('oidc', 'GITHUB_ACTIONS valid fetch response for id_token') |
| 107 | + idToken = json.value |
| 108 | + } else { |
| 109 | + throw new Error('GITHUB_ACTIONS detected. If you intend to publish using OIDC, please set workflow permissions for `id-token: write`') |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + if (!idToken) { |
| 115 | + log.silly('oidc', 'Exiting OIDC, no id_token available') |
| 116 | + return undefined |
| 117 | + } |
| 118 | + |
| 119 | + log.silly('oidc', `id_token has a length of ${idToken.length} characters`) |
| 120 | + |
| 121 | + const parsedRegistry = new URL(registry) |
| 122 | + const regKey = `//${parsedRegistry.host}${parsedRegistry.pathname}` |
| 123 | + const authTokenKey = `${regKey}:_authToken` |
| 124 | + |
| 125 | + const exitingToken = config.get(authTokenKey) |
| 126 | + if (exitingToken) { |
| 127 | + log.silly('oidc', 'Existing token found') |
| 128 | + } else { |
| 129 | + log.silly('oidc', 'No existing token found') |
| 130 | + } |
| 131 | + |
| 132 | + const escapedPackageName = npa(packageName).escapedName |
| 133 | + const response = await npmFetch.json(new URL(`/-/npm/v1/oidc/token/exchange/package/${escapedPackageName}`, registry), { |
| 134 | + ...{ |
| 135 | + ...opts, |
| 136 | + [authTokenKey]: idToken, // Use the idToken as the auth token for the request |
| 137 | + }, |
| 138 | + method: 'POST', |
| 139 | + headers: { |
| 140 | + ...opts.headers, |
| 141 | + 'Content-Type': 'application/json', |
| 142 | + // this will not work because the existing auth token will replace it. |
| 143 | + // authorization: `Bearer ${idToken}`, |
| 144 | + }, |
| 145 | + }) |
| 146 | + |
| 147 | + if (!response?.token) { |
| 148 | + throw new Error('OIDC token exchange failure: missing token in response body') |
| 149 | + } |
| 150 | + /* |
| 151 | + * The "opts" object is a clone of npm.flatOptions and is passed through the `publish` command, |
| 152 | + * eventually reaching `otplease`. To ensure the token is accessible during the publishing process, |
| 153 | + * it must be directly attached to the `opts` object. |
| 154 | + * Additionally, the token is required by the "live" configuration or getters within `config`. |
| 155 | + */ |
| 156 | + opts[authTokenKey] = response.token |
| 157 | + config.set(authTokenKey, response.token, 'user') |
| 158 | + log.silly('oidc', `OIDC token successfully retrieved`) |
| 159 | + } catch (error) { |
| 160 | + log.verbose('oidc', error.message) |
| 161 | + if (error?.body?.message) { |
| 162 | + log.verbose('oidc', `Registry body response error message "${error.body.message}"`) |
| 163 | + } |
| 164 | + } |
| 165 | + return undefined |
| 166 | +} |
| 167 | + |
| 168 | +module.exports = { |
| 169 | + oidc, |
| 170 | +} |
0 commit comments