onestack-auth
OneStack 身份服务的 TypeScript 客户端 SDK:OIDC(Authorization Code + PKCE)协议核心 + 托管资料 API 客户端。
设计边界(重要)
SDK 只做协议:
- ✅ 发现文档(带缓存)、授权 URL + PKCE、token 交换、ID token 验签(JWKS + kid 轮换)、跨站登出/结束会话 URL、健康探测、托管资料 API
- ❌ 不碰 cookie、session、用户映射、数据库——这些语义每个产品不同,留在产品侧
运行时无关:纯 ESM + d.ts,只依赖 jose,只用 Web 标准 API(fetch / crypto.subtle),在 Node 22+、Cloudflare Workers、Deno、Bun 上行为一致。所有出站请求均可传入 AbortSignal 控制超时;所有失败归一为 OneStackAuthError(含服务端错误码与 requestId)。
安装
npm install onestack-auth
后端 RP 模式(推荐)
产品后端持有 client_secret,官网/前端只做跳转与回跳页,token 不落浏览器。
import {
createAuthClient,
OneStackAuthError,
} from "onestack-auth";
const auth = createAuthClient({
issuer: "https://accounts.example.com/api/auth",
clientId: process.env.ACCOUNT_CLIENT_ID!,
clientSecret: process.env.ACCOUNT_CLIENT_SECRET!,
audience: "https://product.example.com",
});
app.get("/login", async (req, reply) => {
const transaction = await auth.authorizationTransaction({
callbackUrl: "https://product.example.com/auth/callback",
scope: "identity:migrate",
});
return reply.redirect(transaction.authorizationUrl);
});
const result = await auth.exchangeCode({
code,
codeVerifier,
callbackUrl: "https://product.example.com/auth/callback",
nonce,
});
reply.redirect(productSignOutUrl(auth.config, "https://product.example.com/"));
托管资料 API(需 profile:manage 能力)
import { getManagedAccountProfile } from "onestack-auth/profile";
const profile = await getManagedAccountProfile(auth.config, accountUserId);
非 TypeScript 产品
SDK 只是提速器:服务端点是标准 OIDC(发现文档 /.well-known/openid-configuration、Authorization Code + PKCE、JWKS),任何语言用对应 OIDC 库(Python authlib、Go go-oidc…)或裸 HTTP 即可接入。见仓库 docs/auth-integration.md。
错误处理
try {
await auth.exchangeCode({ ... });
} catch (error) {
if (error instanceof OneStackAuthError) {
error.code;
error.requestId;
}
}