@ atute/oauth-node-客户端
aproto OAuth 节点客户端js(加上Deno、Bun和其他服务器运行时间)和 Web 扩展。 。 。 .
支持两个:
- 保密客户 - 认证
private_key_jwt延长会期(最多 需要关键管理和主机元数据 - 公共客户 - 没有认证(
token_endpoint_auth_method: 'none'),缩短届会(2届) 每周最多),更简单的CLI工具和本地开发设置
npm install @atcute/oauth-node-client
保密客户
下面的例子使用Hono,但是任何网络框架都有效.
关键管理
保密客户需要不断的私人钥匙 所以我们需要生成一个.
一个模式是保持承诺 .env 带有空占位符并生成特定开发者
.env.local 从不检查 :
- 创建
.env空值:
PRIVATE_KEY_JWK=
- 添加
scripts/setup-env.mjs数字 :
import { existsSync } from 'node:fs';
import { copyFile, readFile, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { generateClientAssertionKey } from '@atcute/oauth-node-client';
const ensureEnvLocal = async () => {
const envPath = resolve(process.cwd(), '.env');
const envLocalPath = resolve(process.cwd(), '.env.local');
if (!existsSync(envLocalPath)) {
await copyFile(envPath, envLocalPath);
}
return envLocalPath;
};
const upsertEnvVar = (input, key, value) => {
const line = `${key}=${value}`;
const re = new RegExp(`^${key}=.*$`, 'm');
if (re.test(input)) {
const match = input.match(re);
const current = match ? match[0].slice(key.length + 1) : '';
const trimmed = current.trim();
if (trimmed === '' || trimmed === `''` || trimmed === `""`) {
return input.replace(re, line);
}
return input;
}
const suffix = input.endsWith('\n') || input.length === 0 ? '' : '\n';
return `${input}${suffix}${line}\n`;
};
const envLocalPath = await ensureEnvLocal();
const envLocal = await readFile(envLocalPath, 'utf8');
// generateClientAssertionKey returns a JWK directly
const jwk = await generateClientAssertionKey('main', 'ES256');
const jwkJson = JSON.stringify(jwk);
const updated = upsertEnvVar(envLocal, 'PRIVATE_KEY_JWK', `'${jwkJson}'`);
if (updated !== envLocal) {
await writeFile(envLocalPath, updated);
console.log(`updated ${envLocalPath}`);
} else {
console.log(`no changes to ${envLocalPath}`);
}
- 运行它:
node scripts/setup-env.mjs
- 运行时创建密钥集 :
import type { ClientAssertionPrivateJwk } from '@atcute/oauth-node-client';
// JWKs can be used directly - no import step needed
const keyset = [JSON.parse(process.env.PRIVATE_KEY_JWK!) as ClientAssertionPrivateJwk];
创建 OAuth 客户端
import {
MemoryStore,
OAuthClient,
scope,
type ClientAssertionPrivateJwk,
} from '@atcute/oauth-node-client';
import {
CompositeDidDocumentResolver,
CompositeHandleResolver,
LocalActorResolver,
PlcDidDocumentResolver,
WebDidDocumentResolver,
WellKnownHandleResolver,
} from '@atcute/identity-resolver';
import { NodeDnsHandleResolver } from '@atcute/identity-resolver-node';
const oauth = new OAuthClient({
metadata: {
// this must be the URL where you serve `oauth.metadata`.
client_id: 'https://example.com/oauth-client-metadata.json',
redirect_uris: ['https://example.com/oauth/callback'],
// scopes; shown here is an example for a full-featured Bluesky client.
scope: [
scope.include({
nsid: 'app.bsky.authFullApp',
aud: 'did:web:api.bsky.app#bsky_appview',
}),
scope.include({
nsid: 'chat.bsky.authFullChatClient',
aud: 'did:web:api.bsky.chat#bsky_chat',
}),
scope.rpc({ lxm: ['com.atproto.moderation.createReport'], aud: '*' }),
scope.blob({ accept: ['image/*', 'video/*'] }),
scope.account({ attr: 'email', action: 'manage' }),
scope.identity({ attr: 'handle' }),
],
// optional: if set, this must be the URL where you serve `oauth.jwks`.
// must be same-origin as client_id. if omitted, `oauth.metadata` will inline jwks instead.
jwks_uri: 'https://example.com/jwks.json',
},
// JWKs can be used directly - no import step needed
keyset: [JSON.parse(process.env.PRIVATE_KEY_JWK!) as ClientAssertionPrivateJwk],
stores: {
// sessions are keyed by session ID (defaults to user's DID) - should be durable across restarts.
sessions: new MemoryStore(),
// states are keyed by OAuth state value - should have ~10 minute TTL.
// MemoryStore works for development; use Redis or similar in production.
states: new MemoryStore(),
},
// optional: custom lock for coordinating token refresh across processes.
// defaults to in-memory, which works for single-process deployments.
// for multi-process/clustered deployments, provide a distributed lock
// (e.g., Redis-based) to prevent concurrent refresh for the same session.
async requestLock(name, fn) {
// ...
},
actorResolver: new LocalActorResolver({
handleResolver: new CompositeHandleResolver({
methods: {
dns: new NodeDnsHandleResolver(),
http: new WellKnownHandleResolver(),
},
}),
didDocumentResolver: new CompositeDidDocumentResolver({
methods: {
plc: new PlcDidDocumentResolver(),
web: new WebDidDocumentResolver(),
},
}),
}),
});
服务元数据和jwks
pDS/授权服务器从您广告的 URL 中获取您的客户端元数据和 JWKS :
app.get('/oauth-client-metadata.json', (c) => c.json(oauth.metadata));
app.get('/jwks.json', (c) => c.json(oauth.jwks));
开始授权
app.get('/login', async (c) => {
const { url } = await oauth.authorize({
target: { type: 'account', identifier: 'mary.my.id' },
state: { returnTo: '/protected' },
});
return c.redirect(url.toString());
});
处理回调
将回调查询参数传递给 callback()。如果你的框架只给你一条路径,结合它
与您的公共来源(在芬兰使用相同的来源) redirect_uri:
app.get('/oauth/callback', async (c) => {
const callbackUrl = new URL(c.req.url);
const { session, state } = await oauth.callback(callbackUrl.searchParams);
// store session.did in your own cookie/session so you know who is signed in.
// oauth tokens are stored in your session store - don't store them elsewhere.
const did = session.did;
const returnTo = (state as { returnTo?: string } | undefined)?.returnTo ?? '/';
void did;
return c.redirect(returnTo);
});
会话恢复
dID 恢复会话 。 如果需要, 这将刷新符号 .
import { Client } from '@atcute/client';
const session = await oauth.restore(did);
const client = new Client({ handler: session });
const { data } = await client.get('com.atproto.server.getSession');
签名退出
await oauth.revoke(did);
或者,如果你已经有一个 OAuthSession数字 :
await session.signOut();
每个账户多个会话
默认情况下, 会话由账户的“ DID” 键入, 因此再次签名取代先前的赠款
用于保存每个浏览器、设备或会话 cookie 的独立授权配置
createSessionId 打开 OAuthClient数字 :
const oauth = new OAuthClient({
// ...
stores: {
sessions: new MemoryStore(),
states: new MemoryStore(),
},
createSessionId: () => crypto.randomUUID(),
});
在您的调用处理器中, 存储 session.sessionId 在你的饼干 并传递给 oauth.restore()
财务报告和审定财务报表 oauth.revoke()数字 :
app.get('/oauth/callback', async (c) => {
const callbackUrl = new URL(c.req.url);
const { session } = await oauth.callback(callbackUrl.searchParams);
// store session.sessionId in your cookie; restore() and revoke() accept it directly
// without needing a separate cookie-to-DID lookup table
const sessionId = session.sessionId;
void sessionId;
return c.redirect('/');
});
createSessionId 接收已核实的 sub (数字化)和 state 从 authorize()这样你也可以
生成结构密钥, 如 ${sub}:${id}数字 :
const oauth = new OAuthClient({
// ...
createSessionId: ({ sub }) => `${sub}:${crypto.randomUUID()}`,
});
公共客户
公共客户不需要密钥管理或托管元数据. 当地CLI工具最理想 交换是缩短会话寿命(最多2周对180天) 保密客户).
循环客户端
循环客户端使用 http://localhost 作为源,授权服务器确认为
公共客户端。 不需要客户端注册或主机元数据 - 库构建
client_id 自动从您重定向的 URI 和 瞄准镜.
import { MemoryStore, OAuthClient, scope, type StoredState } from '@atcute/oauth-node-client';
import {
CompositeDidDocumentResolver,
CompositeHandleResolver,
LocalActorResolver,
PlcDidDocumentResolver,
WebDidDocumentResolver,
WellKnownHandleResolver,
} from '@atcute/identity-resolver';
import { NodeDnsHandleResolver } from '@atcute/identity-resolver-node';
// use any available port for the callback server
const port = 8080;
const redirectUri = `http://127.0.0.1:${port}/callback`;
const oauth = new OAuthClient({
metadata: {
// no client_id needed - built automatically as:
// http://localhost?redirect_uri=http://127.0.0.1:8080/callback&scope=...
redirect_uris: [redirectUri],
scope: [scope.rpc({ lxm: ['app.bsky.actor.getProfile'], aud: '*' })],
},
// no keyset - this makes it a public client
stores: {
sessions: new MemoryStore(),
states: new MemoryStore<string, StoredState>({ maxSize: 10, ttl: 10 * 60_000 }),
},
actorResolver: new LocalActorResolver({
handleResolver: new CompositeHandleResolver({
methods: {
dns: new NodeDnsHandleResolver(),
http: new WellKnownHandleResolver(),
},
}),
didDocumentResolver: new CompositeDidDocumentResolver({
methods: {
plc: new PlcDidDocumentResolver(),
web: new WebDidDocumentResolver(),
},
}),
}),
});
循环重定向 URI 必须使用 127.0.0.1 或者说 [::1] (无) localhost。端口可以是任意的
可用的端口 - 授权服务器在匹配回转方向重定向时忽略端口
RFC 8252 (英语).
见 节点客户端- 公共- 实例 完整的 CLI 软件包 实例.
可发现的公共客户
对于需要发现的公共客户 client_id (例如,移动应用程序或网络应用程序没有
后端),提供 a client_id 指向主机元数据的 URL :
const oauth = new OAuthClient({
metadata: {
client_id: 'https://example.com/oauth-client-metadata.json',
redirect_uris: ['https://example.com/callback'],
scope: 'atproto',
},
stores: { /* ... */ },
actorResolver: /* ... */,
});
应设置主机元数据 token_endpoint_auth_method: 'none' 并省略 jwks编号 :jwks_uri。 。 。 .
自定义存储
用于生产部署,执行 Store 与类似 Redis 的共享存储界面 :
import type { OAuthClientStores } from '@atcute/oauth-node-client';
const stores: OAuthClientStores = {
sessions: {
async get(sessionId, options) {
// ...
},
async set(sessionId, session) {
// ...
},
async delete(sessionId) {
// ...
},
async clear() {},
},
states: {
async get(stateId, options) {
// ...
},
async set(stateId, state) {
// ...
},
async delete(stateId) {
// ...
},
async clear() {},
},
};
Web 扩展
浏览器扩展需要作为 可发现的公共客户端 并因此需要公开的 HTTPS 源码来托管客户端元数据和回调页面.
{
"client_id": "https://example.com/oauth-client-metadata.json",
"client_name": "My App",
"client_uri": "https://example.com",
"redirect_uris": ["https://example.com/oauth/callback"],
"scope": "atproto",
"grant_types": ["authorization_code", "refresh_token"],
"response_types": ["code"],
"token_endpoint_auth_method": "none",
"application_type": "web",
"dpop_bound_access_tokens": true
}
import {
CompositeDidDocumentResolver,
CompositeHandleResolver,
DohJsonHandleResolver,
LocalActorResolver,
PlcDidDocumentResolver,
WebDidDocumentResolver,
WellKnownHandleResolver,
} from '@atcute/identity-resolver';
const oauth = new OAuthClient({
metadata: {
client_id: 'https://example.com/oauth-client-metadata.json',
redirect_uris: ['https://example.com/callback'],
scope: 'atproto',
},
stores: {/* ... */},
requestLock(name, fn) {
return navigator.locks.request(name, fn);
},
actorResolver: new LocalActorResolver({
handleResolver: new CompositeHandleResolver({
methods: {
dns: new DohJsonHandleResolver(),
http: new WellKnownHandleResolver(),
},
}),
didDocumentResolver: new CompositeDidDocumentResolver({
methods: {
plc: new PlcDidDocumentResolver(),
web: new WebDidDocumentResolver(),
},
}),
}),
});
重定向 URIs 中
弹出页面
在您的页面中服务 redirect_uri 将查询字符串转发到扩展名 :
<script>
// allowlist your own extension IDs, do not read the target from the URL.
// firefox uses a different host, see `browser.identity.getRedirectURL()`.
location.replace('https://<extension-id>.chromiumapp.org/' + location.search);
</script>
launchWebAuthFlow 一旦流量到达 URL 时解决 :
const { url } = await oauth.authorize({
target: { type: 'account', identifier: 'mary.my.id' },
});
const redirect = await chrome.identity.launchWebAuthFlow({
url: url.toString(),
interactive: true,
});
const { session } = await oauth.callback(new URL(redirect).searchParams);
这需要 identity 允许.
内容脚本
如果您无法添加回放页面, 请在标签中打开授权 URL, 用
内容脚本与您的 redirect_uri数字 :
// content script
chrome.runtime.sendMessage({ type: 'oauth-callback', search: location.search });
// service worker
chrome.runtime.onMessage.addListener(({ type, search }) => {
if (type === 'oauth-callback') {
oauth.callback(new URLSearchParams(search)).then(
({ session }) => {
// ...
},
(err) => {
// surface the failure, the tab is already gone
},
);
}
});
这需要对调用源头使用主机权限,并且内容脚本必须在 显出.