Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/token-source.md
Original file line number Diff line number Diff line change
@@ -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.
48 changes: 48 additions & 0 deletions packages/livekit-server-sdk/src/AccessToken.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
26 changes: 20 additions & 6 deletions packages/livekit-server-sdk/src/AccessToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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) {
Expand All @@ -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' +
Expand Down Expand Up @@ -195,6 +195,9 @@ export class AccessToken {
* @returns JWT encoded token
*/
async toJwt(): Promise<string> {
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);
Expand All @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion packages/livekit-server-sdk/src/AgentDispatchClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 7 additions & 0 deletions packages/livekit-server-sdk/src/ClientOptions.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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;
};
2 changes: 1 addition & 1 deletion packages/livekit-server-sdk/src/ConnectorClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion packages/livekit-server-sdk/src/EgressClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
StreamOutput,
WebhookConfig,
} from '@livekit/protocol';
import {

Check warning on line 14 in packages/livekit-server-sdk/src/EgressClient.ts

View workflow job for this annotation

GitHub Actions / Formatting

Imports "StartEgressRequest" are only used as type
AudioMixing,
EgressInfo,
ListEgressRequest,
Expand Down Expand Up @@ -142,7 +142,7 @@
* @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,
Expand Down
2 changes: 1 addition & 1 deletion packages/livekit-server-sdk/src/IngressClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion packages/livekit-server-sdk/src/RoomServiceClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
79 changes: 79 additions & 0 deletions packages/livekit-server-sdk/src/ServiceBase.test.ts
Original file line number Diff line number Diff line change
@@ -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<TokenProvider>(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<TokenProvider>(async () => 'provider-token');
const fetchMock = vi.fn<typeof fetch>(
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<ClaimGrants>(
jwt,
new TextEncoder().encode(testSecret),
{ issuer: testApiKey },
);

expect(payload.video).toEqual({ roomAdmin: true, room: 'myroom' });
expect(payload.exp! - payload.nbf!).toEqual(600);
});
});
24 changes: 23 additions & 1 deletion packages/livekit-server-sdk/src/ServiceBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>;

/**
* Authentication options for a service client.
Expand All @@ -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;
}

/**
Expand All @@ -28,6 +37,8 @@ export class ServiceBase {

private readonly token?: string;

private readonly tokenProvider?: TokenProvider;

private readonly ttl: string;

/**
Expand All @@ -50,13 +61,24 @@ 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<Record<string, string>> {
// A pre-signed token is sent verbatim; the caller is responsible for its grants.
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);
Expand Down
2 changes: 1 addition & 1 deletion packages/livekit-server-sdk/src/SipClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
16 changes: 14 additions & 2 deletions packages/livekit-server-sdk/src/grants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,17 @@ export function trackSourceToString(source: TrackSource) {
}

export function claimsToJwtPayload(
grant: ClaimGrants,
grant: TokenGrants,
): JWTPayload & { video?: Record<string, unknown> } {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const claim: Record<string, any> = { ...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;
}
Expand Down Expand Up @@ -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;
1 change: 1 addition & 0 deletions packages/livekit-server-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Loading