Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

npm-profile

npm2.8mISC11.0.1TypeScript support: definitely-typed

Library for updating an npmjs.com profile

readme

npm-profile

Provides functions for fetching and updating an npmjs.com profile.

const profile = require('npm-profile')
const result = await profile.get({token})
//...

The API that this implements is documented here:

Table of Contents

API

> profile.adduser(opener, prompter, [opts]) → Promise

Tries to create a user new web based login, if that fails it falls back to using the legacy CouchDB APIs.

  • opener Function (url) → Promise, returns a promise that resolves after a browser has been opened for the user at url.
  • prompter Function (creds) → Promise, returns a promise that resolves to an object with username, email and password properties.

Promise Value

An object with the following properties:

  • token String, to be used to authenticate further API calls
  • username String, the username the user authenticated as

Promise Rejection

An error object indicating what went wrong.

The headers property will contain the HTTP headers of the response.

If the action was denied because it came from an IP address that this action on this account isn't allowed from then the code will be set to EAUTHIP.

Otherwise the code will be 'E' followed by the HTTP response code, for example a Forbidden response would be E403.

> profile.login(opener, prompter, [opts]) → Promise

Tries to login using new web based login, if that fails it falls back to using the legacy CouchDB APIs.

  • opener Function (url) → Promise, returns a promise that resolves after a browser has been opened for the user at url.
  • prompter Function (creds) → Promise, returns a promise that resolves to an object with username, and password properties.

Promise Value

An object with the following properties:

  • token String, to be used to authenticate further API calls
  • username String, the username the user authenticated as

Promise Rejection

An error object indicating what went wrong.

The headers property will contain the HTTP headers of the response.

If the action was denied because an OTP is required then code will be set to EOTP. This error code can only come from a legacy CouchDB login and so this should be retried with loginCouch.

If the action was denied because it came from an IP address that this action on this account isn't allowed from then the code will be set to EAUTHIP.

Otherwise the code will be 'E' followed by the HTTP response code, for example a Forbidden response would be E403.

> profile.adduserWeb(opener, [opts]) → Promise

Tries to create a user new web based login, if that fails it falls back to using the legacy CouchDB APIs.

  • opener Function (url) → Promise, returns a promise that resolves after a browser has been opened for the user at url.
  • opts Object

Promise Value

An object with the following properties:

  • token String, to be used to authenticate further API calls
  • username String, the username the user authenticated as

Promise Rejection

An error object indicating what went wrong.

The headers property will contain the HTTP headers of the response.

If the registry does not support web-login then an error will be thrown with its code property set to ENYI . You should retry with adduserCouch. If you use adduser then this fallback will be done automatically.

If the action was denied because it came from an IP address that this action on this account isn't allowed from then the code will be set to EAUTHIP.

Otherwise the code will be 'E' followed by the HTTP response code, for example a Forbidden response would be E403.

> profile.loginWeb(opener, [opts]) → Promise

Tries to login using new web based login, if that fails it falls back to using the legacy CouchDB APIs.

  • opener Function (url) → Promise, returns a promise that resolves after a browser has been opened for the user at url.
  • opts Object (optional)

Promise Value

An object with the following properties:

  • token String, to be used to authenticate further API calls
  • username String, the username the user authenticated as

Promise Rejection

An error object indicating what went wrong.

The headers property will contain the HTTP headers of the response.

If the registry does not support web-login then an error will be thrown with its code property set to ENYI . You should retry with loginCouch. If you use login then this fallback will be done automatically.

If the action was denied because it came from an IP address that this action on this account isn't allowed from then the code will be set to EAUTHIP.

Otherwise the code will be 'E' followed by the HTTP response code, for example a Forbidden response would be E403.

> profile.adduserCouch(username, email, password, [opts]) → Promise

const {token} = await profile.adduser(username, email, password, {registry})
// `token` can be passed in through `opts` for authentication.

Creates a new user on the server along with a fresh bearer token for future authentication as this user. This is what you see as an authToken in an .npmrc.

If the user already exists then the npm registry will return an error, but this is registry specific and not guaranteed.

  • username String
  • email String
  • password String
  • opts Object (optional)

Promise Value

An object with the following properties:

  • token String, to be used to authenticate further API calls
  • username String, the username the user authenticated as

Promise Rejection

An error object indicating what went wrong.

The headers property will contain the HTTP headers of the response.

If the action was denied because an OTP is required then code will be set to EOTP.

If the action was denied because it came from an IP address that this action on this account isn't allowed from then the code will be set to EAUTHIP.

Otherwise the code will be 'E' followed by the HTTP response code, for example a Forbidden response would be E403.

> profile.loginCouch(username, password, [opts]) → Promise

let token
try {
  {token} = await profile.login(username, password, {registry})
} catch (err) {
  if (err.code === 'otp') {
    const otp = await getOTPFromSomewhere()
    {token} = await profile.login(username, password, {otp})
  }
}
// `token` can now be passed in through `opts` for authentication.

Logs you into an existing user. Does not create the user if they do not already exist. Logging in means generating a new bearer token for use in future authentication. This is what you use as an authToken in an .npmrc.

  • username String
  • email String
  • password String
  • opts Object (optional)

Promise Value

An object with the following properties:

  • token String, to be used to authenticate further API calls
  • username String, the username the user authenticated as

Promise Rejection

An error object indicating what went wrong.

If the object has a code property set to EOTP then that indicates that this account must use two-factor authentication to login. Try again with a one-time password.

If the object has a code property set to EAUTHIP then that indicates that this account is only allowed to login from certain networks and this ip is not on one of those networks.

If the error was neither of these then the error object will have a code property set to the HTTP response code and a headers property with the HTTP headers in the response.

> profile.get([opts]) → Promise

const {name, email} = await profile.get({token})
console.log(`${token} belongs to https://npm.im/~${name}, (mailto:${email})`)

Fetch profile information for the authenticated user.

Promise Value

An object that looks like this:

// "*" indicates a field that may not always appear
{
  tfa: null |
       false |
       {"mode": "auth-only", pending: Boolean} |
       ["recovery", "codes"] |
       "otpauth://...",
  name: String,
  email: String,
  email_verified: Boolean,
  created: Date,
  updated: Date,
  cidr_whitelist: null | ["192.168.1.1/32", ...],
  fullname: String, // *
  homepage: String, // *
  freenode: String, // *
  twitter: String,  // *
  github: String    // *
}

Promise Rejection

An error object indicating what went wrong.

The headers property will contain the HTTP headers of the response.

If the action was denied because an OTP is required then code will be set to EOTP.

If the action was denied because it came from an IP address that this action on this account isn't allowed from then the code will be set to EAUTHIP.

Otherwise the code will be the HTTP response code.

> profile.set(profileData, [opts]) → Promise

await profile.set({github: 'great-github-account-name'}, {token})

Update profile information for the authenticated user.

  • profileData An object, like that returned from profile.get, but see below for caveats relating to password, tfa and cidr_whitelist.
  • opts Object (optional)

SETTING password

This is used to change your password and is not visible (for obvious reasons) through the get() API. The value should be an object with old and new properties, where the former has the user's current password and the latter has the desired new password. For example

await profile.set({
  password: {
    old: 'abc123',
    new: 'my new (more secure) password'
  }
}, {token})

SETTING cidr_whitelist

The value for this is an Array. Only valid CIDR ranges are allowed in it. Be very careful as it's possible to lock yourself out of your account with this. This is not currently exposed in npm itself.

await profile.set({
  cidr_whitelist: [ '8.8.8.8/32' ]
}, {token})
// ↑ only one of google's dns servers can now access this account.

SETTING tfa

Enabling two-factor authentication is a multi-step process.

  1. Call profile.get and check the status of tfa. If pending is true then you'll need to disable it with profile.set({tfa: {password, mode: 'disable'}, …).
  2. profile.set({tfa: {password, mode}}, {registry, token})
    • Note that the user's password is required here in the tfa object, regardless of how you're authenticating.
    • mode is either auth-only which requires an otp when calling login or createToken, or mode is auth-and-writes and an otp will be required on login, publishing or when granting others access to your modules.
    • Be aware that this set call may require otp as part of the auth object. If otp is needed it will be indicated through a rejection in the usual way.
  3. If tfa was already enabled then you're just switch modes and a successful response means that you're done. If the tfa property is empty and tfa wasn't enabled then it means they were in a pending state.
  4. The response will have a tfa property set to an otpauth URL, as used by Google Authenticator. You will need to show this to the user for them to add to their authenticator application. This is typically done as a QRCODE, but you can also show the value of the secret key in the otpauth query string and they can type or copy paste that in.
  5. To complete setting up two factor auth you need to make a second call to profile.set with tfa set to an array of TWO codes from the user's authenticator, eg: profile.set(tfa: [otp1, otp2]}, {registry, token})
  6. On success you'll get a result object with a tfa property that has an array of one-time-use recovery codes. These are used to authenticate later if the second factor is lost and generally should be printed and put somewhere safe.

Disabling two-factor authentication is more straightforward, set the tfa attribute to an object with a password property and a mode of disable.

await profile.set({tfa: {password, mode: 'disable'}}, {token})

Promise Value

An object reflecting the changes you made, see description for profile.get.

Promise Rejection

An error object indicating what went wrong.

The headers property will contain the HTTP headers of the response.

If the action was denied because an OTP is required then code will be set to EOTP.

If the action was denied because it came from an IP address that this action on this account isn't allowed from then the code will be set to EAUTHIP.

Otherwise the code will be the HTTP response code.

> profile.listTokens([opts]) → Promise

const tokens = await profile.listTokens({registry, token})
console.log(`Number of tokens in your accounts: ${tokens.length}`)

Fetch a list of all of the authentication tokens the authenticated user has.

  • opts Object (optional)

Promise Value

An array of token objects. Each token object has the following properties:

  • key — A sha512 that can be used to remove this token.
  • token — The first six characters of the token UUID. This should be used by the user to identify which token this is.
  • created — The date and time the token was created
  • readonly — If true, this token can only be used to download private modules. Critically, it CAN NOT be used to publish.
  • cidr_whitelist — An array of CIDR ranges that this token is allowed to be used from.

Promise Rejection

An error object indicating what went wrong.

The headers property will contain the HTTP headers of the response.

If the action was denied because an OTP is required then code will be set to EOTP.

If the action was denied because it came from an IP address that this action on this account isn't allowed from then the code will be set to EAUTHIP.

Otherwise the code will be the HTTP response code.

> profile.removeToken(token|key, opts) → Promise

await profile.removeToken(key, {token})
// token is gone!

Remove a specific authentication token.

Promise Value

No value.

Promise Rejection

An error object indicating what went wrong.

The headers property will contain the HTTP headers of the response.

If the action was denied because an OTP is required then code will be set to EOTP.

If the action was denied because it came from an IP address that this action on this account isn't allowed from then the code will be set to EAUTHIP.

Otherwise the code will be the HTTP response code.

> profile.createToken(password, readonly, cidr_whitelist, [opts]) → Promise

const newToken = await profile.createToken(
  password, readonly, cidr_whitelist, {token, otp}
)
// do something with the newToken

Create a new authentication token, possibly with restrictions.

  • password String
  • readonly Boolean
  • cidr_whitelist Array
  • opts Object Optional

Promise Value

The promise will resolve with an object very much like the one's returned by profile.listTokens. The only difference is that token is not truncated.

{
  token: String,
  key: String,    // sha512 hash of the token UUID
  cidr_whitelist: [String],
  created: Date,
  readonly: Boolean
}

Promise Rejection

An error object indicating what went wrong.

The headers property will contain the HTTP headers of the response.

If the action was denied because an OTP is required then code will be set to EOTP.

If the action was denied because it came from an IP address that this action on this account isn't allowed from then the code will be set to EAUTHIP.

Otherwise the code will be the HTTP response code.

options objects

The various API functions accept an optional opts object as a final argument.

Options are passed to npm-registry-fetch options, so anything provided to this module will affect the behavior of that one as well.

Of particular note are opts.registry, and the auth-related options:

  • opts.creds Object, passed through to prompter, common values are:
    • username String, default value for username
    • email String, default value for email
  • opts.username and opts.password - used for Basic auth
  • opts.otp String, the two-factor-auth one-time-password (Will prompt for this if needed and not provided.)
  • opts.hostname String, the hostname of the current machine, to show the user during the WebAuth flow. (Defaults to os.hostname().)

Logging

This modules logs by emitting log events on the global process object via proc-log. These events look like this:

procLog[loglevel]('feature', 'message part 1', 'part 2', 'part 3', 'etc')

loglevel can be one of: error, warn, notice, http, info, verbose, and silly.

feature is any brief string that describes the component doing the logging.

The remaining arguments are evaluated like console.log and joined together with spaces.

A real world example of this is:

  procLog.http('request', '→', conf.method || 'GET', conf.target)

To handle the log events, you would do something like this:

process.on('log', (level, feature, ...args) => {
  console.log(level, feature, ...args)
})

changelog

Changelog

11.0.1 (2024-10-02)

Dependencies

11.0.0 (2024-09-26)

⚠️ BREAKING CHANGES

  • npm-profile now supports node ^18.17.0 || >=20.5.0

    Bug Fixes

  • a0ea10b #152 align to npm 10 node engine range (@reggi)
  • 4ea3f70 #144 exit handler error on login (#144) (@milaninfy)

    Dependencies

  • 66bcc40 #152 `proc-log@5.0.0`

    Chores

  • 8ac1fdb #152 run template-oss-apply (@reggi)
  • 1fdff2e #146 bump @npmcli/eslint-config from 4.0.5 to 5.0.0 (@dependabot[bot])
  • 5b3ebbc #134 bump @npmcli/template-oss to 4.22.0 (@lukekarrys)
  • 6b4558f #147 postinstall for dependabot template-oss PR (@hashtagchris)
  • c644e89 #147 bump @npmcli/template-oss from 4.23.1 to 4.23.3 (@dependabot[bot])

10.0.0 (2024-05-02)

⚠️ BREAKING CHANGES

  • this uses AbortSignal.throwIfAborted() which is not available in all versions of Node 16
  • hostname is no longer sent as part of the web auth body
  • the opener function will now receive an object with an abort signal which can be used to listen for the abort event intead of an event emitter

Features

  • f67687d #131 drop node 16 support (@lukekarrys)
  • d6f6ebe #131 remove hostname from body (@lukekarrys, @wraithgar)
  • c0bb22f #131 add webAuthOpener method (@lukekarrys)
  • df44705 #131 use AbortSignal instead of EventEmitter for opener (@lukekarrys)

Bug Fixes

  • 53db633 #131 pass signal to webAuthCheckLogin timer (@lukekarrys)

Dependencies

9.0.2 (2024-04-30)

Bug Fixes

  • 06687c8 #130 linting: no-unused-vars (#130) (@wraithgar)

Dependencies

Chores

  • 1c8afe8 #127 postinstall for dependabot template-oss PR (@lukekarrys)
  • 3b68ec1 #127 bump @npmcli/template-oss from 4.21.3 to 4.21.4 (@dependabot[bot])

9.0.1 (2024-04-12)

Dependencies

Chores

  • 11f4605 #122 postinstall for dependabot template-oss PR (@lukekarrys)
  • 0719640 #122 bump @npmcli/template-oss from 4.21.1 to 4.21.3 (@dependabot[bot])
  • e944f88 #119 postinstall for dependabot template-oss PR (@lukekarrys)
  • 28888c7 #119 bump @npmcli/template-oss from 4.19.0 to 4.21.1 (@dependabot[bot])
  • 30097a5 #101 postinstall for dependabot template-oss PR (@lukekarrys)
  • efe9f20 #101 bump @npmcli/template-oss from 4.18.1 to 4.19.0 (@dependabot[bot])
  • cd076f1 #100 postinstall for dependabot template-oss PR (@lukekarrys)
  • e928f0c #100 bump @npmcli/template-oss from 4.18.0 to 4.18.1 (@dependabot[bot])

9.0.0 (2023-08-15)

⚠️ BREAKING CHANGES

  • support for node <=16.13 has been removed

Bug Fixes

  • d2fdd5e #97 drop node 16.13.x support (@lukekarrys)

Dependencies

  • 1855caf #96 bump npm-registry-fetch from 15.0.0 to 16.0.0

8.0.0 (2023-08-14)

⚠️ BREAKING CHANGES

  • support for node 14 has been removed

Bug Fixes

Dependencies

  • 96370c2 #92 bump npm-registry-fetch from 14.0.5 to 15.0.0

7.0.1 (2022-10-17)

Dependencies

  • 36fa4b1 #76 bump npm-registry-fetch from 13.3.1 to 14.0.0
  • 29616ad #77 bump proc-log from 2.0.1 to 3.0.0

7.0.0 (2022-09-30)

⚠️ BREAKING CHANGES

  • npm-profile is now compatible with the following semver range for node: ^14.17.0 || ^16.13.0 || >=18.0.0

Features

  • e16befb #68 postinstall for dependabot template-oss PR (@lukekarrys)

6.2.1 (2022-08-02)

Bug Fixes

  • cancel opener promise if web login fails (#57) (cdc4acb)
  • remove npm-use-webauthn header (#53) (b701df2)

6.2.0 (2022-07-12)

Features

  • Add export for webauthCheckLogin (#54) (05a7811)

6.1.0 (2022-06-08)

Features

  • Allow web-login donecheck to cancel opener promise (#50) (aa82de0)
  • set 'npm-use-webauthn' header depending on option (#48) (6bdd233)

6.0.3 (2022-04-20)

Dependencies

  • update npm-registry-fetch requirement from ^13.0.0 to ^13.0.1 (#34) (a444b51)

6.0.2 (2022-02-15)

Dependencies

  • bump npm-registry-fetch from 12.0.2 to 13.0.0 (#28) (7c01310)

6.0.1 (2022-02-14)

Bug Fixes

Dependencies

  • update npm-registry-fetch requirement from ^12.0.0 to ^12.0.2 (82b65f8)
  • use proc-log instead of process.emit (fe2b8f3)

6.0.0 (2022-01-19)

⚠ BREAKING CHANGES

  • this drops support for node<=10 and non-LTS versions of node12 and node14

Features

Documentation

dependencies

v5.0.0 (2020-02-27)

  • Drop the CLI from the project, just maintain the library
  • Drop support for EOL Node.js versions
  • Remove Promise option, just use native Promises
  • Remove figgy-pudding
  • Use npm-registry-fetch v8
  • fix: do not try to open invalid URLs for WebLogin

v4.0.3 (2020-02-27)

  • fix: do not try to open invalid URLs for WebLogin

v4.0.2 (2019-07-16)

  • Update npm-registry-fetch to 4.0.0

v4.0.1 (2018-08-29)

  • opts.password needs to be base64-encoded when passed in for login
  • Bump npm-registry-fetch dep because we depend on opts.forceAuth

v4.0.0 (2018-08-28)

BREAKING CHANGES:

v3.0.2 (2018-06-07)

  • Allow newer make-fetch-happen.
  • Report 500s from weblogin end point as unsupported.
  • EAUTHUNKNOWN errors were incorrectly reported as EAUTHIP.

v3.0.1 (2018-02-18)

  • Log npm-notice headers

v3.0.0 (2018-02-18)

BREAKING CHANGES:

  • profile.login() and profile.adduser() take 2 functions: opener() and prompter(). opener is used when we get the url couplet from the registry. prompter is used if web-based login fails.
  • Non-200 status codes now always throw. Previously if the content.error property was set, content would be returned. Content is available on the thrown error object in the body property.

FEATURES:

  • The previous adduser is available as adduserCouch
  • The previous login is available as loginCouch
  • New loginWeb and adduserWeb commands added, which take an opener function to open up the web browser.
  • General errors have better error message reporting

FIXES:

  • General errors now correctly include the URL.
  • Missing user errors from Couch are now thrown. (As was always intended.)
  • Many errors have better stacktrace filtering.