diff --git a/.changeset/token-source.md b/.changeset/token-source.md new file mode 100644 index 00000000..b25a7237 --- /dev/null +++ b/.changeset/token-source.md @@ -0,0 +1,5 @@ +--- +'livekit-server-sdk': minor +--- + +Add a `tokenProvider` client option, which gets the token for each call from the grants the call needs, in place of signing it with an API key and secret. Add `AccessToken.toClaimsJson()`, which returns the claims as JSON without signing them; an `AccessToken` now needs an API key and secret only to sign. diff --git a/packages/livekit-server-sdk/src/AccessToken.test.ts b/packages/livekit-server-sdk/src/AccessToken.test.ts index d80a8029..1c59dc62 100644 --- a/packages/livekit-server-sdk/src/AccessToken.test.ts +++ b/packages/livekit-server-sdk/src/AccessToken.test.ts @@ -161,3 +161,51 @@ describe('room configuration with agents and egress', () => { expect(decoded.roomConfig?.egress?.room?.roomName).toEqual('test-room'); }); }); + +describe('claims as JSON', () => { + it('matches the grants toJwt signs, without the registered claims', async () => { + const t = new AccessToken(testApiKey, testSecret, { + identity: 'agent-1', + name: 'Agent', + metadata: 'md', + attributes: { foo: 'bar' }, + }); + t.kind = 'agent'; + t.addGrant({ roomJoin: true, room: 'myroom', canPublish: true, canPublishSources: [1, 2] }); + t.addSIPGrant({ call: true }); + + const claims = JSON.parse(t.toClaimsJson()); + const { payload } = await jose.jwtVerify( + await t.toJwt(), + new TextEncoder().encode(testSecret), + { issuer: testApiKey }, + ); + const { iss, sub, exp, nbf, ...signed } = payload; + + expect(sub).toEqual('agent-1'); + expect(iss && exp && nbf).toBeTruthy(); + expect(claims).toEqual({ ...signed, identity: 'agent-1' }); + expect(claims.video).toEqual({ + roomJoin: true, + room: 'myroom', + canPublish: true, + canPublishSources: ['camera', 'microphone'], + }); + }); + + it('works without an API key or secret', () => { + const t = new AccessToken(undefined, undefined, { identity: 'me' }); + t.addGrant({ roomAdmin: true, room: 'myroom' }); + + expect(JSON.parse(t.toClaimsJson())).toEqual({ + identity: 'me', + video: { roomAdmin: true, room: 'myroom' }, + }); + }); + + it('still needs an API key and secret to sign', async () => { + const t = new AccessToken(undefined, undefined, { identity: 'me' }); + + await expect(t.toJwt()).rejects.toThrow('api-key and api-secret must be set'); + }); +}); diff --git a/packages/livekit-server-sdk/src/AccessToken.ts b/packages/livekit-server-sdk/src/AccessToken.ts index 21e0ee23..c4d7fcf3 100644 --- a/packages/livekit-server-sdk/src/AccessToken.ts +++ b/packages/livekit-server-sdk/src/AccessToken.ts @@ -47,9 +47,9 @@ export interface AccessTokenOptions { } export class AccessToken { - private apiKey: string; + private apiKey?: string; - private apiSecret: string; + private apiSecret?: string; private grants: ClaimGrants; @@ -61,6 +61,9 @@ export class AccessToken { * Creates a new AccessToken * @param apiKey - API Key, can be set in env LIVEKIT_API_KEY * @param apiSecret - Secret, can be set in env LIVEKIT_API_SECRET + * + * Both are needed only to sign: {@link toJwt} throws without them, while + * {@link toClaimsJson} works without. */ constructor(apiKey?: string, apiSecret?: string, options?: AccessTokenOptions) { if (!apiKey) { @@ -69,11 +72,8 @@ export class AccessToken { if (!apiSecret) { apiSecret = process.env.LIVEKIT_API_SECRET; } - if (!apiKey || !apiSecret) { - throw Error('api-key and api-secret must be set'); - } // @ts-expect-error we're not including dom lib for the server sdk so document is not defined - else if (typeof document !== 'undefined') { + if (apiKey && apiSecret && typeof document !== 'undefined') { // check against document rather than window because deno provides window console.error( 'You should not include your API secret in your web client bundle.\n\n' + @@ -195,6 +195,9 @@ export class AccessToken { * @returns JWT encoded token */ async toJwt(): Promise { + if (!this.apiKey || !this.apiSecret) { + throw Error('api-key and api-secret must be set'); + } // TODO: check for video grant validity const secret = new TextEncoder().encode(this.apiSecret); @@ -211,6 +214,17 @@ export class AccessToken { } return jwt.sign(secret); } + + /** + * Returns the claims as JSON, without signing them: the payload {@link toJwt} + * would sign, with the identity as `identity` and without the registered + * claims (issuer, subject, expiry, not-before), which the signer sets. This is + * the shape a LiveKit server reads to issue a token, as in an agent worker's + * CreateJobTokenRequest. Needs no API key or secret. + */ + toClaimsJson(): string { + return JSON.stringify({ ...claimsToJwtPayload(this.grants), identity: this.identity }); + } } export class TokenVerifier { diff --git a/packages/livekit-server-sdk/src/AgentDispatchClient.ts b/packages/livekit-server-sdk/src/AgentDispatchClient.ts index b077cc48..1d0ad757 100644 --- a/packages/livekit-server-sdk/src/AgentDispatchClient.ts +++ b/packages/livekit-server-sdk/src/AgentDispatchClient.ts @@ -39,7 +39,7 @@ export class AgentDispatchClient extends ServiceBase { * @param options - client options */ constructor(host: string, apiKey?: string, secret?: string, options?: ClientOptions) { - super({ apiKey, secret, token: options?.token }); + super({ apiKey, secret, token: options?.token, tokenProvider: options?.tokenProvider }); this.rpc = new TwirpRpc(host, livekitPackage, { requestTimeout: options?.requestTimeout, failover: options?.failover, diff --git a/packages/livekit-server-sdk/src/ClientOptions.ts b/packages/livekit-server-sdk/src/ClientOptions.ts index 02cf0b13..6910e1d2 100644 --- a/packages/livekit-server-sdk/src/ClientOptions.ts +++ b/packages/livekit-server-sdk/src/ClientOptions.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2024 LiveKit, Inc. // // SPDX-License-Identifier: Apache-2.0 +import type { TokenProvider } from './ServiceBase.js'; /** * Options common to all clients @@ -22,4 +23,10 @@ export type ClientOptions = { * it needs no secret, the client can run client-side. */ token?: string; + /** + * Gets the token for each request, in place of signing one from an API key + * and secret. It is called with the grants the request needs, as a client + * with a key and secret would sign them. + */ + tokenProvider?: TokenProvider; }; diff --git a/packages/livekit-server-sdk/src/ConnectorClient.ts b/packages/livekit-server-sdk/src/ConnectorClient.ts index dbd0fe3c..5dfd3c07 100644 --- a/packages/livekit-server-sdk/src/ConnectorClient.ts +++ b/packages/livekit-server-sdk/src/ConnectorClient.ts @@ -126,7 +126,7 @@ export class ConnectorClient extends ServiceBase { * @param options - client options */ constructor(host: string, apiKey?: string, secret?: string, options?: ClientOptions) { - super({ apiKey, secret, token: options?.token }); + super({ apiKey, secret, token: options?.token, tokenProvider: options?.tokenProvider }); this.rpc = new TwirpRpc(host, livekitPackage, { requestTimeout: options?.requestTimeout, failover: options?.failover, diff --git a/packages/livekit-server-sdk/src/EgressClient.ts b/packages/livekit-server-sdk/src/EgressClient.ts index 022f2895..6f01e038 100644 --- a/packages/livekit-server-sdk/src/EgressClient.ts +++ b/packages/livekit-server-sdk/src/EgressClient.ts @@ -142,7 +142,7 @@ export class EgressClient extends ServiceBase { * @param options - client options */ constructor(host: string, apiKey?: string, secret?: string, options?: ClientOptions) { - super({ apiKey, secret, token: options?.token }); + super({ apiKey, secret, token: options?.token, tokenProvider: options?.tokenProvider }); this.rpc = new TwirpRpc(host, livekitPackage, { requestTimeout: options?.requestTimeout, failover: options?.failover, diff --git a/packages/livekit-server-sdk/src/IngressClient.ts b/packages/livekit-server-sdk/src/IngressClient.ts index 2672db7c..d1d84ae1 100644 --- a/packages/livekit-server-sdk/src/IngressClient.ts +++ b/packages/livekit-server-sdk/src/IngressClient.ts @@ -138,7 +138,7 @@ export class IngressClient extends ServiceBase { * @param options - client options */ constructor(host: string, apiKey?: string, secret?: string, options?: ClientOptions) { - super({ apiKey, secret, token: options?.token }); + super({ apiKey, secret, token: options?.token, tokenProvider: options?.tokenProvider }); this.rpc = new TwirpRpc(host, livekitPackage, { requestTimeout: options?.requestTimeout, failover: options?.failover, diff --git a/packages/livekit-server-sdk/src/RoomServiceClient.ts b/packages/livekit-server-sdk/src/RoomServiceClient.ts index 09da51b6..df27033a 100644 --- a/packages/livekit-server-sdk/src/RoomServiceClient.ts +++ b/packages/livekit-server-sdk/src/RoomServiceClient.ts @@ -131,7 +131,7 @@ export class RoomServiceClient extends ServiceBase { * @param options - client options */ constructor(host: string, apiKey?: string, secret?: string, options?: ClientOptions) { - super({ apiKey, secret, token: options?.token }); + super({ apiKey, secret, token: options?.token, tokenProvider: options?.tokenProvider }); this.rpc = new TwirpRpc(host, livekitPackage, { requestTimeout: options?.requestTimeout, failover: options?.failover, diff --git a/packages/livekit-server-sdk/src/ServiceBase.test.ts b/packages/livekit-server-sdk/src/ServiceBase.test.ts new file mode 100644 index 00000000..2a1d9019 --- /dev/null +++ b/packages/livekit-server-sdk/src/ServiceBase.test.ts @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: 2026 LiveKit, Inc. +// +// SPDX-License-Identifier: Apache-2.0 +import * as jose from 'jose'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { RoomServiceClient } from './RoomServiceClient.js'; +import { ServiceBase, type TokenProvider } from './ServiceBase.js'; +import { SipClient } from './SipClient.js'; +import type { ClaimGrants } from './grants.js'; + +const testApiKey = 'abcdefg'; +const testSecret = 'abababa'; + +describe('token provider', () => { + it('is called with the grants a call needs, and its token is sent', async () => { + const tokenProvider = vi.fn(async () => 'provider-token'); + const base = new ServiceBase({ tokenProvider }); + + const header = await base.authHeader({ roomAdmin: true, room: 'myroom' }, { call: true }); + + expect(header).toEqual({ Authorization: 'Bearer provider-token' }); + expect(tokenProvider).toHaveBeenCalledWith({ + video: { roomAdmin: true, room: 'myroom' }, + sip: { call: true }, + }); + }); + + it('is used by the service clients', async () => { + const tokenProvider = vi.fn(async () => 'provider-token'); + const fetchMock = vi.fn( + async () => + new Response(JSON.stringify({ participants: [] }), { + headers: { 'Content-Type': 'application/json' }, + }), + ); + vi.stubGlobal('fetch', fetchMock); + + const rooms = new RoomServiceClient('http://localhost:7880', undefined, undefined, { + tokenProvider, + }); + await rooms.listParticipants('myroom'); + + expect(tokenProvider).toHaveBeenCalledWith({ video: { roomAdmin: true, room: 'myroom' } }); + const headers = new Headers(fetchMock.mock.calls[0]![1]!.headers); + expect(headers.get('Authorization')).toEqual('Bearer provider-token'); + + // SIP calls ask for the SIP grant + const sip = new SipClient('http://localhost:7880', undefined, undefined, { tokenProvider }); + fetchMock.mockImplementationOnce( + async () => + new Response(JSON.stringify({ items: [] }), { + headers: { 'Content-Type': 'application/json' }, + }), + ); + await sip.listSipInboundTrunk(); + expect(tokenProvider).toHaveBeenLastCalledWith({ video: {}, sip: { admin: true } }); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); +}); + +describe('API key and secret', () => { + it('signs each call with the grants it needs', async () => { + const base = new ServiceBase({ apiKey: testApiKey, secret: testSecret }); + + const header = await base.authHeader({ roomAdmin: true, room: 'myroom' }); + const jwt = header.Authorization!.replace('Bearer ', ''); + const { payload } = await jose.jwtVerify( + jwt, + new TextEncoder().encode(testSecret), + { issuer: testApiKey }, + ); + + expect(payload.video).toEqual({ roomAdmin: true, room: 'myroom' }); + expect(payload.exp! - payload.nbf!).toEqual(600); + }); +}); diff --git a/packages/livekit-server-sdk/src/ServiceBase.ts b/packages/livekit-server-sdk/src/ServiceBase.ts index fb5286a5..1ddf255f 100644 --- a/packages/livekit-server-sdk/src/ServiceBase.ts +++ b/packages/livekit-server-sdk/src/ServiceBase.ts @@ -2,7 +2,14 @@ // // SPDX-License-Identifier: Apache-2.0 import { AccessToken } from './AccessToken.js'; -import type { SIPGrant, VideoGrant } from './grants.js'; +import type { ClaimGrants, SIPGrant, TokenGrants, VideoGrant } from './grants.js'; + +/** + * Returns a token that carries the given grants, for a client to send in place + * of one it signs itself. The client calls it before each request with the + * grants that request needs, so the provider can cache and refresh tokens. + */ +export type TokenProvider = (grants: TokenGrants) => Promise; /** * Authentication options for a service client. @@ -16,6 +23,8 @@ export interface ServiceBaseOptions { ttl?: string; /** Pre-signed token; sent verbatim, skipping per-call signing. */ token?: string; + /** Gets the token for each call, in place of signing it with the API key and secret. */ + tokenProvider?: TokenProvider; } /** @@ -28,6 +37,8 @@ export class ServiceBase { private readonly token?: string; + private readonly tokenProvider?: TokenProvider; + private readonly ttl: string; /** @@ -50,6 +61,7 @@ export class ServiceBase { this.secret = options.secret; this.ttl = options.ttl || '10m'; this.token = options.token; + this.tokenProvider = options.tokenProvider; } async authHeader(grant: VideoGrant, sip?: SIPGrant): Promise> { @@ -57,6 +69,16 @@ export class ServiceBase { if (this.token) { return { Authorization: `Bearer ${this.token}` }; } + if (this.tokenProvider) { + const grants: ClaimGrants = {}; + if (grant) { + grants.video = { ...grant }; + } + if (sip) { + grants.sip = { ...sip }; + } + return { Authorization: `Bearer ${await this.tokenProvider(grants)}` }; + } const at = new AccessToken(this.apiKey, this.secret, { ttl: this.ttl }); if (grant) { at.addGrant(grant); diff --git a/packages/livekit-server-sdk/src/SipClient.ts b/packages/livekit-server-sdk/src/SipClient.ts index 88b26ac3..d5833be4 100644 --- a/packages/livekit-server-sdk/src/SipClient.ts +++ b/packages/livekit-server-sdk/src/SipClient.ts @@ -260,7 +260,7 @@ export class SipClient extends ServiceBase { * @param options - client options */ constructor(host: string, apiKey?: string, secret?: string, options?: ClientOptions) { - super({ apiKey, secret, token: options?.token }); + super({ apiKey, secret, token: options?.token, tokenProvider: options?.tokenProvider }); this.rpc = new TwirpRpc(host, livekitPackage, { requestTimeout: options?.requestTimeout, failover: options?.failover, diff --git a/packages/livekit-server-sdk/src/grants.ts b/packages/livekit-server-sdk/src/grants.ts index 45e80063..888f87c0 100644 --- a/packages/livekit-server-sdk/src/grants.ts +++ b/packages/livekit-server-sdk/src/grants.ts @@ -21,13 +21,17 @@ export function trackSourceToString(source: TrackSource) { } export function claimsToJwtPayload( - grant: ClaimGrants, + grant: TokenGrants, ): JWTPayload & { video?: Record } { // eslint-disable-next-line @typescript-eslint/no-explicit-any const claim: Record = { ...grant }; // eslint-disable-next-line no-restricted-syntax if (Array.isArray(claim.video?.canPublishSources)) { - claim.video.canPublishSources = claim.video.canPublishSources.map(trackSourceToString); + // a copy: the grants keep their sources, so the claims can be read more than once + claim.video = { + ...claim.video, + canPublishSources: claim.video.canPublishSources.map(trackSourceToString), + }; } return claim; } @@ -130,3 +134,11 @@ export interface ClaimGrants extends JWTPayload { roomPreset?: string; roomConfig?: RoomConfiguration; } + +/** + * The grants that a `TokenProvider` is asked for. Today these are v1 claims + * (`ClaimGrants`). Grants v2 will be accepted here too. The provider does not + * convert between the two: it passes the grants on with {@link claimsToJwtPayload}, + * and the server that signs the token converts them to the format of its key. + */ +export type TokenGrants = ClaimGrants; diff --git a/packages/livekit-server-sdk/src/index.ts b/packages/livekit-server-sdk/src/index.ts index 769b4693..b7c44eba 100644 --- a/packages/livekit-server-sdk/src/index.ts +++ b/packages/livekit-server-sdk/src/index.ts @@ -91,4 +91,5 @@ export * from './RoomServiceClient.js'; export * from './SipClient.js'; export { ServerError, SipCallError, TwirpError } from './TwirpRPC.js'; export type { ClientOptions } from './ClientOptions.js'; +export type { TokenProvider } from './ServiceBase.js'; export * from './WebhookReceiver.js';