import { RoomConfiguration, type TokenSourceResponse } from '@livekit/protocol'; import { decodeJwt } from 'jose'; import type { RoomConfigurationObject, TokenPayload, TokenSourceFetchOptions } from './types'; const ONE_SECOND_IN_MILLISECONDS = 1000; const ONE_MINUTE_IN_MILLISECONDS = 60 * ONE_SECOND_IN_MILLISECONDS; export function isResponseTokenValid(response: TokenSourceResponse) { const jwtPayload = decodeTokenPayload(response.participantToken); // Missing exp: TokenSourceCached would otherwise return this response forever. // nbf is optional (RFC 7519); do not skip the exp check when it is absent. if (!jwtPayload?.exp) { return false; } const now = new Date(); if (jwtPayload.nbf) { const nbfInMilliseconds = jwtPayload.nbf * ONE_SECOND_IN_MILLISECONDS; const nbfDate = new Date(nbfInMilliseconds); if (nbfDate > now) { return false; } } const expInMilliseconds = jwtPayload.exp * ONE_SECOND_IN_MILLISECONDS; const expDate = new Date(expInMilliseconds - ONE_MINUTE_IN_MILLISECONDS); return expDate > now; } /** Given a LiveKit generated participant token, decodes and returns the associated {@link TokenPayload} data. */ export function decodeTokenPayload(token: string) { const payload = decodeJwt>(token); const { roomConfig, ...rest } = payload; const mappedPayload: TokenPayload = { ...rest, roomConfig: payload.roomConfig ? (RoomConfiguration.fromJson(payload.roomConfig as Record, { ignoreUnknownFields: true, }) as RoomConfigurationObject) : undefined, }; return mappedPayload; } /** Given two TokenSourceFetchOptions values, check to see if they are deep equal. */ export function areTokenSourceFetchOptionsEqual( a: TokenSourceFetchOptions, b: TokenSourceFetchOptions, ) { const allKeysSet = new Set([...Object.keys(a), ...Object.keys(b)]) as Set< keyof TokenSourceFetchOptions >; for (const key of allKeysSet) { switch (key) { case 'roomName': case 'participantName': case 'participantIdentity': case 'participantMetadata': case 'agentName': case 'agentMetadata': case 'deployment': if (a[key] !== b[key]) { return false; } break; case 'participantAttributes': if (!areAttributesEqual(a[key], b[key])) { return false; } break; default: // ref: https://stackoverflow.com/a/58009992 const exhaustiveCheckedKey: never = key; throw new Error(`Options key ${exhaustiveCheckedKey} not being checked for equality!`); } } return true; } function areAttributesEqual( a: TokenSourceFetchOptions['participantAttributes'], b: TokenSourceFetchOptions['participantAttributes'], ) { if (a === b) { return true; } if (!a || !b) { return false; } const aKeys = Object.keys(a); const bKeys = new Set(Object.keys(b)); if (aKeys.length !== bKeys.size) { return false; } return aKeys.every((key) => bKeys.has(key) && a[key] === b[key]); }