Skip to content

Native bun login / bun logout #41289

Open

Description

@Amir-Abushanab

What is the problem this feature would solve?

Bun is the only major package manager with no way to authenticate to a registry from the CLI.

  • npm login — yes (web + legacy)
  • pnpm login — yes (web login with QR, stores to its own config.yaml/auth.ini)
  • yarn npm login — yes
  • bun login — Uh-oh. bun login is a subcommand reserved for future use by Bun.

Today the only path is to hand-write a token into .npmrc or bunfig.toml, or shell out to bunx npm login — which installs npm just to obtain a credential Bun already knows how to read. Bun's own error text on an unauthenticated publish points at bunx npm login.

This is a recurring source of friction, and the existing issues are all downstream of the same missing primitive:

The only prior ask for the command itself is #1176 (2022): titled bun login --registry, but filed through the bug template with just Script not found "login" in the body, and closed in two days. There is no open issue, PR, or discussion for it.

This is about to get more pressing. Since December 2025 npm login hands out a two-hour session token instead of a long-lived one, classic tokens are revoked, new granular tokens default to a 7-day lifetime (90-day cap), and bypass-2FA tokens are slated to lose direct publish (npm is targeting January 2027) in favour of staged publishing — #34306 is already asking Bun for an npm stage publish equivalent. The direction is unambiguous: publishing as a human means an interactive, 2FA-backed login session, re-established every couple of hours. Today the only way to get one is bunx npm login.

What is the feature you are proposing to solve the problem?

bun login and bun logout, matching npm's surface:

bun login                                  # web login against the default registry
bun login --registry https://npm.pkg.github.com
bun login --scope @acme                    # writes a scoped credential
bun login --auth-type legacy               # username/password/OTP prompt
bun logout

Two things make this cheaper to build than it looks.

1. The reservation already exists. login/logout were reserved in #4465 and the reservation is live in src/runtime/cli/mod.rs (~line 1055, unchanged on the 1.4.0 tag):

// reserved
if x == RootCommandMatcher::case(b"deploy")
    || x == RootCommandMatcher::case(b"cloud")
    || x == RootCommandMatcher::case(b"config")
    || x == RootCommandMatcher::case(b"use")
    || x == RootCommandMatcher::case(b"auth")
    || x == RootCommandMatcher::case(b"login")
    || x == RootCommandMatcher::case(b"logout")
{
    return Tag::ReservedCommand;
}

So this is not a breaking change and needs no deprecation window — the name is already fenced off from package.json scripts. bun prune was on that same reserved list and graduated to a real command in 1.4.0; this is the identical move.

2. Bun already implements npm's web-login flow. src/runtime/cli/publish_command.rs does the whole browser dance today, just scoped to OTP challenges during publish:

  • get_otp() (~line 1100) parses authUrl and doneUrl out of the registry's challenge
  • press_enter_to_open_in_browser() (~line 1077) launches the browser via open::OPENER
  • the doneUrl is polled for the resulting token, with a same-origin credential guard (~lines 1145-1160; being relaxed in open PR publish: poll cross-origin web login doneUrl without credentials #36556)

That is structurally the same handshake as npm login --auth-type=web. The missing piece is not the protocol — it's a standalone entry point and somewhere to persist the token.

Prior art (checked against current docs and source): npm-profile validates loginUrl/doneUrl are http(s), honours retry-after, and rewrites a registry.npmjs.org doneUrl to the configured registry so proxies work; since December 2025 the token it stores is a two-hour session token. pnpm 11's pnpm login (Rust, pnpm/crates/auth-commands) tries web login first, falls back to classic only on 404/405, works without a TTY, and stores in its own config.yaml via an atomic owner-only write. yarn stores in the home .yarnrc.yml; cargo reads the token from stdin and supports OS-keychain credential providers; JSR stores nothing for interactive publishes. The design below is npm's surface with pnpm's implementation discipline.

What alternatives have you considered?

  • bunx npm login — works, but requires npm in the image and writes credentials Bun then has to guess at. It's what Bun's own error message recommends, which is a bit of an admission.
  • Hand-writing //registry.npmjs.org/:_authToken=${NPM_TOKEN} into .npmrc — fine for CI, hostile for a first-time human publish, and the origin of most of the issues listed above.
  • A bun auth umbrella (bun auth login / bun auth token) — auth is also reserved, so it stays available. But bun login matches npm/pnpm/yarn muscle memory, and nothing stops bun auth later.

Suggested implementation

This is just a rough sketch only — happy to be redirected on any of it.

1. Un-reserve and dispatch. Drop login/logout from the reserved arm in src/runtime/cli/mod.rs, add Tag::LoginCommand / Tag::LogoutCommand, and a new src/runtime/cli/login_command.rs alongside the existing publish_command.rs.

2. Extract the web flow. Lift the authUrl/doneUrl + browser-open + poll loop out of publish_command.rs::get_otp into a shared helper both commands call. Publish keeps its OTP path; login gets the same primitive pointed at a different endpoint.

Worth noting #36556 touches this exact code — it threads an include_auth: bool through construct_publish_headers so a cross-origin doneUrl is polled without the registry's Authorization/Host. That PR is currently conflicting and unreviewed, so I wouldn't build on top of it, but the seam it introduces is the right one: a shared web-login helper needs precisely that "poll this URL, credentials only if same-origin" split. If it stalls, the extraction can carry the same fix. npm-profile solves the same proxy case the other way round: it rewrites a registry.npmjs.org doneUrl to the configured registry's origin (path prefix preserved) so the poll goes through the mirror that holds the session, and leaves every other host alone. The shared helper should probably do both — rewrite for the canonical-host case, uncredentialed poll for anything else cross-origin.

Two precision notes on that same-origin predicate (the scheme comparison is case-sensitive today; hostname is unnormalized but fails closed) are in the first comment below, to keep this readable.

3. The login handshake (mirrors npm-profile):

POST <registry>/-/v1/login   { "hostname": "<machine name>" }
  200 -> { loginUrl, doneUrl }   validate both are http(s), open loginUrl, poll doneUrl -> { token }
  404/405 -> registry has no web login; fall back to legacy

Fall back only on 404/405 as pnpm does (npm falls back on any 4xx/500); a flaky network shouldn't silently downgrade you to typing a password.

Legacy fallback is PUT <registry>/-/user/org.couchdb.user:<username> with prompted username/password/email, plus the OTP prompt Bun already has. Older Verdaccio and several enterprise registries don't implement /-/v1/login (verdaccio#3413), so the fallback isn't optional — but it's a third-party-registry path, not the npmjs.com path: npm has said the legacy endpoint's removal there is "imminent", and npm 12 removed npm adduser, so bun login should never create accounts. --auth-type=web|legacy selects explicitly.

One consequence of npm's new model: npmjs.com now returns a two-hour session token, so bun publish should treat a 401 from a web-login-capable registry as "session expired, re-run the login inline" rather than fail. npm just prints "try npm login again"; Bun can be better here.

4. Persistence — the one real design decision. src/ini/lib.rs is parse-only today (load_npmrc, load_npmrc_config, apply_registry_auth); there is no ini writer. npm writes .npmrc; pnpm, yarn and cargo each keep their own store. Options:

  • Write to the user-level .npmrc ($NPM_CONFIG_USERCONFIG, else ~/.npmrc), as //<registry-path>/:_authToken=<token> plus @scope:registry= when --scope is given. Bun already reads exactly this, and it keeps npm/npx/CI images interoperable. One dependency: Bun doesn't honour NPM_CONFIG_USERCONFIG yet — open PR install: read NPM_CONFIG_USERCONFIG as the user-level .npmrc path #38047 adds it — so bun login should either land after that or carry the same lookup, otherwise it could write a token to a file Bun then doesn't read. My preference for the first PR.
  • A Bun-native store. Bun already ships Bun.secrets (Keychain on macOS, libsecret on Linux, Credential Manager on Windows), so "native" could mean the OS keychain rather than a second plaintext file. Strongest for long-lived third-party tokens (npmjs.com's two-hour sessions make plaintext low-risk). I'd add it as an opt-in after the .npmrc path lands, not instead of it, so everything else that expects .npmrc keeps working.

Either way the write must be a line-preserving patch, not a reserialize — clobbering a hand-maintained .npmrc's comments, ordering, or unrelated scoped registries would be worse than not having the command — and an atomic private write (temp file + rename, no symlink following, 0600 on create). Details in the first comment.

5. bun logout. DELETE <registry>/-/user/token/<token> to revoke server-side, then remove just that line. Treat 401 and 404 as "already invalid" and still remove the local entry — with two-hour sessions the token will often have expired first. If the credential came from an environment variable or a hand-written .npmrc line, revoke it but tell the user where to remove it rather than editing config Bun didn't write (pnpm's rule). The revoke URL carries the token in its last path segment, so strip it before it can reach an error message.

6. Verification. After a successful login, call GET /-/whoami and print Logged in as <user> on <registry> — the username, never the token. bun pm whoami already exists and shares the request. Tests extend test/cli/install/bun-publish.test.ts, whose harness already stands up a fake registry that issues a doneUrl (since #16630, with cross-origin cases added in #36165) — the fixture for this mostly exists.

7. Security requirements. No token on argv (stdin only, like cargo login); http(s)-only loginUrl/doneUrl; a wall-clock cap on the doneUrl poll (today's loop has none); defined non-TTY behaviour; a warning before sending credentials over plain http; and never printing the token anywhere. The full, testable list is in the first comment below.

Out of scope for a first PR: OIDC / trusted publishing (#22423; the earlier attempt #29374 was closed unmerged), --provenance (#15601), basic-auth registries (open PR #38776), and staged publishing (#34306) — the natural next step once a login session exists, since stage approve is precisely an interactive 2FA action.


I'm happy to take this on and open the PR — the get_otp extraction plus a .npmrc patcher is a contained piece of work and I'd rather build it than keep shelling out to npm. Before I start I'd want a maintainer to weigh in on step 4 (write to ~/.npmrc vs. a Bun-native credential store), since that's the decision that's expensive to reverse. Everything else I'd follow npm's behaviour on.

One timing note: #39403 is folding 171 open install/pm/publish PRs into a single branch, including #38047 and #38776, and publish_command.rs is in the middle of that. I'd base this on whatever lands from the fold rather than on today's main.

Activity

  1. added
    enhancement
    on Sep 3, 2026
  2. Amir-Abushanab commented on Sep 3, 2026

    @Amir-Abushanab
    Author

    Some more implementation details regarding security:

    • No --token <value> flag. Shell history. If non-interactive login is needed, take the token on stdin (cargo login, docker login --password-stdin).
    • loginUrl only gets opened in a browser if it's http(s), doneUrl only gets polled if it's http(s). publish already does this (publish_command.rs:1138-1154), the shared helper needs to keep it.
    • The doneUrl poll has no overall timeout. publish_command.rs:1253 honours retry-after and otherwise loops until the registry returns 200. Needs a cap, 5 minutes or so, then a proper error.
    • Without a TTY: web login should print the URL and poll, no "press enter". Legacy login should error out instead of waiting on a prompt. pnpm behaves this way. The current enter-listener thread returns on EOF so web login may already work in CI, but nothing tests it.
    • Warn before sending a password or token to a plain http registry other than localhost. npm and pnpm don't warn afaict. Refusing outright would break too many internal Verdaccio setups.
    • Never print the token. Includes --verbose, error messages, and the revoke URL (/-/user/token/<token>, token is the last segment). src/ini/lib.rs already has redact_sensitive_information from bun install prints npmrc registry authentication credentials when npmrc options cant be parsed #14444/Bun will print private package token if set it ~/.npmrc #14867, reuse it. Registry URLs come from .npmrc and can contain user:pass@ or escape sequences, strip those before printing.
    • Registry auth must stay out of the lifecycle script env. It currently gets npm_config_user_agent and npm_execpath (src/install/lib.rs:828-850) and npm_config_node_gyp (src/install/PackageManager.rs), nothing auth-related. Keep it that way.

    Writing .npmrc

    Patch lines in place, don't reserialize. Write to a temp file in the same dir, fsync, rename over the target. Use symlink_metadata so a symlinked target gets replaced instead of followed. 0600 on create, preserve the existing mode otherwise. pnpm's pnpm_fs::write_atomic_private does all of this, and their auth-commands crate does a read/diff/single write so a failure midway leaves the file untouched.

    Same-origin check in get_otp

    Two things in src/url/lib.rs that matter once this predicate is shared with bun login:

    1. protocol is stored as raw bytes (url/lib.rs:207), so done_url.protocol != registry_url.protocol is case-sensitive. HTTPS://registry.example.com vs https://registry.example.com counts as cross-origin. publish: poll cross-origin web login doneUrl without credentials #36556 changes this to is_https() == is_https(), which handles case (eql_case_insensitive_ascii) but puts every non-https scheme in the same bucket, so a registry URL with any other scheme compares equal to an http: doneUrl and gets credentials. Unlikely in practice but is_s3() is on the same type. A case-insensitive compare of protocol plus the existing http/https check on done_url covers both.

    2. parse_host (url/lib.rs:841) doesn't lowercase, strip trailing dots, or handle punycode, and the hostname comparison is byte equality. Two different origins can't compare equal, so this isn't a bypass. Registry.Example.Com or registry.example.com. just won't be recognised as same-origin and the poll goes out without credentials, which drops you to the OTP prompt. Should be normalized at some point.

    Whatever changes here should only affect which URLs count as same-origin. Credentials still have to be sent when doneUrl is same-origin, some registries require auth on /-/v1/done.

  3. robobun commented on Sep 3, 2026

    @robobun
    Collaborator

    Fix ready for review: #41293 (native bun login and bun logout, web login, token saved to the user .npmrc).
    CI on the PR is green except for one unrelated test on macOS x64 that is broken on main. The PR needs a maintainer to merge.

  4. added
    bun install
    on Sep 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bun installenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions