background
cli-authv0.1.0-beta

让你的 CLI 也拥有生产级别的 OAuth

全功能、完全可插拔的认证库。支持四种流程。包括令牌存储、刷新、跨进程锁和钥匙串集成。每个环节都有人为你处理,也都可以替换。

$npm install cli-auth
MIT 许可证Node.js 22+Bun 1.1+仅支持 ESMTypeScript
~/projects/your-cli — zsh

四种流程,一套库搞定。

选择你的策略,底层细节都帮你包好了。

设备码RFC 8628

适合服务器、Docker shell 以及打不开浏览器的机器。

  • 轮询循环自动帮你处理 slow_down 延迟和过期时间
  • 用户码会通过 onAuthorization 回调抛出,你自定义展示方式
  • access token 临近过期时自动刷新
什么时候用它 → 无头环境、SSH 或远程场景。无浏览器可达时用。用户在笔记本登录,CLI 在后台轮询。
device-code.ts
1import { createCliAuth, keyringStorage } from 'cli-auth';2import { Entry } from '@napi-rs/keyring';3 4const auth = createCliAuth({5  strategy: 'device-code',6  provider: {7    metadata: {8      deviceAuthorizationEndpoint: 'https://your-tenant.logto.app/oidc/device/auth',9      tokenEndpoint: 'https://your-tenant.logto.app/oidc/token',10    },11  },12  clientId: 'your-cli-client',13  storage: keyringStorage({ entry: new Entry('your-cli', 'tokens') }),14  scope: 'openid offline_access',15});16 17await auth.login({18  onAuthorization: ({ userCode, verificationUri }) => {19    console.log(`Visit ${verificationUri} and enter ${userCode}`);20  },21});22 23const accessToken = await auth.getToken();

那些没人告诉你的 CLI 认证坑。

下面这些都是我们已经踩过的真实 bug、竞态以及规范陷阱。

slow_down back-off
PKCE verifier + challenge
loopback on 127.0.0.1
O_CREAT | O_EXCL
atomic write + rename
cross-process lock
recheck after lock
0600 permissions
macOS Keychain
Windows Credential Store
Linux Secret Service
refresh token single-use
expiry threshold
per-resource token cache
proxy / OTel fetch hook
branded callback page
custom parameters
TypeScript discriminated unions
…and tests.
background

每一环都能替换,没有黑盒。

存储、锁、fetch、回调页面都可自定义。没有硬编码。点一下插槽看看配置自动改写。

替换 存储
自动用 macOS 钥匙串、Windows 凭证存储或 Linux Secret Service。底层用 @napi-rs/keyring。
cli-auth.config.ts
1import { createCliAuth } from 'cli-auth';2 3const auth = createCliAuth({4  strategy: 'authorization-code',5  provider: { /* ... */ },6  clientId: 'your-cli-client',7  storage: keyringStorage({ entry: new Entry('your-cli', 'tokens') }),8});

支持任意身份服务商

只要是 OAuth 2.0 / OIDC 标准兼容的服务端都能用。直接设置 endpoint 就能跑。我们做的不止是给 Logto 用的。

Logto
Auth0
Okta
Keycloak
Microsoft Entra
Google
Authelia
Any OIDC 2.0 server
Logto
Auth0
Okta
Keycloak
Microsoft Entra
Google
Authelia
Any OIDC 2.0 server

常见问题解答

这个和 openid-client 有什么区别?

Auth0、Okta 或自建服务能用吗?

跨进程锁是怎么做到的?

系统钥匙串不可用怎么办?

支持哪些运行环境?

可以自定义 post-login 回调页面吗?

使用 Logto Cloud 解锁更多功能

零编码 CLI 认证体验。