🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(sdk): OAuth helpers for native apps and an accessToken provider (#21435)
Innei7b27fd705322
diff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex e00f836631d..6435b0e4120 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -57,6 +57,42 @@ for await (const chunk of response.body!) {(First-class typed SSE methods will come with the spec's response schemas.)+### Signing in with OAuth (native apps)++Public clients registered in LobeHub's OIDC provider (`lobehub-mobile`, `toby`, …) sign in with authorization code + PKCE. Open the authorize URL in the system browser session (`ASWebAuthenticationSession`, Custom Tabs), then exchange the callback:++```ts+import {+ createAuthorizationUrl,+ createLobeHub,+ createPkcePair,+ exchangeAuthorizationCode,+ parseAuthorizationCallback,+ refreshAccessToken,+} from '@lobehub/sdk';++const client = { clientId: 'toby', redirectUri: 'https://app.lobehub.com/oidc/callback/toby' };+const pkce = await createPkcePair(); // or create it natively where crypto.subtle is missing+const url = createAuthorizationUrl({ ...client, codeChallenge: pkce.challenge, state });++const code = parseAuthorizationCallback(callbackUrl, state);+let tokens = await exchangeAuthorizationCode({ ...client, code, codeVerifier: pkce.verifier });++const lobehub = createLobeHub({+ accessToken: async () => {+ if (tokens.expiresAt - Date.now() < 60_000) {+ tokens = await refreshAccessToken({+ clientId: client.clientId,+ refreshToken: tokens.refreshToken!,+ });+ }+ return tokens.accessToken;+ },+});+```++Refresh tokens rotate, so persist the one returned by every refresh. A `LobeHubOAuthError` with `code: 'invalid_grant'` means the user has to sign in again.+## Development- `bun generate` — regenerate `src/generated/` from `../openapi/openapi.yml` (run after the spec changes; naming rules live in `openapi-ts.config.ts`)diff --git a/packages/sdk/src/auth.test.ts b/packages/sdk/src/auth.test.tsnew file mode 100644index 00000000000..82317f18774--- /dev/null+++ b/packages/sdk/src/auth.test.ts@@ -0,0 +1,190 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ createAuthorizationUrl,+ createPkcePair,+ DEFAULT_OAUTH_SCOPE,+ exchangeAuthorizationCode,+ LOBEHUB_API_RESOURCE,+ LobeHubOAuthError,+ parseAuthorizationCallback,+ refreshAccessToken,+} from './auth';++const tokenFetch = (status: number, body: unknown) => {+ const requests: Request[] = [];+ const fetch = (async (input: string, init?: RequestInit) => {+ requests.push(new Request(input, init));+ return new Response(JSON.stringify(body), {+ headers: { 'Content-Type': 'application/json' },+ status,+ });+ }) as typeof globalThis.fetch;+ return { fetch, requests };+};++afterEach(() => {+ vi.useRealTimers();+});++describe('createAuthorizationUrl', () => {+ it('builds a PKCE authorize request for the API resource', () => {+ const url = new URL(+ createAuthorizationUrl({+ clientId: 'toby',+ codeChallenge: 'challenge',+ redirectUri: 'https://app.lobehub.com/oidc/callback/toby',+ state: 'st',+ }),+ );++ expect(`${url.origin}${url.pathname}`).toBe('https://app.lobehub.com/oidc/auth');+ expect(Object.fromEntries(url.searchParams)).toEqual({+ client_id: 'toby',+ code_challenge: 'challenge',+ code_challenge_method: 'S256',+ prompt: 'consent',+ redirect_uri: 'https://app.lobehub.com/oidc/callback/toby',+ resource: LOBEHUB_API_RESOURCE,+ response_type: 'code',+ scope: DEFAULT_OAUTH_SCOPE,+ state: 'st',+ });+ });++ it('honors a custom baseURL with a trailing slash', () => {+ const url = createAuthorizationUrl({+ baseURL: 'http://localhost:3010/',+ clientId: 'c',+ codeChallenge: 'x',+ redirectUri: 'r',+ state: 's',+ });++ expect(url.startsWith('http://localhost:3010/oidc/auth?')).toBe(true);+ });+});++describe('parseAuthorizationCallback', () => {+ it('returns the code when the state matches', () => {+ expect(parseAuthorizationCallback('https://x/cb?code=abc%2F1&state=st', 'st')).toBe('abc/1');+ });++ it('rejects a mismatched state', () => {+ expect(() => parseAuthorizationCallback('https://x/cb?code=abc&state=other', 'st')).toThrow(+ expect.objectContaining({ code: 'state_mismatch' }),+ );+ });++ it('surfaces the provider error', () => {+ expect(() =>+ parseAuthorizationCallback(+ 'https://x/cb?error=access_denied&error_description=No+thanks',+ 'st',+ ),+ ).toThrow(expect.objectContaining({ code: 'access_denied', message: 'No thanks' }));+ });++ it('rejects a callback without a code', () => {+ expect(() => parseAuthorizationCallback('https://x/cb?state=st', 'st')).toThrow(+ expect.objectContaining({ code: 'missing_code' }),+ );+ });+});++describe('token requests', () => {+ it('exchanges the code with the verifier as a public client', async () => {+ vi.useFakeTimers({ now: 1_000_000 });+ const { fetch, requests } = tokenFetch(200, {+ access_token: 'at',+ expires_in: 3600,+ refresh_token: 'rt',+ scope: 'profile offline_access',+ token_type: 'Bearer',+ });++ const tokens = await exchangeAuthorizationCode({+ clientId: 'toby',+ code: 'abc',+ codeVerifier: 'ver',+ fetch,+ redirectUri: 'https://app.lobehub.com/oidc/callback/toby',+ });++ expect(requests[0].url).toBe('https://app.lobehub.com/oidc/token');+ expect(requests[0].headers.get('content-type')).toBe('application/x-www-form-urlencoded');+ expect(Object.fromEntries(new URLSearchParams(await requests[0].text()))).toEqual({+ client_id: 'toby',+ code: 'abc',+ code_verifier: 'ver',+ grant_type: 'authorization_code',+ redirect_uri: 'https://app.lobehub.com/oidc/callback/toby',+ });+ expect(tokens).toEqual({+ accessToken: 'at',+ expiresAt: 1_000_000 + 3_600_000,+ refreshToken: 'rt',+ scope: 'profile offline_access',+ tokenType: 'Bearer',+ });+ });++ it('refreshes with the refresh_token grant', async () => {+ const { fetch, requests } = tokenFetch(200, {+ access_token: 'at2',+ expires_in: 60,+ refresh_token: 'rt2',+ });++ const tokens = await refreshAccessToken({ clientId: 'toby', fetch, refreshToken: 'rt' });++ expect(Object.fromEntries(new URLSearchParams(await requests[0].text()))).toEqual({+ client_id: 'toby',+ grant_type: 'refresh_token',+ refresh_token: 'rt',+ });+ expect(tokens.accessToken).toBe('at2');+ expect(tokens.refreshToken).toBe('rt2');+ expect(tokens.tokenType).toBe('Bearer');+ });++ it('maps an OAuth error response to LobeHubOAuthError', async () => {+ const { fetch } = tokenFetch(400, {+ error: 'invalid_grant',+ error_description: 'grant request is invalid',+ });++ const failure = refreshAccessToken({ clientId: 'toby', fetch, refreshToken: 'gone' });++ await expect(failure).rejects.toBeInstanceOf(LobeHubOAuthError);+ await expect(failure).rejects.toMatchObject({+ code: 'invalid_grant',+ message: 'grant request is invalid',+ status: 400,+ });+ });++ it('rejects a success response without an access token', async () => {+ const { fetch } = tokenFetch(200, { token_type: 'Bearer' });++ await expect(+ refreshAccessToken({ clientId: 'toby', fetch, refreshToken: 'rt' }),+ ).rejects.toMatchObject({+ code: 'missing_access_token',+ });+ });+});++describe('createPkcePair', () => {+ it('derives the S256 challenge from the verifier', async () => {+ const { challenge, verifier } = await createPkcePair();++ expect(verifier).toMatch(/^[\w-]{43}$/);+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));+ const expected = btoa(String.fromCharCode(...new Uint8Array(digest)))+ .replaceAll('+', '-')+ .replaceAll('/', '_')+ .replace(/=+$/, '');+ expect(challenge).toBe(expected);+ });+});diff --git a/packages/sdk/src/auth.ts b/packages/sdk/src/auth.tsnew file mode 100644index 00000000000..4e86c88191a--- /dev/null+++ b/packages/sdk/src/auth.ts@@ -0,0 +1,167 @@+import { DEFAULT_BASE_URL } from './constants';++/** The audience every `/api/v1` access token is issued for. */+export const LOBEHUB_API_RESOURCE = 'urn:lobehub:chat';++/** Scopes a native app needs to call `/api/v1` and keep a refresh token. */+export const DEFAULT_OAUTH_SCOPE = 'profile email offline_access';++export interface OAuthClientOptions {+ /** Origin of the LobeHub deployment, defaults to LobeHub Cloud */+ baseURL?: string;+ /** A registered public client, e.g. `lobehub-mobile` */+ clientId: string;+ fetch?: typeof globalThis.fetch;+}++export interface OAuthTokens {+ accessToken: string;+ /** Epoch milliseconds */+ expiresAt: number;+ /** Rotated on every refresh: always persist the latest one */+ refreshToken?: string;+ scope?: string;+ tokenType: string;+}++export interface PkcePair {+ challenge: string;+ verifier: string;+}++export class LobeHubOAuthError extends Error {+ readonly code: string;+ readonly status?: number;++ constructor(code: string, message?: string, status?: number) {+ super(message ?? code);+ this.name = 'LobeHubOAuthError';+ this.code = code;+ this.status = status;+ }+}++// Hand-rolled instead of URLSearchParams so the module also runs in hosts without it (JavaScriptCore).+const encodeForm = (params: Record<string, string | undefined>) =>+ Object.entries(params)+ .filter((entry): entry is [string, string] => entry[1] !== undefined)+ .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)+ .join('&');++const oidcUrl = (baseURL: string | undefined, path: string) =>+ `${(baseURL ?? DEFAULT_BASE_URL).replace(/\/$/, '')}/oidc/${path}`;++const queryParam = (url: string, name: string) => {+ const match = url.match(new RegExp(`[?&#]${name}=([^&#]*)`));+ return match ? decodeURIComponent(match[1].replaceAll('+', ' ')) : undefined;+};++const base64Url = (bytes: Uint8Array) => {+ let binary = '';+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');+};++/**+ * Generate a PKCE verifier and its S256 challenge with Web Crypto.+ * Hosts without `crypto.subtle` (JavaScriptCore, older RN) should create the+ * pair natively and pass it to {@link createAuthorizationUrl} instead.+ */+export const createPkcePair = async (): Promise<PkcePair> => {+ const crypto = globalThis.crypto;+ if (!crypto?.subtle)+ throw new LobeHubOAuthError('pkce_unavailable', 'crypto.subtle is not available');++ const verifier = base64Url(crypto.getRandomValues(new Uint8Array(32)));+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));+ return { challenge: base64Url(new Uint8Array(digest)), verifier };+};++/** Build the `/oidc/auth` URL to open in the system browser session. */+export const createAuthorizationUrl = (+ options: Omit<OAuthClientOptions, 'fetch'> & {+ codeChallenge: string;+ redirectUri: string;+ scope?: string;+ state: string;+ },+): string =>+ `${oidcUrl(options.baseURL, 'auth')}?${encodeForm({+ client_id: options.clientId,+ code_challenge: options.codeChallenge,+ code_challenge_method: 'S256',+ // oidc-provider only issues a refresh token for offline_access after an explicit consent prompt.+ prompt: 'consent',+ redirect_uri: options.redirectUri,+ resource: LOBEHUB_API_RESOURCE,+ response_type: 'code',+ scope: options.scope ?? DEFAULT_OAUTH_SCOPE,+ state: options.state,+ })}`;++/**+ * Read the authorization code from the callback URL, rejecting a state that+ * does not match the one sent with {@link createAuthorizationUrl}.+ */+export const parseAuthorizationCallback = (callbackUrl: string, expectedState: string): string => {+ const error = queryParam(callbackUrl, 'error');+ if (error) throw new LobeHubOAuthError(error, queryParam(callbackUrl, 'error_description'));+ if (queryParam(callbackUrl, 'state') !== expectedState)+ throw new LobeHubOAuthError('state_mismatch');++ const code = queryParam(callbackUrl, 'code');+ if (!code) throw new LobeHubOAuthError('missing_code');+ return code;+};++const requestTokens = async (+ options: OAuthClientOptions,+ params: Record<string, string>,+): Promise<OAuthTokens> => {+ const fetch = options.fetch ?? globalThis.fetch;+ const requestedAt = Date.now();+ const response = await fetch(oidcUrl(options.baseURL, 'token'), {+ body: encodeForm({ client_id: options.clientId, ...params }),+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ method: 'POST',+ });+ const body = (await response.json().catch(() => ({}))) as Record<string, unknown>;++ if (!response.ok) {+ throw new LobeHubOAuthError(+ typeof body.error === 'string' ? body.error : `http_${response.status}`,+ typeof body.error_description === 'string' ? body.error_description : undefined,+ response.status,+ );+ }+ if (typeof body.access_token !== 'string') throw new LobeHubOAuthError('missing_access_token');++ return {+ accessToken: body.access_token,+ expiresAt: requestedAt + Number(body.expires_in ?? 0) * 1000,+ refreshToken: typeof body.refresh_token === 'string' ? body.refresh_token : undefined,+ scope: typeof body.scope === 'string' ? body.scope : undefined,+ tokenType: typeof body.token_type === 'string' ? body.token_type : 'Bearer',+ };+};++/** Exchange the authorization code for tokens (`authorization_code` grant). */+export const exchangeAuthorizationCode = (+ options: OAuthClientOptions & { code: string; codeVerifier: string; redirectUri: string },+): Promise<OAuthTokens> =>+ requestTokens(options, {+ code: options.code,+ code_verifier: options.codeVerifier,+ grant_type: 'authorization_code',+ redirect_uri: options.redirectUri,+ });++/**+ * Trade a refresh token for a new access token. The refresh token rotates:+ * replace the stored one with `refreshToken` from the result. `invalid_grant`+ * means the grant is gone and the user has to sign in again.+ */+export const refreshAccessToken = (+ options: OAuthClientOptions & { refreshToken: string },+): Promise<OAuthTokens> =>+ requestTokens(options, { grant_type: 'refresh_token', refresh_token: options.refreshToken });diff --git a/packages/sdk/src/constants.ts b/packages/sdk/src/constants.tsnew file mode 100644index 00000000000..6bf80601f35--- /dev/null+++ b/packages/sdk/src/constants.ts@@ -0,0 +1 @@+export const DEFAULT_BASE_URL = 'https://app.lobehub.com';diff --git a/packages/sdk/src/index.test.ts b/packages/sdk/src/index.test.tsindex 3b7b9780530..791f69667f2 100644--- a/packages/sdk/src/index.test.ts+++ b/packages/sdk/src/index.test.ts@@ -27,6 +27,28 @@ describe('createLobeHub', () => {expect(data).toEqual({ status: 'ok' });});+ it('asks the accessToken provider before every request', async () => {+ const { fetch, requests } = captureFetch();+ let issued = 0;+ const lobehub = createLobeHub({+ accessToken: async () => `jwt-${++issued}`,+ apiKey: 'sk-lh-ignored',+ fetch,+ });++ await lobehub.health.check();+ await lobehub.health.check();++ expect(requests.map((request) => request.headers.get('authorization'))).toEqual([+ 'Bearer jwt-1',+ 'Bearer jwt-2',+ ]);+ });++ it('requires an apiKey or an accessToken provider', () => {+ expect(() => createLobeHub({})).toThrow('apiKey or an accessToken');+ });+it('honors a custom baseURL and extra headers', async () => {const { fetch, requests } = captureFetch();const lobehub = createLobeHub({diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.tsindex 9f22a473663..9a8f92569ba 100644--- a/packages/sdk/src/index.ts+++ b/packages/sdk/src/index.ts@@ -1,12 +1,19 @@+import { DEFAULT_BASE_URL } from './constants';import type { Config } from './generated/client';import { createClient, createConfig } from './generated/client';import { LobeHub } from './generated/sdk.gen';-export const DEFAULT_BASE_URL = 'https://app.lobehub.com';+export { DEFAULT_BASE_URL } from './constants';export interface LobeHubOptions extends Omit<Config, 'auth' | 'baseUrl'> {+ /**+ * Called before every request for the OIDC access token to send. Refresh it+ * here (see `refreshAccessToken`) so long-lived clients never send an expired+ * one. Takes precedence over `apiKey`.+ */+ accessToken?: () => Promise<string> | string;/** LobeHub API Key (`sk-lh-...`) or an OIDC JWT */- apiKey: string;+ apiKey?: string;/** API origin, defaults to LobeHub Cloud (`https://app.lobehub.com`) */baseURL?: string;}@@ -19,12 +26,20 @@ export interface LobeHubOptions extends Omit<Config, 'auth' | 'baseUrl'> {* `packages/openapi/openapi.yml` — run `bun generate` after the spec changes.*/export const createLobeHub = (options: LobeHubOptions): LobeHub => {- const { apiKey, baseURL = DEFAULT_BASE_URL, ...clientConfig } = options;- const config: Config = { ...clientConfig, auth: () => apiKey, baseUrl: baseURL };+ const { accessToken, apiKey, baseURL = DEFAULT_BASE_URL, ...clientConfig } = options;+ if (!accessToken && !apiKey)+ throw new Error('createLobeHub needs an apiKey or an accessToken provider');++ const config: Config = {+ ...clientConfig,+ auth: accessToken ? () => accessToken() : () => apiKey,+ baseUrl: baseURL,+ };return new LobeHub({ client: createClient(createConfig(config)) });};+export * from './auth';export type { Client, Config } from './generated/client';export { LobeHub } from './generated/sdk.gen';export type * from './generated/types.gen';