diff --git a/.changeset/npmrc-trusted-publishing.md b/.changeset/npmrc-trusted-publishing.md new file mode 100644 index 00000000..f9987fe7 --- /dev/null +++ b/.changeset/npmrc-trusted-publishing.md @@ -0,0 +1,5 @@ +--- +"@changesets/action": patch +--- + +The `.npmrc` generation now intelligently handles both traditional NPM token authentication and trusted publishing scenarios by only appending the auth token when `NPM_TOKEN` is defined. This prevents 'undefined' from being written to the registry configuration when using OIDC tokens from GitHub Actions trusted publishing. diff --git a/src/index.ts b/src/index.ts index 1b0f63ab..2f05db4e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -67,32 +67,41 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined; "No changesets found. Attempting to publish any unpublished packages to npm" ); - let userNpmrcPath = `${process.env.HOME}/.npmrc`; - if (await fileExists(userNpmrcPath)) { - core.info("Found existing user .npmrc file"); - const userNpmrcContent = await fs.readFile(userNpmrcPath, "utf8"); - const authLine = userNpmrcContent.split("\n").find((line) => { - // check based on https://github.com/npm/cli/blob/8f8f71e4dd5ee66b3b17888faad5a7bf6c657eed/test/lib/adduser.js#L103-L105 - return /^\s*\/\/registry\.npmjs\.org\/:[_-]authToken=/i.test(line); - }); - if (authLine) { - core.info( - "Found existing auth token for the npm registry in the user .npmrc file" - ); + if (process.env.NPM_TOKEN) { + const userNpmrcPath = `${process.env.HOME}/.npmrc`; + + if (await fileExists(userNpmrcPath)) { + core.info("Found existing user .npmrc file"); + const userNpmrcContent = await fs.readFile(userNpmrcPath, "utf8"); + const authLine = userNpmrcContent.split("\n").find((line) => { + // check based on https://github.com/npm/cli/blob/8f8f71e4dd5ee66b3b17888faad5a7bf6c657eed/test/lib/adduser.js#L103-L105 + return /^\s*\/\/registry\.npmjs\.org\/:[_-]authToken=/i.test(line); + }); + if (authLine) { + core.info( + "Found existing auth token for the npm registry in the user .npmrc file" + ); + } else { + core.info( + "Didn't find existing auth token for the npm registry in the user .npmrc file, creating one" + ); + await fs.appendFile( + userNpmrcPath, + `\n//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}\n` + ); + } } else { core.info( - "Didn't find existing auth token for the npm registry in the user .npmrc file, creating one" + "No user .npmrc file found, creating one with NPM_TOKEN used as auth token" ); - await fs.appendFile( + await fs.writeFile( userNpmrcPath, - `\n//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}\n` + `//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}\n` ); } } else { - core.info("No user .npmrc file found, creating one"); - await fs.writeFile( - userNpmrcPath, - `//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}\n` + core.info( + "No NPM_TOKEN found - assuming trusted publishing or npm is already authenticated" ); }